diff --git a/Build.bat b/Build.bat new file mode 100644 index 000000000..a3a691041 --- /dev/null +++ b/Build.bat @@ -0,0 +1,23 @@ +@echo off + +set fdir=%WINDIR%\Microsoft.NET\Framework64 + +if not exist %fdir% ( + set fdir=%WINDIR%\Microsoft.NET\Framework +) + +set msbuild=%fdir%\v4.0.30319\msbuild.exe + +%msbuild% SuperSocket.2010.sln /p:Configuration=Debug /t:Rebuild /p:OutputPath=..\bin\Net40\Debug +FOR /F "tokens=*" %%G IN ('DIR /B /AD /S obj') DO RMDIR /S /Q "%%G" + +%msbuild% SuperSocket.2010.sln /p:Configuration=Release /t:Rebuild /p:OutputPath=..\bin\Net40\Release +FOR /F "tokens=*" %%G IN ('DIR /B /AD /S obj') DO RMDIR /S /Q "%%G" + +%msbuild% SuperSocket.2010.NET35.sln /p:Configuration=Debug /t:Rebuild /p:OutputPath=..\bin\Net35\Debug +FOR /F "tokens=*" %%G IN ('DIR /B /AD /S obj') DO RMDIR /S /Q "%%G" + +%msbuild% SuperSocket.2010.NET35.sln /p:Configuration=Release /t:Rebuild /p:OutputPath=..\bin\Net35\Release +FOR /F "tokens=*" %%G IN ('DIR /B /AD /S obj') DO RMDIR /S /Q "%%G" + +pause \ No newline at end of file diff --git a/BuildQuickStart.bat b/BuildQuickStart.bat new file mode 100644 index 000000000..59174ec3e --- /dev/null +++ b/BuildQuickStart.bat @@ -0,0 +1,12 @@ +@echo off + +set fdir=%WINDIR%\Microsoft.NET\Framework64 + +if not exist %fdir% ( + set fdir=%WINDIR%\Microsoft.NET\Framework +) + +set msbuild=%fdir%\v4.0.30319\msbuild.exe + +%msbuild% QuickStart\QuickStart.sln /p:Configuration=Debug /t:Rebuild +pause \ No newline at end of file diff --git a/Common/ArraySegmentEx.cs b/Common/ArraySegmentEx.cs new file mode 100644 index 000000000..58efaae79 --- /dev/null +++ b/Common/ArraySegmentEx.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.Common +{ + class ArraySegmentEx + { + public ArraySegmentEx(T[] array, int offset, int count) + { + Array = array; + Offset = offset; + Count = count; + } + /// + /// Gets the array. + /// + public T[] Array { get; private set; } + + /// + /// Gets the count. + /// + public int Count { get; private set; } + + /// + /// Gets the offset. + /// + public int Offset { get; private set; } + + public int From { get; set; } + + public int To { get; set; } + } +} diff --git a/Common/ArraySegmentList.cs b/Common/ArraySegmentList.cs new file mode 100644 index 000000000..d274867ef --- /dev/null +++ b/Common/ArraySegmentList.cs @@ -0,0 +1,752 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.Common +{ + /// + /// ArraySegmentList + /// + /// + public class ArraySegmentList : IList + where T : IEquatable + { + private IList> m_Segments; + + internal IList> Segments + { + get { return m_Segments; } + } + + private ArraySegmentEx m_PrevSegment; + private int m_PrevSegmentIndex; + + private int m_Count; + + /// + /// Initializes a new instance of the class. + /// + public ArraySegmentList() + { + m_Segments = new List>(); + } + + private void CalculateSegmentsInfo(IList> segments) + { + int total = 0; + + foreach (var segment in segments) + { + if (segment.Count <= 0) + continue; + + segment.From = total; + segment.To = total + segment.Count - 1; + + m_Segments.Add(segment); + + total += segment.Count; + } + + m_Count = total; + } + + #region IList Members + + /// + /// Determines the index of a specific item in the . + /// + /// The object to locate in the . + /// + /// The index of if found in the list; otherwise, -1. + /// + public int IndexOf(T item) + { + int index = 0; + + for (int i = 0; i < m_Segments.Count; i++) + { + var currentSegment = m_Segments[i]; + int offset = currentSegment.Offset; + + for (int j = 0; j < currentSegment.Count; j++) + { + if (currentSegment.Array[j + offset].Equals(item)) + return index; + + index++; + } + } + + return -1; + } + + /// + /// NotSupported + /// + public void Insert(int index, T item) + { + throw new NotSupportedException(); + } + + /// + /// NotSupported + /// + public void RemoveAt(int index) + { + throw new NotSupportedException(); + } + + /// + /// Gets or sets the element at the specified index. + /// + /// + /// The element at the specified index. + /// + /// + /// is not a valid index in the . + /// + /// + /// + /// The property is set and the is read-only. + /// + public T this[int index] + { + get + { + ArraySegmentEx segment; + + var internalIndex = GetElementInternalIndex(index, out segment); + + if (internalIndex < 0) + throw new IndexOutOfRangeException(); + + return segment.Array[internalIndex]; + } + set + { + ArraySegmentEx segment; + + var internalIndex = GetElementInternalIndex(index, out segment); + + if (internalIndex < 0) + throw new IndexOutOfRangeException(); + + segment.Array[internalIndex] = value; + } + } + + private int GetElementInternalIndex(int index, out ArraySegmentEx segment) + { + segment = null; + + if (index < 0 || index > Count - 1) + return -1; + + if (index == 0) + { + m_PrevSegment = m_Segments[0]; + m_PrevSegmentIndex = 0; + segment = m_PrevSegment; + return m_PrevSegment.Offset; + } + + int compareValue = 0; + + if (m_PrevSegment != null) + { + if (index >= m_PrevSegment.From) + { + if (index <= m_PrevSegment.To) + { + segment = m_PrevSegment; + return m_PrevSegment.Offset + index - m_PrevSegment.From; + } + else + { + compareValue = 1; + } + } + else + { + compareValue = -1; + } + } + + int from, to; + + if (compareValue != 0) + { + from = m_PrevSegmentIndex + compareValue; + + var trySegment = m_Segments[from]; + + if (index >= trySegment.From && index <= trySegment.To) + { + segment = trySegment; + return trySegment.Offset + index - trySegment.From; + } + + from += compareValue; + + var currentSegment = m_Segments[from]; + if (index >= currentSegment.From && index <= currentSegment.To) + { + m_PrevSegment = currentSegment; + m_PrevSegmentIndex = from; + segment = currentSegment; + return currentSegment.Offset + index - currentSegment.From; + } + + if (compareValue > 0) + { + from++; + to = m_Segments.Count - 1; + } + else + { + var tmp = from - 1; + from = 0; + to = tmp; + } + } + else + { + from = 0; + to = m_Segments.Count - 1; + } + + int segmentIndex = -1; + + var result = QuickSearchSegment(from, to, index, out segmentIndex); + + if (result != null) + { + m_PrevSegment = result; + m_PrevSegmentIndex = segmentIndex; + segment = m_PrevSegment; + return result.Offset + index - result.From; + } + + m_PrevSegment = null; + + return -1; + } + + internal ArraySegmentEx QuickSearchSegment(int from, int to, int index, out int segmentIndex) + { + ArraySegmentEx segment; + segmentIndex = -1; + + int diff = to - from; + + if (diff == 0) + { + segment = m_Segments[from]; + + if (index >= segment.From && index <= segment.To) + { + segmentIndex = from; + return segment; + } + + return null; + } + else if (diff == 1) + { + segment = m_Segments[from]; + + if (index >= segment.From && index <= segment.To) + { + segmentIndex = from; + return segment; + } + + segment = m_Segments[to]; + + if (index >= segment.From && index <= segment.To) + { + segmentIndex = to; + return segment; + } + + return null; + } + + int middle = from + diff / 2; + + segment = m_Segments[middle]; + + if (index >= segment.From) + { + if (index <= segment.To) + { + segmentIndex = middle; + return segment; + } + else + { + return QuickSearchSegment(middle + 1, to, index, out segmentIndex); + } + } + else + { + return QuickSearchSegment(from, middle - 1, index, out segmentIndex); + } + } + + #endregion + + #region ICollection Members + + /// + /// NotSupported + /// + public void Add(T item) + { + throw new NotSupportedException(); + } + + /// + /// NotSupported + /// + public void Clear() + { + throw new NotSupportedException(); + } + + /// + /// NotSupported + /// + public bool Contains(T item) + { + throw new NotSupportedException(); + } + + /// + /// Copies to. + /// + /// The array. + /// Index of the array. + public void CopyTo(T[] array, int arrayIndex) + { + CopyTo(array, 0, arrayIndex, Math.Min(array.Length, this.Count - arrayIndex)); + } + + /// + /// Gets the number of elements contained in the . + /// + /// + /// The number of elements contained in the . + /// + public int Count + { + get { return m_Count; } + } + + /// + /// Gets a value indicating whether the is read-only. + /// + /// true if the is read-only; otherwise, false. + /// + public bool IsReadOnly + { + get { return true; } + } + + /// + /// NotSupported + /// + public bool Remove(T item) + { + throw new NotSupportedException(); + } + + #endregion + + #region IEnumerable Members + + /// + /// NotSupported + /// + public IEnumerator GetEnumerator() + { + throw new NotSupportedException(); + } + + #endregion + + #region IEnumerable Members + + /// + /// NotSupported + /// + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() + { + throw new NotSupportedException(); + } + + #endregion + + /// + /// Removes the segment at. + /// + /// The index. + public void RemoveSegmentAt(int index) + { + var removedSegment = m_Segments[index]; + int removedLen = removedSegment.To - removedSegment.From + 1; + + m_Segments.RemoveAt(index); + + m_PrevSegment = null; + + //the removed item is not the the last item + if (index != m_Segments.Count) + { + for (int i = index; i < m_Segments.Count; i++) + { + m_Segments[i].From -= removedLen; + m_Segments[i].To -= removedLen; + } + } + + m_Count -= removedLen; + } + + /// + /// Adds the segment to the list. + /// + /// The array. + /// The offset. + /// The length. + public void AddSegment(T[] array, int offset, int length) + { + AddSegment(array, offset, length, false); + } + + /// + /// Adds the segment to the list. + /// + /// The array. + /// The offset. + /// The length. + /// if set to true [to be copied]. + public void AddSegment(T[] array, int offset, int length, bool toBeCopied) + { + if (length <= 0) + return; + + var currentTotal = m_Count; + + ArraySegmentEx segment = null; + + if (!toBeCopied) + segment = new ArraySegmentEx(array, offset, length); + else + segment = new ArraySegmentEx(array.CloneRange(offset, length), 0, length); + + segment.From = currentTotal; + m_Count = currentTotal + segment.Count; + segment.To = m_Count - 1; + + m_Segments.Add(segment); + } + + /// + /// Gets the segment count. + /// + public int SegmentCount + { + get { return m_Segments.Count; } + } + + /// + /// Clears all the segements. + /// + public void ClearSegements() + { + m_Segments.Clear(); + m_PrevSegment = null; + m_Count = 0; + } + + /// + /// Read all data in this list to the array data. + /// + /// + public T[] ToArrayData() + { + return ToArrayData(0, m_Count); + } + + /// + /// Read the data in specific range to the array data. + /// + /// The start index. + /// The length. + /// + public T[] ToArrayData(int startIndex, int length) + { + var result = new T[length]; + int from = 0, len = 0, total = 0; + + var startSegmentIndex = 0; + + if (startIndex != 0) + { + var startSegment = QuickSearchSegment(0, m_Segments.Count - 1, startIndex, out startSegmentIndex); + from = startIndex - startSegment.From; + if (startSegment == null) + throw new IndexOutOfRangeException(); + } + + for (var i = startSegmentIndex; i < m_Segments.Count; i++) + { + var currentSegment = m_Segments[i]; + len = Math.Min(currentSegment.Count - from, length - total); + Array.Copy(currentSegment.Array, currentSegment.Offset + from, result, total, len); + total += len; + + if (total >= length) + break; + + from = 0; + } + + return result; + } + + /// + /// Trims the end. + /// + /// Size of the trim. + public void TrimEnd(int trimSize) + { + if (trimSize <= 0) + return; + + int expectedTo = this.Count - trimSize - 1; + + for (int i = m_Segments.Count - 1; i >= 0; i--) + { + var s = m_Segments[i]; + + if (s.From <= expectedTo && expectedTo < s.To) + { + s.To = expectedTo; + m_Count -= trimSize; + return; + } + + RemoveSegmentAt(i); + } + } + + /// + /// Searches the last segment. + /// + /// The state. + /// + public int SearchLastSegment(SearchMarkState state) + { + if (m_Segments.Count <= 0) + return -1; + + var lastSegment = m_Segments[m_Segments.Count - 1]; + + if (lastSegment == null) + return -1; + + var result = lastSegment.Array.SearchMark(lastSegment.Offset, lastSegment.Count, state.Mark); + + if (!result.HasValue) + return -1; + + if (result.Value > 0) + { + state.Matched = 0; + return result.Value - lastSegment.Offset + lastSegment.From; + } + + state.Matched = 0 - result.Value; + return -1; + } + + /// + /// Copies to. + /// + /// To. + /// + public int CopyTo(T[] to) + { + return CopyTo(to, 0, 0, Math.Min(m_Count, to.Length)); + } + + /// + /// Copies to. + /// + /// To. + /// Index of the SRC. + /// To index. + /// The length. + /// + public int CopyTo(T[] to, int srcIndex, int toIndex, int length) + { + int copied = 0; + int thisCopied = 0; + + int offsetSegmentIndex; + ArraySegmentEx offsetSegment; + + if (srcIndex > 0) + offsetSegment = QuickSearchSegment(0, m_Segments.Count - 1, srcIndex, out offsetSegmentIndex); + else + { + offsetSegment = m_Segments[0]; + offsetSegmentIndex = 0; + } + + int thisOffset = srcIndex - offsetSegment.From + offsetSegment.Offset; + thisCopied = Math.Min(offsetSegment.Count - thisOffset + offsetSegment.Offset, length - copied); + + Array.Copy(offsetSegment.Array, thisOffset, to, copied + toIndex, thisCopied); + + copied += thisCopied; + + if (copied >= length) + return copied; + + for (var i = offsetSegmentIndex + 1; i < this.m_Segments.Count; i++) + { + var segment = m_Segments[i]; + thisCopied = Math.Min(segment.Count, length - copied); + Array.Copy(segment.Array, segment.Offset, to, copied + toIndex, thisCopied); + copied += thisCopied; + + if (copied >= length) + break; + } + + return copied; + } + } + + /// + /// ArraySegmentList + /// + public class ArraySegmentList : ArraySegmentList + { + /// + /// Decodes bytes to string by the specified encoding. + /// + /// The encoding. + /// + public string Decode(Encoding encoding) + { + return Decode(encoding, 0, Count); + } + + /// + /// Decodes bytes to string by the specified encoding. + /// + /// The encoding. + /// The offset. + /// The length. + /// + public string Decode(Encoding encoding, int offset, int length) + { + var arraySegments = Segments; + + if (arraySegments == null || arraySegments.Count <= 0) + return string.Empty; + + var charsBuffer = new char[encoding.GetMaxCharCount(this.Count)]; + + int bytesUsed, charsUsed; + bool completed; + int totalBytes = 0; + int totalChars = 0; + + int lastSegIndex = arraySegments.Count - 1; + var flush = false; + + var decoder = encoding.GetDecoder(); + + int startSegmentIndex = 0; + + if (offset > 0) + { + QuickSearchSegment(0, arraySegments.Count - 1, offset, out startSegmentIndex); + } + + for (var i = startSegmentIndex; i < arraySegments.Count; i++) + { + var segment = arraySegments[i]; + + if (i == lastSegIndex) + flush = true; + + int decodeOffset = segment.Offset; + int toBeDecoded = Math.Min(length - totalBytes, segment.Count); + + if (i == startSegmentIndex && offset > 0) + { + decodeOffset = offset - segment.From + segment.Offset; + toBeDecoded = Math.Min(segment.Count - offset + segment.From, toBeDecoded); + } + + decoder.Convert(segment.Array, decodeOffset, toBeDecoded, charsBuffer, totalChars, charsBuffer.Length - totalChars, flush, out bytesUsed, out charsUsed, out completed); + totalChars += charsUsed; + totalBytes += bytesUsed; + + if (totalBytes >= length) + break; + } + + return new string(charsBuffer, 0, totalChars); + } + + /// + /// Decodes data by the mask. + /// + /// The mask. + /// The offset. + /// The length. + public void DecodeMask(byte[] mask, int offset, int length) + { + int maskLen = mask.Length; + var startSegmentIndex = 0; + var startSegment = QuickSearchSegment(0, Segments.Count - 1, offset, out startSegmentIndex); + + var shouldDecode = Math.Min(length, startSegment.Count - offset + startSegment.From); + var from = offset - startSegment.From + startSegment.Offset; + + var index = 0; + + for (var i = from; i < from + shouldDecode; i++) + { + startSegment.Array[i] = (byte)(startSegment.Array[i] ^ mask[index++ % maskLen]); + } + + if (index >= length) + return; + + for (var i = startSegmentIndex + 1; i < SegmentCount; i++) + { + var segment = Segments[i]; + + shouldDecode = Math.Min(length - index, segment.Count); + + for (var j = segment.Offset; j < segment.Offset + shouldDecode; j++) + { + segment.Array[j] = (byte)(segment.Array[j] ^ mask[index++ % maskLen]); + } + + if (index >= length) + return; + } + } + } +} diff --git a/Common/AssemblyUtil.cs b/Common/AssemblyUtil.cs new file mode 100644 index 000000000..d850f8bbd --- /dev/null +++ b/Common/AssemblyUtil.cs @@ -0,0 +1,179 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Reflection; +using System.IO; +using System.Linq; + +#if SILVERLIGHT +#else +using System.Runtime.Serialization.Formatters.Binary; +#endif + +namespace SuperSocket.Common +{ + /// + /// Assembly Util Class + /// + public static class AssemblyUtil + { + /// + /// Creates the instance from type name. + /// + /// + /// The type. + /// + public static T CreateInstance(string type) + { + return CreateInstance(type, new object[0]); + } + + /// + /// Creates the instance from type name and parameters. + /// + /// + /// The type. + /// The parameters. + /// + public static T CreateInstance(string type, object[] parameters) + { + Type instanceType = null; + var result = default(T); + + instanceType = Type.GetType(type, true); + + if (instanceType == null) + throw new Exception(string.Format("The type '{0}' was not found!", type)); + + object instance = Activator.CreateInstance(instanceType, parameters); + result = (T)instance; + return result; + } + + /// + /// Gets the implement types from assembly. + /// + /// The type of the base type. + /// The assembly. + /// + public static IEnumerable GetImplementTypes(this Assembly assembly) + { + return assembly.GetExportedTypes().Where(t => + t.IsSubclassOf(typeof(TBaseType)) && t.IsClass && !t.IsAbstract); + } + + /// + /// Gets the implemented objects by interface. + /// + /// The type of the base interface. + /// The assembly. + /// + public static IEnumerable GetImplementedObjectsByInterface(this Assembly assembly) + where TBaseInterface : class + { + return GetImplementedObjectsByInterface(assembly, typeof(TBaseInterface)); + } + + /// + /// Gets the implemented objects by interface. + /// + /// The type of the base interface. + /// The assembly. + /// Type of the target. + /// + public static IEnumerable GetImplementedObjectsByInterface(this Assembly assembly, Type targetType) + where TBaseInterface : class + { + Type[] arrType = assembly.GetExportedTypes(); + + var result = new List(); + + for (int i = 0; i < arrType.Length; i++) + { + var currentImplementType = arrType[i]; + + if (currentImplementType.IsAbstract) + continue; + + if (!targetType.IsAssignableFrom(currentImplementType)) + continue; + + result.Add((TBaseInterface)Activator.CreateInstance(currentImplementType)); + } + + return result; + } + +#if SILVERLIGHT +#else + /// + /// Clone object in binary format. + /// + /// + /// The target. + /// + public static T BinaryClone(this T target) + { + BinaryFormatter formatter = new BinaryFormatter(); + using (MemoryStream ms = new MemoryStream()) + { + formatter.Serialize(ms, target); + ms.Position = 0; + return (T)formatter.Deserialize(ms); + } + } +#endif + + private static object[] m_EmptyObjectArray = new object[] { }; + + /// + /// Copies the properties of one object to another object. + /// + /// The source. + /// The target. + public static T CopyPropertiesTo(this T source, T target) + { + PropertyInfo[] properties = source.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty); + Dictionary sourcePropertiesDict = properties.ToDictionary(p => p.Name); + + PropertyInfo[] targetProperties = target.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty); + for (int i = 0; i < targetProperties.Length; i++) + { + var p = targetProperties[i]; + PropertyInfo sourceProperty; + + if (sourcePropertiesDict.TryGetValue(p.Name, out sourceProperty)) + { + if (sourceProperty.PropertyType != p.PropertyType) + continue; + + if (!sourceProperty.PropertyType.IsSerializable) + continue; + + p.SetValue(target, sourceProperty.GetValue(source, m_EmptyObjectArray), m_EmptyObjectArray); + } + } + + return target; + } + + /// + /// Gets the assemblies from string. + /// + /// The assembly def. + /// + public static IEnumerable GetAssembliesFromString(string assemblyDef) + { + string[] assemblies = assemblyDef.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries); + + List result = new List(assemblies.Length); + + foreach (var a in assemblies) + { + result.Add(Assembly.Load(a)); + } + + return result; + } + } +} diff --git a/Common/BinaryUtil.cs b/Common/BinaryUtil.cs new file mode 100644 index 000000000..c270933ee --- /dev/null +++ b/Common/BinaryUtil.cs @@ -0,0 +1,264 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Collections; + +namespace SuperSocket.Common +{ + /// + /// Binary util class + /// + public static class BinaryUtil + { + /// + /// Search target from source. + /// + /// + /// The source. + /// The target. + /// The pos. + /// The length. + /// + public static int IndexOf(this IList source, T target, int pos, int length) + where T : IEquatable + { + for (int i = pos; i < pos + length; i++) + { + if (source[i].Equals(target)) + return i; + } + + return -1; + } + + /// + /// Searches the mark from source. + /// + /// + /// The source. + /// The mark. + /// + public static int? SearchMark(this IList source, T[] mark) + where T : IEquatable + { + return SearchMark(source, 0, source.Count, mark, 0); + } + + /// + /// Searches the mark from source. + /// + /// + /// The source. + /// The offset. + /// The length. + /// The mark. + /// + public static int? SearchMark(this IList source, int offset, int length, T[] mark) + where T : IEquatable + { + return SearchMark(source, offset, length, mark, 0); + } + + /// + /// Searches the mark from source. + /// + /// + /// The source. + /// The offset. + /// The length. + /// The mark. + /// The matched. + /// + public static int? SearchMark(this IList source, int offset, int length, T[] mark, int matched) + where T : IEquatable + { + int pos = offset; + int endOffset = offset + length - 1; + int matchCount = matched; + + if (matched > 0) + { + for (int i = matchCount; i < mark.Length; i++) + { + if (!source[pos++].Equals(mark[i])) + break; + + matchCount++; + + if (pos > endOffset) + { + if (matchCount == mark.Length) + return offset; + else + return (0 - matchCount); + } + } + + if (matchCount == mark.Length) + return offset; + + pos = offset; + matchCount = 0; + } + + while (true) + { + pos = source.IndexOf(mark[matchCount], pos, length - pos + offset); + + if (pos < 0) + return null; + + matchCount += 1; + + for (int i = matchCount; i < mark.Length; i++) + { + int checkPos = pos + i; + + if (checkPos > endOffset) + { + //found end, return matched chars count + return (0 - matchCount); + } + + if (!source[checkPos].Equals(mark[i])) + break; + + matchCount++; + } + + if (matchCount == mark.Length) + return pos; + + //Reset next round read pos + pos += 1; + //clear matched chars count + matchCount = 0; + } + } + + /// + /// Searches the mark from source. + /// + /// + /// The source. + /// The offset. + /// The length. + /// State of the search. + /// + public static int SearchMark(this IList source, int offset, int length, SearchMarkState searchState) + where T : IEquatable + { + int? result = source.SearchMark(offset, length, searchState.Mark, searchState.Matched); + + if (!result.HasValue) + { + searchState.Matched = 0; + return -1; + } + + if (result.Value < 0) + { + searchState.Matched = 0 - result.Value; + return -1; + } + + searchState.Matched = 0; + return result.Value; + } + + /// + /// Startses the with. + /// + /// + /// The source. + /// The mark. + /// + public static int StartsWith(this IList source, T[] mark) + where T : IEquatable + { + return source.StartsWith(0, source.Count, mark); + } + + /// + /// Startses the with. + /// + /// + /// The source. + /// The offset. + /// The length. + /// The mark. + /// + public static int StartsWith(this IList source, int offset, int length, T[] mark) + where T : IEquatable + { + int pos = offset; + int endOffset = offset + length - 1; + + for (int i = 0; i < mark.Length; i++) + { + int checkPos = pos + i; + + if (checkPos > endOffset) + return i; + + if (!source[checkPos].Equals(mark[i])) + return -1; + } + + return mark.Length; + } + + /// + /// Endses the with. + /// + /// + /// The source. + /// The mark. + /// + public static bool EndsWith(this IList source, T[] mark) + where T : IEquatable + { + return source.EndsWith(0, source.Count, mark); + } + + /// + /// Endses the with. + /// + /// + /// The source. + /// The offset. + /// The length. + /// The mark. + /// + public static bool EndsWith(this IList source, int offset, int length, T[] mark) + where T : IEquatable + { + if (mark.Length > length) + return false; + + for (int i = 0; i < Math.Min(length, mark.Length); i++) + { + if (!mark[i].Equals(source[offset + length - mark.Length + i])) + return false; + } + + return true; + } + + /// + /// Clones the elements in the specific range. + /// + /// + /// The source. + /// The offset. + /// The length. + /// + public static T[] CloneRange(this T[] source, int offset, int length) + { + T[] target = new T[length]; + Array.Copy(source, offset, target, 0, length); + return target; + } + } +} diff --git a/Common/BufferManager.cs b/Common/BufferManager.cs new file mode 100644 index 000000000..f6740e0b7 --- /dev/null +++ b/Common/BufferManager.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Net.Sockets; + +namespace SuperSocket.Common +{ + /// + /// This class creates a single large buffer which can be divided up and assigned to SocketAsyncEventArgs objects for use + /// with each socket I/O operation. This enables bufffers to be easily reused and gaurds against fragmenting heap memory. + /// + /// The operations exposed on the BufferManager class are not thread safe. + /// + public class BufferManager + { + int m_numBytes; // the total number of bytes controlled by the buffer pool + byte[] m_buffer; // the underlying byte array maintained by the Buffer Manager + Stack m_freeIndexPool; // + int m_currentIndex; + int m_bufferSize; + + /// + /// Initializes a new instance of the class. + /// + /// The total bytes. + /// Size of the buffer. + public BufferManager(int totalBytes, int bufferSize) + { + m_numBytes = totalBytes; + m_currentIndex = 0; + m_bufferSize = bufferSize; + m_freeIndexPool = new Stack(); + } + + /// + /// Allocates buffer space used by the buffer pool + /// + public void InitBuffer() + { + // create one big large buffer and divide that out to each SocketAsyncEventArg object + m_buffer = new byte[m_numBytes]; + } + + /// + /// Assigns a buffer from the buffer pool to the specified SocketAsyncEventArgs object + /// + /// true if the buffer was successfully set, else false + public bool SetBuffer(SocketAsyncEventArgs args) + { + + if (m_freeIndexPool.Count > 0) + { + args.SetBuffer(m_buffer, m_freeIndexPool.Pop(), m_bufferSize); + } + else + { + if ((m_numBytes - m_bufferSize) < m_currentIndex) + { + return false; + } + args.SetBuffer(m_buffer, m_currentIndex, m_bufferSize); + m_currentIndex += m_bufferSize; + } + return true; + } + + /// + /// Removes the buffer from a SocketAsyncEventArg object. This frees the buffer back to the + /// buffer pool + /// + public void FreeBuffer(SocketAsyncEventArgs args) + { + m_freeIndexPool.Push(args.Offset); + args.SetBuffer(null, 0, 0); + } + + } +} diff --git a/Common/ConcurrentBatchQueue.cs b/Common/ConcurrentBatchQueue.cs new file mode 100644 index 000000000..cc77ae0ba --- /dev/null +++ b/Common/ConcurrentBatchQueue.cs @@ -0,0 +1,269 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; + +namespace SuperSocket.Common +{ + /// + /// Concurrent BatchQueue + /// + /// + public class ConcurrentBatchQueue : IBatchQueue + { + private Entity m_Entity; + private Entity m_BackEntity; + + private static readonly T m_Null = default(T); + + private Func m_NullValidator; + + class Entity + { + public T[] Array { get; set; } + + public int Count; + } + + /// + /// Initializes a new instance of the class. + /// + public ConcurrentBatchQueue() + : this(16) + { + + } + + /// + /// Initializes a new instance of the class. + /// + /// The capacity of the queue. + public ConcurrentBatchQueue(int capacity) + : this(new T[capacity]) + { + + } + + /// + /// Initializes a new instance of the class. + /// + /// The capacity. + /// The null validator. + public ConcurrentBatchQueue(int capacity, Func nullValidator) + : this(new T[capacity], nullValidator) + { + + } + + /// + /// Initializes a new instance of the class. + /// + /// The array. + public ConcurrentBatchQueue(T[] array) + : this(array, (t) => t == null) + { + + } + + /// + /// Initializes a new instance of the class. + /// + /// The array. + /// The null validator. + public ConcurrentBatchQueue(T[] array, Func nullValidator) + { + m_Entity = new Entity(); + m_Entity.Array = array; + + m_BackEntity = new Entity(); + m_BackEntity.Array = new T[array.Length]; + + m_NullValidator = nullValidator; + } + + /// + /// Enqueues the specified item. + /// + /// The item. + public bool Enqueue(T item) + { + bool full; + + while (true) + { + if (TryEnqueue(item, out full) || full) + break; + } + + return !full; + } + + private bool TryEnqueue(T item, out bool full) + { + full = false; + + EnsureNotRebuild(); + + var entity = m_Entity; + var array = entity.Array; + var count = entity.Count; + + if (count >= array.Length) + { + full = true; + return false; + } + + if(entity != m_Entity) + return false; + + int oldCount = Interlocked.CompareExchange(ref entity.Count, count + 1, count); + + if (oldCount != count) + return false; + + array[count] = item; + + return true; + } + + /// + /// Enqueues the specified items. + /// + /// The items. + public bool Enqueue(IList items) + { + bool full; + + while (true) + { + if (TryEnqueue(items, out full) || full) + break; + } + + return !full; + } + + private bool TryEnqueue(IList items, out bool full) + { + full = false; + + var entity = m_Entity; + var array = entity.Array; + var count = entity.Count; + + int newItemCount = items.Count; + int expectedCount = count + newItemCount; + + if (expectedCount > array.Length) + { + full = true; + return false; + } + + if (entity != m_Entity) + return false; + + int oldCount = Interlocked.CompareExchange(ref entity.Count, expectedCount, count); + + if (oldCount != count) + return false; + + foreach (var item in items) + { + array[count++] = item; + } + + return true; + } + + private void EnsureNotRebuild() + { + if (!m_Rebuilding) + return; + + var spinWait = new SpinWait(); + + while (true) + { + spinWait.SpinOnce(); + + if (!m_Rebuilding) + break; + } + } + + private bool m_Rebuilding = false; + + /// + /// Tries the dequeue. + /// + /// The output items. + /// + public bool TryDequeue(IList outputItems) + { + var entity = m_Entity; + int count = entity.Count; + + if (count <= 0) + return false; + + var spinWait = new SpinWait(); + + Interlocked.Exchange(ref m_Entity, m_BackEntity); + + spinWait.SpinOnce(); + + count = entity.Count; + + var array = entity.Array; + + var i = 0; + + while (true) + { + var item = array[i]; + + while (m_NullValidator(item)) + { + spinWait.SpinOnce(); + item = array[i]; + } + + outputItems.Add(array[i]); + array[i] = m_Null; + + + if (entity.Count <= (i + 1)) + break; + + i++; + } + + m_BackEntity = entity; + m_BackEntity.Count = 0; + + return true; + } + + /// + /// Gets a value indicating whether this instance is empty. + /// + /// + /// true if this instance is empty; otherwise, false. + /// + public bool IsEmpty + { + get { return m_Entity.Count <= 0; } + } + + /// + /// Gets the count. + /// + public int Count + { + get { return m_Entity.Count; } + } + } +} diff --git a/Common/ConfigurationElementBase.cs b/Common/ConfigurationElementBase.cs new file mode 100644 index 000000000..6c15110fe --- /dev/null +++ b/Common/ConfigurationElementBase.cs @@ -0,0 +1,107 @@ +using System; +using System.Configuration; +using System.Collections.Specialized; +using System.Xml; + +namespace SuperSocket.Common +{ + /// + /// ConfigurationElementBase + /// + [Serializable] + public class ConfigurationElementBase : ConfigurationElement + { + private bool m_NameRequired; + + /// + /// Initializes a new instance of the class. + /// + public ConfigurationElementBase() + : this(true) + { + + } + + /// + /// Initializes a new instance of the class. + /// + /// if set to true [name required]. + public ConfigurationElementBase(bool nameRequired) + { + m_NameRequired = nameRequired; + } + + /// + /// Gets the name. + /// + [ConfigurationProperty("name")] + public string Name + { + get { return this["name"] as string; } + } + + /// + /// Reads XML from the configuration file. + /// + /// The that reads from the configuration file. + /// true to serialize only the collection key properties; otherwise, false. + /// The element to read is locked.- or -An attribute of the current node is not recognized.- or -The lock status of the current node cannot be determined. + protected override void DeserializeElement(XmlReader reader, bool serializeCollectionKey) + { + base.DeserializeElement(reader, serializeCollectionKey); + + if (m_NameRequired && string.IsNullOrEmpty(Name)) + { + throw new ConfigurationErrorsException("Required attribute 'name' not found."); + } + } + + /// + /// Gets the options. + /// + public NameValueCollection Options { get; private set; } + + /// + /// Gets a value indicating whether an unknown attribute is encountered during deserialization. + /// + /// The name of the unrecognized attribute. + /// The value of the unrecognized attribute. + /// + /// true when an unknown attribute is encountered while deserializing; otherwise, false. + /// + protected override bool OnDeserializeUnrecognizedAttribute(string name, string value) + { + if (Options == null) + { + Options = new NameValueCollection(); + } + + Options.Add(name, value); + return true; + } + + /// + /// Gets the option elements. + /// + public NameValueCollection OptionElements { get; private set; } + + /// + /// Gets a value indicating whether an unknown element is encountered during deserialization. + /// + /// The name of the unknown subelement. + /// The being used for deserialization. + /// + /// true when an unknown element is encountered while deserializing; otherwise, false. + /// + /// The element identified by is locked.- or -One or more of the element's attributes is locked.- or - is unrecognized, or the element has an unrecognized attribute.- or -The element has a Boolean attribute with an invalid value.- or -An attempt was made to deserialize a property more than once.- or -An attempt was made to deserialize a property that is not a valid member of the element.- or -The element cannot contain a CDATA or text element. + protected override bool OnDeserializeUnrecognizedElement(string elementName, System.Xml.XmlReader reader) + { + if (OptionElements == null) + OptionElements = new NameValueCollection(); + + OptionElements.Add(elementName, reader.ReadOuterXml()); + return true; + } + } +} + diff --git a/Common/ConfigurationExtension.cs b/Common/ConfigurationExtension.cs new file mode 100644 index 000000000..8a47505a1 --- /dev/null +++ b/Common/ConfigurationExtension.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Configuration; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Xml; +using System.IO; + +namespace SuperSocket.Common +{ + /// + /// Configuration extension class + /// + public static class ConfigurationExtension + { + /// + /// Gets the value from namevalue collection by key. + /// + /// The collection. + /// The key. + /// + public static string GetValue(this NameValueCollection collection, string key) + { + return GetValue(collection, key, string.Empty); + } + + /// + /// Gets the value from namevalue collection by key. + /// + /// The collection. + /// The key. + /// The default value. + /// + public static string GetValue(this NameValueCollection collection, string key, string defaultValue) + { + if (string.IsNullOrEmpty(key)) + throw new ArgumentNullException("key"); + + if (collection == null) + return defaultValue; + + var e = collection[key]; + + if (e == null) + return defaultValue; + + return e; + } + + /// + /// Deserializes the specified configuration section. + /// + /// The type of the element. + /// The section. + /// The reader. + public static void Deserialize(this TElement section, XmlReader reader) + where TElement : ConfigurationElement + { + var deserializeElementMethod = typeof(TElement).GetMethod("DeserializeElement", BindingFlags.NonPublic | BindingFlags.Instance); + deserializeElementMethod.Invoke(section, new object[] { reader, false }); + } + + /// + /// Gets the child config. + /// + /// The type of the config. + /// The child elements. + /// Name of the child config. + /// + public static TConfig GetChildConfig(this NameValueCollection childElements, string childConfigName) + where TConfig : ConfigurationElement, new() + { + var childConfig = childElements.GetValue(childConfigName, string.Empty); + + if (string.IsNullOrEmpty(childConfig)) + return default(TConfig); + + XmlReader reader = new XmlTextReader(new StringReader(childConfig)); + + var config = new TConfig(); + + reader.Read(); + config.Deserialize(reader); + + return config; + } + + /// + /// Gets the config source path. + /// + /// The config. + /// + public static string GetConfigSource(this ConfigurationElement config) + { + var source = config.ElementInformation.Source; + + if (!string.IsNullOrEmpty(source) || !Platform.IsMono) + return source; + + var configProperty = typeof(ConfigurationElement).GetProperty("Configuration", BindingFlags.Instance | BindingFlags.NonPublic); + + if (configProperty == null) + return string.Empty; + + var configuration = (Configuration)configProperty.GetValue(config, new object[0]); + return configuration.FilePath; + } + } +} diff --git a/Common/DictionaryExtension.cs b/Common/DictionaryExtension.cs new file mode 100644 index 000000000..bc5e76295 --- /dev/null +++ b/Common/DictionaryExtension.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.Common +{ + /// + /// Extension class for IDictionary + /// + public static class DictionaryExtension + { + /// + /// Gets the value by key. + /// + /// + /// The dictionary. + /// The key. + /// + public static T GetValue(this IDictionary dictionary, object key) + where T : new() + { + T defaultValue = default(T); + return GetValue(dictionary, key, defaultValue); + } + + /// + /// Gets the value by key and default value. + /// + /// + /// The dictionary. + /// The key. + /// The default value. + /// + public static T GetValue(this IDictionary dictionary, object key, T defaultValue) + { + object valueObj; + + if (!dictionary.TryGetValue(key, out valueObj)) + { + return defaultValue; + } + else + { + return (T)valueObj; + } + } + } +} diff --git a/Common/ErrorEventArgs.cs b/Common/ErrorEventArgs.cs new file mode 100644 index 000000000..85607c575 --- /dev/null +++ b/Common/ErrorEventArgs.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.Common +{ + /// + /// EventArgs for error and exception + /// + public class ErrorEventArgs : EventArgs + { + /// + /// Gets the exception. + /// + public Exception Exception { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// The message. + public ErrorEventArgs(string message) + { + Exception = new Exception(message); + } + + /// + /// Initializes a new instance of the class. + /// + /// The exception. + public ErrorEventArgs(Exception exception) + { + Exception = exception; + } + } +} diff --git a/Common/GenericConfigurationElementCollection.cs b/Common/GenericConfigurationElementCollection.cs new file mode 100644 index 000000000..da5afc663 --- /dev/null +++ b/Common/GenericConfigurationElementCollection.cs @@ -0,0 +1,98 @@ +using System; +using System.Configuration; +using System.Collections.Generic; + +namespace SuperSocket.Common +{ + /// + /// GenericConfigurationElementCollectionBase + /// + /// The type of the config element. + /// The type of the config interface. + public class GenericConfigurationElementCollectionBase : ConfigurationElementCollection, IEnumerable + where TConfigElement : ConfigurationElement, TConfigInterface, new() + { + /// + /// Gets or sets a property, attribute, or child element of this configuration element. + /// + /// The specified property, attribute, or child element + public TConfigElement this[int index] + { + get + { + return (TConfigElement)base.BaseGet(index); + } + set + { + if (base.BaseGet(index) != null) + { + base.BaseRemoveAt(index); + } + this.BaseAdd(index, value as ConfigurationElement); + } + } + + /// + /// When overridden in a derived class, creates a new . + /// + /// + /// A new . + /// + protected override ConfigurationElement CreateNewElement() + { + return new TConfigElement() as ConfigurationElement; + } + + /// + /// Gets the element key for a specified configuration element when overridden in a derived class. + /// + /// The to return the key for. + /// + /// An that acts as the key for the specified . + /// + protected override object GetElementKey(ConfigurationElement element) + { + return element; + } + + #region IEnumerable[T] implementation + + /// + /// Returns an enumerator that iterates through the collection. + /// + /// + /// A that can be used to iterate through the collection. + /// + public new IEnumerator GetEnumerator() + { + int count = base.Count; + + for (int i = 0; i < count; i++) + { + yield return (TConfigElement)base.BaseGet(i); + } + } + + #endregion + } + + /// + /// GenericConfigurationElementCollection + /// + /// The type of the config element. + /// The type of the config interface. + public class GenericConfigurationElementCollection : GenericConfigurationElementCollectionBase, IEnumerable + where TConfigElement : ConfigurationElementBase, TConfigInterface, new() + { + /// + /// Gets the element key. + /// + /// The element. + /// + protected override object GetElementKey(ConfigurationElement element) + { + return ((TConfigElement)element).Name; + } + } +} + diff --git a/Common/GlobalResourceManager.cs b/Common/GlobalResourceManager.cs new file mode 100644 index 000000000..e4c7dcd65 --- /dev/null +++ b/Common/GlobalResourceManager.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Reflection; +using System.Resources; + +namespace SuperSocket.Common +{ + /// + /// Global resource manager + /// + public static class GlobalResourceManager + { + private static Dictionary m_DictResources = new Dictionary(); + + private static object m_SyncRoot = new object(); + + /// + /// Registers the resource into resource manager. + /// + /// The name. + /// Name of the base. + /// The assembly. + public static void RegisterResource(string name, string baseName, Assembly assembly) + { + ResourceManager resource = new ResourceManager(baseName, assembly); + + lock (m_SyncRoot) + { + m_DictResources[name.ToLower()] = resource; + } + } + + /// + /// Gets the string from resource manager by resource name and key. + /// + /// Name of the resource. + /// The key. + /// + public static string GetString(string resourceName, string key) + { + ResourceManager manager; + + if (m_DictResources.TryGetValue(resourceName.ToLower(), out manager)) + { + return manager.GetString(key); + } + else + { + return string.Empty; + } + } + + /// + /// Gets the resource manager by name. + /// + /// Name of the resource. + /// + public static ResourceManager GetResourceManager(string resourceName) + { + ResourceManager manager; + + if (m_DictResources.TryGetValue(resourceName.ToLower(), out manager)) + { + return manager; + } + else + { + return null; + } + } + } +} diff --git a/Common/GlobalResources.cs b/Common/GlobalResources.cs new file mode 100644 index 000000000..d195da19e --- /dev/null +++ b/Common/GlobalResources.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Resources; +using System.Globalization; +using System.Reflection; + +namespace SuperSocket.Common +{ + /// + /// Global resources + /// + public static class GlobalResources + { + private static ResourceManager resourceMan; + + private static CultureInfo resourceCulture; + + /// + /// Setups by the specified base name. + /// + /// Name of the base. + /// The assembly. + public static void Setup(string baseName, Assembly assembly) + { + resourceMan = new ResourceManager(baseName, assembly); + } + + /// + /// Gets or sets the culture. + /// + /// + /// The culture. + /// + public static CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + + /// + /// Gets the string. + /// + /// The name. + /// The culture. + /// + public static string GetString(string name, CultureInfo culture) + { + if (resourceMan != null) + return resourceMan.GetString(name, culture); + else + return string.Empty; + } + + /// + /// Gets the string. + /// + /// The name. + /// + public static string GetString(string name) + { + if (resourceMan != null) + return GetString(name, resourceCulture); + else + return string.Empty; + } + } +} diff --git a/Common/IBatchQueue.cs b/Common/IBatchQueue.cs new file mode 100644 index 000000000..23b50033f --- /dev/null +++ b/Common/IBatchQueue.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.Common +{ + /// + /// A queue interface which can operate in batch + /// + /// + public interface IBatchQueue + { + /// + /// Enqueues the specified item. + /// + /// The item. + bool Enqueue(T item); + + /// + /// Enqueues the specified items. + /// + /// The items. + bool Enqueue(IList items); + + /// + /// Tries to dequeue all items in the queue into the output list. + /// + /// The output items. + /// + bool TryDequeue(IList outputItems); + + /// + /// Gets a value indicating whether this instance is empty. + /// + /// + /// true if this instance is empty; otherwise, false. + /// + bool IsEmpty { get; } + + /// + /// Gets the count. + /// + int Count { get; } + } +} diff --git a/Common/Platform.cs b/Common/Platform.cs new file mode 100644 index 000000000..54ae37f5d --- /dev/null +++ b/Common/Platform.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Net.Sockets; + +namespace SuperSocket.Common +{ + /// + /// This class is designed for detect platform attribute in runtime + /// + public static class Platform + { + static Platform() + { + try + { + var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + socket.IOControl(IOControlCode.KeepAliveValues, null, null); + SupportSocketIOControlByCodeEnum = true; + } + catch (NotSupportedException) + { + SupportSocketIOControlByCodeEnum = false; + } + catch (NotImplementedException) + { + SupportSocketIOControlByCodeEnum = false; + } + catch (Exception) + { + SupportSocketIOControlByCodeEnum = true; + } + + Type t = Type.GetType("Mono.Runtime"); + IsMono = t != null; + } + + /// + /// Gets a value indicating whether [support socket IO control by code enum]. + /// + /// + /// true if [support socket IO control by code enum]; otherwise, false. + /// + public static bool SupportSocketIOControlByCodeEnum { get; private set; } + + /// + /// Gets a value indicating whether this instance is mono. + /// + /// + /// true if this instance is mono; otherwise, false. + /// + public static bool IsMono { get; private set; } + } +} diff --git a/Common/PosList.cs b/Common/PosList.cs new file mode 100644 index 000000000..a6beaff2f --- /dev/null +++ b/Common/PosList.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.Common +{ + /// + /// The generic list interface with position + /// + /// + public interface IPosList : IList + { + /// + /// Gets or sets the position of current item. + /// + /// + /// The position. + /// + int Position { get; set; } + } + + /// + /// The generic list with position + /// + /// + public class PosList : List, IPosList + { + /// + /// Gets or sets the position of current item. + /// + /// + /// The position. + /// + public int Position { get; set; } + } +} diff --git a/Common/Properties/AssemblyInfo.cs b/Common/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..49a8374a0 --- /dev/null +++ b/Common/Properties/AssemblyInfo.cs @@ -0,0 +1,17 @@ +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("SuperSocket.Common")] +[assembly: AssemblyDescription("SuperSocket.Common")] +[assembly: AssemblyConfiguration("")] +// 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)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("8056596a-0926-47ad-9f2f-6adad34fdba3")] diff --git a/Common/SearchMarkState.cs b/Common/SearchMarkState.cs new file mode 100644 index 000000000..02cd813f4 --- /dev/null +++ b/Common/SearchMarkState.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.Common +{ + /// + /// SearchMarkState + /// + /// + public class SearchMarkState + where T : IEquatable + { + /// + /// Initializes a new instance of the class. + /// + /// The mark. + public SearchMarkState(T[] mark) + { + Mark = mark; + } + + /// + /// Gets the mark. + /// + public T[] Mark { get; private set; } + + /// + /// Gets or sets whether matched already. + /// + /// + /// The matched. + /// + public int Matched { get; set; } + } +} diff --git a/Common/SocketEx.cs b/Common/SocketEx.cs new file mode 100644 index 000000000..81f0b6281 --- /dev/null +++ b/Common/SocketEx.cs @@ -0,0 +1,70 @@ +using System; +using System.Net.Sockets; + +namespace SuperSocket.Common +{ + /// + /// Socket extension class + /// + public static class SocketEx + { + /// + /// Close the socket safely. + /// + /// The socket. + public static void SafeClose(this Socket socket) + { + if (socket == null) + return; + + if (!socket.Connected) + return; + + try + { + socket.Shutdown(SocketShutdown.Both); + } + catch + { + } + + try + { + socket.Close(); + } + catch + { + } + } + + /// + /// Sends the data. + /// + /// The client. + /// The data. + public static void SendData(this Socket client, byte[] data) + { + SendData(client, data, 0, data.Length); + } + + /// + /// Sends the data. + /// + /// The client. + /// The data. + /// The offset. + /// The length. + public static void SendData(this Socket client, byte[] data, int offset, int length) + { + int sent = 0; + int thisSent = 0; + + while ((length - sent) > 0) + { + thisSent = client.Send(data, offset + sent, length - sent, SocketFlags.None); + sent += thisSent; + } + } + } +} + diff --git a/Common/StringExtension.NET35.cs b/Common/StringExtension.NET35.cs new file mode 100644 index 000000000..3574a7d52 --- /dev/null +++ b/Common/StringExtension.NET35.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.Common +{ + /// + /// String extension + /// + public static partial class StringExtension + { + /// + /// Tries to parse string to enum type. + /// + /// + /// The value. + /// if set to true [ignore case]. + /// The enum value. + /// + public static bool TryParseEnum(this string value, bool ignoreCase, out T enumValue) + where T : struct + { + try + { + enumValue = (T)System.Enum.Parse(typeof(T), value, ignoreCase); + return true; + } + catch + { + enumValue = default(T); + return false; + } + } + } +} diff --git a/Common/StringExtension.NET4.cs b/Common/StringExtension.NET4.cs new file mode 100644 index 000000000..42a2e5d78 --- /dev/null +++ b/Common/StringExtension.NET4.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.Common +{ + /// + /// String extension + /// + public static partial class StringExtension + { + /// + /// Tries parse string to enum. + /// + /// the enum type + /// The value. + /// if set to true [ignore case]. + /// The enum value. + /// + public static bool TryParseEnum(this string value, bool ignoreCase, out T enumValue) + where T : struct + { + return Enum.TryParse(value, ignoreCase, out enumValue); + } + } +} diff --git a/Common/StringExtension.cs b/Common/StringExtension.cs new file mode 100644 index 000000000..607837249 --- /dev/null +++ b/Common/StringExtension.cs @@ -0,0 +1,187 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.Common +{ + /// + /// String extension class + /// + public static partial class StringExtension + { + /// + /// Convert string to int32. + /// + /// The source. + /// + public static int ToInt32(this string source) + { + return source.ToInt32(0); + } + + /// + /// Convert string to int32. + /// + /// The source. + /// The default value. + /// + public static int ToInt32(this string source, int defaultValue) + { + if (string.IsNullOrEmpty(source)) + return defaultValue; + + int value; + + if (!int.TryParse(source, out value)) + value = defaultValue; + + return value; + } + + /// + /// Convert string to long. + /// + /// The source. + /// + public static long ToLong(this string source) + { + return source.ToLong(0); + } + + /// + /// Convert string to long. + /// + /// The source. + /// The default value. + /// + public static long ToLong(this string source, long defaultValue) + { + if (string.IsNullOrEmpty(source)) + return defaultValue; + + long value; + + if (!long.TryParse(source, out value)) + value = defaultValue; + + return value; + } + + /// + /// Convert string to short. + /// + /// The source. + /// + public static short ToShort(this string source) + { + return source.ToShort(0); + } + + /// + /// Convert string to short. + /// + /// The source. + /// The default value. + /// + public static short ToShort(this string source, short defaultValue) + { + if (string.IsNullOrEmpty(source)) + return defaultValue; + + short value; + + if (!short.TryParse(source, out value)) + value = defaultValue; + + return value; + } + + /// + /// Convert string to decimal. + /// + /// The source. + /// + public static decimal ToDecimal(this string source) + { + return source.ToDecimal(0); + } + + /// + /// Convert string to decimal. + /// + /// The source. + /// The default value. + /// + public static decimal ToDecimal(this string source, decimal defaultValue) + { + if (string.IsNullOrEmpty(source)) + return defaultValue; + + decimal value; + + if (!decimal.TryParse(source, out value)) + value = defaultValue; + + return value; + } + + /// + /// Convert string to date time. + /// + /// The source. + /// + public static DateTime ToDateTime(this string source) + { + return source.ToDateTime(DateTime.MinValue); + } + + /// + /// Convert string to date time. + /// + /// The source. + /// The default value. + /// + public static DateTime ToDateTime(this string source, DateTime defaultValue) + { + if (string.IsNullOrEmpty(source)) + return defaultValue; + + DateTime value; + + if (!DateTime.TryParse(source, out value)) + value = defaultValue; + + return value; + } + + /// + /// Convert string to boolean. + /// + /// The source. + /// + public static bool ToBoolean(this string source) + { + return source.ToBoolean(false); + } + + /// + /// Convert string tp boolean. + /// + /// The source. + /// if set to true [default value]. + /// + public static bool ToBoolean(this string source, bool defaultValue) + { + if (string.IsNullOrEmpty(source)) + return defaultValue; + + bool value; + + if (!bool.TryParse(source, out value)) + value = defaultValue; + + return value; + } + } +} diff --git a/Common/SuperSocket.Common.Net35.csproj b/Common/SuperSocket.Common.Net35.csproj new file mode 100644 index 000000000..adfad1b53 --- /dev/null +++ b/Common/SuperSocket.Common.Net35.csproj @@ -0,0 +1,137 @@ + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A} + Library + Properties + SuperSocket.Common + SuperSocket.Common + + + 3.5 + + + v3.5 + false + + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + true + AllRules.ruleset + bin\Debug\SuperSocket.Common.XML + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + AllRules.ruleset + bin\Release\SuperSocket.Common.XML + true + + + true + + + ..\supersocket.snk + + + + False + ..\Reference\log4net.dll + + + + + 3.5 + + + False + ..\Reference\System.Threading.dll + + + + + + GlobalAssemblyInfo.cs + + + + Code + + + + Code + + + + + + + + + + + + + + + + + + + + + + + False + .NET Framework 3.5 SP1 Client Profile + false + + + False + .NET Framework 3.5 SP1 + false + + + False + Windows Installer 3.1 + true + + + + + \ No newline at end of file diff --git a/Common/SuperSocket.Common.csproj b/Common/SuperSocket.Common.csproj new file mode 100644 index 000000000..2fa52aed0 --- /dev/null +++ b/Common/SuperSocket.Common.csproj @@ -0,0 +1,135 @@ + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A} + Library + Properties + SuperSocket.Common + SuperSocket.Common + + + 3.5 + + + v4.0 + false + + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + true + AllRules.ruleset + bin\Debug\SuperSocket.Common.XML + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + AllRules.ruleset + bin\Release\SuperSocket.Common.XML + true + + + true + + + ..\supersocket.snk + + + + ..\Reference\log4net.dll + + + + + 3.5 + + + + + + GlobalAssemblyInfo.cs + + + + Code + + + + Code + + + + + + + + + + + + + + + + + + + + + False + Microsoft .NET Framework 4 %28x86 and x64%29 + true + + + False + .NET Framework 3.5 SP1 Client Profile + false + + + False + .NET Framework 3.5 SP1 + false + + + False + Windows Installer 3.1 + true + + + + + \ No newline at end of file diff --git a/Common/TheadPoolEx.cs b/Common/TheadPoolEx.cs new file mode 100644 index 000000000..e7cab86b9 --- /dev/null +++ b/Common/TheadPoolEx.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; + +namespace SuperSocket.Common +{ + /// + /// Thread pool extension class + /// + public static class TheadPoolEx + { + /// + /// Resets the thread pool. + /// + /// The max working threads. + /// The max completion port threads. + /// The min working threads. + /// The min completion port threads. + /// + public static bool ResetThreadPool(int? maxWorkingThreads, int? maxCompletionPortThreads, int? minWorkingThreads, int? minCompletionPortThreads) + { + if (maxWorkingThreads.HasValue || maxCompletionPortThreads.HasValue) + { + int oldMaxWorkingThreads, oldMaxCompletionPortThreads; + + ThreadPool.GetMaxThreads(out oldMaxWorkingThreads, out oldMaxCompletionPortThreads); + + if (!maxWorkingThreads.HasValue) + maxWorkingThreads = oldMaxWorkingThreads; + + if (!maxCompletionPortThreads.HasValue) + maxCompletionPortThreads = oldMaxCompletionPortThreads; + + if (maxWorkingThreads.Value != oldMaxWorkingThreads + || maxCompletionPortThreads.Value != oldMaxCompletionPortThreads) + { + if (!ThreadPool.SetMaxThreads(maxWorkingThreads.Value, maxCompletionPortThreads.Value)) + return false; + } + } + + if (minWorkingThreads.HasValue || minCompletionPortThreads.HasValue) + { + int oldMinWorkingThreads, oldMinCompletionPortThreads; + + ThreadPool.GetMinThreads(out oldMinWorkingThreads, out oldMinCompletionPortThreads); + + if (!minWorkingThreads.HasValue) + minWorkingThreads = oldMinWorkingThreads; + + if (!minCompletionPortThreads.HasValue) + minCompletionPortThreads = oldMinCompletionPortThreads; + + if (minWorkingThreads.Value != oldMinWorkingThreads + || minCompletionPortThreads.Value != oldMinCompletionPortThreads) + { + if (!ThreadPool.SetMinThreads(minWorkingThreads.Value, minCompletionPortThreads.Value)) + return false; + } + } + + return true; + } + } +} diff --git a/Dlr/DynamicCommand.cs b/Dlr/DynamicCommand.cs new file mode 100644 index 000000000..81981c7d6 --- /dev/null +++ b/Dlr/DynamicCommand.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Microsoft.Scripting; +using Microsoft.Scripting.Hosting; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.Dlr +{ + class DynamicCommand : ICommand + where TAppSession : IAppSession, IAppSession, new() + where TRequestInfo : IRequestInfo + { + private Action m_DynamicExecuteCommand; + + public DynamicCommand(ScriptRuntime scriptRuntime, IScriptSource source) + { + Source = source; + + Name = source.Name; + + var scriptEngine = scriptRuntime.GetEngineByFileExtension(source.LanguageExtension); + var scriptScope = scriptEngine.CreateScope(); + + var scriptSource = scriptEngine.CreateScriptSourceFromString(source.GetScriptCode(), SourceCodeKind.File); + var compiledCode = scriptSource.Compile(); + compiledCode.Execute(scriptScope); + + Action dynamicMethod; + if (!scriptScope.TryGetVariable>("execute", out dynamicMethod)) + throw new Exception("Failed to find a command execution method in source: " + source.Tag); + + CompiledTime = DateTime.Now; + + m_DynamicExecuteCommand = dynamicMethod; + } + + #region ICommand Members + + public virtual void ExecuteCommand(TAppSession session, TRequestInfo requestInfo) + { + m_DynamicExecuteCommand(session, requestInfo); + } + + #endregion + + public IScriptSource Source { get; private set; } + + public DateTime CompiledTime { get; private set; } + + #region ICommand Members + + public string Name { get; private set; } + + #endregion + } +} diff --git a/Dlr/DynamicCommandLoader.cs b/Dlr/DynamicCommandLoader.cs new file mode 100644 index 000000000..9dbd2c6c6 --- /dev/null +++ b/Dlr/DynamicCommandLoader.cs @@ -0,0 +1,101 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using Microsoft.Scripting.Hosting; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Config; + +namespace SuperSocket.Dlr +{ + /// + /// DynamicCommandLoader + /// + public class DynamicCommandLoader : DynamicCommandLoaderBase + { + private HashSet m_ScriptFileExtensions; + + /// + /// Initializes a new instance of the class. + /// + public DynamicCommandLoader() + : base() + { + LoadScriptFileExtensions(); + } + + /// + /// Initializes a new instance of the class. + /// + /// The script runtime. + public DynamicCommandLoader(ScriptRuntime scriptRuntime) + : base(scriptRuntime) + { + LoadScriptFileExtensions(); + } + + private void LoadScriptFileExtensions() + { + List fileExtensions = new List(); + + foreach (var fxts in ScriptRuntime.Setup.LanguageSetups.Select(s => s.FileExtensions)) + fileExtensions.AddRange(fxts); + + m_ScriptFileExtensions = new HashSet(fileExtensions, StringComparer.OrdinalIgnoreCase); + } + + private IEnumerable GetCommandFiles(string path, SearchOption option) + { + return Directory.GetFiles(path, "*.*", option).Where(f => m_ScriptFileExtensions.Contains(Path.GetExtension(f))); + } + + /// + /// Gets the script sources. + /// + /// The root config. + /// The app server. + /// + protected override IEnumerable GetScriptSources(IRootConfig rootConfig, IAppServer appServer) + { + var sources = new List(); + + string commandDir = string.Empty; + string serverCommandDir = string.Empty; + + var commandDirSearchOption = SearchOption.TopDirectoryOnly; + + if (rootConfig.Isolation == IsolationMode.None) + { + commandDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Command"); + serverCommandDir = Path.Combine(commandDir, appServer.Name); + } + else + { + commandDirSearchOption = SearchOption.AllDirectories; + commandDir = Path.Combine(Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory).Parent.FullName, "Command"); + serverCommandDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Command"); + } + + List commandFiles = new List(); + + if (Directory.Exists(commandDir)) + commandFiles.AddRange(GetCommandFiles(commandDir, commandDirSearchOption)); + + if (Directory.Exists(serverCommandDir)) + commandFiles.AddRange(GetCommandFiles(serverCommandDir, SearchOption.AllDirectories)); + + if (!commandFiles.Any()) + { + return sources; + } + + foreach (var file in commandFiles) + { + sources.Add(new FileScriptSource(file)); + } + + return sources; + } + } +} diff --git a/Dlr/DynamicCommandLoaderBase.cs b/Dlr/DynamicCommandLoaderBase.cs new file mode 100644 index 000000000..8d3f9f4c9 --- /dev/null +++ b/Dlr/DynamicCommandLoaderBase.cs @@ -0,0 +1,259 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using Microsoft.Scripting.Hosting; +using SuperSocket.Common; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Config; +using SuperSocket.SocketBase.Logging; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.Dlr +{ + /// + /// Which is used for loading dynamic script file + /// + public abstract class DynamicCommandLoaderBase : CommandLoaderBase + { + class CommandFileEntity + { + public IScriptSource Source { get; set; } + public bool Processed { get; set; } + } + + class ServerCommandState + { + public List Sources { get; set; } + public Action>> CommandUpdater { get; set; } + } + + /// + /// Gets the script runtime. + /// + protected ScriptRuntime ScriptRuntime { get; private set; } + + private Timer m_ScriptSourceCheckingTimer; + + private static readonly int m_ScriptSourceCheckingInterval = 1000 * 60 * 5;// 5 minutes + + private ServerCommandState m_ServerCommandState; + + /// + /// Initializes a new instance of the class. + /// + public DynamicCommandLoaderBase() + : this(ScriptRuntime.CreateFromConfiguration()) + { + + } + + /// + /// Initializes a new instance of the class. + /// + /// The script runtime. + public DynamicCommandLoaderBase(ScriptRuntime scriptRuntime) + { + ScriptRuntime = scriptRuntime; + m_ScriptSourceCheckingTimer = new Timer(OnScriptSourceCheckingTimerCallback, null, m_ScriptSourceCheckingInterval, m_ScriptSourceCheckingInterval); + } + + /// + /// Gets the script sources. + /// + /// The root config. + /// The app server. + /// + protected abstract IEnumerable GetScriptSources(IRootConfig rootConfig, IAppServer appServer); + + private IEnumerable> GetUpdatedCommands(IEnumerable> updatedSources) + { + var updatedCommands = new List>(); + + foreach (var source in updatedSources) + { + if (source.UpdateAction == CommandUpdateAction.Remove) + { + updatedCommands.Add(new CommandUpdateInfo + { + Command = (ICommand)Activator.CreateInstance(m_MockupCommandType, source), + UpdateAction = source.UpdateAction + }); + } + + try + { + var command = (ICommand)Activator.CreateInstance(m_DynamicCommandType, ScriptRuntime, source); + + updatedCommands.Add(new CommandUpdateInfo + { + Command = command, + UpdateAction = source.UpdateAction + }); + } + catch (Exception e) + { + OnError(new Exception("Failed to load command source: " + source.Command.Tag + "!", e)); + continue; + } + } + + return updatedCommands; + } + + + private IAppServer m_AppServer; + + private IRootConfig m_RootConfig; + + private Type m_DynamicCommandType; + + private Type m_MockupCommandType; + + /// + /// Initializes with the specified app server. + /// + /// The type of the command. + /// The root config. + /// The app server. + /// + public override bool Initialize(IRootConfig rootConfig, IAppServer appServer) + { + m_RootConfig = rootConfig; + m_AppServer = appServer; + + var genericParameterTypes = typeof(TCommand).GetGenericArguments(); + m_DynamicCommandType = typeof(DynamicCommand<,>).MakeGenericType(genericParameterTypes); + m_MockupCommandType = typeof(MockupCommand<,>).MakeGenericType(genericParameterTypes); + return true; + } + + /// + /// Tries to load commands. + /// + /// The commands. + /// + public override bool TryLoadCommands(out IEnumerable commands) + { + var outputCommands = new List(); + + if (m_ServerCommandState != null) + { + OnError("This server's commands have been loaded already!"); + commands = outputCommands; + return false; + } + + var serverCommandState = new ServerCommandState + { + CommandUpdater = (o) => OnUpdated(GetUpdatedCommands(o)), + Sources = new List() + }; + + m_ServerCommandState = serverCommandState; + + var scriptSources = GetScriptSources(m_RootConfig, m_AppServer); + + foreach (var source in scriptSources) + { + ICommand command; + + try + { + command = (ICommand)Activator.CreateInstance(m_DynamicCommandType, ScriptRuntime, source); + serverCommandState.Sources.Add(source); + outputCommands.Add(command); + } + catch (Exception e) + { + OnError(new Exception("Failed to load command source: " + source.Tag + "!", e)); + } + } + + commands = outputCommands; + + return true; + } + + private void OnScriptSourceCheckingTimerCallback(object state) + { + m_ScriptSourceCheckingTimer.Change(Timeout.Infinite, Timeout.Infinite); + + try + { + var serverState = m_ServerCommandState; + + var commandSourceDict = serverState.Sources.ToDictionary(c => c.Tag, + c => new CommandFileEntity { Source = c }, + StringComparer.OrdinalIgnoreCase); + + var commandSources = GetScriptSources(m_RootConfig, m_AppServer); + + List> updatedSources = new List>(); + + foreach (var c in commandSources) + { + var lastUpdatedTime = c.LastUpdatedTime; + + CommandFileEntity commandEntity; + + if (commandSourceDict.TryGetValue(c.Tag, out commandEntity)) + { + commandEntity.Processed = true; + + if (commandEntity.Source.LastUpdatedTime != lastUpdatedTime) + { + //update command's last updated time in dictionary + commandEntity.Source = c; + + updatedSources.Add(new CommandUpdateInfo + { + UpdateAction = CommandUpdateAction.Update, + Command = c + }); + } + } + else + { + commandSourceDict.Add(c.Tag, new CommandFileEntity + { + Source = c, + Processed = true + }); + + updatedSources.Add(new CommandUpdateInfo + { + UpdateAction = CommandUpdateAction.Add, + Command = c + }); + } + } + + foreach (var cmd in commandSourceDict.Values.Where(e => !e.Processed)) + { + updatedSources.Add(new CommandUpdateInfo + { + UpdateAction = CommandUpdateAction.Remove, + Command = cmd.Source + }); + } + + if (updatedSources.Count > 0) + { + serverState.Sources = commandSourceDict.Values.Where(e => e.Processed).Select(e => e.Source).ToList(); + serverState.CommandUpdater(updatedSources); + } + } + catch (Exception e) + { + OnError(e); + } + finally + { + m_ScriptSourceCheckingTimer.Change(m_ScriptSourceCheckingInterval, m_ScriptSourceCheckingInterval); + } + } + } +} \ No newline at end of file diff --git a/Dlr/FileScriptSource.cs b/Dlr/FileScriptSource.cs new file mode 100644 index 000000000..ad065b4d5 --- /dev/null +++ b/Dlr/FileScriptSource.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.IO; + +namespace SuperSocket.Dlr +{ + class FileScriptSource : ScriptSourceBase + { + private string m_FilePath; + + public FileScriptSource(string filePath) + { + if (string.IsNullOrEmpty(filePath)) + throw new ArgumentNullException("filePath"); + + m_FilePath = filePath; + + Name = Path.GetFileNameWithoutExtension(filePath); + LanguageExtension = Path.GetExtension(filePath); + LastUpdatedTime = File.GetLastWriteTime(filePath); + } + + public override string GetScriptCode() + { + return File.ReadAllText(m_FilePath, Encoding.UTF8); + } + + public override string Tag + { + get { return m_FilePath; } + } + } +} diff --git a/Dlr/IScriptSource.cs b/Dlr/IScriptSource.cs new file mode 100644 index 000000000..967da2ecf --- /dev/null +++ b/Dlr/IScriptSource.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.Dlr +{ + /// + /// DynamicCommandSource interface + /// + public interface IScriptSource + { + /// + /// Gets the name matches with the command anme. + /// + string Name { get; } + + /// + /// Gets the language extension. + /// + string LanguageExtension { get; } + + /// + /// Gets the tag, a string can identify the script source. + /// + string Tag { get; } + /// + /// Gets the script code. + /// + /// + string GetScriptCode(); + + /// + /// Gets the last updated time. + /// + DateTime LastUpdatedTime { get; } + } +} diff --git a/Dlr/Properties/AssemblyInfo.cs b/Dlr/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..a326d4ba9 --- /dev/null +++ b/Dlr/Properties/AssemblyInfo.cs @@ -0,0 +1,9 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +[assembly: AssemblyTitle("SuperSocket.Dlr")] +[assembly: AssemblyDescription("SuperSocket.Dlr")] +[assembly: AssemblyConfiguration("")] +[assembly: ComVisible(false)] +[assembly: Guid("b80547cb-07f8-4873-8abb-aef72949aab2")] diff --git a/Dlr/ScriptSourceBase.cs b/Dlr/ScriptSourceBase.cs new file mode 100644 index 000000000..4fbae8fe8 --- /dev/null +++ b/Dlr/ScriptSourceBase.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.Dlr +{ + /// + /// ScriptSourceBase + /// + public abstract class ScriptSourceBase : IScriptSource + { + /// + /// Gets the name matches with the command anme. + /// + public string Name { get; protected set; } + + /// + /// Gets the language extension. + /// + public string LanguageExtension { get; protected set; } + + /// + /// Gets the tag. + /// + public abstract string Tag { get; } + + /// + /// Gets the script code. + /// + /// + public abstract string GetScriptCode(); + + /// + /// Gets the last updated time. + /// + public DateTime LastUpdatedTime { get; protected set; } + } +} diff --git a/Dlr/SuperSocket.Dlr.Net35.csproj b/Dlr/SuperSocket.Dlr.Net35.csproj new file mode 100644 index 000000000..3a5fda805 --- /dev/null +++ b/Dlr/SuperSocket.Dlr.Net35.csproj @@ -0,0 +1,88 @@ + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {55BAA051-CE62-4D4A-81B6-68B042CC78E9} + Library + Properties + SuperSocket.Dlr + SuperSocket.Dlr + v3.5 + 512 + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + true + bin\Debug\SuperSocket.Dlr.XML + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + true + bin\Release\SuperSocket.Dlr.XML + + + true + + + ..\supersocket.snk + + + + False + ..\Reference\DLR\Net35\Microsoft.Scripting.dll + + + False + ..\Reference\DLR\Net35\Microsoft.Scripting.Core.dll + + + + + + + + + GlobalAssemblyInfo.cs + + + + + + + + + + + + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A} + SuperSocket.Common.Net35 + + + {40B77789-EA11-4C05-8F52-86711D7BCAAF} + SuperSocket.SocketBase.Net35 + + + + + \ No newline at end of file diff --git a/Dlr/SuperSocket.Dlr.csproj b/Dlr/SuperSocket.Dlr.csproj new file mode 100644 index 000000000..3e452d4bb --- /dev/null +++ b/Dlr/SuperSocket.Dlr.csproj @@ -0,0 +1,84 @@ + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {55BAA051-CE62-4D4A-81B6-68B042CC78E9} + Library + Properties + SuperSocket.Dlr + SuperSocket.Dlr + v4.0 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + bin\Debug\SuperSocket.Dlr.XML + true + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + bin\Release\SuperSocket.Dlr.XML + true + + + true + + + ..\supersocket.snk + + + + False + ..\Reference\DLR\Net40\Microsoft.Scripting.dll + + + + + + + + + + GlobalAssemblyInfo.cs + + + + + + + + + + + + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A} + SuperSocket.Common + + + {40B77789-EA11-4C05-8F52-86711D7BCAAF} + SuperSocket.SocketBase + + + + + \ No newline at end of file diff --git a/Facility/PolicyServer/FlashPolicyServer.cs b/Facility/PolicyServer/FlashPolicyServer.cs new file mode 100644 index 000000000..da6e32385 --- /dev/null +++ b/Facility/PolicyServer/FlashPolicyServer.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.Facility.PolicyServer +{ + /// + /// Flash policy AppServer + /// + public class FlashPolicyServer : PolicyServer + { + /// + /// Initializes a new instance of the class. + /// + public FlashPolicyServer() + : base() + { + + } + + /// + /// Setups the policy response. + /// + /// The policy file data. + /// + protected override byte[] SetupPolicyResponse(byte[] policyFileData) + { + byte[] response = new byte[policyFileData.Length + 1]; + Array.Copy(policyFileData, 0, response, 0, policyFileData.Length); + response[policyFileData.Length] = 0x00; + return response; + } + } +} diff --git a/Facility/PolicyServer/PolicyRequestFilter.cs b/Facility/PolicyServer/PolicyRequestFilter.cs new file mode 100644 index 000000000..0d9e1c180 --- /dev/null +++ b/Facility/PolicyServer/PolicyRequestFilter.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Text; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.Facility.PolicyServer +{ + /// + /// PolicyRequestFilter + /// + class PolicyRequestFilter : FixedSizeRequestFilter + { + private const string m_DefaultRequestInfoKey = "REQU"; + + /// + /// Initializes a new instance of the class. + /// + /// The size. + public PolicyRequestFilter(int size) + : base(size) + { + + } + + /// + /// Filters the buffer after the server receive the enough size of data. + /// + /// The session. + /// The buffer. + /// The offset. + /// The length. + /// if set to true [to be copied]. + /// The left. + /// + protected override BinaryRequestInfo ProcessFixSizeRequest(IAppSession session, byte[] buffer, int offset, int length, bool toBeCopied, out int left) + { + left = length - this.Size; + byte[] data = new byte[this.Size]; + Buffer.BlockCopy(buffer, offset, data, 0, data.Length); + return new BinaryRequestInfo(m_DefaultRequestInfoKey, data); + } + } +} diff --git a/Facility/PolicyServer/PolicyRequestFilterFactory.cs b/Facility/PolicyServer/PolicyRequestFilterFactory.cs new file mode 100644 index 000000000..ba2b12e7d --- /dev/null +++ b/Facility/PolicyServer/PolicyRequestFilterFactory.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.Facility.PolicyServer +{ + class PolicyRequestFilterFactory : IRequestFilterFactory + { + /// + /// Gets the size of the fix request. + /// + /// + /// The size of the fix request. + /// + public int FixRequestSize { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// Size of the fix request. + public PolicyRequestFilterFactory(int fixRequestSize) + { + FixRequestSize = fixRequestSize; + } + + /// + /// Creates the filter. + /// + /// The app server. + /// The socket session. + /// + public IRequestFilter CreateFilter(SocketBase.IAppServer appServer, SocketBase.ISocketSession socketSession) + { + return new PolicyRequestFilter(FixRequestSize); + } + } +} diff --git a/Facility/PolicyServer/PolicyServer.cs b/Facility/PolicyServer/PolicyServer.cs new file mode 100644 index 000000000..6ccc9752f --- /dev/null +++ b/Facility/PolicyServer/PolicyServer.cs @@ -0,0 +1,127 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Config; +using SuperSocket.Common; +using System.Net; +using System.IO; +using System.Net.Sockets; +using System.Threading.Tasks; +using System.Threading; +using System.Collections.Concurrent; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.Facility.PolicyServer +{ + /// + /// PolicyServer base class + /// + public abstract class PolicyServer : AppServer + { + private string m_PolicyFile; + private string m_PolicyRequest = ""; + /// + /// Gets the policy response. + /// + protected byte[] PolicyResponse { get; private set; } + private int m_ExpectedReceivedLength; + + /// + /// Initializes a new instance of the class. + /// + public PolicyServer() + : base() + { + + } + + /// + /// Setups the specified root config. + /// + /// The root config. + /// The config. + /// + protected override bool Setup(IRootConfig rootConfig, IServerConfig config) + { + var policyRequest = config.Options.GetValue("policyRequest"); + if (!string.IsNullOrEmpty(policyRequest)) + m_PolicyRequest = policyRequest; + + m_ExpectedReceivedLength = Encoding.UTF8.GetByteCount(m_PolicyRequest); + + RequestFilterFactory = new PolicyRequestFilterFactory(m_ExpectedReceivedLength); + + m_PolicyFile = config.Options.GetValue("policyFile"); + + if (string.IsNullOrEmpty(m_PolicyFile)) + { + if(Logger.IsErrorEnabled) + Logger.Error("Configuration option policyFile is required!"); + return false; + } + + if (!Path.IsPathRooted(m_PolicyFile)) + m_PolicyFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, m_PolicyFile); + + if (!File.Exists(m_PolicyFile)) + { + if (Logger.IsErrorEnabled) + Logger.Error("The specified policyFile doesn't exist! " + m_PolicyFile); + return false; + } + + PolicyResponse = SetupPolicyResponse(File.ReadAllBytes(m_PolicyFile)); + + this.RequestHandler += new RequestHandler(PolicyServer_RequestHandler); + + return true; + } + + /// + /// Setups the policy response. + /// + /// The policy file data. + /// + protected virtual byte[] SetupPolicyResponse(byte[] policyFileData) + { + return policyFileData; + } + + /// + /// Gets the policy file response. + /// + /// The client end point. + /// + protected virtual byte[] GetPolicyFileResponse(IPEndPoint clientEndPoint) + { + return PolicyResponse; + } + + void PolicyServer_RequestHandler(PolicySession session, BinaryRequestInfo requestInfo) + { + ProcessRequest(session, requestInfo.Data); + } + + /// + /// Processes the request. + /// + /// The session. + /// The data. + protected virtual void ProcessRequest(PolicySession session, byte[] data) + { + var request = Encoding.UTF8.GetString(data); + + if (string.Compare(request, m_PolicyRequest, StringComparison.InvariantCultureIgnoreCase) != 0) + { + session.Close(); + return; + } + + var response = GetPolicyFileResponse(session.RemoteEndPoint); + session.Send(response, 0, response.Length); + } + } +} diff --git a/Facility/PolicyServer/PolicySession.cs b/Facility/PolicyServer/PolicySession.cs new file mode 100644 index 000000000..e291b2543 --- /dev/null +++ b/Facility/PolicyServer/PolicySession.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Sockets; +using System.Text; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.Facility.PolicyServer +{ + /// + /// PolicySession + /// + public class PolicySession : AppSession + { + + } +} diff --git a/Facility/PolicyServer/SilverlightPolicyServer.cs b/Facility/PolicyServer/SilverlightPolicyServer.cs new file mode 100644 index 000000000..f80c14a4b --- /dev/null +++ b/Facility/PolicyServer/SilverlightPolicyServer.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.Facility.PolicyServer +{ + /// + /// Silverlight policy AppServer + /// + public class SilverlightPolicyServer : PolicyServer + { + /// + /// Initializes a new instance of the class. + /// + public SilverlightPolicyServer() + : base() + { + + } + + /// + /// Processes the request. + /// + /// The session. + /// The data. + protected override void ProcessRequest(PolicySession session, byte[] data) + { + base.ProcessRequest(session, data); + session.Close(); + } + } +} diff --git a/Facility/Properties/AssemblyInfo.cs b/Facility/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..da013c898 --- /dev/null +++ b/Facility/Properties/AssemblyInfo.cs @@ -0,0 +1,9 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +[assembly: AssemblyTitle("SuperSocket.Facility")] +[assembly: AssemblyDescription("SuperSocket.Facility")] +[assembly: AssemblyConfiguration("")] +[assembly: ComVisible(false)] +[assembly: Guid("341d2163-09a9-4f60-813f-366405715898")] diff --git a/Facility/SuperSocket.Facility.Net35.csproj b/Facility/SuperSocket.Facility.Net35.csproj new file mode 100644 index 000000000..c808d9cbb --- /dev/null +++ b/Facility/SuperSocket.Facility.Net35.csproj @@ -0,0 +1,84 @@ + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {01987BAC-C498-44DD-B274-62EA2506B51D} + Library + Properties + SuperSocket.Facility + SuperSocket.Facility + v3.5 + 512 + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + true + bin\Debug\SuperSocket.Facility.XML + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + true + bin\Release\SuperSocket.Facility.XML + + + true + + + ..\supersocket.snk + + + + + + + ..\Reference\System.Threading.dll + + + + + + + GlobalAssemblyInfo.cs + + + + + + + + + + + + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A} + SuperSocket.Common.Net35 + + + {40B77789-EA11-4C05-8F52-86711D7BCAAF} + SuperSocket.SocketBase.Net35 + + + + + \ No newline at end of file diff --git a/Facility/SuperSocket.Facility.csproj b/Facility/SuperSocket.Facility.csproj new file mode 100644 index 000000000..e742e9db3 --- /dev/null +++ b/Facility/SuperSocket.Facility.csproj @@ -0,0 +1,81 @@ + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {01987BAC-C498-44DD-B274-62EA2506B51D} + Library + Properties + SuperSocket.Facility + SuperSocket.Facility + v4.0 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + bin\Debug\SuperSocket.Facility.XML + true + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + true + bin\Release\SuperSocket.Facility.XML + + + true + + + ..\supersocket.snk + + + + + + + + + + + GlobalAssemblyInfo.cs + + + + + + + + + + + + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A} + SuperSocket.Common + + + {40B77789-EA11-4C05-8F52-86711D7BCAAF} + SuperSocket.SocketBase + + + + + + \ No newline at end of file diff --git a/LICENSE.TXT b/LICENSE.TXT new file mode 100644 index 000000000..c4ef15800 --- /dev/null +++ b/LICENSE.TXT @@ -0,0 +1,69 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. + +Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. + +Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. + +You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + +1. You must give any other recipients of the Work or Derivative Works a copy of this License; and + +2. You must cause any modified files to carry prominent notices stating that You changed the files; and + +3. You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + +4. If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. + +You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. + +Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. + +This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. + +Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. + +In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. + +While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. \ No newline at end of file diff --git a/QuickStart/BroadcastService/BroadcastServer.cs b/QuickStart/BroadcastService/BroadcastServer.cs new file mode 100644 index 000000000..fccebe0b8 --- /dev/null +++ b/QuickStart/BroadcastService/BroadcastServer.cs @@ -0,0 +1,92 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using SuperSocket.Common; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Command; + +namespace SuperSocket.QuickStart.BroadcastService +{ + public class BroadcastServer : AppServer + { + private Dictionary> broadcastDict = new Dictionary>(StringComparer.OrdinalIgnoreCase); + private object broadcastSyncRoot = new object(); + + private Dictionary broadcastSessionDict = new Dictionary(StringComparer.OrdinalIgnoreCase); + private object syncRoot = new object(); + + public BroadcastServer() + { + lock (broadcastSyncRoot) + { + //It means that device V001 will receive broadcast messages from C001 and C002, + //device V002 will receive broadcast messages from C002 and C003 + broadcastDict["C001"] = new List { "V001" }; + broadcastDict["C002"] = new List { "V001", "V002" }; + broadcastDict["C003"] = new List { "V002" }; + } + } + + internal void RegisterNewSession(BroadcastSession session) + { + if (string.IsNullOrEmpty(session.DeviceNumber)) + return; + + lock (syncRoot) + { + broadcastSessionDict[session.DeviceNumber] = session; + } + } + + internal void RemoveOnlineSession(BroadcastSession session) + { + if (string.IsNullOrEmpty(session.DeviceNumber)) + return; + + lock (syncRoot) + { + broadcastSessionDict.Remove(session.DeviceNumber); + } + } + + internal void BroadcastMessage(BroadcastSession session, string message) + { + List targetDeviceNumbers; + + lock (broadcastSyncRoot) + { + if(!broadcastDict.TryGetValue(session.DeviceNumber, out targetDeviceNumbers)) + return; + } + + if (targetDeviceNumbers == null || targetDeviceNumbers.Count <= 0) + return; + + List sessions = new List(); + + lock (syncRoot) + { + BroadcastSession s; + + foreach(var key in targetDeviceNumbers) + { + if (broadcastSessionDict.TryGetValue(key, out s)) + sessions.Add(s); + } + } + + this.AsyncRun(() => + { + sessions.ForEach(s => s.Send(message)); + }); + } + + protected override void OnSessionClosed(BroadcastSession session, CloseReason reason) + { + RemoveOnlineSession(session); + base.OnSessionClosed(session, reason); + } + } +} diff --git a/QuickStart/BroadcastService/BroadcastService.csproj b/QuickStart/BroadcastService/BroadcastService.csproj new file mode 100644 index 000000000..c046b5b3b --- /dev/null +++ b/QuickStart/BroadcastService/BroadcastService.csproj @@ -0,0 +1,121 @@ + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {083155D6-A0A2-4703-AC43-7C6496A9B607} + Library + Properties + SuperSocket.QuickStart.BroadcastService + SuperSocket.QuickStart.BroadcastService + v4.0 + 512 + + + 3.5 + + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + AllRules.ruleset + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + AllRules.ruleset + + + + + + 3.5 + + + 3.5 + + + 3.5 + + + + + + + + + + + + + + PreserveNewest + + + + + False + .NET Framework 3.5 SP1 Client Profile + false + + + False + .NET Framework 3.5 SP1 + true + + + False + Windows Installer 3.1 + true + + + + + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A} + SuperSocket.Common + + + {40B77789-EA11-4C05-8F52-86711D7BCAAF} + SuperSocket.SocketBase + + + {B9113694-7226-4152-938D-3172B11571A1} + SuperSocket.SocketService + + + + + \ No newline at end of file diff --git a/QuickStart/BroadcastService/BroadcastSession.cs b/QuickStart/BroadcastService/BroadcastSession.cs new file mode 100644 index 000000000..f4fbc7270 --- /dev/null +++ b/QuickStart/BroadcastService/BroadcastSession.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase; + +namespace SuperSocket.QuickStart.BroadcastService +{ + public class BroadcastSession : AppSession + { + public string DeviceNumber { get; set; } + + public new BroadcastServer AppServer + { + get { return (BroadcastServer)base.AppServer; } + } + + public override void HandleException(Exception e) + { + + } + } +} diff --git a/QuickStart/BroadcastService/Command/BROA.cs b/QuickStart/BroadcastService/Command/BROA.cs new file mode 100644 index 000000000..16425c273 --- /dev/null +++ b/QuickStart/BroadcastService/Command/BROA.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.QuickStart.BroadcastService.Command +{ + public class BROA : StringCommandBase + { + public override void ExecuteCommand(BroadcastSession session, StringRequestInfo commandData) + { + string message = commandData.Data; + session.AppServer.BroadcastMessage(session, message); + session.Send("101 message broadcasted"); + } + } +} diff --git a/QuickStart/BroadcastService/Command/CONN.cs b/QuickStart/BroadcastService/Command/CONN.cs new file mode 100644 index 000000000..60214eb64 --- /dev/null +++ b/QuickStart/BroadcastService/Command/CONN.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.QuickStart.BroadcastService.Command +{ + public class CONN : StringCommandBase + { + public override void ExecuteCommand(BroadcastSession session, StringRequestInfo commandData) + { + session.DeviceNumber = commandData[0]; + session.AppServer.RegisterNewSession(session); + session.Send("100 Connected"); + } + } +} diff --git a/QuickStart/BroadcastService/Properties/AssemblyInfo.cs b/QuickStart/BroadcastService/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..6f1573356 --- /dev/null +++ b/QuickStart/BroadcastService/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +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("BroadcastService")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("BroadcastService")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2010")] +[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)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("3fa3ae47-b237-4149-bed5-a6217aba3a55")] + +// 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")] diff --git a/QuickStart/BroadcastService/SuperSocket.SocketService.exe.config b/QuickStart/BroadcastService/SuperSocket.SocketService.exe.config new file mode 100644 index 000000000..720382959 --- /dev/null +++ b/QuickStart/BroadcastService/SuperSocket.SocketService.exe.config @@ -0,0 +1,24 @@ + + + +
+ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/QuickStart/CommandFilter/CommandFilter.csproj b/QuickStart/CommandFilter/CommandFilter.csproj new file mode 100644 index 000000000..a1b19f08e --- /dev/null +++ b/QuickStart/CommandFilter/CommandFilter.csproj @@ -0,0 +1,68 @@ + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {595A2664-BBC7-41CF-AA19-E34DEA3DBE6E} + Library + Properties + SuperSocket.QuickStart.CommandFilter + SuperSocket.QuickStart.CommandFilter + v4.0 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A} + SuperSocket.Common + + + {40B77789-EA11-4C05-8F52-86711D7BCAAF} + SuperSocket.SocketBase + + + + + \ No newline at end of file diff --git a/QuickStart/CommandFilter/CountCommandFilter.cs b/QuickStart/CommandFilter/CountCommandFilter.cs new file mode 100644 index 000000000..b72a213c1 --- /dev/null +++ b/QuickStart/CommandFilter/CountCommandFilter.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Command; +using System.Threading; + +namespace SuperSocket.QuickStart.CommandFilter +{ + public class CountCommandFilter : CommandFilterAttribute + { + private long m_Total = 0; + + public override void OnCommandExecuting(IAppSession session, ICommand command) + { + + } + + public override void OnCommandExecuted(IAppSession session, ICommand command) + { + Interlocked.Increment(ref m_Total); + } + + public long Total + { + get { return m_Total; } + } + } +} diff --git a/QuickStart/CommandFilter/LogTimeCommandFilter.cs b/QuickStart/CommandFilter/LogTimeCommandFilter.cs new file mode 100644 index 000000000..0bc072108 --- /dev/null +++ b/QuickStart/CommandFilter/LogTimeCommandFilter.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.Common; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Command; + +namespace SuperSocket.QuickStart.CommandFilter +{ + public class LogTimeCommandFilter : CommandFilterAttribute + { + public override void OnCommandExecuting(IAppSession session, ICommand command) + { + session.Items["StartTime"] = DateTime.Now; + } + + public override void OnCommandExecuted(IAppSession session, ICommand command) + { + var startTime = session.Items.GetValue("StartTime"); + var ts = DateTime.Now.Subtract(startTime); + + if (ts.TotalSeconds > 5 && session.Logger.IsInfoEnabled) + { + session.Logger.InfoFormat("A command '{0}' took {1} seconds!", command.Name, ts.ToString()); + } + } + } +} diff --git a/QuickStart/CommandFilter/MyAppServer.cs b/QuickStart/CommandFilter/MyAppServer.cs new file mode 100644 index 000000000..e21e3330d --- /dev/null +++ b/QuickStart/CommandFilter/MyAppServer.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase; + +namespace SuperSocket.QuickStart.CommandFilter +{ + [CountCommandFilter]//Global command filter + public class MyAppServer : AppServer + { + + } +} diff --git a/QuickStart/CommandFilter/Properties/AssemblyInfo.cs b/QuickStart/CommandFilter/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..702ca36ab --- /dev/null +++ b/QuickStart/CommandFilter/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +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("CommandFilter")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("CommandFilter")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2011")] +[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)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("a1d43531-f819-483a-bf44-097a76f2f622")] + +// 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")] diff --git a/QuickStart/CommandFilter/QUERY.cs b/QuickStart/CommandFilter/QUERY.cs new file mode 100644 index 000000000..5e856850f --- /dev/null +++ b/QuickStart/CommandFilter/QUERY.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.QuickStart.CommandFilter +{ + [LogTimeCommandFilter] + public class QUERY : StringCommandBase + { + public override void ExecuteCommand(AppSession session, StringRequestInfo commandData) + { + //Your code + } + } +} diff --git a/QuickStart/ConnectionFilter/ConnectionFilter.csproj b/QuickStart/ConnectionFilter/ConnectionFilter.csproj new file mode 100644 index 000000000..df7207099 --- /dev/null +++ b/QuickStart/ConnectionFilter/ConnectionFilter.csproj @@ -0,0 +1,71 @@ + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {E286C017-49DB-4EA9-A6BC-EC6ADB51E0A8} + Library + Properties + SuperSocket.QuickStart.ConnectionFilter + SuperSocket.QuickStart.ConnectionFilter + v4.0 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A} + SuperSocket.Common + + + {40B77789-EA11-4C05-8F52-86711D7BCAAF} + SuperSocket.SocketBase + + + + + Designer + PreserveNewest + + + + + \ No newline at end of file diff --git a/QuickStart/ConnectionFilter/IPConnectionFilter.cs b/QuickStart/ConnectionFilter/IPConnectionFilter.cs new file mode 100644 index 000000000..87e21dd20 --- /dev/null +++ b/QuickStart/ConnectionFilter/IPConnectionFilter.cs @@ -0,0 +1,91 @@ +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Linq; +using System.Net; +using System.Text; +using SuperSocket.Common; +using SuperSocket.SocketBase; + +namespace SuperSocket.QuickStart.ConnectionFilter +{ + public class IPConnectionFilter : IConnectionFilter + { + private Tuple[] m_IpRanges; + + public bool Initialize(string name, IAppServer appServer) + { + Name = name; + + var ipRange = appServer.Config.Options.GetValue("ipRange"); + + string[] ipRangeArray; + + if (string.IsNullOrEmpty(ipRange) + || (ipRangeArray = ipRange.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries)).Length <= 0) + { + throw new ArgumentException("The ipRange doesn't exist in configuration!"); + } + + m_IpRanges = new Tuple[ipRangeArray.Length]; + + for (int i = 0; i < ipRangeArray.Length; i++) + { + var range = ipRangeArray[i]; + m_IpRanges[i] = GenerateIpRange(range); + } + + return true; + } + + private Tuple GenerateIpRange(string range) + { + var ipArray = range.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries); + + if(ipArray.Length != 2) + throw new ArgumentException("Invalid ipRange exist in configuration!"); + + return new Tuple(ConvertIpToLong(ipArray[0]), ConvertIpToLong(ipArray[1])); + } + + private long ConvertIpToLong(string ip) + { + var points = ip.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries); + + if(points.Length != 4) + throw new ArgumentException("Invalid ipRange exist in configuration!"); + + long value = 0; + long unit = 1; + + for (int i = points.Length - 1; i >= 0; i--) + { + value += unit * points[i].ToInt32(); + unit *= 256; + } + + return value; + } + + public string Name { get; private set; } + + public bool AllowConnect(IPEndPoint remoteAddress) + { + var ip = remoteAddress.Address.ToString(); + var ipValue = ConvertIpToLong(ip); + + for (var i = 0; i < m_IpRanges.Length; i++) + { + var range = m_IpRanges[i]; + + if (ipValue > range.Item2) + return false; + + if (ipValue < range.Item1) + return false; + } + + return true; + } + } +} diff --git a/QuickStart/ConnectionFilter/Properties/AssemblyInfo.cs b/QuickStart/ConnectionFilter/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..626c52c2c --- /dev/null +++ b/QuickStart/ConnectionFilter/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +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("ConnectionFilter")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("ConnectionFilter")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2011")] +[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)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("863aee11-8801-40a0-9e27-968725968032")] + +// 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")] diff --git a/QuickStart/ConnectionFilter/SuperSocket.SocketService.exe.config b/QuickStart/ConnectionFilter/SuperSocket.SocketService.exe.config new file mode 100644 index 000000000..8f60f0ff4 --- /dev/null +++ b/QuickStart/ConnectionFilter/SuperSocket.SocketService.exe.config @@ -0,0 +1,28 @@ + + + +
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/QuickStart/CustomProtocol/Command/ECHO.cs b/QuickStart/CustomProtocol/Command/ECHO.cs new file mode 100644 index 000000000..38e94dd1d --- /dev/null +++ b/QuickStart/CustomProtocol/Command/ECHO.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.QuickStart.CustomProtocol.Command +{ + public class ECHO : CommandBase + { + public override void ExecuteCommand(CustomProtocolSession session, BinaryRequestInfo commandInfo) + { + session.Send(Encoding.ASCII.GetString(commandInfo.Data) + Environment.NewLine); + } + } +} diff --git a/QuickStart/CustomProtocol/CustomProtocol.csproj b/QuickStart/CustomProtocol/CustomProtocol.csproj new file mode 100644 index 000000000..4c0b3b6cf --- /dev/null +++ b/QuickStart/CustomProtocol/CustomProtocol.csproj @@ -0,0 +1,87 @@ + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {FB261628-26FD-48B5-9D3D-C9E34B4728CF} + Library + Properties + SuperSocket.QuickStart.CustomProtocol + SuperSocket.QuickStart.CustomProtocol + v4.0 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\..\Reference\nunit.framework.dll + + + + + + + + + + + + + + + + + + + + + + Designer + PreserveNewest + + + + + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A} + SuperSocket.Common + + + {40B77789-EA11-4C05-8F52-86711D7BCAAF} + SuperSocket.SocketBase + + + {153FEF72-191C-43D9-BE71-2B351C7AC760} + SuperSocket.SocketEngine + + + {B9113694-7226-4152-938D-3172B11571A1} + SuperSocket.SocketService + + + + + \ No newline at end of file diff --git a/QuickStart/CustomProtocol/CustomProtocolServer.cs b/QuickStart/CustomProtocol/CustomProtocolServer.cs new file mode 100644 index 000000000..a4dd7eefe --- /dev/null +++ b/QuickStart/CustomProtocol/CustomProtocolServer.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.QuickStart.CustomProtocol +{ + /// + /// It's a protocol like that: + /// +-------+---+-------------------------------+ + /// |request| l | | + /// | name | e | request data | + /// | (4) | n | | + /// | |(2)| | + /// +-------+---+-------------------------------+ + /// request name: the name of the request, 4 chars, used for matching the processing command + /// len: the lenght of request data, two bytes, 0x00 0x02 = 2, 0x01 0x01 = 257 + /// request data: the body of the request + /// + class CustomProtocolServer : AppServer + { + public CustomProtocolServer() + : base(new DefaultRequestFilterFactory()) + { + + } + } +} diff --git a/QuickStart/CustomProtocol/CustomProtocolServerTest.cs b/QuickStart/CustomProtocol/CustomProtocolServerTest.cs new file mode 100644 index 000000000..97b7b7c80 --- /dev/null +++ b/QuickStart/CustomProtocol/CustomProtocolServerTest.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text; +using NUnit.Framework; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Config; +using SuperSocket.SocketBase.Logging; +using SuperSocket.SocketEngine; + +namespace SuperSocket.QuickStart.CustomProtocol +{ + [TestFixture] + public class CustomProtocolServerTest + { + + private CustomProtocolServer m_Server; + private IServerConfig m_Config; + + [TestFixtureSetUp] + public void Setup() + { + m_Config = new ServerConfig + { + Port = 911, + Ip = "Any", + MaxConnectionNumber = 1000, + Mode = SocketMode.Tcp, + Name = "CustomProtocolServer" + }; + + m_Server = new CustomProtocolServer(); + m_Server.Setup(new RootConfig(), m_Config, SocketServerFactory.Instance, logFactory: new ConsoleLogFactory()); + } + + [SetUp] + public void StartServer() + { + m_Server.Start(); + } + + [TearDown] + public void StopServer() + { + m_Server.Stop(); + } + + [Test] + public void TestCustomProtocol() + { + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port); + + using (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) + { + socket.Connect(serverAddress); + + var socketStream = new NetworkStream(socket); + var reader = new StreamReader(socketStream, Encoding.ASCII, false); + + string charSource = Guid.NewGuid().ToString().Replace("-", string.Empty) + + Guid.NewGuid().ToString().Replace("-", string.Empty) + + Guid.NewGuid().ToString().Replace("-", string.Empty); + + Random rd = new Random(); + + for (int i = 0; i < 10; i++) + { + int startPos = rd.Next(0, charSource.Length - 2); + int endPos = rd.Next(startPos + 1, charSource.Length - 1); + + var currentMessage = charSource.Substring(startPos, endPos - startPos + 1); + + byte[] data = Encoding.ASCII.GetBytes("ECHO"); + socketStream.Write(data, 0, data.Length); + data = Encoding.ASCII.GetBytes(currentMessage); + socketStream.Write(new byte[] { (byte)(data.Length / 256), (byte)(data.Length % 256) }, 0, 2); + socketStream.Write(data, 0, data.Length); + socketStream.Flush(); + + var line = reader.ReadLine(); + Console.WriteLine("Received: " + line); + Assert.AreEqual(currentMessage, line); + } + } + } + } +} diff --git a/QuickStart/CustomProtocol/CustomProtocolSession.cs b/QuickStart/CustomProtocol/CustomProtocolSession.cs new file mode 100644 index 000000000..662101bfd --- /dev/null +++ b/QuickStart/CustomProtocol/CustomProtocolSession.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.QuickStart.CustomProtocol +{ + public class CustomProtocolSession : AppSession + { + public override void HandleException(Exception e) + { + + } + } +} diff --git a/QuickStart/CustomProtocol/MyCustomProtocol.cs b/QuickStart/CustomProtocol/MyCustomProtocol.cs new file mode 100644 index 000000000..7edbece07 --- /dev/null +++ b/QuickStart/CustomProtocol/MyCustomProtocol.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.QuickStart.CustomProtocol +{ + + /// + /// It's a protocol like that + /// "SEND 0008 xg^89W(v" + /// "SEND" is command name, which is 4 chars + /// "0008" is command data length, which also is 4 chars + /// "xg^89W(v" is the command data whose lenght is 8 + /// + class MyCustomProtocol : ICustomProtocol + { + #region ICustomProtocol Members + + public ICommandReader CreateCommandReader(IAppServer appServer) + { + return new MyCommandReader(appServer); + } + + #endregion + } +} diff --git a/QuickStart/CustomProtocol/MyDataRequestFilter.cs b/QuickStart/CustomProtocol/MyDataRequestFilter.cs new file mode 100644 index 000000000..103a379d5 --- /dev/null +++ b/QuickStart/CustomProtocol/MyDataRequestFilter.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.QuickStart.CustomProtocol +{ + class MyDataRequestFilter : RequestFilterBase + { + private int m_Length; + + private string m_CommandName; + + internal void Initialize(string commandName, int length, RequestFilterBase previousCommandReader) + { + m_Length = length; + m_CommandName = commandName; + + base.Initialize(previousCommandReader); + } + + public override BinaryRequestInfo Filter(IAppSession session, byte[] readBuffer, int offset, int length, bool toBeCopied, out int left) + { + left = 0; + + int leftLength = m_Length - BufferSegments.Count; + + AddArraySegment(readBuffer, offset, length, toBeCopied); + + if (length >= leftLength) + { + NextRequestFilter = new MyRequestFilter(); + var requestInfo = new BinaryRequestInfo(m_CommandName, BufferSegments.ToArrayData(0, m_Length)); + + if (length > leftLength) + left = length - leftLength; + + return requestInfo; + } + else + { + NextRequestFilter = this; + return null; + } + } + } +} diff --git a/QuickStart/CustomProtocol/MyRequestFilter.cs b/QuickStart/CustomProtocol/MyRequestFilter.cs new file mode 100644 index 000000000..f972487d0 --- /dev/null +++ b/QuickStart/CustomProtocol/MyRequestFilter.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.Common; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.QuickStart.CustomProtocol +{ + class MyRequestFilter : RequestFilterBase + { + private readonly MyDataRequestFilter m_PreparedDataReader = new MyDataRequestFilter(); + + private MyDataRequestFilter GetMyCommandDataReader(string commandName, int dataLength) + { + m_PreparedDataReader.Initialize(commandName, dataLength, this); + return m_PreparedDataReader; + } + + public override BinaryRequestInfo Filter(IAppSession session, byte[] readBuffer, int offset, int length, bool toBeCopied, out int left) + { + left = 0; + + int leftLength = 6 - this.BufferSegments.Count; + + if (length < leftLength) + { + AddArraySegment(readBuffer, offset, length, toBeCopied); + NextRequestFilter = this; + return null; + } + + AddArraySegment(readBuffer, offset, leftLength, toBeCopied); + + string commandName = BufferSegments.Decode(Encoding.ASCII, 0, 4); + + int commandDataLength = (int)BufferSegments[4] * 256 + (int)BufferSegments[5]; + + if (length > leftLength) + { + int leftDataLength = length - leftLength; + if (leftDataLength >= commandDataLength) + { + byte[] commandData = readBuffer.CloneRange(offset + leftLength, commandDataLength); + BufferSegments.ClearSegements(); + NextRequestFilter = this; + var requestInfo = new BinaryRequestInfo(commandName, commandData); + + //The next requestInfo is comming + if (leftDataLength > commandDataLength) + left = leftDataLength - commandDataLength; + + return requestInfo; + } + else// if (leftDataLength < commandDataLength) + { + //Clear previous cached header data + BufferSegments.ClearSegements(); + //Save left data part + AddArraySegment(readBuffer, offset + leftLength, length - leftLength, toBeCopied); + NextRequestFilter = GetMyCommandDataReader(commandName, commandDataLength); + return null; + } + } + else + { + NextRequestFilter = GetMyCommandDataReader(commandName, commandDataLength); + return null; + } + } + } +} diff --git a/QuickStart/CustomProtocol/Properties/AssemblyInfo.cs b/QuickStart/CustomProtocol/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..0964a09de --- /dev/null +++ b/QuickStart/CustomProtocol/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +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("CutomProtocol")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("CutomProtocol")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2011")] +[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)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("e7a4c30b-1f56-4bef-8037-ae4f558cb9cb")] + +// 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")] diff --git a/QuickStart/CustomProtocol/SuperSocket.SocketService.exe.config b/QuickStart/CustomProtocol/SuperSocket.SocketService.exe.config new file mode 100644 index 000000000..f40e2a616 --- /dev/null +++ b/QuickStart/CustomProtocol/SuperSocket.SocketService.exe.config @@ -0,0 +1,23 @@ + + + +
+ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/QuickStart/CustomRequestInfoParser/Command/ECHO.cs b/QuickStart/CustomRequestInfoParser/Command/ECHO.cs new file mode 100644 index 000000000..8eae99c96 --- /dev/null +++ b/QuickStart/CustomRequestInfoParser/Command/ECHO.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.QuickStart.CustomCommandParser.Command +{ + public class ECHO : StringCommandBase + { + public override void ExecuteCommand(YourSession session, StringRequestInfo commandData) + { + foreach (var p in commandData.Parameters) + { + session.Send(p); + } + } + } +} diff --git a/QuickStart/CustomRequestInfoParser/CustomRequestInfoParser.cs b/QuickStart/CustomRequestInfoParser/CustomRequestInfoParser.cs new file mode 100644 index 000000000..2d30a1ccd --- /dev/null +++ b/QuickStart/CustomRequestInfoParser/CustomRequestInfoParser.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.QuickStart.CustomCommandParser +{ + /// + /// CMD:ECHO AabSfght5656D5Cfa5== + /// + public class CustomRequestInfoParser : IRequestInfoParser + { + #region ICommandParser Members + + public StringRequestInfo ParseRequestInfo(string source) + { + if(!source.StartsWith("CMD:")) + return null; + + source = source.Substring(4); + string[] data = source.Split(' '); + return new StringRequestInfo(data[0], data[1], + Encoding.ASCII.GetString(Convert.FromBase64String(data[1])).Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)); + } + + #endregion + } +} diff --git a/QuickStart/CustomRequestInfoParser/CustomRequestInfoParser.csproj b/QuickStart/CustomRequestInfoParser/CustomRequestInfoParser.csproj new file mode 100644 index 000000000..ba4a10b96 --- /dev/null +++ b/QuickStart/CustomRequestInfoParser/CustomRequestInfoParser.csproj @@ -0,0 +1,131 @@ + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {18457034-1FC3-4464-AA10-23B58EB1B0D5} + Library + Properties + SuperSocket.QuickStart.CustomCommandParser + SuperSocket.QuickStart.CustomCommandParser + v4.0 + 512 + + + 3.5 + + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + AllRules.ruleset + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + AllRules.ruleset + + + + False + ..\..\Reference\nunit.framework.dll + + + + + 3.5 + + + 3.5 + + + 3.5 + + + + + + + + + + + + + + + PreserveNewest + Designer + + + + + False + .NET Framework 3.5 SP1 Client Profile + false + + + False + .NET Framework 3.5 SP1 + true + + + False + Windows Installer 3.1 + true + + + + + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A} + SuperSocket.Common + + + {40B77789-EA11-4C05-8F52-86711D7BCAAF} + SuperSocket.SocketBase + + + {153FEF72-191C-43D9-BE71-2B351C7AC760} + SuperSocket.SocketEngine + + + {B9113694-7226-4152-938D-3172B11571A1} + SuperSocket.SocketService + + + + + \ No newline at end of file diff --git a/QuickStart/CustomRequestInfoParser/Properties/AssemblyInfo.cs b/QuickStart/CustomRequestInfoParser/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..c1e51cfdf --- /dev/null +++ b/QuickStart/CustomRequestInfoParser/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +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("CustomCommandParser")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("CustomCommandParser")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2010")] +[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)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("b8110b37-4ed7-4cd3-aa7f-2d834161c783")] + +// 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")] diff --git a/QuickStart/CustomRequestInfoParser/SuperSocket.SocketService.exe.config b/QuickStart/CustomRequestInfoParser/SuperSocket.SocketService.exe.config new file mode 100644 index 000000000..7d9137e15 --- /dev/null +++ b/QuickStart/CustomRequestInfoParser/SuperSocket.SocketService.exe.config @@ -0,0 +1,24 @@ + + + +
+ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/QuickStart/CustomRequestInfoParser/TestSocketServer.cs b/QuickStart/CustomRequestInfoParser/TestSocketServer.cs new file mode 100644 index 000000000..d7959d00a --- /dev/null +++ b/QuickStart/CustomRequestInfoParser/TestSocketServer.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text; +using NUnit.Framework; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Config; +using SuperSocket.SocketBase.Logging; +using SuperSocket.SocketEngine; + +namespace SuperSocket.QuickStart.CustomCommandParser +{ + [TestFixture] + public class TestSocketServer + { + [Test] + public void TestECHO() + { + IServerConfig config = new ServerConfig + { + Name = "My Custom Server", + Ip = "Any", + Port = 100, + Mode = SocketMode.Tcp, + MaxConnectionNumber = 1 + }; + + var rootConfig = new RootConfig(); + + YourServer server = new YourServer(); + server.Setup(rootConfig, config, SocketServerFactory.Instance, logFactory: new ConsoleLogFactory()); + + server.Start(); + + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), config.Port); + + using (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) + { + socket.Connect(serverAddress); + Stream socketStream = new NetworkStream(socket); + using (StreamReader reader = new StreamReader(socketStream, Encoding.Default, true)) + using (StreamWriter writer = new StreamWriter(socketStream, Encoding.Default, 1024 * 8)) + { + //ignore welcome message + reader.ReadLine(); + + string command = "CMD:ECHO "; + string[] parameters = new string[] { "Kerry", "Jiang", "China", "Shanghai" }; + string parameter = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Join(" ", parameters))); + writer.WriteLine(command + parameter); + writer.Flush(); + + foreach (var p in parameters) + { + string param = reader.ReadLine(); + Console.WriteLine(param); + Assert.AreEqual(p, param); + } + } + } + + server.Stop(); + } + } +} diff --git a/QuickStart/CustomRequestInfoParser/YourServer.cs b/QuickStart/CustomRequestInfoParser/YourServer.cs new file mode 100644 index 000000000..9fc09e1a3 --- /dev/null +++ b/QuickStart/CustomRequestInfoParser/YourServer.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.QuickStart.CustomCommandParser +{ + public class YourServer : AppServer + { + public YourServer() + : base(new CommandLineRequestFilterFactory(Encoding.Default, new CustomRequestInfoParser())) + { + + } + } +} diff --git a/QuickStart/CustomRequestInfoParser/YourSession.cs b/QuickStart/CustomRequestInfoParser/YourSession.cs new file mode 100644 index 000000000..490fbe1f0 --- /dev/null +++ b/QuickStart/CustomRequestInfoParser/YourSession.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase; + +namespace SuperSocket.QuickStart.CustomCommandParser +{ + public class YourSession : AppSession + { + protected override void OnSessionStarted() + { + Send("Welcome"); + } + + public override void HandleException(Exception e) + { + + } + } +} diff --git a/QuickStart/EchoService/Command/ECHO.cs b/QuickStart/EchoService/Command/ECHO.cs new file mode 100644 index 000000000..04aff2b12 --- /dev/null +++ b/QuickStart/EchoService/Command/ECHO.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.QuickStart.EchoService.Command +{ + public class ECHO : StringCommandBase + { + #region CommandBase Members + + public override void ExecuteCommand(EchoSession session, StringRequestInfo requestInfo) + { + session.Send(requestInfo.Data); + } + + #endregion + } +} diff --git a/QuickStart/EchoService/EchoServer.cs b/QuickStart/EchoService/EchoServer.cs new file mode 100644 index 000000000..580d1a23f --- /dev/null +++ b/QuickStart/EchoService/EchoServer.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase; + +namespace SuperSocket.QuickStart.EchoService +{ + public class EchoServer : AppServer + { + + } +} diff --git a/QuickStart/EchoService/EchoService.Mono.csproj b/QuickStart/EchoService/EchoService.Mono.csproj new file mode 100644 index 000000000..466a16849 --- /dev/null +++ b/QuickStart/EchoService/EchoService.Mono.csproj @@ -0,0 +1,120 @@ + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {6967B4E6-474F-4D79-BD4D-BD701A8A6085} + Library + Properties + SuperSocket.QuickStart.EchoService + SuperSocket.QuickStart.EchoService + v4.0 + 512 + + + 3.5 + + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + AllRules.ruleset + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + AllRules.ruleset + + + + + + + + + + + + + + + + + + + + + + + + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A} + SuperSocket.Common.Mono + + + {40B77789-EA11-4C05-8F52-86711D7BCAAF} + SuperSocket.SocketBase.Mono + + + {B9113694-7226-4152-938D-3172B11571A1} + SuperSocket.SocketService.Mono + + + + + PreserveNewest + Designer + + + + + False + .NET Framework 3.5 SP1 Client Profile + false + + + False + .NET Framework 3.5 SP1 + true + + + False + Windows Installer 3.1 + true + + + + + \ No newline at end of file diff --git a/QuickStart/EchoService/EchoService.csproj b/QuickStart/EchoService/EchoService.csproj new file mode 100644 index 000000000..096d0ec21 --- /dev/null +++ b/QuickStart/EchoService/EchoService.csproj @@ -0,0 +1,116 @@ + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {6967B4E6-474F-4D79-BD4D-BD701A8A6085} + Library + Properties + SuperSocket.QuickStart.EchoService + SuperSocket.QuickStart.EchoService + v4.0 + 512 + + + 3.5 + + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + AllRules.ruleset + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + AllRules.ruleset + + + + + 3.5 + + + 3.5 + + + 3.5 + + + + + + + + + + + + + PreserveNewest + Designer + + + + + False + .NET Framework 3.5 SP1 Client Profile + false + + + False + .NET Framework 3.5 SP1 + true + + + False + Windows Installer 3.1 + true + + + + + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A} + SuperSocket.Common + + + {40B77789-EA11-4C05-8F52-86711D7BCAAF} + SuperSocket.SocketBase + + + + + \ No newline at end of file diff --git a/QuickStart/EchoService/EchoSession.cs b/QuickStart/EchoService/EchoSession.cs new file mode 100644 index 000000000..8fc2b7c7c --- /dev/null +++ b/QuickStart/EchoService/EchoSession.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase; + +namespace SuperSocket.QuickStart.EchoService +{ + public class EchoSession : AppSession + { + protected override void OnSessionStarted() + { + Send("Welcome to EchoServer!"); + } + + public override void HandleException(Exception e) + { + Send("Server side error occurred!"); + } + } +} diff --git a/QuickStart/EchoService/Properties/AssemblyInfo.cs b/QuickStart/EchoService/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..2594ad61b --- /dev/null +++ b/QuickStart/EchoService/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +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("EchoService")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("EchoService")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2010")] +[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)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("459e0dc7-cc13-4132-9bad-daa66ac9db4e")] + +// 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")] diff --git a/QuickStart/EchoService/SuperSocket.SocketService.exe.config b/QuickStart/EchoService/SuperSocket.SocketService.exe.config new file mode 100644 index 000000000..5c61451d5 --- /dev/null +++ b/QuickStart/EchoService/SuperSocket.SocketService.exe.config @@ -0,0 +1,24 @@ + + + +
+ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/QuickStart/GPSSocketServer/Command/KeepAlive.cs b/QuickStart/GPSSocketServer/Command/KeepAlive.cs new file mode 100644 index 000000000..50bc8ded0 --- /dev/null +++ b/QuickStart/GPSSocketServer/Command/KeepAlive.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.QuickStart.GPSSocketServer.Command +{ + public class KeepAlive : CommandBase + { + public override string Name + { + get + { + return "10"; + } + } + + public override void ExecuteCommand(GPSSession session, BinaryRequestInfo requestInfo) + { + //You can do nothing, after this command is executed, the LastActiveTime of this session will be updated + var response = session.AppServer.DefaultResponse; + session.Send(response, 0, response.Length); + } + } +} diff --git a/QuickStart/GPSSocketServer/Command/Position.cs b/QuickStart/GPSSocketServer/Command/Position.cs new file mode 100644 index 000000000..46b24036f --- /dev/null +++ b/QuickStart/GPSSocketServer/Command/Position.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.QuickStart.GPSSocketServer.Command +{ + public class Position : CommandBase + { + public override string Name + { + get + { + return "1A"; + } + } + + public override void ExecuteCommand(GPSSession session, BinaryRequestInfo requestInfo) + { + //The logic of saving GPS position data + var response = session.AppServer.DefaultResponse; + session.Send(response, 0, response.Length); ; + } + } +} diff --git a/QuickStart/GPSSocketServer/GPSRequestFilter.cs b/QuickStart/GPSSocketServer/GPSRequestFilter.cs new file mode 100644 index 000000000..6613df82e --- /dev/null +++ b/QuickStart/GPSSocketServer/GPSRequestFilter.cs @@ -0,0 +1,122 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.Common; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.QuickStart.GPSSocketServer +{ + /// + /// It is the kind of protocol that + /// the first two bytes of each command are { 0x68, 0x68 } + /// and the last two bytes of each command are { 0x0d, 0x0a } + /// and the 16th byte (data[15]) of each command indicate the command type + /// if data[15] = 0x10, the command is a keep alive one + /// if data[15] = 0x1a, the command is position one + /// + class GPSRequestFilter : RequestFilterBase + { + private static byte[] m_StartMark = new byte[] { 0x68, 0x68 }; + private static byte[] m_EndMark = new byte[] { 0x0d, 0x0a }; + + private SearchMarkState m_StartSearchState; + private SearchMarkState m_EndSearchState; + + private bool m_FoundStart = false; + + public GPSRequestFilter() + { + m_StartSearchState = new SearchMarkState(m_StartMark); + m_EndSearchState = new SearchMarkState(m_EndMark); + } + + public override BinaryRequestInfo Filter(IAppSession session, byte[] readBuffer, int offset, int length, bool toBeCopied, out int left) + { + left = 0; + + if (!m_FoundStart) + { + var pos = readBuffer.SearchMark(offset, length, m_StartSearchState); + + //Don't cache invalid data + if (pos < 0) + return null; + + //Found start mark + m_FoundStart = true; + + int searchEndMarkOffset = pos + m_StartMark.Length; + + //The end mark could not exist in this round received data + if (offset + length <= searchEndMarkOffset) + { + AddArraySegment(m_StartMark, 0, m_StartMark.Length, false); + return null; + } + + int searchEndMarkLength = offset + length - searchEndMarkOffset; + + var endPos = readBuffer.SearchMark(searchEndMarkOffset, searchEndMarkLength, m_EndSearchState); + + if (endPos < 0) + { + AddArraySegment(readBuffer, pos, length + offset - pos, toBeCopied); + return null; + } + + int parsedLen = endPos - pos + m_EndMark.Length; + left = length - parsedLen; + + var requestInfo = CreateCommandInfo(readBuffer.CloneRange(pos, parsedLen)); + + ResetState(); + + return requestInfo; + } + else + { + var endPos = readBuffer.SearchMark(offset, length, m_EndSearchState); + //Haven't found end mark + if (endPos < 0) + { + AddArraySegment(readBuffer, offset, length, toBeCopied); + return null; + } + + //Found end mark + int parsedLen = endPos - offset + m_EndMark.Length; + left = length - parsedLen; + + byte[] commandData = new byte[BufferSegments.Count + parsedLen]; + + if (BufferSegments.Count > 0) + BufferSegments.CopyTo(commandData, 0, 0, BufferSegments.Count); + + Array.Copy(readBuffer, offset, commandData, BufferSegments.Count, parsedLen); + + var requestInfo = CreateCommandInfo(commandData); + + ResetState(); + + return requestInfo; + } + } + + private void ResetState() + { + m_StartSearchState.Matched = 0; + m_EndSearchState.Matched = 0; + m_FoundStart = false; + + ClearBufferSegments(); + } + + private BinaryRequestInfo CreateCommandInfo(byte[] data) + { + return new BinaryRequestInfo(BitConverter.ToString(data, 15, 1), data); + } + } +} diff --git a/QuickStart/GPSSocketServer/GPSServer.cs b/QuickStart/GPSSocketServer/GPSServer.cs new file mode 100644 index 000000000..4ab93b0f8 --- /dev/null +++ b/QuickStart/GPSSocketServer/GPSServer.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.QuickStart.GPSSocketServer +{ + public class GPSServer : AppServer + { + public GPSServer() + : base(new DefaultRequestFilterFactory()) + { + DefaultResponse = new byte[] { 0x54, 0x68, 0x1a, 0x0d, 0x0a}; + } + + internal byte[] DefaultResponse { get; private set; } + } +} diff --git a/QuickStart/GPSSocketServer/GPSServerTest.cs b/QuickStart/GPSSocketServer/GPSServerTest.cs new file mode 100644 index 000000000..155156aec --- /dev/null +++ b/QuickStart/GPSSocketServer/GPSServerTest.cs @@ -0,0 +1,108 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text; +using NUnit.Framework; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Config; +using SuperSocket.SocketBase.Logging; +using SuperSocket.SocketEngine; + +namespace SuperSocket.QuickStart.GPSSocketServer +{ + [TestFixture] + public class GPSServerTest + { + private GPSServer m_Server; + private IServerConfig m_Config; + + [TestFixtureSetUp] + public void Setup() + { + m_Config = new ServerConfig + { + Port = 555, + Ip = "Any", + MaxConnectionNumber = 10, + Mode = SocketMode.Tcp, + Name = "GPSServer" + }; + + m_Server = new GPSServer(); + m_Server.Setup(new RootConfig(), m_Config, SocketServerFactory.Instance, logFactory: new ConsoleLogFactory()); + } + + [SetUp] + public void StartServer() + { + m_Server.Start(); + } + + [TearDown] + public void StopServer() + { + m_Server.Stop(); + } + + private static byte[] m_StartMark = new byte[] { 0x68, 0x68 }; + private static byte[] m_EndMark = new byte[] { 0x0d, 0x0a }; + + [Test] + public void TestCustomProtocol() + { + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port); + + Random rd = new Random(); + + using (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) + { + socket.Connect(serverAddress); + + for (int i = 0; i < 10; i++) + { + List dataSource = new List(); + + int messageRepeat = rd.Next(1, 5); + + StringBuilder sb = new StringBuilder(); + + for (int j = 0; j < messageRepeat; j++) + { + sb.Append(Guid.NewGuid().ToString().Replace("-", string.Empty)); + } + + dataSource.AddRange(m_StartMark); + dataSource.AddRange(Encoding.ASCII.GetBytes(sb.ToString(0, rd.Next(20, sb.Length)))); + dataSource.AddRange(m_EndMark); + + byte[] data = dataSource.ToArray(); + + if(i % 2 == 0) + data[15] = 0x10; + else + data[15] = 0x1a; + + socket.Send(data); + + byte[] response = new byte[5]; + + int read = 0; + + while (read < response.Length) + { + read += socket.Receive(response, read, response.Length - read, SocketFlags.None); + } + + Assert.AreEqual(0x54, response[0]); + Assert.AreEqual(0x68, response[1]); + Assert.AreEqual(0x1a, response[2]); + Assert.AreEqual(0x0d, response[3]); + Assert.AreEqual(0x0a, response[4]); + } + } + } + } +} diff --git a/QuickStart/GPSSocketServer/GPSSession.cs b/QuickStart/GPSSocketServer/GPSSession.cs new file mode 100644 index 000000000..b5c939de2 --- /dev/null +++ b/QuickStart/GPSSocketServer/GPSSession.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.QuickStart.GPSSocketServer +{ + public class GPSSession : AppSession + { + public new GPSServer AppServer + { + get + { + return (GPSServer)base.AppServer; + } + } + } +} diff --git a/QuickStart/GPSSocketServer/GPSSocketServer.csproj b/QuickStart/GPSSocketServer/GPSSocketServer.csproj new file mode 100644 index 000000000..061bff601 --- /dev/null +++ b/QuickStart/GPSSocketServer/GPSSocketServer.csproj @@ -0,0 +1,87 @@ + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {2B1DD784-5A9D-4177-9291-ADEB3213A938} + Library + Properties + SuperSocket.QuickStart.GPSSocketServer + SuperSocket.QuickStart.GPSSocketServer + v4.0 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\..\Reference\nunit.framework.dll + + + + + + + + + + + + + + + + + + + + + + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A} + SuperSocket.Common + + + {40B77789-EA11-4C05-8F52-86711D7BCAAF} + SuperSocket.SocketBase + + + {153FEF72-191C-43D9-BE71-2B351C7AC760} + SuperSocket.SocketEngine + + + {B9113694-7226-4152-938D-3172B11571A1} + SuperSocket.SocketService + + + + + Designer + PreserveNewest + + + + + \ No newline at end of file diff --git a/QuickStart/GPSSocketServer/Properties/AssemblyInfo.cs b/QuickStart/GPSSocketServer/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..a860b2280 --- /dev/null +++ b/QuickStart/GPSSocketServer/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +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("GPSSocketServer")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("GPSSocketServer")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2011")] +[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)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("2ec7a2b2-1251-4e5c-9619-e0e80d8a80fe")] + +// 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")] diff --git a/QuickStart/GPSSocketServer/SuperSocket.SocketService.exe.config b/QuickStart/GPSSocketServer/SuperSocket.SocketService.exe.config new file mode 100644 index 000000000..88fc7ebfc --- /dev/null +++ b/QuickStart/GPSSocketServer/SuperSocket.SocketService.exe.config @@ -0,0 +1,23 @@ + + + +
+ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/QuickStart/IronSocketServer/Command/IronPythonServer/ADD.py b/QuickStart/IronSocketServer/Command/IronPythonServer/ADD.py new file mode 100644 index 000000000..580f5a5b2 --- /dev/null +++ b/QuickStart/IronSocketServer/Command/IronPythonServer/ADD.py @@ -0,0 +1,7 @@ +import clr +clr.AddReference("System") + +from System import * + +def execute(session, command): + session.Send((Convert.ToInt32(command[0]) + Convert.ToInt32(command[1])).ToString()) \ No newline at end of file diff --git a/QuickStart/IronSocketServer/Command/IronPythonServer/MULT.py b/QuickStart/IronSocketServer/Command/IronPythonServer/MULT.py new file mode 100644 index 000000000..3544910cd --- /dev/null +++ b/QuickStart/IronSocketServer/Command/IronPythonServer/MULT.py @@ -0,0 +1,7 @@ +import clr +clr.AddReference("System") + +from System import * + +def execute(session, command): + session.Send((Convert.ToInt32(command[0]) * Convert.ToInt32(command[1])).ToString()) \ No newline at end of file diff --git a/QuickStart/IronSocketServer/Command/IronPythonServer/QUIT.py b/QuickStart/IronSocketServer/Command/IronPythonServer/QUIT.py new file mode 100644 index 000000000..9593123fc --- /dev/null +++ b/QuickStart/IronSocketServer/Command/IronPythonServer/QUIT.py @@ -0,0 +1,2 @@ +def execute(session, command): + session.Close() \ No newline at end of file diff --git a/QuickStart/IronSocketServer/DynamicAppServer.cs b/QuickStart/IronSocketServer/DynamicAppServer.cs new file mode 100644 index 000000000..7e2402b90 --- /dev/null +++ b/QuickStart/IronSocketServer/DynamicAppServer.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase; + +namespace SuperSocket.QuickStart.IronSocketServer +{ + public class DynamicAppServer : AppServer + { + } +} diff --git a/QuickStart/IronSocketServer/IronSocketServer.csproj b/QuickStart/IronSocketServer/IronSocketServer.csproj new file mode 100644 index 000000000..dc411a3aa --- /dev/null +++ b/QuickStart/IronSocketServer/IronSocketServer.csproj @@ -0,0 +1,98 @@ + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {9510FE4C-52ED-419F-B32D-61F18C487A64} + Library + Properties + SuperSocket.QuickStart.IronSocketServer + SuperSocket.QuickStart.IronSocketServer + v4.0 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A} + SuperSocket.Common + + + {55BAA051-CE62-4D4A-81B6-68B042CC78E9} + SuperSocket.Dlr + + + {40B77789-EA11-4C05-8F52-86711D7BCAAF} + SuperSocket.SocketBase + + + {B9113694-7226-4152-938D-3172B11571A1} + SuperSocket.SocketService + + + + + Microsoft.Dynamic.dll + PreserveNewest + + + IronPython.dll + PreserveNewest + + + PreserveNewest + + + Designer + PreserveNewest + + + + + + PreserveNewest + + + PreserveNewest + + + + + \ No newline at end of file diff --git a/QuickStart/IronSocketServer/Properties/AssemblyInfo.cs b/QuickStart/IronSocketServer/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..33f59c57c --- /dev/null +++ b/QuickStart/IronSocketServer/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +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("IronPythonServer")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("IronPythonServer")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2011")] +[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)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("c444cc26-3e7f-4971-bbc7-cbe667dddf84")] + +// 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")] diff --git a/QuickStart/IronSocketServer/SuperSocket.SocketService.exe.config b/QuickStart/IronSocketServer/SuperSocket.SocketService.exe.config new file mode 100644 index 000000000..aeb695ae3 --- /dev/null +++ b/QuickStart/IronSocketServer/SuperSocket.SocketService.exe.config @@ -0,0 +1,39 @@ + + + +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/QuickStart/MultipleAppServer/DESP.cs b/QuickStart/MultipleAppServer/DESP.cs new file mode 100644 index 000000000..e6c77abeb --- /dev/null +++ b/QuickStart/MultipleAppServer/DESP.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.QuickStart.MultipleAppServer +{ + public class DESP : StringCommandBase + { + public override void ExecuteCommand(AppSession session, StringRequestInfo requestInfo) + { + ((MyAppServerA)session.AppServer).DespatchMessage(requestInfo[0], requestInfo[1]); + } + } +} diff --git a/QuickStart/MultipleAppServer/IDespatchServer.cs b/QuickStart/MultipleAppServer/IDespatchServer.cs new file mode 100644 index 000000000..dd0be30bb --- /dev/null +++ b/QuickStart/MultipleAppServer/IDespatchServer.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.QuickStart.MultipleAppServer +{ + interface IDespatchServer + { + void DispatchMessage(string sessionKey, string message); + } +} diff --git a/QuickStart/MultipleAppServer/MultipleAppServer.csproj b/QuickStart/MultipleAppServer/MultipleAppServer.csproj new file mode 100644 index 000000000..290adc18a --- /dev/null +++ b/QuickStart/MultipleAppServer/MultipleAppServer.csproj @@ -0,0 +1,76 @@ + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {22A610A1-5F55-449E-8831-A832D692DAEC} + Library + Properties + SuperSocket.QuickStart.MultipleAppServer + SuperSocket.QuickStart.MultipleAppServer + v4.0 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A} + SuperSocket.Common + + + {40B77789-EA11-4C05-8F52-86711D7BCAAF} + SuperSocket.SocketBase + + + {153FEF72-191C-43D9-BE71-2B351C7AC760} + SuperSocket.SocketEngine + + + + + PreserveNewest + + + + + \ No newline at end of file diff --git a/QuickStart/MultipleAppServer/MyAppServerA.cs b/QuickStart/MultipleAppServer/MyAppServerA.cs new file mode 100644 index 000000000..bb76cab7c --- /dev/null +++ b/QuickStart/MultipleAppServer/MyAppServerA.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase; +using SuperSocket.SocketEngine; + +namespace SuperSocket.QuickStart.MultipleAppServer +{ + public class MyAppServerA : AppServer + { + private IDespatchServer m_DespatchServer; + + protected override void OnStartup() + { + m_DespatchServer = this.Bootstrap.AppServers.FirstOrDefault(s => s.Name.Equals("ServerB", StringComparison.OrdinalIgnoreCase)) as IDespatchServer; + base.OnStartup(); + } + + internal void DespatchMessage(string targetSessionKey, string message) + { + m_DespatchServer.DispatchMessage(targetSessionKey, message); + } + } +} diff --git a/QuickStart/MultipleAppServer/MyAppServerB.cs b/QuickStart/MultipleAppServer/MyAppServerB.cs new file mode 100644 index 000000000..9d67f0c28 --- /dev/null +++ b/QuickStart/MultipleAppServer/MyAppServerB.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase; + +namespace SuperSocket.QuickStart.MultipleAppServer +{ + public class MyAppServerB : AppServer, IDespatchServer + { + public void DispatchMessage(string sessionKey, string message) + { + var session = GetAppSessionByID(sessionKey); + if (session == null) + return; + + session.Send(message); + } + } +} diff --git a/QuickStart/MultipleAppServer/Properties/AssemblyInfo.cs b/QuickStart/MultipleAppServer/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..4974cbd0b --- /dev/null +++ b/QuickStart/MultipleAppServer/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +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("MultipleAppServer")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("MultipleAppServer")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2011")] +[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)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("ad6bd357-f907-4974-9fbe-86a424f37a10")] + +// 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")] diff --git a/QuickStart/MultipleAppServer/SuperSocket.SocketService.exe.config b/QuickStart/MultipleAppServer/SuperSocket.SocketService.exe.config new file mode 100644 index 000000000..fa4057b68 --- /dev/null +++ b/QuickStart/MultipleAppServer/SuperSocket.SocketService.exe.config @@ -0,0 +1,30 @@ + + + +
+ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/QuickStart/MultipleListenersA.exe.config b/QuickStart/MultipleListenersA.exe.config new file mode 100644 index 000000000..e2c230e24 --- /dev/null +++ b/QuickStart/MultipleListenersA.exe.config @@ -0,0 +1,27 @@ + + + +
+ + + + + + + + + + + + + + + + + + + + + + diff --git a/QuickStart/MultipleListenersB.exe.config b/QuickStart/MultipleListenersB.exe.config new file mode 100644 index 000000000..e0e39e4ba --- /dev/null +++ b/QuickStart/MultipleListenersB.exe.config @@ -0,0 +1,27 @@ + + + +
+ + + + + + + + + + + + + + + + + + + + + + diff --git a/QuickStart/MultipleListenersC.exe.config b/QuickStart/MultipleListenersC.exe.config new file mode 100644 index 000000000..602946cb9 --- /dev/null +++ b/QuickStart/MultipleListenersC.exe.config @@ -0,0 +1,28 @@ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + diff --git a/QuickStart/PolicyServer.exe.config b/QuickStart/PolicyServer.exe.config new file mode 100644 index 000000000..eafb8ffb0 --- /dev/null +++ b/QuickStart/PolicyServer.exe.config @@ -0,0 +1,39 @@ + + + +
+ + + + + + + + + + + + + + + + + + + + + diff --git a/QuickStart/QuickStart.sln b/QuickStart/QuickStart.sln new file mode 100644 index 000000000..0ab666480 --- /dev/null +++ b/QuickStart/QuickStart.sln @@ -0,0 +1,137 @@ + +Microsoft Visual Studio Solution File, Format Version 11.00 +# Visual Studio 2010 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SuperSocket", "SuperSocket", "{2E6E656A-D747-4A69-B300-8C82573A76B5}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocket.Common", "..\Common\SuperSocket.Common.csproj", "{A24F4D38-BA9C-4FD6-95B7-4980DE36131A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocket.SocketService", "..\SocketService\SuperSocket.SocketService.csproj", "{B9113694-7226-4152-938D-3172B11571A1}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EchoService", "EchoService\EchoService.csproj", "{6967B4E6-474F-4D79-BD4D-BD701A8A6085}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RemoteProcessService", "RemoteProcessService\RemoteProcessService.csproj", "{CA67AA73-42D0-4A08-85C4-61FB569231A8}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BroadcastService", "BroadcastService\BroadcastService.csproj", "{083155D6-A0A2-4703-AC43-7C6496A9B607}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocket.Test", "..\Test\SuperSocket.Test.csproj", "{BDBB6CE9-C3CE-49C1-A05E-2D7628430A02}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocket.SocketBase", "..\SocketBase\SuperSocket.SocketBase.csproj", "{40B77789-EA11-4C05-8F52-86711D7BCAAF}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocket.SocketEngine", "..\SocketEngine\SuperSocket.SocketEngine.csproj", "{153FEF72-191C-43D9-BE71-2B351C7AC760}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CustomProtocol", "CustomProtocol\CustomProtocol.csproj", "{FB261628-26FD-48B5-9D3D-C9E34B4728CF}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocket.Facility", "..\Facility\SuperSocket.Facility.csproj", "{01987BAC-C498-44DD-B274-62EA2506B51D}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GPSSocketServer", "GPSSocketServer\GPSSocketServer.csproj", "{2B1DD784-5A9D-4177-9291-ADEB3213A938}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CommandFilter", "CommandFilter\CommandFilter.csproj", "{595A2664-BBC7-41CF-AA19-E34DEA3DBE6E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConnectionFilter", "ConnectionFilter\ConnectionFilter.csproj", "{E286C017-49DB-4EA9-A6BC-EC6ADB51E0A8}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MultipleAppServer", "MultipleAppServer\MultipleAppServer.csproj", "{22A610A1-5F55-449E-8831-A832D692DAEC}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocket.Dlr", "..\Dlr\SuperSocket.Dlr.csproj", "{55BAA051-CE62-4D4A-81B6-68B042CC78E9}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IronSocketServer", "IronSocketServer\IronSocketServer.csproj", "{9510FE4C-52ED-419F-B32D-61F18C487A64}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CustomRequestInfoParser", "CustomRequestInfoParser\CustomRequestInfoParser.csproj", "{18457034-1FC3-4464-AA10-23B58EB1B0D5}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ConfigSample", "ConfigSample", "{863EC855-457E-484A-A7F4-2C787EB16E63}" + ProjectSection(SolutionItems) = preProject + MultipleListenersA.exe.config = MultipleListenersA.exe.config + MultipleListenersB.exe.config = MultipleListenersB.exe.config + MultipleListenersC.exe.config = MultipleListenersC.exe.config + PolicyServer.exe.config = PolicyServer.exe.config + SecureServerA.config = SecureServerA.config + SecureServerB.config = SecureServerB.config + EndProjectSection +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A}.Release|Any CPU.Build.0 = Release|Any CPU + {B9113694-7226-4152-938D-3172B11571A1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B9113694-7226-4152-938D-3172B11571A1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B9113694-7226-4152-938D-3172B11571A1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B9113694-7226-4152-938D-3172B11571A1}.Release|Any CPU.Build.0 = Release|Any CPU + {6967B4E6-474F-4D79-BD4D-BD701A8A6085}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6967B4E6-474F-4D79-BD4D-BD701A8A6085}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6967B4E6-474F-4D79-BD4D-BD701A8A6085}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6967B4E6-474F-4D79-BD4D-BD701A8A6085}.Release|Any CPU.Build.0 = Release|Any CPU + {CA67AA73-42D0-4A08-85C4-61FB569231A8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CA67AA73-42D0-4A08-85C4-61FB569231A8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CA67AA73-42D0-4A08-85C4-61FB569231A8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CA67AA73-42D0-4A08-85C4-61FB569231A8}.Release|Any CPU.Build.0 = Release|Any CPU + {083155D6-A0A2-4703-AC43-7C6496A9B607}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {083155D6-A0A2-4703-AC43-7C6496A9B607}.Debug|Any CPU.Build.0 = Debug|Any CPU + {083155D6-A0A2-4703-AC43-7C6496A9B607}.Release|Any CPU.ActiveCfg = Release|Any CPU + {083155D6-A0A2-4703-AC43-7C6496A9B607}.Release|Any CPU.Build.0 = Release|Any CPU + {BDBB6CE9-C3CE-49C1-A05E-2D7628430A02}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BDBB6CE9-C3CE-49C1-A05E-2D7628430A02}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BDBB6CE9-C3CE-49C1-A05E-2D7628430A02}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BDBB6CE9-C3CE-49C1-A05E-2D7628430A02}.Release|Any CPU.Build.0 = Release|Any CPU + {40B77789-EA11-4C05-8F52-86711D7BCAAF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {40B77789-EA11-4C05-8F52-86711D7BCAAF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {40B77789-EA11-4C05-8F52-86711D7BCAAF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {40B77789-EA11-4C05-8F52-86711D7BCAAF}.Release|Any CPU.Build.0 = Release|Any CPU + {153FEF72-191C-43D9-BE71-2B351C7AC760}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {153FEF72-191C-43D9-BE71-2B351C7AC760}.Debug|Any CPU.Build.0 = Debug|Any CPU + {153FEF72-191C-43D9-BE71-2B351C7AC760}.Release|Any CPU.ActiveCfg = Release|Any CPU + {153FEF72-191C-43D9-BE71-2B351C7AC760}.Release|Any CPU.Build.0 = Release|Any CPU + {FB261628-26FD-48B5-9D3D-C9E34B4728CF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FB261628-26FD-48B5-9D3D-C9E34B4728CF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FB261628-26FD-48B5-9D3D-C9E34B4728CF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FB261628-26FD-48B5-9D3D-C9E34B4728CF}.Release|Any CPU.Build.0 = Release|Any CPU + {01987BAC-C498-44DD-B274-62EA2506B51D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {01987BAC-C498-44DD-B274-62EA2506B51D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {01987BAC-C498-44DD-B274-62EA2506B51D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {01987BAC-C498-44DD-B274-62EA2506B51D}.Release|Any CPU.Build.0 = Release|Any CPU + {2B1DD784-5A9D-4177-9291-ADEB3213A938}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2B1DD784-5A9D-4177-9291-ADEB3213A938}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2B1DD784-5A9D-4177-9291-ADEB3213A938}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2B1DD784-5A9D-4177-9291-ADEB3213A938}.Release|Any CPU.Build.0 = Release|Any CPU + {595A2664-BBC7-41CF-AA19-E34DEA3DBE6E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {595A2664-BBC7-41CF-AA19-E34DEA3DBE6E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {595A2664-BBC7-41CF-AA19-E34DEA3DBE6E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {595A2664-BBC7-41CF-AA19-E34DEA3DBE6E}.Release|Any CPU.Build.0 = Release|Any CPU + {E286C017-49DB-4EA9-A6BC-EC6ADB51E0A8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E286C017-49DB-4EA9-A6BC-EC6ADB51E0A8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E286C017-49DB-4EA9-A6BC-EC6ADB51E0A8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E286C017-49DB-4EA9-A6BC-EC6ADB51E0A8}.Release|Any CPU.Build.0 = Release|Any CPU + {22A610A1-5F55-449E-8831-A832D692DAEC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {22A610A1-5F55-449E-8831-A832D692DAEC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {22A610A1-5F55-449E-8831-A832D692DAEC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {22A610A1-5F55-449E-8831-A832D692DAEC}.Release|Any CPU.Build.0 = Release|Any CPU + {55BAA051-CE62-4D4A-81B6-68B042CC78E9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {55BAA051-CE62-4D4A-81B6-68B042CC78E9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {55BAA051-CE62-4D4A-81B6-68B042CC78E9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {55BAA051-CE62-4D4A-81B6-68B042CC78E9}.Release|Any CPU.Build.0 = Release|Any CPU + {9510FE4C-52ED-419F-B32D-61F18C487A64}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9510FE4C-52ED-419F-B32D-61F18C487A64}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9510FE4C-52ED-419F-B32D-61F18C487A64}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9510FE4C-52ED-419F-B32D-61F18C487A64}.Release|Any CPU.Build.0 = Release|Any CPU + {18457034-1FC3-4464-AA10-23B58EB1B0D5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {18457034-1FC3-4464-AA10-23B58EB1B0D5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {18457034-1FC3-4464-AA10-23B58EB1B0D5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {18457034-1FC3-4464-AA10-23B58EB1B0D5}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A} = {2E6E656A-D747-4A69-B300-8C82573A76B5} + {B9113694-7226-4152-938D-3172B11571A1} = {2E6E656A-D747-4A69-B300-8C82573A76B5} + {BDBB6CE9-C3CE-49C1-A05E-2D7628430A02} = {2E6E656A-D747-4A69-B300-8C82573A76B5} + {40B77789-EA11-4C05-8F52-86711D7BCAAF} = {2E6E656A-D747-4A69-B300-8C82573A76B5} + {153FEF72-191C-43D9-BE71-2B351C7AC760} = {2E6E656A-D747-4A69-B300-8C82573A76B5} + {01987BAC-C498-44DD-B274-62EA2506B51D} = {2E6E656A-D747-4A69-B300-8C82573A76B5} + {55BAA051-CE62-4D4A-81B6-68B042CC78E9} = {2E6E656A-D747-4A69-B300-8C82573A76B5} + EndGlobalSection +EndGlobal diff --git a/QuickStart/RemoteProcessService/Command/FROZ.cs b/QuickStart/RemoteProcessService/Command/FROZ.cs new file mode 100644 index 000000000..f6388b463 --- /dev/null +++ b/QuickStart/RemoteProcessService/Command/FROZ.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.QuickStart.RemoteProcessService.Command +{ + public class FROZ : StringCommandBase + { + #region CommandBase Members + + public override void ExecuteCommand(RemoteProcessSession session, StringRequestInfo commandData) + { + var server = session.AppServer; + + string firstParam = commandData.GetFirstParam(); + + if (string.IsNullOrEmpty(firstParam)) + { + session.Send("Invalid parameter!"); + return; + } + + var param = commandData[1]; + + if ("list".Equals(firstParam, StringComparison.OrdinalIgnoreCase)) + { + StringBuilder sb = new StringBuilder(); + foreach (var p in server.GetFrozedProcesses()) + { + sb.AppendLine(p); + } + sb.AppendLine(); + + session.Send(sb.ToString()); + return; + } + else if ("add".Equals(firstParam, StringComparison.OrdinalIgnoreCase)) + { + if (string.IsNullOrEmpty(param)) + { + session.Send("Invalid parameter!"); + return; + } + + server.AddFrozedProcess(param); + session.Send(string.Format("Frozed process {0} has been added!", param)); + return; + } + else if ("remove".Equals(firstParam, StringComparison.OrdinalIgnoreCase)) + { + if (string.IsNullOrEmpty(param)) + { + session.Send("Invalid parameter!"); + return; + } + + server.RemoveFrozedProcess(param); + session.Send(string.Format("Frozed process {0} has been removed!", param)); + return; + } + else if ("clear".Equals(firstParam, StringComparison.OrdinalIgnoreCase)) + { + server.ClearFrozedProcess(); + session.Send("All frozed process have been removed!"); + return; + } + else if ("stop".Equals(firstParam, StringComparison.OrdinalIgnoreCase)) + { + server.StopFroze(); + session.Send("Frozing has been stopped!"); + return; + } + else if ("start".Equals(firstParam, StringComparison.OrdinalIgnoreCase)) + { + server.StartFroze(); + session.Send("Frozing has been started!"); + return; + } + } + + #endregion + } +} diff --git a/QuickStart/RemoteProcessService/Command/KILL.cs b/QuickStart/RemoteProcessService/Command/KILL.cs new file mode 100644 index 000000000..30eea5950 --- /dev/null +++ b/QuickStart/RemoteProcessService/Command/KILL.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Diagnostics; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.QuickStart.RemoteProcessService.Command +{ + public class KILL : StringCommandBase + { + #region CommandBase Members + + public override void ExecuteCommand(RemoteProcessSession session, StringRequestInfo commandData) + { + int processId; + + string processKey = commandData.Parameters.FirstOrDefault(); + + if (string.IsNullOrEmpty(processKey)) + { + session.Send("No parameter!"); + return; + } + + if (int.TryParse(processKey, out processId)) + { + Process process = Process.GetProcessById(processId); + if (process != null) + { + process.Kill(); + session.Send("The specific process has been killed!"); + return; + } + else + { + session.Send("The specific process does not exist!"); + } + } + else + { + List processes = Process.GetProcesses().Where(p => + p.ProcessName.Equals(processKey, StringComparison.OrdinalIgnoreCase)).ToList(); + + processes.ForEach(p => p.Kill()); + + if (processes.Count <= 0) + session.Send("The specific process does not exist!"); + else if (processes.Count == 1) + session.Send("The specific process has been killed!"); + else + session.Send(string.Format("The {0} specific process has been killed!", processes.Count)); + } + } + + #endregion + } +} diff --git a/QuickStart/RemoteProcessService/Command/LIST.cs b/QuickStart/RemoteProcessService/Command/LIST.cs new file mode 100644 index 000000000..59f762114 --- /dev/null +++ b/QuickStart/RemoteProcessService/Command/LIST.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Diagnostics; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.QuickStart.RemoteProcessService.Command +{ + public class LIST : StringCommandBase + { + #region CommandBase Members + + public override void ExecuteCommand(RemoteProcessSession session, StringRequestInfo commandData) + { + Process[] processes; + + string firstParam = commandData.GetFirstParam(); + + if (string.IsNullOrEmpty(firstParam) || firstParam == "*") + processes = Process.GetProcesses(); + else + processes = Process.GetProcesses().Where(p => + p.ProcessName.IndexOf(firstParam, StringComparison.OrdinalIgnoreCase) >= 0).ToArray(); + + StringBuilder sb = new StringBuilder(); + + foreach (var p in processes) + { + sb.AppendLine(string.Format("{0}\t{1}", p.ProcessName, p.Id)); + } + + sb.AppendLine(); + + session.Send(sb.ToString()); + } + + #endregion + } +} diff --git a/QuickStart/RemoteProcessService/Command/QUIT.cs b/QuickStart/RemoteProcessService/Command/QUIT.cs new file mode 100644 index 000000000..4a4e490ce --- /dev/null +++ b/QuickStart/RemoteProcessService/Command/QUIT.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.QuickStart.RemoteProcessService.Command +{ + public class QUIT : StringCommandBase + { + #region CommandBase Members + + public override void ExecuteCommand(RemoteProcessSession session, StringRequestInfo commandData) + { + session.Send("bye"); + session.Close(); + } + + #endregion + } +} diff --git a/QuickStart/RemoteProcessService/Properties/AssemblyInfo.cs b/QuickStart/RemoteProcessService/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..8191882c3 --- /dev/null +++ b/QuickStart/RemoteProcessService/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +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("RemoteProcessService")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("RemoteProcessService")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2010")] +[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)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("105e35f7-c1e6-4b4d-8fe2-f700b74e4522")] + +// 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")] diff --git a/QuickStart/RemoteProcessService/RemoteProcessServer.cs b/QuickStart/RemoteProcessService/RemoteProcessServer.cs new file mode 100644 index 000000000..e4db547b3 --- /dev/null +++ b/QuickStart/RemoteProcessService/RemoteProcessServer.cs @@ -0,0 +1,129 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Text; +using System.Threading; +using SuperSocket.Common; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Config; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.QuickStart.RemoteProcessService +{ + public class RemoteProcessServer : AppServer + { + private Dictionary m_FrozedProcesses = new Dictionary(StringComparer.OrdinalIgnoreCase); + + private object m_FrozedProcessLock = new object(); + + public string[] GetFrozedProcesses() + { + lock (m_FrozedProcessLock) + { + return m_FrozedProcesses.Values.ToArray(); + } + } + + public void AddFrozedProcess(string processName) + { + lock(m_FrozedProcessLock) + { + m_FrozedProcesses[processName] = processName; + } + } + + public void RemoveFrozedProcess(string processName) + { + lock(m_FrozedProcessLock) + { + m_FrozedProcesses.Remove(processName); + } + } + + public void ClearFrozedProcess() + { + lock (m_FrozedProcessLock) + { + m_FrozedProcesses.Clear(); + } + } + + public void StopFroze() + { + m_MonitorTimer.Change(Timeout.Infinite, Timeout.Infinite); + } + + public void StartFroze() + { + int interval = this.Config.Options.GetValue("MonitorInterval", "1").ToInt32(); + TimeSpan intervalTimeSpan = new TimeSpan(0, interval, 0); + m_MonitorTimer.Change(intervalTimeSpan, intervalTimeSpan); + } + + private Timer m_MonitorTimer; + + protected override bool Setup(IRootConfig rootConfig, IServerConfig config) + { + int interval = config.Options.GetValue("MonitorInterval", "1").ToInt32(); + TimeSpan intervalTimeSpan = new TimeSpan(0, interval, 0); + m_MonitorTimer = new Timer(new TimerCallback(OnMonitorTimerCallback), new object(), intervalTimeSpan, intervalTimeSpan); + + return true; + } + + private void OnMonitorTimerCallback(object state) + { + if (Monitor.TryEnter(state)) + { + try + { + if (m_FrozedProcesses.Count <= 0) + return; + + Process[] processes = Process.GetProcesses(); + + List toBeKilled = new List(); + + lock (m_FrozedProcessLock) + { + foreach (var p in processes) + { + if (m_FrozedProcesses.ContainsKey(p.ProcessName)) + toBeKilled.Add(p); + } + } + + foreach (var p in toBeKilled) + { + try + { + p.Kill(); + } + catch (Exception e) + { + if(Logger.IsErrorEnabled) + Logger.Error("Failed to kill the process " + p.ProcessName, e); + } + } + } + catch (Exception e) + { + Logger.Error(e); + } + finally + { + Monitor.Exit(state); + } + } + } + + public override void Stop() + { + m_MonitorTimer.Change(Timeout.Infinite, Timeout.Infinite); + m_MonitorTimer.Dispose(); + base.Stop(); + } + } +} diff --git a/QuickStart/RemoteProcessService/RemoteProcessService.csproj b/QuickStart/RemoteProcessService/RemoteProcessService.csproj new file mode 100644 index 000000000..49262dc8a --- /dev/null +++ b/QuickStart/RemoteProcessService/RemoteProcessService.csproj @@ -0,0 +1,120 @@ + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {CA67AA73-42D0-4A08-85C4-61FB569231A8} + Library + Properties + SuperSocket.QuickStart.RemoteProcessService + SuperSocket.QuickStart.RemoteProcessService + v4.0 + 512 + + + 3.5 + + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + AllRules.ruleset + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + AllRules.ruleset + + + + + + + + + + + + + + + + + + + + + + + + + + + + + PreserveNewest + + + + + False + .NET Framework 3.5 SP1 Client Profile + false + + + False + .NET Framework 3.5 SP1 + true + + + False + Windows Installer 3.1 + true + + + + + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A} + SuperSocket.Common + + + {40B77789-EA11-4C05-8F52-86711D7BCAAF} + SuperSocket.SocketBase + + + + + \ No newline at end of file diff --git a/QuickStart/RemoteProcessService/RemoteProcessSession.cs b/QuickStart/RemoteProcessService/RemoteProcessSession.cs new file mode 100644 index 000000000..d355002c3 --- /dev/null +++ b/QuickStart/RemoteProcessService/RemoteProcessSession.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase; + +namespace SuperSocket.QuickStart.RemoteProcessService +{ + public class RemoteProcessSession : AppSession + { + public new RemoteProcessServer AppServer + { + get { return (RemoteProcessServer)base.AppServer; } + } + + protected override void OnSessionStarted() + { + Send("Welcome to use this tool!"); + } + + public override void HandleException(Exception e) + { + Send("An error has occurred in server side! Error message: " + e.Message + "!"); + } + } +} diff --git a/QuickStart/RemoteProcessService/SuperSocket.SocketService.exe.config b/QuickStart/RemoteProcessService/SuperSocket.SocketService.exe.config new file mode 100644 index 000000000..2645818d8 --- /dev/null +++ b/QuickStart/RemoteProcessService/SuperSocket.SocketService.exe.config @@ -0,0 +1,24 @@ + + + +
+ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/QuickStart/SecureServerA.config b/QuickStart/SecureServerA.config new file mode 100644 index 000000000..dc112b55a --- /dev/null +++ b/QuickStart/SecureServerA.config @@ -0,0 +1,27 @@ + + + +
+ + + + + + + + + + + + + + + + + + + + + + diff --git a/QuickStart/SecureServerB.config b/QuickStart/SecureServerB.config new file mode 100644 index 000000000..03a4683b4 --- /dev/null +++ b/QuickStart/SecureServerB.config @@ -0,0 +1,27 @@ + + + +
+ + + + + + + + + + + + + + + + + + + + + + diff --git a/QuickStart/SuperWebSocket/readme.txt b/QuickStart/SuperWebSocket/readme.txt new file mode 100644 index 000000000..d593ac04d --- /dev/null +++ b/QuickStart/SuperWebSocket/readme.txt @@ -0,0 +1,2 @@ +The source code of SuperWebSocket has been moved to a new separated open source project. +The project's homepage is http://superwebsocket.codeplex.com/ \ No newline at end of file diff --git a/README.TXT b/README.TXT new file mode 100644 index 000000000..b702ee47a --- /dev/null +++ b/README.TXT @@ -0,0 +1,27 @@ +SuperSocket + +SuperSocket is a light weight extensible socket application framework. +You can use it to build a command based server side socket application easily without thinking about how to use socket, +how to maintain the socket connections and how socket works(synchronize/asynchronize). + +It is a pure C# project which is designed to be extended, so it is easy to be integrated to your existing system. +As long as your systems (like forum/CRM/MIS/HRM/ERP) are developed in .NET language, +you must be able to use SuperSocket to build your socket application as a part of your current system perfectly. + + +Project homepage: http://supersocket.codeplex.com/ +SVN address: https://SuperSocket.svn.codeplex.com/svn +Author email address: kerry-jiang@hotmail.com + + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an +"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and limitations under the License. + + +Copyright 2012 Kerry Jiang (kerry-jiang@hotmail.com) \ No newline at end of file diff --git a/Reference/DLR/Net35/Microsoft.Dynamic.dll b/Reference/DLR/Net35/Microsoft.Dynamic.dll new file mode 100644 index 000000000..dbc9cc7f2 Binary files /dev/null and b/Reference/DLR/Net35/Microsoft.Dynamic.dll differ diff --git a/Reference/DLR/Net35/Microsoft.Dynamic.xml b/Reference/DLR/Net35/Microsoft.Dynamic.xml new file mode 100644 index 000000000..e2e92dc76 --- /dev/null +++ b/Reference/DLR/Net35/Microsoft.Dynamic.xml @@ -0,0 +1,6569 @@ + + + + Microsoft.Dynamic + + + + + Binds named arguments to the parameters. Returns a permutation of indices that captures the relationship between + named arguments and their corresponding parameters. Checks for duplicate and unbound named arguments. + + Ensures that for all i: namedArgs[i] binds to parameters[args.Length + bindingPermutation[i]] + + + + + The number of arguments not counting the collapsed ones. + + + + + Gets the total number of visible arguments passed to the call site including collapsed ones. + + + + + ArgBuilder provides an argument value used by the MethodBinder. One ArgBuilder exists for each + physical parameter defined on a method. + + Contrast this with ParameterWrapper which represents the logical argument passed to the method. + + + + + Provides the Expression which provides the value to be passed to the argument. + If null is returned the argument is skipped (not passed to the callee). + + + + + Provides an Expression which will update the provided value after a call to the method. May + return null if no update is required. + + + + + If the argument produces a return value (e.g. a ref or out value) this provides + the additional value to be returned. + + + + + The number of actual arguments consumed by this builder. + + + + + Returns the type required for the argument or null if the ArgBuilder + does not consume a type. + + + + + An assignable value that is passed to a byref parameter + After the call it will contain the updated value + + + + + Indicates the specific type of failure, if any, from binding to a method. + + + + + The binding succeeded. Only one method was applicable or had the best conversion. + + + + + More than one method was applicable for the provided parameters and no method was considered the best. + + + + + There are no overloads that match the number of parameters required for the call + + + + + None of the target method(s) can successfully be called. The failure can be due to: + 1. Arguments could not be successfully converted for the call + 2. Keyword arguments could not be assigned to positional arguments + 3. Keyword arguments could be assigned but would result in an argument being assigned + multiple times (keyword and positional arguments conflit or dupliate keyword arguments). + + + + + Actual arguments cannot be constructed. + + + + + No method is callable. For example, all methods have an unbound generic parameter. + + + + + Encapsulates the result of an attempt to bind to one or methods using the OverloadResolver. + + Users should first check the Result property to see if the binding was successful or + to determine the specific type of failure that occured. If the binding was successful + MakeExpression can then be called to create an expression which calls the method. + If the binding was a failure callers can then create a custom error message based upon + the reason the call failed. + + + + + Creates a new BindingTarget when the method binding has succeeded. + + + + + Creates a new BindingTarget when the method binding has failed due to an incorrect argument count + + + + + Creates a new BindingTarget when the method binding has failued due to + one or more parameters which could not be converted. + + + + + Creates a new BindingTarget when the match was ambiguous + + + + + Other failure. + + + + + Gets an Expression which calls the binding target if the method binding succeeded. + + Throws InvalidOperationException if the binding failed. + + + + + Gets the result of the attempt to bind. + + + + + Returns the method if the binding succeeded, or null if no method was applicable. + + + + + Returns the selected overload if the binding succeeded, or null if no one was applicable. + + + + + Gets the name of the method as supplied to the OverloadResolver. + + + + + Returns the MethodTarget if the binding succeeded, or null if no method was applicable. + + + + + Returns the methods which don't have any matches or null if Result == BindingResult.AmbiguousMatch + + + + + Returns the methods and their associated conversion failures if Result == BindingResult.CallFailure. + + + + + Returns the acceptable number of arguments which can be passed to the method if Result == BindingResult.IncorrectArgumentCount. + + + + + Returns the total number of arguments provided to the call. 0 if the call succeeded or failed for a reason other + than argument count mismatch. + + + + + Gets the MetaObjects which we originally did binding against in their restricted form. + + The members of the array correspond to each of the arguments. All members of the array + have a value. + + + + + Returns the return type of the binding, or null if no method was applicable. + + + + + Returns the NarrowingLevel of the method if the call succeeded. If the call + failed returns NarrowingLevel.None. + + + + + Returns true if the binding was succesful, false if it failed. + + This is an alias for BindingTarget.Result == BindingResult.Success. + + + + + Creates a ReturnBuilder + + the type the ReturnBuilder will leave on the stack + + + + Represents the reason why a call to a specific method could not be performed by the OverloadResolver. + + The reason for the failure is specified by the CallFailureReason property. Once this property + has been consulted the other properties can be consulted for more detailed information regarding + the failure. + + If reason is ConversionFailure the ConversionResults property will be non-null. + If reason is UnassignableKeyword the KeywordArguments property will be non-null and include + the keywords which could not be assigned. + If reason is DuplicateKeyword the KeywordArguments property will be non-null and include + the keywords which were duplicated (either by the keywords themselves or by positional + arguments). + + MethodTarget is always set and indicates the method which failed to bind. + + + + + Gets the MethodTarget which the call failed for. + + + + + Gets the reason for the call failure which determines the other + properties of the CallFailure which should be consulted. + + + + + Gets a list of ConversionResult's for each parameter indicating + whether the conversion was successful or failed and the types + being converted. + + + + + Gets the list of keyword arguments that were either dupliated or + unassignable. + + + + + Default value, their was no CallFailure. + + + + + One of more parameters failed to be converted + + + + + One or more keyword arguments could not be successfully assigned to a positional argument + + + + + One or more keyword arguments were duplicated or would have taken the spot of a + provided positional argument. + + + + + Type arguments could not be inferred + + + + + Represents a collection of MethodCandidate's which all accept the + same number of logical parameters. For example a params method + and a method with 3 parameters would both be a CandidateSet for 3 parameters. + + + + + Represents information about a failure to convert an argument from one + type to another. + + + + + Value of the argument or null if it is not available. + + + + + Argument actual type or its limit type if the value not known. + DynamicNull if the argument value is null. + + + + + ArgBuilder which provides a default parameter value for a method call. + + + + + Provides binding and overload resolution to .NET methods. + + MethodBinder's can be used for: + generating new AST code for calling a method + calling a method via reflection at runtime + (not implemented) performing an abstract call + + MethodBinder's support default arguments, optional arguments, by-ref (in and out), and keyword arguments. + + Implementation Details: + + The MethodBinder works by building up a CandidateSet for each number of effective arguments that can be + passed to a set of overloads. For example a set of overloads such as: + foo(object a, object b, object c) + foo(int a, int b) + + would have 2 target sets - one for 3 parameters and one for 2 parameters. For parameter arrays + we fallback and create the appropriately sized CandidateSet on demand. + + Each CandidateSet consists of a set of MethodCandidate's. Each MethodCandidate knows the flattened + parameters that could be received. For example for a function such as: + foo(params int[] args) + + When this method is in a CandidateSet of size 3 the MethodCandidate takes 3 parameters - all of them + ints; if it's in a CandidateSet of size 4 it takes 4 parameters. Effectively a MethodCandidate is + a simplified view that allows all arguments to be treated as required positional arguments. + + Each MethodCandidate in turn refers to a MethodTarget. The MethodTarget is composed of a set + of ArgBuilder's and a ReturnBuilder which know how to consume the positional arguments and pass + them to the appropriate argument of the destination method. This includes routing keyword + arguments to the correct position, providing the default values for optional arguments, etc... + + After binding is finished the MethodCandidates are thrown away and a BindingTarget is returned. + The BindingTarget indicates whether the binding was successful and if not any additional information + that should be reported to the user about the failed binding. It also exposes the MethodTarget which + allows consumers to get the flattened list of required parameters for the call. MethodCandidates + are not exposed and are an internal implementation detail of the MethodBinder. + + + + + Resolves a method overload and returns back a BindingTarget. + + The BindingTarget can then be tested for the success or particular type of + failure that prevents the method from being called. If successfully bound the BindingTarget + contains a list of argument meta-objects with additional restrictions that ensure the selection + of the particular overload. + + + + + Checks to see if the language allows named arguments to be bound to instance fields or + properties and turned into setters. By default this is only allowed on contructors. + + + + + Gets an expression that evaluates to the result of GetByRefArray operation. + + + + + Allow to bind an array/dictionary instance or a null reference to params array/dictionary parameter. + + + + + Called before arguments binding. + + + A bitmask that indicates (set bits) the parameters that were mapped by this method. + A default mapping will be constructed for the remaining parameters (cleared bits). + + + + + Return null if arguments cannot be constructed and overload resolution should produce an error. + + + + + Determines whether given overloads are overloaded on index-th parameter (the types of the index-th parameters are the same). + + + + + Selects the best (of two) candidates for conversion from actualType + + + + + Provides ordering for two parameter types if there is no conversion between the two parameter types. + + + + + The method is called each time an item of lazily splatted argument is needed. + + + + + The number of actual arguments consumed by this builder. + + + + + ArgBuilder which provides a value for a keyword argument. + + The KeywordArgBuilder calculates its position at emit time using it's initial + offset within the keyword arguments, the number of keyword arguments, and the + total number of arguments provided by the user. It then delegates to an + underlying ArgBuilder which only receives the single correct argument. + + Delaying the calculation of the position to emit time allows the method binding to be + done without knowing the exact the number of arguments provided by the user. Hence, + the method binder can be dependent only on the set of method overloads and keyword names, + but not the user arguments. While the number of user arguments could be determined + upfront, the current MethodBinder does not have this design. + + + + + The underlying builder should expect a single parameter as KeywordArgBuilder is responsible + for calculating the correct parameter to use + + + + + + Updates fields/properties of the returned value with unused keyword parameters. + + + + + MethodCandidate represents the different possible ways of calling a method or a set of method overloads. + A single method can result in multiple MethodCandidates. Some reasons include: + - Every optional parameter or parameter with a default value will result in a candidate + - The presence of ref and out parameters will add a candidate for languages which want to return the updated values as return values. + - ArgumentKind.List and ArgumentKind.Dictionary can result in a new candidate per invocation since the list might be different every time. + + Each MethodCandidate represents the parameter type for the candidate using ParameterWrapper. + + + + + Builds a new MethodCandidate which takes count arguments and the provided list of keyword arguments. + + The basic idea here is to figure out which parameters map to params or a dictionary params and + fill in those spots w/ extra ParameterWrapper's. + + + + + Narrowing conversions are conversions that cannot be proved to always succeed, conversions that are + known to possibly lose information, and conversions across domains of types sufficiently different + to merit narrowing notation like casts. + + Its upto every language to define the levels for conversions. The narrowling levels can be used by + for method overload resolution, where the overload is based on the parameter types (and not the number + of parameters). + + + + + Conversions at this level do not do any narrowing. Typically, this will include + implicit numeric conversions, Type.IsAssignableFrom, StringBuilder to string, etc. + + + + + Language defined prefered narrowing conversion. First level that introduces narrowing + conversions. + + + + + Language defined preferred narrowing conversion. Second level that introduces narrowing + conversions and should have more conversions than One. + + + + + Language defined preferred narrowing conversion. Third level that introduces narrowing + conversions and should have more conversions that Two. + + + + + A somewhat meaningful conversion is possible, but it will quite likely be lossy. + For eg. BigInteger to an Int32, Boolean to Int32, one-char string to a char, + larger number type to a smaller numeric type (where there is no overflow), etc + + + + + Builds the argument for an out argument when not passed a StrongBox. The out parameter + is returned as an additional return value. + + + + + Defines a method overload abstraction for the purpose of overload resolution. + It provides the overload resolver the metadata it needs to perform the resolution. + + + WARNING: This is a temporary API that will undergo breaking changes in future versions. + + + + + Null for constructors. + + + + + The method arity can vary, i.e. the method has params array or params dict parameters. + + + + + Represents a method overload that is bound to a . + + + Not thread safe. + WARNING: This is a temporary API that will undergo breaking changes in future versions. + + + + + Maps out parameters to return args and ref parameters to ones that don't accept StrongBox. + + + + + ParameterWrapper represents the logical view of a parameter. For eg. the byref-reduced signature + of a method with byref parameters will be represented using a ParameterWrapper of the underlying + element type, since the logical view of the byref-reduced signature is that the argument will be + passed by value (and the updated value is included in the return value). + + Contrast this with ArgBuilder which represents the real physical argument passed to the method. + + + + + ParameterInfo is not available. + + + + + Creates a parameter that represents an expanded item of params-array. + + + + + True if the wrapper represents a params-array parameter (false for parameters created by expansion of a params-array). + + + + + True if the wrapper represents a params-dict parameter (false for parameters created by expansion of a params-dict). + + + + + Builds the parameter for a params dictionary argument - this collects all the extra name/value + pairs provided to the function into a SymbolDictionary which is passed to the function. + + + + + An argument that the user wants to explicitly pass by-reference (with copy-in copy-out semantics). + The user passes a StrongBox[T] object whose value will get updated when the call returns. + + + + + SimpleArgBuilder produces the value produced by the user as the argument value. It + also tracks information about the original parameter and is used to create extended + methods for params arrays and param dictionary functions. + + + + + Parameter info is not available for this argument. + + + + + Type and whether the parameter is a params-array or params-dictionary is derived from info. + + + + + True if there are restrictions beyond just simple type restrictions + + + + + Builds a parameter for a reference argument when a StrongBox has not been provided. The + updated return value is returned as one of the resulting return values. + + + + + Gets the generic arguments for method based upon the constraints discovered during + type inference. Returns null if not all generic arguments had their types inferred. + + + + + Creates a new set of arg builders for the given generic method definition which target the new + parameters. + + + + + Creates a new list of ParameterWrappers for the generic method replacing the old parameters with the new ones. + + + + + Gets the generic type arguments sorted so that the type arguments + that are depended upon by other type arguments are sorted before + their dependencies. + + + + + Checks to see if the x type parameter is dependent upon the y type parameter. + + + + + Builds a mapping based upon generic parameter constraints between related generic + parameters. This is then used to sort the generic parameters so that we can process + the least dependent parameters first. For example given the method: + + void Foo{T0, T1}(T0 x, T1 y) where T0 : T1 + + We need to first infer the type information for T1 before we infer the type information + for T0 so that we can ensure the constraints are correct. + + + + + Returns a mapping from generic type parameter to the input DMOs which map to it. + + + + + Adds any additional ArgumentInputs entries for the given object and parameter type. + + + + + Walks the nested generic hierarchy to construct all of the generic parameters referred + to by this type. For example if getting the generic parameters for the x parameter on + the method: + + void Foo{T0, T1}(Dictionary{T0, T1} x); + + We would add both typeof(T0) and typeof(T1) to the list of generic arguments. + + + + + Provides generic type inference for a single parameter. + + + For example: + M{T}(T x) + M{T}(IList{T} x) + M{T}(ref T x) + M{T}(T[] x) + M{T}(ref Dictionary{T,T}[] x) + + + + + Provides generic type inference for a single parameter. + + + For example: + M{T}(T x) + M{T}(IList{T} x) + M{T}(ref T x) + M{T}(T[] x) + M{T}(ref Dictionary{T,T}[] x) + + + + + Checks if the constraints are violated by the given input for the specified generic method parameter. + + This method must be supplied with a mapping for any dependent generic method type parameters which + this one can be constrained to. For example for the signature "void Foo{T0, T1}(T0 x, T1 y) where T0 : T1". + we cannot know if the constraints are violated unless we know what we have calculated T1 to be. + + + + + Finds all occurences of genericParameter in openType and the corresponding concrete types in closedType. + Returns true iff all occurences of the generic parameter in the open type correspond to the same concrete type in the closed type + and this type satisfies given constraints. Returns the concrete type in match if so. + + + + + Maps a single type parameter to the possible parameters and DynamicMetaObjects + we can get inference from. For example for the signature: + + void Foo{T0, T1}(T0 x, T1 y, IList{T1} z); + + We would have one ArgumentInput for T0 which holds onto the DMO providing the argument + value for x. We would also have one ArgumentInput for T1 which holds onto the 2 DMOs + for y and z. Associated with y would be a GenericParameterInferer and associated with + z would be a ConstructedParameterInferer. + + + + + Implemented by DynamicMetaObject subclasses when the associated object + can participate in generic method type inference. This interface + is used when the inference engine is attempting to perform type inference + for a parameter which is typed to a delegate type. + + + + + Returns the type inferred for parameterType when performing + inference for a conversion to delegateType. + + + + + Provides information about the result of a custom object which dynamically + infers back types. + + Currently only used for invokable objects to feedback the types for a delegate + type. + + + + + Determines the result of a conversion action. The result can either result in an exception, a value that + has been successfully converted or default(T), or a true/false result indicating if the value can be converted. + + + + + Attempts to perform available implicit conversions and throws if there are no available conversions. + + + + + Attempst to perform available implicit and explicit conversions and throws if there are no available conversions. + + + + + Attempts to perform available implicit conversions and returns default(ReturnType) if no conversions can be performed. + + If the return type of the rule is a value type then the return value will be zero-initialized. If the return type + of the rule is object or another class then the return type will be null (even if the conversion is to a value type). + This enables ImplicitTry to be used to do TryConvertTo even if the type is value type (and the difference between + null and a real value can be distinguished). + + + + + Attempts to perform available implicit and explicit conversions and returns default(ReturnType) if no conversions + can be performed. + + If the return type of the rule is a value type then the return value will be zero-initialized. If the return type + of the rule is object or another class then the return type will be null (even if the conversion is to a value type). + This enables ExplicitTry to be used to do TryConvertTo even if the type is value type (and the difference between + null and a real value can be distinguished). + + + + + Provides binding semantics for a language. This include conversions as well as support + for producing rules for actions. These optimized rules are used for calling methods, + performing operators, and getting members using the ActionBinder's conversion semantics. + + + + + Provides binding semantics for a language. This include conversions as well as support + for producing rules for actions. These optimized rules are used for calling methods, + performing operators, and getting members using the ActionBinder's conversion semantics. + + + + + Converts an object at runtime into the specified type. + + + + + Determines if a conversion exists from fromType to toType at the specified narrowing level. + toNotNullable is true if the target variable doesn't allow null values. + + + + + Provides ordering for two parameter types if there is no conversion between the two parameter types. + + + + + Converts the provided expression to the given type. The expression is safe to evaluate multiple times. + + + + + Gets the members that are visible from the provided type of the specified name. + + The default implemetnation first searches the type, then the flattened heirachy of the type, and then + registered extension methods. + + + + + Called when a set is attempting to assign to a field or property from a derived class through the base class. + + The default behavior is to allow the assignment. + + + + + Creates an ErrorInfo object when a static property is accessed from an instance member. The default behavior is throw + an exception indicating that static members properties be accessed via an instance. Languages can override this to + customize the exception, message, or to produce an ErrorInfo object which reads or writes to the property being accessed. + + The static property being accessed through an instance + True if the user is assigning to the property, false if the user is reading from the property + The parameters being used to access the property. This includes the instance as the first entry, any index parameters, and the + value being assigned as the last entry if isAssignment is true. + + + + + Provides a way for the binder to provide a custom error message when lookup fails. Just + doing this for the time being until we get a more robust error return mechanism. + + Deprecated, use the non-generic version instead + + + + + Gets the extension members of the given name from the provided type. Base classes are also + searched for their extension members. Once any of the types in the inheritance hierarchy + provide an extension member the search is stopped. + + + + + Gets the extension members of the given name from the provided type. Subclasses of the + type and their extension members are not searched. + + + + + Provides an opportunity for languages to replace all MemberTracker's with their own type. + + Alternatlely a language can expose MemberTracker's directly. + + The member which is being returned to the user. + Tthe type which the memberTrack was accessed from + + + + + Determines if the binder should allow access to non-public members. + + By default the binder does not allow access to non-public members. Base classes + can inherit and override this value to customize whether or not private binding + is available. + + + + + Creates the MetaObject for indexing directly into arrays or indexing into objects which have + default members. Returns null if we're not an indexing operation. + + + + + Creates the MetaObject for indexing directly into arrays or indexing into objects which have + default members. Returns null if we're not an indexing operation. + + + + + Creates the meta object for the rest of the operations: comparisons and all other + ExpressionType. If the operation cannot be completed a MetaObject which indicates an + error will be returned. + + + + + Creates the meta object for the rest of the operations: comparisons and all other + ExpressionType. If the operation cannot be completed a MetaObject which indicates an + error will be returned. + + + + + Produces a rule for comparing a value to null - supports comparing object references and nullable types. + + + + + Checks if the conversion is to object and produces a target if it is. + + + + + Checks if any conversions are available and if so builds the target for that conversion. + + + + + Checks if the conversion can be handled by a simple cast. + + + + + Checks if the conversion can be handled by calling a user-defined conversion method. + + + + + Helper that checkes both types to see if either one defines the specified conversion + method. + + + + + Checks if any of the members of the MemberGroup provide the applicable conversion and + if so uses it to build a conversion rule. + + + + + Checks if the conversion is to applicable by extracting the value from Extensible of T. + + + + + Checks if there's an implicit numeric conversion for primitive data types. + + + + + Checks if there's a conversion to/from Nullable of T. + + + + + Checks to see if there's a conversion of null to a reference type + + + + + Helper to produce an error when a conversion cannot occur + + + + + Helper to produce a rule which just boxes a value type + + + + + Helper to produce a conversion rule by calling the helper method to do the convert + + + + + Helper to produce a conversion rule by calling the helper method to do the convert + + + + + Helper to produce a conversion rule by calling the method to do the convert. This version takes the parameter + to be passed to the conversion function and we call it w/ our own value or w/ our Extensible.Value. + + + + + Helper to wrap explicit conversion call into try/catch incase it throws an exception. If + it throws the default value is returned. + + + + + Helper to produce a rule when no conversion is required (the strong type of the expression + input matches the type we're converting to or has an implicit conversion at the IL level) + + + + + Helper to produce a rule when no conversion is required from an extensible type's + underlying storage to the type we're converting to. The type of extensible type + matches the type we're converting to or has an implicit conversion at the IL level. + + + + + Helper to extract the value from an Extensible of T + + + + + Helper to convert a null value to nullable of T + + + + + Helper to produce the rule for converting T to Nullable of T + + + + + Helper to produce the rule for converting T to Nullable of T + + + + + Returns a value which indicates failure when a OldConvertToAction of ImplicitTry or + ExplicitTry. + + + + + Helper to extract the Value of an Extensible of T from the + expression being converted. + + + + + Helper that checks if fromType is an Extensible of T or a subtype of + Extensible of T and if so returns the T. Otherwise it returns fromType. + + This is used to treat extensible types the same as their underlying types. + + + + + Creates a target which returns null for a reference type. + + + + if a member-injector is defined-on or registered-for this type call it + + + + Builds a MetaObject for performing a member get. Supports all built-in .NET members, the OperatorMethod + GetBoundMember, and StrongBox instances. + + + The name of the member to retrieve. This name is not processed by the DefaultBinder and + is instead handed off to the GetMember API which can do name mangling, case insensitive lookups, etc... + + + The MetaObject from which the member is retrieved. + + + Returns a DynamicMetaObject which represents the value that will be returned when the member is accessed. + + The returned DynamicMetaObject may be strongly typed to a value type which needs boxing before being + returned from a standard DLR GetMemberBinder. The language is responsible for performing any boxing + so that it has an opportunity to perform custom boxing. + + + + + Builds a MetaObject for performing a member get. Supports all built-in .NET members, the OperatorMethod + GetBoundMember, and StrongBox instances. + + + The name of the member to retrieve. This name is not processed by the DefaultBinder and + is instead handed off to the GetMember API which can do name mangling, case insensitive lookups, etc... + + + The MetaObject from which the member is retrieved. + + + Provides overload resolution and method binding for any calls which need to be performed for the GetMember. + + + Returns a DynamicMetaObject which represents the value that will be returned when the member is accessed. + + The returned DynamicMetaObject may be strongly typed to a value type which needs boxing before being + returned from a standard DLR GetMemberBinder. The language is responsible for performing any boxing + so that it has an opportunity to perform custom boxing. + + + + + Builds a MetaObject for performing a member get. Supports all built-in .NET members, the OperatorMethod + GetBoundMember, and StrongBox instances. + + + The name of the member to retrieve. This name is not processed by the DefaultBinder and + is instead handed off to the GetMember API which can do name mangling, case insensitive lookups, etc... + + + The MetaObject from which the member is retrieved. + + + An OverloadResolverFactory which can be used for performing overload resolution and method binding. + + + True if the operation should return Operation.Failed on failure, false if it + should return the exception produced by MakeMissingMemberError. + + + The meta object to be used if the get results in an error. + + + Returns a DynamicMetaObject which represents the value that will be returned when the member is accessed. + + The returned DynamicMetaObject may be strongly typed to a value type which needs boxing before being + returned from a standard DLR GetMemberBinder. The language is responsible for performing any boxing + so that it has an opportunity to perform custom boxing. + + + + + Builds a MetaObject for performing a member get. Supports all built-in .NET members, the OperatorMethod + GetBoundMember, and StrongBox instances. + + + The name of the member to retrieve. This name is not processed by the DefaultBinder and + is instead handed off to the GetMember API which can do name mangling, case insensitive lookups, etc... + + + The MetaObject from which the member is retrieved. + + + True if the operation should return Operation.Failed on failure, false if it + should return the exception produced by MakeMissingMemberError. + + + The meta object to be used if the get results in an error. + + + Returns a DynamicMetaObject which represents the value that will be returned when the member is accessed. + + The returned DynamicMetaObject may be strongly typed to a value type which needs boxing before being + returned from a standard DLR GetMemberBinder. The language is responsible for performing any boxing + so that it has an opportunity to perform custom boxing. + + + + if a member-injector is defined-on or registered-for this type call it + + + + Provides default binding for performing a call on the specified meta objects. + + The signature describing the call + The meta object to be called. + + Additional meta objects are the parameters for the call as specified by the CallSignature in the CallAction. + + A MetaObject representing the call or the error. + + + + Provides default binding for performing a call on the specified meta objects. + + The signature describing the call + The meta object to be called. + + Additional meta objects are the parameters for the call as specified by the CallSignature in the CallAction. + + Overload resolver factory. + A MetaObject representing the call or the error. + + + + Provides default binding for performing a call on the specified meta objects. + + The signature describing the call + The meta object to be called. + + Additional meta objects are the parameters for the call as specified by the CallSignature in the CallAction. + + Overload resolver factory. + The result should the object be uncallable. + A MetaObject representing the call or the error. + + + + Gets a TargetInfo object for performing a call on this object. + + If this object is a delegate we bind to the Invoke method. + If this object is a MemberGroup or MethodGroup we bind to the methods in the member group. + If this object is a BoundMemberTracker we bind to the methods with the bound instance. + If the underlying type has defined an operator Call method we'll bind to that method. + + + + + Binds to the methods in a method group. + + + + + Binds to the methods in a member group. + + TODO: We should really only have either MemberGroup or MethodGroup, not both. + + + + + Binds to the BoundMemberTracker and uses the instance in the tracker and restricts + based upon the object instance type. + + + + + Binds to the Invoke method on a delegate if this is a delegate type. + + + + + Attempts to bind to an operator Call method. + + + + + Performs binding against a set of overloaded methods using the specified arguments. The arguments are + consumed as specified by the CallSignature object. + + Overload resolver. + The methods to be called + A meta object which results from the call. + + + + Performs binding against a set of overloaded methods using the specified arguments. The arguments are + consumed as specified by the CallSignature object. + + Overload resolver. + The methods to be called + The name of the method or null to use the name from targets. + A meta object which results from the call. + + + + Performs binding against a set of overloaded methods using the specified arguments. The arguments are + consumed as specified by the CallSignature object. + + Overload resolver. + The methods to be called + Additional restrictions which should be applied to the resulting MetaObject. + A meta object which results from the call. + + + + Performs binding against a set of overloaded methods using the specified arguments. The arguments are + consumed as specified by the CallSignature object. + + Overload resolver. + The methods to be called + Additional restrictions which should be applied to the resulting MetaObject. + The name of the method or null to use the name from targets. + A meta object which results from the call. + + + + Performs binding against a set of overloaded methods using the specified arguments. The arguments are + consumed as specified by the CallSignature object. + + TODO. + TODO. + Overload resolver. + The methods to be called + Additional restrictions which should be applied to the resulting MetaObject. + The resulting binding target which can be used for producing error information. + The name of the method or null to use the name from targets. + A meta object which results from the call. + + + + Makes test for param arrays and param dictionary parameters. + + + + + Pulls out the right argument to build the splat test. MakeParamsTest makes the actual test. + + + + + Builds the restrictions for calling with a splatted argument array. Ensures that the + argument is still an ICollection of object and that it has the same number of arguments. + + + + + Builds the restrictions for calling with keyword arguments. The restrictions include + tests on the individual keys of the dictionary to ensure they have the same names. + + + + + Builds a MetaObject for performing a member get. Supports all built-in .NET members, the OperatorMethod + GetBoundMember, and StrongBox instances. + + + The name of the member to retrieve. This name is not processed by the DefaultBinder and + is instead handed off to the GetMember API which can do name mangling, case insensitive lookups, etc... + + + The MetaObject from which the member is retrieved. + + + The value being assigned to the target member. + + + + + Builds a MetaObject for performing a member get. Supports all built-in .NET members, the OperatorMethod + GetBoundMember, and StrongBox instances. + + + The name of the member to retrieve. This name is not processed by the DefaultBinder and + is instead handed off to the GetMember API which can do name mangling, case insensitive lookups, etc... + + + The MetaObject from which the member is retrieved. + + + The value being assigned to the target member. + + + Provides overload resolution and method binding for any calls which need to be performed for the SetMember. + + + + + Builds a MetaObject for performing a member get. Supports all built-in .NET members, the OperatorMethod + GetBoundMember, and StrongBox instances. + + + The name of the member to retrieve. This name is not processed by the DefaultBinder and + is instead handed off to the GetMember API which can do name mangling, case insensitive lookups, etc... + + + The MetaObject from which the member is retrieved. + + + The value being assigned to the target member. + + + Provides a DynamicMetaObject that is to be used as the result if the member cannot be set. If null then then a language + specific error code is provided by ActionBinder.MakeMissingMemberErrorForAssign which can be overridden by the language. + + + + + Builds a MetaObject for performing a member get. Supports all built-in .NET members, the OperatorMethod + GetBoundMember, and StrongBox instances. + + + The name of the member to retrieve. This name is not processed by the DefaultBinder and + is instead handed off to the GetMember API which can do name mangling, case insensitive lookups, etc... + + + The MetaObject from which the member is retrieved. + + + The value being assigned to the target member. + + + Provides overload resolution and method binding for any calls which need to be performed for the SetMember. + + + Provides a DynamicMetaObject that is to be used as the result if the member cannot be set. If null then then a language + specific error code is provided by ActionBinder.MakeMissingMemberErrorForAssign which can be overridden by the language. + + + + if a member-injector is defined-on or registered-for this type call it + + + + Provides a way for the binder to provide a custom error message when lookup fails. Just + doing this for the time being until we get a more robust error return mechanism. + + + + + Called when the user is accessing a protected or private member on a get. + + The default implementation allows access to the fields or properties using reflection. + + + + + Provides a way for the binder to provide a custom error message when lookup fails. Just + doing this for the time being until we get a more robust error return mechanism. + + + + + Helper class for flowing information about the GetMember request. + + + + + Helper class for flowing information about the GetMember request. + + + + + Encapsulates information about the target of the call. This includes an implicit instance for the call, + the methods that we'll be calling as well as any restrictions required to perform the call. + + + + + A MetaObject which was produced as the result of a failed binding. + + + + + Interceptor prototype. The interceptor is a call site binder that wraps + a real call site binder and can perform arbitrary operations on the expression + trees that the wrapped binder produces: + * Dumping the trees + * Additional rewriting + * Static compilation + * ... + + + + + Returns true if the method should not be displayed in the stack frame. + + + + + Specifies the action for which the default binder is requesting a member. + + + + + If the number of items added to the builder is greater than 4 returns a read-only collection builder containing all the items. + Returns null otherwise. + + + + + Returns null if no expression was added into the builder. + If only a single expression was added returns it. + Otherwise returns a containing the expressions added to the builder. + + + + + Wrapping a tree in this node enables jumps from finally blocks + It does this by generating control-flow logic in the tree + + Reducing this node requires a full tree walk of its body + (but not nested lambdas) + + WARNING: this node cannot contain jumps across blocks, because it + assumes any unknown jumps are jumps to an outer scope. + + + + + Factory methods. + + + + + Determines whether specified expression type represents an assignment. + + + True if the expression type represents an assignment. + + + Note that some other nodes can also assign to variables, members or array items: + MemberInit, NewArrayInit, Call with ref params, New with ref params, Dynamic with ref params. + + + + + Determines if the left child of the given expression is read or written to or both. + + + + + Converts an expression to a void type. + + An to convert to void. + An that has the property equal to and the and property set to void. + + + + Returns an expression that boxes a given value. Uses boxed objects cache for Int32 and Boolean types. + + + + + Creates a generator with type IEnumerable{T}, where T is the label.Type + + + + + + + + Null coalescing expression + {result} ::= ((tmp = {_left}) == null) ? {right} : tmp + '??' operator in C#. + + + + + True coalescing expression. + {result} ::= IsTrue(tmp = {left}) ? {right} : tmp + Generalized AND semantics. + + + + + False coalescing expression. + {result} ::= IsTrue(tmp = {left}) ? tmp : {right} + Generalized OR semantics. + + + + + True coalescing expression. + {result} ::= IsTrue(tmp = {left}) ? {right} : tmp + Generalized AND semantics. + + + + + False coalescing expression. + {result} ::= IsTrue(tmp = {left}) ? tmp : {right} + Generalized OR semantics. + + + + + Wraps the given value in a WeakReference and returns a tree that will retrieve + the value from the WeakReference. + + + + + Creates new instance of the LambdaBuilder with the specified name and return type. + + Return type of the lambda being built. + Name for the lambda being built. + new LambdaBuilder instance + + + + The helper to create the AST method call node. Will add conversions (Utils.Convert) + to parameters and instance if necessary. + + + + + The helper to create the AST method call node. Will add conversions (Utils.Convert) + to parameters and instance if necessary. + + + + + The complex call helper to create the AST method call node. + Will add conversions (Expression.Convert()), deals with default parameter values and params arrays. + + + + + The purpose of this rewriter is simple: ETs do not allow jumps (break, continue, return, goto) + that would go through a finally/fault. So we replace them with code that instead stores a flag, + and then jumps to the end of the finally/fault. At the end of the try-finally, we emit a switch + that then jumps to the correct label. + + A few things that make this more complicated: + + 1. If a finally contains a jump out, then jumps in the try/catch need to be replaced as well. + It's to support cases like this: + # returns 234 + def foo(): + try: return 123 + finally: return 234 + + We need to replace the "return 123" because after it jumps, we'll go to the finally, which + might decide to jump again, but once the IL finally exits, it ignores the finally jump and + keeps going with the original jump. The moral of the story is: if any jumps in finally are + rewritten, try/catch jumps must be also. + + 2. To generate better code, we only have one state variable, so if we have to jump out of + multiple finallys we just keep jumping. It looks sort of like this: + foo: + try { ... } finally { + try { ... } finally { + ... + if (...) { + // was: goto foo; + $flow = 1; goto endInnerFinally; + } + ... + endInnerFinally: + } + switch ($flow) { + case 1: goto endOuterFinally; + } + ... + endOuterFinally: + } + switch ($flow) { + case 1: $flow = 0; goto foo; + } + ... + + + + + + Implemented by expressions which can provide a version which is aware of light exceptions. + + Normally these expressions will simply reduce to a version which throws a real exception. + When the expression is used inside of a region of code which supports light exceptions + the light exception re-writer will call ReduceForLightExceptions. The expression can + then return a new expression which can return a light exception rather than throwing + a real .NET exception. + + + + + Implemented by binders which support light exceptions. Dynamic objects + binding against a binder which implements this interface can check + SupportsLightThrow to see if the binder currently supports safely + returning a light exception. Light exceptions can be created with + LightException.Throw. + + Binders also need to implement GetlightBinder. This method + returns a new call site binder which may return light exceptions if + the binder supports them. + + + + + Gets a binder which will support light exception if one is + available. + + + + + Returns true if a callsite binding against this binder can + return light exceptions. + + + + + Provides a method call to a method which may return light exceptions. + + The call is to a method which supports light exceptions. When reducing + an additional check and throw is added. When a block code of is re-written + for light exceptions this instead reduces to not throw a .NET exception. + + + + + Expression which produces a light exception value. This should be constructed + with the expression which creates the exception and this method will then call + a helper method which wraps the exception in our internal light exception class. + + + + + Used by compilers to provide additional debug information about LambdaExpression to DebugContext + + + + + Implemented by compilers to allow the traceback engine to get additional information. + + + + + Provides services to compilers for instrumenting code with tracebacks. + + + + + Creates a new instance of DebugContext + + + + + Transforms a LambdaExpression to a debuggable LambdaExpression + + + + + Transforms a LambdaExpression to a debuggable LambdaExpression + + + + + Resets a state associated with a source file that's maintained in the DebugContext + + + + + Threads + + + + + Hook + + + + + // This method is called from the generator to update the frame with generator's locals + + + + + Remaps the frame's state to use the generator for execution. + + Int32.MaxValue to map to latest version + + + + Thread + + + + + FrameOrder + + + + + Variables + + + + + CurrentSequencePointIndex + + + + + DebuggableLambdaBuilder is used to transform a DLR expression tree into a debuggable lambda expression. + + + + + Used to wrap a lambda that was already a generator prior to transform. + + + + + Used to rewrite expressions containing DebugInfoExpressions. + + + + + Combines source file and span. Also provides Contains and Intersects functionality. + + + + + Implementation of IDebugRuntimeVariables, which wraps IRuntimeVariables + FunctionInfo/DebugMarker + + + + + IDebugRuntimeVariables is used to wrap IRuntimeVariables and add properties for retrieving + FunctionInfo and DebugMarker from debuggable labmdas. + + + + + Default implementation of BaseDebugThread, which uses DLR's RuntimeVariablesExpression for lifting locals. + + + + + Default implementation of IDebugThreadFactory, which uses DLR's RuntimeVariablesExpression for lifting locals. + + + + + IDebugThreadFactory is used to abstract how frames and local variables are maintained at run/debug time. + + + + + GetTraceLocations + + + + + + SequencePoints + + + + + Name + + + + + CustomPayload + + + + + Callback that is fired by the traceback engine + + + + + Used to extract locals information from expressions. + + + + + Strongly-typed and parameterized string factory. + + + + + Implements IRuntimeVariables in a way that preserves scoping within the lambda. + + + + + TraceSession + + + + + Used to provide information about locals/parameters at debug time. + + + + + Type + + + + + Name + + + + + Parameter + + + + + Caches type member lookup. + + + When enumerating members (methods, properties, events) of a type (declared or inherited) Reflection enumerates all + runtime members of the type and its base types and caches the result. + When looking for a member of a specific name Reflection still enumerates all and filters out those that don't match the name. + That's inefficient when looking for members of multiple names one by one. + Instead we build a map of name to member list and then answer subsequent queries by simply looking up the dictionary. + + + + + Marks a method which may return a light exception. Such + methods need to have their return value checked and the exception + will need to be thrown if the caller is not light exception aware. + + + + + Internal re-writer class which creates code which is light exception aware. + + + + + Adds light exception handling to the provided expression which + is light exception aware. + + + + + Class used to be avoid overhead of creating expression trees when we're usually + + + + + Provides support for light exceptions. These exceptions are propagated by + returning an instance of a private wrapper class containing the exception. Code + which is aware of light exceptions will branch to apporiate exception handling + blocks when in a try and otherwise return the value up the stack. This avoids + using the underlying CLR exception mechanism with overhead such as creating stack + traces. + + When a light exception reaches the boundary of code which is not light exception + aware the caller must check to see if a light exception is being thrown and if + so raise a .NET exception. + + This class provides methods for re-writing expression trees to support light exceptions, + methods to create light throw objects, check if an object is a light + throw object, and turn such an object back into a .NET Exception which can be thrown. + + Light exceptions also don't build up stack traces or interoperate with filter blocks + via 2-pass exception handling. + + + + + Rewrites the provided expression to support light exceptions. + + Calls to the returned expression, if not from other light-weight aware calls, + need to call GetLightException on return to see if an exception was thrown + and if so throw it. + + + + + Returns a new expression which will lazily reduce to a light + expression re-written version of the same expression. + + + + + Returns a new expression which is re-written for light exceptions + but will throw an exception if it escapes the expression. If this + expression is part of a larger experssion which is later re-written + for light exceptions then it will propagate the light exception up. + + + + + Returns an object which represents a light exception. + + + + + Returns an object which represents a light exception. + + + + + Returns an object which represents a light exception. + + + + + If the binder supports light exceptions then a light exception throwing expression is returned. + + Otherwise a normal throwing expression is returned. + + + + + If the binder supports light exceptions then a light exception throwing expression is returned. + + Otherwise a normal throwing expression is returned. + + + + + Throws the exception if the value represents a light exception + + + + + Wraps the expression in a check and rethrow. + + + + + Checks to see if the provided value is a light exception. + + + + + Gets the light exception from an object which may contain a light + exception. Returns null if the object is not a light exception. + + Used for throwing the exception at non-light exception boundaries. + + + + + Returns true if the call site binder is a light exception binder and supports + light throws. Returns false otherwise. + + + + + + + Sealed wrapper class to indicate something is a light exception. + + + + + Stores information needed to emit debugging symbol information for a + source file, in particular the file name and unique language identifier + + + + + The source file name + + + + + Returns the language's unique identifier, if any + + + + + Returns the language vendor's unique identifier, if any + + + + + ArgBuilder provides an argument value used by the MethodBinder. One ArgBuilder exists for each + physical parameter defined on a method. + + Contrast this with ParameterWrapper which represents the logical argument passed to the method. + + + + + Provides the Expression which provides the value to be passed to the argument. + + + + + Provides the Expression which provides the value to be passed to the argument. + This method is called when result is intended to be used ByRef. + + + + + Provides an Expression which will update the provided value after a call to the method. + May return null if no update is required. + + + + + SimpleArgBuilder produces the value produced by the user as the argument value. It + also tracks information about the original parameter and is used to create extended + methods for params arrays and param dictionary functions. + + + + + Provides the implementation of performing AddAssign and SubtractAssign binary operations. + + The binder provided by the call site. + The handler for the operation. + The result of the operation. + true if the operation is complete, false if the call site should determine behavior. + + + + Adds a handler to an event. + + The handler to be added. + The original event with handler added. + + + + Removes handler from the event. + + The handler to be removed. + The original event with handler removed. + + + + Provides helper methods to bind COM objects dynamically. + + + + + Determines if an object is a COM object. + + The object to test. + true if the object is a COM object, false otherwise. + + + + Tries to perform binding of the dynamic get member operation. + + An instance of the that represents the details of the dynamic operation. + The target of the dynamic operation. + The new representing the result of the binding. + true if member evaluation may be delayed. + true if operation was bound successfully; otherwise, false. + + + + Tries to perform binding of the dynamic get member operation. + + An instance of the that represents the details of the dynamic operation. + The target of the dynamic operation. + The new representing the result of the binding. + true if operation was bound successfully; otherwise, false. + + + + Tries to perform binding of the dynamic set member operation. + + An instance of the that represents the details of the dynamic operation. + The target of the dynamic operation. + The representing the value for the set member operation. + The new representing the result of the binding. + true if operation was bound successfully; otherwise, false. + + + + Tries to perform binding of the dynamic invoke operation. + + An instance of the that represents the details of the dynamic operation. + The target of the dynamic operation. + An array of instances - arguments to the invoke member operation. + The new representing the result of the binding. + true if operation was bound successfully; otherwise, false. + + + + Tries to perform binding of the dynamic invoke member operation. + + An instance of the that represents the details of the dynamic operation. + The target of the dynamic operation. + An array of instances - arguments to the invoke member operation. + The new representing the result of the binding. + true if operation was bound successfully; otherwise, false. + + + + Tries to perform binding of the dynamic get index operation. + + An instance of the that represents the details of the dynamic operation. + The target of the dynamic operation. + An array of instances - arguments to the invoke member operation. + The new representing the result of the binding. + true if operation was bound successfully; otherwise, false. + + + + Tries to perform binding of the dynamic set index operation. + + An instance of the that represents the details of the dynamic operation. + The target of the dynamic operation. + An array of instances - arguments to the invoke member operation. + The representing the value for the set index operation. + The new representing the result of the binding. + true if operation was bound successfully; otherwise, false. + + + + Tries to perform binding of the dynamic Convert operation. + + An instance of the that represents the details of the dynamic operation. + The target of the dynamic operation. + The new representing the result of the binding. + true if operation was bound successfully; otherwise, false. + + + + Gets the member names associated with the object. + This function can operate only with objects for which returns true. + + The object for which member names are requested. + The collection of member names. + + + + Gets the member names of the data-like members associated with the object. + This function can operate only with objects for which returns true. + + The object for which member names are requested. + The collection of member names. + + + + Gets the data-like members and associated data for an object. + This function can operate only with objects for which returns true. + + The object for which data members are requested. + The enumeration of names of data members for which to retrieve values. + The collection of pairs that represent data member's names and their data. + + + + Special binder that indicates special semantics for COM GetMember operation. + + + + + This class implements an event sink for a particular RCW. + Unlike the implementation of events in TlbImp'd assemblies, + we will create only one event sink per RCW (theoretically RCW might have + several ComEventSink evenk sinks - but all these implement different source intefaces). + Each ComEventSink contains a list of ComEventSinkMethod objects - which represent + a single method on the source interface an a multicast delegate to redirect + the calls. Notice that we are chaining multicast delegates so that same + ComEventSinkMedhod can invoke multiple event handlers). + + ComEventSink implements an IDisposable pattern to Unadvise from the connection point. + Typically, when RCW is finalized the corresponding Dispose will be triggered by + ComEventSinksContainer finalizer. Notice that lifetime of ComEventSinksContainer + is bound to the lifetime of the RCW. + + + + + Contains a methods DISPID (in a string formatted of "[DISPID=N]" + and a chained list of delegates to invoke + + + + + ComEventSinkProxy class is responsible for handling QIs for sourceIid + on instances of ComEventSink. + + Background: When a COM even sink advises to a connection point it is + supposed to hand over the dispinterface. Now, some hosts will trust + the COM client to pass the correct pointer, but some will not. + E.g. Excel's implementation of Connection Points will not cause a + QI on the pointer that has been passed, however Word will QI the + pointer to return the required interface. + + ComEventSink does not, strongly speaking, implements the interface + that it claims to implement - it is just "faking" it by using IReflect. + Thus, Word's QIs on the pointer passed to ICP::Advise would fail. To + prevent this we take advangate of RealProxy's ability of + "dressing up" like other classes and hence successfully respond to QIs + for interfaces that it does not really support( it is OK to say + "I implement this interface" for event sinks only since the common + practice is to use IDistpach.Invoke when calling into event sinks). + + + + + ComEventSinksContainer is just a regular list with a finalizer. + This list is usually attached as a custom data for RCW object and + is finalized whenever RCW is finalized. + + + + + Layout of the IDispatch vtable + + + + + Invokes the object. If it falls back, just produce an error. + + + + + Splats the arguments to another nested dynamic site, which does the + real invocation of the IDynamicMetaObjectProvider. + + + + + Create a stub for the target of the optimized lopop. + + + + + + Gets expressions to access all the arguments. This includes the instance argument. + + + + + This is a helper class for runtime-callable-wrappers of COM instances. We create one instance of this type + for every generic RCW instance. + + + + + The runtime-callable wrapper + + + + + This is the factory method to get the ComObject corresponding to an RCW + + + + + + The parameter description of a method defined in a type library + + + + + Creates a representation for the paramter of a COM method + + + + + Creates a representation for the return value of a COM method + TODO: Return values should be represented by a different type + + + + + DBNull.Value if there is no default value + + + + + Look for typeinfo using IDispatch.GetTypeInfo + + + + Some COM objects just dont expose typeinfo. In these cases, this method will return null. + Some COM objects do intend to expose typeinfo, but may not be able to do so if the type-library is not properly + registered. This will be considered as acceptable or as an error condition depending on throwIfMissingExpectedTypeInfo + + + + + This method should be called when typeinfo is not available for an object. The function + will check if the typeinfo is expected to be missing. This can include error cases where + the same error is guaranteed to happen all the time, on all machines, under all circumstances. + In such cases, we just have to operate without the typeinfo. + + However, if accessing the typeinfo is failing in a transient way, we might want to throw + an exception so that we will eagerly predictably indicate the problem. + + + + + This class contains methods that either cannot be expressed in C#, or which require writing unsafe code. + Callers of these methods need to use them extremely carefully as incorrect use could cause GC-holes + and other problems. + + + + + + Ensure that "value" is a local variable in some caller's frame. So converting + the byref to an IntPtr is a safe operation. Alternatively, we could also allow + allowed "value" to be a pinned object. + + + + + We will emit an indirect call to an unmanaged function pointer from the vtable of the given interface pointer. + This approach can take only ~300 instructions on x86 compared with ~900 for Marshal.Release. We are relying on + the JIT-compiler to do pinvoke-stub-inlining and calling the pinvoke target directly. + + + + + We will emit an indirect call to an unmanaged function pointer from the vtable of the given IDispatch interface pointer. + It is not possible to express this in C#. Using an indirect pinvoke call allows us to do our own marshalling. + We can allocate the Variant arguments cheaply on the stack. We are relying on the JIT-compiler to do + pinvoke-stub-inlining and calling the pinvoke target directly. + The alternative of calling via a managed interface declaration of IDispatch would have a performance + penalty of going through a CLR stub that would have to re-push the arguments on the stack, etc. + Marshal.GetDelegateForFunctionPointer could be used here, but its too expensive (~2000 instructions on x86). + + + + + Cached information from a TLB. Only information that is required is saved. CoClasses are used + for event hookup. Enums are stored for accessing symbolic names from scripts. + + + + + Reads the latest registered type library for the corresponding GUID, + reads definitions of CoClass'es and Enum's from this library + and creates a IDynamicMetaObjectProvider that allows to instantiate coclasses + and get actual values for the enums. + + Type Library Guid + ComTypeLibDesc object + + + + Gets an ITypeLib object from OLE Automation compatible RCW , + reads definitions of CoClass'es and Enum's from this library + and creates a IDynamicMetaObjectProvider that allows to instantiate coclasses + and get actual values for the enums. + + OLE automation compatible RCW + ComTypeLibDesc object + + + + This represents a bound dispmember on a IDispatch object. + + + + + Strongly-typed and parameterized string factory. + + + Strongly-typed and parameterized string factory. + + + + + A string like "Unexpected VarEnum {0}." + + + + + A string like "Error while invoking {0}." + + + + + A string like "Error while invoking {0}." + + + + + A string like "Error while invoking {0}. Named arguments are not supported." + + + + + A string like "Error while invoking {0}." + + + + + A string like "Could not convert argument {0} for call to {1}." + + + + + A string like "Error while invoking {0}. A required parameter was omitted." + + + + + A string like "IDispatch::GetIDsOfNames behaved unexpectedly for {0}." + + + + + A string like "Could not get dispatch ID for {0} (error: {1})." + + + + + A string like "There are valid conversions from {0} to {1}." + + + + + A string like "Variant.GetAccessor cannot handle {0}." + + + + + A string like "Cannot access member {1} declared on type {0} because the type contains generic parameters." + + + + + A string like "Type '{0}' is missing or cannot be loaded." + + + + + A string like "static property "{0}" of "{1}" can only be read through a type, not an instance" + + + + + A string like "static property "{0}" of "{1}" can only be assigned to through a type, not an instance" + + + + + A string like "Type parameter is {0}. Expected a delegate." + + + + + A string like "Cannot cast from type '{0}' to type '{1}" + + + + + A string like "unknown member type: '{0}'. " + + + + + A string like "The operation requires a non-generic type for {0}, but this represents generic types only" + + + + + A string like "Invalid operation: '{0}'" + + + + + A string like "Cannot create default value for type {0}." + + + + + A string like "Unhandled convert: {0}" + + + + + A string like "{0}.{1} has no publiclly visible method." + + + + + A string like "Extension type {0} must be public." + + + + + A string like "Invalid type of argument {0}; expecting {1}." + + + + + A string like "Field {0} is read-only" + + + + + A string like "Property {0} is read-only" + + + + + A string like "Expected event from {0}.{1}, got event from {2}.{3}." + + + + + A string like "expected bound event, got {0}." + + + + + A string like "Expected type {0}, got {1}." + + + + + A string like "can only write to member {0}." + + + + + A string like "Invalid stream type: {0}." + + + + + A string like "can't add another casing for identifier {0}" + + + + + A string like "can't add new identifier {0}" + + + + + A string like "Type '{0}' doesn't provide a suitable public constructor or its implementation is faulty: {1}" + + + + + A string like "Cannot emit constant {0} ({1})" + + + + + A string like "No implicit cast from {0} to {1}" + + + + + A string like "No explicit cast from {0} to {1}" + + + + + A string like "name '{0}' not defined" + + + + + A string like "Cannot create instance of {0} because it contains generic parameters" + + + + + A string like "Non-verifiable assembly generated: {0}:\nAssembly preserved as {1}\nError text:\n{2}\n" + + + + + A string like "COM object is expected." + + + + + A string like "Cannot perform call." + + + + + A string like "COM object does not support events." + + + + + A string like "COM object does not support specified source interface." + + + + + A string like "Marshal.SetComObjectData failed." + + + + + A string like "This method exists only to keep the compiler happy." + + + + + A string like "ResolveComReference.CannotRetrieveTypeInformation." + + + + + A string like "Attempting to wrap an unsupported enum type." + + + + + A string like "Attempting to pass an event handler of an unsupported type." + + + + + A string like "Method precondition violated" + + + + + A string like "Invalid argument value" + + + + + A string like "Non-empty string required" + + + + + A string like "Non-empty collection required" + + + + + A string like "must by an Exception instance" + + + + + A string like "Type of test must be bool" + + + + + A string like "Type of the expression must be bool" + + + + + A string like "Empty string is not a valid path." + + + + + A string like "Invalid delegate type (Invoke method not found)." + + + + + A string like "expected only static property" + + + + + A string like "Property doesn't exist on the provided type" + + + + + A string like "Field doesn't exist on provided type" + + + + + A string like "Type doesn't have constructor with a given signature" + + + + + A string like "Type doesn't have a method with a given name." + + + + + A string like "Type doesn't have a method with a given name and signature." + + + + + A string like "Count must be non-negative." + + + + + A string like "arrayType must be an array type" + + + + + A string like "Either code or target must be specified." + + + + + A string like "RuleBuilder can only be used with delegates whose first argument is CallSite." + + + + + A string like "no instance for call." + + + + + A string like "Missing Test." + + + + + A string like "Missing Target." + + + + + A string like "Finally already defined." + + + + + A string like "Can not have fault and finally." + + + + + A string like "Fault already defined." + + + + + A string like "Global/top-level local variable names must be unique." + + + + + A string like "Generating code from non-serializable CallSiteBinder." + + + + + A string like "pecified path is invalid." + + + + + A string like "Dictionaries are not hashable." + + + + + A string like "language already registered." + + + + + A string like "The method or operation is not implemented." + + + + + A string like "No exception." + + + + + A string like "Already initialized." + + + + + A string like "CreateScopeExtension must return a scope extension." + + + + + A string like "Invalid number of parameters for the service." + + + + + A string like "Cannot change non-caching value." + + + + + A string like "No code to compile." + + + + + A string like "Queue empty." + + + + + A string like "Enumeration has not started. Call MoveNext." + + + + + A string like "Enumeration already finished." + + + + + A string like "Invalid output directory." + + + + + A string like "Invalid assembly name or file extension." + + + + + A string like "No default value for a given type." + + + + + A string like "Specified language provider type is not registered." + + + + + A string like "can't read from property" + + + + + A string like "can't write to property" + + + + + Strongly-typed and parameterized exception factory. + + + Strongly-typed and parameterized exception factory. + + + + + ArgumentException with message like "COM object does not support events." + + + + + ArgumentException with message like "COM object does not support specified source interface." + + + + + InvalidOperationException with message like "Marshal.SetComObjectData failed." + + + + + InvalidOperationException with message like "This method exists only to keep the compiler happy." + + + + + InvalidOperationException with message like "Unexpected VarEnum {0}." + + + + + System.Reflection.TargetParameterCountException with message like "Error while invoking {0}." + + + + + MissingMemberException with message like "Error while invoking {0}." + + + + + ArgumentException with message like "Error while invoking {0}. Named arguments are not supported." + + + + + OverflowException with message like "Error while invoking {0}." + + + + + ArgumentException with message like "Could not convert argument {0} for call to {1}." + + + + + ArgumentException with message like "Error while invoking {0}. A required parameter was omitted." + + + + + InvalidOperationException with message like "ResolveComReference.CannotRetrieveTypeInformation." + + + + + ArgumentException with message like "IDispatch::GetIDsOfNames behaved unexpectedly for {0}." + + + + + InvalidOperationException with message like "Attempting to wrap an unsupported enum type." + + + + + InvalidOperationException with message like "Attempting to pass an event handler of an unsupported type." + + + + + MissingMemberException with message like "Could not get dispatch ID for {0} (error: {1})." + + + + + System.Reflection.AmbiguousMatchException with message like "There are valid conversions from {0} to {1}." + + + + + NotImplementedException with message like "Variant.GetAccessor cannot handle {0}." + + + + + ArgumentException with message like "Either code or target must be specified." + + + + + InvalidOperationException with message like "Type parameter is {0}. Expected a delegate." + + + + + InvalidOperationException with message like "Cannot cast from type '{0}' to type '{1}" + + + + + InvalidOperationException with message like "unknown member type: '{0}'. " + + + + + InvalidOperationException with message like "RuleBuilder can only be used with delegates whose first argument is CallSite." + + + + + InvalidOperationException with message like "no instance for call." + + + + + InvalidOperationException with message like "Missing Test." + + + + + InvalidOperationException with message like "Missing Target." + + + + + TypeLoadException with message like "The operation requires a non-generic type for {0}, but this represents generic types only" + + + + + ArgumentException with message like "Invalid operation: '{0}'" + + + + + InvalidOperationException with message like "Finally already defined." + + + + + InvalidOperationException with message like "Can not have fault and finally." + + + + + InvalidOperationException with message like "Fault already defined." + + + + + ArgumentException with message like "Cannot create default value for type {0}." + + + + + ArgumentException with message like "Unhandled convert: {0}" + + + + + InvalidOperationException with message like "{0}.{1} has no publiclly visible method." + + + + + ArgumentException with message like "Global/top-level local variable names must be unique." + + + + + ArgumentException with message like "Generating code from non-serializable CallSiteBinder." + + + + + ArgumentException with message like "pecified path is invalid." + + + + + ArgumentTypeException with message like "Dictionaries are not hashable." + + + + + InvalidOperationException with message like "language already registered." + + + + + NotImplementedException with message like "The method or operation is not implemented." + + + + + InvalidOperationException with message like "No exception." + + + + + ArgumentException with message like "Extension type {0} must be public." + + + + + InvalidOperationException with message like "Already initialized." + + + + + InvalidImplementationException with message like "CreateScopeExtension must return a scope extension." + + + + + ArgumentException with message like "Invalid number of parameters for the service." + + + + + ArgumentException with message like "Invalid type of argument {0}; expecting {1}." + + + + + ArgumentException with message like "Cannot change non-caching value." + + + + + MissingMemberException with message like "Field {0} is read-only" + + + + + MissingMemberException with message like "Property {0} is read-only" + + + + + ArgumentException with message like "Expected event from {0}.{1}, got event from {2}.{3}." + + + + + ArgumentTypeException with message like "expected bound event, got {0}." + + + + + ArgumentTypeException with message like "Expected type {0}, got {1}." + + + + + MemberAccessException with message like "can only write to member {0}." + + + + + InvalidOperationException with message like "No code to compile." + + + + + ArgumentException with message like "Invalid stream type: {0}." + + + + + InvalidOperationException with message like "Queue empty." + + + + + InvalidOperationException with message like "Enumeration has not started. Call MoveNext." + + + + + InvalidOperationException with message like "Enumeration already finished." + + + + + InvalidOperationException with message like "can't add another casing for identifier {0}" + + + + + InvalidOperationException with message like "can't add new identifier {0}" + + + + + ArgumentException with message like "Invalid output directory." + + + + + ArgumentException with message like "Invalid assembly name or file extension." + + + + + ArgumentException with message like "Cannot emit constant {0} ({1})" + + + + + ArgumentException with message like "No implicit cast from {0} to {1}" + + + + + ArgumentException with message like "No explicit cast from {0} to {1}" + + + + + MissingMemberException with message like "name '{0}' not defined" + + + + + ArgumentException with message like "No default value for a given type." + + + + + ArgumentException with message like "Specified language provider type is not registered." + + + + + InvalidOperationException with message like "can't read from property" + + + + + InvalidOperationException with message like "can't write to property" + + + + + ArgumentException with message like "Cannot create instance of {0} because it contains generic parameters" + + + + + System.Security.VerificationException with message like "Non-verifiable assembly generated: {0}:\nAssembly preserved as {1}\nError text:\n{2}\n" + + + + + This is similar to ComTypes.EXCEPINFO, but lets us do our own custom marshaling + + + + + An object that implements IDispatch + + This currently has the following issues: + 1. If we prefer ComObjectWithTypeInfo over IDispatchComObject, then we will often not + IDispatchComObject since implementations of IDispatch often rely on a registered type library. + If we prefer IDispatchComObject over ComObjectWithTypeInfo, users get a non-ideal experience. + 2. IDispatch cannot distinguish between properties and methods with 0 arguments (and non-0 + default arguments?). So obj.foo() is ambiguous as it could mean invoking method foo, + or it could mean invoking the function pointer returned by property foo. + We are attempting to find whether we need to call a method or a property by examining + the ITypeInfo associated with the IDispatch. ITypeInfo tell's use what parameters the method + expects, is it a method or a property, what is the default property of the object, how to + create an enumerator for collections etc. + 3. IronPython processes the signature and converts ref arguments into return values. + However, since the signature of a DispMethod is not available beforehand, this conversion + is not possible. There could be other signature conversions that may be affected. How does + VB6 deal with ref arguments and IDispatch? + + We also support events for IDispatch objects: + Background: + COM objects support events through a mechanism known as Connect Points. + Connection Points are separate objects created off the actual COM + object (this is to prevent circular references between event sink + and event source). When clients want to sink events generated by + COM object they would implement callback interfaces (aka source + interfaces) and hand it over (advise) to the Connection Point. + + Implementation details: + When IDispatchComObject.TryGetMember request is received we first check + whether the requested member is a property or a method. If this check + fails we will try to determine whether an event is requested. To do + so we will do the following set of steps: + 1. Verify the COM object implements IConnectionPointContainer + 2. Attempt to find COM object's coclass's description + a. Query the object for IProvideClassInfo interface. Go to 3, if found + b. From object's IDispatch retrieve primary interface description + c. Scan coclasses declared in object's type library. + d. Find coclass implementing this particular primary interface + 3. Scan coclass for all its source interfaces. + 4. Check whether to any of the methods on the source interfaces matches + the request name + + Once we determine that TryGetMember requests an event we will return + an instance of BoundDispEvent class. This class has InPlaceAdd and + InPlaceSubtract operators defined. Calling InPlaceAdd operator will: + 1. An instance of ComEventSinksContainer class is created (unless + RCW already had one). This instance is hanged off the RCW in attempt + to bind the lifetime of event sinks to the lifetime of the RCW itself, + meaning event sink will be collected once the RCW is collected (this + is the same way event sinks lifetime is controlled by PIAs). + Notice: ComEventSinksContainer contains a Finalizer which will go and + unadvise all event sinks. + Notice: ComEventSinksContainer is a list of ComEventSink objects. + 2. Unless we have already created a ComEventSink for the required + source interface, we will create and advise a new ComEventSink. Each + ComEventSink implements a single source interface that COM object + supports. + 3. ComEventSink contains a map between method DISPIDs to the + multicast delegate that will be invoked when the event is raised. + 4. ComEventSink implements IReflect interface which is exposed as + custom IDispatch to COM consumers. This allows us to intercept calls + to IDispatch.Invoke and apply custom logic - in particular we will + just find and invoke the multicast delegate corresponding to the invoked + dispid. + + + + + ArgBuilder which always produces null. + + + + + If a managed user type (as opposed to a primitive type or a COM object) is passed as an argument to a COM call, we need + to determine the VarEnum type we will marshal it as. We have the following options: + 1. Raise an exception. Languages with their own version of primitive types would not be able to call + COM methods using the language's types (for eg. strings in IronRuby are not System.String). An explicit + cast would be needed. + 2. We could marshal it as VT_DISPATCH. Then COM code will be able to access all the APIs in a late-bound manner, + but old COM components will probably malfunction if they expect a primitive type. + 3. We could guess which primitive type is the closest match. This will make COM components be as easily + accessible as .NET methods. + 4. We could use the type library to check what the expected type is. However, the type library may not be available. + + VarEnumSelector implements option # 3 + + + + + Gets the managed type that an object needs to be coverted to in order for it to be able + to be represented as a Variant. + + In general, there is a many-to-many mapping between Type and VarEnum. However, this method + returns a simple mapping that is needed for the current implementation. The reason for the + many-to-many relation is: + 1. Int32 maps to VT_I4 as well as VT_ERROR, and Decimal maps to VT_DECIMAL and VT_CY. However, + this changes if you throw the wrapper types into the mix. + 2. There is no Type to represent COM types. __ComObject is a private type, and Object is too + general. + + + + + Creates a family of COM types such that within each family, there is a completely non-lossy + conversion from a type to an earlier type in the family. + + + + + Get the (one representative type for each) primitive type families that the argument can be converted to + + + + + If there is more than one type family that the argument can be converted to, we will throw a + AmbiguousMatchException instead of randomly picking a winner. + + + + + Is there a unique primitive type that has the best conversion for the argument + + + + + Get the COM Variant type that argument should be marshaled as for a call to COM + + + + + Variant is the basic COM type for late-binding. It can contain any other COM data type. + This type definition precisely matches the unmanaged data layout so that the struct can be passed + to and from COM calls. + + + + + Primitive types are the basic COM types. It includes valuetypes like ints, but also reference types + like BStrs. It does not include composite types like arrays and user-defined COM types (IUnknown/IDispatch). + + + + + Get the managed object representing the Variant. + + + + + + Release any unmanaged memory associated with the Variant + + + + + + VariantBuilder handles packaging of arguments into a Variant for a call to IDispatch.Invoke + + + + + Provides a simple expression which enables embedding FieldBuilder's + in an AST before the type is complete. + + + + + Used to dispatch a single interactive command. It can be used to control things like which Thread + the command is executed on, how long the command is allowed to execute, etc + + + + + Supports detecting the remote runtime being killed, and starting up a new one. + + Threading model: + + ConsoleRestartManager creates a separate thread on which to create and execute the consoles. + There are usually atleast three threads involved: + + 1. Main app thread: Instantiates ConsoleRestartManager and accesses its APIs. This thread has to stay + responsive to user input and so the ConsoleRestartManager APIs cannot be long-running or blocking. + Since the remote runtime process can terminate asynchronously, the current RemoteConsoleHost can + change at any time (if auto-restart is enabled). The app should typically not care which instance of + RemoteConsoleHost is currently being used. The flowchart of this thread is: + Create ConsoleRestartManager + ConsoleRestartManager.Start + Loop: + Respond to user input | Send user input to console for execution | BreakExecution | RestartConsole | GetMemberNames + ConsoleRestartManager.Terminate + TODO: Currently, BreakExecution and GetMemberNames are called by the main thread synchronously. + Since they execute code in the remote runtime, they could take arbitrarily long. We should change + this so that the main app thread can never be blocked indefinitely. + + 2. Console thread: Dedicated thread for creating RemoteConsoleHosts and executing code (which could + take a long time or block indefinitely). + Wait for ConsoleRestartManager.Start to be called + Loop: + Create RemoteConsoleHost + Wait for signal for: + Execute code | RestartConsole | Process.Exited + + 3. CompletionPort async callbacks: + Process.Exited | Process.OutputDataReceived | Process.ErrorDataReceived + + 4. Finalizer thred + Some objects may have a Finalize method (which possibly calls Dispose). Not many (if any) types + should have a Finalize method. + + + + + + Accessing _remoteConsoleHost from a thread other than console thread can result in race. + If _remoteConsoleHost is accessed while holding _accessLock, it is guaranteed to be + null or non-disposed. + + + + + This is created on the "creating thread", and goes on standby. Start needs to be called for activation. + + A host might want one of two behaviors: + 1. Keep the REPL loop alive indefinitely, even when a specific instance of the RemoteConsoleHost terminates normally + 2. Close the REPL loop when an instance of the RemoteConsoleHost terminates normally, and restart the loop + only if the instance terminates abnormally. + + + + Needs to be called for activation. + + + + + Request (from another thread) the console REPL loop to terminate + + + + + This allows the RemoteConsoleHost to abort a long-running operation. The RemoteConsoleHost itself + does not know which ThreadPool thread might be processing the remote call, and so it needs + cooperation from the remote runtime server. + + + + + Since OnOutputDataReceived is sent async, it can arrive late. The remote console + cannot know if all output from the current command has been received. So + RemoteCommandDispatcher writes out a marker to indicate the end of the output + + + + + Aborts the current active call to Execute by doing Thread.Abort + + true if a Thread.Abort was actually called. false if there is no active call to Execute + + + + Customize the CommandLine for remote scenarios + + + + + Command line hosting service. + + + + + Executes the comand line - depending upon the options provided we will + either run a single file, a single command, or enter the interactive loop. + + + + + Runs the command line. Languages can override this to provide custom behavior other than: + 1. Running a single command + 2. Running a file + 3. Entering the interactive console loop. + + + + + + Runs the specified filename + + + + + Starts the interactive loop. Performs any initialization necessary before + starting the loop and then calls RunInteractiveLoop to start the loop. + + Returns the exit code when the interactive loop is completed. + + + + + Runs the interactive loop. Repeatedly parse and run interactive actions + until an exit code is received. If any exceptions are unhandled displays + them to the console + + + + + Attempts to run a single interaction and handle any language-specific + exceptions. Base classes can override this and call the base implementation + surrounded with their own exception handling. + + Returns null if successful and execution should continue, or an exit code. + + + + + Parses a single interactive command or a set of statements and executes it. + + Returns null if successful and execution should continue, or the appropiate exit code. + + We check if the code read is an interactive command or statements is by checking for NewLine + If the code contains NewLine, it's a set of statements (most probably from SendToConsole) + If the code does not contain a NewLine, it's an interactive command typed by the user at the prompt + + + + + Private helper function to see if we should treat the current input as a blank link. + + We do this if we only have auto-indent text. + + + + + Read a statement, which can potentially be a multiple-line statement suite (like a class declaration). + + Should the console session continue, or did the user indicate + that it should be terminated? + Expression to evaluate. null for empty input + + + + Gets the next level for auto-indentation + + + + + Scope is not remotable, and this only works in the same AppDomain. + + + + + CommandDispatcher to ensure synchronize output from the remote runtime + + + + + ConsoleHost where the ScriptRuntime is hosted in a separate process (referred to as the remote runtime server) + + The RemoteConsoleHost spawns the remote runtime server and specifies an IPC channel name to use to communicate + with each other. The remote runtime server creates and initializes a ScriptRuntime and a ScriptEngine, and publishes + it over the specified IPC channel at a well-known URI. Note that the RemoteConsoleHost cannot easily participate + in the initialization of the ScriptEngine as classes like LanguageContext are not remotable. + + The RemoteConsoleHost then starts the interactive loop and executes commands on the ScriptEngine over the remoting channel. + The RemoteConsoleHost listens to stdout of the remote runtime server and echos it locally to the user. + + + + + Core functionality to implement an interactive console. This should be derived for concrete implementations + + + + + Request (from another thread) the console REPL loop to terminate + + The caller can specify the exitCode corresponding to the event triggering + the termination. This will be returned from CommandLine.Run + + + + To be called from entry point. + + + + + Console Host entry-point .exe name. + + + + + Allows the console to customize the environment variables, working directory, etc. + + At the least, processInfo.FileName should be initialized + + + + Aborts the current active call to Execute by doing Thread.Abort + + true if a Thread.Abort was actually called. false if there is no active call to Execute + + + + Called if the remote runtime process exits by itself. ie. without the remote console killing it. + + + + + The remote runtime server uses this class to publish an initialized ScriptEngine and ScriptRuntime + over a remoting channel. + + + + + Publish objects so that the host can use it, and then block indefinitely (until the input stream is open). + + Note that we should publish only one object, and then have other objects be accessible from it. Publishing + multiple objects can cause problems if the client does a call like "remoteProxy1(remoteProxy2)" as remoting + will not be able to know if the server object for both the proxies is on the same server. + + The IPC channel that the remote console expects to use to communicate with the ScriptEngine + A intialized ScriptScope that is ready to start processing script commands + + + Instruction can't be created due to insufficient privileges. + + + Instruction can't be created due to insufficient privileges. + + + + Gets the next type or null if no more types are available. + + + + + Uses reflection to create new instance of the appropriate ReflectedCaller + + + + + Fast creation works if we have a known primitive types for the entire + method siganture. If we have any non-primitive types then FastCreate + falls back to SlowCreate which works for all types. + + Fast creation is fast because it avoids using reflection (MakeGenericType + and Activator.CreateInstance) to create the types. It does this through + calling a series of generic methods picking up each strong type of the + signature along the way. When it runs out of types it news up the + appropriate CallInstruction with the strong-types that have been built up. + + One relaxation is that for return types which are non-primitive types + we can fallback to object due to relaxed delegates. + + + + + The number of arguments including "this" for instance methods. + + + + + This instruction implements a goto expression that can jump out of any expression. + It pops values (arguments) from the evaluation stack that the expression tree nodes in between + the goto expression and the target label node pushed and not consumed yet. + A goto expression can jump into a node that evaluates arguments only if it carries + a value and jumps right after the first argument (the carried value will be used as the first argument). + Goto can jump into an arbitrary child of a BlockExpression since the block doesn’t accumulate values + on evaluation stack as its child expressions are being evaluated. + + Goto needs to execute any finally blocks on the way to the target label. + + { + f(1, 2, try { g(3, 4, try { goto L } finally { ... }, 6) } finally { ... }, 7, 8) + L: ... + } + + The goto expression here jumps to label L while having 4 items on evaluation stack (1, 2, 3 and 4). + The jump needs to execute both finally blocks, the first one on stack level 4 the + second one on stack level 2. So, it needs to jump the first finally block, pop 2 items from the stack, + run second finally block and pop another 2 items from the stack and set instruction pointer to label L. + + Goto also needs to rethrow ThreadAbortException iff it jumps out of a catch handler and + the current thread is in "abort requested" state. + + + + + The first instruction of finally block. + + + + + The last instruction of finally block. + + + + + The last instruction of a catch exception handler. + + + + + The last instruction of a fault exception handler. + + + + + Implements dynamic call site with many arguments. Wraps the arguments into . + + + + + Contains compiler state corresponding to a LabelTarget + See also LabelScopeInfo. + + + + + Returns true if we can jump into this node + + + + + Attaches a cookie to the last emitted instruction. + + + + Instruction can't be created due to insufficient privileges. + + + + Manages creation of interpreted delegates. These delegates will get + compiled if they are executed often enough. + + + + + Used by LightLambda to get the compiled delegate. + + + + + Create a compiled delegate for the LightLambda, and saves it so + future calls to Run will execute the compiled code instead of + interpreting. + + + + + true if the compiled delegate has the same type as the lambda; + false if the type was changed for interpretation. + + + + + Provides notification that the LightLambda has been compiled. + + + + + A simple forth-style stack machine for executing Expression trees + without the need to compile to IL and then invoke the JIT. This trades + off much faster compilation time for a slower execution performance. + For code that is only run a small number of times this can be a + sweet spot. + + The core loop in the interpreter is the RunInstructions method. + + + + + Runs instructions within the given frame. + + + Interpreted stack frames are linked via Parent reference so that each CLR frame of this method corresponds + to an interpreted stack frame in the chain. It is therefore possible to combine CLR stack traces with + interpreted stack traces by aligning interpreted frames to the frames of this method. + Each group of subsequent frames of Run method corresponds to a single interpreted frame. + + + + + Visits a LambdaExpression, replacing the constants with direct accesses + to their StrongBox fields. This is very similar to what + ExpressionQuoter does for LambdaCompiler. + + Also inserts debug information tracking similar to what the interpreter + would do. + + + + + Local variable mapping. + + + + + The variable that holds onto the StrongBox{object}[] closure from + the interpreter + + + + + A stack of variables that are defined in nested scopes. We search + this first when resolving a variable in case a nested scope shadows + one of our variable instances. + + + + + Walks the lambda and produces a higher order function, which can be + used to bind the lambda to a closure array from the interpreter. + + The lambda to bind. + Variables which are being accessed defined in the outer scope. + A delegate that can be called to produce a delegate bound to the passed in closure array. + + + + Provides a list of variables, supporing read/write of the values + + + + + Gets a copy of the local variables which are defined in the current scope. + + + + + + Checks to see if the given variable is defined within the current local scope. + + + + + Gets the variables which are defined in an outer scope and available within the current scope. + + + + + Tracks where a variable is defined and what range of instructions it's used in + + + + + A single interpreted frame might be represented by multiple subsequent Interpreter.Run CLR frames. + This method filters out the duplicate CLR frames. + + + + + arbitrary precision integers + + + + + Create a BigInteger from a little-endian twos-complement byte array + (inverse of ToByteArray()) + + + + + Return the magnitude of this BigInteger as an array of zero or more uints. + Element zero is the value of the least significant four bytes, element one is + the value of the four next most significant bytes, etc. + + The returned data is the unsigned magnitude of the number. To determine the sign, + use GetSign(). + + It is guaranteed that the highest element of the returned array is never zero. + This means that if the value of this BigInteger is zero, a zero-length array + is returned. + + + + + Do an in-place twos complement of d and also return the result. + + + + + Calculates the natural logarithm of the BigInteger. + + + + + Calculates log base 10 of a BigInteger. + + + + + Return the value of this BigInteger as a little-endian twos-complement + byte array, using the fewest number of bytes possible. If the value is zero, + return an array of one byte whose element is 0x00. + + + + + Return the sign of this BigInteger: -1, 0, or 1. + + + + + Wraps all arguments passed to a dynamic site with more arguments than can be accepted by a Func/Action delegate. + The binder generating a rule for such a site should unwrap the arguments first and then perform a binding to them. + + + + + Provides support for converting objects to delegates using the DLR binders + available by the provided language context. + + Primarily this supports converting objects implementing IDynamicMetaObjectProvider + to the appropriate delegate type. + + If the provided object is already a delegate of the appropriate type then the + delegate will simply be returned. + + + + Table of dynamically generated delegates which are shared based upon method signature. + + + + Creates a delegate with a given signature that could be used to invoke this object from non-dynamic code (w/o code context). + A stub is created that makes appropriate conversions/boxing and calls the object. + The stub should be executed within a context of this object's language. + + The converted delegate. + The object is either a subclass of Delegate but not the requested type or does not implement IDynamicMetaObjectProvider. + + + + Represents the type of a null value. + + + + + Private constructor is never called since 'null' is the only valid instance. + + + + + These are some generally useful helper methods. Currently the only methods are those to + cached boxed representations of commonly used primitive types so that they can be shared. + This is useful to most dynamic languages that use object as a universal type. + + The methods in RuntimeHelepers are caleld by the generated code. From here the methods may + dispatch to other parts of the runtime to get bulk of the work done, but the entry points + should be here. + + + + + Used by prologue code that is injected in lambdas to ensure that delegate signature matches what + lambda body expects. Such code typically unwraps subset of the params array manually, + but then passes the rest in bulk if lambda body also expects params array. + + This calls ArrayUtils.ShiftLeft, but performs additional checks that + ArrayUtils.ShiftLeft assumes. + + + + + A singleton boxed boolean true. + + + + + A singleton boxed boolean false. + + + + + Gets a singleton boxed value for the given integer if possible, otherwise boxes the integer. + + The value to box. + The boxed value. + + + + Helper method to create an instance. Work around for Silverlight where Activator.CreateInstance + is SecuritySafeCritical. + + TODO: Why can't we just emit the right thing for default(T)? + It's always null for reference types and it's well defined for value types + + + + + EventInfo.EventHandlerType getter is marked SecuritySafeCritical in CoreCLR + This method is to get to the property without using Reflection + + + + + + + Provides the test to see if an interpreted call site should switch over to being compiled. + + + + + A parameterless generator, that is of type IEnumerable, IEnumerable{T}, + IEnumerator, or IEnumerator{T}. Its body can contain a series of + YieldExpressions. Each call into MoveNext on the enumerator reenters + the generator, and executes until it reaches a YieldReturn or YieldBreak + expression + + + + + The label used by YieldBreak and YieldReturn expressions to yield + from this generator + + + + + The body of the generator, which can contain YieldBreak and + YieldReturn expressions + + + + + Indicates whether the lhs instances are preserved when assignments + are made to expressions containing yields. + + + + + When finding a yield return or yield break, this rewriter flattens out + containing blocks, scopes, and expressions with stack state. All + scopes encountered have their variables promoted to the generator's + closure, so they survive yields. + + + + + Makes an assignment to this variable. Pushes the assignment as far + into the right side as possible, to allow jumps into it. + + + + + Returns true if the expression remains constant no matter when it is evaluated. + + + + + Represents either a YieldBreak or YieldReturn in a GeneratorExpression + If Value is non-null, it's a YieldReturn; otherwise it's a YieldBreak + and executing it will stop enumeration of the generator, causing + MoveNext to return false. + + + + + The value yieled from this expression, if it is a yield return + + + + + The label used to yield from this generator + + + + + Tests to see if the expression is a constant with the given value. + + The expression to examine + The constant value to check for. + true/false + + + + Tests to see if the expression is a constant with the given value. + + The expression to examine + The constant value to check for. + true/false + + + + Begins a catch block. + + + + + Begins an exception block for a filtered exception. + + + + + Begins an exception block for a non-filtered exception. + + + + + + Begins an exception fault block + + + + + Begins a finally block + + + + + Ends an exception block. + + + + + Begins a lexical scope. + + + + + Ends a lexical scope. + + + + + Declares a local variable of the specified type. + + + + + Declares a local variable of the specified type, optionally + pinning the object referred to by the variable. + + + + + Declares a new label. + + + + + Marks the label at the current position. + + + + + Emits an instruction. + + + + + Emits an instruction with a byte argument. + + + + + Emits an instruction with the metadata token for the specified contructor. + + + + + Emits an instruction with a double argument. + + + + + Emits an instruction with the metadata token for the specified field. + + + + + Emits an instruction with a float argument. + + + + + Emits an instruction with an int argument. + + + + + Emits an instruction with a label argument. + + + + + Emits an instruction with multiple target labels (switch). + + + + + Emits an instruction with a reference to a local variable. + + + + + Emits an instruction with a long argument. + + + + + Emits an instruction with the metadata token for a specified method. + + + + + Emits an instruction with a signed byte argument. + + + + + Emits an instruction with a short argument. + + + + + Emits an instruction with a signature token. + + + + + Emits an instruction with a string argument. + + + + + Emits an instruction with the metadata token for a specified type argument. + + + + + Emits a call or a virtual call to the varargs method. + + + + + Emits an unmanaged indirect call instruction. + + + + + Emits a managed indirect call instruction. + + + + + Marks a sequence point. + + + + + Specifies the namespace to be used in evaluating locals and watches for the + current active lexical scope. + + + + + Emits a Ldind* instruction for the appropriate type + + + + + Emits a Stind* instruction for the appropriate type. + + + + + Emits a Stelem* instruction for the appropriate type. + + + + + Boxes the value of the stack. No-op for reference types. Void is + converted to a null reference. For almost all value types this + method will box them in the standard way. Int32 and Boolean are + handled with optimized conversions that reuse the same object for + small values. For Int32 this is purely a performance optimization. + For Boolean this is use to ensure that True and False are always + the same objects. + + + + + Emits an array of constant values provided in the given list. + The array is strongly typed. + + + + + Emits an array of values of count size. The items are emitted via the callback + which is provided with the current item index to emit. + + + + + Emits an array construction code. + The code assumes that bounds for all dimensions + are already emitted. + + + + + Emits default(T) + Semantics match C# compiler behavior + + + + + A simple dictionary of queues, keyed off a particular type + This is useful for storing free lists of variables + + + + + Directory where snippet assembly will be saved if SaveSnippets is set. + + + + + Save snippets to an assembly (see also SnippetsDirectory, SnippetsFileName). + + + + + Gets the Compiler associated with the Type Initializer (cctor) creating it if necessary. + + + + + A tree rewriter which will find dynamic sites which consume dynamic sites and + turn them into a single combo dynamic site. The combo dynamic site will then run the + individual meta binders and produce the resulting code in a single dynamic site. + + + + + A reducible node which we use to generate the combo dynamic sites. Each time we encounter + a dynamic site we replace it with a ComboDynamicSiteExpression. When a child of a dynamic site + turns out to be a ComboDynamicSiteExpression we will then merge the child with the parent updating + the binding mapping info. If any of the inputs cause side effects then we'll stop the combination. + + + + + A binder which can combine multiple binders into a single dynamic site. The creator + of this needs to perform the mapping of parameters, constants, and sub-site expressions + and provide a List of BinderMappingInfo representing this data. From there the ComboBinder + just processes the list to create the resulting code. + + + + + Provides a mapping for inputs of combo action expressions. The input can map + to either an input of the new dynamic site, an input of a previous DynamicExpression, + or a ConstantExpression which has been pulled out of the dynamic site arguments. + + + + + Contains the mapping information for a single Combo Binder. This includes the original + meta-binder and the mapping of parameters, sub-sites, and constants into the binding. + + + + + Builds up a series of conditionals when the False clause isn't yet known. We can + keep appending conditions and if true's. Each subsequent true branch becomes the + false branch of the previous condition and body. Finally a non-conditional terminating + branch must be added. + + + + + Adds a new conditional and body. The first call this becomes the top-level + conditional, subsequent calls will have it added as false statement of the + previous conditional. + + + + + Adds the non-conditional terminating node. + + + + + Adds the non-conditional terminating node. + + + + + Gets the resulting meta object for the full body. FinishCondition + must have been called. + + + + + Adds a variable which will be scoped at the level of the final expression. + + + + + Marks a method as not having side effects. used by the combo binder + to allow calls to methods. + + + + + OperatorInfo provides a mapping from DLR ExpressionType to their associated .NET methods. + + + + + Given an operator returns the OperatorInfo associated with the operator or null + + + + + The operator the OperatorInfo provides info for. + + + + + The primary method name associated with the method. This method name is + usally in the form of op_Operator (e.g. op_Addition). + + + + + The secondary method name associated with the method. This method name is + usually a standard .NET method name with pascal casing (e.g. Add). + + + + + The builder for creating the LambdaExpression node. + + Since the nodes require that parameters and variables are created + before hand and then passed to the factories creating LambdaExpression + this builder keeps track of the different pieces and at the end creates + the LambdaExpression. + + TODO: This has some functionality related to CodeContext that should be + removed, in favor of languages handling their own local scopes + + + + + Creates a parameter on the lambda with a given name and type. + + Parameters maintain the order in which they are created, + however custom ordering is possible via direct access to + Parameters collection. + + + + + Creates a parameter on the lambda with a given name and type. + + Parameters maintain the order in which they are created, + however custom ordering is possible via direct access to + Parameters collection. + + + + + adds existing parameter to the lambda. + + Parameters maintain the order in which they are created, + however custom ordering is possible via direct access to + Parameters collection. + + + + + Creates a hidden parameter on the lambda with a given name and type. + + Parameters maintain the order in which they are created, + however custom ordering is possible via direct access to + Parameters collection. + + + + + Creates a params array argument on the labmda. + + The params array argument is added to the signature immediately. Before the lambda is + created, the builder validates that it is still the last (since the caller can modify + the order of parameters explicitly by maniuplating the parameter list) + + + + + Creates a local variable with specified name and type. + TODO: simplify by pushing logic into callers + + + + + Creates a local variable with specified name and type. + TODO: simplify by pushing logic into callers + + + + + Creates a temporary variable with specified name and type. + + + + + Adds the temporary variable to the list of variables maintained + by the builder. This is useful in cases where the variable is + created outside of the builder. + + + + + Creates the LambdaExpression from the builder. + After this operation, the builder can no longer be used to create other instances. + + Desired type of the lambda. + New LambdaExpression instance. + + + + Creates the LambdaExpression from the builder. + After this operation, the builder can no longer be used to create other instances. + + New LambdaExpression instance. + + + + Creates the generator LambdaExpression from the builder. + After this operation, the builder can no longer be used to create other instances. + + New LambdaExpression instance. + + + + Fixes up lambda body and parameters to match the signature of the given delegate if needed. + + + + + + Validates that the builder has enough information to create the lambda. + + + + + The name of the lambda. + Currently anonymous/unnamed lambdas are not allowed. + + + + + Return type of the lambda being created. + + + + + List of lambda's local variables for direct manipulation. + + + + + List of lambda's parameters for direct manipulation + + + + + The params array argument, if any. + + + + + The body of the lambda. This must be non-null. + + + + + The generated lambda should have dictionary of locals + instead of allocating them directly on the CLR stack. + + + + + The scope is visible (default). Invisible if false. + + + + + marks a field, class, or struct as being safe to have statics which can be accessed + from multiple runtimes. + + Static fields which are not read-only or marked with this attribute will be flagged + by a test which looks for state being shared between runtimes. Before applying this + attribute you should ensure that it is safe to share the state. This is typically + state which is lazy initialized or state which is caching values which are identical + in all runtimes and are immutable. + + + + + This class is useful for quickly collecting performance counts for expensive + operations. Usually this means operations involving either reflection or + code gen. Long-term we need to see if this can be plugged better into the + standard performance counter architecture. + + + + + temporary categories for quick investigation, use a custom key if you + need to track multiple items, and if you want to keep it then create + a new Categories entry and rename all your temporary entries. + + + + + Represents the context that is flowed for doing Compiler. Languages can derive + from this class to provide additional contextual information. + + + + + Source unit currently being compiled in the CompilerContext + + + + + Current error sink. + + + + + Sink for parser callbacks (e.g. brace matching, etc.). + + + + + Compiler specific options. + + + + + Indicates that a DynamicMetaObject might be convertible to a CLR type. + + + + + Gets custom data to be serialized when saving script codes to disk. + + + + + Indicates that a MetaObject is already representing a restricted type. Useful + when we're already restricted to a known type but this isn't captured in + the type info (e.g. the type is not sealed). + + + + + Returns Microsoft.Scripting.Runtime.DynamicNull if the object contains a null value, + otherwise, returns self.LimitType + + + + + Returns Microsoft.Scripting.Runtime.DynamicNull if the object contains a null value, + otherwise, returns self.RuntimeType + + + + + ScriptCode is an instance of compiled code that is bound to a specific LanguageContext + but not a specific ScriptScope. The code can be re-executed multiple times in different + scopes. Hosting API counterpart for this class is CompiledCode. + + + + + This takes an assembly name including extension and saves the provided ScriptCode objects into the assembly. + + The provided script codes can constitute code from multiple languages. The assemblyName can be either a fully qualified + or a relative path. The DLR will simply save the assembly to the desired location. The assembly is created by the DLR and + if a file already exists than an exception is raised. + + The DLR determines the internal format of the ScriptCode and the DLR can feel free to rev this as appropriate. + + + + + This will take an assembly object which the user has loaded and return a new set of ScriptCode’s which have + been loaded into the provided ScriptDomainManager. + + If the language associated with the ScriptCode’s has not already been loaded the DLR will load the + LanguageContext into the ScriptDomainManager based upon the saved LanguageContext type. + + If the LanguageContext or the version of the DLR the language was compiled against is unavailable a + TypeLoadException will be raised unless policy has been applied by the administrator to redirect bindings. + + + + + Sets the current position inside current token or one character behind it. + + + + + Sets the current position inside current token or one character behind it. + A relative displacement with respect to the current position in the token is specified. + + + + + Marks token end. Enables to read the current token. + + + + + Marks token start. It means the buffer can drop the current token. + Can be called even if no token has been read yet. + + + + + Reads till the end of line and returns the character that stopped the reading. + The returned character is not skipped. + + + + + Resizes an array to a speficied new size and copies a portion of the original array into its beginning. + + + + + Helper class to remove methods w/ identical signatures. Used for GetDefaultMembers + which returns members from all types in the hierarchy. + + + + + Handles input and output for the console. It is comparable to System.IO.TextReader, + System.IO.TextWriter, System.Console, etc + + + + + Read a single line of interactive input, or a block of multi-line statements. + + An event-driven GUI console can implement this method by creating a thread that + blocks and waits for an event indicating that input is available + + The indentation level to be used for the current suite of a compound statement. + The console can ignore this argument if it does not want to support auto-indentation + null if the input stream has been closed. A string with a command to execute otherwise. + It can be a multi-line string which should be processed as block of statements + + + + + + + + name == null means that the argument doesn't specify an option; the value contains the entire argument + name == "" means that the option name is empty (argument separator); the value is null then + + + + + Literal script command given using -c option + + + + + Filename to execute passed on the command line options. + + + + + Only print the version of the script interpreter and exit + + + + On error. + + + + The console input buffer. + + + + + Current position - index into the input buffer + + + + + The number of white-spaces displayed for the auto-indenation of the current line + + + + + Length of the output currently rendered on screen. + + + + + Command history + + + + + Tab options available in current context + + + + + Cursort anchor - position of cursor when the routine was called + + + + + The command line that this console is attached to. + + + + + Displays the next option in the option list, + or beeps if no options available for current input prefix. + If no input prefix, simply print tab. + + + + + + + Handle the enter key. Adds the current input (if not empty) to the history. + + + The input string. + + + + Class managing the command history. + + + + + List of available options + + + + + Cursor position management + + + + + Beginning position of the cursor - top coordinate. + + + + + Beginning position of the cursor - left coordinate. + + + + + Implementation of the complex number data type. + + + + + Helper methods that calls are generated to from the default DLR binders. + + + + + Helper function to combine an object array with a sequence of additional parameters that has been splatted for a function call. + + + + + EventInfo.EventHandlerType getter is marked SecuritySafeCritical in CoreCLR + This method is to get to the property without using Reflection + + + + + + + Implements explicit casts supported by the runtime. + + + Implements explicit casts supported by the runtime. + + + + + Explicitly casts the object to a given type (and returns it as object) + + + + + Used as the value for the ScriptingRuntimeHelpers.GetDelegate method caching system + + + + + Generates stub to receive the CLR call and then call the dynamic language code. + + + + + Used as the key for the LanguageContext.GetDelegate method caching system + + + + + A useful interface for taking slices of numeric arrays, inspired by Python's Slice objects. + + + + + The starting index of the slice or null if no first index defined + + + + + The ending index of the slice or null if no ending index defined + + + + + The length of step to take + + + + + Given an ID returns the object associated with that ID. + + + + + Gets a unique ID for an object + + + + + Goes over the hashtable and removes empty entries + + + + + Weak-ref wrapper caches the weak reference, our hash code, and the object ID. + + + + + WrapperComparer treats Wrapper as transparent envelope + + + + + Internal class which binds a LanguageContext, StreamContentProvider, and Encoding together to produce + a TextContentProvider which reads binary data with the correct language semantics. + + + + + Creates a dictionary of locals in this scope + + + + + Abstract base class used for optimized thread-safe dictionaries which have a set + of pre-defined string keys. + + Implementers derive from this class and override the GetExtraKeys, TrySetExtraValue, + and TryGetExtraValue methods. When looking up a value first the extra keys will be + searched using the optimized Try*ExtraValue functions. If the value isn't found there + then the value is stored in the underlying .NET dictionary. + + This dictionary can store object values in addition to string values. It also supports + null keys. + + + + + Provides hashing and equality based upon the value of the object instead of the reference. + + + + + Gets the hash code for the value of the instance. + + A hash code + The type is mutable and cannot be hashed by value + + + + Determines if two values are equal + + The object to compare the current object against. + Returns true if the objects are equal, false if they are not. + + + + Gets a list of the extra keys that are cached by the the optimized implementation + of the module. + + + + + Try to set the extra value and return true if the specified key was found in the + list of extra values. + + + + + Try to get the extra value and returns true if the specified key was found in the + list of extra values. Returns true even if the value is Uninitialized. + + + + + Efficiently tracks (line,column) information as text is added, and + collects line mappings between the original and generated source code + so we can generate correct debugging information later + + + + + Marks the current position of the writer as corresponding to the + original location passed in + + the line pragma corresponding to the + current position in the generated code + + + + Provides a dictionary-like object used for caches which holds onto a maximum + number of elements specified at construction time. + + This class is not thread safe. + + + + + Creates a dictionary-like object used for caches. + + The maximum number of elements to store. + + + + Tries to get the value associated with 'key', returning true if it's found and + false if it's not present. + + + + + Adds a new element to the cache, replacing and moving it to the front if the + element is already present. + + + + + Returns the value associated with the given key, or throws KeyNotFoundException + if the key is not present. + + + + + Wraps the provided enumerable into a ReadOnlyCollection{T} + + Copies all of the data into a new array, so the data can't be + changed after creation. The exception is if the enumerable is + already a ReadOnlyCollection{T}, in which case we just return it. + + + + + List optimized for few writes and multiple reads. It provides thread-safe read and write access. + Iteration is not thread-safe by default, but GetCopyForRead allows for iteration + without taking a lock. + + + + + Gets a copy of the contents of the list. The copy will not change even if the original + CopyOnWriteList object is modified. This method should be used to iterate the list in + a thread-safe way if no lock is taken. Iterating on the original list is not guaranteed + to be thread-safe. + + The returned copy should not be modified by the caller. + + + + Returns the list of expressions represented by the instances. + + An array of instances to extract expressions from. + The array of expressions. + + + + Creates an instance of for a runtime value and the expression that represents it during the binding process. + + The runtime value to be represented by the . + An expression to represent this during the binding process. + The new instance of . + + + + Produces an interpreted binding using the given binder which falls over to a compiled + binding after hitCount tries. + + This method should be called whenever an interpreted binding is required. Sometimes it will + return a compiled binding if a previous binding was produced and it's hit count was exhausted. + In this case the binder will not be called back for a new binding - the previous one will + be used. + + The delegate type being used for the call site + The binder used for the call site + The number of calls before the binder should switch to a compiled mode. + The arguments that are passed for the binding (as received in a BindDelegate call) + A delegate which represents the interpreted binding. + + + + Expression which reduces to the normal test but under the interpreter adds a count down + check which enables compiling when the count down is reached. + + + + + Base class for storing information about the binding that a specific rule is applicable for. + + We have a derived generic class but this class enables us to refer to it w/o having the + generic type information around. + + This class tracks both the count down to when we should compile. When we compile we + take the Expression[T] that was used before and compile it. While this is happening + we continue to allow the interpreted code to run. When the compilation is complete we + store a thread static which tells us what binding failed and the current rule is no + longer functional. Finally the language binder will call us again and we'll retrieve + and return the compiled overload. + + + + + A hybrid dictionary which compares based upon object identity. + + + + + Calculates the quotient of two 32-bit signed integers rounded towards negative infinity. + + Dividend. + Divisor. + The quotient of the specified numbers rounded towards negative infinity, or (int)Floor((double)x/(double)y). + is 0. + The caller must check for overflow (x = Int32.MinValue, y = -1) + + + + Calculates the quotient of two 32-bit signed integers rounded towards negative infinity. + + Dividend. + Divisor. + The quotient of the specified numbers rounded towards negative infinity, or (int)Floor((double)x/(double)y). + is 0. + The caller must check for overflow (x = Int64.MinValue, y = -1) + + + + Calculates the remainder of floor division of two 32-bit signed integers. + + Dividend. + Divisor. + The remainder of of floor division of the specified numbers, or x - (int)Floor((double)x/(double)y) * y. + is 0. + + + + Calculates the remainder of floor division of two 32-bit signed integers. + + Dividend. + Divisor. + The remainder of of floor division of the specified numbers, or x - (int)Floor((double)x/(double)y) * y. + is 0. + + + + Behaves like Math.Round(value, MidpointRounding.AwayFromZero) + Needed because CoreCLR doesn't support this particular overload of Math.Round + + + + + Behaves like Math.Round(value, precision, MidpointRounding.AwayFromZero) + However, it works correctly on negative precisions and cases where precision is + outside of the [-15, 15] range. + + (This function is also needed because CoreCLR lacks this overload.) + + + + + Evaluates a polynomial in v0 where the coefficients are ordered in increasing degree + + + + + Evaluates a polynomial in v0 where the coefficients are ordered in increasing degree + if reverse is false, and increasing degree if reverse is true. + + + + + A numerically precise version of sin(v0 * pi) + + + + + A numerically precise version of |sin(v0 * pi)| + + + + + Take the quotient of the 2 polynomials forming the Lanczos approximation + with N=13 and G=13.144565 + + + + + Computes the Gamma function on positive values, using the Lanczos approximation. + Lanczos parameters are N=13 and G=13.144565. + + + + + Computes the Log-Gamma function on positive values, using the Lanczos approximation. + Lanczos parameters are N=13 and G=13.144565. + + + + + Thread safe dictionary that allows lazy-creation where readers will block for + the creation of the lazily created value. Call GetOrCreateValue w/ a key + and a callback function. If the value exists it is returned, if not the create + callback is called (w/o any locks held). The create call back will only be called + once for each key. + + + + + Helper class which stores the published value + + + + + Dictionary[TKey, TValue] is not thread-safe in the face of concurrent reads and writes. SynchronizedDictionary + provides a thread-safe implementation. It holds onto a Dictionary[TKey, TValue] instead of inheriting from + it so that users who need to do manual synchronization can access the underlying Dictionary[TKey, TValue]. + + + + + This returns the raw unsynchronized Dictionary[TKey, TValue]. Users are responsible for locking + on it before accessing it. Also, it should not be arbitrarily handed out to other code since deadlocks + can be caused if other code incorrectly locks on it. + + + + + Provides fast strongly typed thread local storage. This is significantly faster than + Thread.GetData/SetData. + + + + + True if the caller will guarantee that all cleanup happens as the thread + unwinds. + + This is typically used in a case where the thread local is surrounded by + a try/finally block. The try block pushes some state, the finally block + restores the previous state. Therefore when the thread exits the thread + local is back to it's original state. This allows the ThreadLocal object + to not check the current owning thread on retrieval. + + + + + Gets the current value if its not == null or calls the provided function + to create a new value. + + + + + Calls the provided update function with the current value and + replaces the current value with the result of the function. + + + + + Replaces the current value with a new one and returns the old value. + + + + + Gets the StorageInfo for the current thread. + + + + + Called when the fast path storage lookup fails. if we encountered the Empty storage + during the initial fast check then spin until we hit non-empty storage and try the fast + path again. + + + + + Creates the StorageInfo for the thread when one isn't already present. + + + + + Gets or sets the value for the current thread. + + + + + Helper class for storing the value. We need to track if a ManagedThreadId + has been re-used so we also store the thread which owns the value. + + + + + Returns a numerical code of the size of a type. All types get both a horizontal + and vertical code. Types that are lower in both dimensions have implicit conversions + to types that are higher in both dimensions. + + + + + Represents an array that has value equality. + + + + + Simple class for tracking a list of items and enumerating over them. + The items are stored in weak references; if the objects are collected, + they will not be seen when enumerating. + + The type of the collection element. + + + + Similar to Dictionary[TKey,TValue], but it also ensures that the keys will not be kept alive + if the only reference is from this collection. The value will be kept alive as long as the key + is alive. + + This currently has a limitation that the caller is responsible for ensuring that an object used as + a key is not also used as a value in *any* instance of a WeakHash. Otherwise, it will result in the + object being kept alive forever. This effectively means that the owner of the WeakHash should be the + only one who has access to the object used as a value. + + Currently, there is also no guarantee of how long the values will be kept alive even after the keys + get collected. This could be fixed by triggerring CheckCleanup() to be called on every garbage-collection + by having a dummy watch-dog object with a finalizer which calls CheckCleanup(). + + + + + Check if any of the keys have gotten collected + + Currently, there is also no guarantee of how long the values will be kept alive even after the keys + get collected. This could be fixed by triggerring CheckCleanup() to be called on every garbage-collection + by having a dummy watch-dog object with a finalizer which calls CheckCleanup(). + + + + + This class holds onto internal debugging options used in this assembly. + These options can be set via environment variables DLR_{option-name}. + Boolean options map "true" to true and other values to false. + + These options are for internal debugging only, and should not be + exposed through any public APIs. + + + + + Sets the value at the given index for a tuple of the given size. This set supports + walking through nested tuples to get the correct final index. + + + + + Gets the value at the given index for a tuple of the given size. This get + supports walking through nested tuples to get the correct final index. + + + + + Gets the unbound generic Tuple type which has at lease size slots or null if a large enough tuple is not available. + + + + + Creates a generic tuple with the specified types. + + If the number of slots fits within the maximum tuple size then we simply + create a single tuple. If it's greater then we create nested tuples + (e.g. a Tuple`2 which contains a Tuple`128 and a Tuple`8 if we had a size of 136). + + + + + Gets the number of usable slots in the provided Tuple type including slots available in nested tuples. + + + + + Creates a new instance of tupleType with the specified args. If the tuple is a nested + tuple the values are added in their nested forms. + + + + + Gets the values from a tuple including unpacking nested values. + + + + + Gets the series of properties that needs to be accessed to access a logical item in a potentially nested tuple. + + + + + Gets the series of properties that needs to be accessed to access a logical item in a potentially nested tuple. + + + + + Provides an expression for creating a tuple with the specified values. + + + + + TODO: Alternatively, it should be sufficient to remember indices for this, list, dict and block. + + + + + Convention for an individual argument at a callsite. + + Multiple different callsites can match against a single declaration. + Some argument kinds can be "unrolled" into multiple arguments, such as list and dictionary. + + + + + Simple unnamed positional argument. + In Python: foo(1,2,3) are all simple arguments. + + + + + Argument with associated name at the callsite + In Python: foo(a=1) + + + + + Argument containing a list of arguments. + In Python: foo(*(1,2*2,3)) would match 'def foo(a,b,c)' with 3 declared arguments such that (a,b,c)=(1,4,3). + it could also match 'def foo(*l)' with 1 declared argument such that l=(1,4,3) + + + + + Argument containing a dictionary of named arguments. + In Python: foo(**{'a':1, 'b':2}) + + + + + Represents a logical member of a type. The member could either be real concrete member on a type or + an extension member. + + This seperates the "physical" members that .NET knows exist on types from the members that + logically exist on a type. It also provides other abstractions above the level of .NET reflection + such as MemberGroups and NamespaceTracker's. + + It also provides a wrapper around the reflection APIs which cannot be extended from partial trust. + + + + + Gets the expression that creates the value. + + Returns null if it's an error to get the value. The caller can then call GetErrorForGet to get + the correct error Expression (or null if they should provide a default). + + + + + Gets an expression that assigns a value to the left hand side. + + Returns null if it's an error to assign to. The caller can then call GetErrorForSet to + get the correct error Expression (or null if a default error should be provided). + + + + + Gets an expression that assigns a value to the left hand side. + + Returns null if it's an error to assign to. The caller can then call GetErrorForSet to + get the correct error Expression (or null if a default error should be provided). + + + + + Gets an expression that performs a call on the object using the specified arguments. + + Returns null if it's an error to perform the specific operation. The caller can then call + GetErrorsForDoCall to get the correct error Expression (or null if a default error should be provided). + + + + + Returns the error associated with getting the value. + + A null return value indicates that the default error message should be provided by the caller. + + + + + Returns the error associated with accessing this member via a bound instance. + + A null return value indicates that the default error message should be provided by the caller. + + + + + Helper for getting values that have been bound. Called from BoundMemberTracker. Custom member + trackers can override this to provide their own behaviors when bound to an instance. + + + + + Helper for setting values that have been bound. Called from BoundMemberTracker. Custom member + trackers can override this to provide their own behaviors when bound to an instance. + + + + + Helper for setting values that have been bound. Called from BoundMemberTracker. Custom member + trackers can override this to provide their own behaviors when bound to an instance. + + + + + Binds the member tracker to the specified instance rturning a new member tracker if binding + is possible. If binding is not possible the existing member tracker will be returned. For example + binding to a static field results in returning the original MemberTracker. Binding to an instance + field results in a new BoundMemberTracker which will get GetBoundValue/SetBoundValue to pass the + instance through. + + + + + The type of member tracker. + + + + + The logical declaring type of the member. + + + + + The name of the member. + + + + + We ensure we only produce one MemberTracker for each member which logically lives on the declaring type. So + for example if you get a member from a derived class which is declared on the base class it should be the same + as getting the member from the base class. That’s easy enough until you get into extension members – here there + might be one extension member which is being applied to multiple types. Therefore we need to take into account the + extension type when ensuring that we only have 1 MemberTracker ever created. + + + + + Richly represents the signature of a callsite. + + + + + Array of additional meta information about the arguments, such as named arguments. + Null for a simple signature that's just an expression list. eg: foo(a*b,c,d) + + + + + Number of arguments in the signature. + + + + + True if the OldCallAction includes an ArgumentInfo of ArgumentKind.Dictionary or ArgumentKind.Named. + + + + + Gets the number of positional arguments the user provided at the call site. + + + + + All arguments are unnamed and matched by position. + + + + + A custom member tracker which enables languages to plug in arbitrary + members into the lookup process. + + + + + Encapsulates information about the result that should be produced when + a OldDynamicAction cannot be performed. The ErrorInfo can hold one of: + an expression which creates an Exception to be thrown + an expression which produces a value which should be returned + directly to the user and represents an error has occured (for + example undefined in JavaScript) + an expression which produces a value which should be returned + directly to the user but does not actually represent an error. + + ErrorInfo's are produced by an ActionBinder in response to a failed + binding. + + + + + Private constructor - consumers must use static From* factories + to create ErrorInfo objects. + + + + + Creates a new ErrorInfo which represents an exception that should + be thrown. + + + + + Creates a new ErrorInfo which represents a value which should be + returned to the user. + + + + + Crates a new ErrorInfo which represents a value which should be returned + to the user but does not represent an error. + + + + + + + The ErrorInfo expression produces an exception + + + + + The ErrorInfo expression produces a value which represents the error (e.g. undefined) + + + + + The ErrorInfo expression produces a value which is not an error + + + + + Gets the stub list for a COM Object. For COM objects we store the stub list + directly on the object using the Marshal APIs. This allows us to not have + any circular references to deal with via weak references which are challenging + in the face of COM. + + + + + Doesn't need to check PrivateBinding setting: no method that is part of the event is public the entire event is private. + If the code has already a reference to the event tracker instance for a private event its "static-ness" is not influenced + by private-binding setting. + + + + + Holds on a list of delegates hooked to the event. + We need the list because we cannot enumerate the delegates hooked to CLR event and we need to do so in + handler removal (we need to do custom delegate comparison there). If BCL enables the enumeration we could remove this. + + + + + Storage for the handlers - a key value pair of the callable object and the delegate handler. + + + + + Storage for the handlers - a key value pair of the callable object and the delegate handler. + + The delegate handler is closed over the callable object. Therefore as long as the object is alive the + delegate will stay alive and so will the callable object. That means it's fine to have a weak reference + to both of these objects. + + + + + Represents extension method. + + + + + The declaring type of the extension (the type this extension method extends) + + + + + The declaring type of the extension method. Since this is an extension method, + the declaring type is in fact the type this extension method extends, + not Method.DeclaringType + + + + + Represents a logical Property as a member of a Type. This Property can either be a real + concrete Property on a type (implemented with a ReflectedPropertyTracker) or an extension + property (implemented with an ExtensionPropertyTracker). + + + + + MemberGroups are a collection of MemberTrackers which are commonly produced + on-demand to talk about the available members. They can consist of a mix of + different member types or multiple membes of the same type. + + The most common source of MemberGroups is from ActionBinder.GetMember. From here + the DLR will perform binding to the MemberTrackers frequently producing the value + resulted from the user. If the result of the action produces a member it's self + the ActionBinder can provide the value exposed to the user via ReturnMemberTracker. + + ActionBinder provides default functionality for both getting members from a type + as well as exposing the members to the user. Getting members from the type maps + closely to reflection and exposing them to the user exposes the MemberTrackers + directly. + + + + + MethodGroup's represent a unique collection of method's. Typically this + unique set is all the methods which are overloaded by the same name including + methods with different arity. These methods represent a single logically + overloaded element of a .NET type. + + The base DLR binders will produce MethodGroup's when provided with a MemberGroup + which contains only methods. The MethodGroup's will be unique instances per + each unique group of methods. + + + + + Returns a BuiltinFunction bound to the provided type arguments. Returns null if the binding + cannot be performed. + + + + + NamespaceTracker represent a CLS namespace. + + + + + Provides a list of all the members of an instance. + + + + + Loads all the types from all assemblies that contribute to the current namespace (but not child namespaces) + + + + + Populates the tree with nodes for each part of the namespace + + + Full namespace name. It can be null (for top-level types) + + + + + As a fallback, so if the type does exist in any assembly. This would happen if a new type was added + that was not in the hardcoded list of types. + This code is not accurate because: + 1. We dont deal with generic types (TypeCollision). + 2. Previous calls to GetCustomMemberNames (eg. "from foo import *" in Python) would not have included this type. + 3. This does not deal with new namespaces added to the assembly + + + + + This stores all the public non-nested type names in a single namespace and from a single assembly. + This allows inspection of the namespace without eagerly loading all the types. Eagerly loading + types slows down startup, increases working set, and is semantically incorrect as it can trigger + TypeLoadExceptions sooner than required. + + + + + Enables implicit Type to TypeTracker conversions accross dynamic languages. + + + + + Represents the top reflected package which contains extra information such as + all the assemblies loaded and the built-in modules. + + + + + returns the package associated with the specified namespace and + updates the associated module to mark the package as imported. + + + + + Ensures that the assembly is loaded + + + true if the assembly was loaded for the first time. + false if the assembly had already been loaded before + + + + When an (interop) assembly is loaded, we scan it to discover the GUIDs of COM interfaces so that we can + associate the type definition with COM objects with that GUID. + Since scanning all loaded assemblies can be expensive, in the future, we might consider a more explicit + user binder to trigger scanning of COM types. + + + + Specifies that the member is a constructor, representing a ConstructorTracker + + + Specifies that the member is an event, representing a EventTracker + + + Specifies that the member is a field, representing a FieldTracker + + + Specifies that the member is a method, representing a MethodTracker + + + Specifies that the member is a property, representing a PropertyTracker + + + Specifies that the member is a property, representing a TypeTracker + + + Specifies that the member is a namespace, representing a NamespaceTracker + + + Specifies that the member is a group of method overloads, representing a MethodGroup + + + Specifies that the member is a group of types that very by arity, representing a TypeGroup + + + Specifies that the member is a custom meber, represetning a CustomTracker + + + Specifies that the member is a bound to an instance, representing a BoundMemberTracker + + + + A TypeCollision is used when we have a collision between + two types with the same name. Currently this is only possible w/ generic + methods that should logically have arity as a portion of their name. For eg: + System.EventHandler and System.EventHandler[T] + System.Nullable and System.Nullable[T] + System.IComparable and System.IComparable[T] + + The TypeCollision provides an indexer but also is a real type. When used + as a real type it is the non-generic form of the type. + + The indexer allows the user to disambiguate between the generic and + non-generic versions. Therefore users must always provide additional + information to get the generic version. + + + + The merged list so far. Could be null + The new type(s) to add to the merged list + The merged list. Could be a TypeTracker or TypeGroup + + + Gets the arity of generic parameters + + + No non-generic type is represented by this group. + + + + This returns the DeclaringType of all the types in the TypeGroup + + + + + This returns the base name of the TypeGroup (the name shared by all types minus arity) + + + + + This will return the result only for the non-generic type if one exists, and will throw + an exception if all types in the TypeGroup are generic + + + + + This will return the result only for the non-generic type if one exists, and will throw + an exception if all types in the TypeGroup are generic + + + + + True if the MethodBase is method which is going to construct an object + + + + + Returns the System.Type for any object, including null. The type of null + is represented by None.Type and all other objects just return the + result of Object.GetType + + + + + Simply returns a Type[] from calling GetType on each element of args. + + + + + EMITTED + Used by default method binder to check types of splatted arguments. + + + + + Given a MethodInfo which may be declared on a non-public type this attempts to + return a MethodInfo which will dispatch to the original MethodInfo but is declared + on a public type. + + Returns the original method if the method if a public version cannot be found. + + + + + Non-public types can have public members that we find when calling type.GetMember(...). This + filters out the non-visible members by attempting to resolve them to the correct visible type. + + If no correct visible type can be found then the member is not visible and we won't call it. + + + + + Sees if two MemberInfos point to the same underlying construct in IL. This + ignores the ReflectedType property which exists on MemberInfos which + causes direct comparisons to be false even if they are the same member. + + + + + Returns a value which indicates failure when a OldConvertToAction of ImplicitTry or + ExplicitTry. + + + + + Creates an interpreted delegate for the lambda. + + The lambda to compile. + A delegate which can interpret the lambda. + + + + Creates an interpreted delegate for the lambda. + + The lambda to compile. + The number of iterations before the interpreter starts compiling + A delegate which can interpret the lambda. + + + + Creates an interpreted delegate for the lambda. + + The lambda's delegate type. + The lambda to compile. + A delegate which can interpret the lambda. + + + + Creates an interpreted delegate for the lambda. + + The lambda to compile. + The number of iterations before the interpreter starts compiling + A delegate which can interpret the lambda. + + + + Compiles the lambda into a method definition. + + the lambda to compile + A which will be used to hold the lambda's IL. + A parameter that indicates if debugging information should be emitted to a PDB symbol store. + + + + Compiles the LambdaExpression. + + If the lambda is compiled with emitDebugSymbols, it will be + generated into a TypeBuilder. Otherwise, this method is the same as + calling LambdaExpression.Compile() + + This is a workaround for a CLR limitiation: DynamicMethods cannot + have debugging information. + + the lambda to compile + true to generate a debuggable method, false otherwise + the compiled delegate + + + + Compiles the LambdaExpression, emitting it into a new type, and + optionally making it debuggable. + + This is a workaround for a CLR limitiation: DynamicMethods cannot + have debugging information. + + the lambda to compile + Debugging information generator used by the compiler to mark sequence points and annotate local variables. + True if debug symbols (PDBs) are emitted by the . + the compiled delegate + + + + Reduces the provided DynamicExpression into site.Target(site, *args). + + + + + Removes all live objects and places them in static fields of a type. + + + + + Enables an object to be serializable to an Expression tree. The expression tree can then + be emitted into an assembly enabling the de-serialization of the object. + + + + + Serializes constants and dynamic sites so the code can be saved to disk + + + + + The MethodBinder will perform normal method binding. + + + + + The MethodBinder will return the languages definition of NotImplemented if the arguments are + incompatible with the signature. + + + + + The MethodBinder will set properties/fields for unused keyword arguments on the instance + that gets returned from the method. + + + + + The delegate representing the DLR Main function + + + + + An attribute that is applied to saved ScriptCode's to be used to re-create the ScriptCode + from disk. + + + + + Gets names stored in optimized scope. + + + + + Provides a mechanism for providing documentation stored in an assembly as metadata. + + Applying this attribute will enable documentation to be provided to the user at run-time + even if XML Documentation files are unavailable. + + + + + Updates an exception before it's getting re-thrown so + we can present a reasonable stack trace to the user. + + + + + Returns all the stack traces associates with an exception + + + + + Marks a class in the assembly as being an extension type for another type. + + + + + Marks a type in the assembly as being an extension type for another type. + + The type which is being extended + The type which provides the extension members. + + + + The type which contains extension members which are added to the type being extended. + + + + + The type which is being extended by the extension type. + + + + + Not all .NET enumerators throw exceptions if accessed in an invalid state. This type + can be used to throw exceptions from enumerators implemented in IronPython. + + + + + Event args for when a ScriptScope has had its contents changed. + + + + + Creates a new ModuleChangeEventArgs object with the specified name and type. + + + + + Creates a nwe ModuleChangeEventArgs with the specified name, type, and changed value. + + + + + Gets the name of the symbol that has changed. + + + + + Gets the way in which the symbol has changed: Set or Delete. + + + + + The the symbol has been set provides the new value. + + + + + The way in which a module has changed : Set or Delete + + + + + A new value has been set in the module (or a previous value has changed). + + + + + A value has been removed from the module. + + + + + A NullTextContentProvider to be provided when we have a pre-compiled ScriptCode which doesn't + have source code associated with it. + + + + + Singleton instance returned from an operator method when the operator method cannot provide a value. + + + + + Represents an ops-extension method which is added as an operator. + + The name must be a well-formed name such as "Add" that matches the CLS + naming conventions for adding overloads associated with op_* methods. + + + + + Represents an ops-extension method which is used to implement a property. + + + + + Provides a cache of reflection members. Only one set of values is ever handed out per a + specific request. + + + + + TODO: Make me private again + + + + + Indicates an extension method should be added as a static method, not a instance method. + + + + + Converts a generic ICollection of T into an array of T. + + If the collection is already an array of T the original collection is returned. + + + + + Converts a generic ICollection of T into an array of R using a given conversion. + + If the collection is already an array of R the original collection is returned. + + + + + Allows wrapping of proxy types (like COM RCWs) to expose their IEnumerable functionality + which is supported after casting to IEnumerable, even though Reflection will not indicate + IEnumerable as a supported interface + + + + + Requires the specified index to point inside the array. + + Array is null. + Index is outside the array. + + + + Requires the specified index to point inside the array. + + Index is outside the array. + + + + Requires the specified index to point inside the array or at the end + + Array is null. + Index is outside the array. + + + + Requires the specified index to point inside the array or at the end + + Array is null. + Index is outside the array. + + + + Requires the range [offset, offset + count] to be a subset of [0, array.Count]. + + Offset or count are out of range. + + + + Requires the range [offset, offset + count] to be a subset of [0, array.Count]. + + Offset or count are out of range. + + + + Requires the range [offset, offset + count] to be a subset of [0, array.Count]. + + Array is null. + Offset or count are out of range. + + + + Requires the range [offset, offset + count] to be a subset of [0, array.Count]. + + String is null. + Offset or count are out of range. + + + + Requires the array and all its items to be non-null. + + + + + Requires the enumerable collection and all its items to be non-null. + + + + + Presents a flat enumerable view of multiple dictionaries + + + + + Seeks the first character of a specified line in the text stream. + + The reader. + Line number. The current position is assumed to be line #1. + + Returns true if the line is found, false otherwise. + + + + + Reads characters to a string until end position or a terminator is reached. + Doesn't include the terminator into the resulting string. + Returns null, if the reader is at the end position. + + + + + Reads characters until end position or a terminator is reached. + Returns true if the character has been found (the reader is positioned right behind the character), + false otherwise. + + + + + Creates an open delegate for the given (dynamic)method. + + + + + Creates a closed delegate for the given (dynamic)method. + + + + + Gets a Func of CallSite, object * paramCnt, object delegate type + that's suitable for use in a non-strongly typed call site. + + + + + Returns true if the specified parameter is mandatory, i.e. is not optional and doesn't have a default value. + + + + + Yields all ancestors of the given type including the type itself. + Does not include implemented interfaces. + + + + + Like Type.GetInterfaces, but only returns the interfaces implemented by this type + and not its parents. + + + + + Enumerates extension methods in given assembly. Groups the methods by declaring namespace. + Uses a global cache if is true. + + + + + Binds occurances of generic parameters in against corresponding types in . + Invokes (parameter, type) for each such binding. + Returns false if the is structurally different from or if the binder returns false. + + + + + Determines if a given type matches the type that the method extends. + The match might be non-trivial if the extended type is an open generic type with constraints. + + + + + Splits text and optionally indents first lines - breaks along words, not characters. + + + + + Defines methods to support the comparison of objects for structural equality. + + + + + Determines whether an object is equal to the current instance. + + The object to compare with the current instance. + An object that determines whether the current instance and other are equal. + true if the two objects are equal; otherwise, false. + + + + Returns a hash code for the current instance. + + An object that computes the hash code of the current object. + The hash code for the current instance. + + + + Supports the structural comparison of collection objects. + + + + + Determines whether the current collection object precedes, occurs in the + same position as, or follows another object in the sort order. + + The object to compare with the current instance. + An object that compares the current object and other. + + An integer that indicates the relationship of the current collection object + to other, as shown in the following table. + Return value Description + -1 The current instance precedes other. + 0 The current instance and other are equal. + 1 The current instance follows other. + + + + + Provides a StreamContentProvider for a stream of content backed by a file on disk. + + + + diff --git a/Reference/DLR/Net35/Microsoft.Scripting.Core.dll b/Reference/DLR/Net35/Microsoft.Scripting.Core.dll new file mode 100644 index 000000000..55b921d7a Binary files /dev/null and b/Reference/DLR/Net35/Microsoft.Scripting.Core.dll differ diff --git a/Reference/DLR/Net35/Microsoft.Scripting.Core.xml b/Reference/DLR/Net35/Microsoft.Scripting.Core.xml new file mode 100644 index 000000000..2c271a1ac --- /dev/null +++ b/Reference/DLR/Net35/Microsoft.Scripting.Core.xml @@ -0,0 +1,10867 @@ + + + + Microsoft.Scripting.Core + + + + + Describes arguments in the dynamic binding process. + + + ArgumentCount - all inclusive number of arguments. + ArgumentNames - names for those arguments that are named. + + Argument names match to the argument values in left to right order + and last name corresponds to the last argument. + + Example: + Foo(arg1, arg2, arg3, name1 = arg4, name2 = arg5, name3 = arg6) + + will correspond to: + ArgumentCount: 6 + ArgumentNames: {"name1", "name2", "name3"} + + + + + Creates a new PositionalArgumentInfo. + + The number of arguments. + The argument names. + The new CallInfo + + + + Creates a new CallInfo that represents arguments in the dynamic binding process. + + The number of arguments. + The argument names. + The new CallInfo + + + + Serves as a hash function for the current CallInfo. + + A hash code for the current CallInfo. + + + + Determines whether the specified CallInfo instance is considered equal to the current. + + The instance of CallInfo to compare with the current instance. + true if the specified instance is equal to the current one otherwise, false. + + + + The number of arguments. + + + + + The argument names. + + + + + This API supports the .NET Framework infrastructure and is not intended to be used directly from your code. + + + + + Creates an instance of a dynamic call site used for cache lookup. + + The type of the delegate of the . + The new call site. + + + + Checks if a dynamic site requires an update. + + An instance of the dynamic call site. + true if rule does not need updating, false otherwise. + + + + Checks whether the executed rule matched + + An instance of the dynamic call site. + true if rule matched, false otherwise. + + + + Clears the match flag on the matchmaker call site. + + An instance of the dynamic call site. + + + + Adds a rule to the cache maintained on the dynamic call site. + + The type of the delegate of the . + An instance of the dynamic call site. + An instance of the call site rule. + + + + Updates rules in the cache. + + The type of the delegate of the . + An instance of the dynamic call site. + The matched rule index. + + + + Gets the dynamic binding rules from the call site. + + The type of the delegate of the . + An instance of the dynamic call site. + An array of dynamic binding rules. + + + + Retrieves binding rule cache. + + The type of the delegate of the . + An instance of the dynamic call site. + The cache. + + + + Moves the binding rule within the cache. + + The type of the delegate of the . + The call site rule cache. + An instance of the call site rule. + An index of the call site rule. + + + + Searches the dynamic rule cache for rules applicable to the dynamic operation. + + The type of the delegate of the . + The cache. + The collection of applicable rules. + + + + Updates the call site target with a new rule based on the arguments. + + The type of the delegate of the . + The call site binder. + An instance of the dynamic call site. + Arguments to the call site. + The new call site target. + + + + Represents information about a dynamic get member operation, indicating + if the get member should invoke properties when performing the get. + + + + + Gets the value indicating if this GetMember should invoke properties + when performing the get. The default value when this interface is not present + is true. + + + This property is used by some languages to get a better COM interop experience. + When the value is set to false, the dynamic COM object won't invoke the object + but will instead bind to the name, and return an object that can be invoked or + indexed later. This is useful for indexed properties and languages that don't + produce InvokeMember call sites. + + + + + Represents the invoke member dynamic operation at the call site, + providing the binding semantic and the details about the operation. + + + + + The dynamic call site binder that participates in the binding protocol. + + + The performs the binding of the dynamic operation using the runtime values + as input. On the other hand, the participates in the + binding protocol. + + + + + Class responsible for runtime binding of the dynamic operations on the dynamic call site. + + + + + The Level 2 cache - all rules produced for the same binder. + + + + + Initializes a new instance of the class. + + + + + Performs the runtime binding of the dynamic operation on a set of arguments. + + An array of arguments to the dynamic operation. + The array of instances that represent the parameters of the call site in the binding process. + A LabelTarget used to return the result of the dynamic binding. + + An Expression that performs tests on the dynamic operation arguments, and + performs the dynamic operation if hte tests are valid. If the tests fail on + subsequent occurrences of the dynamic operation, Bind will be called again + to produce a new for the new argument types. + + + + + Provides low-level runtime binding support. Classes can override this and provide a direct + delegate for the implementation of rule. This can enable saving rules to disk, having + specialized rules available at runtime, or providing a different caching policy. + + The target type of the CallSite. + The CallSite the bind is being performed for. + The arguments for the binder. + A new delegate which replaces the CallSite Target. + + + + Adds a target to the cache of known targets. The cached targets will + be scanned before calling BindDelegate to produce the new rule. + + The type of target being added. + The target delegate to be added to the cache. + + + + Gets a label that can be used to cause the binding to be updated. It + indicates that the expression's binding is no longer valid. + This is typically used when the "version" of a dynamic object has + changed. + + + + + Initializes a new instance of the class. + + + + + Performs the runtime binding of the dynamic operation on a set of arguments. + + An array of arguments to the dynamic operation. + The array of instances that represent the parameters of the call site in the binding process. + A LabelTarget used to return the result of the dynamic binding. + + An Expression that performs tests on the dynamic operation arguments, and + performs the dynamic operation if the tests are valid. If the tests fail on + subsequent occurrences of the dynamic operation, Bind will be called again + to produce a new for the new argument types. + + + + + When overridden in the derived class, performs the binding of the dynamic operation. + + The target of the dynamic operation. + An array of arguments of the dynamic operation. + The representing the result of the binding. + + + + Gets an expression that will cause the binding to be updated. It + indicates that the expression's binding is no longer valid. + This is typically used when the "version" of a dynamic object has + changed. + + The Type property of the resulting expression; any type is allowed. + The update expression. + + + + Defers the binding of the operation until later time when the runtime values of all dynamic operation arguments have been computed. + + The target of the dynamic operation. + An array of arguments of the dynamic operation. + The representing the result of the binding. + + + + Defers the binding of the operation until later time when the runtime values of all dynamic operation arguments have been computed. + + An array of arguments of the dynamic operation. + The representing the result of the binding. + + + + The result type of the operation. + + + + + Initializes a new instance of the . + + The name of the member to invoke. + true if the name should be matched ignoring case; false otherwise. + The signature of the arguments at the call site. + + + + Performs the binding of the dynamic invoke member operation. + + The target of the dynamic invoke member operation. + An array of arguments of the dynamic invoke member operation. + The representing the result of the binding. + + + + Performs the binding of the dynamic invoke member operation if the target dynamic object cannot bind. + + The target of the dynamic invoke member operation. + The arguments of the dynamic invoke member operation. + The representing the result of the binding. + + + + When overridden in the derived class, performs the binding of the dynamic invoke member operation if the target dynamic object cannot bind. + + The target of the dynamic invoke member operation. + The arguments of the dynamic invoke member operation. + The binding result to use if binding fails, or null. + The representing the result of the binding. + + + + When overridden in the derived class, performs the binding of the dynamic invoke operation if the target dynamic object cannot bind. + + The target of the dynamic invoke operation. + The arguments of the dynamic invoke operation. + The binding result to use if binding fails, or null. + The representing the result of the binding. + + This method is called by the target when the target implements the invoke member operation + as a sequence of get member, and invoke, to let the + request the binding of the invoke operation only. + + + + + The result type of the operation. + + + + + Gets the name of the member to invoke. + + + + + Gets the value indicating if the string comparison should ignore the case of the member name. + + + + + Gets the signature of the arguments at the call site. + + + + + Represents the binary dynamic operation at the call site, providing the binding semantic and the details about the operation. + + + + + Initializes a new instance of the class. + + The binary operation kind. + + + + Performs the binding of the binary dynamic operation if the target dynamic object cannot bind. + + The target of the dynamic binary operation. + The right hand side operand of the dynamic binary operation. + The representing the result of the binding. + + + + When overridden in the derived class, performs the binding of the binary dynamic operation if the target dynamic object cannot bind. + + The target of the dynamic binary operation. + The right hand side operand of the dynamic binary operation. + The binding result in case the binding fails, or null. + The representing the result of the binding. + + + + Performs the binding of the dynamic binary operation. + + The target of the dynamic operation. + An array of arguments of the dynamic operation. + The representing the result of the binding. + + + + The result type of the operation. + + + + + The binary operation kind. + + + + + A Dynamic Call Site base class. This type is used as a parameter type to the + dynamic site targets. The first parameter of the delegate (T) below must be + of this type. + + + + + The Binder responsible for binding operations at this call site. + This binder is invoked by the UpdateAndExecute below if all Level 0, + Level 1 and Level 2 caches experience cache miss. + + + + + used by Matchmaker sites to indicate rule match. + + + + + Creates a CallSite with the given delegate type and binder. + + The CallSite delegate type. + The CallSite binder. + The new CallSite. + + + + Class responsible for binding dynamic operations on the dynamic site. + + + + + Dynamic site type. + + The delegate type. + + + + The Level 0 cache - a delegate specialized based on the site history. + + + + + The Level 1 cache - a history of the dynamic site. + + + + + Creates an instance of the dynamic call site, initialized with the binder responsible for the + runtime binding of the dynamic operations at this call site. + + The binder responsible for the runtime binding of the dynamic operations at this call site. + The new instance of dynamic call site. + + + + Clears the rule cache ... used by the call site tests. + + + + + The update delegate. Called when the dynamic site experiences cache miss. + + The update delegate. + + + + Class that contains helper methods for DLR CallSites. + + + + + Checks if a is internally used by DLR and should not + be displayed on the language code's stack. + + The input + + True if the input is internally used by DLR and should not + be displayed on the language code's stack. Otherwise, false. + + + + + Represents the convert dynamic operation at the call site, providing the binding semantic and the details about the operation. + + + + + Initializes a new intsance of the . + + The type to convert to. + true if the conversion should consider explicit conversions; otherwise, false. + + + + Performs the binding of the dynamic convert operation if the target dynamic object cannot bind. + + The target of the dynamic convert operation. + The representing the result of the binding. + + + + When overridden in the derived class, performs the binding of the dynamic convert operation if the target dynamic object cannot bind. + + The target of the dynamic convert operation. + The binding result to use if binding fails, or null. + The representing the result of the binding. + + + + Performs the binding of the dynamic convert operation. + + The target of the dynamic convert operation. + An array of arguments of the dynamic convert operation. + The representing the result of the binding. + + + + The type to convert to. + + + + + Gets the value indicating if the conversion should consider explicit conversions. + + + + + The result type of the operation. + + + + + Represents the dynamic delete index operation at the call site, providing the binding semantic and the details about the operation. + + + + + Initializes a new instance of the . + + The signature of the arguments at the call site. + + + + Performs the binding of the dynamic delete index operation. + + The target of the dynamic delete index operation. + An array of arguments of the dynamic delete index operation. + The representing the result of the binding. + + + + Performs the binding of the dynamic delete index operation if the target dynamic object cannot bind. + + The target of the dynamic delete index operation. + The arguments of the dynamic delete index operation. + The representing the result of the binding. + + + + When overridden in the derived class, performs the binding of the dynamic delete index operation if the target dynamic object cannot bind. + + The target of the dynamic delete index operation. + The arguments of the dynamic delete index operation. + The binding result to use if binding fails, or null. + The representing the result of the binding. + + + + The result type of the operation. + + + + + Gets the signature of the arguments at the call site. + + + + + Provides a simple class that can be inherited from to create an object with dynamic behavior + at runtime. Subclasses can override the various binder methods (GetMember, SetMember, Call, etc...) + to provide custom behavior that will be invoked at runtime. + + If a method is not overridden then the DynamicObject does not directly support that behavior and + the call site will determine how the binding should be performed. + + + + + Represents a dynamic object, that can have its operations bound at runtime. + + + Objects that want to participate in the binding process should implement an IDynamicMetaObjectProvider interface, + and implement to return a . + + + + + Returns the responsible for binding operations performed on this object. + + The expression tree representation of the runtime value. + The to bind this object. + + + + Enables derived types to create a new instance of DynamicObject. DynamicObject instances cannot be + directly instantiated because they have no implementation of dynamic behavior. + + + + + Provides the implementation of getting a member. Derived classes can override + this method to customize behavior. When not overridden the call site requesting the + binder determines the behavior. + + The binder provided by the call site. + The result of the get operation. + true if the operation is complete, false if the call site should determine behavior. + + + + Provides the implementation of setting a member. Derived classes can override + this method to customize behavior. When not overridden the call site requesting the + binder determines the behavior. + + The binder provided by the call site. + The value to set. + true if the operation is complete, false if the call site should determine behavior. + + + + Provides the implementation of deleting a member. Derived classes can override + this method to customize behavior. When not overridden the call site requesting the + binder determines the behavior. + + The binder provided by the call site. + true if the operation is complete, false if the call site should determine behavior. + + + + Provides the implementation of calling a member. Derived classes can override + this method to customize behavior. When not overridden the call site requesting the + binder determines the behavior. + + The binder provided by the call site. + The arguments to be used for the invocation. + The result of the invocation. + true if the operation is complete, false if the call site should determine behavior. + + + + Provides the implementation of converting the DynamicObject to another type. Derived classes + can override this method to customize behavior. When not overridden the call site + requesting the binder determines the behavior. + + The binder provided by the call site. + The result of the conversion. + true if the operation is complete, false if the call site should determine behavior. + + + + Provides the implementation of creating an instance of the DynamicObject. Derived classes + can override this method to customize behavior. When not overridden the call site requesting + the binder determines the behavior. + + The binder provided by the call site. + The arguments used for creation. + The created instance. + true if the operation is complete, false if the call site should determine behavior. + + + + Provides the implementation of invoking the DynamicObject. Derived classes can + override this method to customize behavior. When not overridden the call site requesting + the binder determines the behavior. + + The binder provided by the call site. + The arguments to be used for the invocation. + The result of the invocation. + true if the operation is complete, false if the call site should determine behavior. + + + + Provides the implementation of performing a binary operation. Derived classes can + override this method to customize behavior. When not overridden the call site requesting + the binder determines the behavior. + + The binder provided by the call site. + The right operand for the operation. + The result of the operation. + true if the operation is complete, false if the call site should determine behavior. + + + + Provides the implementation of performing a unary operation. Derived classes can + override this method to customize behavior. When not overridden the call site requesting + the binder determines the behavior. + + The binder provided by the call site. + The result of the operation. + true if the operation is complete, false if the call site should determine behavior. + + + + Provides the implementation of performing a get index operation. Derived classes can + override this method to customize behavior. When not overridden the call site requesting + the binder determines the behavior. + + The binder provided by the call site. + The indexes to be used. + The result of the operation. + true if the operation is complete, false if the call site should determine behavior. + + + + Provides the implementation of performing a set index operation. Derived classes can + override this method to custmize behavior. When not overridden the call site requesting + the binder determines the behavior. + + The binder provided by the call site. + The indexes to be used. + The value to set. + true if the operation is complete, false if the call site should determine behavior. + + + + Provides the implementation of performing a delete index operation. Derived classes + can override this method to custmize behavior. When not overridden the call site + requesting the binder determines the behavior. + + The binder provided by the call site. + The indexes to be deleted. + true if the operation is complete, false if the call site should determine behavior. + + + + Returns the enumeration of all dynamic member names. + + The list of dynamic member names. + + + + The provided MetaObject will dispatch to the Dynamic virtual methods. + The object can be encapsulated inside of another MetaObject to + provide custom behavior for individual actions. + + + + + Represents the dynamic binding and a binding logic of an object participating in the dynamic binding. + + + + + Represents an empty array of type . This field is read only. + + + + + Initializes a new instance of the class. + + The expression representing this during the dynamic binding process. + The set of binding restrictions under which the binding is valid. + + + + Initializes a new instance of the class. + + The expression representing this during the dynamic binding process. + The set of binding restrictions under which the binding is valid. + The runtime value represented by the . + + + + Performs the binding of the dynamic conversion operation. + + An instance of the that represents the details of the dynamic operation. + The new representing the result of the binding. + + + + Performs the binding of the dynamic get member operation. + + An instance of the that represents the details of the dynamic operation. + The new representing the result of the binding. + + + + Performs the binding of the dynamic set member operation. + + An instance of the that represents the details of the dynamic operation. + The representing the value for the set member operation. + The new representing the result of the binding. + + + + Performs the binding of the dynamic delete member operation. + + An instance of the that represents the details of the dynamic operation. + The new representing the result of the binding. + + + + Performs the binding of the dynamic get index operation. + + An instance of the that represents the details of the dynamic operation. + An array of instances - indexes for the get index operation. + The new representing the result of the binding. + + + + Performs the binding of the dynamic set index operation. + + An instance of the that represents the details of the dynamic operation. + An array of instances - indexes for the set index operation. + The representing the value for the set index operation. + The new representing the result of the binding. + + + + Performs the binding of the dynamic delete index operation. + + An instance of the that represents the details of the dynamic operation. + An array of instances - indexes for the delete index operation. + The new representing the result of the binding. + + + + Performs the binding of the dynamic invoke member operation. + + An instance of the that represents the details of the dynamic operation. + An array of instances - arguments to the invoke member operation. + The new representing the result of the binding. + + + + Performs the binding of the dynamic invoke operation. + + An instance of the that represents the details of the dynamic operation. + An array of instances - arguments to the invoke operation. + The new representing the result of the binding. + + + + Performs the binding of the dynamic create instance operation. + + An instance of the that represents the details of the dynamic operation. + An array of instances - arguments to the create instance operation. + The new representing the result of the binding. + + + + Performs the binding of the dynamic unary operation. + + An instance of the that represents the details of the dynamic operation. + The new representing the result of the binding. + + + + Performs the binding of the dynamic binary operation. + + An instance of the that represents the details of the dynamic operation. + An instance of the representing the right hand side of the binary operation. + The new representing the result of the binding. + + + + Returns the enumeration of all dynamic member names. + + The list of dynamic member names. + + + + Returns the list of expressions represented by the instances. + + An array of instances to extract expressions from. + The array of expressions. + + + + Creates a meta-object for the specified object. + + The object to get a meta-object for. + The expression representing this during the dynamic binding process. + + If the given object implements and is not a remote object from outside the current AppDomain, + returns the object's specific meta-object returned by . Otherwise a plain new meta-object + with no restrictions is created and returned. + + + + + The expression representing the during the dynamic binding process. + + + + + The set of binding restrictions under which the binding is valid. + + + + + The runtime value represented by this . + + + + + Gets a value indicating whether the has the runtime value. + + + + + Gets the of the runtime value or null if the has no value associated with it. + + + + + Gets the limit type of the . + + Represents the most specific type known about the object represented by the . if runtime value is available, a type of the otherwise. + + + + Helper method for generating expressions that assign byRef call + parameters back to their original variables + + + + + Helper method for generating arguments for calling methods + on DynamicObject. parameters is either a list of ParameterExpressions + to be passed to the method as an object[], or NoArgs to signify that + the target method takes no object[] parameter. + + + + + Helper method for generating a MetaObject which calls a + specific method on Dynamic that returns a result + + + + + Helper method for generating a MetaObject which calls a + specific method on Dynamic that returns a result + + + + + Helper method for generating a MetaObject which calls a + specific method on DynamicObject that returns a result. + + args is either an array of arguments to be passed + to the method as an object[] or NoArgs to signify that + the target method takes no parameters. + + + + + Helper method for generating a MetaObject which calls a + specific method on Dynamic, but uses one of the arguments for + the result. + + args is either an array of arguments to be passed + to the method as an object[] or NoArgs to signify that + the target method takes no parameters. + + + + + Helper method for generating a MetaObject which calls a + specific method on Dynamic, but uses one of the arguments for + the result. + + args is either an array of arguments to be passed + to the method as an object[] or NoArgs to signify that + the target method takes no parameters. + + + + + Checks if the derived type has overridden the specified method. If there is no + implementation for the method provided then Dynamic falls back to the base class + behavior which lets the call site determine how the binder is performed. + + + + + Returns a Restrictions object which includes our current restrictions merged + with a restriction limiting our type + + + + + Returns our Expression converted to DynamicObject + + + + + Represents the dynamic get member operation at the call site, providing the binding semantic and the details about the operation. + + + + + Initializes a new instance of the . + + The name of the member to get. + true if the name should be matched ignoring case; false otherwise. + + + + Performs the binding of the dynamic get member operation if the target dynamic object cannot bind. + + The target of the dynamic get member operation. + The representing the result of the binding. + + + + When overridden in the derived class, performs the binding of the dynamic get member operation if the target dynamic object cannot bind. + + The target of the dynamic get member operation. + The binding result to use if binding fails, or null. + The representing the result of the binding. + + + + Performs the binding of the dynamic get member operation. + + The target of the dynamic get member operation. + An array of arguments of the dynamic get member operation. + The representing the result of the binding. + + + + The result type of the operation. + + + + + Gets the name of the member to get. + + + + + Gets the value indicating if the string comparison should ignore the case of the member name. + + + + + Represents an object with members that can be dynamically added and removed at runtime. + + + + + Creates a new ExpandoObject with no members. + + + + + Try to get the data stored for the specified class at the specified index. If the + class has changed a full lookup for the slot will be performed and the correct + value will be retrieved. + + + + + Sets the data for the specified class at the specified index. If the class has + changed then a full look for the slot will be performed. If the new class does + not have the provided slot then the Expando's class will change. Only case sensitive + setter is supported in ExpandoObject. + + + + + Deletes the data stored for the specified class at the specified index. + + + + + Returns true if the member at the specified index has been deleted, + otherwise false. Call this function holding the lock. + + + + + Promotes the class from the old type to the new type and returns the new + ExpandoData object. + + + + + Internal helper to promote a class. Called from our RuntimeOps helper. This + version simply doesn't expose the ExpandoData object which is a private + data structure. + + + + + Exposes the ExpandoClass which we've associated with this + Expando object. Used for type checks in rules. + + + + + Adds a dynamic test which checks if the version has changed. The test is only necessary for + performance as the methods will do the correct thing if called with an incorrect version. + + + + + Gets the class and the index associated with the given name. Does not update the expando object. Instead + this returns both the original and desired new class. A rule is created which includes the test for the + original class, the promotion to the new class, and the set/delete based on the class post-promotion. + + + + + Returns our Expression converted to our known LimitType + + + + + Returns a Restrictions object which includes our current restrictions merged + with a restriction limiting our type + + + + + Stores the class and the data associated with the class as one atomic + pair. This enables us to do a class check in a thread safe manner w/o + requiring locks. + + + + + the dynamically assigned class associated with the Expando object + + + + + data stored in the expando object, key names are stored in the class. + + Expando._data must be locked when mutating the value. Otherwise a copy of it + could be made and lose values. + + + + + Constructs an empty ExpandoData object with the empty class and no data. + + + + + the version of the ExpandoObject that tracks set and delete operations + + + + + Constructs a new ExpandoData object with the specified class and data. + + + + + Update the associated class and increases the storage for the data array if needed. + + + + + + Indexer for getting/setting the data + + + + + This API supports the .NET Framework infrastructure and is not intended to be used directly from your code. + Contains helper methods called from dynamically generated methods. + + + + + Gets the value of an item in an expando object. + + The expando object. + The class of the expando object. + The index of the member. + The name of the member. + true if the name should be matched ignoring case; false otherwise. + The out parameter containing the value of the member. + True if the member exists in the expando object, otherwise false. + + + + Sets the value of an item in an expando object. + + The expando object. + The class of the expando object. + The index of the member. + The value of the member. + The name of the member. + true if the name should be matched ignoring case; false otherwise. + + Returns the index for the set member. + + + + + Deletes the value of an item in an expando object. + + The expando object. + The class of the expando object. + The index of the member. + The name of the member. + true if the name should be matched ignoring case; false otherwise. + true if the item was successfully removed; otherwise, false. + + + + Checks the version of the expando object. + + The expando object. + The version to check. + true if the version is equal; otherwise, false. + + + + Promotes an expando object from one class to a new class. + + The expando object. + The old class of the expando object. + The new class of the expando object. + + + + Creates an interface that can be used to modify closed over variables at runtime. + + The closure array. + An array of indicies into the closure array where variables are found. + An interface to access variables. + + + + Creates an interface that can be used to modify closed over variables at runtime. + + An interface to access variables. + + + + Quotes the provided expression tree. + + The expression to quote. + The hoisted local state provided by the compiler. + The actual hoisted local values. + The quoted expression. + + + + Combines two runtime variable lists and returns a new list. + + The first list. + The second list. + The index array indicating which list to get variables from. + The merged runtime variables. + + + + An interface to represent values of runtime variables. + + + + + Count of the variables. + + + + + An indexer to get/set the values of the runtime variables. + + An index of the runtime variable. + The value of the runtime variable. + + + + Provides a list of variables, supporing read/write of the values + Exposed via RuntimeVariablesExpression + + + + + Represents a visitor or rewriter for expression trees. + + + This class is designed to be inherited to create more specialized + classes whose functionality requires traversing, examining or copying + an expression tree. + + + + + Initializes a new instance of . + + + + + Dispatches the expression to one of the more specialized visit methods in this class. + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Dispatches the list of expressions to one of the more specialized visit methods in this class. + + The expressions to visit. + The modified expression list, if any of the elements were modified; + otherwise, returns the original expression list. + + + + Visits all nodes in the collection using a specified element visitor. + + The type of the nodes. + The nodes to visit. + A delegate that visits a single element, + optionally replacing it with a new element. + The modified node list, if any of the elements were modified; + otherwise, returns the original node list. + + + + Visits an expression, casting the result back to the original expression type. + + The type of the expression. + The expression to visit. + The name of the calling method; used to report to report a better error message. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + The visit method for this node returned a different type. + + + + Visits an expression, casting the result back to the original expression type. + + The type of the expression. + The expression to visit. + The name of the calling method; used to report to report a better error message. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + The visit method for this node returned a different type. + + + + Visits the children of the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the children of the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the children of the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the children of the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the children of the extension expression. + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + This can be overridden to visit or rewrite specific extension nodes. + If it is not overridden, this method will call , + which gives the node a chance to walk its children. By default, + will try to reduce the node. + + + + + Visits the children of the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the children of the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the children of the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the children of the . + + The type of the delegate. + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the children of the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the children of the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the children of the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the children of the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the children of the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the children of the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the children of the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the children of the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the children of the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the children of the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the children of the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the children of the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the children of the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the children of the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the children of the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the children of the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the children of the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the children of the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the children of the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Visits the children of the . + + The expression to visit. + The modified expression, if it or any subexpression was modified; + otherwise, returns the original expression. + + + + Provides a list of variables, supporing read/write of the values + Exposed via RuntimeVariablesExpression + + + + + Represents a dynamically assigned class. Expando objects which share the same + members will share the same class. Classes are dynamically assigned as the + expando object gains members. + + + + + Constructs the empty ExpandoClass. This is the class used when an + empty Expando object is initially constructed. + + + + + Constructs a new ExpandoClass that can hold onto the specified keys. The + keys must be sorted ordinally. The hash code must be precalculated for + the keys. + + + + + Finds or creates a new ExpandoClass given the existing set of keys + in this ExpandoClass plus the new key to be added. Members in an + ExpandoClass are always stored case sensitively. + + + + + Gets the lists of transitions that are valid from this ExpandoClass + to an ExpandoClass whos keys hash to the apporopriate hash code. + + + + + Gets the index at which the value should be stored for the specified name. + + + + + Gets the index at which the value should be stored for the specified name + case sensitively. Returns the index even if the member is marked as deleted. + + + + + Gets the index at which the value should be stored for the specified name, + the method is only used in the case-insensitive case. + + the name of the member + The ExpandoObject associated with the class + that is used to check if a member has been deleted. + + the exact match if there is one + if there is exactly one member with case insensitive match, return it + otherwise we throw AmbiguousMatchException. + + + + + Gets the names of the keys that can be stored in the Expando class. The + list is sorted ordinally. + + + + + Represents the dynamic get index operation at the call site, providing the binding semantic and the details about the operation. + + + + + Initializes a new instance of the . + + The signature of the arguments at the call site. + + + + Performs the binding of the dynamic get index operation. + + The target of the dynamic get index operation. + An array of arguments of the dynamic get index operation. + The representing the result of the binding. + + + + Performs the binding of the dynamic get index operation if the target dynamic object cannot bind. + + The target of the dynamic get index operation. + The arguments of the dynamic get index operation. + The representing the result of the binding. + + + + When overridden in the derived class, performs the binding of the dynamic get index operation if the target dynamic object cannot bind. + + The target of the dynamic get index operation. + The arguments of the dynamic get index operation. + The binding result to use if binding fails, or null. + The representing the result of the binding. + + + + The result type of the operation. + + + + + Gets the signature of the arguments at the call site. + + + + + Represents the create dynamic operation at the call site, providing the binding semantic and the details about the operation. + + + + + Initializes a new intsance of the . + + The signature of the arguments at the call site. + + + + Performs the binding of the dynamic create operation if the target dynamic object cannot bind. + + The target of the dynamic create operation. + The arguments of the dynamic create operation. + The representing the result of the binding. + + + + When overridden in the derived class, performs the binding of the dynamic create operation if the target dynamic object cannot bind. + + The target of the dynamic create operation. + The arguments of the dynamic create operation. + The binding result to use if binding fails, or null. + The representing the result of the binding. + + + + Performs the binding of the dynamic create operation. + + The target of the dynamic create operation. + An array of arguments of the dynamic create operation. + The representing the result of the binding. + + + + The result type of the operation. + + + + + Gets the signature of the arguments at the call site. + + + + + Represents the dynamic delete member operation at the call site, providing the binding semantic and the details about the operation. + + + + + Initializes a new instance of the . + + The name of the member to delete. + true if the name should be matched ignoring case; false otherwise. + + + + Performs the binding of the dynamic delete member operation if the target dynamic object cannot bind. + + The target of the dynamic delete member operation. + The representing the result of the binding. + + + + When overridden in the derived class, performs the binding of the dynamic delete member operation if the target dynamic object cannot bind. + + The target of the dynamic delete member operation. + The binding result to use if binding fails, or null. + The representing the result of the binding. + + + + Performs the binding of the dynamic delete member operation. + + The target of the dynamic delete member operation. + An array of arguments of the dynamic delete member operation. + The representing the result of the binding. + + + + Gets the name of the member to delete. + + + + + Gets the value indicating if the string comparison should ignore the case of the member name. + + + + + The result type of the operation. + + + + + Represents the invoke dynamic operation at the call site, providing the binding semantic and the details about the operation. + + + + + Initializes a new instance of the . + + The signature of the arguments at the call site. + + + + Performs the binding of the dynamic invoke operation if the target dynamic object cannot bind. + + The target of the dynamic invoke operation. + The arguments of the dynamic invoke operation. + The representing the result of the binding. + + + + Performs the binding of the dynamic invoke operation if the target dynamic object cannot bind. + + The target of the dynamic invoke operation. + The arguments of the dynamic invoke operation. + The binding result to use if binding fails, or null. + The representing the result of the binding. + + + + Performs the binding of the dynamic invoke operation. + + The target of the dynamic invoke operation. + An array of arguments of the dynamic invoke operation. + The representing the result of the binding. + + + + The result type of the operation. + + + + + Gets the signature of the arguments at the call site. + + + + + Represents a set of binding restrictions on the under which the dynamic binding is valid. + + + + + Represents an empty set of binding restrictions. This field is read only. + + + + + Merges the set of binding restrictions with the current binding restrictions. + + The set of restrictions with which to merge the current binding restrictions. + The new set of binding restrictions. + + + + Creates the binding restriction that check the expression for runtime type identity. + + The expression to test. + The exact type to test. + The new binding restrictions. + + + + The method takes a DynamicMetaObject, and returns an instance restriction for testing null if the object + holds a null value, otherwise returns a type restriction. + + + + + Creates the binding restriction that checks the expression for object instance identity. + + The expression to test. + The exact object instance to test. + The new binding restrictions. + + + + Creates the binding restriction that checks the expression for arbitrary immutable properties. + + The expression expression the restrictions. + The new binding restrictions. + + By convention, the general restrictions created by this method must only test + immutable object properties. + + + + + Combines binding restrictions from the list of instances into one set of restrictions. + + The list of instances from which to combine restrictions. + The new set of binding restrictions. + + + + Creates the representing the binding restrictions. + + The expression tree representing the restrictions. + + + + Builds a balanced tree of AndAlso nodes. + We do this so the compiler won't stack overflow if we have many + restrictions. + + + + + This API supports the .NET Framework infrastructure and is not intended to be used directly from your code. + Represents a cache of runtime binding rules. + + The delegate type. + + + + Represents the dynamic set index operation at the call site, providing the binding semantic and the details about the operation. + + + + + Initializes a new instance of the . + + The signature of the arguments at the call site. + + + + Performs the binding of the dynamic set index operation. + + The target of the dynamic set index operation. + An array of arguments of the dynamic set index operation. + The representing the result of the binding. + + + + Performs the binding of the dynamic set index operation if the target dynamic object cannot bind. + + The target of the dynamic set index operation. + The arguments of the dynamic set index operation. + The value to set to the collection. + The representing the result of the binding. + + + + When overridden in the derived class, performs the binding of the dynamic set index operation if the target dynamic object cannot bind. + + The target of the dynamic set index operation. + The arguments of the dynamic set index operation. + The value to set to the collection. + The binding result to use if binding fails, or null. + The representing the result of the binding. + + + + The result type of the operation. + + + + + Gets the signature of the arguments at the call site. + + + + + Represents the dynamic set member operation at the call site, providing the binding semantic and the details about the operation. + + + + + Initializes a new instance of the . + + The name of the member to get. + true if the name should be matched ignoring case; false otherwise. + + + + Performs the binding of the dynamic set member operation. + + The target of the dynamic set member operation. + An array of arguments of the dynamic set member operation. + The representing the result of the binding. + + + + Performs the binding of the dynamic set member operation if the target dynamic object cannot bind. + + The target of the dynamic set member operation. + The value to set to the member. + The representing the result of the binding. + + + + Performs the binding of the dynamic set member operation if the target dynamic object cannot bind. + + The target of the dynamic set member operation. + The value to set to the member. + The binding result to use if binding fails, or null. + The representing the result of the binding. + + + + The result type of the operation. + + + + + Gets the name of the member to get. + + + + + Gets the value indicating if the string comparison should ignore the case of the member name. + + + + + The base type for all nodes in Expression Trees. + + + + + Creates a with the specified span. + + The that represents the source file. + The start line of this . Must be greater than 0. + The start column of this . Must be greater than 0. + The end line of this . Must be greater or equal than the start line. + The end column of this . If the end line is the same as the start line, it must be greater or equal than the start column. In any case, must be greater than 0. + An instance of . + + + + Creates a for clearing a sequence point. + + The that represents the source file. + An instance of for clearning a sequence point. + + + + Creates an instance of . + + A to set the equal to. + A that has the property set to the specified value. + + + + Creates an instance of . + + A to set the equal to. + A to set the equal to. + A that has the + and properties set to the specified value. + + + + Creates an instance of . + + A to set the equal to. + A to set the equal to. + A to set the equal to. + A that has the + and + and properties set to the specified value. + + + + Creates an instance of . + + A to set the equal to. + A to set the equal to. + A to set the equal to. + A to set the equal to. + A that has the + and + and + and properties set to the specified value. + + + + Creates a representing a break statement. + + The that the will jump to. + + A with equal to Break, + the property set to , and a null value to be passed to the target label upon jumping. + + + + + Creates a representing a break statement. The value passed to the label upon jumping can be specified. + + The that the will jump to. + The value that will be passed to the associated label upon jumping. + + A with equal to Break, + the property set to , + and to be passed to the target label upon jumping. + + + + + Creates a representing a break statement with the specified type. + + The that the will jump to. + An to set the property equal to. + + A with equal to Break, + the property set to , + and the property set to . + + + + + Creates a representing a break statement with the specified type. + The value passed to the label upon jumping can be specified. + + The that the will jump to. + The value that will be passed to the associated label upon jumping. + An to set the property equal to. + + A with equal to Break, + the property set to , + the property set to , + and to be passed to the target label upon jumping. + + + + + Creates a representing a continue statement. + + The that the will jump to. + + A with equal to Continue, + the property set to , + and a null value to be passed to the target label upon jumping. + + + + + Creates a representing a continue statement with the specified type. + + The that the will jump to. + An to set the property equal to. + + A with equal to Continue, + the property set to , + the property set to , + and a null value to be passed to the target label upon jumping. + + + + + Creates a representing a return statement. + + The that the will jump to. + + A with equal to Return, + the property set to , + and a null value to be passed to the target label upon jumping. + + + + + Creates a representing a return statement with the specified type. + + The that the will jump to. + An to set the property equal to. + + A with equal to Return, + the property set to , + the property set to , + and a null value to be passed to the target label upon jumping. + + + + + Creates a representing a return statement. The value passed to the label upon jumping can be specified. + + The that the will jump to. + The value that will be passed to the associated label upon jumping. + + A with equal to Continue, + the property set to , + and to be passed to the target label upon jumping. + + + + + Creates a representing a return statement with the specified type. + The value passed to the label upon jumping can be specified. + + The that the will jump to. + The value that will be passed to the associated label upon jumping. + An to set the property equal to. + + A with equal to Continue, + the property set to , + the property set to , + and to be passed to the target label upon jumping. + + + + + Creates a representing a goto. + + The that the will jump to. + + A with equal to Goto, + the property set to the specified value, + and a null value to be passed to the target label upon jumping. + + + + + Creates a representing a goto with the specified type. + + The that the will jump to. + An to set the property equal to. + + A with equal to Goto, + the property set to the specified value, + the property set to , + and a null value to be passed to the target label upon jumping. + + + + + Creates a representing a goto. The value passed to the label upon jumping can be specified. + + The that the will jump to. + The value that will be passed to the associated label upon jumping. + + A with equal to Goto, + the property set to , + and to be passed to the target label upon jumping. + + + + + Creates a representing a goto with the specified type. + The value passed to the label upon jumping can be specified. + + The that the will jump to. + The value that will be passed to the associated label upon jumping. + An to set the property equal to. + + A with equal to Goto, + the property set to , + the property set to , + and to be passed to the target label upon jumping. + + + + + Creates a representing a jump of the specified . + The value passed to the label upon jumping can also be specified. + + The of the . + The that the will jump to. + The value that will be passed to the associated label upon jumping. + An to set the property equal to. + + A with equal to , + the property set to , + the property set to , + and to be passed to the target label upon jumping. + + + + + Creates a that represents a dynamic operation bound by the provided . + + The type of the delegate used by the . + The runtime binder for the dynamic operation. + The arguments to the dynamic operation. + + A that has equal to + Dynamic and has the + DelegateType, + Binder, and + Arguments set to the specified values. + + + + + Creates a that represents a dynamic operation bound by the provided . + + The type of the delegate used by the . + The runtime binder for the dynamic operation. + The arguments to the dynamic operation. + + A that has equal to + Dynamic and has the + DelegateType, + Binder, and + Arguments set to the specified values. + + + + + Creates a that represents a dynamic operation bound by the provided and one argument. + + The type of the delegate used by the . + The runtime binder for the dynamic operation. + The argument to the dynamic operation. + + A that has equal to + Dynamic and has the + DelegateType, + Binder, and + Arguments set to the specified values. + + + + + Creates a that represents a dynamic operation bound by the provided and two arguments. + + The type of the delegate used by the . + The runtime binder for the dynamic operation. + The first argument to the dynamic operation. + The second argument to the dynamic operation. + + A that has equal to + Dynamic and has the + DelegateType, + Binder, and + Arguments set to the specified values. + + + + + Creates a that represents a dynamic operation bound by the provided and three arguments. + + The type of the delegate used by the . + The runtime binder for the dynamic operation. + The first argument to the dynamic operation. + The second argument to the dynamic operation. + The third argument to the dynamic operation. + + A that has equal to + Dynamic and has the + DelegateType, + Binder, and + Arguments set to the specified values. + + + + + Creates a that represents a dynamic operation bound by the provided and four arguments. + + The type of the delegate used by the . + The runtime binder for the dynamic operation. + The first argument to the dynamic operation. + The second argument to the dynamic operation. + The third argument to the dynamic operation. + The fourth argument to the dynamic operation. + + A that has equal to + Dynamic and has the + DelegateType, + Binder, and + Arguments set to the specified values. + + + + + Creates a that represents a dynamic operation bound by the provided . + + The runtime binder for the dynamic operation. + The result type of the dynamic expression. + The arguments to the dynamic operation. + + A that has equal to + Dynamic and has the + Binder and + Arguments set to the specified values. + + + The DelegateType property of the + result will be inferred from the types of the arguments and the specified return type. + + + + + Creates a that represents a dynamic operation bound by the provided . + + The runtime binder for the dynamic operation. + The result type of the dynamic expression. + The first argument to the dynamic operation. + + A that has equal to + Dynamic and has the + Binder and + Arguments set to the specified values. + + + The DelegateType property of the + result will be inferred from the types of the arguments and the specified return type. + + + + + Creates a that represents a dynamic operation bound by the provided . + + The runtime binder for the dynamic operation. + The result type of the dynamic expression. + The first argument to the dynamic operation. + The second argument to the dynamic operation. + + A that has equal to + Dynamic and has the + Binder and + Arguments set to the specified values. + + + The DelegateType property of the + result will be inferred from the types of the arguments and the specified return type. + + + + + Creates a that represents a dynamic operation bound by the provided . + + The runtime binder for the dynamic operation. + The result type of the dynamic expression. + The first argument to the dynamic operation. + The second argument to the dynamic operation. + The third argument to the dynamic operation. + + A that has equal to + Dynamic and has the + Binder and + Arguments set to the specified values. + + + The DelegateType property of the + result will be inferred from the types of the arguments and the specified return type. + + + + + Creates a that represents a dynamic operation bound by the provided . + + The runtime binder for the dynamic operation. + The result type of the dynamic expression. + The first argument to the dynamic operation. + The second argument to the dynamic operation. + The third argument to the dynamic operation. + The fourth argument to the dynamic operation. + + A that has equal to + Dynamic and has the + Binder and + Arguments set to the specified values. + + + The DelegateType property of the + result will be inferred from the types of the arguments and the specified return type. + + + + + Creates a that represents a dynamic operation bound by the provided . + + The runtime binder for the dynamic operation. + The result type of the dynamic expression. + The arguments to the dynamic operation. + + A that has equal to + Dynamic and has the + Binder and + Arguments set to the specified values. + + + The DelegateType property of the + result will be inferred from the types of the arguments and the specified return type. + + + + + Creates a that represents an assignment operation. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + + Creates a BinaryExpression, given the left and right operands, by calling an appropriate factory method. + + The ExpressionType that specifies the type of binary operation. + An Expression that represents the left operand. + An Expression that represents the right operand. + The BinaryExpression that results from calling the appropriate factory method. + + + + Creates a BinaryExpression, given the left and right operands, by calling an appropriate factory method. + + The ExpressionType that specifies the type of binary operation. + An Expression that represents the left operand. + An Expression that represents the right operand. + true to set IsLiftedToNull to true; false to set IsLiftedToNull to false. + A MethodInfo that specifies the implementing method. + The BinaryExpression that results from calling the appropriate factory method. + + + + + Creates a BinaryExpression, given the left and right operands, by calling an appropriate factory method. + + The ExpressionType that specifies the type of binary operation. + An Expression that represents the left operand. + An Expression that represents the right operand. + true to set IsLiftedToNull to true; false to set IsLiftedToNull to false. + A MethodInfo that specifies the implementing method. + A LambdaExpression that represents a type conversion function. This parameter is used if binaryType is Coalesce or compound assignment. + The BinaryExpression that results from calling the appropriate factory method. + + + + Creates a that represents an equality comparison. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents an equality comparison. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + true to set IsLiftedToNull to true; false to set IsLiftedToNull to false. + A that has the property equal to + and the , , , and properties set to the specified values. + + + + + Creates a that represents a reference equality comparison. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + + Creates a that represents an inequality comparison. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents an inequality comparison. + + An to set the property equal to. + An to set the property equal to. + true to set IsLiftedToNull to true; false to set IsLiftedToNull to false. + A to set the property equal to. + A that has the property equal to + and the , , , and properties set to the specified values. + + + + + Creates a that represents a reference inequality comparison. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + + Creates a that represents a "greater than" numeric comparison. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents a "greater than" numeric comparison. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + true to set IsLiftedToNull to true; false to set IsLiftedToNull to false. + A that has the property equal to + and the , , , and properties set to the specified values. + + + + + Creates a that represents a "less than" numeric comparison. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents a "less than" numeric comparison. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + true to set IsLiftedToNull to true; false to set IsLiftedToNull to false. + A that has the property equal to + and the , , , and properties set to the specified values. + + + + + Creates a that represents a "greater than or equal" numeric comparison. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents a "greater than or equal" numeric comparison. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + true to set IsLiftedToNull to true; false to set IsLiftedToNull to false. + A that has the property equal to + and the , , , and properties set to the specified values. + + + + + Creates a that represents a "less than or equal" numeric comparison. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents a "less than or equal" numeric comparison. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + true to set IsLiftedToNull to true; false to set IsLiftedToNull to false. + A that has the property equal to + and the , , , and properties set to the specified values. + + + + + Creates a that represents a conditional AND operation that evaluates the second operand only if it has to. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents a conditional AND operation that evaluates the second operand only if it has to. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , and properties set to the specified values. + + + + + Creates a that represents a conditional OR operation that evaluates the second operand only if it has to. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents a conditional OR operation that evaluates the second operand only if it has to. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , and properties set to the specified values. + + + + + Creates a BinaryExpression that represents a coalescing operation. + + An to set the property equal to. + An to set the property equal to. + A BinaryExpression that has the NodeType property equal to Coalesce and the Left and Right properties set to the specified values. + + + + Creates a BinaryExpression that represents a coalescing operation. + + An to set the property equal to. + An to set the property equal to. + A LambdaExpression to set the Conversion property equal to. + A BinaryExpression that has the NodeType property equal to Coalesce and the Left, Right and Conversion properties set to the specified values. + + + + + Creates a that represents an arithmetic addition operation that does not have overflow checking. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents an arithmetic addition operation that does not have overflow checking. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , and properties set to the specified values. + + + + + Creates a that represents an addition assignment operation that does not have overflow checking. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents an addition assignment operation that does not have overflow checking. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , and properties set to the specified values. + + + + + Creates a that represents an addition assignment operation that does not have overflow checking. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , , + and properties set to the specified values. + + + + + Creates a that represents an addition assignment operation that has overflow checking. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and + properties set to the specified values. + + + + + Creates a that represents an addition assignment operation that has overflow checking. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , and properties set to the specified values. + + + + + Creates a that represents an addition assignment operation that has overflow checking. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , , + and properties set to the specified values. + + + + + Creates a that represents an arithmetic addition operation that has overflow checking. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents an arithmetic addition operation that has overflow checking. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , and properties set to the specified values. + + + + + Creates a that represents an arithmetic subtraction operation that does not have overflow checking. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents an arithmetic subtraction operation that does not have overflow checking. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , and properties set to the specified values. + + + + + Creates a that represents a subtraction assignment operation that does not have overflow checking. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents a subtraction assignment operation that does not have overflow checking. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , and properties set to the specified values. + + + + + Creates a that represents a subtraction assignment operation that does not have overflow checking. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , , + and properties set to the specified values. + + + + + Creates a that represents a subtraction assignment operation that has overflow checking. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents a subtraction assignment operation that has overflow checking. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , and properties set to the specified values. + + + + + Creates a that represents a subtraction assignment operation that has overflow checking. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , , + and properties set to the specified values. + + + + + Creates a that represents an arithmetic subtraction operation that has overflow checking. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents an arithmetic subtraction operation that has overflow checking. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , and properties set to the specified values. + + + + + Creates a that represents an arithmetic division operation. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents an arithmetic division operation. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , and properties set to the specified values. + + + + + Creates a that represents a division assignment operation that does not have overflow checking. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents a division assignment operation that does not have overflow checking. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , and properties set to the specified values. + + + + + Creates a that represents a division assignment operation that does not have overflow checking. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , , + and properties set to the specified values. + + + + + Creates a that represents an arithmetic remainder operation. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents an arithmetic remainder operation. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , and properties set to the specified values. + + + + + Creates a that represents a remainder assignment operation. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents a remainder assignment operation. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , and properties set to the specified values. + + + + + Creates a that represents a remainder assignment operation. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , , + and properties set to the specified values. + + + + + Creates a that represents an arithmetic multiplication operation that does not have overflow checking. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents an arithmetic multiplication operation that does not have overflow checking. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , and properties set to the specified values. + + + + + Creates a that represents a multiplication assignment operation that does not have overflow checking. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents a multiplication assignment operation that does not have overflow checking. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , and properties set to the specified values. + + + + + Creates a that represents a multiplication assignment operation that does not have overflow checking. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , , + and properties set to the specified values. + + + + + Creates a that represents a multiplication assignment operation that has overflow checking. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents a multiplication assignment operation that has overflow checking. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , and properties set to the specified values. + + + + + Creates a that represents a multiplication assignment operation that has overflow checking. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , , + and properties set to the specified values. + + + + + Creates a that represents an arithmetic multiplication operation that has overflow checking. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents an arithmetic multiplication operation that has overflow checking. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , and properties set to the specified values. + + + + + Creates a that represents an bitwise left-shift operation. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents an bitwise left-shift operation. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , and properties set to the specified values. + + + + + Creates a that represents a bitwise left-shift assignment operation. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents a bitwise left-shift assignment operation. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , and properties set to the specified values. + + + + + Creates a that represents a bitwise left-shift assignment operation. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , , + and properties set to the specified values. + + + + + Creates a that represents an bitwise right-shift operation. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents an bitwise right-shift operation. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , and properties set to the specified values. + + + + + Creates a that represents a bitwise right-shift assignment operation. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents a bitwise right-shift assignment operation. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , and properties set to the specified values. + + + + + Creates a that represents a bitwise right-shift assignment operation. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , , + and properties set to the specified values. + + + + + Creates a that represents an bitwise AND operation. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents an bitwise AND operation. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , and properties set to the specified values. + + + + + Creates a that represents a bitwise AND assignment operation. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents a bitwise AND assignment operation. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , and properties set to the specified values. + + + + + Creates a that represents a bitwise AND assignment operation. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , , + and properties set to the specified values. + + + + + Creates a that represents an bitwise OR operation. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents an bitwise OR operation. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , and properties set to the specified values. + + + + + Creates a that represents a bitwise OR assignment operation. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents a bitwise OR assignment operation. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , and properties set to the specified values. + + + + + Creates a that represents a bitwise OR assignment operation. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , , + and properties set to the specified values. + + + + + Creates a that represents a bitwise or logical XOR operation, using op_ExclusiveOr for user-defined types. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents a bitwise or logical XOR operation, using op_ExclusiveOr for user-defined types. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , and properties set to the specified values. + + + + + Creates a that represents a bitwise or logical XOR assignment operation, using op_ExclusiveOr for user-defined types. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents a bitwise or logical XOR assignment operation, using op_ExclusiveOr for user-defined types. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , and properties set to the specified values. + + + + + Creates a that represents a bitwise or logical XOR assignment operation, using op_ExclusiveOr for user-defined types. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , , + and properties set to the specified values. + + + + + Creates a that represents raising a number to a power. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents raising a number to a power. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , and properties set to the specified values. + + + + + Creates a that represents raising an expression to a power and assigning the result back to the expression. + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the and properties set to the specified values. + + + + Creates a that represents raising an expression to a power and assigning the result back to the expression. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , and properties set to the specified values. + + + + + Creates a that represents raising an expression to a power and assigning the result back to the expression. + + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , , + and properties set to the specified values. + + + + + Creates a BinaryExpression that represents applying an array index operator to an array of rank one. + + An Expression to set the Left property equal to. + An Expression to set the Right property equal to. + A BinaryExpression that has the NodeType property equal to ArrayIndex and the Left and Right properties set to the specified values. + + + + Creates a that contains two expressions and has no variables. + + The first expression in the block. + The second expression in the block. + The created . + + + + Creates a that contains three expressions and has no variables. + + The first expression in the block. + The second expression in the block. + The third expression in the block. + The created . + + + + Creates a that contains four expressions and has no variables. + + The first expression in the block. + The second expression in the block. + The third expression in the block. + The fourth expression in the block. + The created . + + + + Creates a that contains five expressions and has no variables. + + The first expression in the block. + The second expression in the block. + The third expression in the block. + The fourth expression in the block. + The fifth expression in the block. + The created . + + + + Creates a that contains the given expressions and has no variables. + + The expressions in the block. + The created . + + + + Creates a that contains the given expressions and has no variables. + + The expressions in the block. + The created . + + + + Creates a that contains the given expressions, has no variables and has specific result type. + + The result type of the block. + The expressions in the block. + The created . + + + + Creates a that contains the given expressions, has no variables and has specific result type. + + The result type of the block. + The expressions in the block. + The created . + + + + Creates a that contains the given variables and expressions. + + The variables in the block. + The expressions in the block. + The created . + + + + Creates a that contains the given variables and expressions. + + The result type of the block. + The variables in the block. + The expressions in the block. + The created . + + + + Creates a that contains the given variables and expressions. + + The variables in the block. + The expressions in the block. + The created . + + + + Creates a that contains the given variables and expressions. + + The result type of the block. + The variables in the block. + The expressions in the block. + The created . + + + + Creates a representing a catch statement. + The of object to be caught can be specified but no reference to the object + will be available for use in the . + + The of this will handle. + The body of the catch statement. + The created . + + + + Creates a representing a catch statement with a reference to the caught object for use in the handler body. + + A representing a reference to the object caught by this handler. + The body of the catch statement. + The created . + + + + Creates a representing a catch statement with + an filter but no reference to the caught object. + + The of this will handle. + The body of the catch statement. + The body of the filter. + The created . + + + + Creates a representing a catch statement with + an filter and a reference to the caught object. + + A representing a reference to the object caught by this handler. + The body of the catch statement. + The body of the filter. + The created . + + + + Creates a representing a catch statement with the specified elements. + + The of this will handle. + A representing a reference to the object caught by this handler. + The body of the catch statement. + The body of the filter. + The created . + must be non-null and match the type of (if it is supplied). + + + + Creates a . + + An to set the property equal to. + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the , , + and properties set to the specified values. + + + + Creates a . + + An to set the property equal to. + An to set the property equal to. + An to set the property equal to. + A to set the property equal to. + A that has the property equal to + and the , , + and properties set to the specified values. + This method allows explicitly unifying the result type of the conditional expression in cases where the types of + and expressions are not equal. Types of both and must be implicitly + reference assignable to the result type. The is allowed to be . + + + + Creates a . + + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the , , + properties set to the specified values. The property is set to default expression and + the type of the resulting returned by this method is . + + + + Creates a . + + An to set the property equal to. + An to set the property equal to. + An to set the property equal to. + A that has the property equal to + and the , , + and properties set to the specified values. The type of the resulting + returned by this method is . + + + + Creates a that has the property set to the specified value. . + + An to set the property equal to. + + A that has the property equal to + and the property set to the specified value. + + + + + Creates a that has the + and properties set to the specified values. . + + An to set the property equal to. + A to set the property equal to. + + A that has the property equal to + and the and + properties set to the specified values. + + + + + Creates an empty expression that has type. + + + A that has the property equal to + and the property set to . + + + + + Creates a that has the property set to the specified type. + + A to set the property equal to. + + A that has the property equal to + and the property set to the specified type. + + + + + Creates an ElementInit expression that represents the initialization of a list. + + The for the list's Add method. + An array containing the Expressions to be used to initialize the list. + The created ElementInit expression. + + + + Creates an ElementInit expression that represents the initialization of a list. + + The for the list's Add method. + An containing elements to initialize the list. + The created ElementInit expression. + + + + Constructs a new instance of . + + + + + Reduces this node to a simpler expression. If CanReduce returns + true, this should return a valid expression. This method is + allowed to return another node which itself must be reduced. + + The reduced expression. + + + + Reduces the node and then calls the visitor delegate on the reduced expression. + Throws an exception if the node isn't reducible. + + An instance of . + The expression being visited, or an expression which should replace it in the tree. + + Override this method to provide logic to walk the node's children. + A typical implementation will call visitor.Visit on each of its + children, and if any of them change, should return a new copy of + itself with the modified children. + + + + + Dispatches to the specific visit method for this node type. For + example, will call into + . + + The visitor to visit this node with. + The result of visiting this node. + + This default implementation for + nodes will call . + Override this method to call into a more specific method on a derived + visitor class of ExprressionVisitor. However, it should still + support unknown visitors by calling VisitExtension. + + + + + Reduces this node to a simpler expression. If CanReduce returns + true, this should return a valid expression. This method is + allowed to return another node which itself must be reduced. + + The reduced expression. + + Unlike Reduce, this method checks that the reduced node satisfies + certain invariants. + + + + + Reduces the expression to a known node type (i.e. not an Extension node) + or simply returns the expression if it is already a known type. + + The reduced expression. + + + + Creates a representation of the Expression. + + A representation of the Expression. + + + + Writes a representation of the to a . + + A that will be used to build the string representation. + + + + Helper used for ensuring we only return 1 instance of a ReadOnlyCollection of T. + + This is called from various methods where we internally hold onto an IList of T + or a readonly collection of T. We check to see if we've already returned a + readonly collection of T and if so simply return the other one. Otherwise we do + a thread-safe replacement of the list w/ a readonly collection which wraps it. + + Ultimately this saves us from having to allocate a ReadOnlyCollection for our + data types because the compiler is capable of going directly to the IList of T. + + + + + Helper used for ensuring we only return 1 instance of a ReadOnlyCollection of T. + + This is similar to the ReturnReadOnly of T. This version supports nodes which hold + onto multiple Expressions where one is typed to object. That object field holds either + an expression or a ReadOnlyCollection of Expressions. When it holds a ReadOnlyCollection + the IList which backs it is a ListArgumentProvider which uses the Expression which + implements IArgumentProvider to get 2nd and additional values. The ListArgumentProvider + continues to hold onto the 1st expression. + + This enables users to get the ReadOnlyCollection w/o it consuming more memory than if + it was just an array. Meanwhile The DLR internally avoids accessing which would force + the readonly collection to be created resulting in a typical memory savings. + + + + + Helper which is used for specialized subtypes which use ReturnReadOnly(ref object, ...). + This is the reverse version of ReturnReadOnly which takes an IArgumentProvider. + + This is used to return the 1st argument. The 1st argument is typed as object and either + contains a ReadOnlyCollection or the Expression. We check for the Expression and if it's + present we return that, otherwise we return the 1st element of the ReadOnlyCollection. + + + + + Creates an that represents accessing an indexed property in an object. + + The object to which the property belongs. Should be null if the property is static(shared). + An representing the property to index. + An IEnumerable{Expression} contaning the arguments to be used to index the property. + The created . + + + + Creates an to access an array. + + An expression representing the array to index. + An array containing expressions used to index the array. + The expression representing the array can be obtained by using the MakeMemberAccess method, + or through NewArrayBounds or NewArrayInit. + The created . + + + + Creates an to access an array. + + An expression representing the array to index. + An containing expressions used to index the array. + The expression representing the array can be obtained by using the MakeMemberAccess method, + or through NewArrayBounds or NewArrayInit. + The created . + + + + Creates an representing the access to an indexed property. + + The object to which the property belongs. If the property is static/shared, it must be null. + The name of the indexer. + An array of objects that are used to index the property. + The created . + + + + The method finds the instance property with the specified name in a type. The property's type signature needs to be compatible with + the arguments if it is a indexer. If the arguments is null or empty, we get a normal property. + + + + + Creates an representing the access to an indexed property. + + The object to which the property belongs. If the property is static/shared, it must be null. + The that represents the property to index. + An array of objects that are used to index the property. + The created . + + + + Creates an representing the access to an indexed property. + + The object to which the property belongs. If the property is static/shared, it must be null. + The that represents the property to index. + An of objects that are used to index the property. + The created . + + + + Creates an that + applies a delegate or lambda expression to a list of argument expressions. + + + An that + applies the specified delegate or lambda expression to the provided arguments. + + + An that represents the delegate + or lambda expression to be applied. + + + An array of objects + that represent the arguments that the delegate or lambda expression is applied to. + + + is null. + + .Type does not represent a delegate type or an .-or-The property of an element of is not assignable to the type of the corresponding parameter of the delegate represented by . + + does not contain the same number of elements as the list of parameters for the delegate represented by . + + + + Creates an that + applies a delegate or lambda expression to a list of argument expressions. + + + An that + applies the specified delegate or lambda expression to the provided arguments. + + + An that represents the delegate + or lambda expression to be applied. + + + An of objects + that represent the arguments that the delegate or lambda expression is applied to. + + + is null. + + .Type does not represent a delegate type or an .-or-The property of an element of is not assignable to the type of the corresponding parameter of the delegate represented by . + + does not contain the same number of elements as the list of parameters for the delegate represented by . + + + + Gets the delegate's Invoke method; used by InvocationExpression. + + The expression to be invoked. + + + + Creates a representing a label with void type and no name. + + The new . + + + + Creates a representing a label with void type and the given name. + + The name of the label. + The new . + + + + Creates a representing a label with the given type. + + The type of value that is passed when jumping to the label. + The new . + + + + Creates a representing a label with the given type and name. + + The type of value that is passed when jumping to the label. + The name of the label. + The new . + + + + Creates a representing a label with no default value. + + The which this will be associated with. + A with no default value. + + + + Creates a representing a label with the given default value. + + The which this will be associated with. + The value of this when the label is reached through normal control flow. + A with the given default value. + + + + Creates an Expression{T} given the delegate type. Caches the + factory method to speed up repeated creations for the same T. + + + + + Creates an where the delegate type is known at compile time. + + The delegate type. + An to set the property equal to. + An array that contains objects to use to populate the collection. + An that has the property equal to and the and properties set to the specified values. + + + + Creates an where the delegate type is known at compile time. + + The delegate type. + An to set the property equal to. + A that indicates if tail call optimization will be applied when compiling the created expression. + An array that contains objects to use to populate the collection. + An that has the property equal to and the and properties set to the specified values. + + + + Creates an where the delegate type is known at compile time. + + The delegate type. + An to set the property equal to. + An that contains objects to use to populate the collection. + An that has the property equal to and the and properties set to the specified values. + + + + Creates an where the delegate type is known at compile time. + + The delegate type. + An to set the property equal to. + A that indicates if tail call optimization will be applied when compiling the created expression. + An that contains objects to use to populate the collection. + An that has the property equal to and the and properties set to the specified values. + + + + Creates an where the delegate type is known at compile time. + + The delegate type. + An to set the property equal to. + An that contains objects to use to populate the collection. + The name of the lambda. Used for generating debugging info. + An that has the property equal to and the and properties set to the specified values. + + + + Creates an where the delegate type is known at compile time. + + The delegate type. + An to set the property equal to. + The name of the lambda. Used for generating debugging info. + An that contains objects to use to populate the collection. + A that indicates if tail call optimization will be applied when compiling the created expression. + An that has the property equal to and the and properties set to the specified values. + + + + Creates a LambdaExpression by first constructing a delegate type. + + An to set the property equal to. + An array that contains objects to use to populate the collection. + A that has the property equal to Lambda and the and properties set to the specified values. + + + + Creates a LambdaExpression by first constructing a delegate type. + + An to set the property equal to. + A that indicates if tail call optimization will be applied when compiling the created expression. + An array that contains objects to use to populate the collection. + A that has the property equal to Lambda and the and properties set to the specified values. + + + + Creates a LambdaExpression by first constructing a delegate type. + + An to set the property equal to. + An that contains objects to use to populate the collection. + A that has the property equal to Lambda and the and properties set to the specified values. + + + + Creates a LambdaExpression by first constructing a delegate type. + + An to set the property equal to. + A that indicates if tail call optimization will be applied when compiling the created expression. + An that contains objects to use to populate the collection. + A that has the property equal to Lambda and the and properties set to the specified values. + + + + Creates a LambdaExpression by first constructing a delegate type. + + An to set the property equal to. + An array that contains objects to use to populate the collection. + A representing the delegate signature for the lambda. + A that has the property equal to Lambda and the and properties set to the specified values. + + + + Creates a LambdaExpression by first constructing a delegate type. + + An to set the property equal to. + A that indicates if tail call optimization will be applied when compiling the created expression. + An array that contains objects to use to populate the collection. + A representing the delegate signature for the lambda. + A that has the property equal to Lambda and the and properties set to the specified values. + + + + Creates a LambdaExpression by first constructing a delegate type. + + An to set the property equal to. + An that contains objects to use to populate the collection. + A representing the delegate signature for the lambda. + A that has the property equal to Lambda and the and properties set to the specified values. + + + + Creates a LambdaExpression by first constructing a delegate type. + + An to set the property equal to. + A that indicates if tail call optimization will be applied when compiling the created expression. + An that contains objects to use to populate the collection. + A representing the delegate signature for the lambda. + A that has the property equal to Lambda and the and properties set to the specified values. + + + + Creates a LambdaExpression by first constructing a delegate type. + + An to set the property equal to. + An that contains objects to use to populate the collection. + The name for the lambda. Used for emitting debug information. + A that has the property equal to Lambda and the and properties set to the specified values. + + + + Creates a LambdaExpression by first constructing a delegate type. + + An to set the property equal to. + The name for the lambda. Used for emitting debug information. + A that indicates if tail call optimization will be applied when compiling the created expression. + An that contains objects to use to populate the collection. + A that has the property equal to Lambda and the and properties set to the specified values. + + + + Creates a LambdaExpression by first constructing a delegate type. + + An to set the property equal to. + An that contains objects to use to populate the collection. + The name for the lambda. Used for emitting debug information. + A representing the delegate signature for the lambda. + A that has the property equal to Lambda and the and properties set to the specified values. + + + + Creates a LambdaExpression by first constructing a delegate type. + + A representing the delegate signature for the lambda. + An to set the property equal to. + The name for the lambda. Used for emitting debug information. + A that indicates if tail call optimization will be applied when compiling the created expression. + An that contains objects to use to populate the collection. + A that has the property equal to Lambda and the and properties set to the specified values. + + + + Creates a object that represents a generic System.Func delegate type that has specific type arguments. + The last type argument specifies the return type of the created delegate. + + An array of Type objects that specify the type arguments for the System.Func delegate type. + The type of a System.Func delegate that has the specified type arguments. + + + + Creates a object that represents a generic System.Func delegate type that has specific type arguments. + The last type argument specifies the return type of the created delegate. + + An array of Type objects that specify the type arguments for the System.Func delegate type. + When this method returns, contains the generic System.Func delegate type that has specific type arguments. Contains null if there is no generic System.Func delegate that matches the .This parameter is passed uninitialized. + true if generic System.Func delegate type was created for specific ; false otherwise. + + + + Creates a object that represents a generic System.Action delegate type that has specific type arguments. + + An array of Type objects that specify the type arguments for the System.Action delegate type. + The type of a System.Action delegate that has the specified type arguments. + + + + Creates a object that represents a generic System.Action delegate type that has specific type arguments. + + An array of Type objects that specify the type arguments for the System.Action delegate type. + When this method returns, contains the generic System.Action delegate type that has specific type arguments. Contains null if there is no generic System.Action delegate that matches the .This parameter is passed uninitialized. + true if generic System.Action delegate type was created for specific ; false otherwise. + + + + Gets a object that represents a generic System.Func or System.Action delegate type that has specific type arguments. + The last type argument determines the return type of the delegate. If no Func or Action is large enough, it will generate a custom + delegate type. + + The type arguments of the delegate. + The delegate type. + + As with Func, the last argument is the return type. It can be set + to System.Void to produce an Action. + + + + Creates a that uses a method named "Add" to add elements to a collection. + + A to set the property equal to. + An array of objects to use to populate the collection. + A that has the property equal to ListInit and the property set to the specified value. + + + + Creates a that uses a method named "Add" to add elements to a collection. + + A to set the property equal to. + An that contains objects to use to populate the collection. + A that has the property equal to ListInit and the property set to the specified value. + + + + Creates a that uses a specified method to add elements to a collection. + + A to set the property equal to. + A that represents an instance method named "Add" (case insensitive), that adds an element to a collection. + An array of objects to use to populate the collection. + A that has the property equal to ListInit and the property set to the specified value. + + + + Creates a that uses a specified method to add elements to a collection. + + A to set the property equal to. + A that represents an instance method named "Add" (case insensitive), that adds an element to a collection. + An that contains objects to use to populate the Initializers collection. + A that has the property equal to ListInit and the property set to the specified value. + + + + Creates a that uses specified objects to initialize a collection. + + A to set the property equal to. + An array that contains objects to use to populate the collection. + + A that has the property equal to ListInit + and the and properties set to the specified values. + + + The property of must represent a type that implements . + The property of the resulting is equal to newExpression.Type. + + + + + Creates a that uses specified objects to initialize a collection. + + A to set the property equal to. + An that contains objects to use to populate the collection. + An that contains objects to use to populate the collection. + + The property of must represent a type that implements . + The property of the resulting is equal to newExpression.Type. + + + + + Creates an instance of . + + An array of objects to use to populate the collection. + An instance of that has the property equal to and the property set to the specified value. + + + + Creates an instance of . + + A collection of objects to use to populate the collection. + An instance of that has the property equal to and the property set to the specified value. + + + + Creates a with the given body. + + The body of the loop. + The created . + + + + Creates a with the given body and break target. + + The body of the loop. + The break target used by the loop body. + The created . + + + + Creates a with the given body. + + The body of the loop. + The break target used by the loop body. + The continue target used by the loop body. + The created . + + + + Creates a binding the specified value to the given member. + + The for the member which is being assigned to. + The value to be assigned to . + The created . + + + + Creates a binding the specified value to the given property. + + The for the property which is being assigned to. + The value to be assigned to . + The created . + + + + Creates a accessing a field. + + The containing object of the field. This can be null for static fields. + The field to be accessed. + The created . + + + + Creates a accessing a field. + + The containing object of the field. This can be null for static fields. + The field to be accessed. + The created . + + + + Creates a accessing a field. + + The containing object of the field. This can be null for static fields. + The containing the field. + The field to be accessed. + The created . + + + + Creates a accessing a property. + + The containing object of the property. This can be null for static properties. + The property to be accessed. + The created . + + + + Creates a accessing a property. + + The containing object of the property. This can be null for static properties. + The containing the property. + The property to be accessed. + The created . + + + + Creates a accessing a property. + + The containing object of the property. This can be null for static properties. + The property to be accessed. + The created . + + + + Creates a accessing a property. + + The containing object of the property. This can be null for static properties. + An accessor method of the property to be accessed. + The created . + + + + Creates a accessing a property or field. + + The containing object of the member. This can be null for static members. + The member to be accessed. + The created . + + + + Creates a accessing a property or field. + + The containing object of the member. This can be null for static members. + The member to be accessed. + The created . + + + Creates a . + A that has the property equal to and the and properties set to the specified values. + A to set the property equal to. + An array of objects to use to populate the collection. + + or is null. + The property of an element of does not represent a member of the type that .Type represents. + + + Creates a . + A that has the property equal to and the and properties set to the specified values. + A to set the property equal to. + An that contains objects to use to populate the collection. + + or is null. + The property of an element of does not represent a member of the type that .Type represents. + + + Creates a where the member is a field or property. + A that has the property equal to and the and properties set to the specified values. + A that represents a field or property to set the property equal to. + An array of objects to use to populate the collection. + + is null. -or-One or more elements of is null. + + does not represent a field or property.-or-The or of the field or property that represents does not implement . + + + Creates a where the member is a field or property. + A that has the property equal to and the and properties set to the specified values. + A that represents a field or property to set the property equal to. + An that contains objects to use to populate the collection. + + is null. -or-One or more elements of is null. + + does not represent a field or property.-or-The or of the field or property that represents does not implement . + + + Creates a object based on a specified property accessor method. + A that has the property equal to , the property set to the that represents the property accessed in , and populated with the elements of . + A that represents a property accessor method. + An array of objects to use to populate the collection. + + is null. -or-One or more elements of is null. + + does not represent a property accessor method.-or-The of the property that the method represented by accesses does not implement . + + + Creates a based on a specified property accessor method. + A that has the property equal to , the property set to the that represents the property accessed in , and populated with the elements of . + A that represents a property accessor method. + An that contains objects to use to populate the collection. + + is null. -or-One or more elements of are null. + + does not represent a property accessor method.-or-The of the property that the method represented by accesses does not implement . + + + + Creates a that represents the recursive initialization of members of a field or property. + + The to set the property equal to. + An array of objects to use to populate the collection. + A that has the property equal to and the and properties set to the specified values. + + + + Creates a that represents the recursive initialization of members of a field or property. + + The to set the property equal to. + An that contains objects to use to populate the collection. + A that has the property equal to and the and properties set to the specified values. + + + + Creates a that represents the recursive initialization of members of a member that is accessed by using a property accessor method. + + The that represents a property accessor method. + An that contains objects to use to populate the collection. + + A that has the property equal to , + the Member property set to the that represents the property accessed in , + and properties set to the specified values. + + + + + Creates a that represents the recursive initialization of members of a member that is accessed by using a property accessor method. + + The that represents a property accessor method. + An that contains objects to use to populate the collection. + + A that has the property equal to , + the Member property set to the that represents the property accessed in , + and properties set to the specified values. + + + + Creates a that represents a call to a static method that takes one argument. + A that has the property equal to and the and properties set to the specified values. + A to set the property equal to. + The that represents the first argument. + + is null. + + + Creates a that represents a call to a static method that takes two arguments. + A that has the property equal to and the and properties set to the specified values. + A to set the property equal to. + The that represents the first argument. + The that represents the second argument. + + is null. + + + Creates a that represents a call to a static method that takes three arguments. + A that has the property equal to and the and properties set to the specified values. + A to set the property equal to. + The that represents the first argument. + The that represents the second argument. + The that represents the third argument. + + is null. + + + Creates a that represents a call to a static method that takes four arguments. + A that has the property equal to and the and properties set to the specified values. + A to set the property equal to. + The that represents the first argument. + The that represents the second argument. + The that represents the third argument. + The that represents the fourth argument. + + is null. + + + Creates a that represents a call to a static method that takes five arguments. + A that has the property equal to and the and properties set to the specified values. + A to set the property equal to. + The that represents the first argument. + The that represents the second argument. + The that represents the third argument. + The that represents the fourth argument. + The that represents the fifth argument. + + is null. + A that has the property equal to and the and properties set to the specified values. + + + + Creates a that represents a call to a static (Shared in Visual Basic) method. + + The that represents the target method. + The array of one or more of that represents the call arguments. + A that has the property equal to and the and properties set to the specified values. + + + + Creates a that represents a call to a static (Shared in Visual Basic) method. + + The that represents the target method. + A collection of that represents the call arguments. + A that has the property equal to and the and properties set to the specified values. + + + + Creates a that represents a call to a method that takes no arguments. + + An that specifies the instance for an instance call. (pass null for a static (Shared in Visual Basic) method). + The that represents the target method. + A that has the property equal to and the and properties set to the specified values. + + + + Creates a that represents a method call. + + An that specifies the instance for an instance call. (pass null for a static (Shared in Visual Basic) method). + The that represents the target method. + An array of one or more of that represents the call arguments. + A that has the property equal to and the and properties set to the specified values. + + + + Creates a that represents a call to a method that takes two arguments. + + An that specifies the instance for an instance call. (pass null for a static (Shared in Visual Basic) method). + The that represents the target method. + The that represents the first argument. + The that represents the second argument. + A that has the property equal to and the and properties set to the specified values. + + + + Creates a that represents a call to a method that takes three arguments. + + An that specifies the instance for an instance call. (pass null for a static (Shared in Visual Basic) method). + The that represents the target method. + The that represents the first argument. + The that represents the second argument. + The that represents the third argument. + A that has the property equal to and the and properties set to the specified values. + + + Creates a that represents a call to an instance method by calling the appropriate factory method. + A that has the property equal to , the property equal to , set to the that represents the specified instance method, and set to the specified arguments. + An whose property value will be searched for a specific method. + The name of the method. + + An array of objects that specify the type parameters of the generic method. + This argument should be null when specifies a non-generic method. + + An array of objects that represents the arguments to the method. + + or is null. + No method whose name is , whose type parameters match , and whose parameter types match is found in .Type or its base types.-or-More than one method whose name is , whose type parameters match , and whose parameter types match is found in .Type or its base types. + + + Creates a that represents a call to a static (Shared in Visual Basic) method by calling the appropriate factory method. + A that has the property equal to , the property set to the that represents the specified static (Shared in Visual Basic) method, and the property set to the specified arguments. + The that specifies the type that contains the specified static (Shared in Visual Basic) method. + The name of the method. + + An array of objects that specify the type parameters of the generic method. + This argument should be null when specifies a non-generic method. + + An array of objects that represent the arguments to the method. + + or is null. + No method whose name is , whose type parameters match , and whose parameter types match is found in or its base types.-or-More than one method whose name is , whose type parameters match , and whose parameter types match is found in or its base types. + + + Creates a that represents a method call. + A that has the property equal to and the , , and properties set to the specified values. + An to set the property equal to (pass null for a static (Shared in Visual Basic) method). + A to set the property equal to. + An that contains objects to use to populate the collection. + + is null.-or- is null and represents an instance method. + + .Type is not assignable to the declaring type of the method represented by .-or-The number of elements in does not equal the number of parameters for the method represented by .-or-One or more of the elements of is not assignable to the corresponding parameter for the method represented by . + + + Creates a that represents applying an array index operator to a multi-dimensional array. + A that has the property equal to and the and properties set to the specified values. + An array of instances - indexes for the array index operation. + An array that contains objects to use to populate the collection. + + + Creates a that represents applying an array index operator to an array of rank more than one. + A that has the property equal to and the and properties set to the specified values. + An to set the property equal to. + An that contains objects to use to populate the collection. + + or is null. + + .Type does not represent an array type.-or-The rank of .Type does not match the number of elements in .-or-The property of one or more elements of does not represent the type. + + + + Creates a new array expression of the specified type from the provided initializers. + + A Type that represents the element type of the array. + The expressions used to create the array elements. + An instance of the . + + + + Creates a new array expression of the specified type from the provided initializers. + + A Type that represents the element type of the array. + The expressions used to create the array elements. + An instance of the . + + + + Creates a that represents creating an array that has a specified rank. + + A that represents the element type of the array. + An array that contains Expression objects to use to populate the Expressions collection. + A that has the property equal to type and the property set to the specified value. + + + + Creates a that represents creating an array that has a specified rank. + + A that represents the element type of the array. + An IEnumerable{T} that contains Expression objects to use to populate the Expressions collection. + A that has the property equal to type and the property set to the specified value. + + + + Creates a new that represents calling the specified constructor that takes no arguments. + + The to set the property equal to. + A that has the property equal to and the property set to the specified value. + + + + Creates a new that represents calling the specified constructor that takes no arguments. + + The to set the property equal to. + An array of objects to use to populate the Arguments collection. + A that has the property equal to and the and properties set to the specified value. + + + + Creates a new that represents calling the specified constructor that takes no arguments. + + The to set the property equal to. + An of objects to use to populate the Arguments collection. + A that has the property equal to and the and properties set to the specified value. + + + + Creates a new that represents calling the specified constructor with the specified arguments. The members that access the constructor initialized fields are specified. + + The to set the property equal to. + An of objects to use to populate the Arguments collection. + An of objects to use to populate the Members collection. + A that has the property equal to and the , and properties set to the specified value. + + + + Creates a new that represents calling the specified constructor with the specified arguments. The members that access the constructor initialized fields are specified. + + The to set the property equal to. + An of objects to use to populate the Arguments collection. + An Array of objects to use to populate the Members collection. + A that has the property equal to and the , and properties set to the specified value. + + + + Creates a that represents calling the parameterless constructor of the specified type. + + A that has a constructor that takes no arguments. + A that has the property equal to New and the Constructor property set to the ConstructorInfo that represents the parameterless constructor of the specified type. + + + + Creates a node that can be used to identify a parameter or a variable in an expression tree. + + The type of the parameter or variable. + A node with the specified name and type. + + + + Creates a node that can be used to identify a parameter or a variable in an expression tree. + + The type of the parameter or variable. + A node with the specified name and type. + + + + Creates a node that can be used to identify a parameter or a variable in an expression tree. + + The type of the parameter or variable. + The name of the parameter or variable, used for debugging or pretty printing purpose only. + A node with the specified name and type. + + + + Creates a node that can be used to identify a parameter or a variable in an expression tree. + + The type of the parameter or variable. + The name of the parameter or variable, used for debugging or pretty printing purpose only. + A node with the specified name and type. + + + + Creates a SwitchCase for use in a . + + The body of the case. + The test values of the case. + The created SwitchCase. + + + + Creates a SwitchCase for use in a . + + The body of the case. + The test values of the case. + The created SwitchCase. + + + + Creates a . + + The value to be tested against each case. + The valid cases for this switch. + The created . + + + + Creates a . + + The value to be tested against each case. + The result of the switch if no cases are matched. + The valid cases for this switch. + The created . + + + + Creates a . + + The value to be tested against each case. + The result of the switch if no cases are matched. + The equality comparison method to use. + The valid cases for this switch. + The created . + + + + Creates a . + + The result type of the switch. + The value to be tested against each case. + The result of the switch if no cases are matched. + The equality comparison method to use. + The valid cases for this switch. + The created . + + + + Creates a . + + The value to be tested against each case. + The result of the switch if no cases are matched. + The equality comparison method to use. + The valid cases for this switch. + The created . + + + + Creates a . + + The result type of the switch. + The value to be tested against each case. + The result of the switch if no cases are matched. + The equality comparison method to use. + The valid cases for this switch. + The created . + + + + If custom type is provided, all branches must be reference assignable to the result type. + If no custom type is provided, all branches must have the same type - resultType. + + + + + Creates a representing a try block with a fault block and no catch statements. + + The body of the try block. + The body of the fault block. + The created . + + + + Creates a representing a try block with a finally block and no catch statements. + + The body of the try block. + The body of the finally block. + The created . + + + + Creates a representing a try block with any number of catch statements and neither a fault nor finally block. + + The body of the try block. + The array of zero or more s representing the catch statements to be associated with the try block. + The created . + + + + Creates a representing a try block with any number of catch statements and a finally block. + + The body of the try block. + The body of the finally block. + The array of zero or more s representing the catch statements to be associated with the try block. + The created . + + + + Creates a representing a try block with the specified elements. + + The result type of the try expression. If null, bodh and all handlers must have identical type. + The body of the try block. + The body of the finally block. Pass null if the try block has no finally block associated with it. + The body of the t block. Pass null if the try block has no fault block associated with it. + A collection of s representing the catch statements to be associated with the try block. + The created . + + + + Creates a . + + An to set the property equal to. + A to set the property equal to. + A for which the property is equal to and for which the and properties are set to the specified values. + + + + Creates a that compares run-time type identity. + + An to set the property equal to. + A to set the property equal to. + A for which the property is equal to and for which the and properties are set to the specified values. + + + + Creates a , given an operand, by calling the appropriate factory method. + + The that specifies the type of unary operation. + An that represents the operand. + The that specifies the type to be converted to (pass null if not applicable). + The that results from calling the appropriate factory method. + Thrown when does not correspond to a unary expression. + Thrown when is null. + + + + Creates a , given an operand and implementing method, by calling the appropriate factory method. + + The that specifies the type of unary operation. + An that represents the operand. + The that specifies the type to be converted to (pass null if not applicable). + The that represents the implementing method. + The that results from calling the appropriate factory method. + Thrown when does not correspond to a unary expression. + Thrown when is null. + + + + Creates a that represents an arithmetic negation operation. + + An to set the property equal to. + A that has the property equal to and the properties set to the specified value. + Thrown when is null. + Thrown when the unary minus operator is not defined for + + + + Creates a that represents an arithmetic negation operation. + + An to set the property equal to. + A to set the property equal to. + A that has the property equal to and the and properties set to the specified value. + Thrown when is null. + Thrown when is not null and the method it represents returns void, is not static (Shared in Visual Basic), or does not take exactly one argument. + Thown when is null and the unary minus operator is not defined for expression.Type or expression.Type (or its corresponding non-nullable type if it is a nullable value type) is not assignable to the argument type of the method represented by method. + + + + Creates a that represents a unary plus operation. + + An to set the property equal to. + A that has the property equal to and the property set to the specified value. + Thrown when is null. + Thown when the unary minus operator is not defined for expression.Type. + + + + Creates a that represents a unary plus operation. + + An to set the property equal to. + A to set the property equal to. + A that has the property equal to and the and property set to the specified value. + Thrown when is null. + Thrown when is not null and the method it represents returns void, is not static (Shared in Visual Basic), or does not take exactly one argument. + Thown when is null and the unary minus operator is not defined for expression.Type or expression.Type (or its corresponding non-nullable type if it is a nullable value type) is not assignable to the argument type of the method represented by method. + + + Creates a that represents an arithmetic negation operation that has overflow checking. + A that has the property equal to and the property set to the specified value. + An to set the property equal to. + + Thrown when is null. + Thrown when the unary minus operator is not defined for .Type. + + + Creates a that represents an arithmetic negation operation that has overflow checking. The implementing method can be specified. + A that has the property equal to and the and properties set to the specified values. + An to set the property equal to. + A to set the property equal to. + + is null. + + is not null and the method it represents returns void, is not static (Shared in Visual Basic), or does not take exactly one argument. + + is null and the unary minus operator is not defined for .Type.-or-.Type (or its corresponding non-nullable type if it is a nullable value type) is not assignable to the argument type of the method represented by . + + + Creates a that represents a bitwise complement operation. + A that has the property equal to and the property set to the specified value. + An to set the property equal to. + + is null. + The unary not operator is not defined for .Type. + + + Creates a that represents a bitwise complement operation. The implementing method can be specified. + A that has the property equal to and the and properties set to the specified values. + An to set the property equal to. + A to set the property equal to. + + is null. + + is not null and the method it represents returns void, is not static (Shared in Visual Basic), or does not take exactly one argument. + + is null and the unary not operator is not defined for .Type.-or-.Type (or its corresponding non-nullable type if it is a nullable value type) is not assignable to the argument type of the method represented by . + + + + Returns whether the expression evaluates to false. + + An to evaluate. + An instance of . + + + + Returns whether the expression evaluates to false. + + An to evaluate. + A that represents the implementing method. + An instance of . + + + + Returns whether the expression evaluates to true. + + An to evaluate. + An instance of . + + + + Returns whether the expression evaluates to true. + + An to evaluate. + A that represents the implementing method. + An instance of . + + + + Returns the expression representing the ones complement. + + An . + An instance of . + + + + Returns the expression representing the ones complement. + + An . + A that represents the implementing method. + An instance of . + + + Creates a that represents an explicit reference or boxing conversion where null is supplied if the conversion fails. + A that has the property equal to and the and properties set to the specified values. + An to set the property equal to. + A to set the property equal to. + + or is null. + + + + Creates a that represents an explicit unboxing. + + An to unbox. + The new of the expression. + An instance of . + + + Creates a that represents a conversion operation. + A that has the property equal to and the and properties set to the specified values. + An to set the property equal to. + A to set the property equal to. + + or is null. + No conversion operator is defined between .Type and . + + + Creates a that represents a conversion operation for which the implementing method is specified. + A that has the property equal to and the , , and properties set to the specified values. + An to set the property equal to. + A to set the property equal to. + A to set the property equal to. + + or is null. + + is not null and the method it represents returns void, is not static (Shared in Visual Basic), or does not take exactly one argument. + More than one method that matches the description was found. + No conversion operator is defined between .Type and .-or-.Type is not assignable to the argument type of the method represented by .-or-The return type of the method represented by is not assignable to .-or-.Type or is a nullable value type and the corresponding non-nullable value type does not equal the argument type or the return type, respectively, of the method represented by . + + + Creates a that represents a conversion operation that throws an exception if the target type is overflowed. + A that has the property equal to and the and properties set to the specified values. + An to set the property equal to. + A to set the property equal to. + + or is null. + No conversion operator is defined between .Type and . + + + Creates a that represents a conversion operation that throws an exception if the target type is overflowed and for which the implementing method is specified. + A that has the property equal to and the , , and properties set to the specified values. + An to set the property equal to. + A to set the property equal to. + A to set the property equal to. + + or is null. + + is not null and the method it represents returns void, is not static (Shared in Visual Basic), or does not take exactly one argument. + More than one method that matches the description was found. + No conversion operator is defined between .Type and .-or-.Type is not assignable to the argument type of the method represented by .-or-The return type of the method represented by is not assignable to .-or-.Type or is a nullable value type and the corresponding non-nullable value type does not equal the argument type or the return type, respectively, of the method represented by . + + + Creates a that represents getting the length of a one-dimensional array. + A that has the property equal to and the property equal to . + An to set the property equal to. + + is null. + + .Type does not represent an array type. + + + Creates a that represents an expression that has a constant value of type . + A that has the property equal to and the property set to the specified value. + An to set the property equal to. + + is null. + + + + Creates a that represents a rethrowing of an exception. + + A that represents a rethrowing of an exception. + + + + Creates a that represents a rethrowing of an exception with a given type. + + The new of the expression. + A that represents a rethrowing of an exception. + + + + Creates a that represents a throwing of an exception. + + An . + A that represents the exception. + + + + Creates a that represents a throwing of a value with a given type. + + An . + The new of the expression. + A that represents the exception. + + + + Creates a that represents the incrementing of the expression by 1. + + An to increment. + A that represents the incremented expression. + + + + Creates a that represents the incrementing of the expression by 1. + + An to increment. + A that represents the implementing method. + A that represents the incremented expression. + + + + Creates a that represents the decrementing of the expression by 1. + + An to decrement. + A that represents the decremented expression. + + + + Creates a that represents the decrementing of the expression by 1. + + An to decrement. + A that represents the implementing method. + A that represents the decremented expression. + + + + Creates a that increments the expression by 1 + and assigns the result back to the expression. + + An to apply the operations on. + A that represents the resultant expression. + + + + Creates a that increments the expression by 1 + and assigns the result back to the expression. + + An to apply the operations on. + A that represents the implementing method. + A that represents the resultant expression. + + + + Creates a that decrements the expression by 1 + and assigns the result back to the expression. + + An to apply the operations on. + A that represents the resultant expression. + + + + Creates a that decrements the expression by 1 + and assigns the result back to the expression. + + An to apply the operations on. + A that represents the implementing method. + A that represents the resultant expression. + + + + Creates a that represents the assignment of the expression + followed by a subsequent increment by 1 of the original expression. + + An to apply the operations on. + A that represents the resultant expression. + + + + Creates a that represents the assignment of the expression + followed by a subsequent increment by 1 of the original expression. + + An to apply the operations on. + A that represents the implementing method. + A that represents the resultant expression. + + + + Creates a that represents the assignment of the expression + followed by a subsequent decrement by 1 of the original expression. + + An to apply the operations on. + A that represents the resultant expression. + + + + Creates a that represents the assignment of the expression + followed by a subsequent decrement by 1 of the original expression. + + An to apply the operations on. + A that represents the implementing method. + A that represents the resultant expression. + + + + The of the . + + + + + The of the value represented by this . + + + + + Indicates that the node can be reduced to a simpler node. If this + returns true, Reduce() can be called to produce the reduced form. + + + + + Creates a representation of the Expression. + + A representation of the Expression. + + + + Provides an internal interface for accessing the arguments that multiple tree + nodes (DynamicExpression, ElementInit, MethodCallExpression, InvocationExpression, NewExpression, + and InexExpression). + + This enables two optimizations which reduce the size of the trees. The first is it enables + the nodes to hold onto an IList of T instead of a ReadOnlyCollection. This saves the cost + of allocating the ReadOnlyCollection for each node. The second is that it enables specialized + subclasses to be created which hold onto a specific number of arguments. For example Block2, + Block3, Block4. These nodes can therefore avoid allocating both a ReadOnlyCollection and an + array for storing their elements saving 32 bytes per node. + + Meanwhile the nodes can continue to expose the original LINQ properties of ReadOnlyCollections. They + do this by re-using 1 field for storing both the array or an element that would normally be stored + in the array. + + For the array case the collection is typed to IList of T instead of ReadOnlyCollection of T. + When the node is initially constructed it is an array. When the compiler accesses the members it + uses this interface. If a user accesses the members the array is promoted to a ReadOnlyCollection. + + For the object case we store the 1st argument in a field typed to object and when the node is initially + constructed this holds directly onto the Expression. When the compiler accesses the members + it again uses this interface and the accessor for the 1st argument uses Expression.ReturnObject to + return the object which handles the Expression or ReadOnlyCollection case. When the user accesses + the ReadOnlyCollection then the object field is updated to hold directly onto the ReadOnlyCollection. + + It is important that the Expressions consistently return the same ReadOnlyCollection otherwise the + re-writer will be broken and it would be a breaking change from LINQ v1. The problem is that currently + users can rely on object identity to tell if the node has changed. Storing the readonly collection in + an overloaded field enables us to both reduce memory usage as well as maintain compatibility and an + easy to use external API. + + + + + Provides a wrapper around an IArgumentProvider which exposes the argument providers + members out as an IList of Expression. This is used to avoid allocating an array + which needs to be stored inside of a ReadOnlyCollection. Instead this type has + the same amount of overhead as an array without duplicating the storage of the + elements. This ensures that internally we can avoid creating and copying arrays + while users of the Expression trees also don't pay a size penalty for this internal + optimization. See IArgumentProvider for more general information on the Expression + tree optimizations being used here. + + + + + Represents the unary dynamic operation at the call site, providing the binding semantic and the details about the operation. + + + + + Initializes a new instance of the class. + + The unary operation kind. + + + + Performs the binding of the unary dynamic operation if the target dynamic object cannot bind. + + The target of the dynamic unary operation. + The representing the result of the binding. + + + + Performs the binding of the unary dynamic operation if the target dynamic object cannot bind. + + The target of the dynamic unary operation. + The binding result in case the binding fails, or null. + The representing the result of the binding. + + + + Performs the binding of the dynamic unary operation. + + The target of the dynamic operation. + An array of arguments of the dynamic operation. + The representing the result of the binding. + + + + The result type of the operation. + + + + + The unary operation kind. + + + + + Output a given expression tree to a string. + + + + + Output a given member binding to a string. + + + + + Output a given ElementInit to a string. + + + + + This type tracks "runtime" constants--live objects that appear in + ConstantExpression nodes and must be bound to the delegate. + + + + + The list of constants in the order they appear in the constant array + + + + + The index of each constant in the constant array + + + + + Each constant referenced within this lambda, and how often it was referenced + + + + + IL locals for storing frequently used constants + + + + + Called by VariableBinder. Adds the constant to the list (if needed) + and increases the reference count by one + + + + + Emits a live object as a constant + + + + + Emit code to cache frequently used constants into IL locals, + instead of pulling them out of the array each time + + + + + Constants can emit themselves as different types + For caching purposes, we need to treat each distinct Type as a + seperate thing to cache. (If we have to cast it on the way out, it + ends up using a JIT temp and defeats the purpose of caching the + value in a local) + + + + + Emits or clears a sequence point for debug information. + + This allows the debugger to highlight the correct source code when + debugging. + + + + + Dispatches to the specific visit method for this node type. + + + + + Gets the static type of the expression that this represents. (Inherited from .) + + The that represents the static type of the expression. + + + + Returns the node type of this . (Inherited from .) + + The that represents this expression. + + + + Gets the start line of this . + + + + + Gets the start column of this . + + + + + Gets the end line of this . + + + + + Gets the end column of this . + + + + + Gets the that represents the source file. + + + + + Gets the value to indicate if the is for clearing a sequence point. + + + + + Stores information needed to emit debugging symbol information for a + source file, in particular the file name and unique language identifier. + + + + + The source file name. + + + + + Returns the language's unique identifier, if any. + + + + + Returns the language vendor's unique identifier, if any. + + + + + Returns the document type's unique identifier, if any. + Defaults to the guid for a text file. + + + + + Finds a delegate type using the types in the array. + We use the cache to avoid copying the array, and to cache the + created delegate type + + + + + Finds a delegate type for a CallSite using the types in the ReadOnlyCollection of Expression. + + We take the readonly collection of Expression explicitly to avoid allocating memory (an array + of types) on lookup of delegate types. + + + + + Finds a delegate type for a CallSite using the MetaObject array. + + We take the array of MetaObject explicitly to avoid allocating memory (an array of types) on + lookup of delegate types. + + + + + Creates a new delegate, or uses a func/action + Note: this method does not cache + + + + + Specifies what kind of jump this represents. + + + + + A that represents a jump to some location. + + + + + A that represents a return statement. + + + + + A that represents a break statement. + + + + + A that represents a continue statement. + + + + + Represents an unconditional jump. This includes return statements, break and continue statements, and other jumps. + + + + + Dispatches to the specific visit method for this node type. + + + + + Creates a new expression that is like this one, but using the + supplied children. If all of the children are the same, it will + return this expression. + + The property of the result. + The property of the result. + This expression if no children changed, or an expression with the updated children. + + + + Gets the static type of the expression that this represents. (Inherited from .) + + The that represents the static type of the expression. + + + + Returns the node type of this . (Inherited from .) + + The that represents this expression. + + + + The value passed to the target, or null if the target is of type + System.Void. + + + + + The target label where this node jumps to. + + + + + The kind of the goto. For information purposes only. + + + + + Contains compiler state corresponding to a LabelTarget + See also LabelScopeInfo. + + + + + Indicates if it is legal to emit a "branch" instruction based on + currently available information. Call the Reference method before + using this property. + + + + + Returns true if we can jump into this node + + + + + Wraps ILGenerator with code that tracks the current IL offset as instructions are emitted into the IL stream. + + + + + Represents a dynamic operation. + + + + + Dispatches to the specific visit method for this node type. + + + + + Makes a copy of this node replacing the args with the provided values. The + number of the args needs to match the number of the current block. + + This helper is provided to allow re-writing of nodes to not depend on the specific optimized + subclass of DynamicExpression which is being used. + + + + + Creates a new expression that is like this one, but using the + supplied children. If all of the children are the same, it will + return this expression. + + The property of the result. + This expression if no children changed, or an expression with the updated children. + + + + Gets the static type of the expression that this represents. + + The that represents the static type of the expression. + + + + Returns the node type of this Expression. Extension nodes should return + ExpressionType.Extension when overriding this method. + + The of the expression. + + + + Gets the , which determines the runtime behavior of the + dynamic site. + + + + + Gets the type of the delegate used by the . + + + + + Gets the arguments to the dynamic operation. + + + + + Represents an expression that has a binary operator. + + + + + Creates a new expression that is like this one, but using the + supplied children. If all of the children are the same, it will + return this expression. + + The property of the result. + The property of the result. + The property of the result. + This expression if no children changed, or an expression with the updated children. + + + + Reduces the binary expression node to a simpler expression. + If CanReduce returns true, this should return a valid expression. + This method is allowed to return another node which itself + must be reduced. + + The reduced expression. + + + + Dispatches to the specific visit method for this node type. + + + + + Gets a value that indicates whether the expression tree node can be reduced. + + + + + Gets the right operand of the binary operation. + + + + + Gets the left operand of the binary operation. + + + + + Gets the implementing method for the binary operation. + + + + + Gets the type conversion function that is used by a coalescing or compound assignment operation. + + + + + Gets a value that indicates whether the expression tree node represents a lifted call to an operator. + + + + + Gets a value that indicates whether the expression tree node represents a lifted call to an operator whose return type is lifted to a nullable type. + + + + + Represents a block that contains a sequence of expressions where variables can be defined. + + + + + Dispatches to the specific visit method for this node type. + + + + + Creates a new expression that is like this one, but using the + supplied children. If all of the children are the same, it will + return this expression. + + The property of the result. + The property of the result. + This expression if no children changed, or an expression with the updated children. + + + + Makes a copy of this node replacing the parameters/args with the provided values. The + shape of the parameters/args needs to match the shape of the current block - in other + words there should be the same # of parameters and args. + + parameters can be null in which case the existing parameters are used. + + This helper is provided to allow re-writing of nodes to not depend on the specific optimized + subclass of BlockExpression which is being used. + + + + + Helper used for ensuring we only return 1 instance of a ReadOnlyCollection of T. + + This is similar to the ReturnReadOnly which only takes a single argument. This version + supports nodes which hold onto 5 Expressions and puts all of the arguments into the + ReadOnlyCollection. + + Ultimately this means if we create the readonly collection we will be slightly more wasteful as we'll + have a readonly collection + some fields in the type. The DLR internally avoids accessing anything + which would force the readonly collection to be created. + + This is used by BlockExpression5 and MethodCallExpression5. + + + + + Gets the expressions in this block. + + + + + Gets the variables defined in this block. + + + + + Gets the last expression in this block. + + + + + Returns the node type of this Expression. Extension nodes should return + ExpressionType.Extension when overriding this method. + + The of the expression. + + + + Gets the static type of the expression that this represents. + + The that represents the static type of the expression. + + + + Provides a wrapper around an IArgumentProvider which exposes the argument providers + members out as an IList of Expression. This is used to avoid allocating an array + which needs to be stored inside of a ReadOnlyCollection. Instead this type has + the same amount of overhead as an array without duplicating the storage of the + elements. This ensures that internally we can avoid creating and copying arrays + while users of the Expression trees also don't pay a size penalty for this internal + optimization. See IArgumentProvider for more general information on the Expression + tree optimizations being used here. + + + + + Represents a catch statement in a try block. + This must have the same return type (i.e., the type of ) as the try block it is associated with. + + + + + Returns a that represents the current . + + A that represents the current . + + + + Creates a new expression that is like this one, but using the + supplied children. If all of the children are the same, it will + return this expression. + + The property of the result. + The property of the result. + The property of the result. + This expression if no children changed, or an expression with the updated children. + + + + Gets a reference to the object caught by this handler. + + + + + Gets the type of this handler catches. + + + + + Gets the body of the catch block. + + + + + Gets the body of the 's filter. + + + + + Represents an expression that has a conditional operator. + + + + + Dispatches to the specific visit method for this node type. + + + + + Creates a new expression that is like this one, but using the + supplied children. If all of the children are the same, it will + return this expression. + + The property of the result. + The property of the result. + The property of the result. + This expression if no children changed, or an expression with the updated children. + + + + Returns the node type of this Expression. Extension nodes should return + ExpressionType.Extension when overriding this method. + + The of the expression. + + + + Gets the static type of the expression that this represents. + + The that represents the static type of the expression. + + + + Gets the test of the conditional operation. + + + + + Gets the expression to execute if the test evaluates to true. + + + + + Gets the expression to execute if the test evaluates to false. + + + + + Represents an expression that has a constant value. + + + + + Dispatches to the specific visit method for this node type. + + + + + Gets the static type of the expression that this represents. + + The that represents the static type of the expression. + + + + Returns the node type of this Expression. Extension nodes should return + ExpressionType.Extension when overriding this method. + + The of the expression. + + + + Gets the value of the constant expression. + + + + + Represents the default value of a type or an empty expression. + + + + + Dispatches to the specific visit method for this node type. + + + + + Gets the static type of the expression that this represents. + + The that represents the static type of the expression. + + + + Returns the node type of this Expression. Extension nodes should return + ExpressionType.Extension when overriding this method. + + The of the expression. + + + + Represents the initialization of a list. + + + + + Creates a representation of the node. + + A representation of the node. + + + + Creates a new expression that is like this one, but using the + supplied children. If all of the children are the same, it will + return this expression. + + The property of the result. + This expression if no children changed, or an expression with the updated children. + + + + Gets the used to add elements to the object. + + + + + Gets the list of elements to be added to the object. + + + + + Describes the node types for the nodes of an expression tree. + + + + + A node that represents arithmetic addition without overflow checking. + + + + + A node that represents arithmetic addition with overflow checking. + + + + + A node that represents a bitwise AND operation. + + + + + A node that represents a short-circuiting conditional AND operation. + + + + + A node that represents getting the length of a one-dimensional array. + + + + + A node that represents indexing into a one-dimensional array. + + + + + A node that represents represents a method call. + + + + + A node that represents a null coalescing operation. + + + + + A node that represents a conditional operation. + + + + + A node that represents an expression that has a constant value. + + + + + A node that represents a cast or conversion operation. If the operation is a numeric conversion, it overflows silently if the converted value does not fit the target type. + + + + + A node that represents a cast or conversion operation. If the operation is a numeric conversion, an exception is thrown if the converted value does not fit the target type. + + + + + A node that represents arithmetic division. + + + + + A node that represents an equality comparison. + + + + + A node that represents a bitwise XOR operation. + + + + + A node that represents a "greater than" numeric comparison. + + + + + A node that represents a "greater than or equal" numeric comparison. + + + + + A node that represents applying a delegate or lambda expression to a list of argument expressions. + + + + + A node that represents a lambda expression. + + + + + A node that represents a bitwise left-shift operation. + + + + + A node that represents a "less than" numeric comparison. + + + + + A node that represents a "less than or equal" numeric comparison. + + + + + A node that represents creating a new IEnumerable object and initializing it from a list of elements. + + + + + A node that represents reading from a field or property. + + + + + A node that represents creating a new object and initializing one or more of its members. + + + + + A node that represents an arithmetic remainder operation. + + + + + A node that represents arithmetic multiplication without overflow checking. + + + + + A node that represents arithmetic multiplication with overflow checking. + + + + + A node that represents an arithmetic negation operation. + + + + + A node that represents a unary plus operation. The result of a predefined unary plus operation is simply the value of the operand, but user-defined implementations may have non-trivial results. + + + + + A node that represents an arithmetic negation operation that has overflow checking. + + + + + A node that represents calling a constructor to create a new object. + + + + + A node that represents creating a new one-dimensional array and initializing it from a list of elements. + + + + + A node that represents creating a new array where the bounds for each dimension are specified. + + + + + A node that represents a bitwise complement operation. + + + + + A node that represents an inequality comparison. + + + + + A node that represents a bitwise OR operation. + + + + + A node that represents a short-circuiting conditional OR operation. + + + + + A node that represents a reference to a parameter or variable defined in the context of the expression. + + + + + A node that represents raising a number to a power. + + + + + A node that represents an expression that has a constant value of type Expression. A Quote node can contain references to parameters defined in the context of the expression it represents. + + + + + A node that represents a bitwise right-shift operation. + + + + + A node that represents arithmetic subtraction without overflow checking. + + + + + A node that represents arithmetic subtraction with overflow checking. + + + + + A node that represents an explicit reference or boxing conversion where null reference (Nothing in Visual Basic) is supplied if the conversion fails. + + + + + A node that represents a type test. + + + + + A node that represents an assignment. + + + + + A node that represents a block of expressions. + + + + + A node that represents a debugging information. + + + + + A node that represents a unary decrement. + + + + + A node that represents a dynamic operation. + + + + + A node that represents a default value. + + + + + A node that represents an extension expression. + + + + + A node that represents a goto. + + + + + A node that represents a unary increment. + + + + + A node that represents an index operation. + + + + + A node that represents a label. + + + + + A node that represents a list of runtime variables. + + + + + A node that represents a loop. + + + + + A node that represents a switch operation. + + + + + A node that represents a throwing of an exception. + + + + + A node that represents a try-catch expression. + + + + + A node that represents an unbox value type operation. + + + + + A node that represents an arithmetic addition compound assignment without overflow checking. + + + + + A node that represents a bitwise AND compound assignment. + + + + + A node that represents an arithmetic division compound assignment . + + + + + A node that represents a bitwise XOR compound assignment. + + + + + A node that represents a bitwise left-shift compound assignment. + + + + + A node that represents an arithmetic remainder compound assignment. + + + + + A node that represents arithmetic multiplication compound assignment without overflow checking. + + + + + A node that represents a bitwise OR compound assignment. + + + + + A node that represents raising a number to a power compound assignment. + + + + + A node that represents a bitwise right-shift compound assignment. + + + + + A node that represents arithmetic subtraction compound assignment without overflow checking. + + + + + A node that represents an arithmetic addition compound assignment with overflow checking. + + + + + A node that represents arithmetic multiplication compound assignment with overflow checking. + + + + + A node that represents arithmetic subtraction compound assignment with overflow checking. + + + + + A node that represents an unary prefix increment. + + + + + A node that represents an unary prefix decrement. + + + + + A node that represents an unary postfix increment. + + + + + A node that represents an unary postfix decrement. + + + + + A node that represents a exact type test. + + + + + A node that represents a ones complement. + + + + + A node that represents a true condition value. + + + + + A node that represents a false condition value. + + + + + Represents indexing a property or array. + + + + + Creates a new expression that is like this one, but using the + supplied children. If all of the children are the same, it will + return this expression. + + The property of the result. + The property of the result. + This expression if no children changed, or an expression with the updated children. + + + + Dispatches to the specific visit method for this node type. + + + + + Returns the node type of this . (Inherited from .) + + The that represents this expression. + + + + Gets the static type of the expression that this represents. (Inherited from .) + + The that represents the static type of the expression. + + + + An object to index. + + + + + Gets the for the property if the expression represents an indexed property, returns null otherwise. + + + + + Gets the arguments to be used to index the property or array. + + + + + Represents an expression that applies a delegate or lambda expression to a list of argument expressions. + + + + + Creates a new expression that is like this one, but using the + supplied children. If all of the children are the same, it will + return this expression. + + The property of the result. + The property of the result. + This expression if no children changed, or an expression with the updated children. + + + + Dispatches to the specific visit method for this node type. + + + + + Gets the static type of the expression that this represents. + + The that represents the static type of the expression. + + + + Returns the node type of this Expression. Extension nodes should return + ExpressionType.Extension when overriding this method. + + The of the expression. + + + + Gets the delegate or lambda expression to be applied. + + + + + Gets the arguments that the delegate or lambda expression is applied to. + + + + + Used to denote the target of a . + + + + + Returns a that represents the current . + + A that represents the current . + + + + Gets the name of the label. + + The label's name is provided for information purposes only. + + + + The type of value that is passed when jumping to the label + (or System.Void if no value should be passed). + + + + + Represents a label, which can be placed in any context. If + it is jumped to, it will get the value provided by the corresponding + . Otherwise, it gets the value in . If the + equals System.Void, no value should be provided. + + + + + Dispatches to the specific visit method for this node type. + + + + + Creates a new expression that is like this one, but using the + supplied children. If all of the children are the same, it will + return this expression. + + The property of the result. + The property of the result. + This expression if no children changed, or an expression with the updated children. + + + + Gets the static type of the expression that this represents. (Inherited from .) + + The that represents the static type of the expression. + + + + Returns the node type of this . (Inherited from .) + + The that represents this expression. + + + + The which this label is associated with. + + + + + The value of the when the label is reached through + normal control flow (e.g. is not jumped to). + + + + + Creates a node. + This captures a block of code that is similar to a .NET method body. + + + Lambda expressions take input through parameters and are expected to be fully bound. + + + + + Produces a delegate that represents the lambda expression. + + A delegate containing the compiled version of the lambda. + + + + Produces a delegate that represents the lambda expression. + + Debugging information generator used by the compiler to mark sequence points and annotate local variables. + A delegate containing the compiled version of the lambda. + + + + Compiles the lambda into a method definition. + + A which will be used to hold the lambda's IL. + + + + Compiles the lambda into a method definition and custom debug information. + + A which will be used to hold the lambda's IL. + Debugging information generator used by the compiler to mark sequence points and annotate local variables. + + + + Gets the static type of the expression that this represents. (Inherited from .) + + The that represents the static type of the expression. + + + + Returns the node type of this . (Inherited from .) + + The that represents this expression. + + + + Gets the parameters of the lambda expression. + + + + + Gets the name of the lambda expression. + + Used for debugging purposes. + + + + Gets the body of the lambda expression. + + + + + Gets the return type of the lambda expression. + + + + + Gets the value that indicates if the lambda expression will be compiled with + tail call optimization. + + + + + Defines a node. + This captures a block of code that is similar to a .NET method body. + + The type of the delegate. + + Lambda expressions take input through parameters and are expected to be fully bound. + + + + + Produces a delegate that represents the lambda expression. + + A delegate containing the compiled version of the lambda. + + + + Produces a delegate that represents the lambda expression. + + Debugging information generator used by the compiler to mark sequence points and annotate local variables. + A delegate containing the compiled version of the lambda. + + + + Creates a new expression that is like this one, but using the + supplied children. If all of the children are the same, it will + return this expression. + + The Body property of the result. + The Parameters property of the result. + This expression if no children changed, or an expression with the updated children. + + + + Dispatches to the specific visit method for this node type. + + + + + Represents a constructor call that has a collection initializer. + + + Use the factory methods to create a ListInitExpression. + The value of the NodeType property of a ListInitExpression is ListInit. + + + + + Dispatches to the specific visit method for this node type. + + + + + Reduces the binary expression node to a simpler expression. + If CanReduce returns true, this should return a valid expression. + This method is allowed to return another node which itself + must be reduced. + + The reduced expression. + + + + Creates a new expression that is like this one, but using the + supplied children. If all of the children are the same, it will + return this expression. + + The property of the result. + The property of the result. + This expression if no children changed, or an expression with the updated children. + + + + Returns the node type of this . (Inherited from .) + + The that represents this expression. + + + + Gets the static type of the expression that this represents. (Inherited from .) + + The that represents the static type of the expression. + + + + Gets a value that indicates whether the expression tree node can be reduced. + + + + + Gets the expression that contains a call to the constructor of a collection type. + + + + + Gets the element initializers that are used to initialize a collection. + + + + + An expression that provides runtime read/write access to variables. + Needed to implement "eval" in some dynamic languages. + Evaluates to an instance of when executed. + + + + + Dispatches to the specific visit method for this node type. + + + + + Creates a new expression that is like this one, but using the + supplied children. If all of the children are the same, it will + return this expression. + + The property of the result. + This expression if no children changed, or an expression with the updated children. + + + + Gets the static type of the expression that this represents. + + The that represents the static type of the expression. + + + + Returns the node type of this Expression. Extension nodes should return + ExpressionType.Extension when overriding this method. + + The of the expression. + + + + The variables or parameters to which to provide runtime access. + + + + + Represents an infinite loop. It can be exited with "break". + + + + + Dispatches to the specific visit method for this node type. + + + + + Creates a new expression that is like this one, but using the + supplied children. If all of the children are the same, it will + return this expression. + + The property of the result. + The property of the result. + The property of the result. + This expression if no children changed, or an expression with the updated children. + + + + Gets the static type of the expression that this represents. + + The that represents the static type of the expression. + + + + Returns the node type of this Expression. Extension nodes should return + ExpressionType.Extension when overriding this method. + + The of the expression. + + + + Gets the that is the body of the loop. + + + + + Gets the that is used by the loop body as a break statement target. + + + + + Gets the that is used by the loop body as a continue statement target. + + + + + Represents assignment to a member of an object. + + + + + Provides the base class from which the classes that represent bindings that are used to initialize members of a newly created object derive. + + + + + Initializes an instance of class. + + The type of member binding. + The field or property to be initialized. + + + + Returns a that represents the current . + + A that represents the current . + + + + Gets the type of binding that is represented. + + + + + Gets the field or property to be initialized. + + + + + Creates a new expression that is like this one, but using the + supplied children. If all of the children are the same, it will + return this expression. + + The property of the result. + This expression if no children changed, or an expression with the updated children. + + + + Gets the which represents the object whose member is being assigned to. + + + + + Describes the binding types that are used in MemberInitExpression objects. + + + + + A binding that represents initializing a member with the value of an expression. + + + + + A binding that represents recursively initializing members of a member. + + + + + A binding that represents initializing a member of type or from a list of elements. + + + + + Represents accessing a field or property. + + + + + Dispatches to the specific visit method for this node type. + + + + + Creates a new expression that is like this one, but using the + supplied children. If all of the children are the same, it will + return this expression. + + The property of the result. + This expression if no children changed, or an expression with the updated children. + + + + Gets the field or property to be accessed. + + + + + Gets the containing object of the field or property. + + + + + Returns the node type of this . (Inherited from .) + + The that represents this expression. + + + + Represents calling a constructor and initializing one or more members of the new object. + + + + + Dispatches to the specific visit method for this node type. + + + + + Reduces the to a simpler expression. + If CanReduce returns true, this should return a valid expression. + This method is allowed to return another node which itself + must be reduced. + + The reduced expression. + + + + Creates a new expression that is like this one, but using the + supplied children. If all of the children are the same, it will + return this expression. + + The property of the result. + The property of the result. + This expression if no children changed, or an expression with the updated children. + + + + Gets the static type of the expression that this represents. + + The that represents the static type of the expression. + + + + Gets a value that indicates whether the expression tree node can be reduced. + + + + + Returns the node type of this Expression. Extension nodes should return + ExpressionType.Extension when overriding this method. + + The of the expression. + + + Gets the expression that represents the constructor call. + A that represents the constructor call. + + + Gets the bindings that describe how to initialize the members of the newly created object. + A of objects which describe how to initialize the members. + + + + Represents initializing the elements of a collection member of a newly created object. + + + + + Creates a new expression that is like this one, but using the + supplied children. If all of the children are the same, it will + return this expression. + + The property of the result. + This expression if no children changed, or an expression with the updated children. + + + + Gets the element initializers for initializing a collection member of a newly created object. + + + + + Represents initializing members of a member of a newly created object. + + + Use the factory methods to create a . + The value of the property of a object is . + + + + + Creates a new expression that is like this one, but using the + supplied children. If all of the children are the same, it will + return this expression. + + The property of the result. + This expression if no children changed, or an expression with the updated children. + + + + Gets the bindings that describe how to initialize the members of a member. + + + + + Represents a call to either static or an instance method. + + + + + Creates a new expression that is like this one, but using the + supplied children. If all of the children are the same, it will + return this expression. + + The property of the result. + The property of the result. + This expression if no children changed, or an expression with the updated children. + + + + Dispatches to the specific visit method for this node type. + + + + + Returns a new MethodCallExpression replacing the existing instance/args with the + newly provided instance and args. Arguments can be null to use the existing + arguments. + + This helper is provided to allow re-writing of nodes to not depend on the specific optimized + subclass of MethodCallExpression which is being used. + + + + + Returns the node type of this . (Inherited from .) + + The that represents this expression. + + + + Gets the static type of the expression that this represents. (Inherited from .) + + The that represents the static type of the expression. + + + + Gets the for the method to be called. + + + + + Gets the that represents the instance + for instance method calls or null for static method cals. + + + + + Gets a collection of expressions that represent arguments to the method call. + + + + + Represents creating a new array and possibly initializing the elements of the new array. + + + + + Dispatches to the specific visit method for this node type. + + + + + Creates a new expression that is like this one, but using the + supplied children. If all of the children are the same, it will + return this expression. + + The property of the result. + This expression if no children changed, or an expression with the updated children. + + + + Gets the static type of the expression that this represents. (Inherited from .) + + The that represents the static type of the expression. + + + + Gets the bounds of the array if the value of the property is NewArrayBounds, or the values to initialize the elements of the new array if the value of the property is NewArrayInit. + + + + + Returns the node type of this . (Inherited from .) + + The that represents this expression. + + + + Returns the node type of this . (Inherited from .) + + The that represents this expression. + + + + Represents a constructor call. + + + + + Dispatches to the specific visit method for this node type. + + + + + Creates a new expression that is like this one, but using the + supplied children. If all of the children are the same, it will + return this expression. + + The property of the result. + This expression if no children changed, or an expression with the updated children. + + + + Gets the static type of the expression that this represents. (Inherited from .) + + The that represents the static type of the expression. + + + + Returns the node type of this . (Inherited from .) + + The that represents this expression. + + + + Gets the called constructor. + + + + + Gets the arguments to the constructor. + + + + + Gets the members that can retrieve the values of the fields that were initialized with constructor arguments. + + + + + Represents a named parameter expression. + + + + + Dispatches to the specific visit method for this node type. + + + + + Gets the static type of the expression that this represents. (Inherited from .) + + The that represents the static type of the expression. + + + + Returns the node type of this . (Inherited from .) + + The that represents this expression. + + + + The Name of the parameter or variable. + + + + + Indicates that this ParameterExpression is to be treated as a ByRef parameter. + + + + + Specialized subclass to avoid holding onto the byref flag in a + parameter expression. This version always holds onto the expression + type explicitly and therefore derives from TypedParameterExpression. + + + + + Specialized subclass which holds onto the type of the expression for + uncommon types. + + + + + Generic type to avoid needing explicit storage for primitive data types + which are commonly used. + + + + + Represents one case of a . + + + + + Returns a that represents the current . + + A that represents the current . + + + + Creates a new expression that is like this one, but using the + supplied children. If all of the children are the same, it will + return this expression. + + The property of the result. + The property of the result. + This expression if no children changed, or an expression with the updated children. + + + + Gets the values of this case. This case is selected for execution when the matches any of these values. + + + + + Gets the body of this case. + + + + + Represents a control expression that handles multiple selections by passing control to a . + + + + + Dispatches to the specific visit method for this node type. + + + + + Creates a new expression that is like this one, but using the + supplied children. If all of the children are the same, it will + return this expression. + + The property of the result. + The property of the result. + The property of the result. + This expression if no children changed, or an expression with the updated children. + + + + Gets the static type of the expression that this represents. + + The that represents the static type of the expression. + + + + Returns the node type of this Expression. Extension nodes should return + ExpressionType.Extension when overriding this method. + + The of the expression. + + + + Gets the test for the switch. + + + + + Gets the collection of objects for the switch. + + + + + Gets the test for the switch. + + + + + Gets the equality comparison method, if any. + + + + + Represents a try/catch/finally/fault block. + + The body is protected by the try block. + The handlers consist of a set of s that can either be catch or filters. + The fault runs if an exception is thrown. + The finally runs regardless of how control exits the body. + Only one of fault or finally can be supplied. + The return type of the try block must match the return type of any associated catch statements. + + + + + Dispatches to the specific visit method for this node type. + + + + + Creates a new expression that is like this one, but using the + supplied children. If all of the children are the same, it will + return this expression. + + The property of the result. + The property of the result. + The property of the result. + The property of the result. + This expression if no children changed, or an expression with the updated children. + + + + Gets the static type of the expression that this represents. (Inherited from .) + + The that represents the static type of the expression. + + + + Returns the node type of this . (Inherited from .) + + The that represents this expression. + + + + Gets the representing the body of the try block. + + + + + Gets the collection of s associated with the try block. + + + + + Gets the representing the finally block. + + + + + Gets the representing the fault block. + + + + + Represents an operation between an expression and a type. + + + + + Dispatches to the specific visit method for this node type. + + + + + Creates a new expression that is like this one, but using the + supplied children. If all of the children are the same, it will + return this expression. + + The property of the result. + This expression if no children changed, or an expression with the updated children. + + + + Gets the static type of the expression that this represents. + + The that represents the static type of the expression. + + + + Returns the node type of this Expression. Extension nodes should return + ExpressionType.Extension when overriding this method. + + The of the expression. + + + + Gets the expression operand of a type test operation. + + + + + Gets the type operand of a type test operation. + + + + + Searches for an operator method on the type. The method must have + the specified signature, no generic arguments, and have the + SpecialName bit set. Also searches inherited operator methods. + + NOTE: This was designed to satisfy the needs of op_True and + op_False, because we have to do runtime lookup for those. It may + not work right for unary operators in general. + + + + + We can cache references to types, as long as they aren't in + collectable assemblies. Unfortunately, we can't really distinguish + between different flavors of assemblies. But, we can at least + create a whitelist for types in mscorlib (so we get the primitives) + and System.Core (so we find Func/Action overloads, etc). + + + + + Represents an expression that has a unary operator. + + + + + Dispatches to the specific visit method for this node type. + + + + + Reduces the expression node to a simpler expression. + If CanReduce returns true, this should return a valid expression. + This method is allowed to return another node which itself + must be reduced. + + The reduced expression. + + + + Creates a new expression that is like this one, but using the + supplied children. If all of the children are the same, it will + return this expression. + + The property of the result. + This expression if no children changed, or an expression with the updated children. + + + + Gets the static type of the expression that this represents. (Inherited from .) + + The that represents the static type of the expression. + + + + Returns the node type of this . (Inherited from .) + + The that represents this expression. + + + + Gets the operand of the unary operation. + + An that represents the operand of the unary operation. + + + + Gets the implementing method for the unary operation. + + The that represents the implementing method. + + + + Gets a value that indicates whether the expression tree node represents a lifted call to an operator. + + true if the node represents a lifted call; otherwise, false. + + + + Gets a value that indicates whether the expression tree node represents a lifted call to an operator whose return type is lifted to a nullable type. + + true if the operator's return type is lifted to a nullable type; otherwise, false. + + + + Gets a value that indicates whether the expression tree node can be reduced. + + + + + This API supports the .NET Framework infrastructure and is not intended to be used directly from your code. + Represents the runtime state of a dynamically generated method. + + + + + Represents the non-trivial constants and locally executable expressions that are referenced by a dynamically generated method. + + + + + Represents the hoisted local variables from the parent context. + + + + + Creates an object to hold state of a dynamically generated method. + + The constant values used by the method. + The hoisted local variables from the parent context. + + + + CompilerScope is the data structure which the Compiler keeps information + related to compiling scopes. It stores the following information: + 1. Parent relationship (for resolving variables) + 2. Information about hoisted variables + 3. Information for resolving closures + + Instances are produced by VariableBinder, which does a tree walk + looking for scope nodes: LambdaExpression and BlockExpression. + + + + + parent scope, if any + + + + + The expression node for this scope + Can be LambdaExpression, BlockExpression, or CatchBlock + + + + + True if this node corresponds to an IL method. + Can only be true if the Node is a LambdaExpression. + But inlined lambdas will have it set to false. + + + + + Does this scope (or any inner scope) close over variables from any + parent scope? + Populated by VariableBinder + + + + + Variables defined in this scope, and whether they're hoisted or not + Populated by VariableBinder + + + + + Each variable referenced within this scope, and how often it was referenced + Populated by VariableBinder + + + + + Scopes whose variables were merged into this one + + Created lazily as we create hundreds of compiler scopes w/o merging scopes when compiling rules. + + + + + The scope's hoisted locals, if any. + Provides storage for variables that are referenced from nested lambdas + + + + + The closed over hoisted locals + + + + + Mutable dictionary that maps non-hoisted variables to either local + slots or argument slots + + + + + Called when entering a lambda/block. Performs all variable allocation + needed, including creating hoisted locals and IL locals for accessing + parent locals + + + + + Frees unnamed locals, clears state associated with this compiler + + + + + Adds a new virtual variable corresponding to an IL local + + + + + Resolve a local variable in this scope or a closed over scope + Throws if the variable is defined + + + + + This scope's hoisted locals, or the closed over locals, if any + Equivalent to: _hoistedLocals ?? _closureHoistedLocals + + + + + If the result of a TypeBinaryExpression is known statically, this + returns the result, otherwise it returns null, meaning we'll need + to perform the IsInst instruction at runtime. + + The result of this function must be equivalent to IsInst, or + null. + + + + + If the result of an isinst opcode is known statically, this + returns the result, otherwise it returns null, meaning we'll need + to perform the IsInst instruction at runtime. + + The result of this function must be equivalent to IsInst, or + null. + + + + + Write out the given AST + + + + + Return true if the input string contains any whitespace character. + Otherwise false. + + + + + Stores information about locals and arguments that are hoisted into + the closure array because they're referenced in an inner lambda. + + This class is sometimes emitted as a runtime constant for internal + use to hoist variables/parameters in quoted expressions + + Invariant: this class stores no mutable state + + + + + A simple dictionary of queues, keyed off a particular type + This is useful for storing free lists of variables + + + + + Dynamic Language Runtime Compiler. + This part compiles lambdas. + + + LambdaCompiler is responsible for compiling individual lambda (LambdaExpression). The complete tree may + contain multiple lambdas, the Compiler class is reponsible for compiling the whole tree, individual + lambdas are then compiled by the LambdaCompiler. + + + + + Update the flag with a new EmitAsTailCall flag + + + + + Update the flag with a new EmitExpressionStart flag + + + + + Update the flag with a new EmitAsType flag + + + + + Generates code for this expression in a value position. + This method will leave the value of the expression + on the top of the stack typed as Type. + + + + + Emits an expression and discards the result. For some nodes this emits + more optimial code then EmitExpression/Pop + + + + + Emits arguments to a call, and returns an array of writebacks that + should happen after the call. + + + + + Emits arguments to a call, and returns an array of writebacks that + should happen after the call. For emitting dynamic expressions, we + need to skip the first parameter of the method (the call site). + + + + + Emits code which creates new instance of the delegateType delegate. + + Since the delegate is getting closed over the "Closure" argument, this + cannot be used with virtual/instance methods (inner must be static method) + + + + + Emits a delegate to the method generated for the LambdaExpression. + May end up creating a wrapper to match the requested delegate type. + + Lambda for which to generate a delegate + + + + + Emits the lambda body. If inlined, the parameters should already be + pushed onto the IL stack. + + The parent scope. + true if the lambda is inlined; false otherwise. + + The emum to specify if the lambda is compiled with the tail call optimization. + + + + + returns true if the expression is not empty, otherwise false. + + + + + returns true if the expression is NOT empty and is not debug info, + or a block that contains only insignificant expressions. + + + + + Emits the expression and then either brtrue/brfalse to the label. + + True for brtrue, false for brfalse. + The expression to emit. + The label to conditionally branch to. + + This function optimizes equality and short circuiting logical + operators to avoid double-branching, minimize instruction count, + and generate similar IL to the C# compiler. This is important for + the JIT to optimize patterns like: + x != null AndAlso x.GetType() == typeof(SomeType) + + One optimization we don't do: we always emits at least one + conditional branch to the label, and always possibly falls through, + even if we know if the branch will always succeed or always fail. + We do this to avoid generating unreachable code, which is fine for + the CLR JIT, but doesn't verify with peverify. + + This kind of optimization could be implemented safely, by doing + constant folding over conditionals and logical expressions at the + tree level. + + + + + Gets the common test test value type of the SwitchExpression. + + + + + Creates the label for this case. + Optimization: if the body is just a goto, and we can branch + to it, put the goto target directly in the jump table. + + + + + Emits the start of a catch block. The exception value that is provided by the + CLR is stored in the variable specified by the catch block or popped if no + variable is provided. + + + + + The value is true if a clearance was emitted and no new sequence point + has been emitted since that. + + + + + Creates a lambda compiler that will compile to a dynamic method + + + + + Creates a lambda compiler that will compile into the provided Methodbuilder + + + + + Creates a lambda compiler for an inlined lambda + + + + + Compiler entry point + + LambdaExpression to compile. + Debug info generator. + The compiled delegate. + + + + Mutates the MethodBuilder parameter, filling in IL, parameters, + and return type. + + (probably shouldn't be modifying parameters/return type...) + + + + + Gets the argument slot corresponding to the parameter at the given + index. Assumes that the method takes a certain number of prefix + arguments, followed by the real parameters stored in Parameters + + + + + Returns the index-th argument. This method provides access to the actual arguments + defined on the lambda itself, and excludes the possible 0-th closure argument. + + + + + Creates an unitialized field suitible for private implementation details + Works with DynamicMethods or TypeBuilders. + + + + + Generates debug information for lambdas in an expression tree. + + + + + Creates PDB symbol generator. + + PDB symbol generator. + + + + Marks a sequence point. + + The lambda being generated. + IL offset where to mark the sequence point. + Debug informaton corresponding to the sequence point. + + + + A simple hashset, built on Dictionary{K, V} + + + + + Expression rewriting to spill the CLR stack into temporary variables + in order to guarantee some properties of code generation, for + example that we always enter try block on empty stack. + + + + + Rewrite the expression + + + Expression to rewrite + State of the stack before the expression is emitted. + Rewritten expression. + + + + Will perform: + save: temp = expression + return value: temp + + + + + Creates a special block that is marked as not allowing jumps in. + This should not be used for rewriting BlockExpression itself, or + anything else that supports jumping. + + + + + Creates a special block that is marked as not allowing jumps in. + This should not be used for rewriting BlockExpression itself, or + anything else that supports jumping. + + + + + The source of temporary variables + + + + + Initial stack state. Normally empty, but when inlining the lambda + we might have a non-empty starting stack state. + + + + + Lambda rewrite result. We need this for inlined lambdas to figure + out whether we need to guarentee it an empty stack. + + + + + Analyzes a lambda, producing a new one that has correct invariants + for codegen. In particular, it spills the IL stack to temps in + places where it's invalid to have a non-empty stack (for example, + entering a try statement). + + + + + Will clone an IList into an array of the same size, and copy + all vaues up to (and NOT including) the max index + + The cloned array. + + + + If we are spilling, requires that there are no byref arguments to + the method call. + + Used for: + NewExpression, + MethodCallExpression, + InvocationExpression, + DynamicExpression, + UnaryExpression, + BinaryExpression. + + + We could support this if spilling happened later in the compiler. + Other expressions that can emit calls with arguments (such as + ListInitExpression and IndexExpression) don't allow byref arguments. + + + + + Requires that the instance is not a value type (primitive types are + okay because they're immutable). + + Used for: + MethodCallExpression, + MemberExpression (for properties), + IndexExpression, + ListInitExpression, + MemberInitExpression, + assign to MemberExpression, + assign to IndexExpression. + + + We could support this if spilling happened later in the compiler. + + + + + Current temporary variable + + + + + List of free temporary variables. These can be recycled for new temps. + + + + + Stack of currently active temporary variables. + + + + + List of all temps created by stackspiller for this rule/lambda + + + + + Rewrites child expressions, spilling them into temps if needed. The + stack starts in the inital state, and after the first subexpression + is added it is change to non-empty. This behavior can be overridden + by setting the stack manually between adds. + + When all children have been added, the caller should rewrite the + node if Rewrite is true. Then, it should call Finish with etiher + the orignal expression or the rewritten expression. Finish will call + Expression.Comma if necessary and return a new Result. + + + + + A special subtype of BlockExpression that indicates to the compiler + that this block is a spilled expression and should not allow jumps in. + + + + + Generator of PDB debugging information for expression trees. + + + + + Determines if variables are closed over in nested lambdas and need to + be hoisted. + + + + + Emits a Ldind* instruction for the appropriate type + + + + + Emits a Stind* instruction for the appropriate type. + + + + + Emits a Stelem* instruction for the appropriate type. + + + + + Emits an array of constant values provided in the given list. + The array is strongly typed. + + + + + Emits an array of values of count size. The items are emitted via the callback + which is provided with the current item index to emit. + + + + + Emits an array construction code. + The code assumes that bounds for all dimensions + are already emitted. + + + + + Emits default(T) + Semantics match C# compiler behavior + + + + + Encapsulates a method that takes five parameters and does not return a value. + + The type of the first parameter of the method that this delegate encapsulates. + The type of the second parameter of the method that this delegate encapsulates. + The type of the third parameter of the method that this delegate encapsulates. + The type of the fourth parameter of the method that this delegate encapsulates. + The type of the fifth parameter of the method that this delegate encapsulates. + The first parameter of the method that this delegate encapsulates. + The second parameter of the method that this delegate encapsulates. + The third parameter of the method that this delegate encapsulates. + The fourth parameter of the method that this delegate encapsulates. + The fifth parameter of the method that this delegate encapsulates. + + + + Encapsulates a method that takes six parameters and does not return a value. + + The type of the first parameter of the method that this delegate encapsulates. + The type of the second parameter of the method that this delegate encapsulates. + The type of the third parameter of the method that this delegate encapsulates. + The type of the fourth parameter of the method that this delegate encapsulates. + The type of the fifth parameter of the method that this delegate encapsulates. + The type of the sixth parameter of the method that this delegate encapsulates. + The first parameter of the method that this delegate encapsulates. + The second parameter of the method that this delegate encapsulates. + The third parameter of the method that this delegate encapsulates. + The fourth parameter of the method that this delegate encapsulates. + The fifth parameter of the method that this delegate encapsulates. + The sixth parameter of the method that this delegate encapsulates. + + + + Encapsulates a method that takes seven parameters and does not return a value. + + The type of the first parameter of the method that this delegate encapsulates. + The type of the second parameter of the method that this delegate encapsulates. + The type of the third parameter of the method that this delegate encapsulates. + The type of the fourth parameter of the method that this delegate encapsulates. + The type of the fifth parameter of the method that this delegate encapsulates. + The type of the sixth parameter of the method that this delegate encapsulates. + The type of the seventh parameter of the method that this delegate encapsulates. + The first parameter of the method that this delegate encapsulates. + The second parameter of the method that this delegate encapsulates. + The third parameter of the method that this delegate encapsulates. + The fourth parameter of the method that this delegate encapsulates. + The fifth parameter of the method that this delegate encapsulates. + The sixth parameter of the method that this delegate encapsulates. + The seventh parameter of the method that this delegate encapsulates. + + + + Encapsulates a method that takes eight parameters and does not return a value. + + The type of the first parameter of the method that this delegate encapsulates. + The type of the second parameter of the method that this delegate encapsulates. + The type of the third parameter of the method that this delegate encapsulates. + The type of the fourth parameter of the method that this delegate encapsulates. + The type of the fifth parameter of the method that this delegate encapsulates. + The type of the sixth parameter of the method that this delegate encapsulates. + The type of the seventh parameter of the method that this delegate encapsulates. + The type of the eighth parameter of the method that this delegate encapsulates. + The first parameter of the method that this delegate encapsulates. + The second parameter of the method that this delegate encapsulates. + The third parameter of the method that this delegate encapsulates. + The fourth parameter of the method that this delegate encapsulates. + The fifth parameter of the method that this delegate encapsulates. + The sixth parameter of the method that this delegate encapsulates. + The seventh parameter of the method that this delegate encapsulates. + The eighth parameter of the method that this delegate encapsulates. + + + + Encapsulates a method that takes nine parameters and does not return a value. + + The type of the first parameter of the method that this delegate encapsulates. + The type of the second parameter of the method that this delegate encapsulates. + The type of the third parameter of the method that this delegate encapsulates. + The type of the fourth parameter of the method that this delegate encapsulates. + The type of the fifth parameter of the method that this delegate encapsulates. + The type of the sixth parameter of the method that this delegate encapsulates. + The type of the seventh parameter of the method that this delegate encapsulates. + The type of the eighth parameter of the method that this delegate encapsulates. + The type of the ninth parameter of the method that this delegate encapsulates. + The first parameter of the method that this delegate encapsulates. + The second parameter of the method that this delegate encapsulates. + The third parameter of the method that this delegate encapsulates. + The fourth parameter of the method that this delegate encapsulates. + The fifth parameter of the method that this delegate encapsulates. + The sixth parameter of the method that this delegate encapsulates. + The seventh parameter of the method that this delegate encapsulates. + The eighth parameter of the method that this delegate encapsulates. + The ninth parameter of the method that this delegate encapsulates. + + + + Encapsulates a method that takes ten parameters and does not return a value. + + The type of the first parameter of the method that this delegate encapsulates. + The type of the second parameter of the method that this delegate encapsulates. + The type of the third parameter of the method that this delegate encapsulates. + The type of the fourth parameter of the method that this delegate encapsulates. + The type of the fifth parameter of the method that this delegate encapsulates. + The type of the sixth parameter of the method that this delegate encapsulates. + The type of the seventh parameter of the method that this delegate encapsulates. + The type of the eighth parameter of the method that this delegate encapsulates. + The type of the ninth parameter of the method that this delegate encapsulates. + The type of the tenth parameter of the method that this delegate encapsulates. + The first parameter of the method that this delegate encapsulates. + The second parameter of the method that this delegate encapsulates. + The third parameter of the method that this delegate encapsulates. + The fourth parameter of the method that this delegate encapsulates. + The fifth parameter of the method that this delegate encapsulates. + The sixth parameter of the method that this delegate encapsulates. + The seventh parameter of the method that this delegate encapsulates. + The eighth parameter of the method that this delegate encapsulates. + The ninth parameter of the method that this delegate encapsulates. + The tenth parameter of the method that this delegate encapsulates. + + + + Encapsulates a method that takes eleven parameters and does not return a value. + + The type of the first parameter of the method that this delegate encapsulates. + The type of the second parameter of the method that this delegate encapsulates. + The type of the third parameter of the method that this delegate encapsulates. + The type of the fourth parameter of the method that this delegate encapsulates. + The type of the fifth parameter of the method that this delegate encapsulates. + The type of the sixth parameter of the method that this delegate encapsulates. + The type of the seventh parameter of the method that this delegate encapsulates. + The type of the eighth parameter of the method that this delegate encapsulates. + The type of the ninth parameter of the method that this delegate encapsulates. + The type of the tenth parameter of the method that this delegate encapsulates. + The type of the eleventh parameter of the method that this delegate encapsulates. + The first parameter of the method that this delegate encapsulates. + The second parameter of the method that this delegate encapsulates. + The third parameter of the method that this delegate encapsulates. + The fourth parameter of the method that this delegate encapsulates. + The fifth parameter of the method that this delegate encapsulates. + The sixth parameter of the method that this delegate encapsulates. + The seventh parameter of the method that this delegate encapsulates. + The eighth parameter of the method that this delegate encapsulates. + The ninth parameter of the method that this delegate encapsulates. + The tenth parameter of the method that this delegate encapsulates. + The eleventh parameter of the method that this delegate encapsulates. + + + + Encapsulates a method that takes twelve parameters and does not return a value. + + The type of the first parameter of the method that this delegate encapsulates. + The type of the second parameter of the method that this delegate encapsulates. + The type of the third parameter of the method that this delegate encapsulates. + The type of the fourth parameter of the method that this delegate encapsulates. + The type of the fifth parameter of the method that this delegate encapsulates. + The type of the sixth parameter of the method that this delegate encapsulates. + The type of the seventh parameter of the method that this delegate encapsulates. + The type of the eighth parameter of the method that this delegate encapsulates. + The type of the ninth parameter of the method that this delegate encapsulates. + The type of the tenth parameter of the method that this delegate encapsulates. + The type of the eleventh parameter of the method that this delegate encapsulates. + The type of the twelfth parameter of the method that this delegate encapsulates. + The first parameter of the method that this delegate encapsulates. + The second parameter of the method that this delegate encapsulates. + The third parameter of the method that this delegate encapsulates. + The fourth parameter of the method that this delegate encapsulates. + The fifth parameter of the method that this delegate encapsulates. + The sixth parameter of the method that this delegate encapsulates. + The seventh parameter of the method that this delegate encapsulates. + The eighth parameter of the method that this delegate encapsulates. + The ninth parameter of the method that this delegate encapsulates. + The tenth parameter of the method that this delegate encapsulates. + The eleventh parameter of the method that this delegate encapsulates. + The twelfth parameter of the method that this delegate encapsulates. + + + + Encapsulates a method that takes thirteen parameters and does not return a value. + + The type of the first parameter of the method that this delegate encapsulates. + The type of the second parameter of the method that this delegate encapsulates. + The type of the third parameter of the method that this delegate encapsulates. + The type of the fourth parameter of the method that this delegate encapsulates. + The type of the fifth parameter of the method that this delegate encapsulates. + The type of the sixth parameter of the method that this delegate encapsulates. + The type of the seventh parameter of the method that this delegate encapsulates. + The type of the eighth parameter of the method that this delegate encapsulates. + The type of the ninth parameter of the method that this delegate encapsulates. + The type of the tenth parameter of the method that this delegate encapsulates. + The type of the eleventh parameter of the method that this delegate encapsulates. + The type of the twelfth parameter of the method that this delegate encapsulates. + The type of the thirteenth parameter of the method that this delegate encapsulates. + The first parameter of the method that this delegate encapsulates. + The second parameter of the method that this delegate encapsulates. + The third parameter of the method that this delegate encapsulates. + The fourth parameter of the method that this delegate encapsulates. + The fifth parameter of the method that this delegate encapsulates. + The sixth parameter of the method that this delegate encapsulates. + The seventh parameter of the method that this delegate encapsulates. + The eighth parameter of the method that this delegate encapsulates. + The ninth parameter of the method that this delegate encapsulates. + The tenth parameter of the method that this delegate encapsulates. + The eleventh parameter of the method that this delegate encapsulates. + The twelfth parameter of the method that this delegate encapsulates. + The thirteenth parameter of the method that this delegate encapsulates. + + + + Encapsulates a method that takes fourteen parameters and does not return a value. + + The type of the first parameter of the method that this delegate encapsulates. + The type of the second parameter of the method that this delegate encapsulates. + The type of the third parameter of the method that this delegate encapsulates. + The type of the fourth parameter of the method that this delegate encapsulates. + The type of the fifth parameter of the method that this delegate encapsulates. + The type of the sixth parameter of the method that this delegate encapsulates. + The type of the seventh parameter of the method that this delegate encapsulates. + The type of the eighth parameter of the method that this delegate encapsulates. + The type of the ninth parameter of the method that this delegate encapsulates. + The type of the tenth parameter of the method that this delegate encapsulates. + The type of the eleventh parameter of the method that this delegate encapsulates. + The type of the twelfth parameter of the method that this delegate encapsulates. + The type of the thirteenth parameter of the method that this delegate encapsulates. + The type of the fourteenth parameter of the method that this delegate encapsulates. + The first parameter of the method that this delegate encapsulates. + The second parameter of the method that this delegate encapsulates. + The third parameter of the method that this delegate encapsulates. + The fourth parameter of the method that this delegate encapsulates. + The fifth parameter of the method that this delegate encapsulates. + The sixth parameter of the method that this delegate encapsulates. + The seventh parameter of the method that this delegate encapsulates. + The eighth parameter of the method that this delegate encapsulates. + The ninth parameter of the method that this delegate encapsulates. + The tenth parameter of the method that this delegate encapsulates. + The eleventh parameter of the method that this delegate encapsulates. + The twelfth parameter of the method that this delegate encapsulates. + The thirteenth parameter of the method that this delegate encapsulates. + The fourteenth parameter of the method that this delegate encapsulates. + + + + Encapsulates a method that takes fifteen parameters and does not return a value. + + The type of the first parameter of the method that this delegate encapsulates. + The type of the second parameter of the method that this delegate encapsulates. + The type of the third parameter of the method that this delegate encapsulates. + The type of the fourth parameter of the method that this delegate encapsulates. + The type of the fifth parameter of the method that this delegate encapsulates. + The type of the sixth parameter of the method that this delegate encapsulates. + The type of the seventh parameter of the method that this delegate encapsulates. + The type of the eighth parameter of the method that this delegate encapsulates. + The type of the ninth parameter of the method that this delegate encapsulates. + The type of the tenth parameter of the method that this delegate encapsulates. + The type of the eleventh parameter of the method that this delegate encapsulates. + The type of the twelfth parameter of the method that this delegate encapsulates. + The type of the thirteenth parameter of the method that this delegate encapsulates. + The type of the fourteenth parameter of the method that this delegate encapsulates. + The type of the fifteenth parameter of the method that this delegate encapsulates. + The first parameter of the method that this delegate encapsulates. + The second parameter of the method that this delegate encapsulates. + The third parameter of the method that this delegate encapsulates. + The fourth parameter of the method that this delegate encapsulates. + The fifth parameter of the method that this delegate encapsulates. + The sixth parameter of the method that this delegate encapsulates. + The seventh parameter of the method that this delegate encapsulates. + The eighth parameter of the method that this delegate encapsulates. + The ninth parameter of the method that this delegate encapsulates. + The tenth parameter of the method that this delegate encapsulates. + The eleventh parameter of the method that this delegate encapsulates. + The twelfth parameter of the method that this delegate encapsulates. + The thirteenth parameter of the method that this delegate encapsulates. + The fourteenth parameter of the method that this delegate encapsulates. + The fifteenth parameter of the method that this delegate encapsulates. + + + + Encapsulates a method that takes sixteen parameters and does not return a value. + + The type of the first parameter of the method that this delegate encapsulates. + The type of the second parameter of the method that this delegate encapsulates. + The type of the third parameter of the method that this delegate encapsulates. + The type of the fourth parameter of the method that this delegate encapsulates. + The type of the fifth parameter of the method that this delegate encapsulates. + The type of the sixth parameter of the method that this delegate encapsulates. + The type of the seventh parameter of the method that this delegate encapsulates. + The type of the eighth parameter of the method that this delegate encapsulates. + The type of the ninth parameter of the method that this delegate encapsulates. + The type of the tenth parameter of the method that this delegate encapsulates. + The type of the eleventh parameter of the method that this delegate encapsulates. + The type of the twelfth parameter of the method that this delegate encapsulates. + The type of the thirteenth parameter of the method that this delegate encapsulates. + The type of the fourteenth parameter of the method that this delegate encapsulates. + The type of the fifteenth parameter of the method that this delegate encapsulates. + The type of the sixteenth parameter of the method that this delegate encapsulates. + The first parameter of the method that this delegate encapsulates. + The second parameter of the method that this delegate encapsulates. + The third parameter of the method that this delegate encapsulates. + The fourth parameter of the method that this delegate encapsulates. + The fifth parameter of the method that this delegate encapsulates. + The sixth parameter of the method that this delegate encapsulates. + The seventh parameter of the method that this delegate encapsulates. + The eighth parameter of the method that this delegate encapsulates. + The ninth parameter of the method that this delegate encapsulates. + The tenth parameter of the method that this delegate encapsulates. + The eleventh parameter of the method that this delegate encapsulates. + The twelfth parameter of the method that this delegate encapsulates. + The thirteenth parameter of the method that this delegate encapsulates. + The fourteenth parameter of the method that this delegate encapsulates. + The fifteenth parameter of the method that this delegate encapsulates. + The sixteenth parameter of the method that this delegate encapsulates. + + + + Provides a dictionary-like object used for caches which holds onto a maximum + number of elements specified at construction time. + + This class is not thread safe. + + + + + Creates a dictionary-like object used for caches. + + The maximum number of elements to store. + + + + Tries to get the value associated with 'key', returning true if it's found and + false if it's not present. + + + + + Adds a new element to the cache, replacing and moving it to the front if the + element is already present. + + + + + Returns the value associated with the given key, or throws KeyNotFoundException + if the key is not present. + + + + + Wraps the provided enumerable into a ReadOnlyCollection{T} + + Copies all of the data into a new array, so the data can't be + changed after creation. The exception is if the enumerable is + already a ReadOnlyCollection{T}, in which case we just return it. + + + + + Requires the range [offset, offset + count] to be a subset of [0, array.Count]. + + Array is null. + Offset or count are out of range. + + + + Requires the array and all its items to be non-null. + + + + + Strongly-typed and parameterized string factory. + + + + + A string like "Variable '{0}' uses unsupported type '{1}'. Reference types are not supported for variables." + + + + + A string like "Found duplicate parameter '{0}'. Each ParameterExpression in the list must be a unique object." + + + + + A string like "Extension node must override the property {0}." + + + + + A string like "User-defined operator method '{0}' must be static." + + + + + A string like "User-defined operator method '{0}' must not be void." + + + + + A string like "No coercion operator is defined between types '{0}' and '{1}'." + + + + + A string like "The result type '{0}' of the dynamic binding produced by binder '{1}' is not compatible with the result type '{2}' expected by the call site." + + + + + A string like "The result type '{0}' of the dynamic binding produced by the object with type '{1}' for the binder '{2}' is not compatible with the result type '{3}' expected by the call site." + + + + + A string like "The result of the dynamic binding produced by the object with type '{0}' for the binder '{1}' needs at least one restriction." + + + + + A string like "The result type '{0}' of the binder '{1}' is not compatible with the result type '{2}' expected by the call site." + + + + + A string like "The unary operator {0} is not defined for the type '{1}'." + + + + + A string like "The binary operator {0} is not defined for the types '{1}' and '{2}'." + + + + + A string like "Reference equality is not defined for the types '{0}' and '{1}'." + + + + + A string like "The operands for operator '{0}' do not match the parameters of method '{1}'." + + + + + A string like "The return type of overload method for operator '{0}' does not match the parameter type of conversion method '{1}'." + + + + + A string like "The user-defined equality method '{0}' must return a boolean value." + + + + + A string like "Cannot auto initialize elements of value type through property '{0}', use assignment instead" + + + + + A string like "Cannot auto initialize members of value type through property '{0}', use assignment instead" + + + + + A string like "The type used in TypeAs Expression must be of reference or nullable type, {0} is neither" + + + + + A string like "An expression of type '{0}' cannot be used to initialize an array of type '{1}'" + + + + + A string like "Expression of type '{0}' cannot be used for constructor parameter of type '{1}'" + + + + + A string like " Argument type '{0}' does not match the corresponding member type '{1}'" + + + + + A string like " The member '{0}' is not declared on type '{1}' being created" + + + + + A string like "Expression of type '{0}' cannot be used for parameter of type '{1}' of method '{2}'" + + + + + A string like "Expression of type '{0}' cannot be used for parameter of type '{1}'" + + + + + A string like "Expression of type '{0}' cannot be used for return type '{1}'" + + + + + A string like "Expression of type '{0}' cannot be used for assignment to type '{1}'" + + + + + A string like "Expression of type '{0}' cannot be used for label of type '{1}'" + + + + + A string like "Expression of type '{0}' cannot be invoked" + + + + + A string like "Field '{0}' is not defined for type '{1}'" + + + + + A string like "Instance field '{0}' is not defined for type '{1}'" + + + + + A string like "Field '{0}.{1}' is not defined for type '{2}'" + + + + + A string like "Incorrect number of arguments supplied for call to method '{0}'" + + + + + A string like "Member '{0}' not field or property" + + + + + A string like "Method {0} contains generic parameters" + + + + + A string like "Method {0} is a generic method definition" + + + + + A string like "The method '{0}.{1}' is not a property accessor" + + + + + A string like "The property '{0}' has no 'get' accessor" + + + + + A string like "The property '{0}' has no 'set' accessor" + + + + + A string like "The property '{0}' has no 'get' or 'set' accessors" + + + + + A string like "'{0}' is not a member of type '{1}'" + + + + + A string like "The operator '{0}' is not implemented for type '{1}'" + + + + + A string like "ParameterExpression of type '{0}' cannot be used for delegate parameter of type '{1}'" + + + + + A string like "Property '{0}' is not defined for type '{1}'" + + + + + A string like "Instance property '{0}' is not defined for type '{1}'" + + + + + A string like "Instance property '{0}' that takes no argument is not defined for type '{1}'" + + + + + A string like "Instance property '{0}{1}' is not defined for type '{2}'" + + + + + A string like "Method '{0}' declared on type '{1}' cannot be called with instance of type '{2}'" + + + + + A string like "Type {0} contains generic parameters" + + + + + A string like "Type {0} is a generic type definition" + + + + + A string like "Type '{0}' does not have a default constructor" + + + + + A string like "Parameter '{0}' of element initializer method '{1}' must not be a pass by reference parameter" + + + + + A string like "Type '{0}' is not IEnumerable" + + + + + A string like "Type parameter is {0}. Expected a delegate." + + + + + A string like "Cannot cast from type '{0}' to type '{1}" + + + + + A string like "Unhandled binary: {0}" + + + + + A string like "Unhandled Binding Type: {0}" + + + + + A string like "Unhandled convert: {0}" + + + + + A string like "Unhandled Expression Type: {0}" + + + + + A string like "Unhandled unary: {0}" + + + + + A string like "The user-defined operator method '{1}' for operator '{0}' must have identical parameter and return types." + + + + + A string like "The user-defined operator method '{1}' for operator '{0}' must return the same type as its parameter or a derived type." + + + + + A string like "The user-defined operator method '{1}' for operator '{0}' must have associated boolean True and False operators." + + + + + A string like "No method '{0}' exists on type '{1}'." + + + + + A string like "No method '{0}' on type '{1}' is compatible with the supplied arguments." + + + + + A string like "No generic method '{0}' on type '{1}' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic. " + + + + + A string like "More than one method '{0}' on type '{1}' is compatible with the supplied arguments." + + + + + A string like "More than one property '{0}' on type '{1}' is compatible with the supplied arguments." + + + + + A string like "More than one key matching '{0}' was found in the ExpandoObject." + + + + + A string like "An element with the same key '{0}' already exists in the ExpandoObject." + + + + + A string like "The specified key '{0}' does not exist in the ExpandoObject." + + + + + A string like "Invalid operation: '{0}'" + + + + + A string like "{0} must be greater than or equal to {1}" + + + + + A string like "Cannot redefine label '{0}' in an inner block." + + + + + A string like "Cannot jump to undefined label '{0}'." + + + + + A string like "Cannot jump to ambiguous label '{0}'." + + + + + A string like "Cannot jump to non-local label '{0}' with a value. Only jumps to labels defined in outer blocks can pass values." + + + + + A string like "CompileToMethod cannot compile constant '{0}' because it is a non-trivial value, such as a live object. Instead, create an expression tree that can construct this value." + + + + + A string like "Invalid lvalue for assignment: {0}." + + + + + A string like "Invalid member type: {0}." + + + + + A string like "unknown lift type: '{0}'." + + + + + A string like "Cannot create instance of {0} because it contains generic parameters" + + + + + A string like "variable '{0}' of type '{1}' referenced from scope '{2}', but it is not defined" + + + + + A string like "Cannot close over byref parameter '{0}' referenced in lambda '{1}'" + + + + + A string like "Unexpected VarArgs call to method '{0}'" + + + + + A string like "When called from '{0}', rewriting a node of type '{1}' must return a non-null value of the same type. Alternatively, override '{2}' and change it to not visit children of this type." + + + + + A string like "Rewriting child expression from type '{0}' to type '{1}' is not allowed, because it would change the meaning of the operation. If this is intentional, override '{2}' and change it to allow this rewrite." + + + + + A string like "Rewritten expression calls operator method '{0}', but the original node had no operator method. If this is is intentional, override '{1}' and change it to allow this rewrite." + + + + + A string like "The value null is not of type '{0}' and cannot be used in this collection." + + + + + A string like "The value '{0}' is not of type '{1}' and cannot be used in this collection." + + + + + A string like "TryExpression is not supported as an argument to method '{0}' because it has an argument with by-ref type. Construct the tree so the TryExpression is not nested inside of this expression." + + + + + A string like "TryExpression is not supported as a child expression when accessing a member on type '{0}' because it is a value type. Construct the tree so the TryExpression is not nested inside of this expression." + + + + + A string like "Test value of type '{0}' cannot be used for the comparison method parameter of type '{1}'" + + + + + A string like "Switch value of type '{0}' cannot be used for the comparison method parameter of type '{1}'" + + + + + A string like "An IDynamicMetaObjectProvider {0} created an invalid DynamicMetaObject instance." + + + + + A string like "Method precondition violated" + + + + + A string like "Invalid argument value" + + + + + A string like "Non-empty collection required" + + + + + A string like "Argument count must be greater than number of named arguments." + + + + + A string like "reducible nodes must override Expression.Reduce()" + + + + + A string like "node cannot reduce to itself or null" + + + + + A string like "cannot assign from the reduced node type to the original node type" + + + + + A string like "Setter must have parameters." + + + + + A string like "Property cannot have a managed pointer type." + + + + + A string like "Indexing parameters of getter and setter must match." + + + + + A string like "Accessor method should not have VarArgs." + + + + + A string like "Accessor indexes cannot be passed ByRef." + + + + + A string like "Bounds count cannot be less than 1" + + + + + A string like "type must not be ByRef" + + + + + A string like "Type doesn't have constructor with a given signature" + + + + + A string like "Count must be non-negative." + + + + + A string like "arrayType must be an array type" + + + + + A string like "Setter should have void type." + + + + + A string like "Property type must match the value type of setter" + + + + + A string like "Both accessors must be static." + + + + + A string like "Static field requires null instance, non-static field requires non-null instance." + + + + + A string like "Static property requires null instance, non-static property requires non-null instance." + + + + + A string like "Static method requires null instance, non-static method requires non-null instance." + + + + + A string like "Property cannot have a void type." + + + + + A string like "Can only unbox from an object or interface type to a value type." + + + + + A string like "Expression must be readable" + + + + + A string like "Expression must be writeable" + + + + + A string like "Argument must not have a value type." + + + + + A string like "must be reducible node" + + + + + A string like "All test values must have the same type." + + + + + A string like "All case bodies and the default body must have the same type." + + + + + A string like "Default body must be supplied if case bodies are not System.Void." + + + + + A string like "MethodBuilder does not have a valid TypeBuilder" + + + + + A string like "Type must be derived from System.Delegate" + + + + + A string like "Argument type cannot be void" + + + + + A string like "Label type must be System.Void if an expression is not supplied" + + + + + A string like "Type must be System.Void for this label argument" + + + + + A string like "Quoted expression must be a lambda" + + + + + A string like "Start and End must be well ordered" + + + + + A string like "fault cannot be used with catch or finally clauses" + + + + + A string like "try must have at least one catch, finally, or fault clause" + + + + + A string like "Body of catch must have the same type as body of try." + + + + + A string like "Conversion is not supported for arithmetic types without operator overloading." + + + + + A string like "Argument must be array" + + + + + A string like "Argument must be boolean" + + + + + A string like "Argument must be either a FieldInfo or PropertyInfo" + + + + + A string like "Argument must be either a FieldInfo, PropertyInfo or MethodInfo" + + + + + A string like "Argument must be an instance member" + + + + + A string like "Argument must be of an integer type" + + + + + A string like "Argument for array index must be of type Int32" + + + + + A string like "Argument must be single dimensional array type" + + + + + A string like "Argument types do not match" + + + + + A string like "Coalesce used with type that cannot be null" + + + + + A string like "Incorrect number of indexes" + + + + + A string like "Incorrect number of arguments supplied for lambda invocation" + + + + + A string like "Incorrect number of parameters supplied for lambda declaration" + + + + + A string like "Incorrect number of arguments for constructor" + + + + + A string like " Incorrect number of members for constructor" + + + + + A string like "Incorrect number of arguments for the given members " + + + + + A string like "Lambda type parameter must be derived from System.Delegate" + + + + + A string like "List initializers must contain at least one initializer" + + + + + A string like "Element initializer method must be named 'Add'" + + + + + A string like "Element initializer method must have at least 1 parameter" + + + + + A string like "Element initializer method must be an instance method" + + + + + A string like "Unexpected coalesce operator." + + + + + A string like "Unhandled binding " + + + + + A string like "Unknown binding type" + + + + + A string like "An incorrect number of type args were specified for the declaration of a Func type." + + + + + A string like "An incorrect number of type args were specified for the declaration of an Action type." + + + + + A string like "Argument type cannot be System.Void." + + + + + A string like "No or Invalid rule produced" + + + + + A string like "First argument of delegate must be CallSite" + + + + + A string like "Bind cannot return null." + + + + + A string like "Queue empty." + + + + + A string like "Control cannot leave a finally block." + + + + + A string like "Control cannot leave a filter test." + + + + + A string like "Control cannot enter a try block." + + + + + A string like "Control cannot enter an expression--only statements can be jumped into." + + + + + A string like "Extension should have been reduced." + + + + + A string like "Dynamic expressions are not supported by CompileToMethod. Instead, create an expression tree that uses System.Runtime.CompilerServices.CallSite." + + + + + A string like "Invalid output directory." + + + + + A string like "Invalid assembly name or file extension." + + + + + A string like "Collection is read-only." + + + + + A string like "Rethrow statement is valid only inside a Catch block." + + + + + A string like "Try expression is not allowed inside a filter body." + + + + + A string like "Collection was modified; enumeration operation may not execute." + + + + + A string like "Enumeration has either not started or has already finished." + + + + + A string like "Dynamic operations can only be performed in homogenous AppDomain." + + + + + A string like "DebugInfoGenerator created by CreatePdbGenerator can only be used with LambdaExpression.CompileToMethod." + + + + + Strongly-typed and parameterized exception factory. + + + + + ArgumentException with message like "Argument count must be greater than number of named arguments." + + + + + ArgumentException with message like "reducible nodes must override Expression.Reduce()" + + + + + ArgumentException with message like "node cannot reduce to itself or null" + + + + + ArgumentException with message like "cannot assign from the reduced node type to the original node type" + + + + + ArgumentException with message like "Setter must have parameters." + + + + + ArgumentException with message like "Property cannot have a managed pointer type." + + + + + ArgumentException with message like "Indexing parameters of getter and setter must match." + + + + + ArgumentException with message like "Accessor method should not have VarArgs." + + + + + ArgumentException with message like "Accessor indexes cannot be passed ByRef." + + + + + ArgumentException with message like "Bounds count cannot be less than 1" + + + + + ArgumentException with message like "type must not be ByRef" + + + + + ArgumentException with message like "Type doesn't have constructor with a given signature" + + + + + ArgumentException with message like "Count must be non-negative." + + + + + ArgumentException with message like "arrayType must be an array type" + + + + + ArgumentException with message like "Setter should have void type." + + + + + ArgumentException with message like "Property type must match the value type of setter" + + + + + ArgumentException with message like "Both accessors must be static." + + + + + ArgumentException with message like "Static method requires null instance, non-static method requires non-null instance." + + + + + ArgumentException with message like "Property cannot have a void type." + + + + + ArgumentException with message like "Can only unbox from an object or interface type to a value type." + + + + + ArgumentException with message like "Argument must not have a value type." + + + + + ArgumentException with message like "must be reducible node" + + + + + ArgumentException with message like "Default body must be supplied if case bodies are not System.Void." + + + + + ArgumentException with message like "MethodBuilder does not have a valid TypeBuilder" + + + + + ArgumentException with message like "Type must be derived from System.Delegate" + + + + + ArgumentException with message like "Argument type cannot be void" + + + + + ArgumentException with message like "Label type must be System.Void if an expression is not supplied" + + + + + ArgumentException with message like "Type must be System.Void for this label argument" + + + + + ArgumentException with message like "Quoted expression must be a lambda" + + + + + ArgumentException with message like "Variable '{0}' uses unsupported type '{1}'. Reference types are not supported for variables." + + + + + ArgumentException with message like "Found duplicate parameter '{0}'. Each ParameterExpression in the list must be a unique object." + + + + + ArgumentException with message like "Start and End must be well ordered" + + + + + ArgumentException with message like "fault cannot be used with catch or finally clauses" + + + + + ArgumentException with message like "try must have at least one catch, finally, or fault clause" + + + + + ArgumentException with message like "Body of catch must have the same type as body of try." + + + + + InvalidOperationException with message like "Extension node must override the property {0}." + + + + + ArgumentException with message like "User-defined operator method '{0}' must be static." + + + + + ArgumentException with message like "User-defined operator method '{0}' must not be void." + + + + + InvalidOperationException with message like "No coercion operator is defined between types '{0}' and '{1}'." + + + + + InvalidCastException with message like "The result type '{0}' of the dynamic binding produced by binder '{1}' is not compatible with the result type '{2}' expected by the call site." + + + + + InvalidCastException with message like "The result type '{0}' of the dynamic binding produced by the object with type '{1}' for the binder '{2}' is not compatible with the result type '{3}' expected by the call site." + + + + + InvalidOperationException with message like "The result of the dynamic binding produced by the object with type '{0}' for the binder '{1}' needs at least one restriction." + + + + + InvalidOperationException with message like "The result type '{0}' of the binder '{1}' is not compatible with the result type '{2}' expected by the call site." + + + + + InvalidOperationException with message like "The unary operator {0} is not defined for the type '{1}'." + + + + + InvalidOperationException with message like "The binary operator {0} is not defined for the types '{1}' and '{2}'." + + + + + InvalidOperationException with message like "Reference equality is not defined for the types '{0}' and '{1}'." + + + + + InvalidOperationException with message like "The operands for operator '{0}' do not match the parameters of method '{1}'." + + + + + InvalidOperationException with message like "The return type of overload method for operator '{0}' does not match the parameter type of conversion method '{1}'." + + + + + InvalidOperationException with message like "Conversion is not supported for arithmetic types without operator overloading." + + + + + ArgumentException with message like "Argument must be array" + + + + + ArgumentException with message like "Argument must be boolean" + + + + + ArgumentException with message like "The user-defined equality method '{0}' must return a boolean value." + + + + + ArgumentException with message like "Argument must be either a FieldInfo or PropertyInfo" + + + + + ArgumentException with message like "Argument must be either a FieldInfo, PropertyInfo or MethodInfo" + + + + + ArgumentException with message like "Argument must be an instance member" + + + + + ArgumentException with message like "Argument must be of an integer type" + + + + + ArgumentException with message like "Argument for array index must be of type Int32" + + + + + ArgumentException with message like "Argument must be single dimensional array type" + + + + + ArgumentException with message like "Argument types do not match" + + + + + InvalidOperationException with message like "Cannot auto initialize elements of value type through property '{0}', use assignment instead" + + + + + InvalidOperationException with message like "Cannot auto initialize members of value type through property '{0}', use assignment instead" + + + + + ArgumentException with message like "The type used in TypeAs Expression must be of reference or nullable type, {0} is neither" + + + + + InvalidOperationException with message like "Coalesce used with type that cannot be null" + + + + + InvalidOperationException with message like "An expression of type '{0}' cannot be used to initialize an array of type '{1}'" + + + + + ArgumentException with message like "Expression of type '{0}' cannot be used for constructor parameter of type '{1}'" + + + + + ArgumentException with message like " Argument type '{0}' does not match the corresponding member type '{1}'" + + + + + ArgumentException with message like " The member '{0}' is not declared on type '{1}' being created" + + + + + ArgumentException with message like "Expression of type '{0}' cannot be used for parameter of type '{1}' of method '{2}'" + + + + + ArgumentException with message like "Expression of type '{0}' cannot be used for parameter of type '{1}'" + + + + + ArgumentException with message like "Expression of type '{0}' cannot be used for return type '{1}'" + + + + + ArgumentException with message like "Expression of type '{0}' cannot be used for assignment to type '{1}'" + + + + + ArgumentException with message like "Expression of type '{0}' cannot be used for label of type '{1}'" + + + + + ArgumentException with message like "Expression of type '{0}' cannot be invoked" + + + + + ArgumentException with message like "Field '{0}' is not defined for type '{1}'" + + + + + ArgumentException with message like "Instance field '{0}' is not defined for type '{1}'" + + + + + ArgumentException with message like "Field '{0}.{1}' is not defined for type '{2}'" + + + + + ArgumentException with message like "Incorrect number of indexes" + + + + + InvalidOperationException with message like "Incorrect number of arguments supplied for lambda invocation" + + + + + ArgumentException with message like "Incorrect number of parameters supplied for lambda declaration" + + + + + ArgumentException with message like "Incorrect number of arguments supplied for call to method '{0}'" + + + + + ArgumentException with message like "Incorrect number of arguments for constructor" + + + + + ArgumentException with message like " Incorrect number of members for constructor" + + + + + ArgumentException with message like "Incorrect number of arguments for the given members " + + + + + ArgumentException with message like "Lambda type parameter must be derived from System.Delegate" + + + + + ArgumentException with message like "Member '{0}' not field or property" + + + + + ArgumentException with message like "Method {0} contains generic parameters" + + + + + ArgumentException with message like "Method {0} is a generic method definition" + + + + + ArgumentException with message like "The method '{0}.{1}' is not a property accessor" + + + + + ArgumentException with message like "The property '{0}' has no 'get' accessor" + + + + + ArgumentException with message like "The property '{0}' has no 'set' accessor" + + + + + ArgumentException with message like "The property '{0}' has no 'get' or 'set' accessors" + + + + + ArgumentException with message like "'{0}' is not a member of type '{1}'" + + + + + NotImplementedException with message like "The operator '{0}' is not implemented for type '{1}'" + + + + + ArgumentException with message like "ParameterExpression of type '{0}' cannot be used for delegate parameter of type '{1}'" + + + + + ArgumentException with message like "Property '{0}' is not defined for type '{1}'" + + + + + ArgumentException with message like "Instance property '{0}' is not defined for type '{1}'" + + + + + ArgumentException with message like "Instance property '{0}' that takes no argument is not defined for type '{1}'" + + + + + ArgumentException with message like "Instance property '{0}{1}' is not defined for type '{2}'" + + + + + ArgumentException with message like "Method '{0}' declared on type '{1}' cannot be called with instance of type '{2}'" + + + + + ArgumentException with message like "Type {0} contains generic parameters" + + + + + ArgumentException with message like "Type {0} is a generic type definition" + + + + + ArgumentException with message like "Type '{0}' does not have a default constructor" + + + + + ArgumentException with message like "List initializers must contain at least one initializer" + + + + + ArgumentException with message like "Element initializer method must be named 'Add'" + + + + + ArgumentException with message like "Parameter '{0}' of element initializer method '{1}' must not be a pass by reference parameter" + + + + + ArgumentException with message like "Element initializer method must have at least 1 parameter" + + + + + ArgumentException with message like "Element initializer method must be an instance method" + + + + + ArgumentException with message like "Type '{0}' is not IEnumerable" + + + + + InvalidOperationException with message like "Type parameter is {0}. Expected a delegate." + + + + + InvalidOperationException with message like "Unexpected coalesce operator." + + + + + InvalidOperationException with message like "Cannot cast from type '{0}' to type '{1}" + + + + + ArgumentException with message like "Unhandled binary: {0}" + + + + + ArgumentException with message like "Unhandled binding " + + + + + ArgumentException with message like "Unhandled Binding Type: {0}" + + + + + ArgumentException with message like "Unhandled convert: {0}" + + + + + ArgumentException with message like "Unhandled Expression Type: {0}" + + + + + ArgumentException with message like "Unhandled unary: {0}" + + + + + ArgumentException with message like "Unknown binding type" + + + + + ArgumentException with message like "The user-defined operator method '{1}' for operator '{0}' must have identical parameter and return types." + + + + + ArgumentException with message like "The user-defined operator method '{1}' for operator '{0}' must return the same type as its parameter or a derived type." + + + + + ArgumentException with message like "The user-defined operator method '{1}' for operator '{0}' must have associated boolean True and False operators." + + + + + InvalidOperationException with message like "No method '{0}' exists on type '{1}'." + + + + + InvalidOperationException with message like "No method '{0}' on type '{1}' is compatible with the supplied arguments." + + + + + InvalidOperationException with message like "No generic method '{0}' on type '{1}' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic. " + + + + + InvalidOperationException with message like "More than one method '{0}' on type '{1}' is compatible with the supplied arguments." + + + + + InvalidOperationException with message like "More than one property '{0}' on type '{1}' is compatible with the supplied arguments." + + + + + ArgumentException with message like "An incorrect number of type args were specified for the declaration of a Func type." + + + + + ArgumentException with message like "An incorrect number of type args were specified for the declaration of an Action type." + + + + + ArgumentException with message like "Argument type cannot be System.Void." + + + + + System.Reflection.AmbiguousMatchException with message like "More than one key matching '{0}' was found in the ExpandoObject." + + + + + ArgumentException with message like "An element with the same key '{0}' already exists in the ExpandoObject." + + + + + System.Collections.Generic.KeyNotFoundException with message like "The specified key '{0}' does not exist in the ExpandoObject." + + + + + InvalidOperationException with message like "No or Invalid rule produced" + + + + + ArgumentException with message like "First argument of delegate must be CallSite" + + + + + InvalidOperationException with message like "Bind cannot return null." + + + + + ArgumentException with message like "Invalid operation: '{0}'" + + + + + ArgumentOutOfRangeException with message like "{0} must be greater than or equal to {1}" + + + + + InvalidOperationException with message like "Queue empty." + + + + + InvalidOperationException with message like "Cannot redefine label '{0}' in an inner block." + + + + + InvalidOperationException with message like "Cannot jump to undefined label '{0}'." + + + + + InvalidOperationException with message like "Control cannot leave a finally block." + + + + + InvalidOperationException with message like "Control cannot leave a filter test." + + + + + InvalidOperationException with message like "Cannot jump to ambiguous label '{0}'." + + + + + InvalidOperationException with message like "Control cannot enter a try block." + + + + + InvalidOperationException with message like "Control cannot enter an expression--only statements can be jumped into." + + + + + InvalidOperationException with message like "Cannot jump to non-local label '{0}' with a value. Only jumps to labels defined in outer blocks can pass values." + + + + + InvalidOperationException with message like "Extension should have been reduced." + + + + + InvalidOperationException with message like "CompileToMethod cannot compile constant '{0}' because it is a non-trivial value, such as a live object. Instead, create an expression tree that can construct this value." + + + + + NotSupportedException with message like "Dynamic expressions are not supported by CompileToMethod. Instead, create an expression tree that uses System.Runtime.CompilerServices.CallSite." + + + + + InvalidOperationException with message like "Invalid lvalue for assignment: {0}." + + + + + InvalidOperationException with message like "Invalid member type: {0}." + + + + + InvalidOperationException with message like "unknown lift type: '{0}'." + + + + + ArgumentException with message like "Invalid output directory." + + + + + ArgumentException with message like "Invalid assembly name or file extension." + + + + + NotSupportedException with message like "Collection is read-only." + + + + + ArgumentException with message like "Cannot create instance of {0} because it contains generic parameters" + + + + + InvalidOperationException with message like "variable '{0}' of type '{1}' referenced from scope '{2}', but it is not defined" + + + + + InvalidOperationException with message like "Cannot close over byref parameter '{0}' referenced in lambda '{1}'" + + + + + InvalidOperationException with message like "Unexpected VarArgs call to method '{0}'" + + + + + InvalidOperationException with message like "Rethrow statement is valid only inside a Catch block." + + + + + InvalidOperationException with message like "Try expression is not allowed inside a filter body." + + + + + InvalidOperationException with message like "When called from '{0}', rewriting a node of type '{1}' must return a non-null value of the same type. Alternatively, override '{2}' and change it to not visit children of this type." + + + + + InvalidOperationException with message like "Rewriting child expression from type '{0}' to type '{1}' is not allowed, because it would change the meaning of the operation. If this is intentional, override '{2}' and change it to allow this rewrite." + + + + + InvalidOperationException with message like "Rewritten expression calls operator method '{0}', but the original node had no operator method. If this is is intentional, override '{1}' and change it to allow this rewrite." + + + + + NotSupportedException with message like "TryExpression is not supported as an argument to method '{0}' because it has an argument with by-ref type. Construct the tree so the TryExpression is not nested inside of this expression." + + + + + NotSupportedException with message like "TryExpression is not supported as a child expression when accessing a member on type '{0}' because it is a value type. Construct the tree so the TryExpression is not nested inside of this expression." + + + + + InvalidOperationException with message like "Collection was modified; enumeration operation may not execute." + + + + + InvalidOperationException with message like "Enumeration has either not started or has already finished." + + + + + InvalidOperationException with message like "Dynamic operations can only be performed in homogenous AppDomain." + + + + + ArgumentException with message like "Test value of type '{0}' cannot be used for the comparison method parameter of type '{1}'" + + + + + ArgumentException with message like "Switch value of type '{0}' cannot be used for the comparison method parameter of type '{1}'" + + + + + InvalidOperationException with message like "An IDynamicMetaObjectProvider {0} created an invalid DynamicMetaObject instance." + + + + + NotSupportedException with message like "DebugInfoGenerator created by CreatePdbGenerator can only be used with LambdaExpression.CompileToMethod." + + + + + Encapsulates a method that has five parameters and returns a value of the type specified by the TResult parameter. + + The type of the first parameter of the method that this delegate encapsulates. + The type of the second parameter of the method that this delegate encapsulates. + The type of the third parameter of the method that this delegate encapsulates. + The type of the fourth parameter of the method that this delegate encapsulates. + The type of the fifth parameter of the method that this delegate encapsulates. + The type of the return value of the method that this delegate encapsulates. + The first parameter of the method that this delegate encapsulates. + The second parameter of the method that this delegate encapsulates. + The third parameter of the method that this delegate encapsulates. + The fourth parameter of the method that this delegate encapsulates. + The fifth parameter of the method that this delegate encapsulates. + The return value of the method that this delegate encapsulates. + + + + Encapsulates a method that has six parameters and returns a value of the type specified by the TResult parameter. + + The type of the first parameter of the method that this delegate encapsulates. + The type of the second parameter of the method that this delegate encapsulates. + The type of the third parameter of the method that this delegate encapsulates. + The type of the fourth parameter of the method that this delegate encapsulates. + The type of the fifth parameter of the method that this delegate encapsulates. + The type of the sixth parameter of the method that this delegate encapsulates. + The type of the return value of the method that this delegate encapsulates. + The first parameter of the method that this delegate encapsulates. + The second parameter of the method that this delegate encapsulates. + The third parameter of the method that this delegate encapsulates. + The fourth parameter of the method that this delegate encapsulates. + The fifth parameter of the method that this delegate encapsulates. + The sixth parameter of the method that this delegate encapsulates. + The return value of the method that this delegate encapsulates. + + + + Encapsulates a method that has seven parameters and returns a value of the type specified by the TResult parameter. + + The type of the first parameter of the method that this delegate encapsulates. + The type of the second parameter of the method that this delegate encapsulates. + The type of the third parameter of the method that this delegate encapsulates. + The type of the fourth parameter of the method that this delegate encapsulates. + The type of the fifth parameter of the method that this delegate encapsulates. + The type of the sixth parameter of the method that this delegate encapsulates. + The type of the seventh parameter of the method that this delegate encapsulates. + The type of the return value of the method that this delegate encapsulates. + The first parameter of the method that this delegate encapsulates. + The second parameter of the method that this delegate encapsulates. + The third parameter of the method that this delegate encapsulates. + The fourth parameter of the method that this delegate encapsulates. + The fifth parameter of the method that this delegate encapsulates. + The sixth parameter of the method that this delegate encapsulates. + The seventh parameter of the method that this delegate encapsulates. + The return value of the method that this delegate encapsulates. + + + + Encapsulates a method that has eight parameters and returns a value of the type specified by the TResult parameter. + + The type of the first parameter of the method that this delegate encapsulates. + The type of the second parameter of the method that this delegate encapsulates. + The type of the third parameter of the method that this delegate encapsulates. + The type of the fourth parameter of the method that this delegate encapsulates. + The type of the fifth parameter of the method that this delegate encapsulates. + The type of the sixth parameter of the method that this delegate encapsulates. + The type of the seventh parameter of the method that this delegate encapsulates. + The type of the eighth parameter of the method that this delegate encapsulates. + The type of the return value of the method that this delegate encapsulates. + The first parameter of the method that this delegate encapsulates. + The second parameter of the method that this delegate encapsulates. + The third parameter of the method that this delegate encapsulates. + The fourth parameter of the method that this delegate encapsulates. + The fifth parameter of the method that this delegate encapsulates. + The sixth parameter of the method that this delegate encapsulates. + The seventh parameter of the method that this delegate encapsulates. + The eighth parameter of the method that this delegate encapsulates. + The return value of the method that this delegate encapsulates. + + + + Encapsulates a method that has nine parameters and returns a value of the type specified by the TResult parameter. + + The type of the first parameter of the method that this delegate encapsulates. + The type of the second parameter of the method that this delegate encapsulates. + The type of the third parameter of the method that this delegate encapsulates. + The type of the fourth parameter of the method that this delegate encapsulates. + The type of the fifth parameter of the method that this delegate encapsulates. + The type of the sixth parameter of the method that this delegate encapsulates. + The type of the seventh parameter of the method that this delegate encapsulates. + The type of the eighth parameter of the method that this delegate encapsulates. + The type of the ninth parameter of the method that this delegate encapsulates. + The type of the return value of the method that this delegate encapsulates. + The first parameter of the method that this delegate encapsulates. + The second parameter of the method that this delegate encapsulates. + The third parameter of the method that this delegate encapsulates. + The fourth parameter of the method that this delegate encapsulates. + The fifth parameter of the method that this delegate encapsulates. + The sixth parameter of the method that this delegate encapsulates. + The seventh parameter of the method that this delegate encapsulates. + The eighth parameter of the method that this delegate encapsulates. + The ninth parameter of the method that this delegate encapsulates. + The return value of the method that this delegate encapsulates. + + + + Encapsulates a method that has ten parameters and returns a value of the type specified by the TResult parameter. + + The type of the first parameter of the method that this delegate encapsulates. + The type of the second parameter of the method that this delegate encapsulates. + The type of the third parameter of the method that this delegate encapsulates. + The type of the fourth parameter of the method that this delegate encapsulates. + The type of the fifth parameter of the method that this delegate encapsulates. + The type of the sixth parameter of the method that this delegate encapsulates. + The type of the seventh parameter of the method that this delegate encapsulates. + The type of the eighth parameter of the method that this delegate encapsulates. + The type of the ninth parameter of the method that this delegate encapsulates. + The type of the tenth parameter of the method that this delegate encapsulates. + The type of the return value of the method that this delegate encapsulates. + The first parameter of the method that this delegate encapsulates. + The second parameter of the method that this delegate encapsulates. + The third parameter of the method that this delegate encapsulates. + The fourth parameter of the method that this delegate encapsulates. + The fifth parameter of the method that this delegate encapsulates. + The sixth parameter of the method that this delegate encapsulates. + The seventh parameter of the method that this delegate encapsulates. + The eighth parameter of the method that this delegate encapsulates. + The ninth parameter of the method that this delegate encapsulates. + The tenth parameter of the method that this delegate encapsulates. + The return value of the method that this delegate encapsulates. + + + + Encapsulates a method that has eleven parameters and returns a value of the type specified by the TResult parameter. + + The type of the first parameter of the method that this delegate encapsulates. + The type of the second parameter of the method that this delegate encapsulates. + The type of the third parameter of the method that this delegate encapsulates. + The type of the fourth parameter of the method that this delegate encapsulates. + The type of the fifth parameter of the method that this delegate encapsulates. + The type of the sixth parameter of the method that this delegate encapsulates. + The type of the seventh parameter of the method that this delegate encapsulates. + The type of the eighth parameter of the method that this delegate encapsulates. + The type of the ninth parameter of the method that this delegate encapsulates. + The type of the tenth parameter of the method that this delegate encapsulates. + The type of the eleventh parameter of the method that this delegate encapsulates. + The type of the return value of the method that this delegate encapsulates. + The first parameter of the method that this delegate encapsulates. + The second parameter of the method that this delegate encapsulates. + The third parameter of the method that this delegate encapsulates. + The fourth parameter of the method that this delegate encapsulates. + The fifth parameter of the method that this delegate encapsulates. + The sixth parameter of the method that this delegate encapsulates. + The seventh parameter of the method that this delegate encapsulates. + The eighth parameter of the method that this delegate encapsulates. + The ninth parameter of the method that this delegate encapsulates. + The tenth parameter of the method that this delegate encapsulates. + The eleventh parameter of the method that this delegate encapsulates. + The return value of the method that this delegate encapsulates. + + + + Encapsulates a method that has twelve parameters and returns a value of the type specified by the TResult parameter. + + The type of the first parameter of the method that this delegate encapsulates. + The type of the second parameter of the method that this delegate encapsulates. + The type of the third parameter of the method that this delegate encapsulates. + The type of the fourth parameter of the method that this delegate encapsulates. + The type of the fifth parameter of the method that this delegate encapsulates. + The type of the sixth parameter of the method that this delegate encapsulates. + The type of the seventh parameter of the method that this delegate encapsulates. + The type of the eighth parameter of the method that this delegate encapsulates. + The type of the ninth parameter of the method that this delegate encapsulates. + The type of the tenth parameter of the method that this delegate encapsulates. + The type of the eleventh parameter of the method that this delegate encapsulates. + The type of the twelfth parameter of the method that this delegate encapsulates. + The type of the return value of the method that this delegate encapsulates. + The first parameter of the method that this delegate encapsulates. + The second parameter of the method that this delegate encapsulates. + The third parameter of the method that this delegate encapsulates. + The fourth parameter of the method that this delegate encapsulates. + The fifth parameter of the method that this delegate encapsulates. + The sixth parameter of the method that this delegate encapsulates. + The seventh parameter of the method that this delegate encapsulates. + The eighth parameter of the method that this delegate encapsulates. + The ninth parameter of the method that this delegate encapsulates. + The tenth parameter of the method that this delegate encapsulates. + The eleventh parameter of the method that this delegate encapsulates. + The twelfth parameter of the method that this delegate encapsulates. + The return value of the method that this delegate encapsulates. + + + + Encapsulates a method that has thirteen parameters and returns a value of the type specified by the TResult parameter. + + The type of the first parameter of the method that this delegate encapsulates. + The type of the second parameter of the method that this delegate encapsulates. + The type of the third parameter of the method that this delegate encapsulates. + The type of the fourth parameter of the method that this delegate encapsulates. + The type of the fifth parameter of the method that this delegate encapsulates. + The type of the sixth parameter of the method that this delegate encapsulates. + The type of the seventh parameter of the method that this delegate encapsulates. + The type of the eighth parameter of the method that this delegate encapsulates. + The type of the ninth parameter of the method that this delegate encapsulates. + The type of the tenth parameter of the method that this delegate encapsulates. + The type of the eleventh parameter of the method that this delegate encapsulates. + The type of the twelfth parameter of the method that this delegate encapsulates. + The type of the thirteenth parameter of the method that this delegate encapsulates. + The type of the return value of the method that this delegate encapsulates. + The first parameter of the method that this delegate encapsulates. + The second parameter of the method that this delegate encapsulates. + The third parameter of the method that this delegate encapsulates. + The fourth parameter of the method that this delegate encapsulates. + The fifth parameter of the method that this delegate encapsulates. + The sixth parameter of the method that this delegate encapsulates. + The seventh parameter of the method that this delegate encapsulates. + The eighth parameter of the method that this delegate encapsulates. + The ninth parameter of the method that this delegate encapsulates. + The tenth parameter of the method that this delegate encapsulates. + The eleventh parameter of the method that this delegate encapsulates. + The twelfth parameter of the method that this delegate encapsulates. + The thirteenth parameter of the method that this delegate encapsulates. + The return value of the method that this delegate encapsulates. + + + + Encapsulates a method that has fourteen parameters and returns a value of the type specified by the TResult parameter. + + The type of the first parameter of the method that this delegate encapsulates. + The type of the second parameter of the method that this delegate encapsulates. + The type of the third parameter of the method that this delegate encapsulates. + The type of the fourth parameter of the method that this delegate encapsulates. + The type of the fifth parameter of the method that this delegate encapsulates. + The type of the sixth parameter of the method that this delegate encapsulates. + The type of the seventh parameter of the method that this delegate encapsulates. + The type of the eighth parameter of the method that this delegate encapsulates. + The type of the ninth parameter of the method that this delegate encapsulates. + The type of the tenth parameter of the method that this delegate encapsulates. + The type of the eleventh parameter of the method that this delegate encapsulates. + The type of the twelfth parameter of the method that this delegate encapsulates. + The type of the thirteenth parameter of the method that this delegate encapsulates. + The type of the fourteenth parameter of the method that this delegate encapsulates. + The type of the return value of the method that this delegate encapsulates. + The first parameter of the method that this delegate encapsulates. + The second parameter of the method that this delegate encapsulates. + The third parameter of the method that this delegate encapsulates. + The fourth parameter of the method that this delegate encapsulates. + The fifth parameter of the method that this delegate encapsulates. + The sixth parameter of the method that this delegate encapsulates. + The seventh parameter of the method that this delegate encapsulates. + The eighth parameter of the method that this delegate encapsulates. + The ninth parameter of the method that this delegate encapsulates. + The tenth parameter of the method that this delegate encapsulates. + The eleventh parameter of the method that this delegate encapsulates. + The twelfth parameter of the method that this delegate encapsulates. + The thirteenth parameter of the method that this delegate encapsulates. + The fourteenth parameter of the method that this delegate encapsulates. + The return value of the method that this delegate encapsulates. + + + + Encapsulates a method that has fifteen parameters and returns a value of the type specified by the TResult parameter. + + The type of the first parameter of the method that this delegate encapsulates. + The type of the second parameter of the method that this delegate encapsulates. + The type of the third parameter of the method that this delegate encapsulates. + The type of the fourth parameter of the method that this delegate encapsulates. + The type of the fifth parameter of the method that this delegate encapsulates. + The type of the sixth parameter of the method that this delegate encapsulates. + The type of the seventh parameter of the method that this delegate encapsulates. + The type of the eighth parameter of the method that this delegate encapsulates. + The type of the ninth parameter of the method that this delegate encapsulates. + The type of the tenth parameter of the method that this delegate encapsulates. + The type of the eleventh parameter of the method that this delegate encapsulates. + The type of the twelfth parameter of the method that this delegate encapsulates. + The type of the thirteenth parameter of the method that this delegate encapsulates. + The type of the fourteenth parameter of the method that this delegate encapsulates. + The type of the fifteenth parameter of the method that this delegate encapsulates. + The type of the return value of the method that this delegate encapsulates. + The first parameter of the method that this delegate encapsulates. + The second parameter of the method that this delegate encapsulates. + The third parameter of the method that this delegate encapsulates. + The fourth parameter of the method that this delegate encapsulates. + The fifth parameter of the method that this delegate encapsulates. + The sixth parameter of the method that this delegate encapsulates. + The seventh parameter of the method that this delegate encapsulates. + The eighth parameter of the method that this delegate encapsulates. + The ninth parameter of the method that this delegate encapsulates. + The tenth parameter of the method that this delegate encapsulates. + The eleventh parameter of the method that this delegate encapsulates. + The twelfth parameter of the method that this delegate encapsulates. + The thirteenth parameter of the method that this delegate encapsulates. + The fourteenth parameter of the method that this delegate encapsulates. + The fifteenth parameter of the method that this delegate encapsulates. + The return value of the method that this delegate encapsulates. + + + + Encapsulates a method that has sixteen parameters and returns a value of the type specified by the TResult parameter. + + The type of the first parameter of the method that this delegate encapsulates. + The type of the second parameter of the method that this delegate encapsulates. + The type of the third parameter of the method that this delegate encapsulates. + The type of the fourth parameter of the method that this delegate encapsulates. + The type of the fifth parameter of the method that this delegate encapsulates. + The type of the sixth parameter of the method that this delegate encapsulates. + The type of the seventh parameter of the method that this delegate encapsulates. + The type of the eighth parameter of the method that this delegate encapsulates. + The type of the ninth parameter of the method that this delegate encapsulates. + The type of the tenth parameter of the method that this delegate encapsulates. + The type of the eleventh parameter of the method that this delegate encapsulates. + The type of the twelfth parameter of the method that this delegate encapsulates. + The type of the thirteenth parameter of the method that this delegate encapsulates. + The type of the fourteenth parameter of the method that this delegate encapsulates. + The type of the fifteenth parameter of the method that this delegate encapsulates. + The type of the sixteenth parameter of the method that this delegate encapsulates. + The type of the return value of the method that this delegate encapsulates. + The first parameter of the method that this delegate encapsulates. + The second parameter of the method that this delegate encapsulates. + The third parameter of the method that this delegate encapsulates. + The fourth parameter of the method that this delegate encapsulates. + The fifth parameter of the method that this delegate encapsulates. + The sixth parameter of the method that this delegate encapsulates. + The seventh parameter of the method that this delegate encapsulates. + The eighth parameter of the method that this delegate encapsulates. + The ninth parameter of the method that this delegate encapsulates. + The tenth parameter of the method that this delegate encapsulates. + The eleventh parameter of the method that this delegate encapsulates. + The twelfth parameter of the method that this delegate encapsulates. + The thirteenth parameter of the method that this delegate encapsulates. + The fourteenth parameter of the method that this delegate encapsulates. + The fifteenth parameter of the method that this delegate encapsulates. + The sixteenth parameter of the method that this delegate encapsulates. + The return value of the method that this delegate encapsulates. + + + + The builder for read only collection. + + The type of the collection element. + + + + Constructs a ReadOnlyCollectionBuilder. + + + + + Constructs a ReadOnlyCollectionBuilder with a given initial capacity. + The contents are empty but builder will have reserved room for the given + number of elements before any reallocations are required. + + + + + Constructs a ReadOnlyCollectionBuilder, copying contents of the given collection. + + + + + + Returns the index of the first occurrence of a given value in the builder. + + An item to search for. + The index of the first occurrence of an item. + + + + Inserts an item to the at the specified index. + + The zero-based index at which item should be inserted. + The object to insert into the . + + + + Removes the item at the specified index. + + The zero-based index of the item to remove. + + + + Adds an item to the . + + The object to add to the . + + + + Removes all items from the . + + + + + Determines whether the contains a specific value + + the object to locate in the . + true if item is found in the ; otherwise, false. + + + + Copies the elements of the to an , + starting at particular index. + + The one-dimensional that is the destination of the elements copied from . + The zero-based index in array at which copying begins. + + + + Removes the first occurrence of a specific object from the . + + The object to remove from the . + true if item was successfully removed from the ; + otherwise, false. This method also returns false if item is not found in the original . + + + + + Returns an enumerator that iterates through the collection. + + A that can be used to iterate through the collection. + + + + Reverses the order of the elements in the entire . + + + + + Reverses the order of the elements in the specified range. + + The zero-based starting index of the range to reverse. + The number of elements in the range to reverse. + + + + Copies the elements of the to a new array. + + An array containing copies of the elements of the . + + + + Creates a containing all of the the elements of the , + avoiding copying the elements to the new array if possible. Resets the after the + has been created. + + A new instance of . + + + + Gets and sets the capacity of this ReadOnlyCollectionBuilder + + + + + Returns number of elements in the ReadOnlyCollectionBuilder. + + + + + Gets or sets the element at the specified index. + + The zero-based index of the element to get or set. + The element at the specified index. + + + + Creates instnace of TrueReadOnlyCollection, wrapping passed in array. + !!! DOES NOT COPY THE ARRAY !!! + + + + + Creates a closed delegate for the given (dynamic)method. + + + + + Returns true if the method's parameter types are reference assignable from + the argument types, otherwise false. + + An example that can make the method return false is that + typeof(double).GetMethod("op_Equality", ..., new[] { typeof(double), typeof(int) }) + returns a method with two double parameters, which doesn't match the provided + argument types. + + + + + diff --git a/Reference/DLR/Net35/Microsoft.Scripting.dll b/Reference/DLR/Net35/Microsoft.Scripting.dll new file mode 100644 index 000000000..a57640f2e Binary files /dev/null and b/Reference/DLR/Net35/Microsoft.Scripting.dll differ diff --git a/Reference/DLR/Net35/Microsoft.Scripting.xml b/Reference/DLR/Net35/Microsoft.Scripting.xml new file mode 100644 index 000000000..e6c59f76e --- /dev/null +++ b/Reference/DLR/Net35/Microsoft.Scripting.xml @@ -0,0 +1,3812 @@ + + + + Microsoft.Scripting + + + + + Provides documentation against live objects for use in a REPL window. + + + + + Gets the available members defined on the provided object. + + + + + Gets the overloads available for the provided object if it is invokable. + + + + + Gets the available members on the provided remote object. + + + + + Gets the overloads available for the provided remote object if it is invokable. + + + + + Provides documentation about a member in a live object. + + + + + The name of the member + + + + + The kind of the member if it's known. + + + + + Specifies the type of member. + + + + + Provides documentation for a single overload of an invokable object. + + + + + The name of the invokable object. + + + + + The documentation for the overload or null if no documentation is available. + + + + + The parameters for the invokable object. + + + + + Information about the return value. + + + + + Provides documentation for a single parameter. + + + + + The name of the parameter + + + + + The type name of the parameter or null if no type information is available. + + + + + Provides addition information about the parameter such as if it's a parameter array. + + + + + Gets the documentation string for this parameter or null if no documentation is available. + + + + + Indications extra information about a parameter such as if it's a parameter array. + + + + + This structure represents an immutable integer interval that describes a range of values, from Start to End. + + It is closed on the left and open on the right: [Start .. End). + + + + + Wraps a an IDictionary[object, object] and exposes it as an IDynamicMetaObjectProvider so that + users can access string attributes using member accesses. + + + + + Provides language specific documentation for live objects. + + + + + Helper for storing information about stack frames. + + + + + Exposes a IDictionary[string, object] as a dynamic object. Gets/sets/deletes turn + into accesses on the underlying dictionary. + + + + + Class that represents compiler options. + Note that this class is likely to change when hosting API becomes part of .Net + + + + + This overload will be called when a SourceUnit is not available. This can happen if the code is being executed remotely, + since SourceUnit cannot be marshaled across AppDomains. + + + + + Hosting API counterpart for . + + + + + Executes code in a default scope. + + + + + Execute code within a given scope and returns the result. + + + + + Executes code in in a default scope and converts to a given type. + + + + + Execute code within a given scope and converts result to a given type. + + + + + Executes the code in an empty scope. + Returns an ObjectHandle wrapping the resulting value of running the code. + + + + + Executes the code in the specified scope. + Returns an ObjectHandle wrapping the resulting value of running the code. + + + + + Executes the code in an empty scope. + Returns an ObjectHandle wrapping the resulting value of running the code. + + If an exception is thrown the exception is caught and an ObjectHandle to + the exception is provided. + + + Use this API to handle non-serializable exceptions (exceptions might not be serializable due to security restrictions) + or if an exception serialization loses information. + + + + + Executes the expression in the specified scope and return a result. + Returns an ObjectHandle wrapping the resulting value of running the code. + + If an exception is thrown the exception is caught and an ObjectHandle to + the exception is provided. + + + Use this API to handle non-serializable exceptions (exceptions might not be serializable due to security restrictions) + or if an exception serialization loses information. + + + + + Engine that compiled this code. + + + + + Default scope for this code. + + + + + The host can use this class to track for errors reported during script parsing and compilation. + Hosting API counterpart for . + + + + + Bridges ErrorSink and ErrorListener. + Errors reported by language compilers to ErrorSink are forwarded to the ErrorListener provided by the host. + + + This proxy is created in the scenario when the compiler is processing a single SourceUnit. + Therefore it could maintain one to one mapping from SourceUnit to ScriptSource. + In a case, which shouldn't happen, that the compiler reports an error in a different SourceUnit we just create + a new instance of the ScriptSource each time. + + TODO: Consider compilation of multiple source units and creating a hashtable mapping SourceUnits to ScriptSources + within the context of compilation unit. + + + + + Bridges ErrorListener and ErrorSink. It provides the reverse functionality as ErrorSinkProxyListener + + + + + Stores information needed to setup a language + + + + + Creates a new LanguageSetup + + assembly qualified type name of the language + provider + + + + Creates a new LanguageSetup with the provided options + TODO: remove this overload? + + + + + Creates a new LanguageSetup with the provided options + + + + + Gets an option as a strongly typed value. + + + + + The assembly qualified type name of the language provider + + + + + Display name of the language. If empty, it will be set to the first + name in the Names list. + + + + + Case-insensitive language names. + + + + + Case-insensitive file extension, optionally starts with a dot. + + + + + Option names are case-sensitive. + + + + + ObjectOperations provide a large catalogue of object operations such as member access, conversions, + indexing, and things like addition. There are several introspection and tool support services available + for more advanced hosts. + + You get ObjectOperation instances from ScriptEngine, and they are bound to their engines for the semantics + of the operations. There is a default instance of ObjectOperations you can share across all uses of the + engine. However, very advanced hosts can create new instances. + + + + + Returns true if the object can be called, false if it cannot. + + Even if an object is callable Call may still fail if an incorrect number of arguments or type of arguments are provided. + + + + + Invokes the provided object with the given parameters and returns the result. + + The prefered way of calling objects is to convert the object to a strongly typed delegate + using the ConvertTo methods and then invoking that delegate. + + + + + Invokes a member on the provided object with the given parameters and returns the result. + + + + + Creates a new instance from the provided object using the given parameters, and returns the result. + + + + + Gets the member name from the object obj. Throws an exception if the member does not exist or is write-only. + + + + + Gets the member name from the object obj and converts it to the type T. Throws an exception if the + member does not exist, is write-only, or cannot be converted. + + + + + Gets the member name from the object obj. Returns true if the member is successfully retrieved and + stores the value in the value out param. + + + + + Returns true if the object has a member named name, false if the member does not exist. + + + + + Removes the member name from the object obj. + + + + + Sets the member name on object obj to value. + + + + + Sets the member name on object obj to value. This overload can be used to avoid + boxing and casting of strongly typed members. + + + + + Gets the member name from the object obj. Throws an exception if the member does not exist or is write-only. + + + + + Gets the member name from the object obj and converts it to the type T. Throws an exception if the + member does not exist, is write-only, or cannot be converted. + + + + + Gets the member name from the object obj. Returns true if the member is successfully retrieved and + stores the value in the value out param. + + + + + Returns true if the object has a member named name, false if the member does not exist. + + + + + Removes the member name from the object obj. + + + + + Sets the member name on object obj to value. + + + + + Sets the member name on object obj to value. This overload can be used to avoid + boxing and casting of strongly typed members. + + + + + Converts the object obj to the type T. The conversion will be explicit or implicit depending on + what the langauge prefers. + + + + + Converts the object obj to the type type. The conversion will be explicit or implicit depending on + what the langauge prefers. + + + + + Converts the object obj to the type T. Returns true if the value can be converted, false if it cannot. + + The conversion will be explicit or implicit depending on what the langauge prefers. + + + + + Converts the object obj to the type type. Returns true if the value can be converted, false if it cannot. + + The conversion will be explicit or implicit depending on what the langauge prefers. + + + + + Converts the object obj to the type T including explicit conversions which may lose information. + + + + + Converts the object obj to the type type including explicit conversions which may lose information. + + + + + Converts the object obj to the type T including explicit conversions which may lose information. + + Returns true if the value can be converted, false if it cannot. + + + + + Converts the object obj to the type type including explicit conversions which may lose information. + + Returns true if the value can be converted, false if it cannot. + + + + + Converts the object obj to the type T including implicit conversions. + + + + + Converts the object obj to the type type including implicit conversions. + + + + + Converts the object obj to the type T including implicit conversions. + + Returns true if the value can be converted, false if it cannot. + + + + + Converts the object obj to the type type including implicit conversions. + + Returns true if the value can be converted, false if it cannot. + + + + + Performs a generic unary operation on the specified target and returns the result. + + + + + Performs a generic unary operation on the strongly typed target and returns the value as the specified type + + + + + Performs the generic binary operation on the specified targets and returns the result. + + + + + Peforms the generic binary operation on the specified strongly typed targets and returns + the strongly typed result. + + + + + Performs addition on the specified targets and returns the result. Throws an exception + if the operation cannot be performed. + + + + + Performs subtraction on the specified targets and returns the result. Throws an exception + if the operation cannot be performed. + + + + + Raises the first object to the power of the second object. Throws an exception + if the operation cannot be performed. + + + + + Multiplies the two objects. Throws an exception + if the operation cannot be performed. + + + + + Divides the first object by the second object. Throws an exception + if the operation cannot be performed. + + + + + Performs modulus of the 1st object by the second object. Throws an exception + if the operation cannot be performed. + + + + + Shifts the left object left by the right object. Throws an exception if the + operation cannot be performed. + + + + + Shifts the left object right by the right object. Throws an exception if the + operation cannot be performed. + + + + + Performs a bitwise-and of the two operands. Throws an exception if the operation + cannot be performed. + + + + + Performs a bitwise-or of the two operands. Throws an exception if the operation + cannot be performed. + + + + + Performs a exclusive-or of the two operands. Throws an exception if the operation + cannot be performed. + + + + + Compares the two objects and returns true if the left object is less than the right object. + Throws an exception if hte comparison cannot be performed. + + + + + Compares the two objects and returns true if the left object is greater than the right object. + Throws an exception if hte comparison cannot be performed. + + + + + Compares the two objects and returns true if the left object is less than or equal to the right object. + Throws an exception if hte comparison cannot be performed. + + + + + Compares the two objects and returns true if the left object is greater than or equal to the right object. + Throws an exception if hte comparison cannot be performed. + + + + + Compares the two objects and returns true if the left object is equal to the right object. + Throws an exception if the comparison cannot be performed. + + + + + Compares the two objects and returns true if the left object is not equal to the right object. + Throws an exception if hte comparison cannot be performed. + + + + + Returns a string which describes the object as it appears in source code + + + + + Returns a string representation of the object in a language specific object display format. + + + + + Returns a list of strings which contain the known members of the object. + + + + + Returns a string providing documentation for the specified object. + + + + + Returns a list of signatures applicable for calling the specified object in a form displayable to the user. + + + + + Returns true if the remote object is callable. + + + + + Invokes the specified remote object with the specified remote parameters. + + Though delegates are preferable for calls they may not always be usable for remote objects. + + + + + Invokes the specified remote object with the local parameters which will be serialized + to the remote app domain. + + + + + Creates a new remote instance from the provided remote object using the given parameters, and returns the result. + + + + + Creates a new remote instance from the provided remote object using the given parameters, and returns the result. + + + + + Sets the remote object as a member on the provided remote object. + + + + + Sets the member name on the remote object obj to value. This overload can be used to avoid + boxing and casting of strongly typed members. + + + + + Gets the member name on the remote object. Throws an exception if the member is not defined or + is write-only. + + + + + Gets the member name on the remote object. Throws an exception if the member is not defined or + is write-only. + + + + + Gets the member name on the remote object. Returns false if the member is not defined or + is write-only. + + + + + Tests to see if the member name is defined on the remote object. + + + + + Removes the member from the remote object + + + + + Converts the remote object into the specified type returning a handle to + the new remote object. The conversion will be explicit or implicit depending on + what the langauge prefers. + + + + + Converts the remote object into the specified type returning a handle to + the new remote object. The conversion will be explicit or implicit depending on + what the langauge prefers. + + + + + Converts the remote object into the specified type returning a handle to + the new remote object. Returns true if the value can be converted, + false if it cannot. The conversion will be explicit or implicit depending on + what the langauge prefers. + + + + + Converts the remote object into the specified type returning a handle to + the new remote object. Returns true if the value can be converted, + false if it cannot. The conversion will be explicit or implicit depending on + what the langauge prefers. + + + + + Converts the object obj to the type T including explicit conversions which may lose information. + + + + + Converts the object obj to the type type including explicit conversions which may lose information. + + + + + Converts the object obj to the type T including explicit conversions which may lose information. + + Returns true if the value can be converted, false if it cannot. + + + + + Converts the object obj to the type type including explicit conversions which may lose information. + + Returns true if the value can be converted, false if it cannot. + + + + + Converts the object obj to the type T including implicit conversions. + + + + + Converts the object obj to the type type including implicit conversions. + + + + + Converts the object obj to the type T including implicit conversions. + + Returns true if the value can be converted, false if it cannot. + + + + + Converts the object obj to the type type including implicit conversions. + + Returns true if the value can be converted, false if it cannot. + + + + + Unwraps the remote object and converts it into the specified type before + returning it. + + + + + Performs the specified unary operator on the remote object. + + + + + Performs the specified binary operator on the remote object. + + + + + Adds the two remote objects. Throws an exception if the operation cannot be performed. + + + + + Subtracts the 1st remote object from the second. Throws an exception if the operation cannot be performed. + + + + + Raises the 1st remote object to the power of the 2nd. Throws an exception if the operation cannot be performed. + + + + + Multiplies the two remote objects. Throws an exception if the operation cannot be performed. + + + + + Divides the 1st remote object by the 2nd. Throws an exception if the operation cannot be performed. + + + + + Performs modulus on the 1st remote object by the 2nd. Throws an exception if the operation cannot be performed. + + + + + Shifts the 1st remote object left by the 2nd remote object. Throws an exception if the operation cannot be performed. + + + + + Shifts the 1st remote object right by the 2nd remote object. Throws an exception if the operation cannot be performed. + + + + + Performs bitwise-and on the two remote objects. Throws an exception if the operation cannot be performed. + + + + + Performs bitwise-or on the two remote objects. Throws an exception if the operation cannot be performed. + + + + + Performs exclusive-or on the two remote objects. Throws an exception if the operation cannot be performed. + + + + + Compares the two remote objects and returns true if the 1st is less than the 2nd. Throws an exception if the operation cannot be performed. + + + + + Compares the two remote objects and returns true if the 1st is greater than the 2nd. Throws an exception if the operation cannot be performed. + + + + + Compares the two remote objects and returns true if the 1st is less than or equal to the 2nd. Throws an exception if the operation cannot be performed. + + + + + Compares the two remote objects and returns true if the 1st is greater than or equal to than the 2nd. Throws an exception if the operation cannot be performed. + + + + + Compares the two remote objects and returns true if the 1st is equal to the 2nd. Throws an exception if the operation cannot be performed. + + + + + Compares the two remote objects and returns true if the 1st is not equal to the 2nd. Throws an exception if the operation cannot be performed. + + + + + Returns a string representation of the object in a langauge specific object display format. + + + + + Returns a list of strings which contain the known members of the remote object. + + + + + Returns a string providing documentation for the specified remote object. + + + + + Returns a list of signatures applicable for calling the specified object in a form displayable to the user. + + + + + Helper to unwrap an object - in the future maybe we should validate the current app domain. + + + + + Helper to unwrap multiple objects + + + + + Reads an option whose value is expected to be a collection of non-null strings. + Reaturns a read-only copy of the option's value. + + + + + Dynamically choose between interpreting, simple compilation and compilation + that takes advantage of runtime history. + + + + + The number of iterations before the interpreter starts compiling.s + + + + + Display exception detail (callstack) when exception gets caught + + + + + Whether to gather performance statistics. + + + + + Initial file search paths provided by the host. + + + + + Abstracts system operations that are used by DLR and could potentially be platform specific. + The host can implement its PAL to adapt DLR to the platform it is running on. + For example, the Silverlight host adapts some file operations to work against files on the server. + + + + Invalid path. + + + Invalid path. + + + + Advanced APIs for HAPI providers. These methods should not be used by hosts. + They are provided for other hosting API implementers that would like to leverage existing HAPI and + extend it with language specific functionality, for example. + + + + is a null reference. + is remote. + + + e is a null reference. + is remote. + + + is a null reference. + is remote. + + + is a null reference. + is remote. + + + is a null reference. + is remote. + + + is a null reference. + is remote. + + + is a null reference. + is a null reference. + is a transparent proxy. + + + + Performs a callback in the ScriptEngine's app domain and returns the result. + + + + + Creates a new DocumentationOperations object from the given DocumentationProvider. + + + + + Represents a language in Hosting API. + Hosting API counterpart for . + + + + + Returns a new ObjectOperations object. See the Operations property for why you might want to call this. + + + + + Returns a new ObjectOperations object that inherits any semantics particular to the provided ScriptScope. + + See the Operations property for why you might want to call this. + + + + + Executes an expression. The execution is not bound to any particular scope. + + The engine doesn't support code execution. + is a null reference. + + + + Executes an expression within the specified scope. + + The engine doesn't support code execution. + is a null reference. + is a null reference. + + + + Executes an expression within a new scope and converts result to the given type. + + The engine doesn't support code execution. + is a null reference. + + + + Executes an expression within the specified scope and converts result to the given type. + + The engine doesn't support code execution. + is a null reference. + is a null reference. + + + + Executes content of the specified file in a new scope and returns that scope. + + The engine doesn't support code execution. + is a null reference. + + + + Executes content of the specified file against the given scope. + + The . + The engine doesn't support code execution. + is a null reference. + is a null reference. + + + + Executes the expression in the specified scope and return a result. + Returns an ObjectHandle wrapping the resulting value of running the code. + + + + + Executes the code in an empty scope. + Returns an ObjectHandle wrapping the resulting value of running the code. + + + + + Executes the expression in the specified scope and return a result. + Returns an ObjectHandle wrapping the resulting value of running the code. + + If an exception is thrown the exception is caught and an ObjectHandle to + the exception is provided. + + + Use this API in case the exception is not serializable (for example, due to security restrictions) or its serialization + loses information that you need to access. + + + + + Executes the code in an empty scope. + Returns an ObjectHandle wrapping the resulting value of running the code. + + If an exception is thrown the exception is caught and an ObjectHandle to + the exception is provided. + + + Use this API in case the exception is not serializable (for example, due to security restrictions) or its serialization + loses information that you need to access. + + + + + Creates a new ScriptScope whose storage is an arbitrary object. + + Accesses to the ScriptScope will turn into get, set, and delete members against the object. + + + + + This method returns the ScriptScope in which a ScriptSource of given path was executed. + + The ScriptSource.Path property is the key to finding the ScriptScope. Hosts need + to make sure they create a ScriptSource and set its Path property appropriately. + + GetScope is primarily useful for tools that need to map files to their execution scopes. For example, + an editor and interpreter tool might run a file Foo that imports or requires a file Bar. + + The editor's user might later open the file Bar and want to execute expressions in its context. + The tool would need to find Bar's ScriptScope for setting the appropriate context in its interpreter window. + This method helps with this scenario. + + + + + Return a ScriptSource object from string contents with the current engine as the language binding. + + The default SourceCodeKind is AutoDetect. + + The ScriptSource's Path property defaults to null. + + + + + Return a ScriptSource object from string contents with the current engine as the language binding. + + The ScriptSource's Path property defaults to null. + + + + + Return a ScriptSource object from string contents with the current engine as the language binding. + + The default SourceCodeKind is AutoDetect. + + + + + Return a ScriptSource object from string contents. These are helpers for creating ScriptSources' with the right language binding. + + + + + Return a ScriptSource object from file contents with the current engine as the language binding. + + The path's extension does NOT have to be in ScriptRuntime.GetRegisteredFileExtensions + or map to this language engine with ScriptRuntime.GetEngineByFileExtension. + + The default SourceCodeKind is File. + + The ScriptSource's Path property will be the path argument. + + The encoding defaults to System.Text.Encoding.Default. + + + + + Return a ScriptSource object from file contents with the current engine as the language binding. + + The path's extension does NOT have to be in ScriptRuntime.GetRegisteredFileExtensions + or map to this language engine with ScriptRuntime.GetEngineByFileExtension. + + The default SourceCodeKind is File. + + The ScriptSource's Path property will be the path argument. + + + + + Return a ScriptSource object from file contents with the current engine as the language binding. + + The path's extension does NOT have to be in ScriptRuntime.GetRegisteredFileExtensions + or map to this language engine with ScriptRuntime.GetEngineByFileExtension. + + The ScriptSource's Path property will be the path argument. + + + + + This method returns a ScriptSource object from a System.CodeDom.CodeObject. + This is a factory method for creating a ScriptSources with this language binding. + + The expected CodeDom support is extremely minimal for syntax-independent expression of semantics. + + Languages may do more, but hosts should only expect CodeMemberMethod support, + and only sub nodes consisting of the following: + CodeSnippetStatement + CodeSnippetExpression + CodePrimitiveExpression + CodeMethodInvokeExpression + CodeExpressionStatement (for holding MethodInvoke) + + + + + This method returns a ScriptSource object from a System.CodeDom.CodeObject. + This is a factory method for creating a ScriptSources with this language binding. + + The expected CodeDom support is extremely minimal for syntax-independent expression of semantics. + + Languages may do more, but hosts should only expect CodeMemberMethod support, + and only sub nodes consisting of the following: + CodeSnippetStatement + CodeSnippetExpression + CodePrimitiveExpression + CodeMethodInvokeExpression + CodeExpressionStatement (for holding MethodInvoke) + + + + + This method returns a ScriptSource object from a System.CodeDom.CodeObject. + This is a factory method for creating a ScriptSources with this language binding. + + The expected CodeDom support is extremely minimal for syntax-independent expression of semantics. + + Languages may do more, but hosts should only expect CodeMemberMethod support, + and only sub nodes consisting of the following: + CodeSnippetStatement + CodeSnippetExpression + CodePrimitiveExpression + CodeMethodInvokeExpression + CodeExpressionStatement (for holding MethodInvoke) + + + + + This method returns a ScriptSource object from a System.CodeDom.CodeObject. + This is a factory method for creating a ScriptSources with this language binding. + + The expected CodeDom support is extremely minimal for syntax-independent expression of semantics. + + Languages may do more, but hosts should only expect CodeMemberMethod support, + and only sub nodes consisting of the following: + CodeSnippetStatement + CodeSnippetExpression + CodePrimitiveExpression + CodeMethodInvokeExpression + CodeExpressionStatement (for holding MethodInvoke) + + + + + These methods return ScriptSource objects from stream contents with the current engine as the language binding. + + The default SourceCodeKind is File. + + The encoding defaults to Encoding.Default. + + + + + These methods return ScriptSource objects from stream contents with the current engine as the language binding. + + The default SourceCodeKind is File. + + + + + These methods return ScriptSource objects from stream contents with the current engine as the language binding. + + The encoding defaults to Encoding.Default. + + + + + This method returns a ScriptSource with the content provider supplied with the current engine as the language binding. + + This helper lets you own the content provider so that you can implement a stream over internal host data structures, such as an editor's text representation. + + + + + This method returns a language-specific service. + + It provides a point of extensibility for a language implementation + to offer more functionality than the standard engine members discussed here. + + Commonly available services include: + TokenCategorizer + Provides standardized tokenization of source code + ExceptionOperations + Provides formatting of exception objects. + DocumentationProvidera + Provides documentation for live object. + + + + + Sets the search paths used by the engine for loading files when a script wants + to import or require another file of code. + + The language doesn't allow to set search paths. + + + + Gets the search paths used by the engine for loading files when a script wants + to import or require another file of code. + + + + + Returns a default ObjectOperations for the engine. + + Because an ObjectOperations object caches rules for the types of + objects and operations it processes, using the default ObjectOperations for + many objects could degrade the caching benefits. Eventually the cache for + some operations could degrade to a point where ObjectOperations stops caching and + does a full search for an implementation of the requested operation for the given objects. + + Another reason to create a new ObjectOperations instance is to have it bound + to the specific view of a ScriptScope. Languages may attach per-language + behavior to a ScriptScope which would alter how the operations are performed. + + For simple hosting situations, this is sufficient behavior. + + + + + + + This property returns readon-only LanguageOptions this engine is using. + + + The values are determined during runtime initialization and read-only afterwards. + You can change the settings via a configuration file or explicitly using ScriptRuntimeSetup class. + + + + + This property returns the ScriptRuntime for the context in which this engine executes. + + + + + This property returns the engine's version as a string. The format is language-dependent. + + + + + ScriptHost is collocated with ScriptRuntime in the same app-domain. + The host can implement a derived class to consume some notifications and/or + customize operations like TryGetSourceUnit,ResolveSourceUnit, etc. + + The areguments to the the constructor of the derived class are specified in ScriptRuntimeSetup + instance that enters ScriptRuntime initialization. + + If the host is remote with respect to DLR (i.e. also with respect to ScriptHost) + and needs to access objects living in its app-domain it can pass MarshalByRefObject + as an argument to its ScriptHost subclass constructor. + + + + + The runtime the host is attached to. + + + + + Invoked after the initialization of the associated Runtime is finished. + The host can override this method to perform additional initialization of runtime (like loading assemblies etc.). + + + + + Invoked after a new language is loaded into the Runtime. + The host can override this method to perform additional initialization of language engines. + + + + + Provides hosting to DLR. Forwards DLR requests to the ScriptHost. + + + + + DLR requires any Hosting API provider to implement this class and provide its instance upon Runtime initialization. + DLR calls on it to perform basic host/system dependent operations. + + + + + Abstracts system operations that are used by DLR and could potentially be platform specific. + + + + + Provides host-redirectable IO streams used by DLR languages for default IO. + + + + + Used if the host stores the output as binary data. + + Binary stream to write data to. + Encoding used to convert textual data written to the output by the script. + + + + Used if the host handles both kinds of data (textual and binary) by itself. + + + + + Represents a Dynamic Language Runtime in Hosting API. + Hosting API counterpart for . + + + + + Creates ScriptRuntime in the current app-domain and initialized according to the the specified settings. + Creates an instance of host class specified in the setup and associates it with the created runtime. + Both Runtime and ScriptHost are collocated in the current app-domain. + + + + + Creates a new runtime with languages set up according to the current application configuration + (using System.Configuration). + + + + + Creates ScriptRuntime in the current app-domain and initialized according to the the specified settings. + Creates an instance of host class specified in the setup and associates it with the created runtime. + Both Runtime and ScriptHost are collocated in the specified app-domain. + + + + + + + + + Gets engine for the specified language. + + + + + Looks up the engine for the specified language. If the engine hasn't been created in this Runtime, it is instantiated here. + The method doesn't lock nor send notifications to the host. + + + + + path is empty, contains one or more of the invalid characters defined in GetInvalidPathChars or doesn't have an extension. + + + + path is null + file extension does not map to language engine + language does not have any search paths + file does exist in language's search path + + + + This method walks the assembly's namespaces and name bindings to ScriptRuntime.Globals + to represent the types available in the assembly. Each top-level namespace name gets + bound in Globals to a dynamic object representing the namespace. Within each top-level + namespace object, nested namespace names are bound to dynamic objects representing each + tier of nested namespaces. When this method encounters the same namespace-qualified name, + it merges names together objects representing the namespaces. + + + + + + This property returns the "global object" or name bindings of the ScriptRuntime as a ScriptScope. + + You can set the globals scope, which you might do if you created a ScriptScope with an + IAttributesCollection so that your host could late bind names. + + + + + Stores information needed to setup a ScriptRuntime + + + + + Reads setup from .NET configuration system (.config files). + If there is no configuration available returns an empty setup. + + + + + Reads setup from a specified XML stream. + + + + + Reads setup from a specified XML file. + + + + + The list of language setup information for languages to load into + the runtime + + + + + Indicates that the script runtime is in debug mode. + This means: + + 1) Symbols are emitted for debuggable methods (methods associated with SourceUnit). + 2) Debuggable methods are emitted to non-collectable types (this is due to CLR limitations on dynamic method debugging). + 3) JIT optimization is disabled for all methods + 4) Languages may disable optimizations based on this value. + + + + + Ignore CLR visibility checks + + + + + Can be any derived class of ScriptHost. When set, it allows the + host to override certain methods to control behavior of the runtime + + + + + Option names are case-sensitive. + + + + + Arguments passed to the host type when it is constructed + + + + + A ScriptScope is a unit of execution for code. It consists of a global Scope which + all code executes in. A ScriptScope can have an arbitrary initializer and arbitrary + reloader. + + ScriptScope is not thread safe. Host should either lock when multiple threads could + access the same module or should make a copy for each thread. + + Hosting API counterpart for . + + + + + Gets a value stored in the scope under the given name. + + The specified name is not defined in the scope. + is a null reference. + + + + Gets a value stored in the scope under the given name. + Converts the result to the specified type using the conversion that the language associated with the scope defines. + If no language is associated with the scope, the default CLR conversion is attempted. + + The specified name is not defined in the scope. + is a null reference. + + + + Tries to get a value stored in the scope under the given name. + + is a null reference. + + + + Tries to get a value stored in the scope under the given name. + Converts the result to the specified type using the conversion that the language associated with the scope defines. + If no language is associated with the scope, the default CLR conversion is attempted. + + is a null reference. + + + + Sets the name to the specified value. + + is a null reference. + + + + Gets a handle for a value stored in the scope under the given name. + + The specified name is not defined in the scope. + is a null reference. + + + + Tries to get a handle for a value stored in the scope under the given name. + Returns true if there is such name, false otherwise. + + is a null reference. + + + + Sets the name to the specified value. + + + The value held by the handle isn't from the scope's app-domain and isn't serializable or MarshalByRefObject. + + or is a null reference. + + + + Determines if this context or any outer scope contains the defined name. + + is a null reference. + + + + Removes the variable of the given name from this scope. + + true if the value existed in the scope before it has been removed. + is a null reference. + + + + Gets a list of variable names stored in the scope. + + + + + Gets an array of variable names and their values stored in the scope. + + + + + Gets an engine for the language associated with this scope. + Returns invariant engine if the scope is language agnostic. + + + + + Hosting counterpart for . + + + + + Compile the ScriptSource into CompileCode object that can be executed + repeatedly in its default scope or in other scopes without having to recompile the code. + + Code cannot be compiled. + + + + Errors are reported to the specified listener. + Returns null if the parser cannot compile the code due to errors. + + + + + Errors are reported to the specified listener. + Returns null if the parser cannot compile the code due to error(s). + + + + + Errors are reported to the specified listener. + Returns null if the parser cannot compile the code due to error(s). + + + + + Executes the code in the specified scope. + Returns an object that is the resulting value of running the code. + + When the ScriptSource is a file or statement, the engine decides what is + an appropriate value to return. Some languages return the value produced + by the last expression or statement, but languages that are not expression + based may return null. + + Code cannot be compiled. + + + + Executes the source code. The execution is not bound to any particular scope. + + + + + Executes the code in a specified scope and converts the result to the specified type. + The conversion is language specific. + + + + + Executes the code in an empty scope and converts the result to the specified type. + The conversion is language specific. + + + + + Executes the code in an empty scope. + Returns an ObjectHandle wrapping the resulting value of running the code. + + + + + Executes the code in the specified scope. + Returns an ObjectHandle wrapping the resulting value of running the code. + + + + + Executes the code in an empty scope. + Returns an ObjectHandle wrapping the resulting value of running the code. + + If an exception is thrown the exception is caught and an ObjectHandle to + the exception is provided. + + + Use this API to handle non-serializable exceptions (exceptions might not be serializable due to security restrictions) + or if an exception serialization loses information. + + + + + Executes the expression in the specified scope and return a result. + Returns an ObjectHandle wrapping the resulting value of running the code. + + If an exception is thrown the exception is caught and an ObjectHandle to + the exception is provided. + + + Use this API to handle non-serializable exceptions (exceptions might not be serializable due to security restrictions) + or if an exception serialization loses information. + + + + + Runs a specified code as if it was a program launched from OS command shell. + and returns a process exit code indicating the success or error condition + of executing the code. + + Exact behavior depends on the language. Some languages have a dedicated "exit" exception that + carries the exit code, in which case the exception is cought and the exit code is returned. + The default behavior returns the result of program's execution converted to an integer + using a language specific conversion. + + Code cannot be compiled. + + + + Detects the encoding of the content. + + + An encoding that is used by the reader of the script source to transcode its content to Unicode text. + Null if the content is already textual and no transcoding is performed. + + + Note that the default encoding specified when the script source is created could be overridden by + an encoding that is found in the content preamble (Unicode BOM or a language specific encoding preamble). + In that case the preamble encoding is returned. Otherwise, the default encoding is returned. + + An I/O error occurs. + + + + Reads specified range of lines (or less) from the source unit. + + 1-based number of the first line to fetch. + The number of lines to fetch. + + Which character sequences are considered line separators is language specific. + If language doesn't specify otherwise "\r", "\n", "\r\n" are recognized line separators. + + An I/O error occurs. + + + + Reads a specified line. + + 1-based line number. + Line content. Line separator is not included. + An I/O error occurs. + + Which character sequences are considered line separators is language specific. + If language doesn't specify otherwise "\r", "\n", "\r\n" are recognized line separators. + + + + + Gets script source content. + + Entire content. + An I/O error occurs. + + The result includes language specific preambles (e.g. "#coding:UTF-8" encoding preamble recognized by Ruby), + but not the preamble defined by the content encoding (e.g. BOM). + The entire content of the source unit is encoded by single encoding (if it is read from binary stream). + + + + + Identification of the source unit. Assigned by the host. + The format and semantics is host dependent (could be a path on file system or URL). + null for anonymous script source. + Cannot be an empty string. + + + + + Move the tokenizer past the next token and return its category. + + The token information associated with the token just scanned. + + + + Move the tokenizer past the next token. + + False if the end of stream has been reached, true otherwise. + + + + Get all tokens over a block of the stream. + + + + The scanner should return full tokens. If startLocation + length lands in the middle of a token, the full token + should be returned. + + s + Tokens are read until at least given amount of characters is read or the stream ends. + A enumeration of tokens. + + + + Scan from startLocation to at least startLocation + length. + + Tokens are read until at least given amount of characters is read or the stream ends. + + This method is used to determine state at arbitrary startLocation. + + False if the end of stream has been reached, true otherwise. + + + + The current internal state of the scanner. + + + + + The current startLocation of the scanner. + + + + + Represents a language context. Typically there is at most 1 context + associated with each language, but some languages may use more than one context + to identify code that should be treated differently. Contexts are used during + member and operator lookup. + + + + + Registers a language within the system with the specified name. + + + + + Looks up the context ID for the specified context identifier + + + + + Singleton for each language. + + + + + Must not be called under a lock as it can potentially call a user code. + + The language context's implementation failed to instantiate. + + + + Whether the application is in debug mode. + This means: + + 1) Symbols are emitted for debuggable methods (methods associated with SourceUnit). + 2) Debuggable methods are emitted to non-collectable types (this is due to CLR limitations on dynamic method debugging). + 3) JIT optimization is disabled for all methods + 4) Languages may disable optimizations based on this value. + + + + + Ignore CLR visibility checks. + + + + + ObjectOperations provide a large catalogue of object operations such as member access, conversions, + indexing, and things like addition. There are several introspection and tool support services available + for more advanced hosts. + + You get ObjectOperation instances from ScriptEngine, and they are bound to their engines for the semantics + of the operations. There is a default instance of ObjectOperations you can share across all uses of the + engine. However, very advanced hosts can create new instances. + + + + the number of sites required before we'll try cleaning up the cache... + + + the minimum difference between the average that is required to remove + + + the maximum number we'll remove on a single cache cleanup + + + the number of sites we should clear after if we can't make progress cleaning up otherwise + + + a dictionary of SiteKey's which are used to cache frequently used operations, logically a set + + + the # of sites we had created at the last cleanup + + + the total number of sites we've ever created + + + + Calls the provided object with the given parameters and returns the result. + + The prefered way of calling objects is to convert the object to a strongly typed delegate + using the ConvertTo methods and then invoking that delegate. + + + + + Invokes a member on the provided object with the given parameters and returns the result. + + + + + Invokes a member on the provided object with the given parameters and returns the result. + + + + + Creates a new instance from the provided object using the given parameters, and returns the result. + + + + + Gets the member name from the object obj. Throws an exception if the member does not exist or is write-only. + + + + + Gets the member name from the object obj and converts it to the type T. Throws an exception if the + member does not exist, is write-only, or cannot be converted. + + + + + Gets the member name from the object obj. Returns true if the member is successfully retrieved and + stores the value in the value out param. + + + + + Returns true if the object has a member named name, false if the member does not exist. + + + + + Removes the member name from the object obj. + + + + + Sets the member name on object obj to value. + + + + + Sets the member name on object obj to value. This overload can be used to avoid + boxing and casting of strongly typed members. + + + + + Gets the member name from the object obj. Throws an exception if the member does not exist or is write-only. + + + + + Gets the member name from the object obj and converts it to the type T. The conversion will be explicit or implicit + depending on what the langauge prefers. Throws an exception if the member does not exist, is write-only, or cannot be converted. + + + + + Gets the member name from the object obj. Returns true if the member is successfully retrieved and + stores the value in the value out param. + + + + + Returns true if the object has a member named name, false if the member does not exist. + + + + + Removes the member name from the object obj. Returns true if the member was successfully removed + or false if the member does not exist. + + + + + Sets the member name on object obj to value. + + + + + Sets the member name on object obj to value. This overload can be used to avoid + boxing and casting of strongly typed members. + + + + + Converts the object obj to the type T. The conversion will be explicit or implicit + depending on what the langauge prefers. + + + + + Converts the object obj to the type type. The conversion will be explicit or implicit + depending on what the langauge prefers. + + + + + Converts the object obj to the type T. Returns true if the value can be converted, false if it cannot. + + The conversion will be explicit or implicit depending on what the langauge prefers. + + + + + Converts the object obj to the type type. Returns true if the value can be converted, false if it cannot. + + The conversion will be explicit or implicit depending on what the langauge prefers. + + + + + Convers the object obj to the type T including explicit conversions which may lose information. + + + + + Converts the object obj to the type type including explicit conversions which may lose information. + + + + + Converts the object obj to the type type including explicit conversions which may lose information. + + Returns true if the value can be converted, false if it cannot. + + + + + Converts the object obj to the type T. Returns true if the value can be converted, false if it cannot. + + + + + Convers the object obj to the type T including implicit conversions. + + + + + Converts the object obj to the type type including implicit conversions. + + + + + Converts the object obj to the type type including implicit conversions. + + Returns true if the value can be converted, false if it cannot. + + + + + Converts the object obj to the type T. Returns true if the value can be converted, false if it cannot. + + + + + Performs a generic unary operation on the strongly typed target and returns the value as the specified type + + + + + Peforms the generic binary operation on the specified strongly typed targets and returns + the strongly typed result. + + + + + Returns a list of strings which contain the known members of the object. + + + + + Returns a string representation of the object in a language specific object display format. + + + + + Gets or creates a dynamic site w/ the specified type parameters for the provided binder. + + + This will either get the site from the cache or create a new site and return it. The cache + may be cleaned if it's gotten too big since the last usage. + + + + + Gets or creates a dynamic site w/ the specified type parameters for the provided binder. + + + This will either get the site from the cache or create a new site and return it. The cache + may be cleaned if it's gotten too big since the last usage. + + + + + Gets or creates a dynamic site w/ the specified type parameters for the provided binder. + + + This will either get the site from the cache or create a new site and return it. The cache + may be cleaned if it's gotten too big since the last usage. + + + + + Gets or creates a dynamic site w/ the specified type parameters for the provided binder. + + + This will either get the site from the cache or create a new site and return it. The cache + may be cleaned if it's gotten too big since the last usage. + + + + + Gets or creates a dynamic site w/ the specified type parameters for the provided binder. + + + This will either get the site from the cache or create a new site and return it. The cache + may be cleaned if it's gotten too big since the last usage. + + + + + Helper to create to get or create the dynamic site - called by the GetSite methods. + + + + + Removes items from the cache that have the lowest usage... + + + + + Helper class for tracking all of our unique dynamic sites and their + usage patterns. We hash on the combination of the binder and site type. + + We also track the hit count and the key holds the site associated w/ the + key. Logically this is a set based upon the binder and site-type but we + store it in a dictionary. + + + + + Singleton LanguageContext which represents a language-neutral LanguageContext + + + + + Provides language specific facilities which are typically called by the runtime. + + + + + Provides access to setting variables in scopes. + + By default this goes through ObjectOperations which can be rather slow. + Languages can override this to provide fast customized access which avoids + ObjectOperations. Languages can provide fast access to commonly used scope + types for that language. Typically this includes ScopeStorage and any other + classes which the language themselves uses for backing of a Scope. + + + + + Provides access to try getting variables in scopes. + + By default this goes through ObjectOperations which can be rather slow. + Languages can override this to provide fast customized access which avoids + ObjectOperations. Languages can provide fast access to commonly used scope + types for that language. Typically this includes ScopeStorage and any other + classes which the language themselves uses for backing of a Scope. + + + + + Provides access to getting variables in scopes and converting the result. + + By default this goes through ObjectOperations which can be rather slow. + Languages can override this to provide fast customized access which avoids + ObjectOperations. Languages can provide fast access to commonly used scope + types for that language. Typically this includes ScopeStorage and any other + classes which the language themselves uses for backing of a Scope. + + + + + Provides access to getting variables in scopes. + + By default this goes through ObjectOperations which can be rather slow. + Languages can override this to provide fast customized access which avoids + ObjectOperations. Languages can provide fast access to commonly used scope + types for that language. Typically this includes ScopeStorage and any other + classes which the language themselves uses for backing of a Scope. + + + + + Provides a text reader for source code that is to be read from a given stream. + + The stream open for reading. The stream must also allow seeking. + An encoding that should be used if the stream doesn't have Unicode or language specific preamble. + the path of the source unit if available + The reader. + An I/O error occurs. + + + + Creates the language specific CompilerOptions object for compilation of code not bound to any particular scope. + The language should flow any relevant options from LanguageContext to the newly created options instance. + + + + + Creates the language specific CompilerOptions object for compilation of code bound to a given scope. + + + + + Parses the source code within a specified compiler context. + The source unit to parse is held on by the context. + + null on failure. + Could also set the code properties and line/file mappings on the source unit. + + + + Creates a conversion binder. + + If explicitCast is true then the binder should do explicit conversions. + If explicitCast is false then the binder should do implicit conversions. + + If explicitCast is null it is up to the language to select the conversions + which closest match their normal behavior. + + + + + Gets the member names associated with the object + By default, only returns IDO names + + + + + Returns a string representation of the object in a language specific object display format. + + Dynamic sites container that could be used for any dynamic dispatches necessary for formatting. + Object to format. + A string representation of object. + + + + Provides the ContextId which includes members that should only be shown for this LanguageContext. + + ContextId's are used for filtering by Scope's. + + + + + Gets the ScriptDomainManager that this LanguageContext is running within. + + + + + Whether the language can parse code and create source units. + + + + + Internal class which binds a LanguageContext, StreamContentProvider, and Encoding together to produce + a TextContentProvider which reads binary data with the correct language semantics. + + + + + Provides a factory to create TextReader's over one source of textual content. + + TextContentProvider's are used when reading from a source which is already decoded + or has a known specific decoding. + + For example a text editor might provide a TextContentProvider whose backing is + an in-memory text buffer that the user can actively edit. + + + + + Creates a new TextReader which is backed by the content the TextContentProvider was created for. + + This method may be called multiple times. For example once to compile the code and again to get + the source code to display error messages. + + + + + This attribute marks a parameter that is not allowed to be null. + It is used by the method binding infrastructure to generate better error + messages and method selection. + + + + + This attribute marks a parameter whose type is an array that is not allowed to have null items. + It is used by the method binding infrastructure to generate better error + messages and method selection. + + + + + This attribute is used to mark a parameter that can accept any keyword parameters that + are not bound to normal arguments. The extra keyword parameters will be + passed in a dictionary which is created for the call. + + Most languages which support params dictionaries will support the following types: + IDictionary<string, anything> + IDictionary<object, anything> + Dictionary<string, anything> + Dictionary<object, anything> + IDictionary + IAttributesCollection (deprecated) + + For languages which don't have language level support the user will be required to + create and populate the dictionary by hand. + + This attribute is the dictionary equivalent of the System.ParamArrayAttribute. + + + public static void KeywordArgFunction([ParamsDictionary]IDictionary<string, object> dict) { + foreach (var v in dict) { + Console.WriteLine("Key: {0} Value: {1}", v.Key, v.Value); + } + } + + Called from Python: + + KeywordArgFunction(a = 2, b = "abc") + + will print: + Key: a Value = 2 + Key: b Value = abc + + + + + Represents a host-provided variables for executable code. The variables are + typically backed by a host-provided dictionary. Languages can also associate per-language + information with the context by using scope extensions. This can be used for tracking + state which is used across multiple executions, for providing custom forms of + storage (for example object keyed access), or other language specific semantics. + + Scope objects are thread-safe as long as their underlying storage is thread safe. + + Script hosts can choose to use thread safe or thread unsafe modules but must be sure + to constrain the code they right to be single-threaded if using thread unsafe + storage. + + + + + Creates a new scope with a new empty thread-safe dictionary. + + + + + Creates a new scope which is backed by an arbitrary object for it's storage. + + + + + + Gets the ScopeExtension associated with the provided ContextId. + + + + + Sets the ScopeExtension to the provided value for the given ContextId. + + The extension can only be set once. The returned value is either the new ScopeExtension + if no value was previously set or the previous value. + + + + + Provides optimized and cacheable support for scope storage. + + This is the default object used for storing values in a scope. + + + + The implementation uses a case-insensitive dictionary which holds + onto ScopeVariableIgnoreCase objects. The SVIC's hold onto ScopeVariable + objects for each possible casing. + + + + + Gets the named value from the scope optionally ignoring case. + + If the named value is not present an InvalidOperationException is raised. + + + + + Attempts to get the named value from the scope optionally ignoring the case. + + Returns true if the value is present, false if it is not. + + + + + Sets the named value in the scope optionally ignoring the case. + + + + + Deletes the named value from the scope optionally ignoring the case. + + + + + Checks if the named value is present in the scope optionally ignoring the case. + + + + + Gets the IScopeVariable for the scope optionally ignoring case. + + The IScopeVariable can be held onto and get/set/deleted without performing + a dictionary lookup on subsequent accesses. + + + + + Gets the ScopeVariable for the scope in a case-sensitive manner. + + The ScopeVariable can be held onto and get/set/deleted without performing + a dictionary lookup on subsequent accesses. + + + + + Gets the ScopeVariableIgnoreCase for the scope in a case-insensitive manner. + + The ScopeVariable can be held onto and get/set/deleted without performing + a dictionary lookup on subsequent accesses. + + + + + Returns all of the member names which currently have values in the scope. + + The list contains all available casings. + + + + + Returns all of the member names and their associated values from the scope. + + The list contains all available casings. + + + + + Provides convenient case-sensitive value access. + + + + + Provides a common interface for accessing both case sensitive and + case insensitive variable storage. + + + + + Atempts to get the value. If a value is assigned it returns true otherwise + it returns false. + + + + + Sets the current value in the scope. + + + + + Removes the current value from the scope. + + + + + True if the scope has a value, false if it does not. + + + + + Boxes the value for storage in a scope. Languages or consumers of the scope + can save this value and use it to get/set the current value in the scope for + commonly accessed values. + + ScopeVariables are case sensitive and will only refer to a single value. + + + + + Atempts to get the value. If a value is assigned it returns true otherwise + it returns false. + + + + + Sets the current value in the scope. + + + + + Removes the current value from the scope. + + + + + True if the scope has a value, false if it does not. + + + + + Boxes the value for storage in a scope. Languages or consumers of the scope + can save this value and use it to get/set the current value in the scope for + commonly accessed values. + + ScopeVariablesIgnoreCase are case insensitive and may access different casings + depending on how other gets/sets occur in the scope. + + + + + Atempts to get the value. If a value is assigned it returns true otherwise + it returns false. + + + + + Sets the current value in the scope. + + + + + Removes the current value from the scope. + + + + + True if the scope has a value, false if it does not. + + + + + ScriptCode is an instance of compiled code that is bound to a specific LanguageContext + but not a specific ScriptScope. The code can be re-executed multiple times in different + scopes. Hosting API counterpart for this class is CompiledCode. + + + + + A collection of environment variables. + + + + + Event for when a host calls LoadAssembly. After hooking this + event languages will need to call GetLoadedAssemblyList to + get any assemblies which were loaded before the language was + loaded. + + + + + Only host should redirect I/O. + + + + + Provides a factory to create streams over one source of binary content. + + StreamContentProvider's are used when opening a file of an unknown encoding. The + StreamContentProvider will be wrapped in a TextContentProvider provided by the language + which can support a language specific way of interpreting the binary data into text. + + For example some languages allow a marker at the beginning of the file which specifies + the encoding of the rest of the file. + + + + + Creates a new Stream which is backed by the content the StreamContentProvider was created for. + + For example if the StreamContentProvider was backing a file then GetStream re-opens the file and returns + the new stream. + + This method may be called multiple times. For example once to compile the code and again to get + the source code to display error messages. + + + + + Move the tokenizer past the next token and return its category. + + The token information associated with the token just scanned. + + + + Move the tokenizer past the next token. + + False if the end of stream has been reached, true otherwise. + + + + Get all tokens over a block of the stream. + + + + The scanner should return full tokens. If startLocation + length lands in the middle of a token, the full token + should be returned. + + + Tokens are read until at least given amount of characters is read or the stream ends. + A enumeration of tokens. + + + + Scan from startLocation to at least startLocation + length. + + The mininum number of characters to process while getting tokens. + + This method is used to determine state at arbitrary startLocation. + + False if the end of stream has been reached, true otherwise. + + + + The current internal state of the scanner. + + + + + The current startLocation of the scanner. + + + + + See also Microsoft.VisualStudio.Package.TokenTriggers. + + + + + Source code is a syntactically correct. + + + + + Source code represents an empty statement/expression. + + + + + Source code is already invalid and no suffix can make it syntactically correct. + + + + + Last token is incomplete. Source code can still be completed correctly. + + + + + Last statement is incomplete. Source code can still be completed correctly. + + + + + Defines a kind of the source code. The parser sets its initial state accordingly. + + + + + The code is an expression. + + + + + The code is a sequence of statements. + + + + + The code is a single statement. + + + + + The code is a content of a file. + + + + + The code is an interactive command. + + + + + The language parser auto-detects the kind. A syntax error is reported if it is not able to do so. + + + + + Source code reader. + + + + + Seeks the first character of a specified line in the text stream. + + Line number. The current position is assumed to be line #1. + + Returns true if the line is found, false otherwise. + + + + + Encoding that is used by the reader to convert binary data read from an underlying binary stream. + Null if the reader is reading from a textual source (not performing any byte to character transcoding). + + + + + Provides a StreamContentProvider for a stream of content backed by a file on disk. + + + + + Represents a location in source code. + + + + + Creates a new source location. + + The index in the source stream the location represents (0-based). + The line in the source stream the location represents (1-based). + The column in the source stream the location represents (1-based). + + + + Compares two specified location values to see if they are equal. + + One location to compare. + The other location to compare. + True if the locations are the same, False otherwise. + + + + Compares two specified location values to see if they are not equal. + + One location to compare. + The other location to compare. + True if the locations are not the same, False otherwise. + + + + Compares two specified location values to see if one is before the other. + + One location to compare. + The other location to compare. + True if the first location is before the other location, False otherwise. + + + + Compares two specified location values to see if one is after the other. + + One location to compare. + The other location to compare. + True if the first location is after the other location, False otherwise. + + + + Compares two specified location values to see if one is before or the same as the other. + + One location to compare. + The other location to compare. + True if the first location is before or the same as the other location, False otherwise. + + + + Compares two specified location values to see if one is after or the same as the other. + + One location to compare. + The other location to compare. + True if the first location is after or the same as the other location, False otherwise. + + + + Compares two specified location values. + + One location to compare. + The other location to compare. + 0 if the locations are equal, -1 if the left one is less than the right one, 1 otherwise. + + + + A location that is valid but represents no location at all. + + + + + An invalid location. + + + + + A minimal valid location. + + + + + The index in the source stream the location represents (0-based). + + + + + The line in the source stream the location represents (1-based). + + + + + The column in the source stream the location represents (1-based). + + + + + Whether the location is a valid location. + + True if the location is valid, False otherwise. + + + + Stores the location of a span of text in a source file. + + + + + Constructs a new span with a specific start and end location. + + The beginning of the span. + The end of the span. + + + + A valid span that represents no location. + + + + + An invalid span. + + + + + Compares two specified Span values to see if they are equal. + + One span to compare. + The other span to compare. + True if the spans are the same, False otherwise. + + + + Compares two specified Span values to see if they are not equal. + + One span to compare. + The other span to compare. + True if the spans are not the same, False otherwise. + + + + The start location of the span. + + + + + The end location of the span. Location of the first character behind the span. + + + + + Length of the span (number of characters inside the span). + + + + + Whether the locations in the span are valid. + + + + + Reads specified range of lines (or less) from the source unit. + Line numbers starts with 1. + + + + + Errors are reported to the specified sink. + Returns null if the parser cannot compile the code due to error(s). + + + + + Executes against a specified scope. + + + + + Executes against a specified scope and reports errors to the given error sink. + + + + + Executes in a new scope created by the language. + + + + + Executes in a new scope created by the language. + + + + + Executes in a new scope created by the language. + + + + + Identification of the source unit. Assigned by the host. + The format and semantics is host dependent (could be a path on file system or URL). + Empty string for anonymous source units. + + + + + LanguageContext of the language of the unit. + + + + + Unmapped span. + + + + + A token marking an end of stream. + + + + + A space, tab, or newline. + + + + + A block comment. + + + + + A single line comment. + + + + + A documentation comment. + + + + + A numeric literal. + + + + + A character literal. + + + + + A string literal. + + + + + A regular expression literal. + + + + + A keyword. + + + + + A directive (e.g. #line). + + + + + A punctuation character that has a specific meaning in a language. + + + + + A token that operates as a separator between two language elements. + + + + + An identifier (variable, $variable, @variable, @@variable, $variable$, function!, function?, [variable], i'variable', ...) + + + + + Braces, parenthesis, brackets. + + + + + Errors. + + + + + Converts a generic ICollection of T into an array of T. + + If the collection is already an array of T the original collection is returned. + + + + + Not all .NET enumerators throw exceptions if accessed in an invalid state. This type + can be used to throw exceptions from enumerators implemented in IronPython. + + + + + Wraps the provided enumerable into a ReadOnlyCollection{T} + + Copies all of the data into a new array, so the data can't be + changed after creation. The exception is if the enumerable is + already a ReadOnlyCollection{T}, in which case we just return it. + + + + + Console input stream (Console.OpenStandardInput) has a bug that manifests itself if reading small amounts of data. + This class wraps the standard input stream with a buffer that ensures that enough data are read from the underlying stream. + + + + + Requires the range [offset, offset + count] to be a subset of [0, array.Count]. + + Offset or count are out of range. + + + + Requires the range [offset, offset + count] to be a subset of [0, array.Count]. + + Offset or count are out of range. + + + + Requires the array and all its items to be non-null. + + + + + Requires the enumerable collection and all its items to be non-null. + + + + + Requires the range [offset, offset + count] to be a subset of [0, array.Count]. + + Array is null. + Offset or count are out of range. + + + + Presents a flat enumerable view of multiple dictionaries + + + + + Strongly-typed and parameterized string factory. + + + + + A string like "Cannot access member {1} declared on type {0} because the type contains generic parameters." + + + + + A string like "Type '{0}' is missing or cannot be loaded." + + + + + A string like "static property "{0}" of "{1}" can only be read through a type, not an instance" + + + + + A string like "static property "{0}" of "{1}" can only be assigned to through a type, not an instance" + + + + + A string like "Type parameter is {0}. Expected a delegate." + + + + + A string like "Cannot cast from type '{0}' to type '{1}" + + + + + A string like "unknown member type: '{0}'. " + + + + + A string like "The operation requires a non-generic type for {0}, but this represents generic types only" + + + + + A string like "Invalid operation: '{0}'" + + + + + A string like "Cannot create default value for type {0}." + + + + + A string like "Unhandled convert: {0}" + + + + + A string like "{0}.{1} has no publiclly visible method." + + + + + A string like "Extension type {0} must be public." + + + + + A string like "Invalid type of argument {0}; expecting {1}." + + + + + A string like "Field {0} is read-only" + + + + + A string like "Property {0} is read-only" + + + + + A string like "Expected event from {0}.{1}, got event from {2}.{3}." + + + + + A string like "expected bound event, got {0}." + + + + + A string like "Expected type {0}, got {1}." + + + + + A string like "can only write to member {0}." + + + + + A string like "Invalid stream type: {0}." + + + + + A string like "can't add another casing for identifier {0}" + + + + + A string like "can't add new identifier {0}" + + + + + A string like "Type '{0}' doesn't provide a suitable public constructor or its implementation is faulty: {1}" + + + + + A string like "Cannot emit constant {0} ({1})" + + + + + A string like "No implicit cast from {0} to {1}" + + + + + A string like "No explicit cast from {0} to {1}" + + + + + A string like "name '{0}' not defined" + + + + + A string like "Cannot create instance of {0} because it contains generic parameters" + + + + + A string like "Non-verifiable assembly generated: {0}:\nAssembly preserved as {1}\nError text:\n{2}\n" + + + + + A string like "Method precondition violated" + + + + + A string like "Invalid argument value" + + + + + A string like "Non-empty string required" + + + + + A string like "Non-empty collection required" + + + + + A string like "must by an Exception instance" + + + + + A string like "Type of test must be bool" + + + + + A string like "Type of the expression must be bool" + + + + + A string like "Empty string is not a valid path." + + + + + A string like "Invalid delegate type (Invoke method not found)." + + + + + A string like "expected only static property" + + + + + A string like "Property doesn't exist on the provided type" + + + + + A string like "Field doesn't exist on provided type" + + + + + A string like "Type doesn't have constructor with a given signature" + + + + + A string like "Type doesn't have a method with a given name." + + + + + A string like "Type doesn't have a method with a given name and signature." + + + + + A string like "Count must be non-negative." + + + + + A string like "arrayType must be an array type" + + + + + A string like "Either code or target must be specified." + + + + + A string like "RuleBuilder can only be used with delegates whose first argument is CallSite." + + + + + A string like "no instance for call." + + + + + A string like "Missing Test." + + + + + A string like "Missing Target." + + + + + A string like "Finally already defined." + + + + + A string like "Can not have fault and finally." + + + + + A string like "Fault already defined." + + + + + A string like "Global/top-level local variable names must be unique." + + + + + A string like "Generating code from non-serializable CallSiteBinder." + + + + + A string like "Specified path is invalid." + + + + + A string like "Dictionaries are not hashable." + + + + + A string like "language already registered." + + + + + A string like "The method or operation is not implemented." + + + + + A string like "No exception." + + + + + A string like "Already initialized." + + + + + A string like "CreateScopeExtension must return a scope extension." + + + + + A string like "Invalid number of parameters for the service." + + + + + A string like "Cannot change non-caching value." + + + + + A string like "No code to compile." + + + + + A string like "Queue empty." + + + + + A string like "Enumeration has not started. Call MoveNext." + + + + + A string like "Enumeration already finished." + + + + + A string like "Invalid output directory." + + + + + A string like "Invalid assembly name or file extension." + + + + + A string like "No default value for a given type." + + + + + A string like "Specified language provider type is not registered." + + + + + A string like "can't read from property" + + + + + A string like "can't write to property" + + + + + Strongly-typed and parameterized exception factory. + + + + + ArgumentException with message like "Either code or target must be specified." + + + + + InvalidOperationException with message like "Type parameter is {0}. Expected a delegate." + + + + + InvalidOperationException with message like "Cannot cast from type '{0}' to type '{1}" + + + + + InvalidOperationException with message like "unknown member type: '{0}'. " + + + + + InvalidOperationException with message like "RuleBuilder can only be used with delegates whose first argument is CallSite." + + + + + InvalidOperationException with message like "no instance for call." + + + + + InvalidOperationException with message like "Missing Test." + + + + + InvalidOperationException with message like "Missing Target." + + + + + TypeLoadException with message like "The operation requires a non-generic type for {0}, but this represents generic types only" + + + + + ArgumentException with message like "Invalid operation: '{0}'" + + + + + InvalidOperationException with message like "Finally already defined." + + + + + InvalidOperationException with message like "Can not have fault and finally." + + + + + InvalidOperationException with message like "Fault already defined." + + + + + ArgumentException with message like "Cannot create default value for type {0}." + + + + + ArgumentException with message like "Unhandled convert: {0}" + + + + + InvalidOperationException with message like "{0}.{1} has no publiclly visible method." + + + + + ArgumentException with message like "Global/top-level local variable names must be unique." + + + + + ArgumentException with message like "Generating code from non-serializable CallSiteBinder." + + + + + ArgumentException with message like "Specified path is invalid." + + + + + ArgumentTypeException with message like "Dictionaries are not hashable." + + + + + InvalidOperationException with message like "language already registered." + + + + + NotImplementedException with message like "The method or operation is not implemented." + + + + + InvalidOperationException with message like "No exception." + + + + + ArgumentException with message like "Extension type {0} must be public." + + + + + InvalidOperationException with message like "Already initialized." + + + + + InvalidImplementationException with message like "CreateScopeExtension must return a scope extension." + + + + + ArgumentException with message like "Invalid number of parameters for the service." + + + + + ArgumentException with message like "Invalid type of argument {0}; expecting {1}." + + + + + ArgumentException with message like "Cannot change non-caching value." + + + + + MissingMemberException with message like "Field {0} is read-only" + + + + + MissingMemberException with message like "Property {0} is read-only" + + + + + ArgumentException with message like "Expected event from {0}.{1}, got event from {2}.{3}." + + + + + ArgumentTypeException with message like "expected bound event, got {0}." + + + + + ArgumentTypeException with message like "Expected type {0}, got {1}." + + + + + MemberAccessException with message like "can only write to member {0}." + + + + + InvalidOperationException with message like "No code to compile." + + + + + ArgumentException with message like "Invalid stream type: {0}." + + + + + InvalidOperationException with message like "Queue empty." + + + + + InvalidOperationException with message like "Enumeration has not started. Call MoveNext." + + + + + InvalidOperationException with message like "Enumeration already finished." + + + + + InvalidOperationException with message like "can't add another casing for identifier {0}" + + + + + InvalidOperationException with message like "can't add new identifier {0}" + + + + + ArgumentException with message like "Invalid output directory." + + + + + ArgumentException with message like "Invalid assembly name or file extension." + + + + + ArgumentException with message like "Cannot emit constant {0} ({1})" + + + + + ArgumentException with message like "No implicit cast from {0} to {1}" + + + + + ArgumentException with message like "No explicit cast from {0} to {1}" + + + + + MissingMemberException with message like "name '{0}' not defined" + + + + + ArgumentException with message like "No default value for a given type." + + + + + ArgumentException with message like "Specified language provider type is not registered." + + + + + InvalidOperationException with message like "can't read from property" + + + + + InvalidOperationException with message like "can't write to property" + + + + + ArgumentException with message like "Cannot create instance of {0} because it contains generic parameters" + + + + + System.Security.VerificationException with message like "Non-verifiable assembly generated: {0}:\nAssembly preserved as {1}\nError text:\n{2}\n" + + + + + Gets a Func of CallSite, object * paramCnt, object delegate type + that's suitable for use in a non-strongly typed call site. + + + + diff --git a/Reference/DLR/Net40/Microsoft.Dynamic.dll b/Reference/DLR/Net40/Microsoft.Dynamic.dll new file mode 100644 index 000000000..d04c1a12e Binary files /dev/null and b/Reference/DLR/Net40/Microsoft.Dynamic.dll differ diff --git a/Reference/DLR/Net40/Microsoft.Dynamic.xml b/Reference/DLR/Net40/Microsoft.Dynamic.xml new file mode 100644 index 000000000..c68cc6a0b --- /dev/null +++ b/Reference/DLR/Net40/Microsoft.Dynamic.xml @@ -0,0 +1,6534 @@ + + + + Microsoft.Dynamic + + + + + Binds named arguments to the parameters. Returns a permutation of indices that captures the relationship between + named arguments and their corresponding parameters. Checks for duplicate and unbound named arguments. + + Ensures that for all i: namedArgs[i] binds to parameters[args.Length + bindingPermutation[i]] + + + + + The number of arguments not counting the collapsed ones. + + + + + Gets the total number of visible arguments passed to the call site including collapsed ones. + + + + + ArgBuilder provides an argument value used by the MethodBinder. One ArgBuilder exists for each + physical parameter defined on a method. + + Contrast this with ParameterWrapper which represents the logical argument passed to the method. + + + + + Provides the Expression which provides the value to be passed to the argument. + If null is returned the argument is skipped (not passed to the callee). + + + + + Provides an Expression which will update the provided value after a call to the method. May + return null if no update is required. + + + + + If the argument produces a return value (e.g. a ref or out value) this provides + the additional value to be returned. + + + + + The number of actual arguments consumed by this builder. + + + + + Returns the type required for the argument or null if the ArgBuilder + does not consume a type. + + + + + An assignable value that is passed to a byref parameter + After the call it will contain the updated value + + + + + Indicates the specific type of failure, if any, from binding to a method. + + + + + The binding succeeded. Only one method was applicable or had the best conversion. + + + + + More than one method was applicable for the provided parameters and no method was considered the best. + + + + + There are no overloads that match the number of parameters required for the call + + + + + None of the target method(s) can successfully be called. The failure can be due to: + 1. Arguments could not be successfully converted for the call + 2. Keyword arguments could not be assigned to positional arguments + 3. Keyword arguments could be assigned but would result in an argument being assigned + multiple times (keyword and positional arguments conflit or dupliate keyword arguments). + + + + + Actual arguments cannot be constructed. + + + + + No method is callable. For example, all methods have an unbound generic parameter. + + + + + Encapsulates the result of an attempt to bind to one or methods using the OverloadResolver. + + Users should first check the Result property to see if the binding was successful or + to determine the specific type of failure that occured. If the binding was successful + MakeExpression can then be called to create an expression which calls the method. + If the binding was a failure callers can then create a custom error message based upon + the reason the call failed. + + + + + Creates a new BindingTarget when the method binding has succeeded. + + + + + Creates a new BindingTarget when the method binding has failed due to an incorrect argument count + + + + + Creates a new BindingTarget when the method binding has failued due to + one or more parameters which could not be converted. + + + + + Creates a new BindingTarget when the match was ambiguous + + + + + Other failure. + + + + + Gets an Expression which calls the binding target if the method binding succeeded. + + Throws InvalidOperationException if the binding failed. + + + + + Gets the result of the attempt to bind. + + + + + Returns the method if the binding succeeded, or null if no method was applicable. + + + + + Returns the selected overload if the binding succeeded, or null if no one was applicable. + + + + + Gets the name of the method as supplied to the OverloadResolver. + + + + + Returns the MethodTarget if the binding succeeded, or null if no method was applicable. + + + + + Returns the methods which don't have any matches or null if Result == BindingResult.AmbiguousMatch + + + + + Returns the methods and their associated conversion failures if Result == BindingResult.CallFailure. + + + + + Returns the acceptable number of arguments which can be passed to the method if Result == BindingResult.IncorrectArgumentCount. + + + + + Returns the total number of arguments provided to the call. 0 if the call succeeded or failed for a reason other + than argument count mismatch. + + + + + Gets the MetaObjects which we originally did binding against in their restricted form. + + The members of the array correspond to each of the arguments. All members of the array + have a value. + + + + + Returns the return type of the binding, or null if no method was applicable. + + + + + Returns the NarrowingLevel of the method if the call succeeded. If the call + failed returns NarrowingLevel.None. + + + + + Returns true if the binding was succesful, false if it failed. + + This is an alias for BindingTarget.Result == BindingResult.Success. + + + + + Creates a ReturnBuilder + + the type the ReturnBuilder will leave on the stack + + + + Represents the reason why a call to a specific method could not be performed by the OverloadResolver. + + The reason for the failure is specified by the CallFailureReason property. Once this property + has been consulted the other properties can be consulted for more detailed information regarding + the failure. + + If reason is ConversionFailure the ConversionResults property will be non-null. + If reason is UnassignableKeyword the KeywordArguments property will be non-null and include + the keywords which could not be assigned. + If reason is DuplicateKeyword the KeywordArguments property will be non-null and include + the keywords which were duplicated (either by the keywords themselves or by positional + arguments). + + MethodTarget is always set and indicates the method which failed to bind. + + + + + Gets the MethodTarget which the call failed for. + + + + + Gets the reason for the call failure which determines the other + properties of the CallFailure which should be consulted. + + + + + Gets a list of ConversionResult's for each parameter indicating + whether the conversion was successful or failed and the types + being converted. + + + + + Gets the list of keyword arguments that were either dupliated or + unassignable. + + + + + Default value, their was no CallFailure. + + + + + One of more parameters failed to be converted + + + + + One or more keyword arguments could not be successfully assigned to a positional argument + + + + + One or more keyword arguments were duplicated or would have taken the spot of a + provided positional argument. + + + + + Type arguments could not be inferred + + + + + Represents a collection of MethodCandidate's which all accept the + same number of logical parameters. For example a params method + and a method with 3 parameters would both be a CandidateSet for 3 parameters. + + + + + Represents information about a failure to convert an argument from one + type to another. + + + + + Value of the argument or null if it is not available. + + + + + Argument actual type or its limit type if the value not known. + DynamicNull if the argument value is null. + + + + + ArgBuilder which provides a default parameter value for a method call. + + + + + Provides binding and overload resolution to .NET methods. + + MethodBinder's can be used for: + generating new AST code for calling a method + calling a method via reflection at runtime + (not implemented) performing an abstract call + + MethodBinder's support default arguments, optional arguments, by-ref (in and out), and keyword arguments. + + Implementation Details: + + The MethodBinder works by building up a CandidateSet for each number of effective arguments that can be + passed to a set of overloads. For example a set of overloads such as: + foo(object a, object b, object c) + foo(int a, int b) + + would have 2 target sets - one for 3 parameters and one for 2 parameters. For parameter arrays + we fallback and create the appropriately sized CandidateSet on demand. + + Each CandidateSet consists of a set of MethodCandidate's. Each MethodCandidate knows the flattened + parameters that could be received. For example for a function such as: + foo(params int[] args) + + When this method is in a CandidateSet of size 3 the MethodCandidate takes 3 parameters - all of them + ints; if it's in a CandidateSet of size 4 it takes 4 parameters. Effectively a MethodCandidate is + a simplified view that allows all arguments to be treated as required positional arguments. + + Each MethodCandidate in turn refers to a MethodTarget. The MethodTarget is composed of a set + of ArgBuilder's and a ReturnBuilder which know how to consume the positional arguments and pass + them to the appropriate argument of the destination method. This includes routing keyword + arguments to the correct position, providing the default values for optional arguments, etc... + + After binding is finished the MethodCandidates are thrown away and a BindingTarget is returned. + The BindingTarget indicates whether the binding was successful and if not any additional information + that should be reported to the user about the failed binding. It also exposes the MethodTarget which + allows consumers to get the flattened list of required parameters for the call. MethodCandidates + are not exposed and are an internal implementation detail of the MethodBinder. + + + + + Resolves a method overload and returns back a BindingTarget. + + The BindingTarget can then be tested for the success or particular type of + failure that prevents the method from being called. If successfully bound the BindingTarget + contains a list of argument meta-objects with additional restrictions that ensure the selection + of the particular overload. + + + + + Checks to see if the language allows named arguments to be bound to instance fields or + properties and turned into setters. By default this is only allowed on contructors. + + + + + Gets an expression that evaluates to the result of GetByRefArray operation. + + + + + Allow to bind an array/dictionary instance or a null reference to params array/dictionary parameter. + + + + + Called before arguments binding. + + + A bitmask that indicates (set bits) the parameters that were mapped by this method. + A default mapping will be constructed for the remaining parameters (cleared bits). + + + + + Return null if arguments cannot be constructed and overload resolution should produce an error. + + + + + Determines whether given overloads are overloaded on index-th parameter (the types of the index-th parameters are the same). + + + + + Selects the best (of two) candidates for conversion from actualType + + + + + Provides ordering for two parameter types if there is no conversion between the two parameter types. + + + + + The method is called each time an item of lazily splatted argument is needed. + + + + + The number of actual arguments consumed by this builder. + + + + + ArgBuilder which provides a value for a keyword argument. + + The KeywordArgBuilder calculates its position at emit time using it's initial + offset within the keyword arguments, the number of keyword arguments, and the + total number of arguments provided by the user. It then delegates to an + underlying ArgBuilder which only receives the single correct argument. + + Delaying the calculation of the position to emit time allows the method binding to be + done without knowing the exact the number of arguments provided by the user. Hence, + the method binder can be dependent only on the set of method overloads and keyword names, + but not the user arguments. While the number of user arguments could be determined + upfront, the current MethodBinder does not have this design. + + + + + The underlying builder should expect a single parameter as KeywordArgBuilder is responsible + for calculating the correct parameter to use + + + + + + Updates fields/properties of the returned value with unused keyword parameters. + + + + + MethodCandidate represents the different possible ways of calling a method or a set of method overloads. + A single method can result in multiple MethodCandidates. Some reasons include: + - Every optional parameter or parameter with a default value will result in a candidate + - The presence of ref and out parameters will add a candidate for languages which want to return the updated values as return values. + - ArgumentKind.List and ArgumentKind.Dictionary can result in a new candidate per invocation since the list might be different every time. + + Each MethodCandidate represents the parameter type for the candidate using ParameterWrapper. + + + + + Builds a new MethodCandidate which takes count arguments and the provided list of keyword arguments. + + The basic idea here is to figure out which parameters map to params or a dictionary params and + fill in those spots w/ extra ParameterWrapper's. + + + + + Narrowing conversions are conversions that cannot be proved to always succeed, conversions that are + known to possibly lose information, and conversions across domains of types sufficiently different + to merit narrowing notation like casts. + + Its upto every language to define the levels for conversions. The narrowling levels can be used by + for method overload resolution, where the overload is based on the parameter types (and not the number + of parameters). + + + + + Conversions at this level do not do any narrowing. Typically, this will include + implicit numeric conversions, Type.IsAssignableFrom, StringBuilder to string, etc. + + + + + Language defined prefered narrowing conversion. First level that introduces narrowing + conversions. + + + + + Language defined preferred narrowing conversion. Second level that introduces narrowing + conversions and should have more conversions than One. + + + + + Language defined preferred narrowing conversion. Third level that introduces narrowing + conversions and should have more conversions that Two. + + + + + A somewhat meaningful conversion is possible, but it will quite likely be lossy. + For eg. BigInteger to an Int32, Boolean to Int32, one-char string to a char, + larger number type to a smaller numeric type (where there is no overflow), etc + + + + + Builds the argument for an out argument when not passed a StrongBox. The out parameter + is returned as an additional return value. + + + + + Defines a method overload abstraction for the purpose of overload resolution. + It provides the overload resolver the metadata it needs to perform the resolution. + + + WARNING: This is a temporary API that will undergo breaking changes in future versions. + + + + + Null for constructors. + + + + + The method arity can vary, i.e. the method has params array or params dict parameters. + + + + + Represents a method overload that is bound to a . + + + Not thread safe. + WARNING: This is a temporary API that will undergo breaking changes in future versions. + + + + + Maps out parameters to return args and ref parameters to ones that don't accept StrongBox. + + + + + ParameterWrapper represents the logical view of a parameter. For eg. the byref-reduced signature + of a method with byref parameters will be represented using a ParameterWrapper of the underlying + element type, since the logical view of the byref-reduced signature is that the argument will be + passed by value (and the updated value is included in the return value). + + Contrast this with ArgBuilder which represents the real physical argument passed to the method. + + + + + ParameterInfo is not available. + + + + + Creates a parameter that represents an expanded item of params-array. + + + + + True if the wrapper represents a params-array parameter (false for parameters created by expansion of a params-array). + + + + + True if the wrapper represents a params-dict parameter (false for parameters created by expansion of a params-dict). + + + + + Builds the parameter for a params dictionary argument - this collects all the extra name/value + pairs provided to the function into a SymbolDictionary which is passed to the function. + + + + + An argument that the user wants to explicitly pass by-reference (with copy-in copy-out semantics). + The user passes a StrongBox[T] object whose value will get updated when the call returns. + + + + + SimpleArgBuilder produces the value produced by the user as the argument value. It + also tracks information about the original parameter and is used to create extended + methods for params arrays and param dictionary functions. + + + + + Parameter info is not available for this argument. + + + + + Type and whether the parameter is a params-array or params-dictionary is derived from info. + + + + + True if there are restrictions beyond just simple type restrictions + + + + + Builds a parameter for a reference argument when a StrongBox has not been provided. The + updated return value is returned as one of the resulting return values. + + + + + Gets the generic arguments for method based upon the constraints discovered during + type inference. Returns null if not all generic arguments had their types inferred. + + + + + Creates a new set of arg builders for the given generic method definition which target the new + parameters. + + + + + Creates a new list of ParameterWrappers for the generic method replacing the old parameters with the new ones. + + + + + Gets the generic type arguments sorted so that the type arguments + that are depended upon by other type arguments are sorted before + their dependencies. + + + + + Checks to see if the x type parameter is dependent upon the y type parameter. + + + + + Builds a mapping based upon generic parameter constraints between related generic + parameters. This is then used to sort the generic parameters so that we can process + the least dependent parameters first. For example given the method: + + void Foo{T0, T1}(T0 x, T1 y) where T0 : T1 + + We need to first infer the type information for T1 before we infer the type information + for T0 so that we can ensure the constraints are correct. + + + + + Returns a mapping from generic type parameter to the input DMOs which map to it. + + + + + Adds any additional ArgumentInputs entries for the given object and parameter type. + + + + + Walks the nested generic hierarchy to construct all of the generic parameters referred + to by this type. For example if getting the generic parameters for the x parameter on + the method: + + void Foo{T0, T1}(Dictionary{T0, T1} x); + + We would add both typeof(T0) and typeof(T1) to the list of generic arguments. + + + + + Provides generic type inference for a single parameter. + + + For example: + M{T}(T x) + M{T}(IList{T} x) + M{T}(ref T x) + M{T}(T[] x) + M{T}(ref Dictionary{T,T}[] x) + + + + + Provides generic type inference for a single parameter. + + + For example: + M{T}(T x) + M{T}(IList{T} x) + M{T}(ref T x) + M{T}(T[] x) + M{T}(ref Dictionary{T,T}[] x) + + + + + Checks if the constraints are violated by the given input for the specified generic method parameter. + + This method must be supplied with a mapping for any dependent generic method type parameters which + this one can be constrained to. For example for the signature "void Foo{T0, T1}(T0 x, T1 y) where T0 : T1". + we cannot know if the constraints are violated unless we know what we have calculated T1 to be. + + + + + Finds all occurences of genericParameter in openType and the corresponding concrete types in closedType. + Returns true iff all occurences of the generic parameter in the open type correspond to the same concrete type in the closed type + and this type satisfies given constraints. Returns the concrete type in match if so. + + + + + Maps a single type parameter to the possible parameters and DynamicMetaObjects + we can get inference from. For example for the signature: + + void Foo{T0, T1}(T0 x, T1 y, IList{T1} z); + + We would have one ArgumentInput for T0 which holds onto the DMO providing the argument + value for x. We would also have one ArgumentInput for T1 which holds onto the 2 DMOs + for y and z. Associated with y would be a GenericParameterInferer and associated with + z would be a ConstructedParameterInferer. + + + + + Implemented by DynamicMetaObject subclasses when the associated object + can participate in generic method type inference. This interface + is used when the inference engine is attempting to perform type inference + for a parameter which is typed to a delegate type. + + + + + Returns the type inferred for parameterType when performing + inference for a conversion to delegateType. + + + + + Provides information about the result of a custom object which dynamically + infers back types. + + Currently only used for invokable objects to feedback the types for a delegate + type. + + + + + Determines the result of a conversion action. The result can either result in an exception, a value that + has been successfully converted or default(T), or a true/false result indicating if the value can be converted. + + + + + Attempts to perform available implicit conversions and throws if there are no available conversions. + + + + + Attempst to perform available implicit and explicit conversions and throws if there are no available conversions. + + + + + Attempts to perform available implicit conversions and returns default(ReturnType) if no conversions can be performed. + + If the return type of the rule is a value type then the return value will be zero-initialized. If the return type + of the rule is object or another class then the return type will be null (even if the conversion is to a value type). + This enables ImplicitTry to be used to do TryConvertTo even if the type is value type (and the difference between + null and a real value can be distinguished). + + + + + Attempts to perform available implicit and explicit conversions and returns default(ReturnType) if no conversions + can be performed. + + If the return type of the rule is a value type then the return value will be zero-initialized. If the return type + of the rule is object or another class then the return type will be null (even if the conversion is to a value type). + This enables ExplicitTry to be used to do TryConvertTo even if the type is value type (and the difference between + null and a real value can be distinguished). + + + + + Provides binding semantics for a language. This include conversions as well as support + for producing rules for actions. These optimized rules are used for calling methods, + performing operators, and getting members using the ActionBinder's conversion semantics. + + + + + Provides binding semantics for a language. This include conversions as well as support + for producing rules for actions. These optimized rules are used for calling methods, + performing operators, and getting members using the ActionBinder's conversion semantics. + + + + + Converts an object at runtime into the specified type. + + + + + Determines if a conversion exists from fromType to toType at the specified narrowing level. + toNotNullable is true if the target variable doesn't allow null values. + + + + + Provides ordering for two parameter types if there is no conversion between the two parameter types. + + + + + Converts the provided expression to the given type. The expression is safe to evaluate multiple times. + + + + + Gets the members that are visible from the provided type of the specified name. + + The default implemetnation first searches the type, then the flattened heirachy of the type, and then + registered extension methods. + + + + + Called when a set is attempting to assign to a field or property from a derived class through the base class. + + The default behavior is to allow the assignment. + + + + + Creates an ErrorInfo object when a static property is accessed from an instance member. The default behavior is throw + an exception indicating that static members properties be accessed via an instance. Languages can override this to + customize the exception, message, or to produce an ErrorInfo object which reads or writes to the property being accessed. + + The static property being accessed through an instance + True if the user is assigning to the property, false if the user is reading from the property + The parameters being used to access the property. This includes the instance as the first entry, any index parameters, and the + value being assigned as the last entry if isAssignment is true. + + + + + Provides a way for the binder to provide a custom error message when lookup fails. Just + doing this for the time being until we get a more robust error return mechanism. + + Deprecated, use the non-generic version instead + + + + + Gets the extension members of the given name from the provided type. Base classes are also + searched for their extension members. Once any of the types in the inheritance hierarchy + provide an extension member the search is stopped. + + + + + Gets the extension members of the given name from the provided type. Subclasses of the + type and their extension members are not searched. + + + + + Provides an opportunity for languages to replace all MemberTracker's with their own type. + + Alternatlely a language can expose MemberTracker's directly. + + The member which is being returned to the user. + Tthe type which the memberTrack was accessed from + + + + + Determines if the binder should allow access to non-public members. + + By default the binder does not allow access to non-public members. Base classes + can inherit and override this value to customize whether or not private binding + is available. + + + + + Creates the MetaObject for indexing directly into arrays or indexing into objects which have + default members. Returns null if we're not an indexing operation. + + + + + Creates the MetaObject for indexing directly into arrays or indexing into objects which have + default members. Returns null if we're not an indexing operation. + + + + + Creates the meta object for the rest of the operations: comparisons and all other + ExpressionType. If the operation cannot be completed a MetaObject which indicates an + error will be returned. + + + + + Creates the meta object for the rest of the operations: comparisons and all other + ExpressionType. If the operation cannot be completed a MetaObject which indicates an + error will be returned. + + + + + Produces a rule for comparing a value to null - supports comparing object references and nullable types. + + + + + Checks if the conversion is to object and produces a target if it is. + + + + + Checks if any conversions are available and if so builds the target for that conversion. + + + + + Checks if the conversion can be handled by a simple cast. + + + + + Checks if the conversion can be handled by calling a user-defined conversion method. + + + + + Helper that checkes both types to see if either one defines the specified conversion + method. + + + + + Checks if any of the members of the MemberGroup provide the applicable conversion and + if so uses it to build a conversion rule. + + + + + Checks if the conversion is to applicable by extracting the value from Extensible of T. + + + + + Checks if there's an implicit numeric conversion for primitive data types. + + + + + Checks if there's a conversion to/from Nullable of T. + + + + + Checks to see if there's a conversion of null to a reference type + + + + + Helper to produce an error when a conversion cannot occur + + + + + Helper to produce a rule which just boxes a value type + + + + + Helper to produce a conversion rule by calling the helper method to do the convert + + + + + Helper to produce a conversion rule by calling the helper method to do the convert + + + + + Helper to produce a conversion rule by calling the method to do the convert. This version takes the parameter + to be passed to the conversion function and we call it w/ our own value or w/ our Extensible.Value. + + + + + Helper to wrap explicit conversion call into try/catch incase it throws an exception. If + it throws the default value is returned. + + + + + Helper to produce a rule when no conversion is required (the strong type of the expression + input matches the type we're converting to or has an implicit conversion at the IL level) + + + + + Helper to produce a rule when no conversion is required from an extensible type's + underlying storage to the type we're converting to. The type of extensible type + matches the type we're converting to or has an implicit conversion at the IL level. + + + + + Helper to extract the value from an Extensible of T + + + + + Helper to convert a null value to nullable of T + + + + + Helper to produce the rule for converting T to Nullable of T + + + + + Helper to produce the rule for converting T to Nullable of T + + + + + Returns a value which indicates failure when a OldConvertToAction of ImplicitTry or + ExplicitTry. + + + + + Helper to extract the Value of an Extensible of T from the + expression being converted. + + + + + Helper that checks if fromType is an Extensible of T or a subtype of + Extensible of T and if so returns the T. Otherwise it returns fromType. + + This is used to treat extensible types the same as their underlying types. + + + + + Creates a target which returns null for a reference type. + + + + if a member-injector is defined-on or registered-for this type call it + + + + Builds a MetaObject for performing a member get. Supports all built-in .NET members, the OperatorMethod + GetBoundMember, and StrongBox instances. + + + The name of the member to retrieve. This name is not processed by the DefaultBinder and + is instead handed off to the GetMember API which can do name mangling, case insensitive lookups, etc... + + + The MetaObject from which the member is retrieved. + + + Returns a DynamicMetaObject which represents the value that will be returned when the member is accessed. + + The returned DynamicMetaObject may be strongly typed to a value type which needs boxing before being + returned from a standard DLR GetMemberBinder. The language is responsible for performing any boxing + so that it has an opportunity to perform custom boxing. + + + + + Builds a MetaObject for performing a member get. Supports all built-in .NET members, the OperatorMethod + GetBoundMember, and StrongBox instances. + + + The name of the member to retrieve. This name is not processed by the DefaultBinder and + is instead handed off to the GetMember API which can do name mangling, case insensitive lookups, etc... + + + The MetaObject from which the member is retrieved. + + + Provides overload resolution and method binding for any calls which need to be performed for the GetMember. + + + Returns a DynamicMetaObject which represents the value that will be returned when the member is accessed. + + The returned DynamicMetaObject may be strongly typed to a value type which needs boxing before being + returned from a standard DLR GetMemberBinder. The language is responsible for performing any boxing + so that it has an opportunity to perform custom boxing. + + + + + Builds a MetaObject for performing a member get. Supports all built-in .NET members, the OperatorMethod + GetBoundMember, and StrongBox instances. + + + The name of the member to retrieve. This name is not processed by the DefaultBinder and + is instead handed off to the GetMember API which can do name mangling, case insensitive lookups, etc... + + + The MetaObject from which the member is retrieved. + + + An OverloadResolverFactory which can be used for performing overload resolution and method binding. + + + True if the operation should return Operation.Failed on failure, false if it + should return the exception produced by MakeMissingMemberError. + + + The meta object to be used if the get results in an error. + + + Returns a DynamicMetaObject which represents the value that will be returned when the member is accessed. + + The returned DynamicMetaObject may be strongly typed to a value type which needs boxing before being + returned from a standard DLR GetMemberBinder. The language is responsible for performing any boxing + so that it has an opportunity to perform custom boxing. + + + + + Builds a MetaObject for performing a member get. Supports all built-in .NET members, the OperatorMethod + GetBoundMember, and StrongBox instances. + + + The name of the member to retrieve. This name is not processed by the DefaultBinder and + is instead handed off to the GetMember API which can do name mangling, case insensitive lookups, etc... + + + The MetaObject from which the member is retrieved. + + + True if the operation should return Operation.Failed on failure, false if it + should return the exception produced by MakeMissingMemberError. + + + The meta object to be used if the get results in an error. + + + Returns a DynamicMetaObject which represents the value that will be returned when the member is accessed. + + The returned DynamicMetaObject may be strongly typed to a value type which needs boxing before being + returned from a standard DLR GetMemberBinder. The language is responsible for performing any boxing + so that it has an opportunity to perform custom boxing. + + + + if a member-injector is defined-on or registered-for this type call it + + + + Provides default binding for performing a call on the specified meta objects. + + The signature describing the call + The meta object to be called. + + Additional meta objects are the parameters for the call as specified by the CallSignature in the CallAction. + + A MetaObject representing the call or the error. + + + + Provides default binding for performing a call on the specified meta objects. + + The signature describing the call + The meta object to be called. + + Additional meta objects are the parameters for the call as specified by the CallSignature in the CallAction. + + Overload resolver factory. + A MetaObject representing the call or the error. + + + + Provides default binding for performing a call on the specified meta objects. + + The signature describing the call + The meta object to be called. + + Additional meta objects are the parameters for the call as specified by the CallSignature in the CallAction. + + Overload resolver factory. + The result should the object be uncallable. + A MetaObject representing the call or the error. + + + + Gets a TargetInfo object for performing a call on this object. + + If this object is a delegate we bind to the Invoke method. + If this object is a MemberGroup or MethodGroup we bind to the methods in the member group. + If this object is a BoundMemberTracker we bind to the methods with the bound instance. + If the underlying type has defined an operator Call method we'll bind to that method. + + + + + Binds to the methods in a method group. + + + + + Binds to the methods in a member group. + + TODO: We should really only have either MemberGroup or MethodGroup, not both. + + + + + Binds to the BoundMemberTracker and uses the instance in the tracker and restricts + based upon the object instance type. + + + + + Binds to the Invoke method on a delegate if this is a delegate type. + + + + + Attempts to bind to an operator Call method. + + + + + Performs binding against a set of overloaded methods using the specified arguments. The arguments are + consumed as specified by the CallSignature object. + + Overload resolver. + The methods to be called + A meta object which results from the call. + + + + Performs binding against a set of overloaded methods using the specified arguments. The arguments are + consumed as specified by the CallSignature object. + + Overload resolver. + The methods to be called + The name of the method or null to use the name from targets. + A meta object which results from the call. + + + + Performs binding against a set of overloaded methods using the specified arguments. The arguments are + consumed as specified by the CallSignature object. + + Overload resolver. + The methods to be called + Additional restrictions which should be applied to the resulting MetaObject. + A meta object which results from the call. + + + + Performs binding against a set of overloaded methods using the specified arguments. The arguments are + consumed as specified by the CallSignature object. + + Overload resolver. + The methods to be called + Additional restrictions which should be applied to the resulting MetaObject. + The name of the method or null to use the name from targets. + A meta object which results from the call. + + + + Performs binding against a set of overloaded methods using the specified arguments. The arguments are + consumed as specified by the CallSignature object. + + TODO. + TODO. + Overload resolver. + The methods to be called + Additional restrictions which should be applied to the resulting MetaObject. + The resulting binding target which can be used for producing error information. + The name of the method or null to use the name from targets. + A meta object which results from the call. + + + + Makes test for param arrays and param dictionary parameters. + + + + + Pulls out the right argument to build the splat test. MakeParamsTest makes the actual test. + + + + + Builds the restrictions for calling with a splatted argument array. Ensures that the + argument is still an ICollection of object and that it has the same number of arguments. + + + + + Builds the restrictions for calling with keyword arguments. The restrictions include + tests on the individual keys of the dictionary to ensure they have the same names. + + + + + Builds a MetaObject for performing a member get. Supports all built-in .NET members, the OperatorMethod + GetBoundMember, and StrongBox instances. + + + The name of the member to retrieve. This name is not processed by the DefaultBinder and + is instead handed off to the GetMember API which can do name mangling, case insensitive lookups, etc... + + + The MetaObject from which the member is retrieved. + + + The value being assigned to the target member. + + + + + Builds a MetaObject for performing a member get. Supports all built-in .NET members, the OperatorMethod + GetBoundMember, and StrongBox instances. + + + The name of the member to retrieve. This name is not processed by the DefaultBinder and + is instead handed off to the GetMember API which can do name mangling, case insensitive lookups, etc... + + + The MetaObject from which the member is retrieved. + + + The value being assigned to the target member. + + + Provides overload resolution and method binding for any calls which need to be performed for the SetMember. + + + + + Builds a MetaObject for performing a member get. Supports all built-in .NET members, the OperatorMethod + GetBoundMember, and StrongBox instances. + + + The name of the member to retrieve. This name is not processed by the DefaultBinder and + is instead handed off to the GetMember API which can do name mangling, case insensitive lookups, etc... + + + The MetaObject from which the member is retrieved. + + + The value being assigned to the target member. + + + Provides a DynamicMetaObject that is to be used as the result if the member cannot be set. If null then then a language + specific error code is provided by ActionBinder.MakeMissingMemberErrorForAssign which can be overridden by the language. + + + + + Builds a MetaObject for performing a member get. Supports all built-in .NET members, the OperatorMethod + GetBoundMember, and StrongBox instances. + + + The name of the member to retrieve. This name is not processed by the DefaultBinder and + is instead handed off to the GetMember API which can do name mangling, case insensitive lookups, etc... + + + The MetaObject from which the member is retrieved. + + + The value being assigned to the target member. + + + Provides overload resolution and method binding for any calls which need to be performed for the SetMember. + + + Provides a DynamicMetaObject that is to be used as the result if the member cannot be set. If null then then a language + specific error code is provided by ActionBinder.MakeMissingMemberErrorForAssign which can be overridden by the language. + + + + if a member-injector is defined-on or registered-for this type call it + + + + Provides a way for the binder to provide a custom error message when lookup fails. Just + doing this for the time being until we get a more robust error return mechanism. + + + + + Called when the user is accessing a protected or private member on a get. + + The default implementation allows access to the fields or properties using reflection. + + + + + Provides a way for the binder to provide a custom error message when lookup fails. Just + doing this for the time being until we get a more robust error return mechanism. + + + + + Helper class for flowing information about the GetMember request. + + + + + Helper class for flowing information about the GetMember request. + + + + + Encapsulates information about the target of the call. This includes an implicit instance for the call, + the methods that we'll be calling as well as any restrictions required to perform the call. + + + + + A MetaObject which was produced as the result of a failed binding. + + + + + Interceptor prototype. The interceptor is a call site binder that wraps + a real call site binder and can perform arbitrary operations on the expression + trees that the wrapped binder produces: + * Dumping the trees + * Additional rewriting + * Static compilation + * ... + + + + + Returns true if the method should not be displayed in the stack frame. + + + + + Specifies the action for which the default binder is requesting a member. + + + + + If the number of items added to the builder is greater than 4 returns a read-only collection builder containing all the items. + Returns null otherwise. + + + + + Returns null if no expression was added into the builder. + If only a single expression was added returns it. + Otherwise returns a containing the expressions added to the builder. + + + + + Wrapping a tree in this node enables jumps from finally blocks + It does this by generating control-flow logic in the tree + + Reducing this node requires a full tree walk of its body + (but not nested lambdas) + + WARNING: this node cannot contain jumps across blocks, because it + assumes any unknown jumps are jumps to an outer scope. + + + + + Factory methods. + + + + + Determines whether specified expression type represents an assignment. + + + True if the expression type represents an assignment. + + + Note that some other nodes can also assign to variables, members or array items: + MemberInit, NewArrayInit, Call with ref params, New with ref params, Dynamic with ref params. + + + + + Determines if the left child of the given expression is read or written to or both. + + + + + Converts an expression to a void type. + + An to convert to void. + An that has the property equal to and the and property set to void. + + + + Returns an expression that boxes a given value. Uses boxed objects cache for Int32 and Boolean types. + + + + + Creates a generator with type IEnumerable{T}, where T is the label.Type + + + + + + + + Null coalescing expression + {result} ::= ((tmp = {_left}) == null) ? {right} : tmp + '??' operator in C#. + + + + + True coalescing expression. + {result} ::= IsTrue(tmp = {left}) ? {right} : tmp + Generalized AND semantics. + + + + + False coalescing expression. + {result} ::= IsTrue(tmp = {left}) ? tmp : {right} + Generalized OR semantics. + + + + + True coalescing expression. + {result} ::= IsTrue(tmp = {left}) ? {right} : tmp + Generalized AND semantics. + + + + + False coalescing expression. + {result} ::= IsTrue(tmp = {left}) ? tmp : {right} + Generalized OR semantics. + + + + + Wraps the given value in a WeakReference and returns a tree that will retrieve + the value from the WeakReference. + + + + + Creates new instance of the LambdaBuilder with the specified name and return type. + + Return type of the lambda being built. + Name for the lambda being built. + new LambdaBuilder instance + + + + The helper to create the AST method call node. Will add conversions (Utils.Convert) + to parameters and instance if necessary. + + + + + The helper to create the AST method call node. Will add conversions (Utils.Convert) + to parameters and instance if necessary. + + + + + The complex call helper to create the AST method call node. + Will add conversions (Expression.Convert()), deals with default parameter values and params arrays. + + + + + The purpose of this rewriter is simple: ETs do not allow jumps (break, continue, return, goto) + that would go through a finally/fault. So we replace them with code that instead stores a flag, + and then jumps to the end of the finally/fault. At the end of the try-finally, we emit a switch + that then jumps to the correct label. + + A few things that make this more complicated: + + 1. If a finally contains a jump out, then jumps in the try/catch need to be replaced as well. + It's to support cases like this: + # returns 234 + def foo(): + try: return 123 + finally: return 234 + + We need to replace the "return 123" because after it jumps, we'll go to the finally, which + might decide to jump again, but once the IL finally exits, it ignores the finally jump and + keeps going with the original jump. The moral of the story is: if any jumps in finally are + rewritten, try/catch jumps must be also. + + 2. To generate better code, we only have one state variable, so if we have to jump out of + multiple finallys we just keep jumping. It looks sort of like this: + foo: + try { ... } finally { + try { ... } finally { + ... + if (...) { + // was: goto foo; + $flow = 1; goto endInnerFinally; + } + ... + endInnerFinally: + } + switch ($flow) { + case 1: goto endOuterFinally; + } + ... + endOuterFinally: + } + switch ($flow) { + case 1: $flow = 0; goto foo; + } + ... + + + + + + Implemented by expressions which can provide a version which is aware of light exceptions. + + Normally these expressions will simply reduce to a version which throws a real exception. + When the expression is used inside of a region of code which supports light exceptions + the light exception re-writer will call ReduceForLightExceptions. The expression can + then return a new expression which can return a light exception rather than throwing + a real .NET exception. + + + + + Implemented by binders which support light exceptions. Dynamic objects + binding against a binder which implements this interface can check + SupportsLightThrow to see if the binder currently supports safely + returning a light exception. Light exceptions can be created with + LightException.Throw. + + Binders also need to implement GetlightBinder. This method + returns a new call site binder which may return light exceptions if + the binder supports them. + + + + + Gets a binder which will support light exception if one is + available. + + + + + Returns true if a callsite binding against this binder can + return light exceptions. + + + + + Provides a method call to a method which may return light exceptions. + + The call is to a method which supports light exceptions. When reducing + an additional check and throw is added. When a block code of is re-written + for light exceptions this instead reduces to not throw a .NET exception. + + + + + Expression which produces a light exception value. This should be constructed + with the expression which creates the exception and this method will then call + a helper method which wraps the exception in our internal light exception class. + + + + + Used by compilers to provide additional debug information about LambdaExpression to DebugContext + + + + + Implemented by compilers to allow the traceback engine to get additional information. + + + + + Provides services to compilers for instrumenting code with tracebacks. + + + + + Creates a new instance of DebugContext + + + + + Transforms a LambdaExpression to a debuggable LambdaExpression + + + + + Transforms a LambdaExpression to a debuggable LambdaExpression + + + + + Resets a state associated with a source file that's maintained in the DebugContext + + + + + Threads + + + + + Hook + + + + + // This method is called from the generator to update the frame with generator's locals + + + + + Remaps the frame's state to use the generator for execution. + + Int32.MaxValue to map to latest version + + + + Thread + + + + + FrameOrder + + + + + Variables + + + + + CurrentSequencePointIndex + + + + + DebuggableLambdaBuilder is used to transform a DLR expression tree into a debuggable lambda expression. + + + + + Used to wrap a lambda that was already a generator prior to transform. + + + + + Used to rewrite expressions containing DebugInfoExpressions. + + + + + Combines source file and span. Also provides Contains and Intersects functionality. + + + + + Implementation of IDebugRuntimeVariables, which wraps IRuntimeVariables + FunctionInfo/DebugMarker + + + + + IDebugRuntimeVariables is used to wrap IRuntimeVariables and add properties for retrieving + FunctionInfo and DebugMarker from debuggable labmdas. + + + + + Default implementation of BaseDebugThread, which uses DLR's RuntimeVariablesExpression for lifting locals. + + + + + Default implementation of IDebugThreadFactory, which uses DLR's RuntimeVariablesExpression for lifting locals. + + + + + IDebugThreadFactory is used to abstract how frames and local variables are maintained at run/debug time. + + + + + GetTraceLocations + + + + + + SequencePoints + + + + + Name + + + + + CustomPayload + + + + + Callback that is fired by the traceback engine + + + + + Used to extract locals information from expressions. + + + + + Strongly-typed and parameterized string factory. + + + + + Implements IRuntimeVariables in a way that preserves scoping within the lambda. + + + + + TraceSession + + + + + Used to provide information about locals/parameters at debug time. + + + + + Type + + + + + Name + + + + + Parameter + + + + + Caches type member lookup. + + + When enumerating members (methods, properties, events) of a type (declared or inherited) Reflection enumerates all + runtime members of the type and its base types and caches the result. + When looking for a member of a specific name Reflection still enumerates all and filters out those that don't match the name. + That's inefficient when looking for members of multiple names one by one. + Instead we build a map of name to member list and then answer subsequent queries by simply looking up the dictionary. + + + + + Provides services for loading XAML and binding events to dynamic language code definitions. + + + + + Loads XAML from the specified stream and returns the deserialized object. Any event handlers + are bound to methods defined in the provided Scope and converted using the provided DynamicOperations + object. + + + + + Loads XAML from the specified filename and returns the deserialized object. Any event handlers + are bound to methods defined in the provided Scope and converted using the provided DynamicOperations + object. + + + + + Loads XAML from the specified XmlReader and returns the deserialized object. Any event handlers + are bound to methods defined in the provided Scope and converted using the provided DynamicOperations + object. + + + + + Loads XAML from the specified TextReader and returns the deserialized object. Any event handlers + are bound to methods defined in the provided Scope and converted using the provided DynamicOperations + object. + + + + + Loads XAML from the specified XamlXmlReader and returns the deserialized object. Any event handlers + are bound to methods defined in the provided Scope and converted using the provided DynamicOperations + object. + + + + + Dummy, should never be called + + + + + Returns the list of x:Name'd objects that we saw and should set on the root object. + + + + + Marks a method which may return a light exception. Such + methods need to have their return value checked and the exception + will need to be thrown if the caller is not light exception aware. + + + + + Internal re-writer class which creates code which is light exception aware. + + + + + Adds light exception handling to the provided expression which + is light exception aware. + + + + + Class used to be avoid overhead of creating expression trees when we're usually + + + + + Provides support for light exceptions. These exceptions are propagated by + returning an instance of a private wrapper class containing the exception. Code + which is aware of light exceptions will branch to apporiate exception handling + blocks when in a try and otherwise return the value up the stack. This avoids + using the underlying CLR exception mechanism with overhead such as creating stack + traces. + + When a light exception reaches the boundary of code which is not light exception + aware the caller must check to see if a light exception is being thrown and if + so raise a .NET exception. + + This class provides methods for re-writing expression trees to support light exceptions, + methods to create light throw objects, check if an object is a light + throw object, and turn such an object back into a .NET Exception which can be thrown. + + Light exceptions also don't build up stack traces or interoperate with filter blocks + via 2-pass exception handling. + + + + + Rewrites the provided expression to support light exceptions. + + Calls to the returned expression, if not from other light-weight aware calls, + need to call GetLightException on return to see if an exception was thrown + and if so throw it. + + + + + Returns a new expression which will lazily reduce to a light + expression re-written version of the same expression. + + + + + Returns a new expression which is re-written for light exceptions + but will throw an exception if it escapes the expression. If this + expression is part of a larger experssion which is later re-written + for light exceptions then it will propagate the light exception up. + + + + + Returns an object which represents a light exception. + + + + + Returns an object which represents a light exception. + + + + + Returns an object which represents a light exception. + + + + + If the binder supports light exceptions then a light exception throwing expression is returned. + + Otherwise a normal throwing expression is returned. + + + + + If the binder supports light exceptions then a light exception throwing expression is returned. + + Otherwise a normal throwing expression is returned. + + + + + Throws the exception if the value represents a light exception + + + + + Wraps the expression in a check and rethrow. + + + + + Checks to see if the provided value is a light exception. + + + + + Gets the light exception from an object which may contain a light + exception. Returns null if the object is not a light exception. + + Used for throwing the exception at non-light exception boundaries. + + + + + Returns true if the call site binder is a light exception binder and supports + light throws. Returns false otherwise. + + + + + + + Sealed wrapper class to indicate something is a light exception. + + + + + Stores information needed to emit debugging symbol information for a + source file, in particular the file name and unique language identifier + + + + + The source file name + + + + + Returns the language's unique identifier, if any + + + + + Returns the language vendor's unique identifier, if any + + + + + ArgBuilder provides an argument value used by the MethodBinder. One ArgBuilder exists for each + physical parameter defined on a method. + + Contrast this with ParameterWrapper which represents the logical argument passed to the method. + + + + + Provides the Expression which provides the value to be passed to the argument. + + + + + Provides the Expression which provides the value to be passed to the argument. + This method is called when result is intended to be used ByRef. + + + + + Provides an Expression which will update the provided value after a call to the method. + May return null if no update is required. + + + + + SimpleArgBuilder produces the value produced by the user as the argument value. It + also tracks information about the original parameter and is used to create extended + methods for params arrays and param dictionary functions. + + + + + Provides the implementation of performing AddAssign and SubtractAssign binary operations. + + The binder provided by the call site. + The handler for the operation. + The result of the operation. + true if the operation is complete, false if the call site should determine behavior. + + + + Adds a handler to an event. + + The handler to be added. + The original event with handler added. + + + + Removes handler from the event. + + The handler to be removed. + The original event with handler removed. + + + + Provides helper methods to bind COM objects dynamically. + + + + + Determines if an object is a COM object. + + The object to test. + true if the object is a COM object, false otherwise. + + + + Tries to perform binding of the dynamic get member operation. + + An instance of the that represents the details of the dynamic operation. + The target of the dynamic operation. + The new representing the result of the binding. + true if member evaluation may be delayed. + true if operation was bound successfully; otherwise, false. + + + + Tries to perform binding of the dynamic get member operation. + + An instance of the that represents the details of the dynamic operation. + The target of the dynamic operation. + The new representing the result of the binding. + true if operation was bound successfully; otherwise, false. + + + + Tries to perform binding of the dynamic set member operation. + + An instance of the that represents the details of the dynamic operation. + The target of the dynamic operation. + The representing the value for the set member operation. + The new representing the result of the binding. + true if operation was bound successfully; otherwise, false. + + + + Tries to perform binding of the dynamic invoke operation. + + An instance of the that represents the details of the dynamic operation. + The target of the dynamic operation. + An array of instances - arguments to the invoke member operation. + The new representing the result of the binding. + true if operation was bound successfully; otherwise, false. + + + + Tries to perform binding of the dynamic invoke member operation. + + An instance of the that represents the details of the dynamic operation. + The target of the dynamic operation. + An array of instances - arguments to the invoke member operation. + The new representing the result of the binding. + true if operation was bound successfully; otherwise, false. + + + + Tries to perform binding of the dynamic get index operation. + + An instance of the that represents the details of the dynamic operation. + The target of the dynamic operation. + An array of instances - arguments to the invoke member operation. + The new representing the result of the binding. + true if operation was bound successfully; otherwise, false. + + + + Tries to perform binding of the dynamic set index operation. + + An instance of the that represents the details of the dynamic operation. + The target of the dynamic operation. + An array of instances - arguments to the invoke member operation. + The representing the value for the set index operation. + The new representing the result of the binding. + true if operation was bound successfully; otherwise, false. + + + + Tries to perform binding of the dynamic Convert operation. + + An instance of the that represents the details of the dynamic operation. + The target of the dynamic operation. + The new representing the result of the binding. + true if operation was bound successfully; otherwise, false. + + + + Gets the member names associated with the object. + This function can operate only with objects for which returns true. + + The object for which member names are requested. + The collection of member names. + + + + Gets the member names of the data-like members associated with the object. + This function can operate only with objects for which returns true. + + The object for which member names are requested. + The collection of member names. + + + + Gets the data-like members and associated data for an object. + This function can operate only with objects for which returns true. + + The object for which data members are requested. + The enumeration of names of data members for which to retrieve values. + The collection of pairs that represent data member's names and their data. + + + + Special binder that indicates special semantics for COM GetMember operation. + + + + + This class implements an event sink for a particular RCW. + Unlike the implementation of events in TlbImp'd assemblies, + we will create only one event sink per RCW (theoretically RCW might have + several ComEventSink evenk sinks - but all these implement different source intefaces). + Each ComEventSink contains a list of ComEventSinkMethod objects - which represent + a single method on the source interface an a multicast delegate to redirect + the calls. Notice that we are chaining multicast delegates so that same + ComEventSinkMedhod can invoke multiple event handlers). + + ComEventSink implements an IDisposable pattern to Unadvise from the connection point. + Typically, when RCW is finalized the corresponding Dispose will be triggered by + ComEventSinksContainer finalizer. Notice that lifetime of ComEventSinksContainer + is bound to the lifetime of the RCW. + + + + + Contains a methods DISPID (in a string formatted of "[DISPID=N]" + and a chained list of delegates to invoke + + + + + ComEventSinkProxy class is responsible for handling QIs for sourceIid + on instances of ComEventSink. + + Background: When a COM even sink advises to a connection point it is + supposed to hand over the dispinterface. Now, some hosts will trust + the COM client to pass the correct pointer, but some will not. + E.g. Excel's implementation of Connection Points will not cause a + QI on the pointer that has been passed, however Word will QI the + pointer to return the required interface. + + ComEventSink does not, strongly speaking, implements the interface + that it claims to implement - it is just "faking" it by using IReflect. + Thus, Word's QIs on the pointer passed to ICP::Advise would fail. To + prevent this we take advangate of RealProxy's ability of + "dressing up" like other classes and hence successfully respond to QIs + for interfaces that it does not really support( it is OK to say + "I implement this interface" for event sinks only since the common + practice is to use IDistpach.Invoke when calling into event sinks). + + + + + ComEventSinksContainer is just a regular list with a finalizer. + This list is usually attached as a custom data for RCW object and + is finalized whenever RCW is finalized. + + + + + Layout of the IDispatch vtable + + + + + Invokes the object. If it falls back, just produce an error. + + + + + Splats the arguments to another nested dynamic site, which does the + real invocation of the IDynamicMetaObjectProvider. + + + + + Create a stub for the target of the optimized lopop. + + + + + + Gets expressions to access all the arguments. This includes the instance argument. + + + + + This is a helper class for runtime-callable-wrappers of COM instances. We create one instance of this type + for every generic RCW instance. + + + + + The runtime-callable wrapper + + + + + This is the factory method to get the ComObject corresponding to an RCW + + + + + + The parameter description of a method defined in a type library + + + + + Creates a representation for the paramter of a COM method + + + + + Creates a representation for the return value of a COM method + TODO: Return values should be represented by a different type + + + + + DBNull.Value if there is no default value + + + + + Look for typeinfo using IDispatch.GetTypeInfo + + + + Some COM objects just dont expose typeinfo. In these cases, this method will return null. + Some COM objects do intend to expose typeinfo, but may not be able to do so if the type-library is not properly + registered. This will be considered as acceptable or as an error condition depending on throwIfMissingExpectedTypeInfo + + + + + This method should be called when typeinfo is not available for an object. The function + will check if the typeinfo is expected to be missing. This can include error cases where + the same error is guaranteed to happen all the time, on all machines, under all circumstances. + In such cases, we just have to operate without the typeinfo. + + However, if accessing the typeinfo is failing in a transient way, we might want to throw + an exception so that we will eagerly predictably indicate the problem. + + + + + This class contains methods that either cannot be expressed in C#, or which require writing unsafe code. + Callers of these methods need to use them extremely carefully as incorrect use could cause GC-holes + and other problems. + + + + + + Ensure that "value" is a local variable in some caller's frame. So converting + the byref to an IntPtr is a safe operation. Alternatively, we could also allow + allowed "value" to be a pinned object. + + + + + We will emit an indirect call to an unmanaged function pointer from the vtable of the given interface pointer. + This approach can take only ~300 instructions on x86 compared with ~900 for Marshal.Release. We are relying on + the JIT-compiler to do pinvoke-stub-inlining and calling the pinvoke target directly. + + + + + We will emit an indirect call to an unmanaged function pointer from the vtable of the given IDispatch interface pointer. + It is not possible to express this in C#. Using an indirect pinvoke call allows us to do our own marshalling. + We can allocate the Variant arguments cheaply on the stack. We are relying on the JIT-compiler to do + pinvoke-stub-inlining and calling the pinvoke target directly. + The alternative of calling via a managed interface declaration of IDispatch would have a performance + penalty of going through a CLR stub that would have to re-push the arguments on the stack, etc. + Marshal.GetDelegateForFunctionPointer could be used here, but its too expensive (~2000 instructions on x86). + + + + + Cached information from a TLB. Only information that is required is saved. CoClasses are used + for event hookup. Enums are stored for accessing symbolic names from scripts. + + + + + Reads the latest registered type library for the corresponding GUID, + reads definitions of CoClass'es and Enum's from this library + and creates a IDynamicMetaObjectProvider that allows to instantiate coclasses + and get actual values for the enums. + + Type Library Guid + ComTypeLibDesc object + + + + Gets an ITypeLib object from OLE Automation compatible RCW , + reads definitions of CoClass'es and Enum's from this library + and creates a IDynamicMetaObjectProvider that allows to instantiate coclasses + and get actual values for the enums. + + OLE automation compatible RCW + ComTypeLibDesc object + + + + This represents a bound dispmember on a IDispatch object. + + + + + Strongly-typed and parameterized string factory. + + + Strongly-typed and parameterized string factory. + + + + + A string like "Unexpected VarEnum {0}." + + + + + A string like "Error while invoking {0}." + + + + + A string like "Error while invoking {0}." + + + + + A string like "Error while invoking {0}. Named arguments are not supported." + + + + + A string like "Error while invoking {0}." + + + + + A string like "Could not convert argument {0} for call to {1}." + + + + + A string like "Error while invoking {0}. A required parameter was omitted." + + + + + A string like "IDispatch::GetIDsOfNames behaved unexpectedly for {0}." + + + + + A string like "Could not get dispatch ID for {0} (error: {1})." + + + + + A string like "There are valid conversions from {0} to {1}." + + + + + A string like "Variant.GetAccessor cannot handle {0}." + + + + + A string like "Cannot access member {1} declared on type {0} because the type contains generic parameters." + + + + + A string like "Type '{0}' is missing or cannot be loaded." + + + + + A string like "static property "{0}" of "{1}" can only be read through a type, not an instance" + + + + + A string like "static property "{0}" of "{1}" can only be assigned to through a type, not an instance" + + + + + A string like "Type parameter is {0}. Expected a delegate." + + + + + A string like "Cannot cast from type '{0}' to type '{1}" + + + + + A string like "unknown member type: '{0}'. " + + + + + A string like "The operation requires a non-generic type for {0}, but this represents generic types only" + + + + + A string like "Invalid operation: '{0}'" + + + + + A string like "Cannot create default value for type {0}." + + + + + A string like "Unhandled convert: {0}" + + + + + A string like "{0}.{1} has no publiclly visible method." + + + + + A string like "Extension type {0} must be public." + + + + + A string like "Invalid type of argument {0}; expecting {1}." + + + + + A string like "Field {0} is read-only" + + + + + A string like "Property {0} is read-only" + + + + + A string like "Expected event from {0}.{1}, got event from {2}.{3}." + + + + + A string like "expected bound event, got {0}." + + + + + A string like "Expected type {0}, got {1}." + + + + + A string like "can only write to member {0}." + + + + + A string like "Invalid stream type: {0}." + + + + + A string like "can't add another casing for identifier {0}" + + + + + A string like "can't add new identifier {0}" + + + + + A string like "Type '{0}' doesn't provide a suitable public constructor or its implementation is faulty: {1}" + + + + + A string like "Cannot emit constant {0} ({1})" + + + + + A string like "No implicit cast from {0} to {1}" + + + + + A string like "No explicit cast from {0} to {1}" + + + + + A string like "name '{0}' not defined" + + + + + A string like "Cannot create instance of {0} because it contains generic parameters" + + + + + A string like "Non-verifiable assembly generated: {0}:\nAssembly preserved as {1}\nError text:\n{2}\n" + + + + + A string like "COM object is expected." + + + + + A string like "Cannot perform call." + + + + + A string like "COM object does not support events." + + + + + A string like "COM object does not support specified source interface." + + + + + A string like "Marshal.SetComObjectData failed." + + + + + A string like "This method exists only to keep the compiler happy." + + + + + A string like "ResolveComReference.CannotRetrieveTypeInformation." + + + + + A string like "Attempting to wrap an unsupported enum type." + + + + + A string like "Attempting to pass an event handler of an unsupported type." + + + + + A string like "Method precondition violated" + + + + + A string like "Invalid argument value" + + + + + A string like "Non-empty string required" + + + + + A string like "Non-empty collection required" + + + + + A string like "must by an Exception instance" + + + + + A string like "Type of test must be bool" + + + + + A string like "Type of the expression must be bool" + + + + + A string like "Empty string is not a valid path." + + + + + A string like "Invalid delegate type (Invoke method not found)." + + + + + A string like "expected only static property" + + + + + A string like "Property doesn't exist on the provided type" + + + + + A string like "Field doesn't exist on provided type" + + + + + A string like "Type doesn't have constructor with a given signature" + + + + + A string like "Type doesn't have a method with a given name." + + + + + A string like "Type doesn't have a method with a given name and signature." + + + + + A string like "Count must be non-negative." + + + + + A string like "arrayType must be an array type" + + + + + A string like "Either code or target must be specified." + + + + + A string like "RuleBuilder can only be used with delegates whose first argument is CallSite." + + + + + A string like "no instance for call." + + + + + A string like "Missing Test." + + + + + A string like "Missing Target." + + + + + A string like "Finally already defined." + + + + + A string like "Can not have fault and finally." + + + + + A string like "Fault already defined." + + + + + A string like "Global/top-level local variable names must be unique." + + + + + A string like "Generating code from non-serializable CallSiteBinder." + + + + + A string like "pecified path is invalid." + + + + + A string like "Dictionaries are not hashable." + + + + + A string like "language already registered." + + + + + A string like "The method or operation is not implemented." + + + + + A string like "No exception." + + + + + A string like "Already initialized." + + + + + A string like "CreateScopeExtension must return a scope extension." + + + + + A string like "Invalid number of parameters for the service." + + + + + A string like "Cannot change non-caching value." + + + + + A string like "No code to compile." + + + + + A string like "Queue empty." + + + + + A string like "Enumeration has not started. Call MoveNext." + + + + + A string like "Enumeration already finished." + + + + + A string like "Invalid output directory." + + + + + A string like "Invalid assembly name or file extension." + + + + + A string like "No default value for a given type." + + + + + A string like "Specified language provider type is not registered." + + + + + A string like "can't read from property" + + + + + A string like "can't write to property" + + + + + Strongly-typed and parameterized exception factory. + + + Strongly-typed and parameterized exception factory. + + + + + ArgumentException with message like "COM object does not support events." + + + + + ArgumentException with message like "COM object does not support specified source interface." + + + + + InvalidOperationException with message like "Marshal.SetComObjectData failed." + + + + + InvalidOperationException with message like "This method exists only to keep the compiler happy." + + + + + InvalidOperationException with message like "Unexpected VarEnum {0}." + + + + + System.Reflection.TargetParameterCountException with message like "Error while invoking {0}." + + + + + MissingMemberException with message like "Error while invoking {0}." + + + + + ArgumentException with message like "Error while invoking {0}. Named arguments are not supported." + + + + + OverflowException with message like "Error while invoking {0}." + + + + + ArgumentException with message like "Could not convert argument {0} for call to {1}." + + + + + ArgumentException with message like "Error while invoking {0}. A required parameter was omitted." + + + + + InvalidOperationException with message like "ResolveComReference.CannotRetrieveTypeInformation." + + + + + ArgumentException with message like "IDispatch::GetIDsOfNames behaved unexpectedly for {0}." + + + + + InvalidOperationException with message like "Attempting to wrap an unsupported enum type." + + + + + InvalidOperationException with message like "Attempting to pass an event handler of an unsupported type." + + + + + MissingMemberException with message like "Could not get dispatch ID for {0} (error: {1})." + + + + + System.Reflection.AmbiguousMatchException with message like "There are valid conversions from {0} to {1}." + + + + + NotImplementedException with message like "Variant.GetAccessor cannot handle {0}." + + + + + ArgumentException with message like "Either code or target must be specified." + + + + + InvalidOperationException with message like "Type parameter is {0}. Expected a delegate." + + + + + InvalidOperationException with message like "Cannot cast from type '{0}' to type '{1}" + + + + + InvalidOperationException with message like "unknown member type: '{0}'. " + + + + + InvalidOperationException with message like "RuleBuilder can only be used with delegates whose first argument is CallSite." + + + + + InvalidOperationException with message like "no instance for call." + + + + + InvalidOperationException with message like "Missing Test." + + + + + InvalidOperationException with message like "Missing Target." + + + + + TypeLoadException with message like "The operation requires a non-generic type for {0}, but this represents generic types only" + + + + + ArgumentException with message like "Invalid operation: '{0}'" + + + + + InvalidOperationException with message like "Finally already defined." + + + + + InvalidOperationException with message like "Can not have fault and finally." + + + + + InvalidOperationException with message like "Fault already defined." + + + + + ArgumentException with message like "Cannot create default value for type {0}." + + + + + ArgumentException with message like "Unhandled convert: {0}" + + + + + InvalidOperationException with message like "{0}.{1} has no publiclly visible method." + + + + + ArgumentException with message like "Global/top-level local variable names must be unique." + + + + + ArgumentException with message like "Generating code from non-serializable CallSiteBinder." + + + + + ArgumentException with message like "pecified path is invalid." + + + + + ArgumentTypeException with message like "Dictionaries are not hashable." + + + + + InvalidOperationException with message like "language already registered." + + + + + NotImplementedException with message like "The method or operation is not implemented." + + + + + InvalidOperationException with message like "No exception." + + + + + ArgumentException with message like "Extension type {0} must be public." + + + + + InvalidOperationException with message like "Already initialized." + + + + + InvalidImplementationException with message like "CreateScopeExtension must return a scope extension." + + + + + ArgumentException with message like "Invalid number of parameters for the service." + + + + + ArgumentException with message like "Invalid type of argument {0}; expecting {1}." + + + + + ArgumentException with message like "Cannot change non-caching value." + + + + + MissingMemberException with message like "Field {0} is read-only" + + + + + MissingMemberException with message like "Property {0} is read-only" + + + + + ArgumentException with message like "Expected event from {0}.{1}, got event from {2}.{3}." + + + + + ArgumentTypeException with message like "expected bound event, got {0}." + + + + + ArgumentTypeException with message like "Expected type {0}, got {1}." + + + + + MemberAccessException with message like "can only write to member {0}." + + + + + InvalidOperationException with message like "No code to compile." + + + + + ArgumentException with message like "Invalid stream type: {0}." + + + + + InvalidOperationException with message like "Queue empty." + + + + + InvalidOperationException with message like "Enumeration has not started. Call MoveNext." + + + + + InvalidOperationException with message like "Enumeration already finished." + + + + + InvalidOperationException with message like "can't add another casing for identifier {0}" + + + + + InvalidOperationException with message like "can't add new identifier {0}" + + + + + ArgumentException with message like "Invalid output directory." + + + + + ArgumentException with message like "Invalid assembly name or file extension." + + + + + ArgumentException with message like "Cannot emit constant {0} ({1})" + + + + + ArgumentException with message like "No implicit cast from {0} to {1}" + + + + + ArgumentException with message like "No explicit cast from {0} to {1}" + + + + + MissingMemberException with message like "name '{0}' not defined" + + + + + ArgumentException with message like "No default value for a given type." + + + + + ArgumentException with message like "Specified language provider type is not registered." + + + + + InvalidOperationException with message like "can't read from property" + + + + + InvalidOperationException with message like "can't write to property" + + + + + ArgumentException with message like "Cannot create instance of {0} because it contains generic parameters" + + + + + System.Security.VerificationException with message like "Non-verifiable assembly generated: {0}:\nAssembly preserved as {1}\nError text:\n{2}\n" + + + + + This is similar to ComTypes.EXCEPINFO, but lets us do our own custom marshaling + + + + + An object that implements IDispatch + + This currently has the following issues: + 1. If we prefer ComObjectWithTypeInfo over IDispatchComObject, then we will often not + IDispatchComObject since implementations of IDispatch often rely on a registered type library. + If we prefer IDispatchComObject over ComObjectWithTypeInfo, users get a non-ideal experience. + 2. IDispatch cannot distinguish between properties and methods with 0 arguments (and non-0 + default arguments?). So obj.foo() is ambiguous as it could mean invoking method foo, + or it could mean invoking the function pointer returned by property foo. + We are attempting to find whether we need to call a method or a property by examining + the ITypeInfo associated with the IDispatch. ITypeInfo tell's use what parameters the method + expects, is it a method or a property, what is the default property of the object, how to + create an enumerator for collections etc. + 3. IronPython processes the signature and converts ref arguments into return values. + However, since the signature of a DispMethod is not available beforehand, this conversion + is not possible. There could be other signature conversions that may be affected. How does + VB6 deal with ref arguments and IDispatch? + + We also support events for IDispatch objects: + Background: + COM objects support events through a mechanism known as Connect Points. + Connection Points are separate objects created off the actual COM + object (this is to prevent circular references between event sink + and event source). When clients want to sink events generated by + COM object they would implement callback interfaces (aka source + interfaces) and hand it over (advise) to the Connection Point. + + Implementation details: + When IDispatchComObject.TryGetMember request is received we first check + whether the requested member is a property or a method. If this check + fails we will try to determine whether an event is requested. To do + so we will do the following set of steps: + 1. Verify the COM object implements IConnectionPointContainer + 2. Attempt to find COM object's coclass's description + a. Query the object for IProvideClassInfo interface. Go to 3, if found + b. From object's IDispatch retrieve primary interface description + c. Scan coclasses declared in object's type library. + d. Find coclass implementing this particular primary interface + 3. Scan coclass for all its source interfaces. + 4. Check whether to any of the methods on the source interfaces matches + the request name + + Once we determine that TryGetMember requests an event we will return + an instance of BoundDispEvent class. This class has InPlaceAdd and + InPlaceSubtract operators defined. Calling InPlaceAdd operator will: + 1. An instance of ComEventSinksContainer class is created (unless + RCW already had one). This instance is hanged off the RCW in attempt + to bind the lifetime of event sinks to the lifetime of the RCW itself, + meaning event sink will be collected once the RCW is collected (this + is the same way event sinks lifetime is controlled by PIAs). + Notice: ComEventSinksContainer contains a Finalizer which will go and + unadvise all event sinks. + Notice: ComEventSinksContainer is a list of ComEventSink objects. + 2. Unless we have already created a ComEventSink for the required + source interface, we will create and advise a new ComEventSink. Each + ComEventSink implements a single source interface that COM object + supports. + 3. ComEventSink contains a map between method DISPIDs to the + multicast delegate that will be invoked when the event is raised. + 4. ComEventSink implements IReflect interface which is exposed as + custom IDispatch to COM consumers. This allows us to intercept calls + to IDispatch.Invoke and apply custom logic - in particular we will + just find and invoke the multicast delegate corresponding to the invoked + dispid. + + + + + ArgBuilder which always produces null. + + + + + If a managed user type (as opposed to a primitive type or a COM object) is passed as an argument to a COM call, we need + to determine the VarEnum type we will marshal it as. We have the following options: + 1. Raise an exception. Languages with their own version of primitive types would not be able to call + COM methods using the language's types (for eg. strings in IronRuby are not System.String). An explicit + cast would be needed. + 2. We could marshal it as VT_DISPATCH. Then COM code will be able to access all the APIs in a late-bound manner, + but old COM components will probably malfunction if they expect a primitive type. + 3. We could guess which primitive type is the closest match. This will make COM components be as easily + accessible as .NET methods. + 4. We could use the type library to check what the expected type is. However, the type library may not be available. + + VarEnumSelector implements option # 3 + + + + + Gets the managed type that an object needs to be coverted to in order for it to be able + to be represented as a Variant. + + In general, there is a many-to-many mapping between Type and VarEnum. However, this method + returns a simple mapping that is needed for the current implementation. The reason for the + many-to-many relation is: + 1. Int32 maps to VT_I4 as well as VT_ERROR, and Decimal maps to VT_DECIMAL and VT_CY. However, + this changes if you throw the wrapper types into the mix. + 2. There is no Type to represent COM types. __ComObject is a private type, and Object is too + general. + + + + + Creates a family of COM types such that within each family, there is a completely non-lossy + conversion from a type to an earlier type in the family. + + + + + Get the (one representative type for each) primitive type families that the argument can be converted to + + + + + If there is more than one type family that the argument can be converted to, we will throw a + AmbiguousMatchException instead of randomly picking a winner. + + + + + Is there a unique primitive type that has the best conversion for the argument + + + + + Get the COM Variant type that argument should be marshaled as for a call to COM + + + + + Variant is the basic COM type for late-binding. It can contain any other COM data type. + This type definition precisely matches the unmanaged data layout so that the struct can be passed + to and from COM calls. + + + + + Primitive types are the basic COM types. It includes valuetypes like ints, but also reference types + like BStrs. It does not include composite types like arrays and user-defined COM types (IUnknown/IDispatch). + + + + + Get the managed object representing the Variant. + + + + + + Release any unmanaged memory associated with the Variant + + + + + + VariantBuilder handles packaging of arguments into a Variant for a call to IDispatch.Invoke + + + + + Provides a simple expression which enables embedding FieldBuilder's + in an AST before the type is complete. + + + + + Used to dispatch a single interactive command. It can be used to control things like which Thread + the command is executed on, how long the command is allowed to execute, etc + + + + + Supports detecting the remote runtime being killed, and starting up a new one. + + Threading model: + + ConsoleRestartManager creates a separate thread on which to create and execute the consoles. + There are usually atleast three threads involved: + + 1. Main app thread: Instantiates ConsoleRestartManager and accesses its APIs. This thread has to stay + responsive to user input and so the ConsoleRestartManager APIs cannot be long-running or blocking. + Since the remote runtime process can terminate asynchronously, the current RemoteConsoleHost can + change at any time (if auto-restart is enabled). The app should typically not care which instance of + RemoteConsoleHost is currently being used. The flowchart of this thread is: + Create ConsoleRestartManager + ConsoleRestartManager.Start + Loop: + Respond to user input | Send user input to console for execution | BreakExecution | RestartConsole | GetMemberNames + ConsoleRestartManager.Terminate + TODO: Currently, BreakExecution and GetMemberNames are called by the main thread synchronously. + Since they execute code in the remote runtime, they could take arbitrarily long. We should change + this so that the main app thread can never be blocked indefinitely. + + 2. Console thread: Dedicated thread for creating RemoteConsoleHosts and executing code (which could + take a long time or block indefinitely). + Wait for ConsoleRestartManager.Start to be called + Loop: + Create RemoteConsoleHost + Wait for signal for: + Execute code | RestartConsole | Process.Exited + + 3. CompletionPort async callbacks: + Process.Exited | Process.OutputDataReceived | Process.ErrorDataReceived + + 4. Finalizer thred + Some objects may have a Finalize method (which possibly calls Dispose). Not many (if any) types + should have a Finalize method. + + + + + + Accessing _remoteConsoleHost from a thread other than console thread can result in race. + If _remoteConsoleHost is accessed while holding _accessLock, it is guaranteed to be + null or non-disposed. + + + + + This is created on the "creating thread", and goes on standby. Start needs to be called for activation. + + A host might want one of two behaviors: + 1. Keep the REPL loop alive indefinitely, even when a specific instance of the RemoteConsoleHost terminates normally + 2. Close the REPL loop when an instance of the RemoteConsoleHost terminates normally, and restart the loop + only if the instance terminates abnormally. + + + + Needs to be called for activation. + + + + + Request (from another thread) the console REPL loop to terminate + + + + + This allows the RemoteConsoleHost to abort a long-running operation. The RemoteConsoleHost itself + does not know which ThreadPool thread might be processing the remote call, and so it needs + cooperation from the remote runtime server. + + + + + Since OnOutputDataReceived is sent async, it can arrive late. The remote console + cannot know if all output from the current command has been received. So + RemoteCommandDispatcher writes out a marker to indicate the end of the output + + + + + Aborts the current active call to Execute by doing Thread.Abort + + true if a Thread.Abort was actually called. false if there is no active call to Execute + + + + Customize the CommandLine for remote scenarios + + + + + Command line hosting service. + + + + + Executes the comand line - depending upon the options provided we will + either run a single file, a single command, or enter the interactive loop. + + + + + Runs the command line. Languages can override this to provide custom behavior other than: + 1. Running a single command + 2. Running a file + 3. Entering the interactive console loop. + + + + + + Runs the specified filename + + + + + Starts the interactive loop. Performs any initialization necessary before + starting the loop and then calls RunInteractiveLoop to start the loop. + + Returns the exit code when the interactive loop is completed. + + + + + Runs the interactive loop. Repeatedly parse and run interactive actions + until an exit code is received. If any exceptions are unhandled displays + them to the console + + + + + Attempts to run a single interaction and handle any language-specific + exceptions. Base classes can override this and call the base implementation + surrounded with their own exception handling. + + Returns null if successful and execution should continue, or an exit code. + + + + + Parses a single interactive command or a set of statements and executes it. + + Returns null if successful and execution should continue, or the appropiate exit code. + + We check if the code read is an interactive command or statements is by checking for NewLine + If the code contains NewLine, it's a set of statements (most probably from SendToConsole) + If the code does not contain a NewLine, it's an interactive command typed by the user at the prompt + + + + + Private helper function to see if we should treat the current input as a blank link. + + We do this if we only have auto-indent text. + + + + + Read a statement, which can potentially be a multiple-line statement suite (like a class declaration). + + Should the console session continue, or did the user indicate + that it should be terminated? + Expression to evaluate. null for empty input + + + + Gets the next level for auto-indentation + + + + + Scope is not remotable, and this only works in the same AppDomain. + + + + + CommandDispatcher to ensure synchronize output from the remote runtime + + + + + ConsoleHost where the ScriptRuntime is hosted in a separate process (referred to as the remote runtime server) + + The RemoteConsoleHost spawns the remote runtime server and specifies an IPC channel name to use to communicate + with each other. The remote runtime server creates and initializes a ScriptRuntime and a ScriptEngine, and publishes + it over the specified IPC channel at a well-known URI. Note that the RemoteConsoleHost cannot easily participate + in the initialization of the ScriptEngine as classes like LanguageContext are not remotable. + + The RemoteConsoleHost then starts the interactive loop and executes commands on the ScriptEngine over the remoting channel. + The RemoteConsoleHost listens to stdout of the remote runtime server and echos it locally to the user. + + + + + Core functionality to implement an interactive console. This should be derived for concrete implementations + + + + + Request (from another thread) the console REPL loop to terminate + + The caller can specify the exitCode corresponding to the event triggering + the termination. This will be returned from CommandLine.Run + + + + To be called from entry point. + + + + + Console Host entry-point .exe name. + + + + + Allows the console to customize the environment variables, working directory, etc. + + At the least, processInfo.FileName should be initialized + + + + Aborts the current active call to Execute by doing Thread.Abort + + true if a Thread.Abort was actually called. false if there is no active call to Execute + + + + Called if the remote runtime process exits by itself. ie. without the remote console killing it. + + + + + The remote runtime server uses this class to publish an initialized ScriptEngine and ScriptRuntime + over a remoting channel. + + + + + Publish objects so that the host can use it, and then block indefinitely (until the input stream is open). + + Note that we should publish only one object, and then have other objects be accessible from it. Publishing + multiple objects can cause problems if the client does a call like "remoteProxy1(remoteProxy2)" as remoting + will not be able to know if the server object for both the proxies is on the same server. + + The IPC channel that the remote console expects to use to communicate with the ScriptEngine + A intialized ScriptScope that is ready to start processing script commands + + + Instruction can't be created due to insufficient privileges. + + + Instruction can't be created due to insufficient privileges. + + + + Gets the next type or null if no more types are available. + + + + + Uses reflection to create new instance of the appropriate ReflectedCaller + + + + + Fast creation works if we have a known primitive types for the entire + method siganture. If we have any non-primitive types then FastCreate + falls back to SlowCreate which works for all types. + + Fast creation is fast because it avoids using reflection (MakeGenericType + and Activator.CreateInstance) to create the types. It does this through + calling a series of generic methods picking up each strong type of the + signature along the way. When it runs out of types it news up the + appropriate CallInstruction with the strong-types that have been built up. + + One relaxation is that for return types which are non-primitive types + we can fallback to object due to relaxed delegates. + + + + + The number of arguments including "this" for instance methods. + + + + + This instruction implements a goto expression that can jump out of any expression. + It pops values (arguments) from the evaluation stack that the expression tree nodes in between + the goto expression and the target label node pushed and not consumed yet. + A goto expression can jump into a node that evaluates arguments only if it carries + a value and jumps right after the first argument (the carried value will be used as the first argument). + Goto can jump into an arbitrary child of a BlockExpression since the block doesn’t accumulate values + on evaluation stack as its child expressions are being evaluated. + + Goto needs to execute any finally blocks on the way to the target label. + + { + f(1, 2, try { g(3, 4, try { goto L } finally { ... }, 6) } finally { ... }, 7, 8) + L: ... + } + + The goto expression here jumps to label L while having 4 items on evaluation stack (1, 2, 3 and 4). + The jump needs to execute both finally blocks, the first one on stack level 4 the + second one on stack level 2. So, it needs to jump the first finally block, pop 2 items from the stack, + run second finally block and pop another 2 items from the stack and set instruction pointer to label L. + + Goto also needs to rethrow ThreadAbortException iff it jumps out of a catch handler and + the current thread is in "abort requested" state. + + + + + The first instruction of finally block. + + + + + The last instruction of finally block. + + + + + The last instruction of a catch exception handler. + + + + + The last instruction of a fault exception handler. + + + + + Implements dynamic call site with many arguments. Wraps the arguments into . + + + + + Contains compiler state corresponding to a LabelTarget + See also LabelScopeInfo. + + + + + Returns true if we can jump into this node + + + + + Attaches a cookie to the last emitted instruction. + + + + Instruction can't be created due to insufficient privileges. + + + + Manages creation of interpreted delegates. These delegates will get + compiled if they are executed often enough. + + + + + Used by LightLambda to get the compiled delegate. + + + + + Create a compiled delegate for the LightLambda, and saves it so + future calls to Run will execute the compiled code instead of + interpreting. + + + + + true if the compiled delegate has the same type as the lambda; + false if the type was changed for interpretation. + + + + + Provides notification that the LightLambda has been compiled. + + + + + A simple forth-style stack machine for executing Expression trees + without the need to compile to IL and then invoke the JIT. This trades + off much faster compilation time for a slower execution performance. + For code that is only run a small number of times this can be a + sweet spot. + + The core loop in the interpreter is the RunInstructions method. + + + + + Runs instructions within the given frame. + + + Interpreted stack frames are linked via Parent reference so that each CLR frame of this method corresponds + to an interpreted stack frame in the chain. It is therefore possible to combine CLR stack traces with + interpreted stack traces by aligning interpreted frames to the frames of this method. + Each group of subsequent frames of Run method corresponds to a single interpreted frame. + + + + + Visits a LambdaExpression, replacing the constants with direct accesses + to their StrongBox fields. This is very similar to what + ExpressionQuoter does for LambdaCompiler. + + Also inserts debug information tracking similar to what the interpreter + would do. + + + + + Local variable mapping. + + + + + The variable that holds onto the StrongBox{object}[] closure from + the interpreter + + + + + A stack of variables that are defined in nested scopes. We search + this first when resolving a variable in case a nested scope shadows + one of our variable instances. + + + + + Walks the lambda and produces a higher order function, which can be + used to bind the lambda to a closure array from the interpreter. + + The lambda to bind. + Variables which are being accessed defined in the outer scope. + A delegate that can be called to produce a delegate bound to the passed in closure array. + + + + Provides a list of variables, supporing read/write of the values + + + + + Gets a copy of the local variables which are defined in the current scope. + + + + + + Checks to see if the given variable is defined within the current local scope. + + + + + Gets the variables which are defined in an outer scope and available within the current scope. + + + + + Tracks where a variable is defined and what range of instructions it's used in + + + + + A single interpreted frame might be represented by multiple subsequent Interpreter.Run CLR frames. + This method filters out the duplicate CLR frames. + + + + + arbitrary precision integers + + + + + Calculates the natural logarithm of the BigInteger. + + + + + Calculates log base 10 of a BigInteger. + + + + + Return the value of this BigInteger as a little-endian twos-complement + byte array, using the fewest number of bytes possible. If the value is zero, + return an array of one byte whose element is 0x00. + + + + + Return the sign of this BigInteger: -1, 0, or 1. + + + + + Wraps all arguments passed to a dynamic site with more arguments than can be accepted by a Func/Action delegate. + The binder generating a rule for such a site should unwrap the arguments first and then perform a binding to them. + + + + + Provides support for converting objects to delegates using the DLR binders + available by the provided language context. + + Primarily this supports converting objects implementing IDynamicMetaObjectProvider + to the appropriate delegate type. + + If the provided object is already a delegate of the appropriate type then the + delegate will simply be returned. + + + + Table of dynamically generated delegates which are shared based upon method signature. + + + + Creates a delegate with a given signature that could be used to invoke this object from non-dynamic code (w/o code context). + A stub is created that makes appropriate conversions/boxing and calls the object. + The stub should be executed within a context of this object's language. + + The converted delegate. + The object is either a subclass of Delegate but not the requested type or does not implement IDynamicMetaObjectProvider. + + + + Represents the type of a null value. + + + + + Private constructor is never called since 'null' is the only valid instance. + + + + + These are some generally useful helper methods. Currently the only methods are those to + cached boxed representations of commonly used primitive types so that they can be shared. + This is useful to most dynamic languages that use object as a universal type. + + The methods in RuntimeHelepers are caleld by the generated code. From here the methods may + dispatch to other parts of the runtime to get bulk of the work done, but the entry points + should be here. + + + + + Used by prologue code that is injected in lambdas to ensure that delegate signature matches what + lambda body expects. Such code typically unwraps subset of the params array manually, + but then passes the rest in bulk if lambda body also expects params array. + + This calls ArrayUtils.ShiftLeft, but performs additional checks that + ArrayUtils.ShiftLeft assumes. + + + + + A singleton boxed boolean true. + + + + + A singleton boxed boolean false. + + + + + Gets a singleton boxed value for the given integer if possible, otherwise boxes the integer. + + The value to box. + The boxed value. + + + + Helper method to create an instance. Work around for Silverlight where Activator.CreateInstance + is SecuritySafeCritical. + + TODO: Why can't we just emit the right thing for default(T)? + It's always null for reference types and it's well defined for value types + + + + + EventInfo.EventHandlerType getter is marked SecuritySafeCritical in CoreCLR + This method is to get to the property without using Reflection + + + + + + + Provides the test to see if an interpreted call site should switch over to being compiled. + + + + + A parameterless generator, that is of type IEnumerable, IEnumerable{T}, + IEnumerator, or IEnumerator{T}. Its body can contain a series of + YieldExpressions. Each call into MoveNext on the enumerator reenters + the generator, and executes until it reaches a YieldReturn or YieldBreak + expression + + + + + The label used by YieldBreak and YieldReturn expressions to yield + from this generator + + + + + The body of the generator, which can contain YieldBreak and + YieldReturn expressions + + + + + Indicates whether the lhs instances are preserved when assignments + are made to expressions containing yields. + + + + + When finding a yield return or yield break, this rewriter flattens out + containing blocks, scopes, and expressions with stack state. All + scopes encountered have their variables promoted to the generator's + closure, so they survive yields. + + + + + Makes an assignment to this variable. Pushes the assignment as far + into the right side as possible, to allow jumps into it. + + + + + Returns true if the expression remains constant no matter when it is evaluated. + + + + + Represents either a YieldBreak or YieldReturn in a GeneratorExpression + If Value is non-null, it's a YieldReturn; otherwise it's a YieldBreak + and executing it will stop enumeration of the generator, causing + MoveNext to return false. + + + + + The value yieled from this expression, if it is a yield return + + + + + The label used to yield from this generator + + + + + Tests to see if the expression is a constant with the given value. + + The expression to examine + The constant value to check for. + true/false + + + + Tests to see if the expression is a constant with the given value. + + The expression to examine + The constant value to check for. + true/false + + + + Begins a catch block. + + + + + Begins an exception block for a filtered exception. + + + + + Begins an exception block for a non-filtered exception. + + + + + + Begins an exception fault block + + + + + Begins a finally block + + + + + Ends an exception block. + + + + + Begins a lexical scope. + + + + + Ends a lexical scope. + + + + + Declares a local variable of the specified type. + + + + + Declares a local variable of the specified type, optionally + pinning the object referred to by the variable. + + + + + Declares a new label. + + + + + Marks the label at the current position. + + + + + Emits an instruction. + + + + + Emits an instruction with a byte argument. + + + + + Emits an instruction with the metadata token for the specified contructor. + + + + + Emits an instruction with a double argument. + + + + + Emits an instruction with the metadata token for the specified field. + + + + + Emits an instruction with a float argument. + + + + + Emits an instruction with an int argument. + + + + + Emits an instruction with a label argument. + + + + + Emits an instruction with multiple target labels (switch). + + + + + Emits an instruction with a reference to a local variable. + + + + + Emits an instruction with a long argument. + + + + + Emits an instruction with the metadata token for a specified method. + + + + + Emits an instruction with a signed byte argument. + + + + + Emits an instruction with a short argument. + + + + + Emits an instruction with a signature token. + + + + + Emits an instruction with a string argument. + + + + + Emits an instruction with the metadata token for a specified type argument. + + + + + Emits a call or a virtual call to the varargs method. + + + + + Emits an unmanaged indirect call instruction. + + + + + Emits a managed indirect call instruction. + + + + + Marks a sequence point. + + + + + Specifies the namespace to be used in evaluating locals and watches for the + current active lexical scope. + + + + + Emits a Ldind* instruction for the appropriate type + + + + + Emits a Stind* instruction for the appropriate type. + + + + + Emits a Stelem* instruction for the appropriate type. + + + + + Boxes the value of the stack. No-op for reference types. Void is + converted to a null reference. For almost all value types this + method will box them in the standard way. Int32 and Boolean are + handled with optimized conversions that reuse the same object for + small values. For Int32 this is purely a performance optimization. + For Boolean this is use to ensure that True and False are always + the same objects. + + + + + Emits an array of constant values provided in the given list. + The array is strongly typed. + + + + + Emits an array of values of count size. The items are emitted via the callback + which is provided with the current item index to emit. + + + + + Emits an array construction code. + The code assumes that bounds for all dimensions + are already emitted. + + + + + Emits default(T) + Semantics match C# compiler behavior + + + + + A simple dictionary of queues, keyed off a particular type + This is useful for storing free lists of variables + + + + + Directory where snippet assembly will be saved if SaveSnippets is set. + + + + + Save snippets to an assembly (see also SnippetsDirectory, SnippetsFileName). + + + + + Gets the Compiler associated with the Type Initializer (cctor) creating it if necessary. + + + + + A tree rewriter which will find dynamic sites which consume dynamic sites and + turn them into a single combo dynamic site. The combo dynamic site will then run the + individual meta binders and produce the resulting code in a single dynamic site. + + + + + A reducible node which we use to generate the combo dynamic sites. Each time we encounter + a dynamic site we replace it with a ComboDynamicSiteExpression. When a child of a dynamic site + turns out to be a ComboDynamicSiteExpression we will then merge the child with the parent updating + the binding mapping info. If any of the inputs cause side effects then we'll stop the combination. + + + + + A binder which can combine multiple binders into a single dynamic site. The creator + of this needs to perform the mapping of parameters, constants, and sub-site expressions + and provide a List of BinderMappingInfo representing this data. From there the ComboBinder + just processes the list to create the resulting code. + + + + + Provides a mapping for inputs of combo action expressions. The input can map + to either an input of the new dynamic site, an input of a previous DynamicExpression, + or a ConstantExpression which has been pulled out of the dynamic site arguments. + + + + + Contains the mapping information for a single Combo Binder. This includes the original + meta-binder and the mapping of parameters, sub-sites, and constants into the binding. + + + + + Builds up a series of conditionals when the False clause isn't yet known. We can + keep appending conditions and if true's. Each subsequent true branch becomes the + false branch of the previous condition and body. Finally a non-conditional terminating + branch must be added. + + + + + Adds a new conditional and body. The first call this becomes the top-level + conditional, subsequent calls will have it added as false statement of the + previous conditional. + + + + + Adds the non-conditional terminating node. + + + + + Adds the non-conditional terminating node. + + + + + Gets the resulting meta object for the full body. FinishCondition + must have been called. + + + + + Adds a variable which will be scoped at the level of the final expression. + + + + + Marks a method as not having side effects. used by the combo binder + to allow calls to methods. + + + + + OperatorInfo provides a mapping from DLR ExpressionType to their associated .NET methods. + + + + + Given an operator returns the OperatorInfo associated with the operator or null + + + + + The operator the OperatorInfo provides info for. + + + + + The primary method name associated with the method. This method name is + usally in the form of op_Operator (e.g. op_Addition). + + + + + The secondary method name associated with the method. This method name is + usually a standard .NET method name with pascal casing (e.g. Add). + + + + + The builder for creating the LambdaExpression node. + + Since the nodes require that parameters and variables are created + before hand and then passed to the factories creating LambdaExpression + this builder keeps track of the different pieces and at the end creates + the LambdaExpression. + + TODO: This has some functionality related to CodeContext that should be + removed, in favor of languages handling their own local scopes + + + + + Creates a parameter on the lambda with a given name and type. + + Parameters maintain the order in which they are created, + however custom ordering is possible via direct access to + Parameters collection. + + + + + Creates a parameter on the lambda with a given name and type. + + Parameters maintain the order in which they are created, + however custom ordering is possible via direct access to + Parameters collection. + + + + + adds existing parameter to the lambda. + + Parameters maintain the order in which they are created, + however custom ordering is possible via direct access to + Parameters collection. + + + + + Creates a hidden parameter on the lambda with a given name and type. + + Parameters maintain the order in which they are created, + however custom ordering is possible via direct access to + Parameters collection. + + + + + Creates a params array argument on the labmda. + + The params array argument is added to the signature immediately. Before the lambda is + created, the builder validates that it is still the last (since the caller can modify + the order of parameters explicitly by maniuplating the parameter list) + + + + + Creates a local variable with specified name and type. + TODO: simplify by pushing logic into callers + + + + + Creates a local variable with specified name and type. + TODO: simplify by pushing logic into callers + + + + + Creates a temporary variable with specified name and type. + + + + + Adds the temporary variable to the list of variables maintained + by the builder. This is useful in cases where the variable is + created outside of the builder. + + + + + Creates the LambdaExpression from the builder. + After this operation, the builder can no longer be used to create other instances. + + Desired type of the lambda. + New LambdaExpression instance. + + + + Creates the LambdaExpression from the builder. + After this operation, the builder can no longer be used to create other instances. + + New LambdaExpression instance. + + + + Creates the generator LambdaExpression from the builder. + After this operation, the builder can no longer be used to create other instances. + + New LambdaExpression instance. + + + + Fixes up lambda body and parameters to match the signature of the given delegate if needed. + + + + + + Validates that the builder has enough information to create the lambda. + + + + + The name of the lambda. + Currently anonymous/unnamed lambdas are not allowed. + + + + + Return type of the lambda being created. + + + + + List of lambda's local variables for direct manipulation. + + + + + List of lambda's parameters for direct manipulation + + + + + The params array argument, if any. + + + + + The body of the lambda. This must be non-null. + + + + + The generated lambda should have dictionary of locals + instead of allocating them directly on the CLR stack. + + + + + The scope is visible (default). Invisible if false. + + + + + marks a field, class, or struct as being safe to have statics which can be accessed + from multiple runtimes. + + Static fields which are not read-only or marked with this attribute will be flagged + by a test which looks for state being shared between runtimes. Before applying this + attribute you should ensure that it is safe to share the state. This is typically + state which is lazy initialized or state which is caching values which are identical + in all runtimes and are immutable. + + + + + This class is useful for quickly collecting performance counts for expensive + operations. Usually this means operations involving either reflection or + code gen. Long-term we need to see if this can be plugged better into the + standard performance counter architecture. + + + + + temporary categories for quick investigation, use a custom key if you + need to track multiple items, and if you want to keep it then create + a new Categories entry and rename all your temporary entries. + + + + + Represents the context that is flowed for doing Compiler. Languages can derive + from this class to provide additional contextual information. + + + + + Source unit currently being compiled in the CompilerContext + + + + + Current error sink. + + + + + Sink for parser callbacks (e.g. brace matching, etc.). + + + + + Compiler specific options. + + + + + Indicates that a DynamicMetaObject might be convertible to a CLR type. + + + + + Gets custom data to be serialized when saving script codes to disk. + + + + + Indicates that a MetaObject is already representing a restricted type. Useful + when we're already restricted to a known type but this isn't captured in + the type info (e.g. the type is not sealed). + + + + + Returns Microsoft.Scripting.Runtime.DynamicNull if the object contains a null value, + otherwise, returns self.LimitType + + + + + Returns Microsoft.Scripting.Runtime.DynamicNull if the object contains a null value, + otherwise, returns self.RuntimeType + + + + + ScriptCode is an instance of compiled code that is bound to a specific LanguageContext + but not a specific ScriptScope. The code can be re-executed multiple times in different + scopes. Hosting API counterpart for this class is CompiledCode. + + + + + This takes an assembly name including extension and saves the provided ScriptCode objects into the assembly. + + The provided script codes can constitute code from multiple languages. The assemblyName can be either a fully qualified + or a relative path. The DLR will simply save the assembly to the desired location. The assembly is created by the DLR and + if a file already exists than an exception is raised. + + The DLR determines the internal format of the ScriptCode and the DLR can feel free to rev this as appropriate. + + + + + This will take an assembly object which the user has loaded and return a new set of ScriptCode’s which have + been loaded into the provided ScriptDomainManager. + + If the language associated with the ScriptCode’s has not already been loaded the DLR will load the + LanguageContext into the ScriptDomainManager based upon the saved LanguageContext type. + + If the LanguageContext or the version of the DLR the language was compiled against is unavailable a + TypeLoadException will be raised unless policy has been applied by the administrator to redirect bindings. + + + + + Sets the current position inside current token or one character behind it. + + + + + Sets the current position inside current token or one character behind it. + A relative displacement with respect to the current position in the token is specified. + + + + + Marks token end. Enables to read the current token. + + + + + Marks token start. It means the buffer can drop the current token. + Can be called even if no token has been read yet. + + + + + Reads till the end of line and returns the character that stopped the reading. + The returned character is not skipped. + + + + + Resizes an array to a speficied new size and copies a portion of the original array into its beginning. + + + + + Helper class to remove methods w/ identical signatures. Used for GetDefaultMembers + which returns members from all types in the hierarchy. + + + + + Handles input and output for the console. It is comparable to System.IO.TextReader, + System.IO.TextWriter, System.Console, etc + + + + + Read a single line of interactive input, or a block of multi-line statements. + + An event-driven GUI console can implement this method by creating a thread that + blocks and waits for an event indicating that input is available + + The indentation level to be used for the current suite of a compound statement. + The console can ignore this argument if it does not want to support auto-indentation + null if the input stream has been closed. A string with a command to execute otherwise. + It can be a multi-line string which should be processed as block of statements + + + + + + + + name == null means that the argument doesn't specify an option; the value contains the entire argument + name == "" means that the option name is empty (argument separator); the value is null then + + + + + Literal script command given using -c option + + + + + Filename to execute passed on the command line options. + + + + + Only print the version of the script interpreter and exit + + + + On error. + + + + The console input buffer. + + + + + Current position - index into the input buffer + + + + + The number of white-spaces displayed for the auto-indenation of the current line + + + + + Length of the output currently rendered on screen. + + + + + Command history + + + + + Tab options available in current context + + + + + Cursort anchor - position of cursor when the routine was called + + + + + The command line that this console is attached to. + + + + + Displays the next option in the option list, + or beeps if no options available for current input prefix. + If no input prefix, simply print tab. + + + + + + + Handle the enter key. Adds the current input (if not empty) to the history. + + + The input string. + + + + Class managing the command history. + + + + + List of available options + + + + + Cursor position management + + + + + Beginning position of the cursor - top coordinate. + + + + + Beginning position of the cursor - left coordinate. + + + + + Implementation of the complex number data type. + + + + + Helper methods that calls are generated to from the default DLR binders. + + + + + Helper function to combine an object array with a sequence of additional parameters that has been splatted for a function call. + + + + + EventInfo.EventHandlerType getter is marked SecuritySafeCritical in CoreCLR + This method is to get to the property without using Reflection + + + + + + + Implements explicit casts supported by the runtime. + + + Implements explicit casts supported by the runtime. + + + + + Explicitly casts the object to a given type (and returns it as object) + + + + + Used as the value for the ScriptingRuntimeHelpers.GetDelegate method caching system + + + + + Generates stub to receive the CLR call and then call the dynamic language code. + + + + + Used as the key for the LanguageContext.GetDelegate method caching system + + + + + A useful interface for taking slices of numeric arrays, inspired by Python's Slice objects. + + + + + The starting index of the slice or null if no first index defined + + + + + The ending index of the slice or null if no ending index defined + + + + + The length of step to take + + + + + Given an ID returns the object associated with that ID. + + + + + Gets a unique ID for an object + + + + + Goes over the hashtable and removes empty entries + + + + + Weak-ref wrapper caches the weak reference, our hash code, and the object ID. + + + + + WrapperComparer treats Wrapper as transparent envelope + + + + + Internal class which binds a LanguageContext, StreamContentProvider, and Encoding together to produce + a TextContentProvider which reads binary data with the correct language semantics. + + + + + Creates a dictionary of locals in this scope + + + + + Abstract base class used for optimized thread-safe dictionaries which have a set + of pre-defined string keys. + + Implementers derive from this class and override the GetExtraKeys, TrySetExtraValue, + and TryGetExtraValue methods. When looking up a value first the extra keys will be + searched using the optimized Try*ExtraValue functions. If the value isn't found there + then the value is stored in the underlying .NET dictionary. + + This dictionary can store object values in addition to string values. It also supports + null keys. + + + + + Gets a list of the extra keys that are cached by the the optimized implementation + of the module. + + + + + Try to set the extra value and return true if the specified key was found in the + list of extra values. + + + + + Try to get the extra value and returns true if the specified key was found in the + list of extra values. Returns true even if the value is Uninitialized. + + + + + Efficiently tracks (line,column) information as text is added, and + collects line mappings between the original and generated source code + so we can generate correct debugging information later + + + + + Marks the current position of the writer as corresponding to the + original location passed in + + the line pragma corresponding to the + current position in the generated code + + + + Provides a dictionary-like object used for caches which holds onto a maximum + number of elements specified at construction time. + + This class is not thread safe. + + + + + Creates a dictionary-like object used for caches. + + The maximum number of elements to store. + + + + Tries to get the value associated with 'key', returning true if it's found and + false if it's not present. + + + + + Adds a new element to the cache, replacing and moving it to the front if the + element is already present. + + + + + Returns the value associated with the given key, or throws KeyNotFoundException + if the key is not present. + + + + + Wraps the provided enumerable into a ReadOnlyCollection{T} + + Copies all of the data into a new array, so the data can't be + changed after creation. The exception is if the enumerable is + already a ReadOnlyCollection{T}, in which case we just return it. + + + + + List optimized for few writes and multiple reads. It provides thread-safe read and write access. + Iteration is not thread-safe by default, but GetCopyForRead allows for iteration + without taking a lock. + + + + + Gets a copy of the contents of the list. The copy will not change even if the original + CopyOnWriteList object is modified. This method should be used to iterate the list in + a thread-safe way if no lock is taken. Iterating on the original list is not guaranteed + to be thread-safe. + + The returned copy should not be modified by the caller. + + + + Returns the list of expressions represented by the instances. + + An array of instances to extract expressions from. + The array of expressions. + + + + Creates an instance of for a runtime value and the expression that represents it during the binding process. + + The runtime value to be represented by the . + An expression to represent this during the binding process. + The new instance of . + + + + Produces an interpreted binding using the given binder which falls over to a compiled + binding after hitCount tries. + + This method should be called whenever an interpreted binding is required. Sometimes it will + return a compiled binding if a previous binding was produced and it's hit count was exhausted. + In this case the binder will not be called back for a new binding - the previous one will + be used. + + The delegate type being used for the call site + The binder used for the call site + The number of calls before the binder should switch to a compiled mode. + The arguments that are passed for the binding (as received in a BindDelegate call) + A delegate which represents the interpreted binding. + + + + Expression which reduces to the normal test but under the interpreter adds a count down + check which enables compiling when the count down is reached. + + + + + Base class for storing information about the binding that a specific rule is applicable for. + + We have a derived generic class but this class enables us to refer to it w/o having the + generic type information around. + + This class tracks both the count down to when we should compile. When we compile we + take the Expression[T] that was used before and compile it. While this is happening + we continue to allow the interpreted code to run. When the compilation is complete we + store a thread static which tells us what binding failed and the current rule is no + longer functional. Finally the language binder will call us again and we'll retrieve + and return the compiled overload. + + + + + A hybrid dictionary which compares based upon object identity. + + + + + Calculates the quotient of two 32-bit signed integers rounded towards negative infinity. + + Dividend. + Divisor. + The quotient of the specified numbers rounded towards negative infinity, or (int)Floor((double)x/(double)y). + is 0. + The caller must check for overflow (x = Int32.MinValue, y = -1) + + + + Calculates the quotient of two 32-bit signed integers rounded towards negative infinity. + + Dividend. + Divisor. + The quotient of the specified numbers rounded towards negative infinity, or (int)Floor((double)x/(double)y). + is 0. + The caller must check for overflow (x = Int64.MinValue, y = -1) + + + + Calculates the remainder of floor division of two 32-bit signed integers. + + Dividend. + Divisor. + The remainder of of floor division of the specified numbers, or x - (int)Floor((double)x/(double)y) * y. + is 0. + + + + Calculates the remainder of floor division of two 32-bit signed integers. + + Dividend. + Divisor. + The remainder of of floor division of the specified numbers, or x - (int)Floor((double)x/(double)y) * y. + is 0. + + + + Behaves like Math.Round(value, MidpointRounding.AwayFromZero) + Needed because CoreCLR doesn't support this particular overload of Math.Round + + + + + Behaves like Math.Round(value, precision, MidpointRounding.AwayFromZero) + However, it works correctly on negative precisions and cases where precision is + outside of the [-15, 15] range. + + (This function is also needed because CoreCLR lacks this overload.) + + + + + Evaluates a polynomial in v0 where the coefficients are ordered in increasing degree + + + + + Evaluates a polynomial in v0 where the coefficients are ordered in increasing degree + if reverse is false, and increasing degree if reverse is true. + + + + + A numerically precise version of sin(v0 * pi) + + + + + A numerically precise version of |sin(v0 * pi)| + + + + + Take the quotient of the 2 polynomials forming the Lanczos approximation + with N=13 and G=13.144565 + + + + + Computes the Gamma function on positive values, using the Lanczos approximation. + Lanczos parameters are N=13 and G=13.144565. + + + + + Computes the Log-Gamma function on positive values, using the Lanczos approximation. + Lanczos parameters are N=13 and G=13.144565. + + + + + Thread safe dictionary that allows lazy-creation where readers will block for + the creation of the lazily created value. Call GetOrCreateValue w/ a key + and a callback function. If the value exists it is returned, if not the create + callback is called (w/o any locks held). The create call back will only be called + once for each key. + + + + + Helper class which stores the published value + + + + + Dictionary[TKey, TValue] is not thread-safe in the face of concurrent reads and writes. SynchronizedDictionary + provides a thread-safe implementation. It holds onto a Dictionary[TKey, TValue] instead of inheriting from + it so that users who need to do manual synchronization can access the underlying Dictionary[TKey, TValue]. + + + + + This returns the raw unsynchronized Dictionary[TKey, TValue]. Users are responsible for locking + on it before accessing it. Also, it should not be arbitrarily handed out to other code since deadlocks + can be caused if other code incorrectly locks on it. + + + + + Provides fast strongly typed thread local storage. This is significantly faster than + Thread.GetData/SetData. + + + + + True if the caller will guarantee that all cleanup happens as the thread + unwinds. + + This is typically used in a case where the thread local is surrounded by + a try/finally block. The try block pushes some state, the finally block + restores the previous state. Therefore when the thread exits the thread + local is back to it's original state. This allows the ThreadLocal object + to not check the current owning thread on retrieval. + + + + + Gets the current value if its not == null or calls the provided function + to create a new value. + + + + + Calls the provided update function with the current value and + replaces the current value with the result of the function. + + + + + Replaces the current value with a new one and returns the old value. + + + + + Gets the StorageInfo for the current thread. + + + + + Called when the fast path storage lookup fails. if we encountered the Empty storage + during the initial fast check then spin until we hit non-empty storage and try the fast + path again. + + + + + Creates the StorageInfo for the thread when one isn't already present. + + + + + Gets or sets the value for the current thread. + + + + + Helper class for storing the value. We need to track if a ManagedThreadId + has been re-used so we also store the thread which owns the value. + + + + + Returns a numerical code of the size of a type. All types get both a horizontal + and vertical code. Types that are lower in both dimensions have implicit conversions + to types that are higher in both dimensions. + + + + + Represents an array that has value equality. + + + + + Simple class for tracking a list of items and enumerating over them. + The items are stored in weak references; if the objects are collected, + they will not be seen when enumerating. + + The type of the collection element. + + + + Similar to Dictionary[TKey,TValue], but it also ensures that the keys will not be kept alive + if the only reference is from this collection. The value will be kept alive as long as the key + is alive. + + This currently has a limitation that the caller is responsible for ensuring that an object used as + a key is not also used as a value in *any* instance of a WeakHash. Otherwise, it will result in the + object being kept alive forever. This effectively means that the owner of the WeakHash should be the + only one who has access to the object used as a value. + + Currently, there is also no guarantee of how long the values will be kept alive even after the keys + get collected. This could be fixed by triggerring CheckCleanup() to be called on every garbage-collection + by having a dummy watch-dog object with a finalizer which calls CheckCleanup(). + + + + + Check if any of the keys have gotten collected + + Currently, there is also no guarantee of how long the values will be kept alive even after the keys + get collected. This could be fixed by triggerring CheckCleanup() to be called on every garbage-collection + by having a dummy watch-dog object with a finalizer which calls CheckCleanup(). + + + + + This class holds onto internal debugging options used in this assembly. + These options can be set via environment variables DLR_{option-name}. + Boolean options map "true" to true and other values to false. + + These options are for internal debugging only, and should not be + exposed through any public APIs. + + + + + Sets the value at the given index for a tuple of the given size. This set supports + walking through nested tuples to get the correct final index. + + + + + Gets the value at the given index for a tuple of the given size. This get + supports walking through nested tuples to get the correct final index. + + + + + Gets the unbound generic Tuple type which has at lease size slots or null if a large enough tuple is not available. + + + + + Creates a generic tuple with the specified types. + + If the number of slots fits within the maximum tuple size then we simply + create a single tuple. If it's greater then we create nested tuples + (e.g. a Tuple`2 which contains a Tuple`128 and a Tuple`8 if we had a size of 136). + + + + + Gets the number of usable slots in the provided Tuple type including slots available in nested tuples. + + + + + Creates a new instance of tupleType with the specified args. If the tuple is a nested + tuple the values are added in their nested forms. + + + + + Gets the values from a tuple including unpacking nested values. + + + + + Gets the series of properties that needs to be accessed to access a logical item in a potentially nested tuple. + + + + + Gets the series of properties that needs to be accessed to access a logical item in a potentially nested tuple. + + + + + Provides an expression for creating a tuple with the specified values. + + + + + TODO: Alternatively, it should be sufficient to remember indices for this, list, dict and block. + + + + + Convention for an individual argument at a callsite. + + Multiple different callsites can match against a single declaration. + Some argument kinds can be "unrolled" into multiple arguments, such as list and dictionary. + + + + + Simple unnamed positional argument. + In Python: foo(1,2,3) are all simple arguments. + + + + + Argument with associated name at the callsite + In Python: foo(a=1) + + + + + Argument containing a list of arguments. + In Python: foo(*(1,2*2,3)) would match 'def foo(a,b,c)' with 3 declared arguments such that (a,b,c)=(1,4,3). + it could also match 'def foo(*l)' with 1 declared argument such that l=(1,4,3) + + + + + Argument containing a dictionary of named arguments. + In Python: foo(**{'a':1, 'b':2}) + + + + + Represents a logical member of a type. The member could either be real concrete member on a type or + an extension member. + + This seperates the "physical" members that .NET knows exist on types from the members that + logically exist on a type. It also provides other abstractions above the level of .NET reflection + such as MemberGroups and NamespaceTracker's. + + It also provides a wrapper around the reflection APIs which cannot be extended from partial trust. + + + + + Gets the expression that creates the value. + + Returns null if it's an error to get the value. The caller can then call GetErrorForGet to get + the correct error Expression (or null if they should provide a default). + + + + + Gets an expression that assigns a value to the left hand side. + + Returns null if it's an error to assign to. The caller can then call GetErrorForSet to + get the correct error Expression (or null if a default error should be provided). + + + + + Gets an expression that assigns a value to the left hand side. + + Returns null if it's an error to assign to. The caller can then call GetErrorForSet to + get the correct error Expression (or null if a default error should be provided). + + + + + Gets an expression that performs a call on the object using the specified arguments. + + Returns null if it's an error to perform the specific operation. The caller can then call + GetErrorsForDoCall to get the correct error Expression (or null if a default error should be provided). + + + + + Returns the error associated with getting the value. + + A null return value indicates that the default error message should be provided by the caller. + + + + + Returns the error associated with accessing this member via a bound instance. + + A null return value indicates that the default error message should be provided by the caller. + + + + + Helper for getting values that have been bound. Called from BoundMemberTracker. Custom member + trackers can override this to provide their own behaviors when bound to an instance. + + + + + Helper for setting values that have been bound. Called from BoundMemberTracker. Custom member + trackers can override this to provide their own behaviors when bound to an instance. + + + + + Helper for setting values that have been bound. Called from BoundMemberTracker. Custom member + trackers can override this to provide their own behaviors when bound to an instance. + + + + + Binds the member tracker to the specified instance rturning a new member tracker if binding + is possible. If binding is not possible the existing member tracker will be returned. For example + binding to a static field results in returning the original MemberTracker. Binding to an instance + field results in a new BoundMemberTracker which will get GetBoundValue/SetBoundValue to pass the + instance through. + + + + + The type of member tracker. + + + + + The logical declaring type of the member. + + + + + The name of the member. + + + + + We ensure we only produce one MemberTracker for each member which logically lives on the declaring type. So + for example if you get a member from a derived class which is declared on the base class it should be the same + as getting the member from the base class. That’s easy enough until you get into extension members – here there + might be one extension member which is being applied to multiple types. Therefore we need to take into account the + extension type when ensuring that we only have 1 MemberTracker ever created. + + + + + Richly represents the signature of a callsite. + + + + + Array of additional meta information about the arguments, such as named arguments. + Null for a simple signature that's just an expression list. eg: foo(a*b,c,d) + + + + + Number of arguments in the signature. + + + + + True if the OldCallAction includes an ArgumentInfo of ArgumentKind.Dictionary or ArgumentKind.Named. + + + + + Gets the number of positional arguments the user provided at the call site. + + + + + All arguments are unnamed and matched by position. + + + + + A custom member tracker which enables languages to plug in arbitrary + members into the lookup process. + + + + + Encapsulates information about the result that should be produced when + a OldDynamicAction cannot be performed. The ErrorInfo can hold one of: + an expression which creates an Exception to be thrown + an expression which produces a value which should be returned + directly to the user and represents an error has occured (for + example undefined in JavaScript) + an expression which produces a value which should be returned + directly to the user but does not actually represent an error. + + ErrorInfo's are produced by an ActionBinder in response to a failed + binding. + + + + + Private constructor - consumers must use static From* factories + to create ErrorInfo objects. + + + + + Creates a new ErrorInfo which represents an exception that should + be thrown. + + + + + Creates a new ErrorInfo which represents a value which should be + returned to the user. + + + + + Crates a new ErrorInfo which represents a value which should be returned + to the user but does not represent an error. + + + + + + + The ErrorInfo expression produces an exception + + + + + The ErrorInfo expression produces a value which represents the error (e.g. undefined) + + + + + The ErrorInfo expression produces a value which is not an error + + + + + Gets the stub list for a COM Object. For COM objects we store the stub list + directly on the object using the Marshal APIs. This allows us to not have + any circular references to deal with via weak references which are challenging + in the face of COM. + + + + + Doesn't need to check PrivateBinding setting: no method that is part of the event is public the entire event is private. + If the code has already a reference to the event tracker instance for a private event its "static-ness" is not influenced + by private-binding setting. + + + + + Holds on a list of delegates hooked to the event. + We need the list because we cannot enumerate the delegates hooked to CLR event and we need to do so in + handler removal (we need to do custom delegate comparison there). If BCL enables the enumeration we could remove this. + + + + + Storage for the handlers - a key value pair of the callable object and the delegate handler. + + + + + Storage for the handlers - a key value pair of the callable object and the delegate handler. + + The delegate handler is closed over the callable object. Therefore as long as the object is alive the + delegate will stay alive and so will the callable object. That means it's fine to have a weak reference + to both of these objects. + + + + + Represents extension method. + + + + + The declaring type of the extension (the type this extension method extends) + + + + + The declaring type of the extension method. Since this is an extension method, + the declaring type is in fact the type this extension method extends, + not Method.DeclaringType + + + + + Represents a logical Property as a member of a Type. This Property can either be a real + concrete Property on a type (implemented with a ReflectedPropertyTracker) or an extension + property (implemented with an ExtensionPropertyTracker). + + + + + MemberGroups are a collection of MemberTrackers which are commonly produced + on-demand to talk about the available members. They can consist of a mix of + different member types or multiple membes of the same type. + + The most common source of MemberGroups is from ActionBinder.GetMember. From here + the DLR will perform binding to the MemberTrackers frequently producing the value + resulted from the user. If the result of the action produces a member it's self + the ActionBinder can provide the value exposed to the user via ReturnMemberTracker. + + ActionBinder provides default functionality for both getting members from a type + as well as exposing the members to the user. Getting members from the type maps + closely to reflection and exposing them to the user exposes the MemberTrackers + directly. + + + + + MethodGroup's represent a unique collection of method's. Typically this + unique set is all the methods which are overloaded by the same name including + methods with different arity. These methods represent a single logically + overloaded element of a .NET type. + + The base DLR binders will produce MethodGroup's when provided with a MemberGroup + which contains only methods. The MethodGroup's will be unique instances per + each unique group of methods. + + + + + Returns a BuiltinFunction bound to the provided type arguments. Returns null if the binding + cannot be performed. + + + + + NamespaceTracker represent a CLS namespace. + + + + + Provides a list of all the members of an instance. + + + + + Loads all the types from all assemblies that contribute to the current namespace (but not child namespaces) + + + + + Populates the tree with nodes for each part of the namespace + + + Full namespace name. It can be null (for top-level types) + + + + + As a fallback, so if the type does exist in any assembly. This would happen if a new type was added + that was not in the hardcoded list of types. + This code is not accurate because: + 1. We dont deal with generic types (TypeCollision). + 2. Previous calls to GetCustomMemberNames (eg. "from foo import *" in Python) would not have included this type. + 3. This does not deal with new namespaces added to the assembly + + + + + This stores all the public non-nested type names in a single namespace and from a single assembly. + This allows inspection of the namespace without eagerly loading all the types. Eagerly loading + types slows down startup, increases working set, and is semantically incorrect as it can trigger + TypeLoadExceptions sooner than required. + + + + + Enables implicit Type to TypeTracker conversions accross dynamic languages. + + + + + Represents the top reflected package which contains extra information such as + all the assemblies loaded and the built-in modules. + + + + + returns the package associated with the specified namespace and + updates the associated module to mark the package as imported. + + + + + Ensures that the assembly is loaded + + + true if the assembly was loaded for the first time. + false if the assembly had already been loaded before + + + + When an (interop) assembly is loaded, we scan it to discover the GUIDs of COM interfaces so that we can + associate the type definition with COM objects with that GUID. + Since scanning all loaded assemblies can be expensive, in the future, we might consider a more explicit + user binder to trigger scanning of COM types. + + + + Specifies that the member is a constructor, representing a ConstructorTracker + + + Specifies that the member is an event, representing a EventTracker + + + Specifies that the member is a field, representing a FieldTracker + + + Specifies that the member is a method, representing a MethodTracker + + + Specifies that the member is a property, representing a PropertyTracker + + + Specifies that the member is a property, representing a TypeTracker + + + Specifies that the member is a namespace, representing a NamespaceTracker + + + Specifies that the member is a group of method overloads, representing a MethodGroup + + + Specifies that the member is a group of types that very by arity, representing a TypeGroup + + + Specifies that the member is a custom meber, represetning a CustomTracker + + + Specifies that the member is a bound to an instance, representing a BoundMemberTracker + + + + A TypeCollision is used when we have a collision between + two types with the same name. Currently this is only possible w/ generic + methods that should logically have arity as a portion of their name. For eg: + System.EventHandler and System.EventHandler[T] + System.Nullable and System.Nullable[T] + System.IComparable and System.IComparable[T] + + The TypeCollision provides an indexer but also is a real type. When used + as a real type it is the non-generic form of the type. + + The indexer allows the user to disambiguate between the generic and + non-generic versions. Therefore users must always provide additional + information to get the generic version. + + + + The merged list so far. Could be null + The new type(s) to add to the merged list + The merged list. Could be a TypeTracker or TypeGroup + + + Gets the arity of generic parameters + + + No non-generic type is represented by this group. + + + + This returns the DeclaringType of all the types in the TypeGroup + + + + + This returns the base name of the TypeGroup (the name shared by all types minus arity) + + + + + This will return the result only for the non-generic type if one exists, and will throw + an exception if all types in the TypeGroup are generic + + + + + This will return the result only for the non-generic type if one exists, and will throw + an exception if all types in the TypeGroup are generic + + + + + True if the MethodBase is method which is going to construct an object + + + + + Returns the System.Type for any object, including null. The type of null + is represented by None.Type and all other objects just return the + result of Object.GetType + + + + + Simply returns a Type[] from calling GetType on each element of args. + + + + + EMITTED + Used by default method binder to check types of splatted arguments. + + + + + Given a MethodInfo which may be declared on a non-public type this attempts to + return a MethodInfo which will dispatch to the original MethodInfo but is declared + on a public type. + + Returns the original method if the method if a public version cannot be found. + + + + + Non-public types can have public members that we find when calling type.GetMember(...). This + filters out the non-visible members by attempting to resolve them to the correct visible type. + + If no correct visible type can be found then the member is not visible and we won't call it. + + + + + Sees if two MemberInfos point to the same underlying construct in IL. This + ignores the ReflectedType property which exists on MemberInfos which + causes direct comparisons to be false even if they are the same member. + + + + + Returns a value which indicates failure when a OldConvertToAction of ImplicitTry or + ExplicitTry. + + + + + Creates an interpreted delegate for the lambda. + + The lambda to compile. + A delegate which can interpret the lambda. + + + + Creates an interpreted delegate for the lambda. + + The lambda to compile. + The number of iterations before the interpreter starts compiling + A delegate which can interpret the lambda. + + + + Creates an interpreted delegate for the lambda. + + The lambda's delegate type. + The lambda to compile. + A delegate which can interpret the lambda. + + + + Creates an interpreted delegate for the lambda. + + The lambda to compile. + The number of iterations before the interpreter starts compiling + A delegate which can interpret the lambda. + + + + Compiles the lambda into a method definition. + + the lambda to compile + A which will be used to hold the lambda's IL. + A parameter that indicates if debugging information should be emitted to a PDB symbol store. + + + + Compiles the LambdaExpression. + + If the lambda is compiled with emitDebugSymbols, it will be + generated into a TypeBuilder. Otherwise, this method is the same as + calling LambdaExpression.Compile() + + This is a workaround for a CLR limitiation: DynamicMethods cannot + have debugging information. + + the lambda to compile + true to generate a debuggable method, false otherwise + the compiled delegate + + + + Compiles the LambdaExpression, emitting it into a new type, and + optionally making it debuggable. + + This is a workaround for a CLR limitiation: DynamicMethods cannot + have debugging information. + + the lambda to compile + Debugging information generator used by the compiler to mark sequence points and annotate local variables. + True if debug symbols (PDBs) are emitted by the . + the compiled delegate + + + + Reduces the provided DynamicExpression into site.Target(site, *args). + + + + + Removes all live objects and places them in static fields of a type. + + + + + Enables an object to be serializable to an Expression tree. The expression tree can then + be emitted into an assembly enabling the de-serialization of the object. + + + + + Serializes constants and dynamic sites so the code can be saved to disk + + + + + The MethodBinder will perform normal method binding. + + + + + The MethodBinder will return the languages definition of NotImplemented if the arguments are + incompatible with the signature. + + + + + The MethodBinder will set properties/fields for unused keyword arguments on the instance + that gets returned from the method. + + + + + The delegate representing the DLR Main function + + + + + An attribute that is applied to saved ScriptCode's to be used to re-create the ScriptCode + from disk. + + + + + Gets names stored in optimized scope. + + + + + Provides a mechanism for providing documentation stored in an assembly as metadata. + + Applying this attribute will enable documentation to be provided to the user at run-time + even if XML Documentation files are unavailable. + + + + + Updates an exception before it's getting re-thrown so + we can present a reasonable stack trace to the user. + + + + + Returns all the stack traces associates with an exception + + + + + Marks a class in the assembly as being an extension type for another type. + + + + + Marks a type in the assembly as being an extension type for another type. + + The type which is being extended + The type which provides the extension members. + + + + The type which contains extension members which are added to the type being extended. + + + + + The type which is being extended by the extension type. + + + + + Not all .NET enumerators throw exceptions if accessed in an invalid state. This type + can be used to throw exceptions from enumerators implemented in IronPython. + + + + + Event args for when a ScriptScope has had its contents changed. + + + + + Creates a new ModuleChangeEventArgs object with the specified name and type. + + + + + Creates a nwe ModuleChangeEventArgs with the specified name, type, and changed value. + + + + + Gets the name of the symbol that has changed. + + + + + Gets the way in which the symbol has changed: Set or Delete. + + + + + The the symbol has been set provides the new value. + + + + + The way in which a module has changed : Set or Delete + + + + + A new value has been set in the module (or a previous value has changed). + + + + + A value has been removed from the module. + + + + + A NullTextContentProvider to be provided when we have a pre-compiled ScriptCode which doesn't + have source code associated with it. + + + + + Singleton instance returned from an operator method when the operator method cannot provide a value. + + + + + Represents an ops-extension method which is added as an operator. + + The name must be a well-formed name such as "Add" that matches the CLS + naming conventions for adding overloads associated with op_* methods. + + + + + Represents an ops-extension method which is used to implement a property. + + + + + Provides a cache of reflection members. Only one set of values is ever handed out per a + specific request. + + + + + TODO: Make me private again + + + + + Indicates an extension method should be added as a static method, not a instance method. + + + + + Converts a generic ICollection of T into an array of T. + + If the collection is already an array of T the original collection is returned. + + + + + Converts a generic ICollection of T into an array of R using a given conversion. + + If the collection is already an array of R the original collection is returned. + + + + + Allows wrapping of proxy types (like COM RCWs) to expose their IEnumerable functionality + which is supported after casting to IEnumerable, even though Reflection will not indicate + IEnumerable as a supported interface + + + + + Requires the specified index to point inside the array. + + Array is null. + Index is outside the array. + + + + Requires the specified index to point inside the array. + + Index is outside the array. + + + + Requires the specified index to point inside the array or at the end + + Array is null. + Index is outside the array. + + + + Requires the specified index to point inside the array or at the end + + Array is null. + Index is outside the array. + + + + Requires the range [offset, offset + count] to be a subset of [0, array.Count]. + + Offset or count are out of range. + + + + Requires the range [offset, offset + count] to be a subset of [0, array.Count]. + + Offset or count are out of range. + + + + Requires the range [offset, offset + count] to be a subset of [0, array.Count]. + + Array is null. + Offset or count are out of range. + + + + Requires the range [offset, offset + count] to be a subset of [0, array.Count]. + + String is null. + Offset or count are out of range. + + + + Requires the array and all its items to be non-null. + + + + + Requires the enumerable collection and all its items to be non-null. + + + + + Presents a flat enumerable view of multiple dictionaries + + + + + Seeks the first character of a specified line in the text stream. + + The reader. + Line number. The current position is assumed to be line #1. + + Returns true if the line is found, false otherwise. + + + + + Reads characters to a string until end position or a terminator is reached. + Doesn't include the terminator into the resulting string. + Returns null, if the reader is at the end position. + + + + + Reads characters until end position or a terminator is reached. + Returns true if the character has been found (the reader is positioned right behind the character), + false otherwise. + + + + + Creates an open delegate for the given (dynamic)method. + + + + + Creates a closed delegate for the given (dynamic)method. + + + + + Gets a Func of CallSite, object * paramCnt, object delegate type + that's suitable for use in a non-strongly typed call site. + + + + + Returns true if the specified parameter is mandatory, i.e. is not optional and doesn't have a default value. + + + + + Yields all ancestors of the given type including the type itself. + Does not include implemented interfaces. + + + + + Like Type.GetInterfaces, but only returns the interfaces implemented by this type + and not its parents. + + + + + Enumerates extension methods in given assembly. Groups the methods by declaring namespace. + Uses a global cache if is true. + + + + + Binds occurances of generic parameters in against corresponding types in . + Invokes (parameter, type) for each such binding. + Returns false if the is structurally different from or if the binder returns false. + + + + + Determines if a given type matches the type that the method extends. + The match might be non-trivial if the extended type is an open generic type with constraints. + + + + + Splits text and optionally indents first lines - breaks along words, not characters. + + + + + Provides a StreamContentProvider for a stream of content backed by a file on disk. + + + + diff --git a/Reference/DLR/Net40/Microsoft.Scripting.dll b/Reference/DLR/Net40/Microsoft.Scripting.dll new file mode 100644 index 000000000..c75d88438 Binary files /dev/null and b/Reference/DLR/Net40/Microsoft.Scripting.dll differ diff --git a/Reference/DLR/Net40/Microsoft.Scripting.xml b/Reference/DLR/Net40/Microsoft.Scripting.xml new file mode 100644 index 000000000..e802e5ba0 --- /dev/null +++ b/Reference/DLR/Net40/Microsoft.Scripting.xml @@ -0,0 +1,3812 @@ + + + + Microsoft.Scripting + + + + + Provides documentation against live objects for use in a REPL window. + + + + + Gets the available members defined on the provided object. + + + + + Gets the overloads available for the provided object if it is invokable. + + + + + Gets the available members on the provided remote object. + + + + + Gets the overloads available for the provided remote object if it is invokable. + + + + + Provides documentation about a member in a live object. + + + + + The name of the member + + + + + The kind of the member if it's known. + + + + + Specifies the type of member. + + + + + Provides documentation for a single overload of an invokable object. + + + + + The name of the invokable object. + + + + + The documentation for the overload or null if no documentation is available. + + + + + The parameters for the invokable object. + + + + + Information about the return value. + + + + + Provides documentation for a single parameter. + + + + + The name of the parameter + + + + + The type name of the parameter or null if no type information is available. + + + + + Provides addition information about the parameter such as if it's a parameter array. + + + + + Gets the documentation string for this parameter or null if no documentation is available. + + + + + Indications extra information about a parameter such as if it's a parameter array. + + + + + This structure represents an immutable integer interval that describes a range of values, from Start to End. + + It is closed on the left and open on the right: [Start .. End). + + + + + Wraps a an IDictionary[object, object] and exposes it as an IDynamicMetaObjectProvider so that + users can access string attributes using member accesses. + + + + + Provides language specific documentation for live objects. + + + + + Helper for storing information about stack frames. + + + + + Exposes a IDictionary[string, object] as a dynamic object. Gets/sets/deletes turn + into accesses on the underlying dictionary. + + + + + Class that represents compiler options. + Note that this class is likely to change when hosting API becomes part of .Net + + + + + This overload will be called when a SourceUnit is not available. This can happen if the code is being executed remotely, + since SourceUnit cannot be marshaled across AppDomains. + + + + + Hosting API counterpart for . + + + + + Executes code in a default scope. + + + + + Execute code within a given scope and returns the result. + + + + + Executes code in in a default scope and converts to a given type. + + + + + Execute code within a given scope and converts result to a given type. + + + + + Executes the code in an empty scope. + Returns an ObjectHandle wrapping the resulting value of running the code. + + + + + Executes the code in the specified scope. + Returns an ObjectHandle wrapping the resulting value of running the code. + + + + + Executes the code in an empty scope. + Returns an ObjectHandle wrapping the resulting value of running the code. + + If an exception is thrown the exception is caught and an ObjectHandle to + the exception is provided. + + + Use this API to handle non-serializable exceptions (exceptions might not be serializable due to security restrictions) + or if an exception serialization loses information. + + + + + Executes the expression in the specified scope and return a result. + Returns an ObjectHandle wrapping the resulting value of running the code. + + If an exception is thrown the exception is caught and an ObjectHandle to + the exception is provided. + + + Use this API to handle non-serializable exceptions (exceptions might not be serializable due to security restrictions) + or if an exception serialization loses information. + + + + + Engine that compiled this code. + + + + + Default scope for this code. + + + + + The host can use this class to track for errors reported during script parsing and compilation. + Hosting API counterpart for . + + + + + Bridges ErrorSink and ErrorListener. + Errors reported by language compilers to ErrorSink are forwarded to the ErrorListener provided by the host. + + + This proxy is created in the scenario when the compiler is processing a single SourceUnit. + Therefore it could maintain one to one mapping from SourceUnit to ScriptSource. + In a case, which shouldn't happen, that the compiler reports an error in a different SourceUnit we just create + a new instance of the ScriptSource each time. + + TODO: Consider compilation of multiple source units and creating a hashtable mapping SourceUnits to ScriptSources + within the context of compilation unit. + + + + + Bridges ErrorListener and ErrorSink. It provides the reverse functionality as ErrorSinkProxyListener + + + + + Stores information needed to setup a language + + + + + Creates a new LanguageSetup + + assembly qualified type name of the language + provider + + + + Creates a new LanguageSetup with the provided options + TODO: remove this overload? + + + + + Creates a new LanguageSetup with the provided options + + + + + Gets an option as a strongly typed value. + + + + + The assembly qualified type name of the language provider + + + + + Display name of the language. If empty, it will be set to the first + name in the Names list. + + + + + Case-insensitive language names. + + + + + Case-insensitive file extension, optionally starts with a dot. + + + + + Option names are case-sensitive. + + + + + ObjectOperations provide a large catalogue of object operations such as member access, conversions, + indexing, and things like addition. There are several introspection and tool support services available + for more advanced hosts. + + You get ObjectOperation instances from ScriptEngine, and they are bound to their engines for the semantics + of the operations. There is a default instance of ObjectOperations you can share across all uses of the + engine. However, very advanced hosts can create new instances. + + + + + Returns true if the object can be called, false if it cannot. + + Even if an object is callable Call may still fail if an incorrect number of arguments or type of arguments are provided. + + + + + Invokes the provided object with the given parameters and returns the result. + + The prefered way of calling objects is to convert the object to a strongly typed delegate + using the ConvertTo methods and then invoking that delegate. + + + + + Invokes a member on the provided object with the given parameters and returns the result. + + + + + Creates a new instance from the provided object using the given parameters, and returns the result. + + + + + Gets the member name from the object obj. Throws an exception if the member does not exist or is write-only. + + + + + Gets the member name from the object obj and converts it to the type T. Throws an exception if the + member does not exist, is write-only, or cannot be converted. + + + + + Gets the member name from the object obj. Returns true if the member is successfully retrieved and + stores the value in the value out param. + + + + + Returns true if the object has a member named name, false if the member does not exist. + + + + + Removes the member name from the object obj. + + + + + Sets the member name on object obj to value. + + + + + Sets the member name on object obj to value. This overload can be used to avoid + boxing and casting of strongly typed members. + + + + + Gets the member name from the object obj. Throws an exception if the member does not exist or is write-only. + + + + + Gets the member name from the object obj and converts it to the type T. Throws an exception if the + member does not exist, is write-only, or cannot be converted. + + + + + Gets the member name from the object obj. Returns true if the member is successfully retrieved and + stores the value in the value out param. + + + + + Returns true if the object has a member named name, false if the member does not exist. + + + + + Removes the member name from the object obj. + + + + + Sets the member name on object obj to value. + + + + + Sets the member name on object obj to value. This overload can be used to avoid + boxing and casting of strongly typed members. + + + + + Converts the object obj to the type T. The conversion will be explicit or implicit depending on + what the langauge prefers. + + + + + Converts the object obj to the type type. The conversion will be explicit or implicit depending on + what the langauge prefers. + + + + + Converts the object obj to the type T. Returns true if the value can be converted, false if it cannot. + + The conversion will be explicit or implicit depending on what the langauge prefers. + + + + + Converts the object obj to the type type. Returns true if the value can be converted, false if it cannot. + + The conversion will be explicit or implicit depending on what the langauge prefers. + + + + + Converts the object obj to the type T including explicit conversions which may lose information. + + + + + Converts the object obj to the type type including explicit conversions which may lose information. + + + + + Converts the object obj to the type T including explicit conversions which may lose information. + + Returns true if the value can be converted, false if it cannot. + + + + + Converts the object obj to the type type including explicit conversions which may lose information. + + Returns true if the value can be converted, false if it cannot. + + + + + Converts the object obj to the type T including implicit conversions. + + + + + Converts the object obj to the type type including implicit conversions. + + + + + Converts the object obj to the type T including implicit conversions. + + Returns true if the value can be converted, false if it cannot. + + + + + Converts the object obj to the type type including implicit conversions. + + Returns true if the value can be converted, false if it cannot. + + + + + Performs a generic unary operation on the specified target and returns the result. + + + + + Performs a generic unary operation on the strongly typed target and returns the value as the specified type + + + + + Performs the generic binary operation on the specified targets and returns the result. + + + + + Peforms the generic binary operation on the specified strongly typed targets and returns + the strongly typed result. + + + + + Performs addition on the specified targets and returns the result. Throws an exception + if the operation cannot be performed. + + + + + Performs subtraction on the specified targets and returns the result. Throws an exception + if the operation cannot be performed. + + + + + Raises the first object to the power of the second object. Throws an exception + if the operation cannot be performed. + + + + + Multiplies the two objects. Throws an exception + if the operation cannot be performed. + + + + + Divides the first object by the second object. Throws an exception + if the operation cannot be performed. + + + + + Performs modulus of the 1st object by the second object. Throws an exception + if the operation cannot be performed. + + + + + Shifts the left object left by the right object. Throws an exception if the + operation cannot be performed. + + + + + Shifts the left object right by the right object. Throws an exception if the + operation cannot be performed. + + + + + Performs a bitwise-and of the two operands. Throws an exception if the operation + cannot be performed. + + + + + Performs a bitwise-or of the two operands. Throws an exception if the operation + cannot be performed. + + + + + Performs a exclusive-or of the two operands. Throws an exception if the operation + cannot be performed. + + + + + Compares the two objects and returns true if the left object is less than the right object. + Throws an exception if hte comparison cannot be performed. + + + + + Compares the two objects and returns true if the left object is greater than the right object. + Throws an exception if hte comparison cannot be performed. + + + + + Compares the two objects and returns true if the left object is less than or equal to the right object. + Throws an exception if hte comparison cannot be performed. + + + + + Compares the two objects and returns true if the left object is greater than or equal to the right object. + Throws an exception if hte comparison cannot be performed. + + + + + Compares the two objects and returns true if the left object is equal to the right object. + Throws an exception if the comparison cannot be performed. + + + + + Compares the two objects and returns true if the left object is not equal to the right object. + Throws an exception if hte comparison cannot be performed. + + + + + Returns a string which describes the object as it appears in source code + + + + + Returns a string representation of the object in a language specific object display format. + + + + + Returns a list of strings which contain the known members of the object. + + + + + Returns a string providing documentation for the specified object. + + + + + Returns a list of signatures applicable for calling the specified object in a form displayable to the user. + + + + + Returns true if the remote object is callable. + + + + + Invokes the specified remote object with the specified remote parameters. + + Though delegates are preferable for calls they may not always be usable for remote objects. + + + + + Invokes the specified remote object with the local parameters which will be serialized + to the remote app domain. + + + + + Creates a new remote instance from the provided remote object using the given parameters, and returns the result. + + + + + Creates a new remote instance from the provided remote object using the given parameters, and returns the result. + + + + + Sets the remote object as a member on the provided remote object. + + + + + Sets the member name on the remote object obj to value. This overload can be used to avoid + boxing and casting of strongly typed members. + + + + + Gets the member name on the remote object. Throws an exception if the member is not defined or + is write-only. + + + + + Gets the member name on the remote object. Throws an exception if the member is not defined or + is write-only. + + + + + Gets the member name on the remote object. Returns false if the member is not defined or + is write-only. + + + + + Tests to see if the member name is defined on the remote object. + + + + + Removes the member from the remote object + + + + + Converts the remote object into the specified type returning a handle to + the new remote object. The conversion will be explicit or implicit depending on + what the langauge prefers. + + + + + Converts the remote object into the specified type returning a handle to + the new remote object. The conversion will be explicit or implicit depending on + what the langauge prefers. + + + + + Converts the remote object into the specified type returning a handle to + the new remote object. Returns true if the value can be converted, + false if it cannot. The conversion will be explicit or implicit depending on + what the langauge prefers. + + + + + Converts the remote object into the specified type returning a handle to + the new remote object. Returns true if the value can be converted, + false if it cannot. The conversion will be explicit or implicit depending on + what the langauge prefers. + + + + + Converts the object obj to the type T including explicit conversions which may lose information. + + + + + Converts the object obj to the type type including explicit conversions which may lose information. + + + + + Converts the object obj to the type T including explicit conversions which may lose information. + + Returns true if the value can be converted, false if it cannot. + + + + + Converts the object obj to the type type including explicit conversions which may lose information. + + Returns true if the value can be converted, false if it cannot. + + + + + Converts the object obj to the type T including implicit conversions. + + + + + Converts the object obj to the type type including implicit conversions. + + + + + Converts the object obj to the type T including implicit conversions. + + Returns true if the value can be converted, false if it cannot. + + + + + Converts the object obj to the type type including implicit conversions. + + Returns true if the value can be converted, false if it cannot. + + + + + Unwraps the remote object and converts it into the specified type before + returning it. + + + + + Performs the specified unary operator on the remote object. + + + + + Performs the specified binary operator on the remote object. + + + + + Adds the two remote objects. Throws an exception if the operation cannot be performed. + + + + + Subtracts the 1st remote object from the second. Throws an exception if the operation cannot be performed. + + + + + Raises the 1st remote object to the power of the 2nd. Throws an exception if the operation cannot be performed. + + + + + Multiplies the two remote objects. Throws an exception if the operation cannot be performed. + + + + + Divides the 1st remote object by the 2nd. Throws an exception if the operation cannot be performed. + + + + + Performs modulus on the 1st remote object by the 2nd. Throws an exception if the operation cannot be performed. + + + + + Shifts the 1st remote object left by the 2nd remote object. Throws an exception if the operation cannot be performed. + + + + + Shifts the 1st remote object right by the 2nd remote object. Throws an exception if the operation cannot be performed. + + + + + Performs bitwise-and on the two remote objects. Throws an exception if the operation cannot be performed. + + + + + Performs bitwise-or on the two remote objects. Throws an exception if the operation cannot be performed. + + + + + Performs exclusive-or on the two remote objects. Throws an exception if the operation cannot be performed. + + + + + Compares the two remote objects and returns true if the 1st is less than the 2nd. Throws an exception if the operation cannot be performed. + + + + + Compares the two remote objects and returns true if the 1st is greater than the 2nd. Throws an exception if the operation cannot be performed. + + + + + Compares the two remote objects and returns true if the 1st is less than or equal to the 2nd. Throws an exception if the operation cannot be performed. + + + + + Compares the two remote objects and returns true if the 1st is greater than or equal to than the 2nd. Throws an exception if the operation cannot be performed. + + + + + Compares the two remote objects and returns true if the 1st is equal to the 2nd. Throws an exception if the operation cannot be performed. + + + + + Compares the two remote objects and returns true if the 1st is not equal to the 2nd. Throws an exception if the operation cannot be performed. + + + + + Returns a string representation of the object in a langauge specific object display format. + + + + + Returns a list of strings which contain the known members of the remote object. + + + + + Returns a string providing documentation for the specified remote object. + + + + + Returns a list of signatures applicable for calling the specified object in a form displayable to the user. + + + + + Helper to unwrap an object - in the future maybe we should validate the current app domain. + + + + + Helper to unwrap multiple objects + + + + + Reads an option whose value is expected to be a collection of non-null strings. + Reaturns a read-only copy of the option's value. + + + + + Dynamically choose between interpreting, simple compilation and compilation + that takes advantage of runtime history. + + + + + The number of iterations before the interpreter starts compiling.s + + + + + Display exception detail (callstack) when exception gets caught + + + + + Whether to gather performance statistics. + + + + + Initial file search paths provided by the host. + + + + + Abstracts system operations that are used by DLR and could potentially be platform specific. + The host can implement its PAL to adapt DLR to the platform it is running on. + For example, the Silverlight host adapts some file operations to work against files on the server. + + + + Invalid path. + + + Invalid path. + + + + Advanced APIs for HAPI providers. These methods should not be used by hosts. + They are provided for other hosting API implementers that would like to leverage existing HAPI and + extend it with language specific functionality, for example. + + + + is a null reference. + is remote. + + + e is a null reference. + is remote. + + + is a null reference. + is remote. + + + is a null reference. + is remote. + + + is a null reference. + is remote. + + + is a null reference. + is remote. + + + is a null reference. + is a null reference. + is a transparent proxy. + + + + Performs a callback in the ScriptEngine's app domain and returns the result. + + + + + Creates a new DocumentationOperations object from the given DocumentationProvider. + + + + + Represents a language in Hosting API. + Hosting API counterpart for . + + + + + Returns a new ObjectOperations object. See the Operations property for why you might want to call this. + + + + + Returns a new ObjectOperations object that inherits any semantics particular to the provided ScriptScope. + + See the Operations property for why you might want to call this. + + + + + Executes an expression. The execution is not bound to any particular scope. + + The engine doesn't support code execution. + is a null reference. + + + + Executes an expression within the specified scope. + + The engine doesn't support code execution. + is a null reference. + is a null reference. + + + + Executes an expression within a new scope and converts result to the given type. + + The engine doesn't support code execution. + is a null reference. + + + + Executes an expression within the specified scope and converts result to the given type. + + The engine doesn't support code execution. + is a null reference. + is a null reference. + + + + Executes content of the specified file in a new scope and returns that scope. + + The engine doesn't support code execution. + is a null reference. + + + + Executes content of the specified file against the given scope. + + The . + The engine doesn't support code execution. + is a null reference. + is a null reference. + + + + Executes the expression in the specified scope and return a result. + Returns an ObjectHandle wrapping the resulting value of running the code. + + + + + Executes the code in an empty scope. + Returns an ObjectHandle wrapping the resulting value of running the code. + + + + + Executes the expression in the specified scope and return a result. + Returns an ObjectHandle wrapping the resulting value of running the code. + + If an exception is thrown the exception is caught and an ObjectHandle to + the exception is provided. + + + Use this API in case the exception is not serializable (for example, due to security restrictions) or its serialization + loses information that you need to access. + + + + + Executes the code in an empty scope. + Returns an ObjectHandle wrapping the resulting value of running the code. + + If an exception is thrown the exception is caught and an ObjectHandle to + the exception is provided. + + + Use this API in case the exception is not serializable (for example, due to security restrictions) or its serialization + loses information that you need to access. + + + + + Creates a new ScriptScope whose storage is an arbitrary object. + + Accesses to the ScriptScope will turn into get, set, and delete members against the object. + + + + + This method returns the ScriptScope in which a ScriptSource of given path was executed. + + The ScriptSource.Path property is the key to finding the ScriptScope. Hosts need + to make sure they create a ScriptSource and set its Path property appropriately. + + GetScope is primarily useful for tools that need to map files to their execution scopes. For example, + an editor and interpreter tool might run a file Foo that imports or requires a file Bar. + + The editor's user might later open the file Bar and want to execute expressions in its context. + The tool would need to find Bar's ScriptScope for setting the appropriate context in its interpreter window. + This method helps with this scenario. + + + + + Return a ScriptSource object from string contents with the current engine as the language binding. + + The default SourceCodeKind is AutoDetect. + + The ScriptSource's Path property defaults to null. + + + + + Return a ScriptSource object from string contents with the current engine as the language binding. + + The ScriptSource's Path property defaults to null. + + + + + Return a ScriptSource object from string contents with the current engine as the language binding. + + The default SourceCodeKind is AutoDetect. + + + + + Return a ScriptSource object from string contents. These are helpers for creating ScriptSources' with the right language binding. + + + + + Return a ScriptSource object from file contents with the current engine as the language binding. + + The path's extension does NOT have to be in ScriptRuntime.GetRegisteredFileExtensions + or map to this language engine with ScriptRuntime.GetEngineByFileExtension. + + The default SourceCodeKind is File. + + The ScriptSource's Path property will be the path argument. + + The encoding defaults to System.Text.Encoding.Default. + + + + + Return a ScriptSource object from file contents with the current engine as the language binding. + + The path's extension does NOT have to be in ScriptRuntime.GetRegisteredFileExtensions + or map to this language engine with ScriptRuntime.GetEngineByFileExtension. + + The default SourceCodeKind is File. + + The ScriptSource's Path property will be the path argument. + + + + + Return a ScriptSource object from file contents with the current engine as the language binding. + + The path's extension does NOT have to be in ScriptRuntime.GetRegisteredFileExtensions + or map to this language engine with ScriptRuntime.GetEngineByFileExtension. + + The ScriptSource's Path property will be the path argument. + + + + + This method returns a ScriptSource object from a System.CodeDom.CodeObject. + This is a factory method for creating a ScriptSources with this language binding. + + The expected CodeDom support is extremely minimal for syntax-independent expression of semantics. + + Languages may do more, but hosts should only expect CodeMemberMethod support, + and only sub nodes consisting of the following: + CodeSnippetStatement + CodeSnippetExpression + CodePrimitiveExpression + CodeMethodInvokeExpression + CodeExpressionStatement (for holding MethodInvoke) + + + + + This method returns a ScriptSource object from a System.CodeDom.CodeObject. + This is a factory method for creating a ScriptSources with this language binding. + + The expected CodeDom support is extremely minimal for syntax-independent expression of semantics. + + Languages may do more, but hosts should only expect CodeMemberMethod support, + and only sub nodes consisting of the following: + CodeSnippetStatement + CodeSnippetExpression + CodePrimitiveExpression + CodeMethodInvokeExpression + CodeExpressionStatement (for holding MethodInvoke) + + + + + This method returns a ScriptSource object from a System.CodeDom.CodeObject. + This is a factory method for creating a ScriptSources with this language binding. + + The expected CodeDom support is extremely minimal for syntax-independent expression of semantics. + + Languages may do more, but hosts should only expect CodeMemberMethod support, + and only sub nodes consisting of the following: + CodeSnippetStatement + CodeSnippetExpression + CodePrimitiveExpression + CodeMethodInvokeExpression + CodeExpressionStatement (for holding MethodInvoke) + + + + + This method returns a ScriptSource object from a System.CodeDom.CodeObject. + This is a factory method for creating a ScriptSources with this language binding. + + The expected CodeDom support is extremely minimal for syntax-independent expression of semantics. + + Languages may do more, but hosts should only expect CodeMemberMethod support, + and only sub nodes consisting of the following: + CodeSnippetStatement + CodeSnippetExpression + CodePrimitiveExpression + CodeMethodInvokeExpression + CodeExpressionStatement (for holding MethodInvoke) + + + + + These methods return ScriptSource objects from stream contents with the current engine as the language binding. + + The default SourceCodeKind is File. + + The encoding defaults to Encoding.Default. + + + + + These methods return ScriptSource objects from stream contents with the current engine as the language binding. + + The default SourceCodeKind is File. + + + + + These methods return ScriptSource objects from stream contents with the current engine as the language binding. + + The encoding defaults to Encoding.Default. + + + + + This method returns a ScriptSource with the content provider supplied with the current engine as the language binding. + + This helper lets you own the content provider so that you can implement a stream over internal host data structures, such as an editor's text representation. + + + + + This method returns a language-specific service. + + It provides a point of extensibility for a language implementation + to offer more functionality than the standard engine members discussed here. + + Commonly available services include: + TokenCategorizer + Provides standardized tokenization of source code + ExceptionOperations + Provides formatting of exception objects. + DocumentationProvidera + Provides documentation for live object. + + + + + Sets the search paths used by the engine for loading files when a script wants + to import or require another file of code. + + The language doesn't allow to set search paths. + + + + Gets the search paths used by the engine for loading files when a script wants + to import or require another file of code. + + + + + Returns a default ObjectOperations for the engine. + + Because an ObjectOperations object caches rules for the types of + objects and operations it processes, using the default ObjectOperations for + many objects could degrade the caching benefits. Eventually the cache for + some operations could degrade to a point where ObjectOperations stops caching and + does a full search for an implementation of the requested operation for the given objects. + + Another reason to create a new ObjectOperations instance is to have it bound + to the specific view of a ScriptScope. Languages may attach per-language + behavior to a ScriptScope which would alter how the operations are performed. + + For simple hosting situations, this is sufficient behavior. + + + + + + + This property returns readon-only LanguageOptions this engine is using. + + + The values are determined during runtime initialization and read-only afterwards. + You can change the settings via a configuration file or explicitly using ScriptRuntimeSetup class. + + + + + This property returns the ScriptRuntime for the context in which this engine executes. + + + + + This property returns the engine's version as a string. The format is language-dependent. + + + + + ScriptHost is collocated with ScriptRuntime in the same app-domain. + The host can implement a derived class to consume some notifications and/or + customize operations like TryGetSourceUnit,ResolveSourceUnit, etc. + + The areguments to the the constructor of the derived class are specified in ScriptRuntimeSetup + instance that enters ScriptRuntime initialization. + + If the host is remote with respect to DLR (i.e. also with respect to ScriptHost) + and needs to access objects living in its app-domain it can pass MarshalByRefObject + as an argument to its ScriptHost subclass constructor. + + + + + The runtime the host is attached to. + + + + + Invoked after the initialization of the associated Runtime is finished. + The host can override this method to perform additional initialization of runtime (like loading assemblies etc.). + + + + + Invoked after a new language is loaded into the Runtime. + The host can override this method to perform additional initialization of language engines. + + + + + Provides hosting to DLR. Forwards DLR requests to the ScriptHost. + + + + + DLR requires any Hosting API provider to implement this class and provide its instance upon Runtime initialization. + DLR calls on it to perform basic host/system dependent operations. + + + + + Abstracts system operations that are used by DLR and could potentially be platform specific. + + + + + Provides host-redirectable IO streams used by DLR languages for default IO. + + + + + Used if the host stores the output as binary data. + + Binary stream to write data to. + Encoding used to convert textual data written to the output by the script. + + + + Used if the host handles both kinds of data (textual and binary) by itself. + + + + + Represents a Dynamic Language Runtime in Hosting API. + Hosting API counterpart for . + + + + + Creates ScriptRuntime in the current app-domain and initialized according to the the specified settings. + Creates an instance of host class specified in the setup and associates it with the created runtime. + Both Runtime and ScriptHost are collocated in the current app-domain. + + + + + Creates a new runtime with languages set up according to the current application configuration + (using System.Configuration). + + + + + Creates ScriptRuntime in the current app-domain and initialized according to the the specified settings. + Creates an instance of host class specified in the setup and associates it with the created runtime. + Both Runtime and ScriptHost are collocated in the specified app-domain. + + + + + + + + + Gets engine for the specified language. + + + + + Looks up the engine for the specified language. If the engine hasn't been created in this Runtime, it is instantiated here. + The method doesn't lock nor send notifications to the host. + + + + + path is empty, contains one or more of the invalid characters defined in GetInvalidPathChars or doesn't have an extension. + + + + path is null + file extension does not map to language engine + language does not have any search paths + file does exist in language's search path + + + + This method walks the assembly's namespaces and name bindings to ScriptRuntime.Globals + to represent the types available in the assembly. Each top-level namespace name gets + bound in Globals to a dynamic object representing the namespace. Within each top-level + namespace object, nested namespace names are bound to dynamic objects representing each + tier of nested namespaces. When this method encounters the same namespace-qualified name, + it merges names together objects representing the namespaces. + + + + + + This property returns the "global object" or name bindings of the ScriptRuntime as a ScriptScope. + + You can set the globals scope, which you might do if you created a ScriptScope with an + IAttributesCollection so that your host could late bind names. + + + + + Stores information needed to setup a ScriptRuntime + + + + + Reads setup from .NET configuration system (.config files). + If there is no configuration available returns an empty setup. + + + + + Reads setup from a specified XML stream. + + + + + Reads setup from a specified XML file. + + + + + The list of language setup information for languages to load into + the runtime + + + + + Indicates that the script runtime is in debug mode. + This means: + + 1) Symbols are emitted for debuggable methods (methods associated with SourceUnit). + 2) Debuggable methods are emitted to non-collectable types (this is due to CLR limitations on dynamic method debugging). + 3) JIT optimization is disabled for all methods + 4) Languages may disable optimizations based on this value. + + + + + Ignore CLR visibility checks + + + + + Can be any derived class of ScriptHost. When set, it allows the + host to override certain methods to control behavior of the runtime + + + + + Option names are case-sensitive. + + + + + Arguments passed to the host type when it is constructed + + + + + A ScriptScope is a unit of execution for code. It consists of a global Scope which + all code executes in. A ScriptScope can have an arbitrary initializer and arbitrary + reloader. + + ScriptScope is not thread safe. Host should either lock when multiple threads could + access the same module or should make a copy for each thread. + + Hosting API counterpart for . + + + + + Gets a value stored in the scope under the given name. + + The specified name is not defined in the scope. + is a null reference. + + + + Gets a value stored in the scope under the given name. + Converts the result to the specified type using the conversion that the language associated with the scope defines. + If no language is associated with the scope, the default CLR conversion is attempted. + + The specified name is not defined in the scope. + is a null reference. + + + + Tries to get a value stored in the scope under the given name. + + is a null reference. + + + + Tries to get a value stored in the scope under the given name. + Converts the result to the specified type using the conversion that the language associated with the scope defines. + If no language is associated with the scope, the default CLR conversion is attempted. + + is a null reference. + + + + Sets the name to the specified value. + + is a null reference. + + + + Gets a handle for a value stored in the scope under the given name. + + The specified name is not defined in the scope. + is a null reference. + + + + Tries to get a handle for a value stored in the scope under the given name. + Returns true if there is such name, false otherwise. + + is a null reference. + + + + Sets the name to the specified value. + + + The value held by the handle isn't from the scope's app-domain and isn't serializable or MarshalByRefObject. + + or is a null reference. + + + + Determines if this context or any outer scope contains the defined name. + + is a null reference. + + + + Removes the variable of the given name from this scope. + + true if the value existed in the scope before it has been removed. + is a null reference. + + + + Gets a list of variable names stored in the scope. + + + + + Gets an array of variable names and their values stored in the scope. + + + + + Gets an engine for the language associated with this scope. + Returns invariant engine if the scope is language agnostic. + + + + + Hosting counterpart for . + + + + + Compile the ScriptSource into CompileCode object that can be executed + repeatedly in its default scope or in other scopes without having to recompile the code. + + Code cannot be compiled. + + + + Errors are reported to the specified listener. + Returns null if the parser cannot compile the code due to errors. + + + + + Errors are reported to the specified listener. + Returns null if the parser cannot compile the code due to error(s). + + + + + Errors are reported to the specified listener. + Returns null if the parser cannot compile the code due to error(s). + + + + + Executes the code in the specified scope. + Returns an object that is the resulting value of running the code. + + When the ScriptSource is a file or statement, the engine decides what is + an appropriate value to return. Some languages return the value produced + by the last expression or statement, but languages that are not expression + based may return null. + + Code cannot be compiled. + + + + Executes the source code. The execution is not bound to any particular scope. + + + + + Executes the code in a specified scope and converts the result to the specified type. + The conversion is language specific. + + + + + Executes the code in an empty scope and converts the result to the specified type. + The conversion is language specific. + + + + + Executes the code in an empty scope. + Returns an ObjectHandle wrapping the resulting value of running the code. + + + + + Executes the code in the specified scope. + Returns an ObjectHandle wrapping the resulting value of running the code. + + + + + Executes the code in an empty scope. + Returns an ObjectHandle wrapping the resulting value of running the code. + + If an exception is thrown the exception is caught and an ObjectHandle to + the exception is provided. + + + Use this API to handle non-serializable exceptions (exceptions might not be serializable due to security restrictions) + or if an exception serialization loses information. + + + + + Executes the expression in the specified scope and return a result. + Returns an ObjectHandle wrapping the resulting value of running the code. + + If an exception is thrown the exception is caught and an ObjectHandle to + the exception is provided. + + + Use this API to handle non-serializable exceptions (exceptions might not be serializable due to security restrictions) + or if an exception serialization loses information. + + + + + Runs a specified code as if it was a program launched from OS command shell. + and returns a process exit code indicating the success or error condition + of executing the code. + + Exact behavior depends on the language. Some languages have a dedicated "exit" exception that + carries the exit code, in which case the exception is cought and the exit code is returned. + The default behavior returns the result of program's execution converted to an integer + using a language specific conversion. + + Code cannot be compiled. + + + + Detects the encoding of the content. + + + An encoding that is used by the reader of the script source to transcode its content to Unicode text. + Null if the content is already textual and no transcoding is performed. + + + Note that the default encoding specified when the script source is created could be overridden by + an encoding that is found in the content preamble (Unicode BOM or a language specific encoding preamble). + In that case the preamble encoding is returned. Otherwise, the default encoding is returned. + + An I/O error occurs. + + + + Reads specified range of lines (or less) from the source unit. + + 1-based number of the first line to fetch. + The number of lines to fetch. + + Which character sequences are considered line separators is language specific. + If language doesn't specify otherwise "\r", "\n", "\r\n" are recognized line separators. + + An I/O error occurs. + + + + Reads a specified line. + + 1-based line number. + Line content. Line separator is not included. + An I/O error occurs. + + Which character sequences are considered line separators is language specific. + If language doesn't specify otherwise "\r", "\n", "\r\n" are recognized line separators. + + + + + Gets script source content. + + Entire content. + An I/O error occurs. + + The result includes language specific preambles (e.g. "#coding:UTF-8" encoding preamble recognized by Ruby), + but not the preamble defined by the content encoding (e.g. BOM). + The entire content of the source unit is encoded by single encoding (if it is read from binary stream). + + + + + Identification of the source unit. Assigned by the host. + The format and semantics is host dependent (could be a path on file system or URL). + null for anonymous script source. + Cannot be an empty string. + + + + + Move the tokenizer past the next token and return its category. + + The token information associated with the token just scanned. + + + + Move the tokenizer past the next token. + + False if the end of stream has been reached, true otherwise. + + + + Get all tokens over a block of the stream. + + + + The scanner should return full tokens. If startLocation + length lands in the middle of a token, the full token + should be returned. + + s + Tokens are read until at least given amount of characters is read or the stream ends. + A enumeration of tokens. + + + + Scan from startLocation to at least startLocation + length. + + Tokens are read until at least given amount of characters is read or the stream ends. + + This method is used to determine state at arbitrary startLocation. + + False if the end of stream has been reached, true otherwise. + + + + The current internal state of the scanner. + + + + + The current startLocation of the scanner. + + + + + Represents a language context. Typically there is at most 1 context + associated with each language, but some languages may use more than one context + to identify code that should be treated differently. Contexts are used during + member and operator lookup. + + + + + Registers a language within the system with the specified name. + + + + + Looks up the context ID for the specified context identifier + + + + + Singleton for each language. + + + + + Must not be called under a lock as it can potentially call a user code. + + The language context's implementation failed to instantiate. + + + + Whether the application is in debug mode. + This means: + + 1) Symbols are emitted for debuggable methods (methods associated with SourceUnit). + 2) Debuggable methods are emitted to non-collectable types (this is due to CLR limitations on dynamic method debugging). + 3) JIT optimization is disabled for all methods + 4) Languages may disable optimizations based on this value. + + + + + Ignore CLR visibility checks. + + + + + ObjectOperations provide a large catalogue of object operations such as member access, conversions, + indexing, and things like addition. There are several introspection and tool support services available + for more advanced hosts. + + You get ObjectOperation instances from ScriptEngine, and they are bound to their engines for the semantics + of the operations. There is a default instance of ObjectOperations you can share across all uses of the + engine. However, very advanced hosts can create new instances. + + + + the number of sites required before we'll try cleaning up the cache... + + + the minimum difference between the average that is required to remove + + + the maximum number we'll remove on a single cache cleanup + + + the number of sites we should clear after if we can't make progress cleaning up otherwise + + + a dictionary of SiteKey's which are used to cache frequently used operations, logically a set + + + the # of sites we had created at the last cleanup + + + the total number of sites we've ever created + + + + Calls the provided object with the given parameters and returns the result. + + The prefered way of calling objects is to convert the object to a strongly typed delegate + using the ConvertTo methods and then invoking that delegate. + + + + + Invokes a member on the provided object with the given parameters and returns the result. + + + + + Invokes a member on the provided object with the given parameters and returns the result. + + + + + Creates a new instance from the provided object using the given parameters, and returns the result. + + + + + Gets the member name from the object obj. Throws an exception if the member does not exist or is write-only. + + + + + Gets the member name from the object obj and converts it to the type T. Throws an exception if the + member does not exist, is write-only, or cannot be converted. + + + + + Gets the member name from the object obj. Returns true if the member is successfully retrieved and + stores the value in the value out param. + + + + + Returns true if the object has a member named name, false if the member does not exist. + + + + + Removes the member name from the object obj. + + + + + Sets the member name on object obj to value. + + + + + Sets the member name on object obj to value. This overload can be used to avoid + boxing and casting of strongly typed members. + + + + + Gets the member name from the object obj. Throws an exception if the member does not exist or is write-only. + + + + + Gets the member name from the object obj and converts it to the type T. The conversion will be explicit or implicit + depending on what the langauge prefers. Throws an exception if the member does not exist, is write-only, or cannot be converted. + + + + + Gets the member name from the object obj. Returns true if the member is successfully retrieved and + stores the value in the value out param. + + + + + Returns true if the object has a member named name, false if the member does not exist. + + + + + Removes the member name from the object obj. Returns true if the member was successfully removed + or false if the member does not exist. + + + + + Sets the member name on object obj to value. + + + + + Sets the member name on object obj to value. This overload can be used to avoid + boxing and casting of strongly typed members. + + + + + Converts the object obj to the type T. The conversion will be explicit or implicit + depending on what the langauge prefers. + + + + + Converts the object obj to the type type. The conversion will be explicit or implicit + depending on what the langauge prefers. + + + + + Converts the object obj to the type T. Returns true if the value can be converted, false if it cannot. + + The conversion will be explicit or implicit depending on what the langauge prefers. + + + + + Converts the object obj to the type type. Returns true if the value can be converted, false if it cannot. + + The conversion will be explicit or implicit depending on what the langauge prefers. + + + + + Convers the object obj to the type T including explicit conversions which may lose information. + + + + + Converts the object obj to the type type including explicit conversions which may lose information. + + + + + Converts the object obj to the type type including explicit conversions which may lose information. + + Returns true if the value can be converted, false if it cannot. + + + + + Converts the object obj to the type T. Returns true if the value can be converted, false if it cannot. + + + + + Convers the object obj to the type T including implicit conversions. + + + + + Converts the object obj to the type type including implicit conversions. + + + + + Converts the object obj to the type type including implicit conversions. + + Returns true if the value can be converted, false if it cannot. + + + + + Converts the object obj to the type T. Returns true if the value can be converted, false if it cannot. + + + + + Performs a generic unary operation on the strongly typed target and returns the value as the specified type + + + + + Peforms the generic binary operation on the specified strongly typed targets and returns + the strongly typed result. + + + + + Returns a list of strings which contain the known members of the object. + + + + + Returns a string representation of the object in a language specific object display format. + + + + + Gets or creates a dynamic site w/ the specified type parameters for the provided binder. + + + This will either get the site from the cache or create a new site and return it. The cache + may be cleaned if it's gotten too big since the last usage. + + + + + Gets or creates a dynamic site w/ the specified type parameters for the provided binder. + + + This will either get the site from the cache or create a new site and return it. The cache + may be cleaned if it's gotten too big since the last usage. + + + + + Gets or creates a dynamic site w/ the specified type parameters for the provided binder. + + + This will either get the site from the cache or create a new site and return it. The cache + may be cleaned if it's gotten too big since the last usage. + + + + + Gets or creates a dynamic site w/ the specified type parameters for the provided binder. + + + This will either get the site from the cache or create a new site and return it. The cache + may be cleaned if it's gotten too big since the last usage. + + + + + Gets or creates a dynamic site w/ the specified type parameters for the provided binder. + + + This will either get the site from the cache or create a new site and return it. The cache + may be cleaned if it's gotten too big since the last usage. + + + + + Helper to create to get or create the dynamic site - called by the GetSite methods. + + + + + Removes items from the cache that have the lowest usage... + + + + + Helper class for tracking all of our unique dynamic sites and their + usage patterns. We hash on the combination of the binder and site type. + + We also track the hit count and the key holds the site associated w/ the + key. Logically this is a set based upon the binder and site-type but we + store it in a dictionary. + + + + + Singleton LanguageContext which represents a language-neutral LanguageContext + + + + + Provides language specific facilities which are typically called by the runtime. + + + + + Provides access to setting variables in scopes. + + By default this goes through ObjectOperations which can be rather slow. + Languages can override this to provide fast customized access which avoids + ObjectOperations. Languages can provide fast access to commonly used scope + types for that language. Typically this includes ScopeStorage and any other + classes which the language themselves uses for backing of a Scope. + + + + + Provides access to try getting variables in scopes. + + By default this goes through ObjectOperations which can be rather slow. + Languages can override this to provide fast customized access which avoids + ObjectOperations. Languages can provide fast access to commonly used scope + types for that language. Typically this includes ScopeStorage and any other + classes which the language themselves uses for backing of a Scope. + + + + + Provides access to getting variables in scopes and converting the result. + + By default this goes through ObjectOperations which can be rather slow. + Languages can override this to provide fast customized access which avoids + ObjectOperations. Languages can provide fast access to commonly used scope + types for that language. Typically this includes ScopeStorage and any other + classes which the language themselves uses for backing of a Scope. + + + + + Provides access to getting variables in scopes. + + By default this goes through ObjectOperations which can be rather slow. + Languages can override this to provide fast customized access which avoids + ObjectOperations. Languages can provide fast access to commonly used scope + types for that language. Typically this includes ScopeStorage and any other + classes which the language themselves uses for backing of a Scope. + + + + + Provides a text reader for source code that is to be read from a given stream. + + The stream open for reading. The stream must also allow seeking. + An encoding that should be used if the stream doesn't have Unicode or language specific preamble. + the path of the source unit if available + The reader. + An I/O error occurs. + + + + Creates the language specific CompilerOptions object for compilation of code not bound to any particular scope. + The language should flow any relevant options from LanguageContext to the newly created options instance. + + + + + Creates the language specific CompilerOptions object for compilation of code bound to a given scope. + + + + + Parses the source code within a specified compiler context. + The source unit to parse is held on by the context. + + null on failure. + Could also set the code properties and line/file mappings on the source unit. + + + + Creates a conversion binder. + + If explicitCast is true then the binder should do explicit conversions. + If explicitCast is false then the binder should do implicit conversions. + + If explicitCast is null it is up to the language to select the conversions + which closest match their normal behavior. + + + + + Gets the member names associated with the object + By default, only returns IDO names + + + + + Returns a string representation of the object in a language specific object display format. + + Dynamic sites container that could be used for any dynamic dispatches necessary for formatting. + Object to format. + A string representation of object. + + + + Provides the ContextId which includes members that should only be shown for this LanguageContext. + + ContextId's are used for filtering by Scope's. + + + + + Gets the ScriptDomainManager that this LanguageContext is running within. + + + + + Whether the language can parse code and create source units. + + + + + Internal class which binds a LanguageContext, StreamContentProvider, and Encoding together to produce + a TextContentProvider which reads binary data with the correct language semantics. + + + + + Provides a factory to create TextReader's over one source of textual content. + + TextContentProvider's are used when reading from a source which is already decoded + or has a known specific decoding. + + For example a text editor might provide a TextContentProvider whose backing is + an in-memory text buffer that the user can actively edit. + + + + + Creates a new TextReader which is backed by the content the TextContentProvider was created for. + + This method may be called multiple times. For example once to compile the code and again to get + the source code to display error messages. + + + + + This attribute marks a parameter that is not allowed to be null. + It is used by the method binding infrastructure to generate better error + messages and method selection. + + + + + This attribute marks a parameter whose type is an array that is not allowed to have null items. + It is used by the method binding infrastructure to generate better error + messages and method selection. + + + + + This attribute is used to mark a parameter that can accept any keyword parameters that + are not bound to normal arguments. The extra keyword parameters will be + passed in a dictionary which is created for the call. + + Most languages which support params dictionaries will support the following types: + IDictionary<string, anything> + IDictionary<object, anything> + Dictionary<string, anything> + Dictionary<object, anything> + IDictionary + IAttributesCollection (deprecated) + + For languages which don't have language level support the user will be required to + create and populate the dictionary by hand. + + This attribute is the dictionary equivalent of the System.ParamArrayAttribute. + + + public static void KeywordArgFunction([ParamsDictionary]IDictionary<string, object> dict) { + foreach (var v in dict) { + Console.WriteLine("Key: {0} Value: {1}", v.Key, v.Value); + } + } + + Called from Python: + + KeywordArgFunction(a = 2, b = "abc") + + will print: + Key: a Value = 2 + Key: b Value = abc + + + + + Represents a host-provided variables for executable code. The variables are + typically backed by a host-provided dictionary. Languages can also associate per-language + information with the context by using scope extensions. This can be used for tracking + state which is used across multiple executions, for providing custom forms of + storage (for example object keyed access), or other language specific semantics. + + Scope objects are thread-safe as long as their underlying storage is thread safe. + + Script hosts can choose to use thread safe or thread unsafe modules but must be sure + to constrain the code they right to be single-threaded if using thread unsafe + storage. + + + + + Creates a new scope with a new empty thread-safe dictionary. + + + + + Creates a new scope which is backed by an arbitrary object for it's storage. + + + + + + Gets the ScopeExtension associated with the provided ContextId. + + + + + Sets the ScopeExtension to the provided value for the given ContextId. + + The extension can only be set once. The returned value is either the new ScopeExtension + if no value was previously set or the previous value. + + + + + Provides optimized and cacheable support for scope storage. + + This is the default object used for storing values in a scope. + + + + The implementation uses a case-insensitive dictionary which holds + onto ScopeVariableIgnoreCase objects. The SVIC's hold onto ScopeVariable + objects for each possible casing. + + + + + Gets the named value from the scope optionally ignoring case. + + If the named value is not present an InvalidOperationException is raised. + + + + + Attempts to get the named value from the scope optionally ignoring the case. + + Returns true if the value is present, false if it is not. + + + + + Sets the named value in the scope optionally ignoring the case. + + + + + Deletes the named value from the scope optionally ignoring the case. + + + + + Checks if the named value is present in the scope optionally ignoring the case. + + + + + Gets the IScopeVariable for the scope optionally ignoring case. + + The IScopeVariable can be held onto and get/set/deleted without performing + a dictionary lookup on subsequent accesses. + + + + + Gets the ScopeVariable for the scope in a case-sensitive manner. + + The ScopeVariable can be held onto and get/set/deleted without performing + a dictionary lookup on subsequent accesses. + + + + + Gets the ScopeVariableIgnoreCase for the scope in a case-insensitive manner. + + The ScopeVariable can be held onto and get/set/deleted without performing + a dictionary lookup on subsequent accesses. + + + + + Returns all of the member names which currently have values in the scope. + + The list contains all available casings. + + + + + Returns all of the member names and their associated values from the scope. + + The list contains all available casings. + + + + + Provides convenient case-sensitive value access. + + + + + Provides a common interface for accessing both case sensitive and + case insensitive variable storage. + + + + + Atempts to get the value. If a value is assigned it returns true otherwise + it returns false. + + + + + Sets the current value in the scope. + + + + + Removes the current value from the scope. + + + + + True if the scope has a value, false if it does not. + + + + + Boxes the value for storage in a scope. Languages or consumers of the scope + can save this value and use it to get/set the current value in the scope for + commonly accessed values. + + ScopeVariables are case sensitive and will only refer to a single value. + + + + + Atempts to get the value. If a value is assigned it returns true otherwise + it returns false. + + + + + Sets the current value in the scope. + + + + + Removes the current value from the scope. + + + + + True if the scope has a value, false if it does not. + + + + + Boxes the value for storage in a scope. Languages or consumers of the scope + can save this value and use it to get/set the current value in the scope for + commonly accessed values. + + ScopeVariablesIgnoreCase are case insensitive and may access different casings + depending on how other gets/sets occur in the scope. + + + + + Atempts to get the value. If a value is assigned it returns true otherwise + it returns false. + + + + + Sets the current value in the scope. + + + + + Removes the current value from the scope. + + + + + True if the scope has a value, false if it does not. + + + + + ScriptCode is an instance of compiled code that is bound to a specific LanguageContext + but not a specific ScriptScope. The code can be re-executed multiple times in different + scopes. Hosting API counterpart for this class is CompiledCode. + + + + + A collection of environment variables. + + + + + Event for when a host calls LoadAssembly. After hooking this + event languages will need to call GetLoadedAssemblyList to + get any assemblies which were loaded before the language was + loaded. + + + + + Only host should redirect I/O. + + + + + Provides a factory to create streams over one source of binary content. + + StreamContentProvider's are used when opening a file of an unknown encoding. The + StreamContentProvider will be wrapped in a TextContentProvider provided by the language + which can support a language specific way of interpreting the binary data into text. + + For example some languages allow a marker at the beginning of the file which specifies + the encoding of the rest of the file. + + + + + Creates a new Stream which is backed by the content the StreamContentProvider was created for. + + For example if the StreamContentProvider was backing a file then GetStream re-opens the file and returns + the new stream. + + This method may be called multiple times. For example once to compile the code and again to get + the source code to display error messages. + + + + + Move the tokenizer past the next token and return its category. + + The token information associated with the token just scanned. + + + + Move the tokenizer past the next token. + + False if the end of stream has been reached, true otherwise. + + + + Get all tokens over a block of the stream. + + + + The scanner should return full tokens. If startLocation + length lands in the middle of a token, the full token + should be returned. + + + Tokens are read until at least given amount of characters is read or the stream ends. + A enumeration of tokens. + + + + Scan from startLocation to at least startLocation + length. + + The mininum number of characters to process while getting tokens. + + This method is used to determine state at arbitrary startLocation. + + False if the end of stream has been reached, true otherwise. + + + + The current internal state of the scanner. + + + + + The current startLocation of the scanner. + + + + + See also Microsoft.VisualStudio.Package.TokenTriggers. + + + + + Source code is a syntactically correct. + + + + + Source code represents an empty statement/expression. + + + + + Source code is already invalid and no suffix can make it syntactically correct. + + + + + Last token is incomplete. Source code can still be completed correctly. + + + + + Last statement is incomplete. Source code can still be completed correctly. + + + + + Defines a kind of the source code. The parser sets its initial state accordingly. + + + + + The code is an expression. + + + + + The code is a sequence of statements. + + + + + The code is a single statement. + + + + + The code is a content of a file. + + + + + The code is an interactive command. + + + + + The language parser auto-detects the kind. A syntax error is reported if it is not able to do so. + + + + + Source code reader. + + + + + Seeks the first character of a specified line in the text stream. + + Line number. The current position is assumed to be line #1. + + Returns true if the line is found, false otherwise. + + + + + Encoding that is used by the reader to convert binary data read from an underlying binary stream. + Null if the reader is reading from a textual source (not performing any byte to character transcoding). + + + + + Provides a StreamContentProvider for a stream of content backed by a file on disk. + + + + + Represents a location in source code. + + + + + Creates a new source location. + + The index in the source stream the location represents (0-based). + The line in the source stream the location represents (1-based). + The column in the source stream the location represents (1-based). + + + + Compares two specified location values to see if they are equal. + + One location to compare. + The other location to compare. + True if the locations are the same, False otherwise. + + + + Compares two specified location values to see if they are not equal. + + One location to compare. + The other location to compare. + True if the locations are not the same, False otherwise. + + + + Compares two specified location values to see if one is before the other. + + One location to compare. + The other location to compare. + True if the first location is before the other location, False otherwise. + + + + Compares two specified location values to see if one is after the other. + + One location to compare. + The other location to compare. + True if the first location is after the other location, False otherwise. + + + + Compares two specified location values to see if one is before or the same as the other. + + One location to compare. + The other location to compare. + True if the first location is before or the same as the other location, False otherwise. + + + + Compares two specified location values to see if one is after or the same as the other. + + One location to compare. + The other location to compare. + True if the first location is after or the same as the other location, False otherwise. + + + + Compares two specified location values. + + One location to compare. + The other location to compare. + 0 if the locations are equal, -1 if the left one is less than the right one, 1 otherwise. + + + + A location that is valid but represents no location at all. + + + + + An invalid location. + + + + + A minimal valid location. + + + + + The index in the source stream the location represents (0-based). + + + + + The line in the source stream the location represents (1-based). + + + + + The column in the source stream the location represents (1-based). + + + + + Whether the location is a valid location. + + True if the location is valid, False otherwise. + + + + Stores the location of a span of text in a source file. + + + + + Constructs a new span with a specific start and end location. + + The beginning of the span. + The end of the span. + + + + A valid span that represents no location. + + + + + An invalid span. + + + + + Compares two specified Span values to see if they are equal. + + One span to compare. + The other span to compare. + True if the spans are the same, False otherwise. + + + + Compares two specified Span values to see if they are not equal. + + One span to compare. + The other span to compare. + True if the spans are not the same, False otherwise. + + + + The start location of the span. + + + + + The end location of the span. Location of the first character behind the span. + + + + + Length of the span (number of characters inside the span). + + + + + Whether the locations in the span are valid. + + + + + Reads specified range of lines (or less) from the source unit. + Line numbers starts with 1. + + + + + Errors are reported to the specified sink. + Returns null if the parser cannot compile the code due to error(s). + + + + + Executes against a specified scope. + + + + + Executes against a specified scope and reports errors to the given error sink. + + + + + Executes in a new scope created by the language. + + + + + Executes in a new scope created by the language. + + + + + Executes in a new scope created by the language. + + + + + Identification of the source unit. Assigned by the host. + The format and semantics is host dependent (could be a path on file system or URL). + Empty string for anonymous source units. + + + + + LanguageContext of the language of the unit. + + + + + Unmapped span. + + + + + A token marking an end of stream. + + + + + A space, tab, or newline. + + + + + A block comment. + + + + + A single line comment. + + + + + A documentation comment. + + + + + A numeric literal. + + + + + A character literal. + + + + + A string literal. + + + + + A regular expression literal. + + + + + A keyword. + + + + + A directive (e.g. #line). + + + + + A punctuation character that has a specific meaning in a language. + + + + + A token that operates as a separator between two language elements. + + + + + An identifier (variable, $variable, @variable, @@variable, $variable$, function!, function?, [variable], i'variable', ...) + + + + + Braces, parenthesis, brackets. + + + + + Errors. + + + + + Converts a generic ICollection of T into an array of T. + + If the collection is already an array of T the original collection is returned. + + + + + Not all .NET enumerators throw exceptions if accessed in an invalid state. This type + can be used to throw exceptions from enumerators implemented in IronPython. + + + + + Wraps the provided enumerable into a ReadOnlyCollection{T} + + Copies all of the data into a new array, so the data can't be + changed after creation. The exception is if the enumerable is + already a ReadOnlyCollection{T}, in which case we just return it. + + + + + Console input stream (Console.OpenStandardInput) has a bug that manifests itself if reading small amounts of data. + This class wraps the standard input stream with a buffer that ensures that enough data are read from the underlying stream. + + + + + Requires the range [offset, offset + count] to be a subset of [0, array.Count]. + + Offset or count are out of range. + + + + Requires the range [offset, offset + count] to be a subset of [0, array.Count]. + + Offset or count are out of range. + + + + Requires the array and all its items to be non-null. + + + + + Requires the enumerable collection and all its items to be non-null. + + + + + Requires the range [offset, offset + count] to be a subset of [0, array.Count]. + + Array is null. + Offset or count are out of range. + + + + Presents a flat enumerable view of multiple dictionaries + + + + + Strongly-typed and parameterized string factory. + + + + + A string like "Cannot access member {1} declared on type {0} because the type contains generic parameters." + + + + + A string like "Type '{0}' is missing or cannot be loaded." + + + + + A string like "static property "{0}" of "{1}" can only be read through a type, not an instance" + + + + + A string like "static property "{0}" of "{1}" can only be assigned to through a type, not an instance" + + + + + A string like "Type parameter is {0}. Expected a delegate." + + + + + A string like "Cannot cast from type '{0}' to type '{1}" + + + + + A string like "unknown member type: '{0}'. " + + + + + A string like "The operation requires a non-generic type for {0}, but this represents generic types only" + + + + + A string like "Invalid operation: '{0}'" + + + + + A string like "Cannot create default value for type {0}." + + + + + A string like "Unhandled convert: {0}" + + + + + A string like "{0}.{1} has no publiclly visible method." + + + + + A string like "Extension type {0} must be public." + + + + + A string like "Invalid type of argument {0}; expecting {1}." + + + + + A string like "Field {0} is read-only" + + + + + A string like "Property {0} is read-only" + + + + + A string like "Expected event from {0}.{1}, got event from {2}.{3}." + + + + + A string like "expected bound event, got {0}." + + + + + A string like "Expected type {0}, got {1}." + + + + + A string like "can only write to member {0}." + + + + + A string like "Invalid stream type: {0}." + + + + + A string like "can't add another casing for identifier {0}" + + + + + A string like "can't add new identifier {0}" + + + + + A string like "Type '{0}' doesn't provide a suitable public constructor or its implementation is faulty: {1}" + + + + + A string like "Cannot emit constant {0} ({1})" + + + + + A string like "No implicit cast from {0} to {1}" + + + + + A string like "No explicit cast from {0} to {1}" + + + + + A string like "name '{0}' not defined" + + + + + A string like "Cannot create instance of {0} because it contains generic parameters" + + + + + A string like "Non-verifiable assembly generated: {0}:\nAssembly preserved as {1}\nError text:\n{2}\n" + + + + + A string like "Method precondition violated" + + + + + A string like "Invalid argument value" + + + + + A string like "Non-empty string required" + + + + + A string like "Non-empty collection required" + + + + + A string like "must by an Exception instance" + + + + + A string like "Type of test must be bool" + + + + + A string like "Type of the expression must be bool" + + + + + A string like "Empty string is not a valid path." + + + + + A string like "Invalid delegate type (Invoke method not found)." + + + + + A string like "expected only static property" + + + + + A string like "Property doesn't exist on the provided type" + + + + + A string like "Field doesn't exist on provided type" + + + + + A string like "Type doesn't have constructor with a given signature" + + + + + A string like "Type doesn't have a method with a given name." + + + + + A string like "Type doesn't have a method with a given name and signature." + + + + + A string like "Count must be non-negative." + + + + + A string like "arrayType must be an array type" + + + + + A string like "Either code or target must be specified." + + + + + A string like "RuleBuilder can only be used with delegates whose first argument is CallSite." + + + + + A string like "no instance for call." + + + + + A string like "Missing Test." + + + + + A string like "Missing Target." + + + + + A string like "Finally already defined." + + + + + A string like "Can not have fault and finally." + + + + + A string like "Fault already defined." + + + + + A string like "Global/top-level local variable names must be unique." + + + + + A string like "Generating code from non-serializable CallSiteBinder." + + + + + A string like "Specified path is invalid." + + + + + A string like "Dictionaries are not hashable." + + + + + A string like "language already registered." + + + + + A string like "The method or operation is not implemented." + + + + + A string like "No exception." + + + + + A string like "Already initialized." + + + + + A string like "CreateScopeExtension must return a scope extension." + + + + + A string like "Invalid number of parameters for the service." + + + + + A string like "Cannot change non-caching value." + + + + + A string like "No code to compile." + + + + + A string like "Queue empty." + + + + + A string like "Enumeration has not started. Call MoveNext." + + + + + A string like "Enumeration already finished." + + + + + A string like "Invalid output directory." + + + + + A string like "Invalid assembly name or file extension." + + + + + A string like "No default value for a given type." + + + + + A string like "Specified language provider type is not registered." + + + + + A string like "can't read from property" + + + + + A string like "can't write to property" + + + + + Strongly-typed and parameterized exception factory. + + + + + ArgumentException with message like "Either code or target must be specified." + + + + + InvalidOperationException with message like "Type parameter is {0}. Expected a delegate." + + + + + InvalidOperationException with message like "Cannot cast from type '{0}' to type '{1}" + + + + + InvalidOperationException with message like "unknown member type: '{0}'. " + + + + + InvalidOperationException with message like "RuleBuilder can only be used with delegates whose first argument is CallSite." + + + + + InvalidOperationException with message like "no instance for call." + + + + + InvalidOperationException with message like "Missing Test." + + + + + InvalidOperationException with message like "Missing Target." + + + + + TypeLoadException with message like "The operation requires a non-generic type for {0}, but this represents generic types only" + + + + + ArgumentException with message like "Invalid operation: '{0}'" + + + + + InvalidOperationException with message like "Finally already defined." + + + + + InvalidOperationException with message like "Can not have fault and finally." + + + + + InvalidOperationException with message like "Fault already defined." + + + + + ArgumentException with message like "Cannot create default value for type {0}." + + + + + ArgumentException with message like "Unhandled convert: {0}" + + + + + InvalidOperationException with message like "{0}.{1} has no publiclly visible method." + + + + + ArgumentException with message like "Global/top-level local variable names must be unique." + + + + + ArgumentException with message like "Generating code from non-serializable CallSiteBinder." + + + + + ArgumentException with message like "Specified path is invalid." + + + + + ArgumentTypeException with message like "Dictionaries are not hashable." + + + + + InvalidOperationException with message like "language already registered." + + + + + NotImplementedException with message like "The method or operation is not implemented." + + + + + InvalidOperationException with message like "No exception." + + + + + ArgumentException with message like "Extension type {0} must be public." + + + + + InvalidOperationException with message like "Already initialized." + + + + + InvalidImplementationException with message like "CreateScopeExtension must return a scope extension." + + + + + ArgumentException with message like "Invalid number of parameters for the service." + + + + + ArgumentException with message like "Invalid type of argument {0}; expecting {1}." + + + + + ArgumentException with message like "Cannot change non-caching value." + + + + + MissingMemberException with message like "Field {0} is read-only" + + + + + MissingMemberException with message like "Property {0} is read-only" + + + + + ArgumentException with message like "Expected event from {0}.{1}, got event from {2}.{3}." + + + + + ArgumentTypeException with message like "expected bound event, got {0}." + + + + + ArgumentTypeException with message like "Expected type {0}, got {1}." + + + + + MemberAccessException with message like "can only write to member {0}." + + + + + InvalidOperationException with message like "No code to compile." + + + + + ArgumentException with message like "Invalid stream type: {0}." + + + + + InvalidOperationException with message like "Queue empty." + + + + + InvalidOperationException with message like "Enumeration has not started. Call MoveNext." + + + + + InvalidOperationException with message like "Enumeration already finished." + + + + + InvalidOperationException with message like "can't add another casing for identifier {0}" + + + + + InvalidOperationException with message like "can't add new identifier {0}" + + + + + ArgumentException with message like "Invalid output directory." + + + + + ArgumentException with message like "Invalid assembly name or file extension." + + + + + ArgumentException with message like "Cannot emit constant {0} ({1})" + + + + + ArgumentException with message like "No implicit cast from {0} to {1}" + + + + + ArgumentException with message like "No explicit cast from {0} to {1}" + + + + + MissingMemberException with message like "name '{0}' not defined" + + + + + ArgumentException with message like "No default value for a given type." + + + + + ArgumentException with message like "Specified language provider type is not registered." + + + + + InvalidOperationException with message like "can't read from property" + + + + + InvalidOperationException with message like "can't write to property" + + + + + ArgumentException with message like "Cannot create instance of {0} because it contains generic parameters" + + + + + System.Security.VerificationException with message like "Non-verifiable assembly generated: {0}:\nAssembly preserved as {1}\nError text:\n{2}\n" + + + + + Gets a Func of CallSite, object * paramCnt, object delegate type + that's suitable for use in a non-strongly typed call site. + + + + diff --git a/Reference/IronPython/Net35/IronPython.dll b/Reference/IronPython/Net35/IronPython.dll new file mode 100644 index 000000000..545741c78 Binary files /dev/null and b/Reference/IronPython/Net35/IronPython.dll differ diff --git a/Reference/IronPython/Net35/IronPython.xml b/Reference/IronPython/Net35/IronPython.xml new file mode 100644 index 000000000..2378f63f1 --- /dev/null +++ b/Reference/IronPython/Net35/IronPython.xml @@ -0,0 +1,7533 @@ + + + + IronPython + + + + + Creates a method frame for tracking purposes and enforces recursion + + + + + Removes the frames from generated code for when we're compiling the tracing delegate + which will track the frames it's self. + + + + + Returns true if the node can throw, false otherwise. Used to determine + whether or not we need to update the current dynamic stack info. + + + + + A temporary variable to track if the current line number has been emitted via the fault update block. + + For example consider: + + try: + raise Exception() + except Exception, e: + # do something here + raise + + At "do something here" we need to have already emitted the line number, when we re-raise we shouldn't add it + again. If we handled the exception then we should have set the bool back to false. + + We also sometimes directly check _lineNoUpdated to avoid creating this unless we have nested exceptions. + + + + + A temporary variable to track the current line number + + + + + Fake ScopeStatement for FunctionCode's to hold on to after we have deserialized pre-compiled code. + + + + + Gets or creates the FunctionCode object for this FunctionDefinition. + + + + + Gets the expression for updating the dynamic stack trace at runtime when an + exception is thrown. + + + + + Gets the expression for the actual updating of the line number for stack traces to be available + + + + + Wraps the body of a statement which should result in a frame being available during + exception handling. This ensures the line number is updated as the stack is unwound. + + + + + The variable used to hold out parents closure tuple in our local scope. + + + + + Gets the expression associated with the local CodeContext. If the function + doesn't have a local CodeContext then this is the global context. + + + + + True if this scope accesses a variable from an outer scope. + + + + + True if an inner scope is accessing a variable defined in this scope. + + + + + True if we are forcing the creation of a dictionary for storing locals. + + This occurs for calls to locals(), dir(), vars(), unqualified exec, and + from ... import *. + + + + + True if variables can be set in a late bound fashion that we don't + know about at code gen time - for example via from foo import *. + + This is tracked independently of the ContainsUnqualifiedExec/NeedsLocalsDictionary + + + + + Variables that are bound in an outer scope - but not a global scope + + + + + Variables that are bound to the global scope + + + + + Variables that are referred to from a nested scope and need to be + promoted to cells. + + + + + Provides a place holder for the expression which represents + a FunctionCode. For functions/classes this gets updated after + the AST has been generated because the FunctionCode needs to + know about the tree which gets generated. For modules we + immediately have the value because it always comes in as a parameter. + + + + + Reducible node so that re-writing for profiling does not occur until + after the script code has been completed and is ready to be compiled. + + Without this extra node profiling would force reduction of the node + and we wouldn't have setup our constant access correctly yet. + + + + + A global allocator that puts all of the globals into an array access. The array is an + array of PythonGlobal objects. We then just close over the array for any inner functions. + + Once compiled a RuntimeScriptCode is produced which is closed over the entire execution + environment. + + + + + Specifies the compilation mode which will be used during the AST transformation + + + + + Compilation will proceed in a manner in which the resulting AST can be serialized to disk. + + + + + Compilation will use a type and declare static fields for globals. The resulting type + is uncollectible and therefore extended use of this will cause memory leaks. + + + + + Compilation will use an array for globals. The resulting code will be fully collectible + and once all references are released will be collected. + + + + + Compilation will force all global accesses to do a full lookup. This will also happen for + any unbound local references. This is the slowest form of code generation and is only + used for exec/eval code where we can run against an arbitrary dictionary. + + + + + Implements globals which are backed by a static type, followed by an array if the static types' slots become full. The global + variables are stored in static fields on a type for fast access. The type also includes fields for constants and call sites + so they can be accessed much fasetr. + + We don't generate any code into the type though - DynamicMethod's are much faster for code gen then normal ref emit. + + + Implements globals which are backed by a static type, followed by an array if the static types' slots become full. The global + variables are stored in static fields on a type for fast access. The type also includes fields for constants and call sites + so they can be accessed much fasetr. + + We don't generate any code into the type though - DynamicMethod's are much faster for code gen then normal ref emit. + + + + Ensures the underlying array is long enough to accomodate the given index + The context storage type corresponding to the given index + + + Ensures the underlying array is long enough to accomodate the given index + The constant storage type corresponding to the given index + + + Ensures the underlying array is long enough to accomodate the given index + The global storage type corresponding to the given index + + + Ensures the underlying array is long enough to accomodate the given index + The site storage type corresponding to the given index + + + + Not used. + + + + + Not used. + + + + + PythonWalker class - The Python AST Walker (default result is true) + + + + + Not an actual node. We don't create this, but it's here for compatibility. + + + + + Interface used to mark objects which contain a dictionary of custom attributes that shadow + their existing attributes in a dynamic fashion. + + + + + Ensures that a non-null IDictionary instance is created for CustomAttributes and + returns it. + + + + + Meta-object which allows IPythonExpandable objects to behave like Python objects in their + ability to dynamically add and remove new or existing custom attributes, generally shadowing + existing built-in members. + + Getting: Member accesses first consult the object's CustomAttributes dictionary, then fall + through to the underlying object. + + Setting: Values can be bound to any member name, shadowing any existing attributes except + public non-PythonHidden fields and properties, which will bypass the dictionary. Thus, + it is possible for SetMember to fail, for example if the property is read-only or of + the wrong type. + + Deleting: Any member represented in the dictionary can be deleted, re-exposing the + underlying member if it exists. Any other deletions will fail. + + + + + Provides a way for the binder to provide a custom error message when lookup fails. Just + doing this for the time being until we get a more robust error return mechanism. + + + + + Provides a way for the binder to provide a custom error message when lookup fails. Just + doing this for the time being until we get a more robust error return mechanism. + + + + + Gets the PythonBinder associated with tihs CodeContext + + + + + Performs .NET member resolution. This looks within the given type and also + includes any extension members. Base classes and their extension members are + not searched. + + + + + Performs .NET member resolution. This looks within the given type and also + includes any extension members. Base classes and their extension members are + not searched. + + This version allows PythonType's for protected member resolution. It shouldn't + be called externally for other purposes. + + + + + Performs .NET member resolution. This looks the type and any base types + for members. It also searches for extension members in the type and any base types. + + + + + Gets the member names which are defined in this type and any extension members. + + This search does not include members in any subtypes or their extension members. + + + + + Gets the member names which are defined in the type and any subtypes. + + This search includes members in the type and any subtypes as well as extension + types of the type and its subtypes. + + + + + Creates the initial table of extension types. These are standard extension that we apply + to well known .NET types to make working with them better. Being added to this table does + not make a type a Python type though so that it's members are generally accessible w/o an + import clr and their type is not re-named. + + + + + Creates a table of standard .NET types which are also standard Python types. These types have a standard + set of extension types which are shared between all runtimes. + + + + + Event handler for when our domain manager has an assembly loaded by the user hosting the script + runtime. Here we can gather any information regarding extension methods. + + Currently DLR-style extension methods become immediately available w/o an explicit import step. + + + + + Provides a cache from Type/name -> PythonTypeSlot and also allows access to + all members (and remembering whether all members are cached). + + + + + Writes to a cache the result of a type lookup. Null values are allowed for the slots and they indicate that + the value does not exist. + + + + + Looks up a cached type slot for the specified member and type. This may return true and return a null slot - that indicates + that a cached result for a member which doesn't exist has been stored. Otherwise it returns true if a slot is found or + false if it is not. + + + + + Looks up a cached member group for the specified member and type. This may return true and return a null group - that indicates + that a cached result for a member which doesn't exist has been stored. Otherwise it returns true if a group is found or + false if it is not. + + + + + Checks to see if all members have been populated for the provided type. + + + + + Populates the type with all the provided members and marks the type + as being fully cached. + + The dictionary is used for the internal storage and should not be modified after + providing it to the cache. + + + + + Returns an enumerable object which provides access to all the members of the provided type. + + The caller must check that the type is fully cached and populate the cache if it isn't before + calling this method. + + + + + Implements a built-in module which is instanced per PythonContext. + + Implementers can subclass this type and then have a module which has efficient access + to internal state (this doesn't need to go through PythonContext.GetModuleState). These + modules can also declare module level globals which they'd like to provide efficient + access to by overloading GetGlobalVariableNames. When Initialize is called these + globals are provided and can be cached in the instance for fast global access. + + Just like normal static modules these modules are registered with the PythonModuleAttribute. + + + + + Initializes the module for it's first usage. By default this calls PerformModuleReload with the + the dictionary. + + The CodeContext for the module. + A list of globals which have optimize access. Contains at least all of the global variables reutrned by GetGlobalVariableNames. + + + + Gets a list of variable names which should have optimized storage (instances of PythonGlobal objects). + The module receives the global objects during the Initialize call and can hold onto them for + direct access to global members. + + + + + Called when the user attempts to reload() on your module and by the base class Initialize method. + + This provides an opportunity to allocate any per-module data which is not simply function definitions. + + A common usage here is to create exception objects which are allocated by the module using PythonExceptions.CreateSubType. + + + + + Provides access to the PythonContext which this module was created for. + + + + + Provides access to the CodeContext for the module. Returns null before Initialize() is called. + + + + + Copy on write constant dictionary storage used for dictionaries created with constant items. + + + + + Abstract base class for all PythonDictionary storage. + + Defined as a class instead of an interface for performance reasons. Also not + using IDictionary* for keeping a simple interface. + + Full locking is defined as being on the DictionaryStorage object it's self, + not an internal member. This enables subclasses to provide their own locking + aruond large operations and call lock free functions. + + + + + Adds items from this dictionary into the other dictionary + + + + + Provides fast access to the __path__ attribute if the dictionary storage supports caching it. + + + + + Provides fast access to the __package__ attribute if the dictionary storage supports caching it. + + + + + Provides fast access to the __builtins__ attribute if the dictionary storage supports caching it. + + + + + Provides fast access to the __name__ attribute if the dictionary storage supports caching it. + + + + + Provides fast access to the __import__ attribute if the dictionary storage supports caching it. + + + + + Provides more specific type information for Python dictionaries which are not strongly typed. + + This attribute can be applied to fields, parameters, proeprties, and return values. It can be + inspected to get type information about the types of the keys and values of the expected + dictionary or the returned dictionary. + + + + + Adapts an IDictionary[object, object] for use as a PythonDictionary used for + our debug frames. Also hides the special locals which start with $. + + + + + An interface that is implemented on DynamicMetaObjects. + + This allows objects to opt-into custom conversions when calling + COM APIs. The IronPython binders all call this interface before + doing any COM binding. + + + + + Captures and flows the state of executing code from the generated + Python code into the IronPython runtime. + + + + + Creates a new CodeContext which is backed by the specified Python dictionary. + + + + + Attempts to lookup the provided name in this scope or any outer scope. + + + + + Looks up a global variable. If the variable is not defined in the + global scope then built-ins is consulted. + + + + + Attempts to lookup the variable in the local scope. + + + + + Removes a variable from the local scope. + + + + + Sets a variable in the local scope. + + + + + Gets a variable from the global scope. + + + + + Sets a variable in the global scope. + + + + + Removes a variable from the global scope. + + + + + Returns the dictionary associated with __builtins__ if one is + set or null if it's not available. If __builtins__ is a module + the module's dictionary is returned. + + + + + Gets the module state for top-level code. + + + + + Gets the DLR scope object that corresponds to the global variables of this context. + + + + + Gets the PythonContext which created the CodeContext. + + + + + Gets the dictionary for the global variables from the ModuleContext. + + + + + True if this global context should display CLR members on shared types (for example .ToString on int/bool/etc...) + + False if these attributes should be hidden. + + + + + Gets the dictionary used for storage of local variables. + + + + + Marks a type so that IronPython will not expose the IEnumerable interface out as + __iter__ + + + + + ArgBuilder which provides the CodeContext parameter to a method. + + + + + Small reducable node which just fetches the value from a ClosureCell + object. Like w/ global variables the compiler recognizes these on + sets and turns them into assignments on the python global object. + + + + + Creates the storage for the closure cell. If this is a closure over a parameter it + captures the initial incoming parameter value. + + + + + Reduces the closure cell to a read of the value stored in the cell. + + + + + Assigns a value to the closure cell. + + + + + Removes the current value from the closure cell. + + + + + Gets the expression which points at the closure cell. + + + + + The original expression for the incoming parameter if this is a parameter closure. Otherwise + the value is null. + + + + + Gets the PythonVariable for which this closure expression was created. + + + + + Tracking for variables lifted into closure objects. Used to store information in a function + about the outer variables it accesses. + + + + + When finding a yield return or yield break, this rewriter flattens out + containing blocks, scopes, and expressions with stack state. All + scopes encountered have their variables promoted to the generator's + closure, so they survive yields. + + + + + Spills the right side into a temp, and replaces it with its temp. + Returns the expression that initializes the temp. + + + + + Makes an assignment to this variable. Pushes the assignment as far + into the right side as possible, to allow jumps into it. + + + + + Accesses the property of a tuple. The node can be created first and then the tuple and index + type can be filled in before the tree is actually generated. This enables creation of these + nodes before the tuple type is actually known. + + + + + Represents code which can be lazily compiled. + + The code is created in an AST which provides the Expression of T and + whether or not the code should be interpreted. For non-pre compiled + scenarios the code will not be compiled until the 1st time it is run. + + For pre-compiled scenarios the code is IExpressionSerializable and will + turn into a normal pre-compiled method. + + + + + Marks a type so that IronPython will not expose types which have GetMemberNames + as having a __dir__ method. + + Also suppresses __dir__ on something which implements IDynamicMetaObjectProvider + but is not an IPythonObject. + + + + + Marks a type so that IronPython will not expose the ICollection interface out as + __len__. + + + + + Marks a type so that IronPython will not expose the IDisposable interface out as + __enter__ and __exit__ methods of a context manager. + + + + + Marks a type so that IronPython will not expose the IEnumerable interface out as + __contains__ + + + + + Singleton used for dictionaries which contain no items. + + + + + Represents the set of extension methods which are loaded into a module. + + This set is immutable (as far the external viewer is considered). When a + new extension method set is loaded into a module we create a new ExtensionMethodsSet object. + + Multiple modules which have the same set of extension methods use the same set. + + + + + Returns all of the extension methods with the given name. + + + + + Returns all of the extension methods which are applicable for the given type. + + + + + Tracks the extension types that are loaded for a given assembly. + + We can have either types, namespaces, or a full assembly added as a reference. + + When the user just adds types we just add them to the type hash set. + + When the user adds namespaces we add them to the namespaces hashset. On the + next lookup we'll lazily load the types from that namespace and put them in Types. + + When the user adds assemblies we set the value to the NotYetLoadedButFullAssembly + value. The next load request will load the types from that namespace and put them + in Types. When we do that we'll mark the assembly as FullyLoaded so we don't + have to go through that again if the user adds a namespace. + + + + + Return a copy of this tuple's data array. + + + + + ModuleDictionaryStorage for a built-in module which is bound to a specific instance. + + These modules don't need to use PythonContext.GetModuleState() for storage and therefore + can provide efficient access to internal variables. They can also cache PythonGlobal + objects and provide efficient access to module globals. + + To the end user these modules appear just like any other module. These modules are + implemented by subclassing the BuiltinPythonModule class. + + + + + Enables lazy initialization of module dictionaries. + + + + + Gets all of the extra names and values stored in the dictionary. + + + + + Attemps to sets a value in the extra keys. Returns true if the value is set, false if + the value is not an extra key. + + + + + Attempts to get a value from the extra keys. Returns true if the value is an extra + key and has a value. False if it is not an extra key or doesn't have a value. + + + + + Attempts to remove the key. Returns true if the key is removed, false + if the key was not removed, or null if the key is not an extra key. + + + + + A TypeSlot is an item that gets stored in a type's dictionary. Slots provide an + opportunity to customize access at runtime when a value is get or set from a dictionary. + + + + + Gets the value stored in the slot for the given instance binding it to an instance if one is provided and + the slot binds to instances. + + + + + Sets the value of the slot for the given instance. + + true if the value was set, false if it can't be set + + + + Deletes the value stored in the slot from the instance. + + true if the value was deleted, false if it can't be deleted + + + + Gets an expression which is used for accessing this slot. If the slot lookup fails the error expression + is used again. + + The default implementation just calls the TryGetValue method. Subtypes of PythonTypeSlot can override + this and provide a more optimal implementation. + + + + + True if generating code for gets can result in more optimal accesses. + + + + + True if TryGetValue will always succeed, false if it may fail. + + This is used to optimize away error generation code. + + + + + Defines the internal interface used for accessing weak references and adding finalizers + to user-defined types. + + + + + Gets the current WeakRefTracker for an object that can be used to + append additional weak references. + + + + + Attempts to set the WeakRefTracker for an object. Used on the first + addition of a weak ref tracker to an object. If the object doesn't + support adding weak references then it returns false. + + + + + Sets a WeakRefTracker on an object for the purposes of supporting finalization. + All user types (new-style and old-style) support finalization even if they don't + support weak-references, and therefore this function always succeeds. Note the + slot used to store the WeakRefTracker is still shared between SetWeakRef and + SetFinalizer if a type supports both. + + + + + + Provides a list of all the members of an instance. ie. all the keys in the + dictionary of the object. Note that it can contain objects that are not strings. + + Such keys can be added in IronPython using syntax like: + obj.__dict__[100] = someOtherObject + + This Python specific version also supports filtering based upon the show cls + flag by flowing in the code context. + + + + + Validates that the current self object is usable for this method. + + + + + Marks a class as being hidden from the Python hierarchy. This is applied to the base class + and then all derived types will not see the base class in their hierarchy and will not be + able to access members declaredo on the base class. + + + + + Provides more specific type information for Python lists which are not strongly typed. + + This attribute can be applied to fields, parameters, proeprties, and return values. It can be + inspected to get type information about the types of the values of the expected + list or the returned list. + + + + + Captures the globals and other state of module code. + + + + + Creates a new ModuleContext which is backed by the specified dictionary. + + + + + Creates a new ModuleContext for the specified module. + + + + + Initializes __builtins__ for the module scope. + + + + + Gets the dictionary used for the global variables in the module + + + + + Gets the language context which created this module. + + + + + Gets the DLR Scope object which is associated with the modules dictionary. + + + + + Gets the global CodeContext object which is used for execution of top-level code. + + + + + Gets the module object which this code is executing in. + + This module may or may not be published in sys.modules. For user defined + code typically the module gets published at the start of execution. But if + this ModuleContext is attached to a Scope, or if we've just created a new + module context for executing code it will not be in sys.modules. + + + + + Gets the features that code has been compiled with in the module. + + + + + Gets or sets whether code running in this context should display + CLR members (for example .ToString on objects). + + + + + Cached global value. Created and maintained on a per-language basis. Default + implementation returns a singleton which indicates caching is not occuring. + + + + + Creates a new ModuleGlobalCache with the specified value. + + + + + Event handler for when the value has changed. Language implementors should call this when + the cached value is invalidated. + + + + + True if the ModuleGlobalCache is participating in a caching strategy. + + + + + True if there is currently a value associated with this global variable. False if + it is currently unassigned. + + + + + Gets or sets the current cached value + + + + + Enable true division (1/2 == .5) + + + + + Indicates that .NET methods such as .ToString should be available on Python objects. + + + + + Indicates that the module should be generated in an optimal form which will result + in it being uncollectable. + + + + + Indicates when the module should be executed immedatiately upon creation. + + + + + Enable usage of the with statement + + + + + Enable absolute imports + + + + + Indiciates that __builtins__ should not be set in the module + + + + + Indiciates that when the module is initialized it should set __builtins__ to the __builtin__ module + instead of the __builtin__ dictionary. + + + + + Marks code as being created for exec, eval. Code generated this way will + be capable of running against different scopes and will do lookups at runtime + for free global variables. + + + + + Indiciates that the first line of code should be skipped. + + + + + Enable usage of print as a function for better compatibility with Python 3.0. + + + + + Forces the code to be interpreted rather than compiled + + + + + String Literals should be parsed as Unicode strings + + + + + Include comments in the parse tree + + + + + Generated code should support light exceptions + + + + + Manages the acquisition of profiling data for a single ScriptRuntime + + + + + Get the unique Profiler instance for this ScriptRuntime + + + + + Given a MethodBase, return an index into the array of perf data. Treat each + CLR method as unique. + + + + + Given the unique name of something we're profiling, return an index into the array of perf data. + + + + + Add a new profiler entry. Not all names are unique. + + + + + Gets the current summary of profile data + + + + + Resets the current summary of profile data back to zero + + + + + Adds profiling calls to a Python method. + Calculates both the time spent only in this method + + + + + Wraps a call to a MethodInfo with profiling capture for that MethodInfo + + + + + Encapsulates profiler data to return to clients + + + + + Marks that this built-in method should be treated as external by the profiler. + When placed on a call emitted into a Python method, all the time spent in this + call will still show up in its parent's inclusive time, but will not be + part of its exclusive time. + + + + + Gets the closure tuple from our parent context. + + + + + PythonWalkerNonRecursive class - The Python AST Walker (default result is false) + + + + + Pulls the closure tuple from our function/generator which is flowed into each function call. + + + + + Returns an expression which creates the function object. + + + + + Creates the LambdaExpression which is the actual function body. + + + + + Creates the LambdaExpression which implements the body of the function. + + The functions signature is either "object Function(PythonFunction, ...)" + where there is one object parameter for each user defined parameter or + object Function(PythonFunction, object[]) for functions which take more + than PythonCallTargets.MaxArgs arguments. + + + + + Determines delegate type for the Python function + + + + + Scope for the comprehension. Because scopes are usually statements and comprehensions are expressions + this doesn't actually show up in the AST hierarchy and instead hangs off the comprehension expression. + + + + + Provides globals for when we need to lookup into a dictionary for each global access. + + This is the slowest form of globals and is only used when we need to run against an + arbitrary dictionary given to us by a user. + + + + + Provides a wrapper around "dynamic" expressions which we've opened coded (for optimized code generation). + + This lets us recognize both normal Dynamic and our own Dynamic expressions and apply the combo binder on them. + + + + + A ScriptCode which can be saved to disk. We only create this when called via + the clr.CompileModules API. This ScriptCode does not support running. + + + + + Parameter base class + + + + + Position of the parameter: 0-based index + + + + + Parameter name + + + + + Top-level ast for all Python code. Typically represents a module but could also + be exec or eval code. + + + + + Creates a new PythonAst without a body. ParsingFinished should be called afterwards to set + the body. + + + + + Called when parsing is complete, the body is built, the line mapping and language features are known. + + This is used in conjunction with the constructor which does not take a body. It enables creating + the outer most PythonAst first so that nodes can always have a global parent. This lets an un-bound + tree to still provide it's line information immediately after parsing. When we set the location + of each node during construction we also set the global parent. When we name bind the global + parent gets replaced with the real parent ScopeStatement. + + a mapping of where each line begins + The body of code + The language features which were set during parsing. + + + + Binds an AST and makes it capable of being reduced and compiled. Before calling Bind an AST cannot successfully + be reduced. + + + + + Creates a variable at the global level. Called for known globals (e.g. __name__), + for variables explicitly declared global by the user, and names accessed + but not defined in the lexical scope. + + + + + Reduces the PythonAst to a LambdaExpression of type Type. + + + + + Returns a ScriptCode object for this PythonAst. The ScriptCode object + can then be used to execute the code against it's closed over scope or + to execute it against a different scope. + + + + + Rewrites the tree for performing lookups against globals instead of being bound + against the optimized scope. This is used if the user compiles optimied code and then + runs it against a different scope. + + + + + True division is enabled in this AST. + + + + + True if the with statement is enabled in this AST. + + + + + True if absolute imports are enabled + + + + + True if this is on-disk code which we don't really have an AST for. + + + + + Represents a reference to a name. A PythonReference is created for each name + referred to in a scope (global, class, or function). + + + + + True if the user provided a step parameter (either providing an explicit parameter + or providing an empty step parameter) false if only start and stop were provided. + + + + + The statements under the try-block. + + + + + Array of except (catch) blocks associated with this try. NULL if there are no except blocks. + + + + + The body of the optional Else block for this try. NULL if there is no Else block. + + + + + The body of the optional finally associated with this try. NULL if there is no finally block. + + + + + Transform multiple python except handlers for a try block into a single catch body. + + The variable for the exception in the catch block. + Null if there are no except handlers. Else the statement to go inside the catch handler + + + + Surrounds the body of an except block w/ the appropriate code for maintaining the traceback. + + + + + True iff there is a path in control flow graph on which the variable is used before initialized (assigned or deleted). + + + + + True iff the variable is referred to from the inner scope. + + + + + Local variable. + + Local variables can be referenced from nested lambdas + + + + + Parameter to a LambdaExpression + + Like locals, they can be referenced from nested lambdas + + + + + Global variable + + Should only appear in global (top level) lambda. + + + + + WithStatement is translated to the DLR AST equivalent to + the following Python code snippet (from with statement spec): + + mgr = (EXPR) + exit = mgr.__exit__ # Not calling it yet + value = mgr.__enter__() + exc = True + try: + VAR = value # Only if "as VAR" is present + BLOCK + except: + # The exceptional case is handled here + exc = False + if not exit(*sys.exc_info()): + raise + # The exception is swallowed if exit() returns true + finally: + # The normal and non-local-goto cases are handled here + if exc: + exit(None, None, None) + + + + + + A ScriptCode which has been loaded from an assembly which is saved on disk. + + + + + Creates a fake PythonAst object which is represenative of the on-disk script code. + + + + + Base class for all of our fast get delegates. This holds onto the + delegate and provides the Update function. + + + + + Updates the call site when the current rule is no longer applicable. + + + + + Base class for all of our fast set delegates. This holds onto the + delegate and provides the Update and Optimize functions. + + + + + Updates the call site when the current rule is no longer applicable. + + + + + Provides cached global variable for modules to enable optimized access to + module globals. Both the module global value and the cached value can be held + onto and the cached value can be invalidated by the providing LanguageContext. + + The cached value is provided by the LanguageContext.GetModuleCache API. + + + + + Small reducable node which just fetches the value from a PythonGlobal + object. The compiler recognizes these on sets and turns them into + assignments on the python global object. + + + + + Represents a script code which can be dynamically bound to execute against + arbitrary Scope objects. This is used for code when the user runs against + a particular scope as well as for exec and eval code as well. It is also + used when tracing is enabled. + + + + + Represents a script code which can be consumed at runtime as-is. This code has + no external dependencies and is closed over its scope. + + + + + Helper class for implementing the Python class. + + This is exposed as a service through PythonEngine and the helper class + uses this service to get the correct remoting semantics. + + + + + Returns an ObjectHandle to a delegate of type Action[Action] which calls the current + command dispatcher. + + + + + Marks that the return value of a function might include NotImplemented. + + This is added to an operator method to ensure that all necessary methods are called + if one cannot guarantee that it can perform the comparison. + + + + + Provides support for emitting warnings when built in methods are invoked at runtime. + + + + + Backwards compatible Convert for the old sites that need to flow CodeContext + + + + + Creates a new InvokeBinder which will call with positional splatting. + + The signature of the target site should be object(function), object[], retType + + + + + + + Creates a new InvokeBinder which will call with positional and keyword splatting. + + The signature of the target site should be object(function), object[], dictionary, retType + + + + + Fallback action for performing an invoke from Python. We translate the + CallSignature which supports splatting position and keyword args into + their expanded form. + + + + + Gets the PythonContext which the CallSiteBinder is associated with. + + + + + Fallback action for performing a new() on a foreign IDynamicMetaObjectProvider. used + when call falls back. + + + + + Python's Invoke is a non-standard action. Here we first try to bind through a Python + internal interface (IPythonInvokable) which supports CallSigantures. If that fails + and we have an IDO then we translate to the DLR protocol through a nested dynamic site - + this includes unsplatting any keyword / position arguments. Finally if it's just a plain + old .NET type we use the default binder which supports CallSignatures. + + + + + Interface used to mark objects as being invokable from Python. These objects support + calling with splatted positional and keyword arguments. + + + + + Provides binding logic which is implemented to follow various Python protocols. This includes + things such as calling __call__ to perform calls, calling __nonzero__/__len__ to convert to + bool, calling __add__/__radd__ to do addition, etc... + + This logic gets shared between both the IDynamicMetaObjectProvider implementation for Python objects as well + as the Python sites. This ensures the logic we follow for our builtin types and user defined + types is identical and properly conforming to the various protocols. + + + + + Gets a MetaObject which converts the provided object to a bool using __nonzero__ or __len__ + protocol methods. This code is shared between both our fallback for a site and our MetaObject + for user defined objects. + + + + + Used for conversions to bool + + + + + Creates a rule for the contains operator. This is exposed via "x in y" in + IronPython. It is implemented by calling the __contains__ method on x and + passing in y. + + If a type doesn't define __contains__ but does define __getitem__ then __getitem__ is + called repeatedly in order to see if the object is there. + + For normal .NET enumerables we'll walk the iterator and see if it's present. + + + + + Helper to handle a comparison operator call. Checks to see if the call can + return NotImplemented and allows the caller to modify the expression that + is ultimately returned (e.g. to turn __cmp__ into a bool after a comparison) + + + + + calls __coerce__ for old-style classes and performs the operation if the coercion is successful. + + + + + Makes the comparison rule which returns an int (-1, 0, 1). TODO: Better name? + + + + + Python has three protocols for slicing: + Simple Slicing x[i:j] + Extended slicing x[i,j,k,...] + Long Slice x[start:stop:step] + + The first maps to __*slice__ (get, set, and del). + This takes indexes - i, j - which specify the range of elements to be + returned. In the slice variants both i, j must be numeric data types. + The 2nd and 3rd are both __*item__. + This receives a single index which is either a Tuple or a Slice object (which + encapsulates the start, stop, and step values) + + This is in addition to a simple indexing x[y]. + + For simple slicing and long slicing Python generates Operators.*Slice. For + the extended slicing and simple indexing Python generates a Operators.*Item + action. + + Extended slicing maps to the normal .NET multi-parameter input. + + So our job here is to first determine if we're to call a __*slice__ method or + a __*item__ method. + + + + + Helper to convert all of the arguments to their known types. + + + + + Gets the arguments that need to be provided to __*item__ when we need to pass a slice object. + + + + + Helper to get the symbols for __*item__ and __*slice__ based upon if we're doing + a get/set/delete and the minimum number of arguments required for each of those. + + + + + Checks if a coercion check should be performed. We perform coercion under the following + situations: + 1. Old instances performing a binary operator (excluding rich comparisons) + 2. User-defined new instances calling __cmp__ but only if we wouldn't dispatch to a built-in __coerce__ on the parent type + + This matches the behavior of CPython. + + + + + + Produces an error message for the provided message and type names. The error message should contain + string formatting characters ({0}, {1}, etc...) for each of the type names. + + + + + Delegate for finishing the comparison. This takes in a condition and a return value and needs to update the ConditionalBuilder + with the appropriate resulting body. The condition may be null. + + + + + Base class for calling indexers. We have two subclasses that target built-in functions and user defined callable objects. + + The Callable objects get handed off to ItemBuilder's which then call them with the appropriate arguments. + + + + + Creates a new CallableObject. If BuiltinFunction is available we'll create a BuiltinCallable otherwise + we create a SlotCallable. + + + + + Gets the arguments in a form that should be used for extended slicing. + + Python defines that multiple tuple arguments received (x[1,2,3]) get + packed into a Tuple. For most .NET methods we just want to expand + this into the multiple index arguments. For slots and old-instances + we want to pass in the tuple + + + + + Adds the target of the call to the rule. + + + + + Subclass of Callable for a built-in function. This calls a .NET method performing + the appropriate bindings. + + + + + Callable to a user-defined callable object. This could be a Python function, + a class defining __call__, etc... + + + + + Base class for building a __*item__ or __*slice__ call. + + + + + Derived IndexBuilder for calling __*slice__ methods + + + + + Derived IndexBuilder for calling __*item__ methods. + + + + + Common helpers used by the various binding logic. + + + + + Tries to get the BuiltinFunction for the given name on the type of the provided MetaObject. + + Succeeds if the MetaObject is a BuiltinFunction or BuiltinMethodDescriptor. + + + + + Gets the best CallSignature from a MetaAction. + + The MetaAction should be either a Python InvokeBinder, or a DLR InvokeAction or + CreateAction. For Python we can use a full-fidelity + + + + + + + Transforms an invoke member into a Python GetMember/Invoke. The caller should + verify that the given attribute is not resolved against a normal .NET class + before calling this. If it is a normal .NET member then a fallback InvokeMember + is preferred. + + + + + Determines if the type associated with the first MetaObject is a subclass of the + type associated with the second MetaObject. + + + + + Adds a try/finally which enforces recursion limits around the target method. + + + + + Helper to do fallback for Invoke's so we can handle both StandardAction and Python's + InvokeBinder. + + + + + Converts arguments into a form which can be used for COM interop. + + The argument is only converted if we have an IronPython specific + conversion when calling COM methods. + + + + + Converts a single argument into a form which can be used for COM + interop. + + The argument is only converted if we have an IronPython specific + conversion when calling COM methods. + + + + + Builds up a series of conditionals when the False clause isn't yet known. We can + keep appending conditions and if true's. Each subsequent true branch becomes the + false branch of the previous condition and body. Finally a non-conditional terminating + branch must be added. + + + + + Adds a new conditional and body. The first call this becomes the top-level + conditional, subsequent calls will have it added as false statement of the + previous conditional. + + + + + Adds a new condition to the last added body / condition. + + + + + Adds the non-conditional terminating node. + + + + + Gets the resulting meta object for the full body. FinishCondition + must have been called. + + + + + Adds a variable which will be scoped at the level of the final expression. + + + + + Returns true if no conditions have been added + + + + + Returns true if a final, non-conditional, body has been added. + + + + + Creates a target which creates a new dynamic method which contains a single + dynamic site that invokes the callable object. + + TODO: This should be specialized for each callable object + + + + + Various helpers related to calling Python __*__ conversion methods + + + + + Helper for falling back - if we have a base object fallback to it first (which can + then fallback to the calling site), otherwise fallback to the calling site. + + + + + Helper for falling back - if we have a base object fallback to it first (which can + then fallback to the calling site), otherwise fallback to the calling site. + + + + + Checks to see if this type has __getattribute__ that overrides all other attribute lookup. + + This is more complex then it needs to be. The problem is that when we have a + mixed new-style/old-style class we have a weird __getattribute__ defined. When + we always dispatch through rules instead of PythonTypes it should be easy to remove + this. + + + + + Looks up the associated PythonTypeSlot from the object. Indicates if the result + came from a standard .NET type in which case we will fallback to the sites binder. + + + + + Helper for falling back - if we have a base object fallback to it first (which can + then fallback to the calling site), otherwise fallback to the calling site. + + + + + Helper for falling back - if we have a base object fallback to it first (which can + then fallback to the calling site), otherwise fallback to the calling site. + + + + + Provides the lookup logic for resolving a Python object. Subclasses + provide the actual logic for producing the binding result. Currently + there are two forms of the binding result: one is the DynamicMetaObject + form used for non-optimized bindings. The other is the Func of CallSite, + object, CodeContext, object form which is used for fast binding and + pre-compiled rules. + + + + + GetBinder which produces a DynamicMetaObject. This binder always + successfully produces a DynamicMetaObject which can perform the requested get. + + + + + Makes a rule which calls a user-defined __getattribute__ function and falls back to __getattr__ if that + raises an AttributeError. + + slot is the __getattribute__ method to be called. + + + + + Checks a range of the MRO to perform old-style class lookups if any old-style classes + are present. We will call this twice to produce a search before a slot and after + a slot. + + + + + Helper for falling back - if we have a base object fallback to it first (which can + then fallback to the calling site), otherwise fallback to the calling site. + + + + + Custom dynamic site kinds for simple sites that just take a fixed set of parameters. + + + + + Unary operator. + + Gets various documentation about the object returned as a string + + + + + Unary operator. + + Gets information about the type of parameters, returned as a string. + + + + + Unary operator. + + Checks whether the object is callable or not, returns true if it is. + + + + + Binary operator. + + Checks to see if the instance contains another object. Returns true or false. + + + + + Unary operator. + + Returns the number of items stored in the object. + + + + + Binary operator. + + Compares two instances returning an integer indicating the relationship between them. May + throw if the object types are uncomparable. + + + + + Binary operator. + + Returns both the dividend and quotioent of x / y. + + + + + Unary operator. + + Get the absolute value of the instance. + + + + + Unary operator. + + Gets the positive value of the instance. + + + + + Unary operator. + + Negates the instance and return the new value. + + + + + Unary operator. + + Returns the ones complement of the instance. + + + + + Unary operator. + + Boolean negation + + + + + Unary operator. + + Negation, returns object + + + + + Get enumerator for iteration binder. Returns a KeyValuePair<IEnumerator, IDisposable> + + The IEnumerator is used for iteration. The IDisposable is provided if the object was an + IEnumerable or IEnumerable<T> and is a disposable object. + + + + Operator for performing add + + + Operator for performing sub + + + Operator for performing pow + + + Operator for performing mul + + + Operator for performing floordiv + + + Operator for performing div + + + Operator for performing truediv + + + Operator for performing mod + + + Operator for performing lshift + + + Operator for performing rshift + + + Operator for performing and + + + Operator for performing or + + + Operator for performing xor + + + Operator for performing lt + + + Operator for performing gt + + + Operator for performing le + + + Operator for performing ge + + + Operator for performing eq + + + Operator for performing ne + + + Operator for performing lg + + + Operator for performing in-place add + + + Operator for performing in-place sub + + + Operator for performing in-place pow + + + Operator for performing in-place mul + + + Operator for performing in-place floordiv + + + Operator for performing in-place div + + + Operator for performing in-place truediv + + + Operator for performing in-place mod + + + Operator for performing in-place lshift + + + Operator for performing in-place rshift + + + Operator for performing in-place and + + + Operator for performing in-place or + + + Operator for performing in-place xor + + + Operator for performing reverse add + + + Operator for performing reverse sub + + + Operator for performing reverse pow + + + Operator for performing reverse mul + + + Operator for performing reverse floordiv + + + Operator for performing reverse div + + + Operator for performing reverse truediv + + + Operator for performing reverse mod + + + Operator for performing reverse lshift + + + Operator for performing reverse rshift + + + Operator for performing reverse and + + + Operator for performing reverse or + + + Operator for performing reverse xor + + + Operator for performing reverse divmod + + + + Provides an abstraction for calling something which might be a builtin function or + might be some arbitrary user defined slot. If the object is a builtin function the + call will go directly to the underlying .NET method. If the object is an arbitrary + callable object we will setup a nested dynamic site for performing the additional + dispatch. + + TODO: We could probably do a specific binding to the object if it's another IDyanmicObject. + + + + + Combines two methods, which came from two different binary types, selecting the method which has the best + set of conversions (the conversions which result in the least narrowing). + + + + + Tries to get a MethodBinder associated with the slot for the specified type. + + If a method is found the binder is set and true is returned. + If nothing is found binder is null and true is returned. + If something other than a method is found false is returned. + + TODO: Remove rop + + + + + bytearray(string, encoding[, errors]) -> bytearray + bytearray(iterable) -> bytearray + + Construct a mutable bytearray object from: + - an iterable yielding values in range(256), including: + + a list of integer values + + a bytes, bytearray, buffer, or array object + - a text string encoded using the specified encoding + + bytearray([int]) -> bytearray + + Construct a zero-ititialized bytearray of the specified length. + (default=0) + + + + + return true if self is a titlecased string and there is at least one + character in self; also, uppercase characters may only follow uncased + characters (e.g. whitespace) and lowercase characters only cased ones. + return false otherwise. + + + + + Return a string which is the concatenation of the strings + in the sequence seq. The separator between elements is the + string providing this method + + + + + return true if self is a titlecased string and there is at least one + character in self; also, uppercase characters may only follow uncased + characters (e.g. whitespace) and lowercase characters only cased ones. + return false otherwise. + + + + + Return a string which is the concatenation of the strings + in the sequence seq. The separator between elements is the + string providing this method + + + + + Returns a copy of the internal byte array. + + + System.Byte[] + + + + + This method returns the underlying byte array directly. + It should be used sparingly! + + + System.Byte[] + + + + + Marks a method as being a class method. The PythonType which was used to access + the method will then be passed as the first argument. + + + + + this class contains objecs and static methods used for + .NET/CLS interop with Python. + + + + + Gets the current ScriptDomainManager that IronPython is loaded into. The + ScriptDomainManager can then be used to work with the language portion of the + DLR hosting APIs. + + + + + Use(name) -> module + + Attempts to load the specified module searching all languages in the loaded ScriptRuntime. + + + + + Use(path, language) -> module + + Attempts to load the specified module belonging to a specific language loaded into the + current ScriptRuntime. + + + + + SetCommandDispatcher(commandDispatcher) + + Sets the current command dispatcher for the Python command line. + + The command dispatcher will be called with a delegate to be executed. The command dispatcher + should invoke the target delegate in the desired context. + + A common use for this is to enable running all REPL commands on the UI thread while the REPL + continues to run on a non-UI thread. + + + + + LoadTypeLibrary(rcw) -> type lib desc + + Gets an ITypeLib object from OLE Automation compatible RCW , + reads definitions of CoClass'es and Enum's from this library + and creates an object that allows to instantiate coclasses + and get actual values for the enums. + + + + + LoadTypeLibrary(guid) -> type lib desc + + Reads the latest registered type library for the corresponding GUID, + reads definitions of CoClass'es and Enum's from this library + and creates a IDynamicMetaObjectProvider that allows to instantiate coclasses + and get actual values for the enums. + + + + + AddReferenceToTypeLibrary(rcw) -> None + + Makes the type lib desc available for importing. See also LoadTypeLibrary. + + + + + AddReferenceToTypeLibrary(guid) -> None + + Makes the type lib desc available for importing. See also LoadTypeLibrary. + + + + + Gets the CLR Type object from a given Python type object. + + + + + Gets the Python type object from a given CLR Type object. + + + + + OBSOLETE: Gets the Python type object from a given CLR Type object. + + Use clr.GetPythonType instead. + + + + + accepts(*types) -> ArgChecker + + Decorator that returns a new callable object which will validate the arguments are of the specified types. + + + + + + + returns(type) -> ReturnChecker + + Returns a new callable object which will validate the return type is of the specified type. + + + + + returns the result of dir(o) as-if "import clr" has not been performed. + + + + + Returns the result of dir(o) as-if "import clr" has been performed. + + + + + Attempts to convert the provided object to the specified type. Conversions that + will be attempted include standard Python conversions as well as .NET implicit + and explicit conversions. + + If the conversion cannot be performed a TypeError will be raised. + + + + + Provides a helper for compiling a group of modules into a single assembly. The assembly can later be + reloaded using the clr.AddReference API. + + + + + clr.CompileSubclassTypes(assemblyName, *typeDescription) + + Provides a helper for creating an assembly which contains pre-generated .NET + base types for new-style types. + + This assembly can then be AddReferenced or put sys.prefix\DLLs and the cached + types will be used instead of generating the types at runtime. + + This function takes the name of the assembly to save to and then an arbitrary + number of parameters describing the types to be created. Each of those + parameter can either be a plain type or a sequence of base types. + + clr.CompileSubclassTypes(object) -> create a base type for object + clr.CompileSubclassTypes(object, str, System.Collections.ArrayList) -> create + base types for both object and ArrayList. + + clr.CompileSubclassTypes(object, (object, IComparable)) -> create base types for + object and an object which implements IComparable. + + + + + + clr.GetSubclassedTypes() -> tuple + + Returns a tuple of information about the types which have been subclassed. + + This tuple can be passed to clr.CompileSubclassTypes to cache these + types on disk such as: + + clr.CompileSubclassTypes('assembly', *clr.GetSubclassedTypes()) + + + + + Goes through the list of files identifying the relationship between packages + and subpackages. Returns a dictionary with all of the package filenames (minus __init__.py) + mapping to their full name. For example given a structure: + + C:\ + someDir\ + package\ + __init__.py + a.py + b\ + __init.py + c.py + + Returns: + {r'C:\somedir\package' : 'package', r'C:\somedir\package\b', 'package.b'} + + This can then be used for calculating the full module name of individual files + and packages. For example a's full name is "package.a" and c's full name is + "package.b.c". + + + + + Returns a list of profile data. The values are tuples of Profiler.Data objects + + All times are expressed in the same unit of measure as DateTime.Ticks + + + + + Resets all profiler counters back to zero + + + + + Enable or disable profiling for the current ScriptEngine. This will only affect code + that is compiled after the setting is changed; previously-compiled code will retain + whatever setting was active when the code was originally compiled. + + The easiest way to recompile a module is to reload() it. + + + + + Serializes data using the .NET serialization formatter for complex + types. Returns a tuple identifying the serialization format and the serialized + data which can be fed back into clr.Deserialize. + + Current serialization formats include custom formats for primitive .NET + types which aren't already recognized as tuples. None is used to indicate + that the Binary .NET formatter is used. + + + + + Deserializes the result of a Serialize call. This can be used to perform serialization + for .NET types which are serializable. This method is the callable object provided + from __reduce_ex__ for .serializable .NET types. + + The first parameter indicates the serialization format and is the first tuple element + returned from the Serialize call. + + The second parameter is the serialized data. + + + + + Decorator for verifying the arguments to a function are of a specified type. + + + + + Returned value when using clr.accepts/ArgChecker. Validates the argument types and + then calls the original function. + + + + + Decorator for verifying the return type of functions. + + + + + Returned value when using clr.returns/ReturnChecker. Calls the original function and + validates the return type is of a specified type. + + + + + Provides a StreamContentProvider for a stream of content backed by a file on disk. + + + + + Wrapper class used when a user defined type (new-style or old-style) + defines __index__. We provide a conversion from all user defined + types to the Index type so they can be used for determing and method bind + time the most appropriate method to dispatch to. + + + + + New string formatter for 'str'.format(...) calls and support for the Formatter + library via the _formatter_parser / _formatter_field_name_split + methods. + + We parse this format: + + replacement_field = "{" field_name ["!" conversion] [":" format_spec] "}" + field_name = (identifier | integer) ("." attribute_name | "[" element_index "]")* + attribute_name = identifier + element_index = identifier + conversion = "r" | "s" + format_spec = any char, { must be balanced (for computed values), passed to __format__ method on object + + + + + Runs the formatting operation on the given format and keyword arguments + + + + + Gets the formatting information for the given format. This is a list of tuples. The tuples + include: + + text, field name, format spec, conversion + + + + + Parses a field name returning the argument name and an iterable + object which can be used to access the individual attribute + or element accesses. The iterator yields tuples of: + + bool (true if attribute, false if element index), attribute/index value + + + + + Parses the field name including attribute access or element indexing. + + + + + Parses the field name including attribute access or element indexing. + + + + + Converts accessors from our internal structure into a PythonTuple matching how CPython + exposes these + + + + + Parses an identifier and returns it + + + + + Base class used for parsing the format. Subclasss override Text/ReplacementField methods. Those + methods get called when they call Parse and then they can do the appropriate actions for the + format. + + + + + Gets an enumerable object for walking the parsed format. + + TODO: object array? struct? + + + + + Provides an enumerable of the parsed format. The elements of the tuple are: + the text preceding the format information + the field name + the format spec + the conversion + + + + + Handles {{ and }} within the string. Returns true if a double bracket + is found and yields the text + + + + + Parses the conversion character and returns it + + + + + Checks to see if we're at the end of the format. If there's no more characters left we report + the error, otherwise if we hit a } we return true to indicate parsing should stop. + + + + + Parses the format spec string and returns it. + + + + + Parses the field name and returns it. + + + + + Handles parsing the field name and the format spec and returns it. At the parse + level these are basically the same - field names just have more terminating characters. + + The most complex part of parsing them is they both allow nested braces and require + the braces are matched. Strangely though the braces need to be matched across the + combined field and format spec - not within each format. + + + + + Provides the built-in string formatter which is exposed to Python via the str.format API. + + + + + Inspects a format spec to see if it contains nested format specs which + we need to compute. If so runs another string formatter on the format + spec to compute those values. + + + + + Given the field name gets the object from our arguments running + any of the member/index accessors. + + + + + Applies the known built-in conversions to the object if a conversion is + specified. + + + + + Gets the initial object represented by the field name - e.g. the 0 or + keyword name. + + + + + Given the object value runs the accessors in the field name (if any) against the object. + + + + + Encodes all the information about the field name. + + + + + Encodes a single field accessor (.b or [number] or [str]) + + + + + For IList arguments: Marks that the argument is typed to accept a bytes or + bytearray object. This attribute disallows passing a Python list object and + auto-applying our generic conversion. It also enables conversion of a string to + a IList of byte in IronPython 2.6. + + For string arguments: Marks that the argument is typed to accept a bytes object + as well. (2.6 only) + + + + stored for copy_reg module, used for reduce protocol + + + stored for copy_reg module, used for reduce protocol + + + + Creates a new PythonContext not bound to Engine. + + + + + Checks to see if module state has the current value stored already. + + + + + Gets per-runtime state used by a module. The module should have a unique key for + each piece of state it needs to store. + + + + + Sets per-runtime state used by a module. The module should have a unique key for + each piece of state it needs to store. + + + + + Sets per-runtime state used by a module and returns the previous value. The module + should have a unique key for each piece of state it needs to store. + + + + + Sets per-runtime state used by a module and returns the previous value. The module + should have a unique key for each piece of state it needs to store. + + + + + Initializes the sys module on startup. Called both to load and reload sys + + + + + Reads one line keeping track of the # of bytes read + + + + + We use Assembly.LoadFile to load assemblies from a path specified by the script (in LoadAssemblyFromFileWithPath). + However, when the CLR loader tries to resolve any of assembly references, it will not be able to + find the dependencies, unless we can hook into the CLR loader. + + + + + Returns (and creates if necessary) the PythonService that is associated with this PythonContext. + + The PythonService is used for providing remoted convenience helpers for the DLR hosting APIs. + + + + + Gets the member names associated with the object + TODO: Move "GetMemberNames" functionality into MetaObject implementations + + + + + Gets a SiteLocalStorage when no call site is available. + + + + + Invokes the specified operation on the provided arguments and returns the new resulting value. + + operation is usually a value from StandardOperators (standard CLR/DLR operator) or + OperatorStrings (a Python specific operator) + + + + + Sets the current command dispatcher for the Python command line. The previous dispatcher + is returned. Null can be passed to remove the current command dispatcher. + + The command dispatcher will be called with a delegate to be executed. The command dispatcher + should invoke the target delegate in the desired context. + + A common use for this is to enable running all REPL commands on the UI thread while the REPL + continues to run on a non-UI thread. + + The ipy.exe REPL will call into PythonContext.DispatchCommand to dispatch each execution to + the correct thread. Other REPLs can do the same to support this functionality as well. + + + + + Dispatches the command to the current command dispatcher. If there is no current command + dispatcher the command is executed immediately on the current thread. + + + + + Gets a function which can be used for comparing two values. If cmp is not null + then the comparison will use the provided comparison function. Otherwise + it will use the normal Python semantics. + + If type is null then a generic comparison function is returned. If type is + not null a comparison function is returned that's used for just that type. + + + + + Performs a GC collection including the possibility of freeing weak data structures held onto by the Python runtime. + + + + + + Gets a PythonContext given a DynamicMetaObjectBinder. + + + + + Gets or sets the maximum depth of function calls. Equivalent to sys.getrecursionlimit + and sys.setrecursionlimit. + + + + + Gets or sets the main thread which should be interupted by thread.interrupt_main + + + + + Gets or sets the default encoding for this system state / engine. + + + + + Dictionary from name to type of all known built-in module names. + + + + + Dictionary from type to name of all built-in modules. + + + + + TODO: Remove me, or stop caching built-ins. This is broken if the user changes __builtin__ + + + + Dictionary of error handlers for string codecs. + + + Table of functions used for looking for additional codecs. + + + + Returns a shared code context for the current PythonContext. This shared + context can be used for performing general operations which usually + require a CodeContext. + + + + + Returns an overload resolver for the current PythonContext. The overload + resolver will flow the shared context through as it's CodeContext. + + + + + Returns a shared code context for the current PythonContext. This shared + context can be used for doing lookups which need to occur as if they + happened in a module which has done "import clr". + + + + + A DynamicStackFrame which has Python specific data. Currently this + includes the code context which may provide access to locals and the + function code object which is needed to build frame objects from. + + + + + Gets the code context of the function. + + If the function included a call to locals() or the FullFrames + option is enabled then the code context includes all local variables. + + Null if deserialized. + + + + + Gets the code object for this frame. This is used in creating + the trace back. Null if deserialized. + + + + + Created for a user-defined function. + + + + + Python ctor - maps to function.__new__ + + y = func(x.__code__, globals(), 'foo', None, (a, )) + + + + + Calculates the _compat value which is used for call-compatibility checks + for simple calls. Whenver any of the dependent values are updated this + must be called again. + + The dependent values include: + _nparams - this is readonly, and never requies an update + _defaults - the user can mutate this (func_defaults) and that forces + an update + expand dict/list - based on nparams and flags, both read-only + + Bits are allocated as: + 00003fff - Normal argument count + 0fffb000 - Default count + 10000000 - unused + 20000000 - expand list + 40000000 - expand dict + 80000000 - unused + + Enforce recursion is added at runtime. + + + + + The parent CodeContext in which this function was declared. + + + + + Captures the # of args and whether we have kw / arg lists. This + enables us to share sites for simple calls (calls that don't directly + provide named arguments or the list/dict params). + + + + + Generators w/ exception handling need to have some data stored + on them so that we appropriately set/restore the exception state. + + + + + Returns an ID for the function if one has been assigned, or zero if the + function has not yet required the use of an ID. + + + + + Gets the position for the expand list argument or -1 if the function doesn't have an expand list parameter. + + + + + Gets the position for the expand dictionary argument or -1 if the function doesn't have an expand dictionary parameter. + + + + + Gets the number of normal (not params or kw-params) parameters. + + + + + Gets the number of extra arguments (params or kw-params) + + + + + Gets the collection of command line arguments. + + + + + Should we strip out all doc strings (the -O command line option). + + + + + Should we strip out all doc strings (the -OO command line option). + + + + + List of -W (warning filter) options collected from the command line. + + + + + Enables warnings related to Python 3.0 features. + + + + + Enables 3.0 features that are implemented in IronPython. + + + + + Enables debugging support. When enabled a .NET debugger can be attached + to the process to step through Python code. + + + + + Enables inspect mode. After running the main module the REPL will be started + within that modules context. + + + + + Suppresses addition of the user site directory. This is ignored by IronPython + except for updating sys.flags. + + + + + Disables import site on startup. + + + + + Ignore environment variables that configure the IronPython context. + + + + + Enables the verbose option which traces import statements. This is ignored by IronPython + except for setting sys.flags. + + + + + Sets the maximum recursion depth. Setting to Int32.MaxValue will disable recursion + enforcement. + + + + + Makes available sys._getframe. Local variables will not be available in frames unless the + function calls locals(), dir(), vars(), etc... For ensuring locals are always available use + the FullFrames option. + + + + + Makes available sys._getframe. All locals variables will live on the heap (for a considerable + performance cost) enabling introspection of all code. + + + + + Tracing is always available. Without this option tracing is only enabled when sys.settrace + is called. This means code that was already running before sys.settrace will not be debuggable. + + With this option pdb.set_trace and pdb.post_mortem will always work properly. + + + + + Severity of a warning that indentation is formatted inconsistently. + + + + + The division options (old, new, warn, warnall) + + + + + Forces all code to be compiled in a mode in which the code can be reliably collected by the CLR. + + + + + Enable profiling code + + + + + Returns a regular expression of Python files which should not be emitted in debug mode. + + + + + Gets the CPython version which IronPython will emulate. Currently limited + to either 2.6 or 3.0. + + + + + Marks a member as being hidden from Python code. + + + + + This assembly-level attribute specifies which types in the engine represent built-in Python modules. + + Members of a built-in module type should all be static as an instance is never created. + + + + + Creates a new PythonModuleAttribute that can be used to specify a built-in module that exists + within an assembly. + + The built-in module name + The type that implements the built-in module. + + + + The built-in module name + + + + + The type that implements the built-in module + + + + + Marks a type as being a PythonType for purposes of member lookup, creating instances, etc... + + If defined a PythonType will use __new__ / __init__ when creating instances. This allows the + object to match the native Python behavior such as returning cached values from __new__ or + supporting initialization to run multiple times via __init__. + + The attribute also allows you to specify an alternate type name. This allows the .NET name to + be different from the Python name so they can follow .NET naming conventions. + + Types defining this attribute also don't show CLR methods such as Equals, GetHashCode, etc... until + the user has done an import clr. + + + + + General-purpose storage used for Python sets and frozensets. + + The set storage is thread-safe for multiple readers or writers. + + Mutations to the set involve a simple locking strategy of locking on the SetStorage object + itself to ensure mutual exclusion. + + Reads against the set happen lock-free. When the set is mutated, it adds or removes buckets + in an atomic manner so that the readers will see a consistent picture as if the read + occurred either before or after the mutation. + + + + + Creates a new set storage with no buckets + + + + + Creates a new set storage with no buckets + + + + + Adds a new item to the set, unless an equivalent item is already present + + + + + Static helper which adds the given non-null item with a precomputed hash code. Returns + true if the item was added, false if it was already present in the set. + + + + + Lock-free helper on a non-null item with a pre-calculated hash code. Removes the item + if it is present in the set, otherwise adds it. + + + + + Clears the contents of the set + + + + + Clones the set, returning a new SetStorage object + + + + + Checks to see if the given item exists in the set + + + + + Checks to see if the given item exists in the set, and tries to hash it even + if it is known not to be in the set. + + + + + + + Adds items from this set into the other set + + + + + Removes the first set element in the iteration order. + + true if an item was removed, false if the set was empty + + + + Removes an item from the set and returns true if it was present, otherwise returns + false + + + + + Removes an item from the set and returns true if it was removed. The item will always + be hashed, throwing if it is unhashable - even if the set has no buckets. + + + + + Lock-free helper to remove a non-null item + + + + + Determines whether the current set shares no elements with the given set + + + + + Determines whether the current set is a subset of the given set + + + + + Determines whether the current set is a strict subset of the given set + + + + + Mutates this set to contain its union with 'other'. The caller must lock the current + set if synchronization is desired. + + + + + Mutates this set to contain its intersection with 'other'. The caller must lock the + current set if synchronization is desired. + + + + + Mutates this set to contain its symmetric difference with 'other'. The caller must + lock the current set if synchronization is desired. + + + + + Mutates this set to contain its difference with 'other'. The caller must lock the + current set if synchronization is desired. + + + + + Computes the union of self and other, returning an entirely new set. This method is + thread-safe and makes no modifications to self or other. + + + + + Computes the intersection of self and other, returning an entirely new set. This + method is thread-safe and makes no modifications to self or other. + + + + + Computes the symmetric difference of self and other, returning an entirely new set. + This method is thread-safe and makes no modifications to self or other. + + + + + Computes the difference of self and other, returning an entirely new set. This + method is thread-safe and makes no modifications to self or other. + + + + + Helper to hash the given item w/ support for null + + + + + Helper which ensures that the first argument x requires the least work to enumerate + + + + + A factory which creates a SetStorage object from any Python iterable. It extracts + the underlying storage of a set or frozen set without copying, which is left to the + caller if necessary. + + + + + A factory which creates a SetStorage object from any Python iterable. It extracts + the underlying storage of a set or frozen set without copying, which is left to the + caller if necessary. + Returns true if the given object was a set or frozen set, false otherwise. + + + + + A factory which creates a SetStorage object from any Python iterable. It extracts + the underlying storage of a set or frozen set, copying in the former case, to return + a SetStorage object that is guaranteed not to receive any outside mutations. + + + + + Extracts the SetStorage object from o if it is a set or frozenset and returns true. + Otherwise returns false. + + + + + Creates a hashable set from the given set, or does nothing if the given object + is not a set. + + True if o is a set or frozenset, false otherwise + + + + Returns the number of items currently in the set + + + + + Used to store a single hashed item. + + Bucket is not serializable because it stores the computed hash code, which could change + between serialization and deserialization. + + + + + Provides storage which is flowed into a callers site. The same storage object is + flowed for multiple calls enabling the callee to cache data that can be re-used + across multiple calls. + + Data is a public field so that this works properly with DynamicSite's as the reference + type (and EnsureInitialize) + + + + + Provides a representation and parsing for the default formatting specification. This is used + by object.__format__, int.__format__, long.__format__, and float.__format__ to do the common + format spec parsing. + + The default specification is: + + format_spec = [[fill]align][sign][#][0][width][,][.precision][type] + fill = a character other than } + align = "<" | ">" | "=" | "^" + sign = "+" | "-" | " " + width = integer + precision = integer + type = "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "x" | "X" | "%" + + + + + Parses a format spec and returns a new StringFormatSpec object. + + + + + Optimized storage for setting exc_type, exc_value, and exc_traceback. + + This optimization can go away in Python 3.0 when these attributes are no longer used. + + + + + Marks a type as being a suitable type to be used for user-defined classes. + + The requirements for this are that a type has to follow the patterns + that NewTypeMaker derived types follow. This includes: + The type's constructors must all take PythonType as the 1st parameter + which sets the underlying type for the actual object + The type needs to implement IPythonObject + Dictionary-based storage needs to be provided for setting individual members + Virtual methods exposed to Python need to support checking the types dictionary for invocations + + + + + Base class for helper which creates instances. We have two derived types: One for user + defined types which prepends the type before calling, and one for .NET types which + doesn't prepend the type. + + + + + Contains helper methods for converting C# names into Python names. + + + + + TypeInfo captures the minimal CLI information required by NewTypeMaker for a Python object + that inherits from a CLI type. + + + + + "bases" contains a set of PythonTypes. These can include types defined in Python (say cpy1, cpy2), + CLI types (say cCLI1, cCLI2), and CLI interfaces (say iCLI1, iCLI2). Here are some + examples of how this works: + + (bases) => baseType, {interfaceTypes} + + (cpy1) => System.Object, {} + (cpy1, cpy2) => System.Object, {} + (cpy1, cCLI1, iCLI1, iCLI2) => cCLI1, {iCLI1, iCLI2} + [some type that satisfies the line above] => + cCLI1, {iCLI1, iCLI2} + (cCLI1, cCLI2) => error + + + + + Filters out old-classes and throws if any non-types are included, returning a + yielding the remaining PythonType objects. + + + + + Python class hierarchy is represented using the __class__ field in the object. It does not + use the CLI type system for pure Python types. However, Python types which inherit from a + CLI type, or from a builtin Python type which is implemented in the engine by a CLI type, + do have to use the CLI type system to interoperate with the CLI world. This means that + objects of different Python types, but with the same CLI base type, can use the same CLI type - + they will just have different values for the __class__ field. + + The easiest way to inspect the functionality implemented by NewTypeMaker is to persist the + generated IL using "ipy.exe -X:SaveAssemblies", and then inspect the + persisted IL using ildasm. + + + + + Loads any available new types from the provided assembly and makes them + available via the GetNewType API. + + + + + Is this a type used for instances Python types (and not for the types themselves)? + + + + + Gets the position for the parameter which we are overriding. + + + + + + + + + Defines an interface on the type that forwards all calls + to a helper method in UserType. The method names all will + have Helper appended to them to get the name for UserType. The + UserType version should take 1 extra parameter (self). + + + + + Overrides methods - this includes all accessible virtual methods as well as protected non-virtual members + including statics and non-statics. + + + + + Loads all the incoming arguments and forwards them to mi which + has the same signature and then returns the result + + + + + Emits code to check if the class has overridden this specific + function. For example: + + MyDerivedType.SomeVirtualFunction = ... + or + + class MyDerivedType(MyBaseType): + def SomeVirtualFunction(self, ...): + + + + + + Emit code to convert object to a given type. This code is semantically equivalent + to PythonBinder.EmitConvertFromObject, except this version accepts ILGen whereas + PythonBinder accepts Compiler. The Binder will chagne soon and the two will merge. + + + + + Emits code to check if the class has overridden this specific + function. For example: + + MyDerivedType.SomeVirtualFunction = ... + or + + class MyDerivedType(MyBaseType): + def SomeVirtualFunction(self, ...): + + + + + + Emits the call to lookup a member defined in the user's type. Returns + the local which stores the resulting value and leaves a value on the + stack indicating the success of the lookup. + + + + + Creates a method for doing a base method dispatch. This is used to support + super(type, obj) calls. + + + + + Generates stub to receive the CLR call and then call the dynamic language code. + This code is same as StubGenerator.cs in the Microsoft.Scripting, except it + accepts ILGen instead of Compiler. + + + + + Called from PythonTypeOps - the BuiltinFunction._function lock must be held. + + + + + Same as the DLR ReturnFixer, but accepts lower level constructs, + such as LocalBuilder, ParameterInfos and ILGen. + + + + + Creates a new PythonCompilerOptions with the default language features enabled. + + + + + Creates a new PythonCompilerOptions with the specified language features enabled. + + + + + Creates a new PythonCompilerOptions and enables or disables true division. + + This overload is obsolete, instead you should use the overload which takes a + ModuleOptions. + + + + + Gets or sets the initial indentation. This can be set to allow parsing + partial blocks of code that are already indented. + + For each element of the array there is an additional level of indentation. + Each integer value represents the number of spaces used for the indentation. + + If this value is null then no indentation level is specified. + + + + + Language features initialized on parser construction and possibly updated during parsing. + The code can set the language features (e.g. "from __future__ import division"). + + + + + Parse one or more lines of interactive input + + null if input is not yet valid but could be with more lines + + + + Given the interactive text input for a compound statement, calculate what the + indentation level of the next line should be + + + + + Peek if the next token is a 'yield' and parse a yield expression. Else return null. + + Called w/ yield already eaten. + + A yield expression if present, else null. + + + + Maybe eats a new line token returning true if the token was + eaten. + + Python always tokenizes to have only 1 new line character in a + row. But we also craete NLToken's and ignore them except for + error reporting purposes. This gives us the same errors as + CPython and also matches the behavior of the standard library + tokenize module. This function eats any present NL tokens and throws + them away. + + + + + Eats a new line token throwing if the next token isn't a new line. + + Python always tokenizes to have only 1 new line character in a + row. But we also craete NLToken's and ignore them except for + error reporting purposes. This gives us the same errors as + CPython and also matches the behavior of the standard library + tokenize module. This function eats any present NL tokens and throws + them away. + + + + + Summary description for Token. + + + + + IronPython tokenizer + + + + + Used to create tokenizer for hosting API. + + + + + Returns whether the + + + + + Resizes an array to a speficied new size and copies a portion of the original array into its beginning. + + + + + True if the last characters in the buffer are a backslash followed by a new line indicating + that their is an incompletement statement which needs further input to complete. + + + + + Equality comparer that can compare strings to our current token w/o creating a new string first. + + + + + A simple Python command-line should mimic the standard python.exe + + + + + Returns the display look for IronPython. + + The returned string uses This \n instead of Environment.NewLine for it's line seperator + because it is intended to be outputted through the Python I/O system. + + + + + Loads any extension DLLs present in sys.prefix\DLLs directory and adds references to them. + + This provides an easy drop-in location for .NET assemblies which should be automatically referenced + (exposed via import), COM libraries, and pre-compiled Python code. + + + + + Attempts to run a single interaction and handle any language-specific + exceptions. Base classes can override this and call the base implementation + surrounded with their own exception handling. + + Returns null if successful and execution should continue, or an exit code. + + + + + Parses a single interactive command and executes it. + + Returns null if successful and execution should continue, or the appropiate exit code. + + + + + Skip the first line of the code to execute. This is useful for executing Unix scripts which + have the command to execute specified in the first line. + This only apply to the script code executed by the ScriptEngine APIs, but not for other script code + that happens to get called as a result of the execution. + + + + On error. + + + + Provides helpers for interacting with IronPython. + + + + + Creates a new ScriptRuntime with the IronPython scipting engine pre-configured. + + + + + + Creates a new ScriptRuntime with the IronPython scipting engine pre-configured and + additional options. + + + + + Creates a new ScriptRuntime with the IronPython scripting engine pre-configured + in the specified AppDomain. The remote ScriptRuntime may be manipulated from + the local domain but all code will run in the remote domain. + + + + + Creates a new ScriptRuntime with the IronPython scripting engine pre-configured + in the specified AppDomain with additional options. The remote ScriptRuntime may + be manipulated from the local domain but all code will run in the remote domain. + + + + + Creates a new ScriptRuntime and returns the ScriptEngine for IronPython. If + the ScriptRuntime is required it can be acquired from the Runtime property + on the engine. + + + + + Creates a new ScriptRuntime with the specified options and returns the + ScriptEngine for IronPython. If the ScriptRuntime is required it can be + acquired from the Runtime property on the engine. + + + + + Creates a new ScriptRuntime and returns the ScriptEngine for IronPython. If + the ScriptRuntime is required it can be acquired from the Runtime property + on the engine. + + The remote ScriptRuntime may be manipulated from the local domain but + all code will run in the remote domain. + + + + + Creates a new ScriptRuntime with the specified options and returns the + ScriptEngine for IronPython. If the ScriptRuntime is required it can be + acquired from the Runtime property on the engine. + + The remote ScriptRuntime may be manipulated from the local domain but + all code will run in the remote domain. + + + + + Given a ScriptRuntime gets the ScriptEngine for IronPython. + + + + + Gets a ScriptScope which is the Python sys module for the provided ScriptRuntime. + + + + + Gets a ScriptScope which is the Python sys module for the provided ScriptEngine. + + + + + Gets a ScriptScope which is the Python __builtin__ module for the provided ScriptRuntime. + + + + + Gets a ScriptScope which is the Python __builtin__ module for the provided ScriptEngine. + + + + + Gets a ScriptScope which is the Python clr module for the provided ScriptRuntime. + + + + + Gets a ScriptScope which is the Python clr module for the provided ScriptEngine. + + + + + Imports the Python module by the given name and returns its ScriptSCope. If the + module does not exist an exception is raised. + + + + + Imports the Python module by the given name and returns its ScriptSCope. If the + module does not exist an exception is raised. + + + + + Imports the Python module by the given name and inserts it into the ScriptScope as that name. If the + module does not exist an exception is raised. + + + + + + + Sets sys.exec_prefix, sys.executable and sys.version and adds the prefix to sys.path + + + + + Sets sys.exec_prefix, sys.executable and sys.version and adds the prefix to sys.path + + + + + Enables call tracing for the current thread in this ScriptEngine. + + TracebackDelegate will be called back for each function entry, exit, exception, and line change. + + + + + Enables call tracing for the current thread for the Python engine in this ScriptRuntime. + + TracebackDelegate will be called back for each function entry, exit, exception, and line change. + + + + + Provides nested level debugging support when SetTrace or SetProfile are used. + + This saves the current tracing information and then calls the provided object. + + + + + Provides nested level debugging support when SetTrace or SetProfile are used. + + This saves the current tracing information and then calls the provided object. + + + + + Creates a ScriptRuntimeSetup object which includes the Python script engine with the specified options. + + The ScriptRuntimeSetup object can then be additional configured and used to create a ScriptRuntime. + + + + + Creates a LanguageSetup object which includes the Python script engine with the specified options. + + The LanguageSetup object can be used with other LanguageSetup objects from other languages to + configure a ScriptRuntimeSetup object. + + + + + Creates a new PythonModule with the specified name and published it in sys.modules. + + Returns the ScriptScope associated with the module. + + + + + Creates a new PythonModule with the specified name and filename published it + in sys.modules. + + Returns the ScriptScope associated with the module. + + + + + Creates a new PythonModule with the specified name, filename, and doc string and + published it in sys.modules. + + Returns the ScriptScope associated with the module. + + + + + Gets the list of loaded Python module files names which are available in the provided ScriptEngine. + + + + + A strongly-typed resource class, for looking up localized strings, etc. + + + + + Returns the cached ResourceManager instance used by this class. + + + + + Overrides the current thread's CurrentUICulture property for all + resource lookups using this strongly typed resource class. + + + + + Looks up a localized string similar to couldn't find member {0}. + + + + + Looks up a localized string similar to default value must be specified here. + + + + + Looks up a localized string similar to duplicate argument '{0}' in function definition. + + + + + Looks up a localized string similar to duplicate keyword argument. + + + + + Looks up a localized string similar to <eof> while reading string. + + + + + Looks up a localized string similar to EOF while scanning triple-quoted string. + + + + + Looks up a localized string similar to EOL while scanning single-quoted string. + + + + + Looks up a localized string similar to expected an indented block. + + + + + Looks up a localized string similar to expected name. + + + + + Looks up a localized string similar to Expecting identifier:. + + + + + Looks up a localized string similar to inconsistent use of tabs and spaces in indentation. + + + + + Looks up a localized string similar to unindent does not match any outer indentation level. + + + + + Looks up a localized string similar to Invalid argument value.. + + + + + Looks up a localized string similar to MakeGenericType on non-generic type. + + + + + Looks up a localized string similar to Invalid parameter collection for the function.. + + + + + Looks up a localized string similar to invalid syntax. + + + + + Looks up a localized string similar to object ({0}) is not creatable w/ keyword arguments. + + + + + Looks up a localized string similar to keywords must come before * args. + + + + + Looks up a localized string similar to type does not have {0} field. + + + + + Looks up a localized string similar to from __future__ imports must occur at the beginning of the file. + + + + + Looks up a localized string similar to 'return' outside function. + + + + + Looks up a localized string similar to 'yield' outside function. + + + + + Looks up a localized string similar to NEWLINE in double-quoted string. + + + + + Looks up a localized string similar to NEWLINE in single-quoted string. + + + + + Looks up a localized string similar to future statement does not support import *. + + + + + Looks up a localized string similar to non-keyword arg after keyword arg. + + + + + Looks up a localized string similar to not a chance. + + + + + Looks up a localized string similar to The method or operation is not implemented.. + + + + + Looks up a localized string similar to only one ** allowed. + + + + + Looks up a localized string similar to only one * allowed. + + + + + Looks up a localized string similar to Context must be PythonCompilerContext. + + + + + Looks up a localized string similar to cannot delete slot. + + + + + Looks up a localized string similar to cannot get slot. + + + + + Looks up a localized string similar to cannot set slot. + + + + + Looks up a localized string similar to static property '{0}' of '{1}' can only be read through a type, not an instance. + + + + + Looks up a localized string similar to static property '{0}' of '{1}' can only be assigned to through a type, not an instance. + + + + + Looks up a localized string similar to no value for this token. + + + + + Looks up a localized string similar to too many versions. + + + + + Looks up a localized string similar to unexpected token '{0}'. + + + + + Looks up a localized string similar to future feature is not defined:. + + + + + The Action used for Python call sites. This supports both splatting of position and keyword arguments. + + When a foreign object is encountered the arguments are expanded into normal position/keyword arguments. + + + + + Python's Invoke is a non-standard action. Here we first try to bind through a Python + internal interface (IPythonInvokable) which supports CallSigantures. If that fails + and we have an IDO then we translate to the DLR protocol through a nested dynamic site - + this includes unsplatting any keyword / position arguments. Finally if it's just a plain + old .NET type we use the default binder which supports CallSignatures. + + + + + Fallback - performs the default binding operation if the object isn't recognized + as being invokable. + + + + + Creates a nested dynamic site which uses the unpacked arguments. + + + + + Translates our CallSignature into a DLR Argument list and gives the simple MetaObject's which are extracted + from the tuple or dictionary parameters being splatted. + + + + + Gets the CallSignature for this invocation which describes how the MetaObject array + is to be mapped. + + + + + General purpose storage used for most PythonDictionarys. + + This dictionary storage is thread safe for multiple readers or writers. + + Mutations to the dictionary involves a simple locking strategy of + locking on the DictionaryStorage object to ensure that only one + mutation happens at a time. + + Reads against the dictionary happen lock free. When the dictionary is mutated + it is either adding or removing buckets in a thread-safe manner so that the readers + will either see a consistent picture as if the read occured before or after the mutation. + + When resizing the dictionary the buckets are replaced atomically so that the reader + sees the new buckets or the old buckets. When reading the reader first reads + the buckets and then calls a static helper function to do the read from the bucket + array to ensure that readers are not seeing multiple bucket arrays. + + + + + Creates a new dictionary storage with no buckets + + + + + Creates a new dictionary storage with no buckets + + + + + Creates a new dictionary geting values/keys from the + items arary + + + + + Creates a new dictionary storage with the given set of buckets + and size. Used when cloning the dictionary storage. + + + + + Adds a new item to the dictionary, replacing an existing one if it already exists. + + + + + Initializes the buckets to their initial capacity, the caller + must check if the buckets are empty first. + + + + + Add helper that works over a single set of buckets. Used for + both the normal add case as well as the resize case. + + + + + Add helper which adds the given key/value (where the key is not null) with + a pre-computed hash code. + + + + + Removes an entry from the dictionary and returns true if the + entry was removed or false. + + + + + Removes an entry from the dictionary and returns true if the + entry was removed or false. The key will always be hashed + so if it is unhashable an exception will be thrown - even + if the dictionary has no buckets. + + + + + Checks to see if the key exists in the dictionary. + + + + + Trys to get the value associated with the given key and returns true + if it's found or false if it's not present. + + + + + Static helper to try and get the value from the dictionary. + + Used so the value lookup can run against a buckets while a writer + replaces the buckets. + + + + + Clears the contents of the dictionary. + + + + + Clones the storage returning a new DictionaryStorage object. + + + + + Helper to hash the given key w/ support for null. + + + + + Returns the number of key/value pairs currently in the dictionary. + + + + + Used to store a single hashed key/value. + + Bucket is not serializable because it stores the computed hash + code which could change between serialization and deserialization. + + + + + Special marker NullValue used during deserialization to not add + an extra field to the dictionary storage type. + + + + + The error involved an incomplete statement due to an unexpected EOF. + + + + + The error involved an incomplete token. + + + + + The mask for the actual error values + + + + + The error was a general syntax error + + + + + The error was an indentation error. + + + + + The error was a tab error. + + + + + syntax error shouldn't include a caret (no column offset should be included) + + + + + GeneratorExitException is a standard exception raised by Generator.Close() to allow a caller + to close out a generator. + + GeneratorExit is introduced in Pep342 for Python2.5. + + + + .NET exception thrown when a Python syntax error is related to incorrect indentation. + + + + + Implementation of the Python exceptions module and the IronPython/CLR exception mapping + mechanism. The exception module is the parent module for all Python exception classes + and therefore is built-in to IronPython.dll instead of IronPython.Modules.dll. + + The exception mapping mechanism is exposed as internal surface area available to only + IronPython / IronPython.Modules.dll. The actual exceptions themselves are all public. + + Because the oddity of the built-in exception types all sharing the same physical layout + (see also PythonExceptions.BaseException) some classes are defined as classes w/ their + proper name and some classes are defined as PythonType fields. When a class is defined + for convenience their's also an _TypeName version which is the PythonType. + + + + + Creates a new throwable exception of type type where the type is an new-style exception. + + Used at runtime when creating the exception from a user provided type via the raise statement. + + + + + Creates a throwable exception of type type where the type is an OldClass. + + Used at runtime when creating the exception form a user provided type that's an old class (via the raise statement). + + + + + Returns the CLR exception associated with a Python exception + creating a new exception if necessary + + + + + Given a CLR exception returns the Python exception which most closely maps to the CLR exception. + + + + + Creates a new style Python exception from the .NET exception + + + + + Internal helper to associate a .NET exception and a Python exception. + + + + + Internal helper to get the associated Python exception from a .NET exception. + + + + + Converts the DLR SyntaxErrorException into a Python new-style SyntaxError instance. + + + + + Creates a PythonType for a built-in module. These types are mutable like + normal user types. + + + + + Creates a PythonType for a built-in module. These types are mutable like + normal user types. + + + + + Creates a PythonType for a built-in module, where the type may inherit + from multiple bases. These types are mutable like normal user types. + + + + + Creates a new type for a built-in exception which derives from another Python + type. . These types are built-in and immutable like any other normal type. For + example StandardError.x = 3 is illegal. This isn't for module exceptions which + are like user defined types. thread.error.x = 3 is legal. + + + + + Creates a new type for a built-in exception which is the root concrete type. + + + + + Gets the list of DynamicStackFrames for the current exception. + + + + + Base class for all Python exception objects. + + When users throw exceptions they typically throw an exception which is + a subtype of this. A mapping is maintained between Python exceptions + and .NET exceptions and a corresponding .NET exception is thrown which + is associated with the Python exception. This class represents the + base class for the Python exception hierarchy. + + Users can catch exceptions rooted in either hierarchy. The hierarchy + determines whether the user catches the .NET exception object or the + Python exception object. + + Most built-in Python exception classes are actually instances of the BaseException + class here. This is important because in CPython the exceptions do not + add new members and therefore their layouts are compatible for multiple + inheritance. The exceptions to this rule are the classes which define + their own fields within their type, therefore altering their layout: + EnvironmentError + SyntaxError + IndentationError (same layout as SyntaxError) + TabError (same layout as SyntaxError) + SystemExit + UnicodeDecodeError + UnicodeEncodeError + UnicodeTranslateError + + These exceptions cannot be combined in multiple inheritance, e.g.: + class foo(EnvironmentError, IndentationError): pass + + fails but they can be combined with anything which is just a BaseException: + class foo(UnicodeDecodeError, SystemError): pass + + Therefore the majority of the classes are just BaseException instances with a + custom PythonType object. The specialized ones have their own .NET class + which inherits from BaseException. User defined exceptions likewise inherit + from this and have their own .NET class. + + + + + This interface is used for implementing parts of the IronPython type system. It + is not intended for consumption from user programs. + + + + + Thread-safe dictionary set. Returns the dictionary set or the previous value if already set or + null if the dictionary set isn't supported. + + + + + + + Dictionary replacement. Returns true if replaced, false if the dictionary set isn't supported. + + + + + + + Initializes the Exception object with an unlimited number of arguments + + + + + Returns a tuple of (type, (arg0, ..., argN)) for implementing pickling/copying + + + + + Returns a tuple of (type, (arg0, ..., argN)) for implementing pickling/copying + + + + + Updates the exception's state (dictionary) with the new values + + + + + Provides custom member lookup access that fallbacks to the dictionary + + + + + Provides custom member assignment which stores values in the dictionary + + + + + Provides custom member deletion which deletes values from the dictionary + or allows clearing 'message'. + + + + + Implements __repr__ which returns the type name + the args + tuple code formatted. + + + + + Initializes the Python exception from a .NET exception + + + + + + Helper to get the CLR exception associated w/ this Python exception + creating it if one has not already been created. + + + + + Returns the exception 'message' if only a single argument was provided + during creation or an empty string. + + + + + Gets or sets the arguments used for creating the exception + + + + + Gets the nth member of the args property + + + + + Gets or sets the dictionary which is used for storing members not declared to have space reserved + within the exception object. + + + + + Gets the CLR exception associated w/ this Python exception. Not visible + until a .NET namespace is imported. + + + + + .NET exception that is thrown to signal the end of iteration in Python + + + + + .NET exception that is thrown to shutdown the interpretter and exit the system. + + + + + Result of sys.exit(n) + + + null if the script exited using "sys.exit(int_value)" + null if the script exited using "sys.exit(None)" + x if the script exited using "sys.exit(x)" where isinstance(x, int) == False + + + int_value if the script exited using "sys.exit(int_value)" + 1 otherwise + + + + + .NET Exception thrown when a Python syntax error is related to incorrect tabs. + + + + + Represents a sequence which may have been provided as a set of parameters to an indexer. + + TODO: This should be removed, and all uses of this should go to [SpecialName]object GetItem(..., params object[] keys) + and [SpecialName]void SetItem(..., params object [] keys) or this[params object[]xyz] which is also legal. + + currently this exists for backwards compatibility w/ IronPython's "expandable tuples". + + + + + Provides a MetaObject for instances of Python's old-style classes. + + TODO: Lots of CodeConetxt references, need to move CodeContext onto OldClass and pull it from there. + + + + + Performs the actual work of binding to the function. + + Overall this works by going through the arguments and attempting to bind all the outstanding known + arguments - position arguments and named arguments which map to parameters are easy and handled + in the 1st pass for GetArgumentsForRule. We also pick up any extra named or position arguments which + will need to be passed off to a kw argument or a params array. + + After all the normal args have been assigned to do a 2nd pass in FinishArguments. Here we assign + a value to either a value from the params list, kw-dict, or defaults. If there is ambiguity between + this (e.g. we have a splatted params list, kw-dict, and defaults) we call a helper which extracts them + in the proper order (first try the list, then the dict, then the defaults). + + + + + Makes the test for our rule. + + + + + Makes the test when we just have simple positional arguments. + + + + + Makes the test when we have a keyword argument call or splatting. + + + + + + Gets the array of expressions which correspond to each argument for the function. These + correspond with the function as it's defined in Python and must be transformed for our + delegate type before being used. + + + + + Binds any missing arguments to values from params array, kw dictionary, or default values. + + + + + Creates the argument for the list expansion parameter. + + + + + Adds extra positional arguments to the start of the expanded list. + + + + + Creates the argument for the dictionary expansion parameter. + + + + + Adds an unbound keyword argument into the dictionary. + + + + + + Adds a check to the last parameter (so it's evaluated after we've extracted + all the parameters) to ensure that we don't have any extra params or kw-params + when we don't have a params array or params dict to expand them into. + + + + + Helper function to validate that a named arg isn't duplicated with by + a params list or the dictionary (or both). + + + + + Helper function to get a value (which has no default) from either the + params list or the dictionary (or both). + + + + + Helper function to get the specified variable from the dictionary. + + + + + Helper function to extract the variable from defaults, or to call a helper + to check params / kw-dict / defaults to see which one contains the actual value. + + + + + Helper function to extract from the params list or dictionary depending upon + which one has an available value. + + + + + Helper function to extract the next argument from the params list. + + + + + Fixes up the argument list for the appropriate target delegate type. + + + + + Helper function to get the function argument strongly typed. + + + + + Called when the user is expanding a dictionary - we copy the user + dictionary and verify that it contains only valid string names. + + + + + Called when the user is expanding a params argument + + + + + Called when the user hasn't supplied a dictionary to be expanded but the + function takes a dictionary to be expanded. + + + + + Helper function to create the expression for creating the actual tuple passed through. + + + + + Creates the code to invoke the target delegate function w/ the specified arguments. + + + + + Appends the initialization code for the call to the function if any exists. + + + + + Creating a standard .NET type is easy - we just call it's constructor with the provided + arguments. + + + + + Creating a Python type involves calling __new__ and __init__. We resolve them + and generate calls to either the builtin funcions directly or embed sites which + call the slots at runtime. + + + + + Checks if we have a default new and init - in this case if we have any + arguments we don't allow the call. + + + + + Creates a test which tests the specific version of the type. + + + + + Base class for performing member binding. Derived classes override Add methods + to produce the actual final result based upon what the GetBinderHelper resolves. + + + + + + Provides the normal meta binder binding. + + + + + Provides delegate based fast binding. + + + + + The result type of the operation. + + + + + Looks up __init__ avoiding calls to __getattribute__ and handling both + new-style and old-style classes in the MRO. + + + + + Gets a builtin function for the given declaring type and member infos. + + Given the same inputs this always returns the same object ensuring there's only 1 builtinfunction + for each .NET method. + + This method takes both a cacheName and a pythonName. The cache name is the real method name. The pythonName + is the name of the method as exposed to Python. + + + + + Checks to see if the provided members are always visible for the given type. + + This filters out methods such as GetHashCode and Equals on standard .NET + types that we expose directly as Python types (e.g. object, string, etc...). + + It also filters out the base helper overrides that are added for supporting + super calls on user defined types. + + + + + a function is static if it's a static .NET method and it's defined on the type or is an extension method + with StaticExtensionMethod decoration. + + + + + If we have only interfaces, we'll need to insert object's base + + + + + Simple implementation of ASCII encoding/decoding. The default instance (PythonAsciiEncoding.Instance) is + setup to always convert even values outside of the ASCII range. The EncoderFallback/DecoderFallbacks can + be replaced with versions that will throw exceptions instead though. + + + + + Specialized version because enumerating tuples by Python's definition + doesn't call __getitem__, but filter does! + + + + + Opens a file and returns a new file object. + + name -> the name of the file to open. + mode -> the mode to open the file (r for reading, w for writing, a for appending, default is r). + bufsize -> the size of the buffer to be used (<= 0 indicates to use the default size) + + + + + Creates a new Python file object from a .NET stream object. + + stream -> the stream to wrap in a file object. + + + + + object overload of range - attempts to convert via __int__, and __trunc__ if arg is + an OldInstance + + + + + object overload of range - attempts to convert via __int__, and __trunc__ if arg is + an OldInstance + + + + + Gets the appropriate LanguageContext to be used for code compiled with Python's compile, eval, execfile, etc... + + + + Returns true if we should inherit our callers context (true division, etc...), false otherwise + + + Returns the default compiler flags or the flags the user specified. + + + + Gets a scope used for executing new code in optionally replacing the globals and locals dictionaries. + + + + + Set if the function includes a *args argument list. + + + + + Set if the function includes a **kwargs argument dictionary. + + + + + Set if the function is a generator. + + + + + Set if the function was compiled with future division. + + + + + IronPython specific: Set if the function includes nested exception handling and therefore can alter + sys.exc_info(). + + + + + IronPython specific: Set if the function includes a try/finally block. + + + + + Represents a piece of code. This can reference either a CompiledCode + object or a Function. The user can explicitly call FunctionCode by + passing it into exec or eval. + + + + + This is both the lock that is held while enumerating the threads or updating the thread accounting + information. It's also a marker CodeList which is put in place when we are enumerating the thread + list and all additions need to block. + + This lock is also acquired whenever we need to calculate how a function's delegate should be created + so that we don't race against sys.settrace/sys.setprofile. + + + + + Constructor used to create a FunctionCode for code that's been serialized to disk. + + Code constructed this way cannot be interpreted or debugged using sys.settrace/sys.setprofile. + + Function codes created this way do support recursion enforcement and are therefore registered in the global function code registry. + + + + + Constructor to create a FunctionCode at runtime. + + Code constructed this way supports both being interpreted and debugged. When necessary the code will + be re-compiled or re-interpreted for that specific purpose. + + Function codes created this way do support recursion enforcement and are therefore registered in the global function code registry. + + the initial delegate provided here should NOT be the actual code. It should always be a delegate which updates our Target lazily. + + + + + Registers the current function code in our global weak list of all function codes. + + The weak list can be enumerated with GetAllCode(). + + Ultimately there are 3 types of threads we care about races with: + 1. Other threads which are registering function codes + 2. Threads calling sys.settrace which require the world to stop and get updated + 3. Threads running cleanup (thread pool thread, or call to gc.collect). + + The 1st two must have perfect synchronization. We cannot have a thread registering + a new function which another thread is trying to update all of the functions in the world. Doing + so would mean we could miss adding tracing to a thread. + + But the cleanup thread can run in parallel to either registrying or sys.settrace. The only + thing it needs to take a lock for is updating our accounting information about the + number of code objects are alive. + + + + + Enumerates all function codes for updating the current type of targets we generate. + + While enumerating we hold a lock so that users cannot change sys.settrace/sys.setprofile + until the lock is released. + + + + + Creates a FunctionCode object for exec/eval/execfile'd/compile'd code. + + The code is then executed in a specific CodeContext by calling the .Call method. + + If the code is being used for compile (vs. exec/eval/execfile) then it needs to be + registered incase our tracing mode changes. + + + + + Called the 1st time a function is invoked by our OriginalCallTarget* methods + over in PythonCallTargets. This computes the real delegate which needs to be + created for the function. Usually this means starting off interpretering. It + also involves adding the wrapper function for recursion enforcement. + + Because this can race against sys.settrace/setprofile we need to take our + _ThreadIsEnumeratingAndAccountingLock to ensure no one is actively changing all + of the live functions. + + + + + Updates the delegate based upon current Python context settings for recursion enforcement + and for tracing. + + + + + Called to set the initial target delegate when the user has passed -X:Debug to enable + .NET style debugging. + + + + + Gets the LambdaExpression for tracing. + + If this is a generator function code then the lambda gets tranformed into the correct generator code. + + + + + Gets the correct final LambdaExpression for this piece of code. + + This is either just _lambda or _lambda re-written to be a generator expression. + + + + + Returns a list of variable names which are accessed from nested functions. + + + + + Returns the byte code. IronPython does not implement this and always + returns an empty string for byte code. + + + + + Returns a list of constants used by the function. + + The first constant is the doc string, or None if no doc string is provided. + + IronPython currently does not include any other constants than the doc string. + + + + + Returns the filename that the code object was defined in. + + + + + Returns the 1st line number of the code object. + + + + + Returns a set of flags for the function. + + 0x04 is set if the function used *args + 0x08 is set if the function used **args + 0x20 is set if the function is a generator + + + + + Returns a list of free variables (variables accessed + from an outer scope). This does not include variables + accessed in the global scope. + + + + + Returns a mapping between byte code and line numbers. IronPython does + not implement this because byte code is not available. + + + + + Returns the name of the code (function name, class name, or <module>). + + + + + Returns a list of global variable names accessed by the code. + + + + + Returns the number of local varaibles defined in the function. + + + + + Returns the stack size. IronPython does not implement this + because byte code is not supported. + + + + + Extremely light weight linked list of weak references used for tracking + all of the FunctionCode objects which get created and need to be updated + for purposes of recursion enforcement or tracing. + + + + + General conversion routine TryConvert - tries to convert the object to the desired type. + Try to avoid using this method, the goal is to ultimately remove it! + + + + + This function tries to convert an object to IEnumerator, or wraps it into an adapter + Do not use this function directly. It is only meant to be used by Ops.GetEnumerator. + + + + + This function tries to convert an object to IEnumerator, or wraps it into an adapter + Do not use this function directly. It is only meant to be used by Ops.GetEnumerator. + + + + + Attempts to convert value into a index usable for slicing and return the integer + value. If the conversion fails false is returned. + + If throwOverflowError is true then BigInteger's outside the normal range of integers will + result in an OverflowError. + + + + + Attempts to convert value into a index usable for slicing and return the integer + value. If the conversion fails false is returned. + + If throwOverflowError is true then BigInteger's outside the normal range of integers will + result in an OverflowError. + + + + + Converts a value to int ignoring floats + + + + + Note: + IEnumerator innerEnum = Dictionary<K,V>.KeysCollections.GetEnumerator(); + innerEnum.MoveNext() will throw InvalidOperation even if the values get changed, + which is supported in python + + + + + Note: + IEnumerator innerEnum = Dictionary<K,V>.KeysCollections.GetEnumerator(); + innerEnum.MoveNext() will throw InvalidOperation even if the values get changed, + which is supported in python + + + + + Note: + IEnumerator innerEnum = Dictionary<K,V>.KeysCollections.GetEnumerator(); + innerEnum.MoveNext() will throw InvalidOperation even if the values get changed, + which is supported in python + + + + + Provides both helpers for implementing Python dictionaries as well + as providing public methods that should be exposed on all dictionary types. + + Currently these are published on IDictionary<object, object> + + + + + Creates a DLR OverloadDoc object which describes information about this overload. + + The method to document + The name of the method if it should override the name in the MethodBase + Parameters to skip at the end - used for removing the value on a setter method + true to include self on instance methods + + + + True iff the thread is currently inside the generator (ie, invoking the _next delegate). + This can be used to enforce that a generator does not call back into itself. + Pep255 says that a generator should throw a ValueError if called reentrantly. + + + + + We cache the GeneratorFinalizer of generators that were closed on the user + thread, and did not get finalized on the finalizer thread. We can then reuse + the object. Reusing objects with a finalizer is good because it reduces + the load on the GC's finalizer queue. + + + + + Fields set by Throw() to communicate an exception to the yield point. + These are plumbed through the generator to become parameters to Raise(...) invoked + at the yield suspension point in the generator. + + + + + Value sent by generator.send(). + Since send() could send an exception, we need to keep this different from throwable's value. + + + + + See PEP 342 (http://python.org/dev/peps/pep-0342/) for details of new methods on Generator. + Full signature including default params for throw is: + throw(type, value=None, traceback=None) + Use multiple overloads to resolve the default parameters. + + + + + Throw(...) is like Raise(...) being called from the yield point within the generator. + Note it must come from inside the generator so that the traceback matches, and so that it can + properly cooperate with any try/catch/finallys inside the generator body. + + If the generator catches the exception and yields another value, that is the return value of g.throw(). + + + + + send() was added in Pep342. It sends a result back into the generator, and the expression becomes + the result of yield when used as an expression. + + + + + Close introduced in Pep 342. + + + + + Core implementation of IEnumerator.MoveNext() + + + + + Core implementation of Python's next() method. + + + + + Helper called from PythonOps after the yield statement + Keepin this in a helper method: + - reduces generated code size + - allows better coupling with PythonGenerator.Throw() + - avoids throws from emitted code (which can be harder to debug). + + + + + + Called to throw an exception set by Throw(). + + + + + Gets the name of the function that produced this generator object. + + + + + True if the generator has finished (is "closed"), else false. + Python language spec mandates that calling Next on a closed generator gracefully throws a StopIterationException. + This can never be reset. + + + + + True if the generator can set sys exc info and therefore needs exception save/restore. + + + + + Importer class - used for importing modules. Used by Ops and __builtin__ + Singleton living on Python engine. + + + + + Gateway into importing ... called from Ops. Performs the initial import of + a module and returns the module. + + + + + Gateway into importing ... called from Ops. Performs the initial import of + a module and returns the module. This version returns light exceptions instead of throwing. + + + + + Gateway into importing ... called from Ops. This is called after + importing the module and is used to return individual items from + the module. The outer modules dictionary is then updated with the + result. + + + + + Called by the __builtin__.__import__ functions (general importing) and ScriptEngine (for site.py) + + level indiciates whether to perform absolute or relative imports. + -1 indicates both should be performed + 0 indicates only absolute imports should be performed + Positive numbers indicate the # of parent directories to search relative to the calling module + + + + + Interrogates the importing module for __name__ and __path__, which determine + whether the imported module (whose name is 'name') is being imported as nested + module (__path__ is present) or as sibling. + + For sibling import, the full name of the imported module is parent.sibling + For nested import, the full name of the imported module is parent.module.nested + where parent.module is the mod.__name__ + + + the globals dictionary + Name of the module to be imported + Output - full name of the module being imported + Path to use to search for "full" + the import level for relaive imports + the parent module + the global __package__ value + + + + + Given the parent module name looks up the __path__ property. + + + + + Trys to get an existing module and if that fails fall backs to searching + + + + + Attempts to load a module from sys.meta_path as defined in PEP 302. + + The meta_path provides a list of importer objects which can be used to load modules before + searching sys.path but after searching built-in modules. + + + + + Given a user defined importer object as defined in PEP 302 tries to load a module. + + First the find_module(fullName, path) is invoked to get a loader, then load_module(fullName) is invoked + + + + + Finds a user defined importer for the given path or returns null if no importer + handles this path. + + + + + Creates a new list with the data in the array and a size + the same as the length of the array. The array is held + onto and may be mutated in the future by the list. + + params array to use for lists storage + + + + Gets a reasonable size for the addition of two arrays. We round + to a power of two so that we usually have some extra space if + the resulting array gets added to. + + + + + Non-thread safe adder, should only be used by internal callers that + haven't yet exposed their list. + + + + + Compares the two specified keys + + + + + Supports __index__ on arbitrary types, also prevents __float__ + + + + + we need to lock both objects (or copy all of one's data w/ it's lock held, and + then compare, which is bad). Therefore we have a strong order for locking on + the two objects based upon the hash code or object identity in case of a collision + + + + + Summary description for ConstantValue. + + + + + Multiply two object[] arrays - slow version, we need to get the type, etc... + + + + + Multiply two object[] arrays - internal version used for objects backed by arrays + + + + + Add two arrays - internal versions for objects backed by arrays + + + + + + + + + + We override the behavior of equals, compare and hashcode to make + chars seem as much like strings as possible. In Python there is no + difference between these types. + + + + + Helper class that all custom type descriptor implementations call for + the bulk of their implementation. + + + + + Returns the digits for the format spec, no sign is included. + + + + + InstanceOps contains methods that get added to CLS types depending on what + methods and constructors they define. These have not been added directly to + PythonType since they need to be added conditionally. + + Possibilities include: + + __new__, one of 3 __new__ sets can be added: + DefaultNew - This is the __new__ used for a PythonType (list, dict, object, etc...) that + has only 1 default public constructor that takes no parameters. These types are + mutable types, and __new__ returns a new instance of the type, and __init__ can be used + to re-initialize the types. This __new__ allows an unlimited number of arguments to + be passed if a non-default __init__ is also defined. + + NonDefaultNew - This is used when a type has more than one constructor, or only has one + that takes more than zero parameters. This __new__ does not allow an arbitrary # of + extra arguments. + + DefaultNewCls - This is the default new used for CLS types that have only a single ctor + w/ an arbitray number of arguments. This constructor allows setting of properties + based upon an extra set of kw-args, e.g.: System.Windows.Forms.Button(Text='abc'). It + is only used on non-Python types. + + __init__: + For types that do not define __init__ we have an __init__ function that takes an + unlimited number of arguments and does nothing. All types share the same reference + to 1 instance of this. + + next: Defined when a type is an enumerator to expose the Python iter protocol. + + + repr: Added for types that override ToString + + get: added for types that implement IDescriptor + + + + + __dir__(self) -> Returns the list of members defined on a foreign IDynamicMetaObjectProvider. + + + + + Provides the implementation of __enter__ for objects which implement IDisposable. + + + + + Provides the implementation of __exit__ for objects which implement IDisposable. + + + + + Determines if a type member can be imported. This is used to treat static types like modules. + + + + + Implements __contains__ for types implementing IEnumerable of T. + + + + + Implements __contains__ for types implementing IEnumerable + + + + + Implements __contains__ for types implementing IEnumerable of T. + + + + + Implements __contains__ for types implementing IEnumerable + + + + + Implements __reduce_ex__ for .NET types which are serializable. This uses the .NET + serializer to get a string of raw data which can be serialized. + + + + + Contains Python extension methods that are added to object + + + + Types for which the pickle module has built-in support (from PEP 307 case 2) + + + + __class__, a custom slot so that it works for both objects and types. + + + + + Removes an attribute from the provided member + + + + + Returns the hash code of the given object + + + + + Gets the specified attribute from the object without running any custom lookup behavior + (__getattr__ and __getattribute__) + + + + + Initializes the object. The base class does nothing. + + + + + Initializes the object. The base class does nothing. + + + + + Initializes the object. The base class does nothing. + + + + + Creates a new instance of the type + + + + + Creates a new instance of the type + + + + + Creates a new instance of the type + + + + + Runs the pickle protocol + + + + + Runs the pickle protocol + + + + + Runs the pickle protocol + + + + + Returns the code representation of the object. The default implementation returns + a string which consists of the type and a unique numerical identifier. + + + + + Sets an attribute on the object without running any custom object defined behavior. + + + + + Returns the number of bytes of memory required to allocate the object. + + + + + Returns a friendly string representation of the object. + + + + + Return a dict that maps slot names to slot values, but only include slots that have been assigned to. + Looks up slots in base types as well as the current type. + + Sort-of Python equivalent (doesn't look up base slots, while the real code does): + return dict([(slot, getattr(self, slot)) for slot in type(self).__slots__ if hasattr(self, slot)]) + + Return null if the object has no __slots__, or empty dict if it has __slots__ but none are initialized. + + + + + Implements the default __reduce_ex__ method as specified by PEP 307 case 2 (new-style instance, protocol 0 or 1) + + + + + Returns the closest base class (in terms of MRO) that isn't defined in Python code + + + + + Implements the default __reduce_ex__ method as specified by PEP 307 case 3 (new-style instance, protocol 2) + + + + + Contains functions that are called directly from + generated code to perform low-level runtime functionality. + + + + + Creates a new dictionary extracting the keys and values from the + provided data array. Keys/values are adjacent in the array with + the value coming first. + + + + + Creates a new dictionary extracting the keys and values from the + provided data array. Keys/values are adjacent in the array with + the value coming first. + + + + + Wraps up all the semantics of multiplying sequences so that all of our sequences + don't duplicate the same logic. When multiplying sequences we need to deal with + only multiplying by valid sequence types (ints, not floats), support coercion + to integers if the type supports it, not multiplying by None, and getting the + right semantics for multiplying by negative numbers and 1 (w/ and w/o subclasses). + + This function assumes that it is only called for case where count is not implicitly + coercible to int so that check is skipped. + + + + + Supports calling of functions that require an explicit 'this' + Currently, we check if the function object implements the interface + that supports calling with 'this'. If not, the 'this' object is dropped + and a normal call is made. + + + + + Called from generated code emitted by NewTypeMaker. + + + + + Handles the descriptor protocol for user-defined objects that may implement __get__ + + + + + Handles the descriptor protocol for user-defined objects that may implement __set__ + + + + + Handles the descriptor protocol for user-defined objects that may implement __delete__ + + + + + Python runtime helper for raising assertions. Used by AssertStatement. + + Object representing the assertion message + + + + Python runtime helper to create instance of Python List object. + + New instance of List + + + + Python runtime helper to create a populated instance of Python List object. + + + + + Python runtime helper to create a populated instance of Python List object w/o + copying the array contents. + + + + + Python runtime helper to create a populated instance of Python List object. + + List is populated by arbitrary user defined object. + + + + + Python runtime helper to create an instance of Python List object. + + List has the initial provided capacity. + + + + + Python runtime helper to create an instance of Tuple + + + + + + + Python runtime helper to create an instance of Tuple + + + + + + Python Runtime Helper for enumerator unpacking (tuple assignments, ...) + Creates enumerator from the input parameter e, and then extracts + expected number of values, returning them as array + + If the input is a Python tuple returns the tuples underlying data array. Callers + should not mutate the resulting tuple. + + The code context of the AST getting enumerator values. + object to enumerate + expected number of objects to extract from the enumerator + + array of objects (.Lengh == expected) if exactly expected objects are in the enumerator. + Otherwise throws exception + + + + + Python runtime helper to create instance of Slice object + + Start of the slice. + End of the slice. + Step of the slice. + Slice + + + + Prints newline into default standard output + + + + + Prints newline into specified destination. Sets softspace property to false. + + + + + Prints value into default standard output with Python comma semantics. + + + + + Prints value into specified destination with Python comma semantics. + + + + + Called from generated code when we are supposed to print an expression value + + + + + Called from generated code for: + + import spam.eggs + + + + + Python helper method called from generated code for: + + import spam.eggs as ham + + + + + Called from generated code for: + + from spam import eggs1, eggs2 + + + + + Imports one element from the module in the context of: + + from module import a, b, c, d + + Called repeatedly for all elements being imported (a, b, c, d above) + + + + + Called from generated code for: + + from spam import * + + + + + Unqualified exec statement support. + A Python helper which will be called for the statement: + + exec code + + + + + Qualified exec statement support, + Python helper which will be called for the statement: + + exec code in globals [, locals ] + + + + + Called from generated code at the start of a catch block. + + + + + Get an exception tuple for the "current" exception. This is used for sys.exc_info() + + + + + Get an exception tuple for a given exception. This is like the inverse of MakeException. + + the code context + the exception to create a tuple for. + a tuple of (type, value, traceback) + This is called directly by the With statement so that it can get an exception tuple + in its own private except handler without disturbing the thread-wide sys.exc_info(). + + + + helper function for re-raised exceptions. + + + + + helper function for non-re-raise exceptions. + + type is the type of exception to throw or an instance. If it + is an instance then value should be null. + + If type is a type then value can either be an instance of type, + a Tuple, or a single value. This case is handled by EC.CreateThrowable. + + + + + Extracts an argument from either the dictionary or params + + + + + Creates a new array the values set to Uninitialized.Instance. The array + is large enough to hold for all of the slots allocated for the type and + its sub types. + + + + + Helper to determine if the value is a simple numeric type (int or big int or bool) - used for OldInstance + deprecated form of slicing. + + + + + Helper to determine if the type is a simple numeric type (int or big int or bool) - used for OldInstance + deprecated form of slicing. + + + + + Helper to determine if the type is a simple numeric type (int or big int or bool) but not a subclass + + + + + For slicing. Fixes up a BigInteger and returns an integer w/ the length of the + object added if the value is negative. + + + + + For slicing. Gets the length of the object, used to only get the length once. + + + + + Helper method for DynamicSite rules that check the version of their dynamic object + TODO - Remove this method for more direct field accesses + + + + + + + + Called from generated code. Gets a builtin function and the BuiltinFunctionData associated + with the object. Tests to see if the function is bound and has the same data for the generated + rule. + + + + + Convert object to a given type. This code is equivalent to NewTypeMaker.EmitConvertFromObject + except that it happens at runtime instead of compile time. + + + + + Provides access to AppDomain.DefineDynamicAssembly which cannot be called from a DynamicMethod + + + + + Generates a new delegate type. The last type in the array is the return type. + + + + + Generates a new delegate type. The last type in the array is the return type. + + + + + Provides the entry point for a compiled module. The stub exe calls into InitializeModule which + does the actual work of adding references and importing the main module. Upon completion it returns + the exit code that the program reported via SystemExit or 0. + + + + + Provides the entry point for a compiled module. The stub exe calls into InitializeModule which + does the actual work of adding references and importing the main module. Upon completion it returns + the exit code that the program reported via SystemExit or 0. + + + + + Called from generated code, helper to remove a name + + + + + Called from generated code, helper to do name lookup + + + + + Called from generated code, helper to do name assignment + + + + + Returns an IntPtr in the proper way to CPython - an int or a Python long + + + + + Create at TypeError exception for when Raise() can't create the exception requested. + + original type of exception requested + a TypeEror exception + + + + Gets a list of DynamicStackFrames for the given exception. These stack frames + can be programmatically inspected to understand the frames the exception crossed + through including Python frames. + + Dynamic stack frames are not preserved when an exception crosses an app domain + boundary. + + + + + Helper clas for calls to unicode(...). We generate code which checks if unicode + is str and if it is we redirect those calls to the unicode function defined on this + class. + + + + + ExtensibleString is the base class that is used for types the user defines + that derive from string. It carries along with it the string's value and + our converter recognizes it as a string. + + + + + StringOps is the static class that contains the methods defined on strings, i.e. 'abc' + + Here we define all of the methods that a Python user would see when doing dir('abc'). + If the user is running in a CLS aware context they will also see all of the methods + defined in the CLS System.String type. + + + + + Returns a copy of this string converted to uppercase + + + + + return true if self is a titlecased string and there is at least one + character in self; also, uppercase characters may only follow uncased + characters (e.g. whitespace) and lowercase characters only cased ones. + return false otherwise. + + + + + Return a string which is the concatenation of the strings + in the sequence seq. The separator between elements is the + string providing this method + + + + + Replaces each replacement field in the string with the provided arguments. + + replacement_field = "{" field_name ["!" conversion] [":" format_spec] "}" + field_name = (identifier | integer) ("." identifier | "[" element_index "]")* + + format_spec: [[fill]align][sign][#][0][width][,][.precision][type] + + Conversion can be 'r' for repr or 's' for string. + + + + + Replaces each replacement field in the string with the provided arguments. + + replacement_field = "{" field_name ["!" conversion] [":" format_spec] "}" + field_name = (identifier | integer) ("." identifier | "[" element_index "]")* + + format_spec: [[fill]align][sign][#][0][width][.precision][type] + + Conversion can be 'r' for repr or 's' for string. + + + + + Gets the starting offset checking to see if the incoming bytes already include a preamble. + + + + When encoding or decoding strings if an error occurs CPython supports several different + behaviors, in addition it supports user-extensible behaviors as well. For the default + behavior we're ok - both of us support throwing and replacing. For custom behaviors + we define a single fallback for decoding and encoding that calls the python function to do + the replacement. + + When we do the replacement we call the provided handler w/ a UnicodeEncodeError or UnicodeDecodeError + object which contains: + encoding (string, the encoding the user requested) + end (the end of the invalid characters) + object (the original string being decoded) + reason (the error, e.g. 'unexpected byte code', not sure of others) + start (the start of the invalid sequence) + + The decoder returns a tuple of (unicode, int) where unicode is the replacement string + and int is an index where encoding should continue. + + + + Indexer for generic parameter resolution. We bind to one of the generic versions + available in this type collision. A user can also do someType[()] to force to + bind to the non-generic version, but we will always present the non-generic version + when no bindings are available. + + + + + Object.ToString() displays the CLI type name. But we want to display the class name (e.g. + '<foo object at 0x000000000000002C>' unless we've overridden __repr__ but not __str__ in + which case we'll display the result of __repr__. + + + + + Provides a debug view for user defined types. This class is declared as public + because it is referred to from generated code. You should not use this class. + + + + + A DynamicMetaObject which is just used to support custom conversions to COM. + + + + + A marker interface so we can recognize and access sequence members on our array objects. + + + + + List of unary operators which we have sites for to enable fast dispatch that + doesn't collide with other operators. + + + + + Sets the mode to text or binary. Returns true if previously set to text, false if previously set to binary. + + + + + Truncates the file to the current length as indicated by tell(). + + + + + Truncates the file to the specified length. + + + + + + Provides storage of IronPython specific data in the DLR Scope ScopeExtension. + + This enables IronPython to track code compilation flags such as from __future__ + flags and import clr flags across multiple executions of user-provided scopes. + + + + + Provides human readable names for how Python maps the various DLR NarrowingLevel's. + + + + + No narrowing conversions are performed + + + + + Double/Single to Decimal + PythonTuple to Array + Generic conversions + BigInteger to Int64 + + + + + Numeric conversions excluding from floating point values + Boolean conversions + Delegate conversions + Enumeration conversions + + + + + Enables Python protocol conversions (__int__, etc...) + + + + + Provides dictionary based storage which is backed by a Scope object. + + + + + Mutable set class + + + + + Appends an IEnumerable to an existing set + + + + + Immutable set class + + + + + Iterator over sets + + + + + Gets the indices for the deprecated __getslice__, __setslice__, __delslice__ functions + + This form is deprecated in favor of using __getitem__ w/ a slice object as an index. This + form also has subtly different mechanisms for fixing the slice index before calling the function. + + If an index is negative and __len__ is not defined on the object than an AttributeError + is raised. + + + + + StringFormatter provides Python's % style string formatting services. + + + + + Read a possible mapping key for %(key)s. + + The key name enclosed between the '%(key)s', + or null if there are no paranthesis such as '%s'. + + + + AppendBase appends an integer at the specified radix doing all the + special forms for Python. We have a copy and paste version of this + for BigInteger below that should be kept in sync. + + + + + BigInteger version of AppendBase. Should be kept in sync w/ AppendBase + + + + + public class to get optimized + + + + + Returns detailed call statistics. Not implemented in IronPython and always returns None. + + + + + Handles output of the expression statement. + Prints the value and sets the __builtin__._ + + + + + Provides a CustomTracker which handles special fields which have custom + behavior on get/set. + + + + + Provides custom, versioned, dictionary access for instances. Used for both + new-style and old-style instances. + + Each class can allocate a version for instance storage using the + CustomInstanceDictionaryStorage.AllocateInstance method. The version allocated + is dependent upon the names which are likely to appear in the instance + dictionary. Currently these names are calculated by collecting the names + that are assigned to during the __init__ method and combining these with + all such names in the types MRO. + + When creating the dictionary for storing instance values the class can then create + a PythonDictionary backed by a CustomInstanceDictionaryStorage with it's + version. When doing a get/set optimized code can then be produced that + verifies we have CustomInstanceDictionaryStorage and it has the + correct version. If we have a matching dictionary then gets/sets can turn + into simple array accesses rather than dictionary gets/sets. For programs + which access a large number of instance variables this can dramatically + speed up the program. + + TODO: Should we attempt to unify all versions which share the same keys? + + + + + Interface used for things which can convert to delegates w/o code gen. Currently + this is just non-overloaded builtin functions and bound builtin functions. Avoiding + the code gen is not only nice for compilation but it also enables delegates to be added + in C# and removed in Python. + + + + + Represents a set of attributes that different functions can have. + + + + No flags have been set + + + This is a function w/ no instance pointer + + + This is a method that requires an instance + + + Built-in functions can encapsulate both methods and functions, in which case both bits are set + + + True is the function/method should be visible from pure-Python code + + + True if this is a __r*__ method for a CLS overloaded operator method + + + + This method represents a binary operator method for a CLS overloaded operator method. + + Being a binary operator causes the following special behaviors to kick in: + A failed binding at call time returns NotImplemented instead of raising an exception + A reversed operator will automatically be created if: + 1. The parameters are both of the instance type + 2. The parameters are in reversed order (other, this) + + This enables simple .NET operator methods to be mapped into the Python semantics. + + + + + A method declared on a built-in module + + + + + OperatorMapping provides a mapping from DLR operators to their associated .NET methods. + + + + + Given an operator returns the OperatorMapping associated with the operator or null + + + + + The operator the OperatorMapping provides info for. + + + + + The primary method name associated with the method. This method name is + usally in the form of op_Operator (e.g. op_Addition). + + + + + The secondary method name associated with the method. This method name is + usually a standard .NET method name with pascal casing (e.g. Add). + + + + + The return type that must match for the alternate operator to be valid. + + This is available alternate operators don't have special names and therefore + could be confused for a normal method which isn't fulfilling the contract. + + + + + This helper type lets us build a fake ParameterInfo object with a specific type and name + to pass along to methods that expect ParameterInfos. This is currently found useful + for the NewTypeMaker code and may be useful in other situations as well. + + + + + Cached CallSites. User types are cached on the PythonType and System types are cached on the + PythonContext to avoid cross-runtime contamination due to the binder on the site. + + + + + Represents a PythonType. Instances of PythonType are created via PythonTypeBuilder. + + + + + Used in copy_reg which is the only consumer of __flags__ in the standard library. + + Set if the type is user defined + + + + + Set if the type has __abstractmethods__ defined + + + + + Implements fast binding for user defined types. This ensures that common highly dynamic + scenarios will run fast (for instance creating new types repeatedly and only creating a limited + number of instances of them). It also gives better code sharing amongst different subclasses + of the same types and improved startup time due to reduced code generation. + + + + + Provides delegates that will invoke a parameterless type ctor. The first key provides + the dictionary for a specific type, the 2nd key provides the delegate for a specific + call site type used in conjunction w/ our IFastInvokable implementation. + + + + + Shared built-in functions for creating instances of user defined types. Because all + types w/ the same UnderlyingSystemType share the same constructors these can be + shared across multiple types. + + + + + Creates a new type for a user defined type. The name, base classes (a tuple of type + objects), and a dictionary of members is provided. + + + + + Creates a new type for a user defined type. The name, base classes (a tuple of type + objects), and a dictionary of members is provided. + + + + + Creates a new PythonType object which is backed by the specified .NET type for + storage. The type is considered a system type which can not be modified + by the user. + + + + + + Creates a new PythonType which is a subclass of the specified PythonType. + + Used for runtime defined new-style classes which require multiple inheritance. The + primary example of this is the exception system. + + + + + Creates a new PythonType which is a subclass of the specified PythonTypes. + + Used for runtime defined new-style classes which require multiple inheritance. The + primary example of this is the exception system. + + + + + Creates a new PythonType which is a subclass of the specified PythonTypes. + + Used for runtime defined new-style classes which require multiple inheritance. The + primary example of this is the exception system. + + + + + Creates a new PythonType which is a subclass of the specified PythonType. + + Used for runtime defined new-style classes which require multiple inheritance. The + primary example of this is the exception system. + + + + + Creates a new PythonType which is a subclass of the specified PythonTypes. + + Used for runtime defined new-style classes which require multiple inheritance. The + primary example of this is the exception system. + + + + + Creates a new PythonType which is a subclass of the specified PythonTypes. + + Used for runtime defined new-style classes which require multiple inheritance. The + primary example of this is the exception system. + + + + + Creates a new PythonType object which represents an Old-style class. + + + + + Returns true if the specified object is an instance of this type. + + + + + Gets the dynamic type that corresponds with the provided static type. + + Returns null if no type is available. TODO: In the future this will + always return a PythonType created by the DLR. + + + + + + + Sets the python type that corresponds with the provided static type. + + This is used for built-in types which have a metaclass. Currently + only used by ctypes. + + + + + Allocates the storage for the instance running the .NET constructor. This provides + the creation functionality for __new__ implementations. + + + + + Allocates the storage for the instance running the .NET constructor. This provides + the creation functionality for __new__ implementations. + + + + + Allocates the storage for the instance running the .NET constructor. This provides + the creation functionality for __new__ implementations. + + + + + Allocates the storage for the instance running the .NET constructor. This provides + the creation functionality for __new__ implementations. + + + + + Allocates the storage for the instance running the .NET constructor. This provides + the creation functionality for __new__ implementations. + + + + + Allocates the storage for the instance running the .NET constructor. This provides + the creation functionality for __new__ implementations. + + + + + Returns true if this type is a subclass of other + + + + + Looks up a slot on the dynamic type + + + + + Searches the resolution order for a slot matching by name + + + + + Searches the resolution order for a slot matching by name. + + Includes searching for methods in old-style classes + + + + + Internal helper to add a new slot to the type + + + + + + + Gets a value from a dynamic type and any sub-types. Values are stored in slots (which serve as a level of + indirection). This searches the types resolution order and returns the first slot that + contains the value. + + + + + Attempts to lookup a member w/o using the customizer. Equivelent to object.__getattribute__ + but it doens't throw an exception. + + + + + + Gets a value from a dynamic type and any sub-types. Values are stored in slots (which serve as a level of + indirection). This searches the types resolution order and returns the first slot that + contains the value. + + + + + Attempts to lookup a member w/o using the customizer. + + + + + + Sets a value on an instance. If a slot is available in the most derived type the slot + is set there, otherwise the value is stored directly in the instance. + + + + + Attempst to set a value w/o going through the customizer. + + This enables languages to provide the "base" implementation for setting attributes + so that the customizer can call back here. + + + + + Returns a list of all slot names for the type and any subtypes. + + The context that is doing the inquiry of InvariantContext.Instance. + + + + Returns a list of all slot names for the type, any subtypes, and the instance. + + The context that is doing the inquiry of InvariantContext.Instance. + the instance to get instance members from, or null. + + + + Adds members from a user defined type. + + + + + Adds members from a user defined type instance + + + + + Gets the .NET type which is used for instances of the Python type. + + When overridden by a metaclass enables a customization of the .NET type which + is used for instances of the Python type. Meta-classes can construct custom + types at runtime which include new .NET methods, fields, custom attributes or + other features to better interoperate with .NET. + + + + + Initializes a PythonType that represents a standard .NET type. The same .NET type + can be shared with the Python type system. For example object, string, int, + etc... are all the same types. + + + + + Creates a __new__ method for the type. If the type defines interesting constructors + then the __new__ method will call that. Otherwise if it has only a single argless + + + + + This will return a unique integer for every version of every type in the system. + This means that DynamicSite code can generate a check to see if it has the correct + PythonType and version with a single integer compare. + + TODO - This method and related code should fail gracefully on overflow. + + + + + Internal helper function to add a subtype + + + + + Returns a CLR WeakReference object to this PythonType that can be shared + between anyone who needs a weak reference to the type. + + + + + Gets the name of the dynamic type + + + + + Gets the resolution order used for attribute lookup + + + + + Gets the underlying system type that is backing this type. All instances of this + type are an instance of the underlying system type. + + + + + Gets the extension type for this type. The extension type provides + a .NET type which can be inherited from to extend sealed classes + or value types which Python allows inheritance from. + + + + + Gets the base types from which this type inherits. + + + + + True if the type is a system type. A system type is a type which represents an + underlying .NET type and not a subtype of one of these types. + + + + + Gets a list of weak references to all the subtypes of this class. May return null + if there are no subtypes of the class. + + + + + Base class for doing fast type invoke binding. Subclasses are created using + reflection once during the binding. The subclasses can then proceed to do + the binding w/o using reflection. Otherwise we'd have lots more reflection + calls which would slow the binding up. + + + + + Gets or creates delegate for calling the constructor function. + + + + + The type has a ctor which does not accept PythonTypes. This is used + for user defined types which implement __clrtype__ + + + + + Used when a type overrides __new__ with a Python function or other object + that can return an arbitrary value. If the return value is not the same type + as the type which had __new__ then we need to lookup __init__ on the type + and invoke it. Also handles initialization for finalization when __del__ + is defined for the same reasons. + + + + + target is the newly initialized value. + args are the arguments to be passed to __init__ + + + + + Couples a MemberGroup and the name which produces the member group together + + + + + Represents an ops-extension which adds a new slot. The slot can have arbitrary + get/set behavior above and beyond normal .NET methods or properties. This is + typically in regards to how it processes access from instances or subtypes. + + + + + Provides a slot object for the dictionary to allow setting of the dictionary. + + + + + Calculates the method resolution order for a Python class + the rules are: + If A is a subtype of B, then A has precedence (A > B) + If C appears before D in the list of bases then C > D + If E > F in one __mro__ then E > F in all __mro__'s for our subtype + + class A(object): pass + class B(object): pass + class C(B): pass + class N(A,B,C): pass # illegal + + This is because: + C.__mro__ == (C, B, object) + N.__mro__ == (N, A, B, C, object) + which would conflict, but: + + N(B,A) is ok (N, B, a, object) + N(C, B, A) is ok (N, C, B, A, object) + + Calculates a C3 MRO as described in "The Python 2.3 Method Resolution Order" + plus support for old-style classes. + + We build up a list of our base classes MRO's plus our base classes themselves. + We go through the list in order. Look at the 1st class in the current list, and + if it's not the non-first class in any other list then remove it from all the lists + and append it to the mro. Otherwise continue to the next list. If all the classes at + the start are no-good then the MRO is bad and we throw. + + For old-style classes if the old-style class is the only one in the list of bases add + it as a depth-first old-style MRO, otherwise compute a new-style mro for all the classes + and use that. + + + + + + + + + Returns the dictionary used to store state for this object + + + + + Python module. Stores classes, functions, and data. Usually a module + is created by importing a file or package from disk. But a module can also + be directly created by calling the module type and providing a name or + optionally a documentation string. + + + + + Creates a new module backed by a Scope. Used for creating modules for foreign Scope's. + + + + + Creates a new PythonModule with the specified dictionary. + + Used for creating modules for builtin modules which don't have any code associated with them. + + + + + Represents a member of a user-defined type which defines __slots__. The names listed in + __slots__ have storage allocated for them with the type and provide fast get/set access. + + + + + Gets the index into the object array to be used for the slot storage. + + + + + Helpers for interacting w/ .NET types. This includes: + + Member resolution via GetMember/GetMembers. This performs a member lookup which includes the registered + extension types in the PythonBinder. Internally the class has many MemberResolver's which provide + the various resolution behaviors. + + Cached member access - this is via static classes such as Object and provides various MemberInfo's so we're + not constantly looking up via reflection. + + + + list of resolvers which we run to resolve items + + + + Gets the statically known member from the type with the specific name. Searches the entire type hierarchy to find the specified member. + + + + + Gets all the statically known members from the specified type. Searches the entire type hierarchy to get all possible members. + + The result may include multiple resolution. It is the callers responsibility to only treat the 1st one by name as existing. + + + + + Gets the statically known member from the type with the specific name. Searches only the specified type to find the member. + + + + + Gets all the statically known members from the specified type. Searches only the specified type to find the members. + + The result may include multiple resolution. It is the callers responsibility to only treat the 1st one by name as existing. + + + + + Creates the resolver table which includes all the possible resolutions. + + + + + + Provides a resolution for __str__. + + + + + Provides a resolution for __repr__ + + + + + Helper to see if the type explicitly overrides the method. This ignores members + defined on object. + + + + + Provides a resolution for __hash__, first looking for IStructuralEquatable.GetHashCode, + then IValueEquality.GetValueHashCode. + + + + + Provides a resolution for __new__. For standard .NET types __new__ resolves to their + constructor. For Python types they inherit __new__ from their base class. + + TODO: Can we just always fallback to object.__new__? If not why not? + + + + + Provides a resolution for next + + + + + Provides a resolution for __len__ + + + + + Provides a resolution for __iter__ + + + + + Looks for an Equals overload defined on the type and if one is present binds __ne__ to an + InstanceOps helper. + + + + + Provides an implementation of __contains__. We can pull contains from: + ICollection of T which defines Contains directly + IList which defines Contains directly + IDictionary which defines Contains directly + IDictionary of K,V which defines Contains directly + IEnumerable of K which we have an InstaceOps helper for + IEnumerable which we have an instance ops helper for + IEnumerator of K which we have an InstanceOps helper for + IEnumerator which we have an instance ops helper for + + String is ignored here because it defines __contains__ via extension methods already. + + The lookup is well ordered and not dependent upon the order of values returned by reflection. + + + + + Helper for IEnumerable/IEnumerator __contains__ + + + + + Primary worker for getting the member(s) associated with a single name. Can be called with different MemberBinder's to alter the + scope of the search. + + + + + Primary worker for returning a list of all members in a type. Can be called with different MemberBinder's to alter the scope + of the search. + + + + + Helper to get a MemberGroup for methods declared on InstanceOps + + + + + Helper to get the proper typecasting method, according to the following precedence rules: + + 1. Strongest (most specific) declaring type + 2. Strongest (most specific) parameter type + 3. Type of conversion + i. Implicit + ii. Explicit + 4. Return type (order specified in toTypes) + + + + + Helper for creating a typecast resolver + + + + + Helper for creating __getitem__/__setitem__ resolvers + + false for a getter, true for a setter + + + + Filters out methods which are present on standard .NET types but shouldn't be there in Python + + + + + When private binding is enabled we can have a collision between the private Event + and private field backing the event. We filter this out and favor the event. + + This matches the v1.0 behavior of private binding. + + + + + Filters down to include only protected methods + + + + + If an operator is a reverisble operator (e.g. addition) then we need to filter down to just the forward/reverse + versions of the .NET method. For example consider: + + String.op_Multiplication(int, string) + String.op_Multiplication(string, int) + + If this method were defined on string it defines that you can do: + 2 * 'abc' + or: + 'abc' * 2 + + either of which will produce 'abcabc'. The 1st form is considered the reverse form because it is declared on string + but takes a non-string for the 1st argument. The 2nd is considered the forward form because it takes a string as the + 1st argument. + + When dynamically dispatching for 2 * 'abc' we'll first try __mul__ on int, which will fail with a string argument. Then we'll try + __rmul__ on a string which will succeed and dispatch to the (int, string) overload. + + For multiplication in this case it's not too interesting because it's commutative. For addition this might be more interesting + if, for example, we had unicode and ASCII strings. In that case Unicode strings would define addition taking both unicode and + ASCII strings in both forms. + + + + + Checks to see if the parameter type and the declaring type are compatible to determine + if an operator is forward or reverse. + + + + + Checks to see if this is an operator method which Python recognizes. For example + op_Comma is not recognized by Python and therefore should exposed to the user as + a method that is callable by name. + + + + + Provides a resolution for __complex__ + + + + + Provides a resolution for __float__ + + + + + Provides a resolution for __int__ + + + + + Provides a resolution for __long__ + + + + + Provides a resolution for __getitem__ + + + + + Provides a resolution for __setitem__ + + + + + Abstract class used for resolving members. This provides two methods of member look. The first is looking + up a single member by name. The other is getting all of the members. + + There are various subclasses of this which have different methods of resolving the members. The primary + function of the resolvers are to provide the name->value lookup. They also need to provide a simple name + enumerator. The enumerator is kept simple because it's allowed to return duplicate names as well as return + names of members that don't exist. The base MemberResolver will then verify their existance as well as + filter duplicates. + + + + + Looks up an individual member and returns a MemberGroup with the given members. + + + + + Returns a list of members that exist on the type. The ResolvedMember structure indicates both + the name and provides the MemberGroup. + + + + + Returns a list of possible members which could exist. ResolveMember needs to be called to verify their existance. Duplicate + names can also be returned. + + + + + One off resolver for various special methods which are known by name. A delegate is provided to provide the actual member which + will be resolved. + + + + + Standard resolver for looking up .NET members. Uses reflection to get the members by name. + + + + + Resolves methods mapped to __eq__ and __ne__ from: + 1. IStructuralEquatable.Equals + 2. IValueEquality.Equals (CLR2 only) + + + + + Resolves methods mapped to __gt__, __lt__, __ge__, __le__, as well as providing an alternate resolution + for __eq__ and __ne__, from the comparable type's CompareTo method. + + This should be run after the EqualityResolver. + + + + + Resolves methods mapped to __*__ methods automatically from the .NET operator. + + + + + Filters alternative methods out that don't match the expected signature and therefore + are just sharing a common method name. + + + + + Removes Object.Equals methods as we never return these for PythonOperationKind. + + + + + Provides bindings to private members when that global option is enabled. + + + + + Provides resolutions for protected members that haven't yet been + subclassed by NewTypeMaker. + + + + + Base class used for resolving a name into a member on the type. + + + + + Gets an instance op method for the given type and name. + + Instance ops methods appaer on the base most class that's required to expose it. So + if we have: Array[int], Array, object we'd only add an instance op method to Array and + Array[int] inherits it. It's obviously not on object because if it was there we'd just + put the method in ObjectOps. + + Therefore the different binders expose this at the appropriate times. + + + + + MemberBinder which searches the entire type hierarchy and their extension types to find a member. + + + + + MemberBinder which searches only the current type and it's extension types to find a member. + + + + + BuiltinFunction represents any standard CLR function exposed to Python. + This is used for both methods on standard Python types such as list or tuple + and for methods from arbitrary .NET assemblies. + + All calls are made through the optimizedTarget which is created lazily. + + TODO: Back BuiltinFunction's by MethodGroup's. + + + + + Creates a new builtin function for a static .NET function. This is used for module methods + and well-known __new__ methods. + + + + + Creates a built-in function for a .NET method declared on a type. + + + + + Creates a bound built-in function. The instance may be null for built-in functions + accessed for None. + + + + + Returns a BuiltinFunction bound to the provided type arguments. Returns null if the binding + cannot be performed. + + + + + Returns a descriptor for the built-in function if one is + neededed + + + + + Makes a test for the built-in function against the private _data + which is unique per built-in function. + + + + + Helper for generating the call to a builtin function. This is used for calls from built-in method + descriptors and built-in functions w/ and w/o a bound instance. + + This provides all sorts of common checks on top of the call while the caller provides a delegate + to do the actual call. The common checks include: + check for generic-only methods + reversed operator support + transforming arguments so the default binder can understand them (currently user defined mapping types to PythonDictionary) + returning NotImplemented from binary operators + Warning when calling certain built-in functions + + + The call binder we're doing the call for + An expression which points to the code context + the meta object for the built in function + true if we're calling with an instance + The arguments being passed to the function + A restriction for the built-in function, method desc, etc... + A delegate to perform the actual call to the method. + + + + Gets the target methods that we'll be calling. + + + + + True if the method should be visible to non-CLS opt-in callers + + + + + Provides (for reflected methods) a mapping from a signature to the exact target + which takes this signature. + signature with syntax like the following: + someClass.SomeMethod.Overloads[str, int]("Foo", 123) + + + + + Gets the overload dictionary for the logical function. These overloads + are never bound to an instance. + + + + + Returns the instance used for binding. This differs on module functions implemented + using instance methods so the built-in functions there don't expose the instance. + + + + + A custom built-in function which supports indexing + + + + + Use indexing on generic methods to provide a new reflected method with targets bound with + the supplied type arguments. + + + + + The unbound representation of an event property + + + + + BoundEvent is the object that gets returned when the user gets an event object. An + BoundEvent tracks where the event was received from and is used to verify we get + a proper add when dealing w/ statics events. + + + + + Represents a ReflectedProperty created for an extension method. Logically the property is an + instance property but the method implementing it is static. + + + + + Base class for properties backed by methods. These include our slot properties, + indexers, and normal properties. This class provides the storage of these as well + as the storage of our optimized getter/setter methods, documentation for the property, + etc... + + + + + Convenience function for users to call directly + + + + + This function can be used to set a field on a value type without emitting a warning. Otherwise it is provided only to have symmetry with properties which have GetValue/SetValue for supporting explicitly implemented interfaces. + + Setting fields on value types usually warns because it can silently fail to update the value you expect. For example consider this example where Point is a value type with the public fields X and Y: + + arr = System.Array.CreateInstance(Point, 10) + arr[0].X = 42 + print arr[0].X + + prints 0. This is because reading the value from the array creates a copy of the value. Setting the value then mutates the copy and the array does not get updated. The same problem exists when accessing members of a class. + + + + + Provides access to non-default .NET indexers (aka properties w/ parameters). + + C# doesn't support these, but both COM and VB.NET do. The types dictionary + gets populated w/a ReflectedGetterSetter indexer which is a descriptor. Getting + the descriptor returns a bound indexer. The bound indexer supports indexing. + We support multiple indexer parameters via expandable tuples. + + + + + Convenience function for users to call directly + + + + + Convenience function for users to call directly + + + + + True if generating code for gets can result in more optimal accesses. + + + + + single finalizable instance used to track and deliver all the + callbacks for a single object that has been weakly referenced by + one or more references and proxies. The reference to this object + is held in objects that implement IWeakReferenceable. + + + + + Finalizable object used to hook up finalization calls for OldInstances. + + We create one of these each time an object w/ a finalizer gets created. The + only reference to this object is the instance so when that goes out of context + this does as well and this will get finalized. + + + + + Marks a method/field/property as being a wrapper descriptor. A wrapper desriptor + is a member defined on PythonType but is available both for type and other + instances of type. For example type.__bases__. + + + + diff --git a/Reference/IronPython/Net40/IronPython.dll b/Reference/IronPython/Net40/IronPython.dll new file mode 100644 index 000000000..b9c2399f1 Binary files /dev/null and b/Reference/IronPython/Net40/IronPython.dll differ diff --git a/Reference/IronPython/Net40/IronPython.xml b/Reference/IronPython/Net40/IronPython.xml new file mode 100644 index 000000000..fee08bd57 --- /dev/null +++ b/Reference/IronPython/Net40/IronPython.xml @@ -0,0 +1,7569 @@ + + + + IronPython + + + + + Creates a method frame for tracking purposes and enforces recursion + + + + + Removes the frames from generated code for when we're compiling the tracing delegate + which will track the frames it's self. + + + + + Returns true if the node can throw, false otherwise. Used to determine + whether or not we need to update the current dynamic stack info. + + + + + A temporary variable to track if the current line number has been emitted via the fault update block. + + For example consider: + + try: + raise Exception() + except Exception, e: + # do something here + raise + + At "do something here" we need to have already emitted the line number, when we re-raise we shouldn't add it + again. If we handled the exception then we should have set the bool back to false. + + We also sometimes directly check _lineNoUpdated to avoid creating this unless we have nested exceptions. + + + + + A temporary variable to track the current line number + + + + + Fake ScopeStatement for FunctionCode's to hold on to after we have deserialized pre-compiled code. + + + + + Gets or creates the FunctionCode object for this FunctionDefinition. + + + + + Gets the expression for updating the dynamic stack trace at runtime when an + exception is thrown. + + + + + Gets the expression for the actual updating of the line number for stack traces to be available + + + + + Wraps the body of a statement which should result in a frame being available during + exception handling. This ensures the line number is updated as the stack is unwound. + + + + + The variable used to hold out parents closure tuple in our local scope. + + + + + Gets the expression associated with the local CodeContext. If the function + doesn't have a local CodeContext then this is the global context. + + + + + True if this scope accesses a variable from an outer scope. + + + + + True if an inner scope is accessing a variable defined in this scope. + + + + + True if we are forcing the creation of a dictionary for storing locals. + + This occurs for calls to locals(), dir(), vars(), unqualified exec, and + from ... import *. + + + + + True if variables can be set in a late bound fashion that we don't + know about at code gen time - for example via from foo import *. + + This is tracked independently of the ContainsUnqualifiedExec/NeedsLocalsDictionary + + + + + Variables that are bound in an outer scope - but not a global scope + + + + + Variables that are bound to the global scope + + + + + Variables that are referred to from a nested scope and need to be + promoted to cells. + + + + + Provides a place holder for the expression which represents + a FunctionCode. For functions/classes this gets updated after + the AST has been generated because the FunctionCode needs to + know about the tree which gets generated. For modules we + immediately have the value because it always comes in as a parameter. + + + + + Reducible node so that re-writing for profiling does not occur until + after the script code has been completed and is ready to be compiled. + + Without this extra node profiling would force reduction of the node + and we wouldn't have setup our constant access correctly yet. + + + + + A global allocator that puts all of the globals into an array access. The array is an + array of PythonGlobal objects. We then just close over the array for any inner functions. + + Once compiled a RuntimeScriptCode is produced which is closed over the entire execution + environment. + + + + + Specifies the compilation mode which will be used during the AST transformation + + + + + Compilation will proceed in a manner in which the resulting AST can be serialized to disk. + + + + + Compilation will use a type and declare static fields for globals. The resulting type + is uncollectible and therefore extended use of this will cause memory leaks. + + + + + Compilation will use an array for globals. The resulting code will be fully collectible + and once all references are released will be collected. + + + + + Compilation will force all global accesses to do a full lookup. This will also happen for + any unbound local references. This is the slowest form of code generation and is only + used for exec/eval code where we can run against an arbitrary dictionary. + + + + + Implements globals which are backed by a static type, followed by an array if the static types' slots become full. The global + variables are stored in static fields on a type for fast access. The type also includes fields for constants and call sites + so they can be accessed much fasetr. + + We don't generate any code into the type though - DynamicMethod's are much faster for code gen then normal ref emit. + + + Implements globals which are backed by a static type, followed by an array if the static types' slots become full. The global + variables are stored in static fields on a type for fast access. The type also includes fields for constants and call sites + so they can be accessed much fasetr. + + We don't generate any code into the type though - DynamicMethod's are much faster for code gen then normal ref emit. + + + + Ensures the underlying array is long enough to accomodate the given index + The context storage type corresponding to the given index + + + Ensures the underlying array is long enough to accomodate the given index + The constant storage type corresponding to the given index + + + Ensures the underlying array is long enough to accomodate the given index + The global storage type corresponding to the given index + + + Ensures the underlying array is long enough to accomodate the given index + The site storage type corresponding to the given index + + + + Not used. + + + + + Not used. + + + + + PythonWalker class - The Python AST Walker (default result is true) + + + + + Not an actual node. We don't create this, but it's here for compatibility. + + + + + Interface used to mark objects which contain a dictionary of custom attributes that shadow + their existing attributes in a dynamic fashion. + + + + + Ensures that a non-null IDictionary instance is created for CustomAttributes and + returns it. + + + + + Meta-object which allows IPythonExpandable objects to behave like Python objects in their + ability to dynamically add and remove new or existing custom attributes, generally shadowing + existing built-in members. + + Getting: Member accesses first consult the object's CustomAttributes dictionary, then fall + through to the underlying object. + + Setting: Values can be bound to any member name, shadowing any existing attributes except + public non-PythonHidden fields and properties, which will bypass the dictionary. Thus, + it is possible for SetMember to fail, for example if the property is read-only or of + the wrong type. + + Deleting: Any member represented in the dictionary can be deleted, re-exposing the + underlying member if it exists. Any other deletions will fail. + + + + + Provides a way for the binder to provide a custom error message when lookup fails. Just + doing this for the time being until we get a more robust error return mechanism. + + + + + Provides a way for the binder to provide a custom error message when lookup fails. Just + doing this for the time being until we get a more robust error return mechanism. + + + + + Gets the PythonBinder associated with tihs CodeContext + + + + + Performs .NET member resolution. This looks within the given type and also + includes any extension members. Base classes and their extension members are + not searched. + + + + + Performs .NET member resolution. This looks within the given type and also + includes any extension members. Base classes and their extension members are + not searched. + + This version allows PythonType's for protected member resolution. It shouldn't + be called externally for other purposes. + + + + + Performs .NET member resolution. This looks the type and any base types + for members. It also searches for extension members in the type and any base types. + + + + + Gets the member names which are defined in this type and any extension members. + + This search does not include members in any subtypes or their extension members. + + + + + Gets the member names which are defined in the type and any subtypes. + + This search includes members in the type and any subtypes as well as extension + types of the type and its subtypes. + + + + + Creates the initial table of extension types. These are standard extension that we apply + to well known .NET types to make working with them better. Being added to this table does + not make a type a Python type though so that it's members are generally accessible w/o an + import clr and their type is not re-named. + + + + + Creates a table of standard .NET types which are also standard Python types. These types have a standard + set of extension types which are shared between all runtimes. + + + + + Event handler for when our domain manager has an assembly loaded by the user hosting the script + runtime. Here we can gather any information regarding extension methods. + + Currently DLR-style extension methods become immediately available w/o an explicit import step. + + + + + Provides a cache from Type/name -> PythonTypeSlot and also allows access to + all members (and remembering whether all members are cached). + + + + + Writes to a cache the result of a type lookup. Null values are allowed for the slots and they indicate that + the value does not exist. + + + + + Looks up a cached type slot for the specified member and type. This may return true and return a null slot - that indicates + that a cached result for a member which doesn't exist has been stored. Otherwise it returns true if a slot is found or + false if it is not. + + + + + Looks up a cached member group for the specified member and type. This may return true and return a null group - that indicates + that a cached result for a member which doesn't exist has been stored. Otherwise it returns true if a group is found or + false if it is not. + + + + + Checks to see if all members have been populated for the provided type. + + + + + Populates the type with all the provided members and marks the type + as being fully cached. + + The dictionary is used for the internal storage and should not be modified after + providing it to the cache. + + + + + Returns an enumerable object which provides access to all the members of the provided type. + + The caller must check that the type is fully cached and populate the cache if it isn't before + calling this method. + + + + + Implements a built-in module which is instanced per PythonContext. + + Implementers can subclass this type and then have a module which has efficient access + to internal state (this doesn't need to go through PythonContext.GetModuleState). These + modules can also declare module level globals which they'd like to provide efficient + access to by overloading GetGlobalVariableNames. When Initialize is called these + globals are provided and can be cached in the instance for fast global access. + + Just like normal static modules these modules are registered with the PythonModuleAttribute. + + + + + Initializes the module for it's first usage. By default this calls PerformModuleReload with the + the dictionary. + + The CodeContext for the module. + A list of globals which have optimize access. Contains at least all of the global variables reutrned by GetGlobalVariableNames. + + + + Gets a list of variable names which should have optimized storage (instances of PythonGlobal objects). + The module receives the global objects during the Initialize call and can hold onto them for + direct access to global members. + + + + + Called when the user attempts to reload() on your module and by the base class Initialize method. + + This provides an opportunity to allocate any per-module data which is not simply function definitions. + + A common usage here is to create exception objects which are allocated by the module using PythonExceptions.CreateSubType. + + + + + Provides access to the PythonContext which this module was created for. + + + + + Provides access to the CodeContext for the module. Returns null before Initialize() is called. + + + + + Copy on write constant dictionary storage used for dictionaries created with constant items. + + + + + Abstract base class for all PythonDictionary storage. + + Defined as a class instead of an interface for performance reasons. Also not + using IDictionary* for keeping a simple interface. + + Full locking is defined as being on the DictionaryStorage object it's self, + not an internal member. This enables subclasses to provide their own locking + aruond large operations and call lock free functions. + + + + + Adds items from this dictionary into the other dictionary + + + + + Provides fast access to the __path__ attribute if the dictionary storage supports caching it. + + + + + Provides fast access to the __package__ attribute if the dictionary storage supports caching it. + + + + + Provides fast access to the __builtins__ attribute if the dictionary storage supports caching it. + + + + + Provides fast access to the __name__ attribute if the dictionary storage supports caching it. + + + + + Provides fast access to the __import__ attribute if the dictionary storage supports caching it. + + + + + Provides more specific type information for Python dictionaries which are not strongly typed. + + This attribute can be applied to fields, parameters, proeprties, and return values. It can be + inspected to get type information about the types of the keys and values of the expected + dictionary or the returned dictionary. + + + + + Adapts an IDictionary[object, object] for use as a PythonDictionary used for + our debug frames. Also hides the special locals which start with $. + + + + + An interface that is implemented on DynamicMetaObjects. + + This allows objects to opt-into custom conversions when calling + COM APIs. The IronPython binders all call this interface before + doing any COM binding. + + + + + Captures and flows the state of executing code from the generated + Python code into the IronPython runtime. + + + + + Creates a new CodeContext which is backed by the specified Python dictionary. + + + + + Attempts to lookup the provided name in this scope or any outer scope. + + + + + Looks up a global variable. If the variable is not defined in the + global scope then built-ins is consulted. + + + + + Attempts to lookup the variable in the local scope. + + + + + Removes a variable from the local scope. + + + + + Sets a variable in the local scope. + + + + + Gets a variable from the global scope. + + + + + Sets a variable in the global scope. + + + + + Removes a variable from the global scope. + + + + + Returns the dictionary associated with __builtins__ if one is + set or null if it's not available. If __builtins__ is a module + the module's dictionary is returned. + + + + + Gets the module state for top-level code. + + + + + Gets the DLR scope object that corresponds to the global variables of this context. + + + + + Gets the PythonContext which created the CodeContext. + + + + + Gets the dictionary for the global variables from the ModuleContext. + + + + + True if this global context should display CLR members on shared types (for example .ToString on int/bool/etc...) + + False if these attributes should be hidden. + + + + + Gets the dictionary used for storage of local variables. + + + + + Marks a type so that IronPython will not expose the IEnumerable interface out as + __iter__ + + + + + ArgBuilder which provides the CodeContext parameter to a method. + + + + + Small reducable node which just fetches the value from a ClosureCell + object. Like w/ global variables the compiler recognizes these on + sets and turns them into assignments on the python global object. + + + + + Creates the storage for the closure cell. If this is a closure over a parameter it + captures the initial incoming parameter value. + + + + + Reduces the closure cell to a read of the value stored in the cell. + + + + + Assigns a value to the closure cell. + + + + + Removes the current value from the closure cell. + + + + + Gets the expression which points at the closure cell. + + + + + The original expression for the incoming parameter if this is a parameter closure. Otherwise + the value is null. + + + + + Gets the PythonVariable for which this closure expression was created. + + + + + Tracking for variables lifted into closure objects. Used to store information in a function + about the outer variables it accesses. + + + + + When finding a yield return or yield break, this rewriter flattens out + containing blocks, scopes, and expressions with stack state. All + scopes encountered have their variables promoted to the generator's + closure, so they survive yields. + + + + + Spills the right side into a temp, and replaces it with its temp. + Returns the expression that initializes the temp. + + + + + Makes an assignment to this variable. Pushes the assignment as far + into the right side as possible, to allow jumps into it. + + + + + Accesses the property of a tuple. The node can be created first and then the tuple and index + type can be filled in before the tree is actually generated. This enables creation of these + nodes before the tuple type is actually known. + + + + + Represents code which can be lazily compiled. + + The code is created in an AST which provides the Expression of T and + whether or not the code should be interpreted. For non-pre compiled + scenarios the code will not be compiled until the 1st time it is run. + + For pre-compiled scenarios the code is IExpressionSerializable and will + turn into a normal pre-compiled method. + + + + + Marks a type so that IronPython will not expose types which have GetMemberNames + as having a __dir__ method. + + Also suppresses __dir__ on something which implements IDynamicMetaObjectProvider + but is not an IPythonObject. + + + + + Marks a type so that IronPython will not expose the ICollection interface out as + __len__. + + + + + Marks a type so that IronPython will not expose the IDisposable interface out as + __enter__ and __exit__ methods of a context manager. + + + + + Marks a type so that IronPython will not expose the IEnumerable interface out as + __contains__ + + + + + Singleton used for dictionaries which contain no items. + + + + + Represents the set of extension methods which are loaded into a module. + + This set is immutable (as far the external viewer is considered). When a + new extension method set is loaded into a module we create a new ExtensionMethodsSet object. + + Multiple modules which have the same set of extension methods use the same set. + + + + + Returns all of the extension methods with the given name. + + + + + Returns all of the extension methods which are applicable for the given type. + + + + + Tracks the extension types that are loaded for a given assembly. + + We can have either types, namespaces, or a full assembly added as a reference. + + When the user just adds types we just add them to the type hash set. + + When the user adds namespaces we add them to the namespaces hashset. On the + next lookup we'll lazily load the types from that namespace and put them in Types. + + When the user adds assemblies we set the value to the NotYetLoadedButFullAssembly + value. The next load request will load the types from that namespace and put them + in Types. When we do that we'll mark the assembly as FullyLoaded so we don't + have to go through that again if the user adds a namespace. + + + + + Return a copy of this tuple's data array. + + + + + ModuleDictionaryStorage for a built-in module which is bound to a specific instance. + + These modules don't need to use PythonContext.GetModuleState() for storage and therefore + can provide efficient access to internal variables. They can also cache PythonGlobal + objects and provide efficient access to module globals. + + To the end user these modules appear just like any other module. These modules are + implemented by subclassing the BuiltinPythonModule class. + + + + + Enables lazy initialization of module dictionaries. + + + + + Gets all of the extra names and values stored in the dictionary. + + + + + Attemps to sets a value in the extra keys. Returns true if the value is set, false if + the value is not an extra key. + + + + + Attempts to get a value from the extra keys. Returns true if the value is an extra + key and has a value. False if it is not an extra key or doesn't have a value. + + + + + Attempts to remove the key. Returns true if the key is removed, false + if the key was not removed, or null if the key is not an extra key. + + + + + A TypeSlot is an item that gets stored in a type's dictionary. Slots provide an + opportunity to customize access at runtime when a value is get or set from a dictionary. + + + + + Gets the value stored in the slot for the given instance binding it to an instance if one is provided and + the slot binds to instances. + + + + + Sets the value of the slot for the given instance. + + true if the value was set, false if it can't be set + + + + Deletes the value stored in the slot from the instance. + + true if the value was deleted, false if it can't be deleted + + + + Gets an expression which is used for accessing this slot. If the slot lookup fails the error expression + is used again. + + The default implementation just calls the TryGetValue method. Subtypes of PythonTypeSlot can override + this and provide a more optimal implementation. + + + + + True if generating code for gets can result in more optimal accesses. + + + + + True if TryGetValue will always succeed, false if it may fail. + + This is used to optimize away error generation code. + + + + + Defines the internal interface used for accessing weak references and adding finalizers + to user-defined types. + + + + + Gets the current WeakRefTracker for an object that can be used to + append additional weak references. + + + + + Attempts to set the WeakRefTracker for an object. Used on the first + addition of a weak ref tracker to an object. If the object doesn't + support adding weak references then it returns false. + + + + + Sets a WeakRefTracker on an object for the purposes of supporting finalization. + All user types (new-style and old-style) support finalization even if they don't + support weak-references, and therefore this function always succeeds. Note the + slot used to store the WeakRefTracker is still shared between SetWeakRef and + SetFinalizer if a type supports both. + + + + + + Provides a list of all the members of an instance. ie. all the keys in the + dictionary of the object. Note that it can contain objects that are not strings. + + Such keys can be added in IronPython using syntax like: + obj.__dict__[100] = someOtherObject + + This Python specific version also supports filtering based upon the show cls + flag by flowing in the code context. + + + + + Validates that the current self object is usable for this method. + + + + + Marks a class as being hidden from the Python hierarchy. This is applied to the base class + and then all derived types will not see the base class in their hierarchy and will not be + able to access members declaredo on the base class. + + + + + Provides more specific type information for Python lists which are not strongly typed. + + This attribute can be applied to fields, parameters, proeprties, and return values. It can be + inspected to get type information about the types of the values of the expected + list or the returned list. + + + + + Captures the globals and other state of module code. + + + + + Creates a new ModuleContext which is backed by the specified dictionary. + + + + + Creates a new ModuleContext for the specified module. + + + + + Initializes __builtins__ for the module scope. + + + + + Gets the dictionary used for the global variables in the module + + + + + Gets the language context which created this module. + + + + + Gets the DLR Scope object which is associated with the modules dictionary. + + + + + Gets the global CodeContext object which is used for execution of top-level code. + + + + + Gets the module object which this code is executing in. + + This module may or may not be published in sys.modules. For user defined + code typically the module gets published at the start of execution. But if + this ModuleContext is attached to a Scope, or if we've just created a new + module context for executing code it will not be in sys.modules. + + + + + Gets the features that code has been compiled with in the module. + + + + + Gets or sets whether code running in this context should display + CLR members (for example .ToString on objects). + + + + + Cached global value. Created and maintained on a per-language basis. Default + implementation returns a singleton which indicates caching is not occuring. + + + + + Creates a new ModuleGlobalCache with the specified value. + + + + + Event handler for when the value has changed. Language implementors should call this when + the cached value is invalidated. + + + + + True if the ModuleGlobalCache is participating in a caching strategy. + + + + + True if there is currently a value associated with this global variable. False if + it is currently unassigned. + + + + + Gets or sets the current cached value + + + + + Enable true division (1/2 == .5) + + + + + Indicates that .NET methods such as .ToString should be available on Python objects. + + + + + Indicates that the module should be generated in an optimal form which will result + in it being uncollectable. + + + + + Indicates when the module should be executed immedatiately upon creation. + + + + + Enable usage of the with statement + + + + + Enable absolute imports + + + + + Indiciates that __builtins__ should not be set in the module + + + + + Indiciates that when the module is initialized it should set __builtins__ to the __builtin__ module + instead of the __builtin__ dictionary. + + + + + Marks code as being created for exec, eval. Code generated this way will + be capable of running against different scopes and will do lookups at runtime + for free global variables. + + + + + Indiciates that the first line of code should be skipped. + + + + + Enable usage of print as a function for better compatibility with Python 3.0. + + + + + Forces the code to be interpreted rather than compiled + + + + + String Literals should be parsed as Unicode strings + + + + + Include comments in the parse tree + + + + + Generated code should support light exceptions + + + + + Manages the acquisition of profiling data for a single ScriptRuntime + + + + + Get the unique Profiler instance for this ScriptRuntime + + + + + Given a MethodBase, return an index into the array of perf data. Treat each + CLR method as unique. + + + + + Given the unique name of something we're profiling, return an index into the array of perf data. + + + + + Add a new profiler entry. Not all names are unique. + + + + + Gets the current summary of profile data + + + + + Resets the current summary of profile data back to zero + + + + + Adds profiling calls to a Python method. + Calculates both the time spent only in this method + + + + + Wraps a call to a MethodInfo with profiling capture for that MethodInfo + + + + + Encapsulates profiler data to return to clients + + + + + Marks that this built-in method should be treated as external by the profiler. + When placed on a call emitted into a Python method, all the time spent in this + call will still show up in its parent's inclusive time, but will not be + part of its exclusive time. + + + + + Gets the closure tuple from our parent context. + + + + + PythonWalkerNonRecursive class - The Python AST Walker (default result is false) + + + + + Pulls the closure tuple from our function/generator which is flowed into each function call. + + + + + Returns an expression which creates the function object. + + + + + Creates the LambdaExpression which is the actual function body. + + + + + Creates the LambdaExpression which implements the body of the function. + + The functions signature is either "object Function(PythonFunction, ...)" + where there is one object parameter for each user defined parameter or + object Function(PythonFunction, object[]) for functions which take more + than PythonCallTargets.MaxArgs arguments. + + + + + Determines delegate type for the Python function + + + + + Scope for the comprehension. Because scopes are usually statements and comprehensions are expressions + this doesn't actually show up in the AST hierarchy and instead hangs off the comprehension expression. + + + + + Provides globals for when we need to lookup into a dictionary for each global access. + + This is the slowest form of globals and is only used when we need to run against an + arbitrary dictionary given to us by a user. + + + + + Provides a wrapper around "dynamic" expressions which we've opened coded (for optimized code generation). + + This lets us recognize both normal Dynamic and our own Dynamic expressions and apply the combo binder on them. + + + + + A ScriptCode which can be saved to disk. We only create this when called via + the clr.CompileModules API. This ScriptCode does not support running. + + + + + Parameter base class + + + + + Position of the parameter: 0-based index + + + + + Parameter name + + + + + Top-level ast for all Python code. Typically represents a module but could also + be exec or eval code. + + + + + Creates a new PythonAst without a body. ParsingFinished should be called afterwards to set + the body. + + + + + Called when parsing is complete, the body is built, the line mapping and language features are known. + + This is used in conjunction with the constructor which does not take a body. It enables creating + the outer most PythonAst first so that nodes can always have a global parent. This lets an un-bound + tree to still provide it's line information immediately after parsing. When we set the location + of each node during construction we also set the global parent. When we name bind the global + parent gets replaced with the real parent ScopeStatement. + + a mapping of where each line begins + The body of code + The language features which were set during parsing. + + + + Binds an AST and makes it capable of being reduced and compiled. Before calling Bind an AST cannot successfully + be reduced. + + + + + Creates a variable at the global level. Called for known globals (e.g. __name__), + for variables explicitly declared global by the user, and names accessed + but not defined in the lexical scope. + + + + + Reduces the PythonAst to a LambdaExpression of type Type. + + + + + Returns a ScriptCode object for this PythonAst. The ScriptCode object + can then be used to execute the code against it's closed over scope or + to execute it against a different scope. + + + + + Rewrites the tree for performing lookups against globals instead of being bound + against the optimized scope. This is used if the user compiles optimied code and then + runs it against a different scope. + + + + + True division is enabled in this AST. + + + + + True if the with statement is enabled in this AST. + + + + + True if absolute imports are enabled + + + + + True if this is on-disk code which we don't really have an AST for. + + + + + Represents a reference to a name. A PythonReference is created for each name + referred to in a scope (global, class, or function). + + + + + True if the user provided a step parameter (either providing an explicit parameter + or providing an empty step parameter) false if only start and stop were provided. + + + + + The statements under the try-block. + + + + + Array of except (catch) blocks associated with this try. NULL if there are no except blocks. + + + + + The body of the optional Else block for this try. NULL if there is no Else block. + + + + + The body of the optional finally associated with this try. NULL if there is no finally block. + + + + + Transform multiple python except handlers for a try block into a single catch body. + + The variable for the exception in the catch block. + Null if there are no except handlers. Else the statement to go inside the catch handler + + + + Surrounds the body of an except block w/ the appropriate code for maintaining the traceback. + + + + + True iff there is a path in control flow graph on which the variable is used before initialized (assigned or deleted). + + + + + True iff the variable is referred to from the inner scope. + + + + + Local variable. + + Local variables can be referenced from nested lambdas + + + + + Parameter to a LambdaExpression + + Like locals, they can be referenced from nested lambdas + + + + + Global variable + + Should only appear in global (top level) lambda. + + + + + WithStatement is translated to the DLR AST equivalent to + the following Python code snippet (from with statement spec): + + mgr = (EXPR) + exit = mgr.__exit__ # Not calling it yet + value = mgr.__enter__() + exc = True + try: + VAR = value # Only if "as VAR" is present + BLOCK + except: + # The exceptional case is handled here + exc = False + if not exit(*sys.exc_info()): + raise + # The exception is swallowed if exit() returns true + finally: + # The normal and non-local-goto cases are handled here + if exc: + exit(None, None, None) + + + + + + A ScriptCode which has been loaded from an assembly which is saved on disk. + + + + + Creates a fake PythonAst object which is represenative of the on-disk script code. + + + + + Base class for all of our fast get delegates. This holds onto the + delegate and provides the Update function. + + + + + Updates the call site when the current rule is no longer applicable. + + + + + Base class for all of our fast set delegates. This holds onto the + delegate and provides the Update and Optimize functions. + + + + + Updates the call site when the current rule is no longer applicable. + + + + + Provides cached global variable for modules to enable optimized access to + module globals. Both the module global value and the cached value can be held + onto and the cached value can be invalidated by the providing LanguageContext. + + The cached value is provided by the LanguageContext.GetModuleCache API. + + + + + Small reducable node which just fetches the value from a PythonGlobal + object. The compiler recognizes these on sets and turns them into + assignments on the python global object. + + + + + Represents a script code which can be dynamically bound to execute against + arbitrary Scope objects. This is used for code when the user runs against + a particular scope as well as for exec and eval code as well. It is also + used when tracing is enabled. + + + + + Represents a script code which can be consumed at runtime as-is. This code has + no external dependencies and is closed over its scope. + + + + + Helper class for implementing the Python class. + + This is exposed as a service through PythonEngine and the helper class + uses this service to get the correct remoting semantics. + + + + + Returns an ObjectHandle to a delegate of type Action[Action] which calls the current + command dispatcher. + + + + + Marks that the return value of a function might include NotImplemented. + + This is added to an operator method to ensure that all necessary methods are called + if one cannot guarantee that it can perform the comparison. + + + + + Provides support for emitting warnings when built in methods are invoked at runtime. + + + + + Backwards compatible Convert for the old sites that need to flow CodeContext + + + + + Creates a new InvokeBinder which will call with positional splatting. + + The signature of the target site should be object(function), object[], retType + + + + + + + Creates a new InvokeBinder which will call with positional and keyword splatting. + + The signature of the target site should be object(function), object[], dictionary, retType + + + + + Fallback action for performing an invoke from Python. We translate the + CallSignature which supports splatting position and keyword args into + their expanded form. + + + + + Gets the PythonContext which the CallSiteBinder is associated with. + + + + + Fallback action for performing a new() on a foreign IDynamicMetaObjectProvider. used + when call falls back. + + + + + Python's Invoke is a non-standard action. Here we first try to bind through a Python + internal interface (IPythonInvokable) which supports CallSigantures. If that fails + and we have an IDO then we translate to the DLR protocol through a nested dynamic site - + this includes unsplatting any keyword / position arguments. Finally if it's just a plain + old .NET type we use the default binder which supports CallSignatures. + + + + + Interface used to mark objects as being invokable from Python. These objects support + calling with splatted positional and keyword arguments. + + + + + Provides binding logic which is implemented to follow various Python protocols. This includes + things such as calling __call__ to perform calls, calling __nonzero__/__len__ to convert to + bool, calling __add__/__radd__ to do addition, etc... + + This logic gets shared between both the IDynamicMetaObjectProvider implementation for Python objects as well + as the Python sites. This ensures the logic we follow for our builtin types and user defined + types is identical and properly conforming to the various protocols. + + + + + Gets a MetaObject which converts the provided object to a bool using __nonzero__ or __len__ + protocol methods. This code is shared between both our fallback for a site and our MetaObject + for user defined objects. + + + + + Used for conversions to bool + + + + + Creates a rule for the contains operator. This is exposed via "x in y" in + IronPython. It is implemented by calling the __contains__ method on x and + passing in y. + + If a type doesn't define __contains__ but does define __getitem__ then __getitem__ is + called repeatedly in order to see if the object is there. + + For normal .NET enumerables we'll walk the iterator and see if it's present. + + + + + Helper to handle a comparison operator call. Checks to see if the call can + return NotImplemented and allows the caller to modify the expression that + is ultimately returned (e.g. to turn __cmp__ into a bool after a comparison) + + + + + calls __coerce__ for old-style classes and performs the operation if the coercion is successful. + + + + + Makes the comparison rule which returns an int (-1, 0, 1). TODO: Better name? + + + + + Python has three protocols for slicing: + Simple Slicing x[i:j] + Extended slicing x[i,j,k,...] + Long Slice x[start:stop:step] + + The first maps to __*slice__ (get, set, and del). + This takes indexes - i, j - which specify the range of elements to be + returned. In the slice variants both i, j must be numeric data types. + The 2nd and 3rd are both __*item__. + This receives a single index which is either a Tuple or a Slice object (which + encapsulates the start, stop, and step values) + + This is in addition to a simple indexing x[y]. + + For simple slicing and long slicing Python generates Operators.*Slice. For + the extended slicing and simple indexing Python generates a Operators.*Item + action. + + Extended slicing maps to the normal .NET multi-parameter input. + + So our job here is to first determine if we're to call a __*slice__ method or + a __*item__ method. + + + + + Helper to convert all of the arguments to their known types. + + + + + Gets the arguments that need to be provided to __*item__ when we need to pass a slice object. + + + + + Helper to get the symbols for __*item__ and __*slice__ based upon if we're doing + a get/set/delete and the minimum number of arguments required for each of those. + + + + + Checks if a coercion check should be performed. We perform coercion under the following + situations: + 1. Old instances performing a binary operator (excluding rich comparisons) + 2. User-defined new instances calling __cmp__ but only if we wouldn't dispatch to a built-in __coerce__ on the parent type + + This matches the behavior of CPython. + + + + + + Produces an error message for the provided message and type names. The error message should contain + string formatting characters ({0}, {1}, etc...) for each of the type names. + + + + + Delegate for finishing the comparison. This takes in a condition and a return value and needs to update the ConditionalBuilder + with the appropriate resulting body. The condition may be null. + + + + + Base class for calling indexers. We have two subclasses that target built-in functions and user defined callable objects. + + The Callable objects get handed off to ItemBuilder's which then call them with the appropriate arguments. + + + + + Creates a new CallableObject. If BuiltinFunction is available we'll create a BuiltinCallable otherwise + we create a SlotCallable. + + + + + Gets the arguments in a form that should be used for extended slicing. + + Python defines that multiple tuple arguments received (x[1,2,3]) get + packed into a Tuple. For most .NET methods we just want to expand + this into the multiple index arguments. For slots and old-instances + we want to pass in the tuple + + + + + Adds the target of the call to the rule. + + + + + Subclass of Callable for a built-in function. This calls a .NET method performing + the appropriate bindings. + + + + + Callable to a user-defined callable object. This could be a Python function, + a class defining __call__, etc... + + + + + Base class for building a __*item__ or __*slice__ call. + + + + + Derived IndexBuilder for calling __*slice__ methods + + + + + Derived IndexBuilder for calling __*item__ methods. + + + + + Common helpers used by the various binding logic. + + + + + Tries to get the BuiltinFunction for the given name on the type of the provided MetaObject. + + Succeeds if the MetaObject is a BuiltinFunction or BuiltinMethodDescriptor. + + + + + Gets the best CallSignature from a MetaAction. + + The MetaAction should be either a Python InvokeBinder, or a DLR InvokeAction or + CreateAction. For Python we can use a full-fidelity + + + + + + + Transforms an invoke member into a Python GetMember/Invoke. The caller should + verify that the given attribute is not resolved against a normal .NET class + before calling this. If it is a normal .NET member then a fallback InvokeMember + is preferred. + + + + + Determines if the type associated with the first MetaObject is a subclass of the + type associated with the second MetaObject. + + + + + Adds a try/finally which enforces recursion limits around the target method. + + + + + Helper to do fallback for Invoke's so we can handle both StandardAction and Python's + InvokeBinder. + + + + + Converts arguments into a form which can be used for COM interop. + + The argument is only converted if we have an IronPython specific + conversion when calling COM methods. + + + + + Converts a single argument into a form which can be used for COM + interop. + + The argument is only converted if we have an IronPython specific + conversion when calling COM methods. + + + + + Builds up a series of conditionals when the False clause isn't yet known. We can + keep appending conditions and if true's. Each subsequent true branch becomes the + false branch of the previous condition and body. Finally a non-conditional terminating + branch must be added. + + + + + Adds a new conditional and body. The first call this becomes the top-level + conditional, subsequent calls will have it added as false statement of the + previous conditional. + + + + + Adds a new condition to the last added body / condition. + + + + + Adds the non-conditional terminating node. + + + + + Gets the resulting meta object for the full body. FinishCondition + must have been called. + + + + + Adds a variable which will be scoped at the level of the final expression. + + + + + Returns true if no conditions have been added + + + + + Returns true if a final, non-conditional, body has been added. + + + + + Creates a target which creates a new dynamic method which contains a single + dynamic site that invokes the callable object. + + TODO: This should be specialized for each callable object + + + + + Various helpers related to calling Python __*__ conversion methods + + + + + Helper for falling back - if we have a base object fallback to it first (which can + then fallback to the calling site), otherwise fallback to the calling site. + + + + + Helper for falling back - if we have a base object fallback to it first (which can + then fallback to the calling site), otherwise fallback to the calling site. + + + + + Checks to see if this type has __getattribute__ that overrides all other attribute lookup. + + This is more complex then it needs to be. The problem is that when we have a + mixed new-style/old-style class we have a weird __getattribute__ defined. When + we always dispatch through rules instead of PythonTypes it should be easy to remove + this. + + + + + Looks up the associated PythonTypeSlot from the object. Indicates if the result + came from a standard .NET type in which case we will fallback to the sites binder. + + + + + Helper for falling back - if we have a base object fallback to it first (which can + then fallback to the calling site), otherwise fallback to the calling site. + + + + + Helper for falling back - if we have a base object fallback to it first (which can + then fallback to the calling site), otherwise fallback to the calling site. + + + + + Provides the lookup logic for resolving a Python object. Subclasses + provide the actual logic for producing the binding result. Currently + there are two forms of the binding result: one is the DynamicMetaObject + form used for non-optimized bindings. The other is the Func of CallSite, + object, CodeContext, object form which is used for fast binding and + pre-compiled rules. + + + + + GetBinder which produces a DynamicMetaObject. This binder always + successfully produces a DynamicMetaObject which can perform the requested get. + + + + + Makes a rule which calls a user-defined __getattribute__ function and falls back to __getattr__ if that + raises an AttributeError. + + slot is the __getattribute__ method to be called. + + + + + Checks a range of the MRO to perform old-style class lookups if any old-style classes + are present. We will call this twice to produce a search before a slot and after + a slot. + + + + + Helper for falling back - if we have a base object fallback to it first (which can + then fallback to the calling site), otherwise fallback to the calling site. + + + + + Custom dynamic site kinds for simple sites that just take a fixed set of parameters. + + + + + Unary operator. + + Gets various documentation about the object returned as a string + + + + + Unary operator. + + Gets information about the type of parameters, returned as a string. + + + + + Unary operator. + + Checks whether the object is callable or not, returns true if it is. + + + + + Binary operator. + + Checks to see if the instance contains another object. Returns true or false. + + + + + Unary operator. + + Returns the number of items stored in the object. + + + + + Binary operator. + + Compares two instances returning an integer indicating the relationship between them. May + throw if the object types are uncomparable. + + + + + Binary operator. + + Returns both the dividend and quotioent of x / y. + + + + + Unary operator. + + Get the absolute value of the instance. + + + + + Unary operator. + + Gets the positive value of the instance. + + + + + Unary operator. + + Negates the instance and return the new value. + + + + + Unary operator. + + Returns the ones complement of the instance. + + + + + Unary operator. + + Boolean negation + + + + + Unary operator. + + Negation, returns object + + + + + Get enumerator for iteration binder. Returns a KeyValuePair<IEnumerator, IDisposable> + + The IEnumerator is used for iteration. The IDisposable is provided if the object was an + IEnumerable or IEnumerable<T> and is a disposable object. + + + + Operator for performing add + + + Operator for performing sub + + + Operator for performing pow + + + Operator for performing mul + + + Operator for performing floordiv + + + Operator for performing div + + + Operator for performing truediv + + + Operator for performing mod + + + Operator for performing lshift + + + Operator for performing rshift + + + Operator for performing and + + + Operator for performing or + + + Operator for performing xor + + + Operator for performing lt + + + Operator for performing gt + + + Operator for performing le + + + Operator for performing ge + + + Operator for performing eq + + + Operator for performing ne + + + Operator for performing lg + + + Operator for performing in-place add + + + Operator for performing in-place sub + + + Operator for performing in-place pow + + + Operator for performing in-place mul + + + Operator for performing in-place floordiv + + + Operator for performing in-place div + + + Operator for performing in-place truediv + + + Operator for performing in-place mod + + + Operator for performing in-place lshift + + + Operator for performing in-place rshift + + + Operator for performing in-place and + + + Operator for performing in-place or + + + Operator for performing in-place xor + + + Operator for performing reverse add + + + Operator for performing reverse sub + + + Operator for performing reverse pow + + + Operator for performing reverse mul + + + Operator for performing reverse floordiv + + + Operator for performing reverse div + + + Operator for performing reverse truediv + + + Operator for performing reverse mod + + + Operator for performing reverse lshift + + + Operator for performing reverse rshift + + + Operator for performing reverse and + + + Operator for performing reverse or + + + Operator for performing reverse xor + + + Operator for performing reverse divmod + + + + Provides an abstraction for calling something which might be a builtin function or + might be some arbitrary user defined slot. If the object is a builtin function the + call will go directly to the underlying .NET method. If the object is an arbitrary + callable object we will setup a nested dynamic site for performing the additional + dispatch. + + TODO: We could probably do a specific binding to the object if it's another IDyanmicObject. + + + + + Combines two methods, which came from two different binary types, selecting the method which has the best + set of conversions (the conversions which result in the least narrowing). + + + + + Tries to get a MethodBinder associated with the slot for the specified type. + + If a method is found the binder is set and true is returned. + If nothing is found binder is null and true is returned. + If something other than a method is found false is returned. + + TODO: Remove rop + + + + + bytearray(string, encoding[, errors]) -> bytearray + bytearray(iterable) -> bytearray + + Construct a mutable bytearray object from: + - an iterable yielding values in range(256), including: + + a list of integer values + + a bytes, bytearray, buffer, or array object + - a text string encoded using the specified encoding + + bytearray([int]) -> bytearray + + Construct a zero-ititialized bytearray of the specified length. + (default=0) + + + + + return true if self is a titlecased string and there is at least one + character in self; also, uppercase characters may only follow uncased + characters (e.g. whitespace) and lowercase characters only cased ones. + return false otherwise. + + + + + Return a string which is the concatenation of the strings + in the sequence seq. The separator between elements is the + string providing this method + + + + + return true if self is a titlecased string and there is at least one + character in self; also, uppercase characters may only follow uncased + characters (e.g. whitespace) and lowercase characters only cased ones. + return false otherwise. + + + + + Return a string which is the concatenation of the strings + in the sequence seq. The separator between elements is the + string providing this method + + + + + Returns a copy of the internal byte array. + + + System.Byte[] + + + + + This method returns the underlying byte array directly. + It should be used sparingly! + + + System.Byte[] + + + + + Marks a method as being a class method. The PythonType which was used to access + the method will then be passed as the first argument. + + + + + this class contains objecs and static methods used for + .NET/CLS interop with Python. + + + + + Gets the current ScriptDomainManager that IronPython is loaded into. The + ScriptDomainManager can then be used to work with the language portion of the + DLR hosting APIs. + + + + + Use(name) -> module + + Attempts to load the specified module searching all languages in the loaded ScriptRuntime. + + + + + Use(path, language) -> module + + Attempts to load the specified module belonging to a specific language loaded into the + current ScriptRuntime. + + + + + SetCommandDispatcher(commandDispatcher) + + Sets the current command dispatcher for the Python command line. + + The command dispatcher will be called with a delegate to be executed. The command dispatcher + should invoke the target delegate in the desired context. + + A common use for this is to enable running all REPL commands on the UI thread while the REPL + continues to run on a non-UI thread. + + + + + LoadTypeLibrary(rcw) -> type lib desc + + Gets an ITypeLib object from OLE Automation compatible RCW , + reads definitions of CoClass'es and Enum's from this library + and creates an object that allows to instantiate coclasses + and get actual values for the enums. + + + + + LoadTypeLibrary(guid) -> type lib desc + + Reads the latest registered type library for the corresponding GUID, + reads definitions of CoClass'es and Enum's from this library + and creates a IDynamicMetaObjectProvider that allows to instantiate coclasses + and get actual values for the enums. + + + + + AddReferenceToTypeLibrary(rcw) -> None + + Makes the type lib desc available for importing. See also LoadTypeLibrary. + + + + + AddReferenceToTypeLibrary(guid) -> None + + Makes the type lib desc available for importing. See also LoadTypeLibrary. + + + + + Gets the CLR Type object from a given Python type object. + + + + + Gets the Python type object from a given CLR Type object. + + + + + OBSOLETE: Gets the Python type object from a given CLR Type object. + + Use clr.GetPythonType instead. + + + + + accepts(*types) -> ArgChecker + + Decorator that returns a new callable object which will validate the arguments are of the specified types. + + + + + + + returns(type) -> ReturnChecker + + Returns a new callable object which will validate the return type is of the specified type. + + + + + returns the result of dir(o) as-if "import clr" has not been performed. + + + + + Returns the result of dir(o) as-if "import clr" has been performed. + + + + + Attempts to convert the provided object to the specified type. Conversions that + will be attempted include standard Python conversions as well as .NET implicit + and explicit conversions. + + If the conversion cannot be performed a TypeError will be raised. + + + + + Provides a helper for compiling a group of modules into a single assembly. The assembly can later be + reloaded using the clr.AddReference API. + + + + + clr.CompileSubclassTypes(assemblyName, *typeDescription) + + Provides a helper for creating an assembly which contains pre-generated .NET + base types for new-style types. + + This assembly can then be AddReferenced or put sys.prefix\DLLs and the cached + types will be used instead of generating the types at runtime. + + This function takes the name of the assembly to save to and then an arbitrary + number of parameters describing the types to be created. Each of those + parameter can either be a plain type or a sequence of base types. + + clr.CompileSubclassTypes(object) -> create a base type for object + clr.CompileSubclassTypes(object, str, System.Collections.ArrayList) -> create + base types for both object and ArrayList. + + clr.CompileSubclassTypes(object, (object, IComparable)) -> create base types for + object and an object which implements IComparable. + + + + + + clr.GetSubclassedTypes() -> tuple + + Returns a tuple of information about the types which have been subclassed. + + This tuple can be passed to clr.CompileSubclassTypes to cache these + types on disk such as: + + clr.CompileSubclassTypes('assembly', *clr.GetSubclassedTypes()) + + + + + Goes through the list of files identifying the relationship between packages + and subpackages. Returns a dictionary with all of the package filenames (minus __init__.py) + mapping to their full name. For example given a structure: + + C:\ + someDir\ + package\ + __init__.py + a.py + b\ + __init.py + c.py + + Returns: + {r'C:\somedir\package' : 'package', r'C:\somedir\package\b', 'package.b'} + + This can then be used for calculating the full module name of individual files + and packages. For example a's full name is "package.a" and c's full name is + "package.b.c". + + + + + Returns a list of profile data. The values are tuples of Profiler.Data objects + + All times are expressed in the same unit of measure as DateTime.Ticks + + + + + Resets all profiler counters back to zero + + + + + Enable or disable profiling for the current ScriptEngine. This will only affect code + that is compiled after the setting is changed; previously-compiled code will retain + whatever setting was active when the code was originally compiled. + + The easiest way to recompile a module is to reload() it. + + + + + Serializes data using the .NET serialization formatter for complex + types. Returns a tuple identifying the serialization format and the serialized + data which can be fed back into clr.Deserialize. + + Current serialization formats include custom formats for primitive .NET + types which aren't already recognized as tuples. None is used to indicate + that the Binary .NET formatter is used. + + + + + Deserializes the result of a Serialize call. This can be used to perform serialization + for .NET types which are serializable. This method is the callable object provided + from __reduce_ex__ for .serializable .NET types. + + The first parameter indicates the serialization format and is the first tuple element + returned from the Serialize call. + + The second parameter is the serialized data. + + + + + Decorator for verifying the arguments to a function are of a specified type. + + + + + Returned value when using clr.accepts/ArgChecker. Validates the argument types and + then calls the original function. + + + + + Decorator for verifying the return type of functions. + + + + + Returned value when using clr.returns/ReturnChecker. Calls the original function and + validates the return type is of a specified type. + + + + + Provides a StreamContentProvider for a stream of content backed by a file on disk. + + + + + Wrapper class used when a user defined type (new-style or old-style) + defines __index__. We provide a conversion from all user defined + types to the Index type so they can be used for determing and method bind + time the most appropriate method to dispatch to. + + + + + New string formatter for 'str'.format(...) calls and support for the Formatter + library via the _formatter_parser / _formatter_field_name_split + methods. + + We parse this format: + + replacement_field = "{" field_name ["!" conversion] [":" format_spec] "}" + field_name = (identifier | integer) ("." attribute_name | "[" element_index "]")* + attribute_name = identifier + element_index = identifier + conversion = "r" | "s" + format_spec = any char, { must be balanced (for computed values), passed to __format__ method on object + + + + + Runs the formatting operation on the given format and keyword arguments + + + + + Gets the formatting information for the given format. This is a list of tuples. The tuples + include: + + text, field name, format spec, conversion + + + + + Parses a field name returning the argument name and an iterable + object which can be used to access the individual attribute + or element accesses. The iterator yields tuples of: + + bool (true if attribute, false if element index), attribute/index value + + + + + Parses the field name including attribute access or element indexing. + + + + + Parses the field name including attribute access or element indexing. + + + + + Converts accessors from our internal structure into a PythonTuple matching how CPython + exposes these + + + + + Parses an identifier and returns it + + + + + Base class used for parsing the format. Subclasss override Text/ReplacementField methods. Those + methods get called when they call Parse and then they can do the appropriate actions for the + format. + + + + + Gets an enumerable object for walking the parsed format. + + TODO: object array? struct? + + + + + Provides an enumerable of the parsed format. The elements of the tuple are: + the text preceding the format information + the field name + the format spec + the conversion + + + + + Handles {{ and }} within the string. Returns true if a double bracket + is found and yields the text + + + + + Parses the conversion character and returns it + + + + + Checks to see if we're at the end of the format. If there's no more characters left we report + the error, otherwise if we hit a } we return true to indicate parsing should stop. + + + + + Parses the format spec string and returns it. + + + + + Parses the field name and returns it. + + + + + Handles parsing the field name and the format spec and returns it. At the parse + level these are basically the same - field names just have more terminating characters. + + The most complex part of parsing them is they both allow nested braces and require + the braces are matched. Strangely though the braces need to be matched across the + combined field and format spec - not within each format. + + + + + Provides the built-in string formatter which is exposed to Python via the str.format API. + + + + + Inspects a format spec to see if it contains nested format specs which + we need to compute. If so runs another string formatter on the format + spec to compute those values. + + + + + Given the field name gets the object from our arguments running + any of the member/index accessors. + + + + + Applies the known built-in conversions to the object if a conversion is + specified. + + + + + Gets the initial object represented by the field name - e.g. the 0 or + keyword name. + + + + + Given the object value runs the accessors in the field name (if any) against the object. + + + + + Encodes all the information about the field name. + + + + + Encodes a single field accessor (.b or [number] or [str]) + + + + + For IList arguments: Marks that the argument is typed to accept a bytes or + bytearray object. This attribute disallows passing a Python list object and + auto-applying our generic conversion. It also enables conversion of a string to + a IList of byte in IronPython 2.6. + + For string arguments: Marks that the argument is typed to accept a bytes object + as well. (2.6 only) + + + + stored for copy_reg module, used for reduce protocol + + + stored for copy_reg module, used for reduce protocol + + + + Creates a new PythonContext not bound to Engine. + + + + + Checks to see if module state has the current value stored already. + + + + + Gets per-runtime state used by a module. The module should have a unique key for + each piece of state it needs to store. + + + + + Sets per-runtime state used by a module. The module should have a unique key for + each piece of state it needs to store. + + + + + Sets per-runtime state used by a module and returns the previous value. The module + should have a unique key for each piece of state it needs to store. + + + + + Sets per-runtime state used by a module and returns the previous value. The module + should have a unique key for each piece of state it needs to store. + + + + + Initializes the sys module on startup. Called both to load and reload sys + + + + + Reads one line keeping track of the # of bytes read + + + + + We use Assembly.LoadFile to load assemblies from a path specified by the script (in LoadAssemblyFromFileWithPath). + However, when the CLR loader tries to resolve any of assembly references, it will not be able to + find the dependencies, unless we can hook into the CLR loader. + + + + + Returns (and creates if necessary) the PythonService that is associated with this PythonContext. + + The PythonService is used for providing remoted convenience helpers for the DLR hosting APIs. + + + + + Gets the member names associated with the object + TODO: Move "GetMemberNames" functionality into MetaObject implementations + + + + + Gets a SiteLocalStorage when no call site is available. + + + + + Invokes the specified operation on the provided arguments and returns the new resulting value. + + operation is usually a value from StandardOperators (standard CLR/DLR operator) or + OperatorStrings (a Python specific operator) + + + + + Sets the current command dispatcher for the Python command line. The previous dispatcher + is returned. Null can be passed to remove the current command dispatcher. + + The command dispatcher will be called with a delegate to be executed. The command dispatcher + should invoke the target delegate in the desired context. + + A common use for this is to enable running all REPL commands on the UI thread while the REPL + continues to run on a non-UI thread. + + The ipy.exe REPL will call into PythonContext.DispatchCommand to dispatch each execution to + the correct thread. Other REPLs can do the same to support this functionality as well. + + + + + Dispatches the command to the current command dispatcher. If there is no current command + dispatcher the command is executed immediately on the current thread. + + + + + Gets a function which can be used for comparing two values. If cmp is not null + then the comparison will use the provided comparison function. Otherwise + it will use the normal Python semantics. + + If type is null then a generic comparison function is returned. If type is + not null a comparison function is returned that's used for just that type. + + + + + Performs a GC collection including the possibility of freeing weak data structures held onto by the Python runtime. + + + + + + Gets a PythonContext given a DynamicMetaObjectBinder. + + + + + Gets or sets the maximum depth of function calls. Equivalent to sys.getrecursionlimit + and sys.setrecursionlimit. + + + + + Gets or sets the main thread which should be interupted by thread.interrupt_main + + + + + Gets or sets the default encoding for this system state / engine. + + + + + Dictionary from name to type of all known built-in module names. + + + + + Dictionary from type to name of all built-in modules. + + + + + TODO: Remove me, or stop caching built-ins. This is broken if the user changes __builtin__ + + + + Dictionary of error handlers for string codecs. + + + Table of functions used for looking for additional codecs. + + + + Returns a shared code context for the current PythonContext. This shared + context can be used for performing general operations which usually + require a CodeContext. + + + + + Returns an overload resolver for the current PythonContext. The overload + resolver will flow the shared context through as it's CodeContext. + + + + + Returns a shared code context for the current PythonContext. This shared + context can be used for doing lookups which need to occur as if they + happened in a module which has done "import clr". + + + + + A DynamicStackFrame which has Python specific data. Currently this + includes the code context which may provide access to locals and the + function code object which is needed to build frame objects from. + + + + + Gets the code context of the function. + + If the function included a call to locals() or the FullFrames + option is enabled then the code context includes all local variables. + + Null if deserialized. + + + + + Gets the code object for this frame. This is used in creating + the trace back. Null if deserialized. + + + + + Created for a user-defined function. + + + + + Python ctor - maps to function.__new__ + + y = func(x.__code__, globals(), 'foo', None, (a, )) + + + + + Calculates the _compat value which is used for call-compatibility checks + for simple calls. Whenver any of the dependent values are updated this + must be called again. + + The dependent values include: + _nparams - this is readonly, and never requies an update + _defaults - the user can mutate this (func_defaults) and that forces + an update + expand dict/list - based on nparams and flags, both read-only + + Bits are allocated as: + 00003fff - Normal argument count + 0fffb000 - Default count + 10000000 - unused + 20000000 - expand list + 40000000 - expand dict + 80000000 - unused + + Enforce recursion is added at runtime. + + + + + The parent CodeContext in which this function was declared. + + + + + Captures the # of args and whether we have kw / arg lists. This + enables us to share sites for simple calls (calls that don't directly + provide named arguments or the list/dict params). + + + + + Generators w/ exception handling need to have some data stored + on them so that we appropriately set/restore the exception state. + + + + + Returns an ID for the function if one has been assigned, or zero if the + function has not yet required the use of an ID. + + + + + Gets the position for the expand list argument or -1 if the function doesn't have an expand list parameter. + + + + + Gets the position for the expand dictionary argument or -1 if the function doesn't have an expand dictionary parameter. + + + + + Gets the number of normal (not params or kw-params) parameters. + + + + + Gets the number of extra arguments (params or kw-params) + + + + + Gets the collection of command line arguments. + + + + + Should we strip out all doc strings (the -O command line option). + + + + + Should we strip out all doc strings (the -OO command line option). + + + + + List of -W (warning filter) options collected from the command line. + + + + + Enables warnings related to Python 3.0 features. + + + + + Enables 3.0 features that are implemented in IronPython. + + + + + Enables debugging support. When enabled a .NET debugger can be attached + to the process to step through Python code. + + + + + Enables inspect mode. After running the main module the REPL will be started + within that modules context. + + + + + Suppresses addition of the user site directory. This is ignored by IronPython + except for updating sys.flags. + + + + + Disables import site on startup. + + + + + Ignore environment variables that configure the IronPython context. + + + + + Enables the verbose option which traces import statements. This is ignored by IronPython + except for setting sys.flags. + + + + + Sets the maximum recursion depth. Setting to Int32.MaxValue will disable recursion + enforcement. + + + + + Makes available sys._getframe. Local variables will not be available in frames unless the + function calls locals(), dir(), vars(), etc... For ensuring locals are always available use + the FullFrames option. + + + + + Makes available sys._getframe. All locals variables will live on the heap (for a considerable + performance cost) enabling introspection of all code. + + + + + Tracing is always available. Without this option tracing is only enabled when sys.settrace + is called. This means code that was already running before sys.settrace will not be debuggable. + + With this option pdb.set_trace and pdb.post_mortem will always work properly. + + + + + Severity of a warning that indentation is formatted inconsistently. + + + + + The division options (old, new, warn, warnall) + + + + + Forces all code to be compiled in a mode in which the code can be reliably collected by the CLR. + + + + + Enable profiling code + + + + + Returns a regular expression of Python files which should not be emitted in debug mode. + + + + + Gets the CPython version which IronPython will emulate. Currently limited + to either 2.6 or 3.0. + + + + + Marks a member as being hidden from Python code. + + + + + This assembly-level attribute specifies which types in the engine represent built-in Python modules. + + Members of a built-in module type should all be static as an instance is never created. + + + + + Creates a new PythonModuleAttribute that can be used to specify a built-in module that exists + within an assembly. + + The built-in module name + The type that implements the built-in module. + + + + The built-in module name + + + + + The type that implements the built-in module + + + + + Marks a type as being a PythonType for purposes of member lookup, creating instances, etc... + + If defined a PythonType will use __new__ / __init__ when creating instances. This allows the + object to match the native Python behavior such as returning cached values from __new__ or + supporting initialization to run multiple times via __init__. + + The attribute also allows you to specify an alternate type name. This allows the .NET name to + be different from the Python name so they can follow .NET naming conventions. + + Types defining this attribute also don't show CLR methods such as Equals, GetHashCode, etc... until + the user has done an import clr. + + + + + General-purpose storage used for Python sets and frozensets. + + The set storage is thread-safe for multiple readers or writers. + + Mutations to the set involve a simple locking strategy of locking on the SetStorage object + itself to ensure mutual exclusion. + + Reads against the set happen lock-free. When the set is mutated, it adds or removes buckets + in an atomic manner so that the readers will see a consistent picture as if the read + occurred either before or after the mutation. + + + + + Creates a new set storage with no buckets + + + + + Creates a new set storage with no buckets + + + + + Adds a new item to the set, unless an equivalent item is already present + + + + + Static helper which adds the given non-null item with a precomputed hash code. Returns + true if the item was added, false if it was already present in the set. + + + + + Lock-free helper on a non-null item with a pre-calculated hash code. Removes the item + if it is present in the set, otherwise adds it. + + + + + Clears the contents of the set + + + + + Clones the set, returning a new SetStorage object + + + + + Checks to see if the given item exists in the set + + + + + Checks to see if the given item exists in the set, and tries to hash it even + if it is known not to be in the set. + + + + + + + Adds items from this set into the other set + + + + + Removes the first set element in the iteration order. + + true if an item was removed, false if the set was empty + + + + Removes an item from the set and returns true if it was present, otherwise returns + false + + + + + Removes an item from the set and returns true if it was removed. The item will always + be hashed, throwing if it is unhashable - even if the set has no buckets. + + + + + Lock-free helper to remove a non-null item + + + + + Determines whether the current set shares no elements with the given set + + + + + Determines whether the current set is a subset of the given set + + + + + Determines whether the current set is a strict subset of the given set + + + + + Mutates this set to contain its union with 'other'. The caller must lock the current + set if synchronization is desired. + + + + + Mutates this set to contain its intersection with 'other'. The caller must lock the + current set if synchronization is desired. + + + + + Mutates this set to contain its symmetric difference with 'other'. The caller must + lock the current set if synchronization is desired. + + + + + Mutates this set to contain its difference with 'other'. The caller must lock the + current set if synchronization is desired. + + + + + Computes the union of self and other, returning an entirely new set. This method is + thread-safe and makes no modifications to self or other. + + + + + Computes the intersection of self and other, returning an entirely new set. This + method is thread-safe and makes no modifications to self or other. + + + + + Computes the symmetric difference of self and other, returning an entirely new set. + This method is thread-safe and makes no modifications to self or other. + + + + + Computes the difference of self and other, returning an entirely new set. This + method is thread-safe and makes no modifications to self or other. + + + + + Helper to hash the given item w/ support for null + + + + + Helper which ensures that the first argument x requires the least work to enumerate + + + + + A factory which creates a SetStorage object from any Python iterable. It extracts + the underlying storage of a set or frozen set without copying, which is left to the + caller if necessary. + + + + + A factory which creates a SetStorage object from any Python iterable. It extracts + the underlying storage of a set or frozen set without copying, which is left to the + caller if necessary. + Returns true if the given object was a set or frozen set, false otherwise. + + + + + A factory which creates a SetStorage object from any Python iterable. It extracts + the underlying storage of a set or frozen set, copying in the former case, to return + a SetStorage object that is guaranteed not to receive any outside mutations. + + + + + Extracts the SetStorage object from o if it is a set or frozenset and returns true. + Otherwise returns false. + + + + + Creates a hashable set from the given set, or does nothing if the given object + is not a set. + + True if o is a set or frozenset, false otherwise + + + + Returns the number of items currently in the set + + + + + Used to store a single hashed item. + + Bucket is not serializable because it stores the computed hash code, which could change + between serialization and deserialization. + + + + + Provides storage which is flowed into a callers site. The same storage object is + flowed for multiple calls enabling the callee to cache data that can be re-used + across multiple calls. + + Data is a public field so that this works properly with DynamicSite's as the reference + type (and EnsureInitialize) + + + + + Provides a representation and parsing for the default formatting specification. This is used + by object.__format__, int.__format__, long.__format__, and float.__format__ to do the common + format spec parsing. + + The default specification is: + + format_spec = [[fill]align][sign][#][0][width][,][.precision][type] + fill = a character other than } + align = "<" | ">" | "=" | "^" + sign = "+" | "-" | " " + width = integer + precision = integer + type = "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "x" | "X" | "%" + + + + + Parses a format spec and returns a new StringFormatSpec object. + + + + + Optimized storage for setting exc_type, exc_value, and exc_traceback. + + This optimization can go away in Python 3.0 when these attributes are no longer used. + + + + + Marks a type as being a suitable type to be used for user-defined classes. + + The requirements for this are that a type has to follow the patterns + that NewTypeMaker derived types follow. This includes: + The type's constructors must all take PythonType as the 1st parameter + which sets the underlying type for the actual object + The type needs to implement IPythonObject + Dictionary-based storage needs to be provided for setting individual members + Virtual methods exposed to Python need to support checking the types dictionary for invocations + + + + + Base class for helper which creates instances. We have two derived types: One for user + defined types which prepends the type before calling, and one for .NET types which + doesn't prepend the type. + + + + + Contains helper methods for converting C# names into Python names. + + + + + TypeInfo captures the minimal CLI information required by NewTypeMaker for a Python object + that inherits from a CLI type. + + + + + "bases" contains a set of PythonTypes. These can include types defined in Python (say cpy1, cpy2), + CLI types (say cCLI1, cCLI2), and CLI interfaces (say iCLI1, iCLI2). Here are some + examples of how this works: + + (bases) => baseType, {interfaceTypes} + + (cpy1) => System.Object, {} + (cpy1, cpy2) => System.Object, {} + (cpy1, cCLI1, iCLI1, iCLI2) => cCLI1, {iCLI1, iCLI2} + [some type that satisfies the line above] => + cCLI1, {iCLI1, iCLI2} + (cCLI1, cCLI2) => error + + + + + Filters out old-classes and throws if any non-types are included, returning a + yielding the remaining PythonType objects. + + + + + Python class hierarchy is represented using the __class__ field in the object. It does not + use the CLI type system for pure Python types. However, Python types which inherit from a + CLI type, or from a builtin Python type which is implemented in the engine by a CLI type, + do have to use the CLI type system to interoperate with the CLI world. This means that + objects of different Python types, but with the same CLI base type, can use the same CLI type - + they will just have different values for the __class__ field. + + The easiest way to inspect the functionality implemented by NewTypeMaker is to persist the + generated IL using "ipy.exe -X:SaveAssemblies", and then inspect the + persisted IL using ildasm. + + + + + Loads any available new types from the provided assembly and makes them + available via the GetNewType API. + + + + + Is this a type used for instances Python types (and not for the types themselves)? + + + + + Gets the position for the parameter which we are overriding. + + + + + + + + + Defines an interface on the type that forwards all calls + to a helper method in UserType. The method names all will + have Helper appended to them to get the name for UserType. The + UserType version should take 1 extra parameter (self). + + + + + Overrides methods - this includes all accessible virtual methods as well as protected non-virtual members + including statics and non-statics. + + + + + Loads all the incoming arguments and forwards them to mi which + has the same signature and then returns the result + + + + + Emits code to check if the class has overridden this specific + function. For example: + + MyDerivedType.SomeVirtualFunction = ... + or + + class MyDerivedType(MyBaseType): + def SomeVirtualFunction(self, ...): + + + + + + Emit code to convert object to a given type. This code is semantically equivalent + to PythonBinder.EmitConvertFromObject, except this version accepts ILGen whereas + PythonBinder accepts Compiler. The Binder will chagne soon and the two will merge. + + + + + Emits code to check if the class has overridden this specific + function. For example: + + MyDerivedType.SomeVirtualFunction = ... + or + + class MyDerivedType(MyBaseType): + def SomeVirtualFunction(self, ...): + + + + + + Emits the call to lookup a member defined in the user's type. Returns + the local which stores the resulting value and leaves a value on the + stack indicating the success of the lookup. + + + + + Creates a method for doing a base method dispatch. This is used to support + super(type, obj) calls. + + + + + Generates stub to receive the CLR call and then call the dynamic language code. + This code is same as StubGenerator.cs in the Microsoft.Scripting, except it + accepts ILGen instead of Compiler. + + + + + Called from PythonTypeOps - the BuiltinFunction._function lock must be held. + + + + + Same as the DLR ReturnFixer, but accepts lower level constructs, + such as LocalBuilder, ParameterInfos and ILGen. + + + + + Creates a new PythonCompilerOptions with the default language features enabled. + + + + + Creates a new PythonCompilerOptions with the specified language features enabled. + + + + + Creates a new PythonCompilerOptions and enables or disables true division. + + This overload is obsolete, instead you should use the overload which takes a + ModuleOptions. + + + + + Gets or sets the initial indentation. This can be set to allow parsing + partial blocks of code that are already indented. + + For each element of the array there is an additional level of indentation. + Each integer value represents the number of spaces used for the indentation. + + If this value is null then no indentation level is specified. + + + + + Language features initialized on parser construction and possibly updated during parsing. + The code can set the language features (e.g. "from __future__ import division"). + + + + + Parse one or more lines of interactive input + + null if input is not yet valid but could be with more lines + + + + Given the interactive text input for a compound statement, calculate what the + indentation level of the next line should be + + + + + Peek if the next token is a 'yield' and parse a yield expression. Else return null. + + Called w/ yield already eaten. + + A yield expression if present, else null. + + + + Maybe eats a new line token returning true if the token was + eaten. + + Python always tokenizes to have only 1 new line character in a + row. But we also craete NLToken's and ignore them except for + error reporting purposes. This gives us the same errors as + CPython and also matches the behavior of the standard library + tokenize module. This function eats any present NL tokens and throws + them away. + + + + + Eats a new line token throwing if the next token isn't a new line. + + Python always tokenizes to have only 1 new line character in a + row. But we also craete NLToken's and ignore them except for + error reporting purposes. This gives us the same errors as + CPython and also matches the behavior of the standard library + tokenize module. This function eats any present NL tokens and throws + them away. + + + + + Summary description for Token. + + + + + IronPython tokenizer + + + + + Used to create tokenizer for hosting API. + + + + + Returns whether the + + + + + Resizes an array to a speficied new size and copies a portion of the original array into its beginning. + + + + + True if the last characters in the buffer are a backslash followed by a new line indicating + that their is an incompletement statement which needs further input to complete. + + + + + Equality comparer that can compare strings to our current token w/o creating a new string first. + + + + + A simple Python command-line should mimic the standard python.exe + + + + + Returns the display look for IronPython. + + The returned string uses This \n instead of Environment.NewLine for it's line seperator + because it is intended to be outputted through the Python I/O system. + + + + + Loads any extension DLLs present in sys.prefix\DLLs directory and adds references to them. + + This provides an easy drop-in location for .NET assemblies which should be automatically referenced + (exposed via import), COM libraries, and pre-compiled Python code. + + + + + Attempts to run a single interaction and handle any language-specific + exceptions. Base classes can override this and call the base implementation + surrounded with their own exception handling. + + Returns null if successful and execution should continue, or an exit code. + + + + + Parses a single interactive command and executes it. + + Returns null if successful and execution should continue, or the appropiate exit code. + + + + + Skip the first line of the code to execute. This is useful for executing Unix scripts which + have the command to execute specified in the first line. + This only apply to the script code executed by the ScriptEngine APIs, but not for other script code + that happens to get called as a result of the execution. + + + + On error. + + + + Provides helpers for interacting with IronPython. + + + + + Creates a new ScriptRuntime with the IronPython scipting engine pre-configured. + + + + + + Creates a new ScriptRuntime with the IronPython scipting engine pre-configured and + additional options. + + + + + Creates a new ScriptRuntime with the IronPython scripting engine pre-configured + in the specified AppDomain. The remote ScriptRuntime may be manipulated from + the local domain but all code will run in the remote domain. + + + + + Creates a new ScriptRuntime with the IronPython scripting engine pre-configured + in the specified AppDomain with additional options. The remote ScriptRuntime may + be manipulated from the local domain but all code will run in the remote domain. + + + + + Creates a new ScriptRuntime and returns the ScriptEngine for IronPython. If + the ScriptRuntime is required it can be acquired from the Runtime property + on the engine. + + + + + Creates a new ScriptRuntime with the specified options and returns the + ScriptEngine for IronPython. If the ScriptRuntime is required it can be + acquired from the Runtime property on the engine. + + + + + Creates a new ScriptRuntime and returns the ScriptEngine for IronPython. If + the ScriptRuntime is required it can be acquired from the Runtime property + on the engine. + + The remote ScriptRuntime may be manipulated from the local domain but + all code will run in the remote domain. + + + + + Creates a new ScriptRuntime with the specified options and returns the + ScriptEngine for IronPython. If the ScriptRuntime is required it can be + acquired from the Runtime property on the engine. + + The remote ScriptRuntime may be manipulated from the local domain but + all code will run in the remote domain. + + + + + Given a ScriptRuntime gets the ScriptEngine for IronPython. + + + + + Gets a ScriptScope which is the Python sys module for the provided ScriptRuntime. + + + + + Gets a ScriptScope which is the Python sys module for the provided ScriptEngine. + + + + + Gets a ScriptScope which is the Python __builtin__ module for the provided ScriptRuntime. + + + + + Gets a ScriptScope which is the Python __builtin__ module for the provided ScriptEngine. + + + + + Gets a ScriptScope which is the Python clr module for the provided ScriptRuntime. + + + + + Gets a ScriptScope which is the Python clr module for the provided ScriptEngine. + + + + + Imports the Python module by the given name and returns its ScriptSCope. If the + module does not exist an exception is raised. + + + + + Imports the Python module by the given name and returns its ScriptSCope. If the + module does not exist an exception is raised. + + + + + Imports the Python module by the given name and inserts it into the ScriptScope as that name. If the + module does not exist an exception is raised. + + + + + + + Sets sys.exec_prefix, sys.executable and sys.version and adds the prefix to sys.path + + + + + Sets sys.exec_prefix, sys.executable and sys.version and adds the prefix to sys.path + + + + + Enables call tracing for the current thread in this ScriptEngine. + + TracebackDelegate will be called back for each function entry, exit, exception, and line change. + + + + + Enables call tracing for the current thread for the Python engine in this ScriptRuntime. + + TracebackDelegate will be called back for each function entry, exit, exception, and line change. + + + + + Provides nested level debugging support when SetTrace or SetProfile are used. + + This saves the current tracing information and then calls the provided object. + + + + + Provides nested level debugging support when SetTrace or SetProfile are used. + + This saves the current tracing information and then calls the provided object. + + + + + Creates a ScriptRuntimeSetup object which includes the Python script engine with the specified options. + + The ScriptRuntimeSetup object can then be additional configured and used to create a ScriptRuntime. + + + + + Creates a LanguageSetup object which includes the Python script engine with the specified options. + + The LanguageSetup object can be used with other LanguageSetup objects from other languages to + configure a ScriptRuntimeSetup object. + + + + + Creates a new PythonModule with the specified name and published it in sys.modules. + + Returns the ScriptScope associated with the module. + + + + + Creates a new PythonModule with the specified name and filename published it + in sys.modules. + + Returns the ScriptScope associated with the module. + + + + + Creates a new PythonModule with the specified name, filename, and doc string and + published it in sys.modules. + + Returns the ScriptScope associated with the module. + + + + + Gets the list of loaded Python module files names which are available in the provided ScriptEngine. + + + + + A strongly-typed resource class, for looking up localized strings, etc. + + + + + Returns the cached ResourceManager instance used by this class. + + + + + Overrides the current thread's CurrentUICulture property for all + resource lookups using this strongly typed resource class. + + + + + Looks up a localized string similar to couldn't find member {0}. + + + + + Looks up a localized string similar to default value must be specified here. + + + + + Looks up a localized string similar to duplicate argument '{0}' in function definition. + + + + + Looks up a localized string similar to duplicate keyword argument. + + + + + Looks up a localized string similar to <eof> while reading string. + + + + + Looks up a localized string similar to EOF while scanning triple-quoted string. + + + + + Looks up a localized string similar to EOL while scanning single-quoted string. + + + + + Looks up a localized string similar to expected an indented block. + + + + + Looks up a localized string similar to expected name. + + + + + Looks up a localized string similar to Expecting identifier:. + + + + + Looks up a localized string similar to inconsistent use of tabs and spaces in indentation. + + + + + Looks up a localized string similar to unindent does not match any outer indentation level. + + + + + Looks up a localized string similar to Invalid argument value.. + + + + + Looks up a localized string similar to MakeGenericType on non-generic type. + + + + + Looks up a localized string similar to Invalid parameter collection for the function.. + + + + + Looks up a localized string similar to invalid syntax. + + + + + Looks up a localized string similar to object ({0}) is not creatable w/ keyword arguments. + + + + + Looks up a localized string similar to keywords must come before * args. + + + + + Looks up a localized string similar to type does not have {0} field. + + + + + Looks up a localized string similar to from __future__ imports must occur at the beginning of the file. + + + + + Looks up a localized string similar to 'return' outside function. + + + + + Looks up a localized string similar to 'yield' outside function. + + + + + Looks up a localized string similar to NEWLINE in double-quoted string. + + + + + Looks up a localized string similar to NEWLINE in single-quoted string. + + + + + Looks up a localized string similar to future statement does not support import *. + + + + + Looks up a localized string similar to non-keyword arg after keyword arg. + + + + + Looks up a localized string similar to not a chance. + + + + + Looks up a localized string similar to The method or operation is not implemented.. + + + + + Looks up a localized string similar to only one ** allowed. + + + + + Looks up a localized string similar to only one * allowed. + + + + + Looks up a localized string similar to Context must be PythonCompilerContext. + + + + + Looks up a localized string similar to cannot delete slot. + + + + + Looks up a localized string similar to cannot get slot. + + + + + Looks up a localized string similar to cannot set slot. + + + + + Looks up a localized string similar to static property '{0}' of '{1}' can only be read through a type, not an instance. + + + + + Looks up a localized string similar to static property '{0}' of '{1}' can only be assigned to through a type, not an instance. + + + + + Looks up a localized string similar to no value for this token. + + + + + Looks up a localized string similar to too many versions. + + + + + Looks up a localized string similar to unexpected token '{0}'. + + + + + Looks up a localized string similar to future feature is not defined:. + + + + + The Action used for Python call sites. This supports both splatting of position and keyword arguments. + + When a foreign object is encountered the arguments are expanded into normal position/keyword arguments. + + + + + Python's Invoke is a non-standard action. Here we first try to bind through a Python + internal interface (IPythonInvokable) which supports CallSigantures. If that fails + and we have an IDO then we translate to the DLR protocol through a nested dynamic site - + this includes unsplatting any keyword / position arguments. Finally if it's just a plain + old .NET type we use the default binder which supports CallSignatures. + + + + + Fallback - performs the default binding operation if the object isn't recognized + as being invokable. + + + + + Creates a nested dynamic site which uses the unpacked arguments. + + + + + Translates our CallSignature into a DLR Argument list and gives the simple MetaObject's which are extracted + from the tuple or dictionary parameters being splatted. + + + + + Gets the CallSignature for this invocation which describes how the MetaObject array + is to be mapped. + + + + + General purpose storage used for most PythonDictionarys. + + This dictionary storage is thread safe for multiple readers or writers. + + Mutations to the dictionary involves a simple locking strategy of + locking on the DictionaryStorage object to ensure that only one + mutation happens at a time. + + Reads against the dictionary happen lock free. When the dictionary is mutated + it is either adding or removing buckets in a thread-safe manner so that the readers + will either see a consistent picture as if the read occured before or after the mutation. + + When resizing the dictionary the buckets are replaced atomically so that the reader + sees the new buckets or the old buckets. When reading the reader first reads + the buckets and then calls a static helper function to do the read from the bucket + array to ensure that readers are not seeing multiple bucket arrays. + + + + + Creates a new dictionary storage with no buckets + + + + + Creates a new dictionary storage with no buckets + + + + + Creates a new dictionary geting values/keys from the + items arary + + + + + Creates a new dictionary storage with the given set of buckets + and size. Used when cloning the dictionary storage. + + + + + Adds a new item to the dictionary, replacing an existing one if it already exists. + + + + + Initializes the buckets to their initial capacity, the caller + must check if the buckets are empty first. + + + + + Add helper that works over a single set of buckets. Used for + both the normal add case as well as the resize case. + + + + + Add helper which adds the given key/value (where the key is not null) with + a pre-computed hash code. + + + + + Removes an entry from the dictionary and returns true if the + entry was removed or false. + + + + + Removes an entry from the dictionary and returns true if the + entry was removed or false. The key will always be hashed + so if it is unhashable an exception will be thrown - even + if the dictionary has no buckets. + + + + + Checks to see if the key exists in the dictionary. + + + + + Trys to get the value associated with the given key and returns true + if it's found or false if it's not present. + + + + + Static helper to try and get the value from the dictionary. + + Used so the value lookup can run against a buckets while a writer + replaces the buckets. + + + + + Clears the contents of the dictionary. + + + + + Clones the storage returning a new DictionaryStorage object. + + + + + Helper to hash the given key w/ support for null. + + + + + Returns the number of key/value pairs currently in the dictionary. + + + + + Used to store a single hashed key/value. + + Bucket is not serializable because it stores the computed hash + code which could change between serialization and deserialization. + + + + + Special marker NullValue used during deserialization to not add + an extra field to the dictionary storage type. + + + + + The error involved an incomplete statement due to an unexpected EOF. + + + + + The error involved an incomplete token. + + + + + The mask for the actual error values + + + + + The error was a general syntax error + + + + + The error was an indentation error. + + + + + The error was a tab error. + + + + + syntax error shouldn't include a caret (no column offset should be included) + + + + + GeneratorExitException is a standard exception raised by Generator.Close() to allow a caller + to close out a generator. + + GeneratorExit is introduced in Pep342 for Python2.5. + + + + .NET exception thrown when a Python syntax error is related to incorrect indentation. + + + + + Implementation of the Python exceptions module and the IronPython/CLR exception mapping + mechanism. The exception module is the parent module for all Python exception classes + and therefore is built-in to IronPython.dll instead of IronPython.Modules.dll. + + The exception mapping mechanism is exposed as internal surface area available to only + IronPython / IronPython.Modules.dll. The actual exceptions themselves are all public. + + Because the oddity of the built-in exception types all sharing the same physical layout + (see also PythonExceptions.BaseException) some classes are defined as classes w/ their + proper name and some classes are defined as PythonType fields. When a class is defined + for convenience their's also an _TypeName version which is the PythonType. + + + + + Creates a new throwable exception of type type where the type is an new-style exception. + + Used at runtime when creating the exception from a user provided type via the raise statement. + + + + + Creates a throwable exception of type type where the type is an OldClass. + + Used at runtime when creating the exception form a user provided type that's an old class (via the raise statement). + + + + + Returns the CLR exception associated with a Python exception + creating a new exception if necessary + + + + + Given a CLR exception returns the Python exception which most closely maps to the CLR exception. + + + + + Creates a new style Python exception from the .NET exception + + + + + Internal helper to associate a .NET exception and a Python exception. + + + + + Internal helper to get the associated Python exception from a .NET exception. + + + + + Converts the DLR SyntaxErrorException into a Python new-style SyntaxError instance. + + + + + Creates a PythonType for a built-in module. These types are mutable like + normal user types. + + + + + Creates a PythonType for a built-in module. These types are mutable like + normal user types. + + + + + Creates a PythonType for a built-in module, where the type may inherit + from multiple bases. These types are mutable like normal user types. + + + + + Creates a new type for a built-in exception which derives from another Python + type. . These types are built-in and immutable like any other normal type. For + example StandardError.x = 3 is illegal. This isn't for module exceptions which + are like user defined types. thread.error.x = 3 is legal. + + + + + Creates a new type for a built-in exception which is the root concrete type. + + + + + Gets the list of DynamicStackFrames for the current exception. + + + + + Base class for all Python exception objects. + + When users throw exceptions they typically throw an exception which is + a subtype of this. A mapping is maintained between Python exceptions + and .NET exceptions and a corresponding .NET exception is thrown which + is associated with the Python exception. This class represents the + base class for the Python exception hierarchy. + + Users can catch exceptions rooted in either hierarchy. The hierarchy + determines whether the user catches the .NET exception object or the + Python exception object. + + Most built-in Python exception classes are actually instances of the BaseException + class here. This is important because in CPython the exceptions do not + add new members and therefore their layouts are compatible for multiple + inheritance. The exceptions to this rule are the classes which define + their own fields within their type, therefore altering their layout: + EnvironmentError + SyntaxError + IndentationError (same layout as SyntaxError) + TabError (same layout as SyntaxError) + SystemExit + UnicodeDecodeError + UnicodeEncodeError + UnicodeTranslateError + + These exceptions cannot be combined in multiple inheritance, e.g.: + class foo(EnvironmentError, IndentationError): pass + + fails but they can be combined with anything which is just a BaseException: + class foo(UnicodeDecodeError, SystemError): pass + + Therefore the majority of the classes are just BaseException instances with a + custom PythonType object. The specialized ones have their own .NET class + which inherits from BaseException. User defined exceptions likewise inherit + from this and have their own .NET class. + + + + + This interface is used for implementing parts of the IronPython type system. It + is not intended for consumption from user programs. + + + + + Thread-safe dictionary set. Returns the dictionary set or the previous value if already set or + null if the dictionary set isn't supported. + + + + + + + Dictionary replacement. Returns true if replaced, false if the dictionary set isn't supported. + + + + + + + Initializes the Exception object with an unlimited number of arguments + + + + + Returns a tuple of (type, (arg0, ..., argN)) for implementing pickling/copying + + + + + Returns a tuple of (type, (arg0, ..., argN)) for implementing pickling/copying + + + + + Updates the exception's state (dictionary) with the new values + + + + + Provides custom member lookup access that fallbacks to the dictionary + + + + + Provides custom member assignment which stores values in the dictionary + + + + + Provides custom member deletion which deletes values from the dictionary + or allows clearing 'message'. + + + + + Implements __repr__ which returns the type name + the args + tuple code formatted. + + + + + Initializes the Python exception from a .NET exception + + + + + + Helper to get the CLR exception associated w/ this Python exception + creating it if one has not already been created. + + + + + Returns the exception 'message' if only a single argument was provided + during creation or an empty string. + + + + + Gets or sets the arguments used for creating the exception + + + + + Gets the nth member of the args property + + + + + Gets or sets the dictionary which is used for storing members not declared to have space reserved + within the exception object. + + + + + Gets the CLR exception associated w/ this Python exception. Not visible + until a .NET namespace is imported. + + + + + .NET exception that is thrown to signal the end of iteration in Python + + + + + .NET exception that is thrown to shutdown the interpretter and exit the system. + + + + + Result of sys.exit(n) + + + null if the script exited using "sys.exit(int_value)" + null if the script exited using "sys.exit(None)" + x if the script exited using "sys.exit(x)" where isinstance(x, int) == False + + + int_value if the script exited using "sys.exit(int_value)" + 1 otherwise + + + + + .NET Exception thrown when a Python syntax error is related to incorrect tabs. + + + + + Represents a sequence which may have been provided as a set of parameters to an indexer. + + TODO: This should be removed, and all uses of this should go to [SpecialName]object GetItem(..., params object[] keys) + and [SpecialName]void SetItem(..., params object [] keys) or this[params object[]xyz] which is also legal. + + currently this exists for backwards compatibility w/ IronPython's "expandable tuples". + + + + + Provides a MetaObject for instances of Python's old-style classes. + + TODO: Lots of CodeConetxt references, need to move CodeContext onto OldClass and pull it from there. + + + + + Performs the actual work of binding to the function. + + Overall this works by going through the arguments and attempting to bind all the outstanding known + arguments - position arguments and named arguments which map to parameters are easy and handled + in the 1st pass for GetArgumentsForRule. We also pick up any extra named or position arguments which + will need to be passed off to a kw argument or a params array. + + After all the normal args have been assigned to do a 2nd pass in FinishArguments. Here we assign + a value to either a value from the params list, kw-dict, or defaults. If there is ambiguity between + this (e.g. we have a splatted params list, kw-dict, and defaults) we call a helper which extracts them + in the proper order (first try the list, then the dict, then the defaults). + + + + + Makes the test for our rule. + + + + + Makes the test when we just have simple positional arguments. + + + + + Makes the test when we have a keyword argument call or splatting. + + + + + + Gets the array of expressions which correspond to each argument for the function. These + correspond with the function as it's defined in Python and must be transformed for our + delegate type before being used. + + + + + Binds any missing arguments to values from params array, kw dictionary, or default values. + + + + + Creates the argument for the list expansion parameter. + + + + + Adds extra positional arguments to the start of the expanded list. + + + + + Creates the argument for the dictionary expansion parameter. + + + + + Adds an unbound keyword argument into the dictionary. + + + + + + Adds a check to the last parameter (so it's evaluated after we've extracted + all the parameters) to ensure that we don't have any extra params or kw-params + when we don't have a params array or params dict to expand them into. + + + + + Helper function to validate that a named arg isn't duplicated with by + a params list or the dictionary (or both). + + + + + Helper function to get a value (which has no default) from either the + params list or the dictionary (or both). + + + + + Helper function to get the specified variable from the dictionary. + + + + + Helper function to extract the variable from defaults, or to call a helper + to check params / kw-dict / defaults to see which one contains the actual value. + + + + + Helper function to extract from the params list or dictionary depending upon + which one has an available value. + + + + + Helper function to extract the next argument from the params list. + + + + + Fixes up the argument list for the appropriate target delegate type. + + + + + Helper function to get the function argument strongly typed. + + + + + Called when the user is expanding a dictionary - we copy the user + dictionary and verify that it contains only valid string names. + + + + + Called when the user is expanding a params argument + + + + + Called when the user hasn't supplied a dictionary to be expanded but the + function takes a dictionary to be expanded. + + + + + Helper function to create the expression for creating the actual tuple passed through. + + + + + Creates the code to invoke the target delegate function w/ the specified arguments. + + + + + Appends the initialization code for the call to the function if any exists. + + + + + Creating a standard .NET type is easy - we just call it's constructor with the provided + arguments. + + + + + Creating a Python type involves calling __new__ and __init__. We resolve them + and generate calls to either the builtin funcions directly or embed sites which + call the slots at runtime. + + + + + Checks if we have a default new and init - in this case if we have any + arguments we don't allow the call. + + + + + Creates a test which tests the specific version of the type. + + + + + Base class for performing member binding. Derived classes override Add methods + to produce the actual final result based upon what the GetBinderHelper resolves. + + + + + + Provides the normal meta binder binding. + + + + + Provides delegate based fast binding. + + + + + The result type of the operation. + + + + + Looks up __init__ avoiding calls to __getattribute__ and handling both + new-style and old-style classes in the MRO. + + + + + Gets a builtin function for the given declaring type and member infos. + + Given the same inputs this always returns the same object ensuring there's only 1 builtinfunction + for each .NET method. + + This method takes both a cacheName and a pythonName. The cache name is the real method name. The pythonName + is the name of the method as exposed to Python. + + + + + Checks to see if the provided members are always visible for the given type. + + This filters out methods such as GetHashCode and Equals on standard .NET + types that we expose directly as Python types (e.g. object, string, etc...). + + It also filters out the base helper overrides that are added for supporting + super calls on user defined types. + + + + + a function is static if it's a static .NET method and it's defined on the type or is an extension method + with StaticExtensionMethod decoration. + + + + + If we have only interfaces, we'll need to insert object's base + + + + + Simple implementation of ASCII encoding/decoding. The default instance (PythonAsciiEncoding.Instance) is + setup to always convert even values outside of the ASCII range. The EncoderFallback/DecoderFallbacks can + be replaced with versions that will throw exceptions instead though. + + + + + Specialized version because enumerating tuples by Python's definition + doesn't call __getitem__, but filter does! + + + + + Opens a file and returns a new file object. + + name -> the name of the file to open. + mode -> the mode to open the file (r for reading, w for writing, a for appending, default is r). + bufsize -> the size of the buffer to be used (<= 0 indicates to use the default size) + + + + + Creates a new Python file object from a .NET stream object. + + stream -> the stream to wrap in a file object. + + + + + object overload of range - attempts to convert via __int__, and __trunc__ if arg is + an OldInstance + + + + + object overload of range - attempts to convert via __int__, and __trunc__ if arg is + an OldInstance + + + + + Gets the appropriate LanguageContext to be used for code compiled with Python's compile, eval, execfile, etc... + + + + Returns true if we should inherit our callers context (true division, etc...), false otherwise + + + Returns the default compiler flags or the flags the user specified. + + + + Gets a scope used for executing new code in optionally replacing the globals and locals dictionaries. + + + + + Set if the function includes a *args argument list. + + + + + Set if the function includes a **kwargs argument dictionary. + + + + + Set if the function is a generator. + + + + + Set if the function was compiled with future division. + + + + + IronPython specific: Set if the function includes nested exception handling and therefore can alter + sys.exc_info(). + + + + + IronPython specific: Set if the function includes a try/finally block. + + + + + Represents a piece of code. This can reference either a CompiledCode + object or a Function. The user can explicitly call FunctionCode by + passing it into exec or eval. + + + + + This is both the lock that is held while enumerating the threads or updating the thread accounting + information. It's also a marker CodeList which is put in place when we are enumerating the thread + list and all additions need to block. + + This lock is also acquired whenever we need to calculate how a function's delegate should be created + so that we don't race against sys.settrace/sys.setprofile. + + + + + Constructor used to create a FunctionCode for code that's been serialized to disk. + + Code constructed this way cannot be interpreted or debugged using sys.settrace/sys.setprofile. + + Function codes created this way do support recursion enforcement and are therefore registered in the global function code registry. + + + + + Constructor to create a FunctionCode at runtime. + + Code constructed this way supports both being interpreted and debugged. When necessary the code will + be re-compiled or re-interpreted for that specific purpose. + + Function codes created this way do support recursion enforcement and are therefore registered in the global function code registry. + + the initial delegate provided here should NOT be the actual code. It should always be a delegate which updates our Target lazily. + + + + + Registers the current function code in our global weak list of all function codes. + + The weak list can be enumerated with GetAllCode(). + + Ultimately there are 3 types of threads we care about races with: + 1. Other threads which are registering function codes + 2. Threads calling sys.settrace which require the world to stop and get updated + 3. Threads running cleanup (thread pool thread, or call to gc.collect). + + The 1st two must have perfect synchronization. We cannot have a thread registering + a new function which another thread is trying to update all of the functions in the world. Doing + so would mean we could miss adding tracing to a thread. + + But the cleanup thread can run in parallel to either registrying or sys.settrace. The only + thing it needs to take a lock for is updating our accounting information about the + number of code objects are alive. + + + + + Enumerates all function codes for updating the current type of targets we generate. + + While enumerating we hold a lock so that users cannot change sys.settrace/sys.setprofile + until the lock is released. + + + + + Creates a FunctionCode object for exec/eval/execfile'd/compile'd code. + + The code is then executed in a specific CodeContext by calling the .Call method. + + If the code is being used for compile (vs. exec/eval/execfile) then it needs to be + registered incase our tracing mode changes. + + + + + Called the 1st time a function is invoked by our OriginalCallTarget* methods + over in PythonCallTargets. This computes the real delegate which needs to be + created for the function. Usually this means starting off interpretering. It + also involves adding the wrapper function for recursion enforcement. + + Because this can race against sys.settrace/setprofile we need to take our + _ThreadIsEnumeratingAndAccountingLock to ensure no one is actively changing all + of the live functions. + + + + + Updates the delegate based upon current Python context settings for recursion enforcement + and for tracing. + + + + + Called to set the initial target delegate when the user has passed -X:Debug to enable + .NET style debugging. + + + + + Gets the LambdaExpression for tracing. + + If this is a generator function code then the lambda gets tranformed into the correct generator code. + + + + + Gets the correct final LambdaExpression for this piece of code. + + This is either just _lambda or _lambda re-written to be a generator expression. + + + + + Returns a list of variable names which are accessed from nested functions. + + + + + Returns the byte code. IronPython does not implement this and always + returns an empty string for byte code. + + + + + Returns a list of constants used by the function. + + The first constant is the doc string, or None if no doc string is provided. + + IronPython currently does not include any other constants than the doc string. + + + + + Returns the filename that the code object was defined in. + + + + + Returns the 1st line number of the code object. + + + + + Returns a set of flags for the function. + + 0x04 is set if the function used *args + 0x08 is set if the function used **args + 0x20 is set if the function is a generator + + + + + Returns a list of free variables (variables accessed + from an outer scope). This does not include variables + accessed in the global scope. + + + + + Returns a mapping between byte code and line numbers. IronPython does + not implement this because byte code is not available. + + + + + Returns the name of the code (function name, class name, or <module>). + + + + + Returns a list of global variable names accessed by the code. + + + + + Returns the number of local varaibles defined in the function. + + + + + Returns the stack size. IronPython does not implement this + because byte code is not supported. + + + + + Extremely light weight linked list of weak references used for tracking + all of the FunctionCode objects which get created and need to be updated + for purposes of recursion enforcement or tracing. + + + + + General conversion routine TryConvert - tries to convert the object to the desired type. + Try to avoid using this method, the goal is to ultimately remove it! + + + + + This function tries to convert an object to IEnumerator, or wraps it into an adapter + Do not use this function directly. It is only meant to be used by Ops.GetEnumerator. + + + + + This function tries to convert an object to IEnumerator, or wraps it into an adapter + Do not use this function directly. It is only meant to be used by Ops.GetEnumerator. + + + + + Attempts to convert value into a index usable for slicing and return the integer + value. If the conversion fails false is returned. + + If throwOverflowError is true then BigInteger's outside the normal range of integers will + result in an OverflowError. + + + + + Attempts to convert value into a index usable for slicing and return the integer + value. If the conversion fails false is returned. + + If throwOverflowError is true then BigInteger's outside the normal range of integers will + result in an OverflowError. + + + + + Converts a value to int ignoring floats + + + + + Note: + IEnumerator innerEnum = Dictionary<K,V>.KeysCollections.GetEnumerator(); + innerEnum.MoveNext() will throw InvalidOperation even if the values get changed, + which is supported in python + + + + + Note: + IEnumerator innerEnum = Dictionary<K,V>.KeysCollections.GetEnumerator(); + innerEnum.MoveNext() will throw InvalidOperation even if the values get changed, + which is supported in python + + + + + Note: + IEnumerator innerEnum = Dictionary<K,V>.KeysCollections.GetEnumerator(); + innerEnum.MoveNext() will throw InvalidOperation even if the values get changed, + which is supported in python + + + + + Provides both helpers for implementing Python dictionaries as well + as providing public methods that should be exposed on all dictionary types. + + Currently these are published on IDictionary<object, object> + + + + + Creates a DLR OverloadDoc object which describes information about this overload. + + The method to document + The name of the method if it should override the name in the MethodBase + Parameters to skip at the end - used for removing the value on a setter method + true to include self on instance methods + + + + Converts a Type object into a string suitable for lookup in the help file. All generic types are + converted down to their generic type definition. + + + + + Gets the XPathDocument for the specified assembly, or null if one is not available. + + + + + Gets the Xml documentation for the specified MethodBase. + + + + + Gets the Xml documentation for the specified Type. + + + + + Gets the Xml documentation for the specified Field. + + + + + Gets the Xml documentation for the specified Field. + + + + + Converts the XML as stored in the config file into a human readable string. + + + + + True iff the thread is currently inside the generator (ie, invoking the _next delegate). + This can be used to enforce that a generator does not call back into itself. + Pep255 says that a generator should throw a ValueError if called reentrantly. + + + + + We cache the GeneratorFinalizer of generators that were closed on the user + thread, and did not get finalized on the finalizer thread. We can then reuse + the object. Reusing objects with a finalizer is good because it reduces + the load on the GC's finalizer queue. + + + + + Fields set by Throw() to communicate an exception to the yield point. + These are plumbed through the generator to become parameters to Raise(...) invoked + at the yield suspension point in the generator. + + + + + Value sent by generator.send(). + Since send() could send an exception, we need to keep this different from throwable's value. + + + + + See PEP 342 (http://python.org/dev/peps/pep-0342/) for details of new methods on Generator. + Full signature including default params for throw is: + throw(type, value=None, traceback=None) + Use multiple overloads to resolve the default parameters. + + + + + Throw(...) is like Raise(...) being called from the yield point within the generator. + Note it must come from inside the generator so that the traceback matches, and so that it can + properly cooperate with any try/catch/finallys inside the generator body. + + If the generator catches the exception and yields another value, that is the return value of g.throw(). + + + + + send() was added in Pep342. It sends a result back into the generator, and the expression becomes + the result of yield when used as an expression. + + + + + Close introduced in Pep 342. + + + + + Core implementation of IEnumerator.MoveNext() + + + + + Core implementation of Python's next() method. + + + + + Helper called from PythonOps after the yield statement + Keepin this in a helper method: + - reduces generated code size + - allows better coupling with PythonGenerator.Throw() + - avoids throws from emitted code (which can be harder to debug). + + + + + + Called to throw an exception set by Throw(). + + + + + Gets the name of the function that produced this generator object. + + + + + True if the generator has finished (is "closed"), else false. + Python language spec mandates that calling Next on a closed generator gracefully throws a StopIterationException. + This can never be reset. + + + + + True if the generator can set sys exc info and therefore needs exception save/restore. + + + + + Importer class - used for importing modules. Used by Ops and __builtin__ + Singleton living on Python engine. + + + + + Gateway into importing ... called from Ops. Performs the initial import of + a module and returns the module. + + + + + Gateway into importing ... called from Ops. Performs the initial import of + a module and returns the module. This version returns light exceptions instead of throwing. + + + + + Gateway into importing ... called from Ops. This is called after + importing the module and is used to return individual items from + the module. The outer modules dictionary is then updated with the + result. + + + + + Called by the __builtin__.__import__ functions (general importing) and ScriptEngine (for site.py) + + level indiciates whether to perform absolute or relative imports. + -1 indicates both should be performed + 0 indicates only absolute imports should be performed + Positive numbers indicate the # of parent directories to search relative to the calling module + + + + + Interrogates the importing module for __name__ and __path__, which determine + whether the imported module (whose name is 'name') is being imported as nested + module (__path__ is present) or as sibling. + + For sibling import, the full name of the imported module is parent.sibling + For nested import, the full name of the imported module is parent.module.nested + where parent.module is the mod.__name__ + + + the globals dictionary + Name of the module to be imported + Output - full name of the module being imported + Path to use to search for "full" + the import level for relaive imports + the parent module + the global __package__ value + + + + + Given the parent module name looks up the __path__ property. + + + + + Trys to get an existing module and if that fails fall backs to searching + + + + + Attempts to load a module from sys.meta_path as defined in PEP 302. + + The meta_path provides a list of importer objects which can be used to load modules before + searching sys.path but after searching built-in modules. + + + + + Given a user defined importer object as defined in PEP 302 tries to load a module. + + First the find_module(fullName, path) is invoked to get a loader, then load_module(fullName) is invoked + + + + + Finds a user defined importer for the given path or returns null if no importer + handles this path. + + + + + Creates a new list with the data in the array and a size + the same as the length of the array. The array is held + onto and may be mutated in the future by the list. + + params array to use for lists storage + + + + Gets a reasonable size for the addition of two arrays. We round + to a power of two so that we usually have some extra space if + the resulting array gets added to. + + + + + Non-thread safe adder, should only be used by internal callers that + haven't yet exposed their list. + + + + + Compares the two specified keys + + + + + Supports __index__ on arbitrary types, also prevents __float__ + + + + + we need to lock both objects (or copy all of one's data w/ it's lock held, and + then compare, which is bad). Therefore we have a strong order for locking on + the two objects based upon the hash code or object identity in case of a collision + + + + + Summary description for ConstantValue. + + + + + Multiply two object[] arrays - slow version, we need to get the type, etc... + + + + + Multiply two object[] arrays - internal version used for objects backed by arrays + + + + + Add two arrays - internal versions for objects backed by arrays + + + + + + + + + + We override the behavior of equals, compare and hashcode to make + chars seem as much like strings as possible. In Python there is no + difference between these types. + + + + + Helper class that all custom type descriptor implementations call for + the bulk of their implementation. + + + + + Returns the digits for the format spec, no sign is included. + + + + + InstanceOps contains methods that get added to CLS types depending on what + methods and constructors they define. These have not been added directly to + PythonType since they need to be added conditionally. + + Possibilities include: + + __new__, one of 3 __new__ sets can be added: + DefaultNew - This is the __new__ used for a PythonType (list, dict, object, etc...) that + has only 1 default public constructor that takes no parameters. These types are + mutable types, and __new__ returns a new instance of the type, and __init__ can be used + to re-initialize the types. This __new__ allows an unlimited number of arguments to + be passed if a non-default __init__ is also defined. + + NonDefaultNew - This is used when a type has more than one constructor, or only has one + that takes more than zero parameters. This __new__ does not allow an arbitrary # of + extra arguments. + + DefaultNewCls - This is the default new used for CLS types that have only a single ctor + w/ an arbitray number of arguments. This constructor allows setting of properties + based upon an extra set of kw-args, e.g.: System.Windows.Forms.Button(Text='abc'). It + is only used on non-Python types. + + __init__: + For types that do not define __init__ we have an __init__ function that takes an + unlimited number of arguments and does nothing. All types share the same reference + to 1 instance of this. + + next: Defined when a type is an enumerator to expose the Python iter protocol. + + + repr: Added for types that override ToString + + get: added for types that implement IDescriptor + + + + + __dir__(self) -> Returns the list of members defined on a foreign IDynamicMetaObjectProvider. + + + + + Provides the implementation of __enter__ for objects which implement IDisposable. + + + + + Provides the implementation of __exit__ for objects which implement IDisposable. + + + + + Determines if a type member can be imported. This is used to treat static types like modules. + + + + + Implements __contains__ for types implementing IEnumerable of T. + + + + + Implements __contains__ for types implementing IEnumerable + + + + + Implements __contains__ for types implementing IEnumerable of T. + + + + + Implements __contains__ for types implementing IEnumerable + + + + + Implements __reduce_ex__ for .NET types which are serializable. This uses the .NET + serializer to get a string of raw data which can be serialized. + + + + + Contains Python extension methods that are added to object + + + + Types for which the pickle module has built-in support (from PEP 307 case 2) + + + + __class__, a custom slot so that it works for both objects and types. + + + + + Removes an attribute from the provided member + + + + + Returns the hash code of the given object + + + + + Gets the specified attribute from the object without running any custom lookup behavior + (__getattr__ and __getattribute__) + + + + + Initializes the object. The base class does nothing. + + + + + Initializes the object. The base class does nothing. + + + + + Initializes the object. The base class does nothing. + + + + + Creates a new instance of the type + + + + + Creates a new instance of the type + + + + + Creates a new instance of the type + + + + + Runs the pickle protocol + + + + + Runs the pickle protocol + + + + + Runs the pickle protocol + + + + + Returns the code representation of the object. The default implementation returns + a string which consists of the type and a unique numerical identifier. + + + + + Sets an attribute on the object without running any custom object defined behavior. + + + + + Returns the number of bytes of memory required to allocate the object. + + + + + Returns a friendly string representation of the object. + + + + + Return a dict that maps slot names to slot values, but only include slots that have been assigned to. + Looks up slots in base types as well as the current type. + + Sort-of Python equivalent (doesn't look up base slots, while the real code does): + return dict([(slot, getattr(self, slot)) for slot in type(self).__slots__ if hasattr(self, slot)]) + + Return null if the object has no __slots__, or empty dict if it has __slots__ but none are initialized. + + + + + Implements the default __reduce_ex__ method as specified by PEP 307 case 2 (new-style instance, protocol 0 or 1) + + + + + Returns the closest base class (in terms of MRO) that isn't defined in Python code + + + + + Implements the default __reduce_ex__ method as specified by PEP 307 case 3 (new-style instance, protocol 2) + + + + + Contains functions that are called directly from + generated code to perform low-level runtime functionality. + + + + + Creates a new dictionary extracting the keys and values from the + provided data array. Keys/values are adjacent in the array with + the value coming first. + + + + + Creates a new dictionary extracting the keys and values from the + provided data array. Keys/values are adjacent in the array with + the value coming first. + + + + + Wraps up all the semantics of multiplying sequences so that all of our sequences + don't duplicate the same logic. When multiplying sequences we need to deal with + only multiplying by valid sequence types (ints, not floats), support coercion + to integers if the type supports it, not multiplying by None, and getting the + right semantics for multiplying by negative numbers and 1 (w/ and w/o subclasses). + + This function assumes that it is only called for case where count is not implicitly + coercible to int so that check is skipped. + + + + + Supports calling of functions that require an explicit 'this' + Currently, we check if the function object implements the interface + that supports calling with 'this'. If not, the 'this' object is dropped + and a normal call is made. + + + + + Called from generated code emitted by NewTypeMaker. + + + + + Handles the descriptor protocol for user-defined objects that may implement __get__ + + + + + Handles the descriptor protocol for user-defined objects that may implement __set__ + + + + + Handles the descriptor protocol for user-defined objects that may implement __delete__ + + + + + Python runtime helper for raising assertions. Used by AssertStatement. + + Object representing the assertion message + + + + Python runtime helper to create instance of Python List object. + + New instance of List + + + + Python runtime helper to create a populated instance of Python List object. + + + + + Python runtime helper to create a populated instance of Python List object w/o + copying the array contents. + + + + + Python runtime helper to create a populated instance of Python List object. + + List is populated by arbitrary user defined object. + + + + + Python runtime helper to create an instance of Python List object. + + List has the initial provided capacity. + + + + + Python runtime helper to create an instance of Tuple + + + + + + + Python runtime helper to create an instance of Tuple + + + + + + Python Runtime Helper for enumerator unpacking (tuple assignments, ...) + Creates enumerator from the input parameter e, and then extracts + expected number of values, returning them as array + + If the input is a Python tuple returns the tuples underlying data array. Callers + should not mutate the resulting tuple. + + The code context of the AST getting enumerator values. + object to enumerate + expected number of objects to extract from the enumerator + + array of objects (.Lengh == expected) if exactly expected objects are in the enumerator. + Otherwise throws exception + + + + + Python runtime helper to create instance of Slice object + + Start of the slice. + End of the slice. + Step of the slice. + Slice + + + + Prints newline into default standard output + + + + + Prints newline into specified destination. Sets softspace property to false. + + + + + Prints value into default standard output with Python comma semantics. + + + + + Prints value into specified destination with Python comma semantics. + + + + + Called from generated code when we are supposed to print an expression value + + + + + Called from generated code for: + + import spam.eggs + + + + + Python helper method called from generated code for: + + import spam.eggs as ham + + + + + Called from generated code for: + + from spam import eggs1, eggs2 + + + + + Imports one element from the module in the context of: + + from module import a, b, c, d + + Called repeatedly for all elements being imported (a, b, c, d above) + + + + + Called from generated code for: + + from spam import * + + + + + Unqualified exec statement support. + A Python helper which will be called for the statement: + + exec code + + + + + Qualified exec statement support, + Python helper which will be called for the statement: + + exec code in globals [, locals ] + + + + + Called from generated code at the start of a catch block. + + + + + Get an exception tuple for the "current" exception. This is used for sys.exc_info() + + + + + Get an exception tuple for a given exception. This is like the inverse of MakeException. + + the code context + the exception to create a tuple for. + a tuple of (type, value, traceback) + This is called directly by the With statement so that it can get an exception tuple + in its own private except handler without disturbing the thread-wide sys.exc_info(). + + + + helper function for re-raised exceptions. + + + + + helper function for non-re-raise exceptions. + + type is the type of exception to throw or an instance. If it + is an instance then value should be null. + + If type is a type then value can either be an instance of type, + a Tuple, or a single value. This case is handled by EC.CreateThrowable. + + + + + Extracts an argument from either the dictionary or params + + + + + Creates a new array the values set to Uninitialized.Instance. The array + is large enough to hold for all of the slots allocated for the type and + its sub types. + + + + + Helper to determine if the value is a simple numeric type (int or big int or bool) - used for OldInstance + deprecated form of slicing. + + + + + Helper to determine if the type is a simple numeric type (int or big int or bool) - used for OldInstance + deprecated form of slicing. + + + + + Helper to determine if the type is a simple numeric type (int or big int or bool) but not a subclass + + + + + For slicing. Fixes up a BigInteger and returns an integer w/ the length of the + object added if the value is negative. + + + + + For slicing. Gets the length of the object, used to only get the length once. + + + + + Helper method for DynamicSite rules that check the version of their dynamic object + TODO - Remove this method for more direct field accesses + + + + + + + + Called from generated code. Gets a builtin function and the BuiltinFunctionData associated + with the object. Tests to see if the function is bound and has the same data for the generated + rule. + + + + + Convert object to a given type. This code is equivalent to NewTypeMaker.EmitConvertFromObject + except that it happens at runtime instead of compile time. + + + + + Provides access to AppDomain.DefineDynamicAssembly which cannot be called from a DynamicMethod + + + + + Generates a new delegate type. The last type in the array is the return type. + + + + + Generates a new delegate type. The last type in the array is the return type. + + + + + Provides the entry point for a compiled module. The stub exe calls into InitializeModule which + does the actual work of adding references and importing the main module. Upon completion it returns + the exit code that the program reported via SystemExit or 0. + + + + + Provides the entry point for a compiled module. The stub exe calls into InitializeModule which + does the actual work of adding references and importing the main module. Upon completion it returns + the exit code that the program reported via SystemExit or 0. + + + + + Called from generated code, helper to remove a name + + + + + Called from generated code, helper to do name lookup + + + + + Called from generated code, helper to do name assignment + + + + + Returns an IntPtr in the proper way to CPython - an int or a Python long + + + + + Create at TypeError exception for when Raise() can't create the exception requested. + + original type of exception requested + a TypeEror exception + + + + Gets a list of DynamicStackFrames for the given exception. These stack frames + can be programmatically inspected to understand the frames the exception crossed + through including Python frames. + + Dynamic stack frames are not preserved when an exception crosses an app domain + boundary. + + + + + Helper clas for calls to unicode(...). We generate code which checks if unicode + is str and if it is we redirect those calls to the unicode function defined on this + class. + + + + + ExtensibleString is the base class that is used for types the user defines + that derive from string. It carries along with it the string's value and + our converter recognizes it as a string. + + + + + StringOps is the static class that contains the methods defined on strings, i.e. 'abc' + + Here we define all of the methods that a Python user would see when doing dir('abc'). + If the user is running in a CLS aware context they will also see all of the methods + defined in the CLS System.String type. + + + + + Returns a copy of this string converted to uppercase + + + + + return true if self is a titlecased string and there is at least one + character in self; also, uppercase characters may only follow uncased + characters (e.g. whitespace) and lowercase characters only cased ones. + return false otherwise. + + + + + Return a string which is the concatenation of the strings + in the sequence seq. The separator between elements is the + string providing this method + + + + + Replaces each replacement field in the string with the provided arguments. + + replacement_field = "{" field_name ["!" conversion] [":" format_spec] "}" + field_name = (identifier | integer) ("." identifier | "[" element_index "]")* + + format_spec: [[fill]align][sign][#][0][width][,][.precision][type] + + Conversion can be 'r' for repr or 's' for string. + + + + + Replaces each replacement field in the string with the provided arguments. + + replacement_field = "{" field_name ["!" conversion] [":" format_spec] "}" + field_name = (identifier | integer) ("." identifier | "[" element_index "]")* + + format_spec: [[fill]align][sign][#][0][width][.precision][type] + + Conversion can be 'r' for repr or 's' for string. + + + + + Gets the starting offset checking to see if the incoming bytes already include a preamble. + + + + When encoding or decoding strings if an error occurs CPython supports several different + behaviors, in addition it supports user-extensible behaviors as well. For the default + behavior we're ok - both of us support throwing and replacing. For custom behaviors + we define a single fallback for decoding and encoding that calls the python function to do + the replacement. + + When we do the replacement we call the provided handler w/ a UnicodeEncodeError or UnicodeDecodeError + object which contains: + encoding (string, the encoding the user requested) + end (the end of the invalid characters) + object (the original string being decoded) + reason (the error, e.g. 'unexpected byte code', not sure of others) + start (the start of the invalid sequence) + + The decoder returns a tuple of (unicode, int) where unicode is the replacement string + and int is an index where encoding should continue. + + + + Indexer for generic parameter resolution. We bind to one of the generic versions + available in this type collision. A user can also do someType[()] to force to + bind to the non-generic version, but we will always present the non-generic version + when no bindings are available. + + + + + Object.ToString() displays the CLI type name. But we want to display the class name (e.g. + '<foo object at 0x000000000000002C>' unless we've overridden __repr__ but not __str__ in + which case we'll display the result of __repr__. + + + + + Provides a debug view for user defined types. This class is declared as public + because it is referred to from generated code. You should not use this class. + + + + + A DynamicMetaObject which is just used to support custom conversions to COM. + + + + + A marker interface so we can recognize and access sequence members on our array objects. + + + + + List of unary operators which we have sites for to enable fast dispatch that + doesn't collide with other operators. + + + + + Sets the mode to text or binary. Returns true if previously set to text, false if previously set to binary. + + + + + Truncates the file to the current length as indicated by tell(). + + + + + Truncates the file to the specified length. + + + + + + Provides storage of IronPython specific data in the DLR Scope ScopeExtension. + + This enables IronPython to track code compilation flags such as from __future__ + flags and import clr flags across multiple executions of user-provided scopes. + + + + + Provides human readable names for how Python maps the various DLR NarrowingLevel's. + + + + + No narrowing conversions are performed + + + + + Double/Single to Decimal + PythonTuple to Array + Generic conversions + BigInteger to Int64 + + + + + Numeric conversions excluding from floating point values + Boolean conversions + Delegate conversions + Enumeration conversions + + + + + Enables Python protocol conversions (__int__, etc...) + + + + + Provides dictionary based storage which is backed by a Scope object. + + + + + Mutable set class + + + + + Appends an IEnumerable to an existing set + + + + + Immutable set class + + + + + Iterator over sets + + + + + Gets the indices for the deprecated __getslice__, __setslice__, __delslice__ functions + + This form is deprecated in favor of using __getitem__ w/ a slice object as an index. This + form also has subtly different mechanisms for fixing the slice index before calling the function. + + If an index is negative and __len__ is not defined on the object than an AttributeError + is raised. + + + + + StringFormatter provides Python's % style string formatting services. + + + + + Read a possible mapping key for %(key)s. + + The key name enclosed between the '%(key)s', + or null if there are no paranthesis such as '%s'. + + + + AppendBase appends an integer at the specified radix doing all the + special forms for Python. We have a copy and paste version of this + for BigInteger below that should be kept in sync. + + + + + BigInteger version of AppendBase. Should be kept in sync w/ AppendBase + + + + + public class to get optimized + + + + + Returns detailed call statistics. Not implemented in IronPython and always returns None. + + + + + Handles output of the expression statement. + Prints the value and sets the __builtin__._ + + + + + Provides a CustomTracker which handles special fields which have custom + behavior on get/set. + + + + + Provides custom, versioned, dictionary access for instances. Used for both + new-style and old-style instances. + + Each class can allocate a version for instance storage using the + CustomInstanceDictionaryStorage.AllocateInstance method. The version allocated + is dependent upon the names which are likely to appear in the instance + dictionary. Currently these names are calculated by collecting the names + that are assigned to during the __init__ method and combining these with + all such names in the types MRO. + + When creating the dictionary for storing instance values the class can then create + a PythonDictionary backed by a CustomInstanceDictionaryStorage with it's + version. When doing a get/set optimized code can then be produced that + verifies we have CustomInstanceDictionaryStorage and it has the + correct version. If we have a matching dictionary then gets/sets can turn + into simple array accesses rather than dictionary gets/sets. For programs + which access a large number of instance variables this can dramatically + speed up the program. + + TODO: Should we attempt to unify all versions which share the same keys? + + + + + Interface used for things which can convert to delegates w/o code gen. Currently + this is just non-overloaded builtin functions and bound builtin functions. Avoiding + the code gen is not only nice for compilation but it also enables delegates to be added + in C# and removed in Python. + + + + + Represents a set of attributes that different functions can have. + + + + No flags have been set + + + This is a function w/ no instance pointer + + + This is a method that requires an instance + + + Built-in functions can encapsulate both methods and functions, in which case both bits are set + + + True is the function/method should be visible from pure-Python code + + + True if this is a __r*__ method for a CLS overloaded operator method + + + + This method represents a binary operator method for a CLS overloaded operator method. + + Being a binary operator causes the following special behaviors to kick in: + A failed binding at call time returns NotImplemented instead of raising an exception + A reversed operator will automatically be created if: + 1. The parameters are both of the instance type + 2. The parameters are in reversed order (other, this) + + This enables simple .NET operator methods to be mapped into the Python semantics. + + + + + A method declared on a built-in module + + + + + OperatorMapping provides a mapping from DLR operators to their associated .NET methods. + + + + + Given an operator returns the OperatorMapping associated with the operator or null + + + + + The operator the OperatorMapping provides info for. + + + + + The primary method name associated with the method. This method name is + usally in the form of op_Operator (e.g. op_Addition). + + + + + The secondary method name associated with the method. This method name is + usually a standard .NET method name with pascal casing (e.g. Add). + + + + + The return type that must match for the alternate operator to be valid. + + This is available alternate operators don't have special names and therefore + could be confused for a normal method which isn't fulfilling the contract. + + + + + This helper type lets us build a fake ParameterInfo object with a specific type and name + to pass along to methods that expect ParameterInfos. This is currently found useful + for the NewTypeMaker code and may be useful in other situations as well. + + + + + Cached CallSites. User types are cached on the PythonType and System types are cached on the + PythonContext to avoid cross-runtime contamination due to the binder on the site. + + + + + Represents a PythonType. Instances of PythonType are created via PythonTypeBuilder. + + + + + Used in copy_reg which is the only consumer of __flags__ in the standard library. + + Set if the type is user defined + + + + + Set if the type has __abstractmethods__ defined + + + + + Implements fast binding for user defined types. This ensures that common highly dynamic + scenarios will run fast (for instance creating new types repeatedly and only creating a limited + number of instances of them). It also gives better code sharing amongst different subclasses + of the same types and improved startup time due to reduced code generation. + + + + + Provides delegates that will invoke a parameterless type ctor. The first key provides + the dictionary for a specific type, the 2nd key provides the delegate for a specific + call site type used in conjunction w/ our IFastInvokable implementation. + + + + + Shared built-in functions for creating instances of user defined types. Because all + types w/ the same UnderlyingSystemType share the same constructors these can be + shared across multiple types. + + + + + Creates a new type for a user defined type. The name, base classes (a tuple of type + objects), and a dictionary of members is provided. + + + + + Creates a new type for a user defined type. The name, base classes (a tuple of type + objects), and a dictionary of members is provided. + + + + + Creates a new PythonType object which is backed by the specified .NET type for + storage. The type is considered a system type which can not be modified + by the user. + + + + + + Creates a new PythonType which is a subclass of the specified PythonType. + + Used for runtime defined new-style classes which require multiple inheritance. The + primary example of this is the exception system. + + + + + Creates a new PythonType which is a subclass of the specified PythonTypes. + + Used for runtime defined new-style classes which require multiple inheritance. The + primary example of this is the exception system. + + + + + Creates a new PythonType which is a subclass of the specified PythonTypes. + + Used for runtime defined new-style classes which require multiple inheritance. The + primary example of this is the exception system. + + + + + Creates a new PythonType which is a subclass of the specified PythonType. + + Used for runtime defined new-style classes which require multiple inheritance. The + primary example of this is the exception system. + + + + + Creates a new PythonType which is a subclass of the specified PythonTypes. + + Used for runtime defined new-style classes which require multiple inheritance. The + primary example of this is the exception system. + + + + + Creates a new PythonType which is a subclass of the specified PythonTypes. + + Used for runtime defined new-style classes which require multiple inheritance. The + primary example of this is the exception system. + + + + + Creates a new PythonType object which represents an Old-style class. + + + + + Returns true if the specified object is an instance of this type. + + + + + Gets the dynamic type that corresponds with the provided static type. + + Returns null if no type is available. TODO: In the future this will + always return a PythonType created by the DLR. + + + + + + + Sets the python type that corresponds with the provided static type. + + This is used for built-in types which have a metaclass. Currently + only used by ctypes. + + + + + Allocates the storage for the instance running the .NET constructor. This provides + the creation functionality for __new__ implementations. + + + + + Allocates the storage for the instance running the .NET constructor. This provides + the creation functionality for __new__ implementations. + + + + + Allocates the storage for the instance running the .NET constructor. This provides + the creation functionality for __new__ implementations. + + + + + Allocates the storage for the instance running the .NET constructor. This provides + the creation functionality for __new__ implementations. + + + + + Allocates the storage for the instance running the .NET constructor. This provides + the creation functionality for __new__ implementations. + + + + + Allocates the storage for the instance running the .NET constructor. This provides + the creation functionality for __new__ implementations. + + + + + Returns true if this type is a subclass of other + + + + + Looks up a slot on the dynamic type + + + + + Searches the resolution order for a slot matching by name + + + + + Searches the resolution order for a slot matching by name. + + Includes searching for methods in old-style classes + + + + + Internal helper to add a new slot to the type + + + + + + + Gets a value from a dynamic type and any sub-types. Values are stored in slots (which serve as a level of + indirection). This searches the types resolution order and returns the first slot that + contains the value. + + + + + Attempts to lookup a member w/o using the customizer. Equivelent to object.__getattribute__ + but it doens't throw an exception. + + + + + + Gets a value from a dynamic type and any sub-types. Values are stored in slots (which serve as a level of + indirection). This searches the types resolution order and returns the first slot that + contains the value. + + + + + Attempts to lookup a member w/o using the customizer. + + + + + + Sets a value on an instance. If a slot is available in the most derived type the slot + is set there, otherwise the value is stored directly in the instance. + + + + + Attempst to set a value w/o going through the customizer. + + This enables languages to provide the "base" implementation for setting attributes + so that the customizer can call back here. + + + + + Returns a list of all slot names for the type and any subtypes. + + The context that is doing the inquiry of InvariantContext.Instance. + + + + Returns a list of all slot names for the type, any subtypes, and the instance. + + The context that is doing the inquiry of InvariantContext.Instance. + the instance to get instance members from, or null. + + + + Adds members from a user defined type. + + + + + Adds members from a user defined type instance + + + + + Gets the .NET type which is used for instances of the Python type. + + When overridden by a metaclass enables a customization of the .NET type which + is used for instances of the Python type. Meta-classes can construct custom + types at runtime which include new .NET methods, fields, custom attributes or + other features to better interoperate with .NET. + + + + + Initializes a PythonType that represents a standard .NET type. The same .NET type + can be shared with the Python type system. For example object, string, int, + etc... are all the same types. + + + + + Creates a __new__ method for the type. If the type defines interesting constructors + then the __new__ method will call that. Otherwise if it has only a single argless + + + + + This will return a unique integer for every version of every type in the system. + This means that DynamicSite code can generate a check to see if it has the correct + PythonType and version with a single integer compare. + + TODO - This method and related code should fail gracefully on overflow. + + + + + Internal helper function to add a subtype + + + + + Returns a CLR WeakReference object to this PythonType that can be shared + between anyone who needs a weak reference to the type. + + + + + Gets the name of the dynamic type + + + + + Gets the resolution order used for attribute lookup + + + + + Gets the underlying system type that is backing this type. All instances of this + type are an instance of the underlying system type. + + + + + Gets the extension type for this type. The extension type provides + a .NET type which can be inherited from to extend sealed classes + or value types which Python allows inheritance from. + + + + + Gets the base types from which this type inherits. + + + + + True if the type is a system type. A system type is a type which represents an + underlying .NET type and not a subtype of one of these types. + + + + + Gets a list of weak references to all the subtypes of this class. May return null + if there are no subtypes of the class. + + + + + Base class for doing fast type invoke binding. Subclasses are created using + reflection once during the binding. The subclasses can then proceed to do + the binding w/o using reflection. Otherwise we'd have lots more reflection + calls which would slow the binding up. + + + + + Gets or creates delegate for calling the constructor function. + + + + + The type has a ctor which does not accept PythonTypes. This is used + for user defined types which implement __clrtype__ + + + + + Used when a type overrides __new__ with a Python function or other object + that can return an arbitrary value. If the return value is not the same type + as the type which had __new__ then we need to lookup __init__ on the type + and invoke it. Also handles initialization for finalization when __del__ + is defined for the same reasons. + + + + + target is the newly initialized value. + args are the arguments to be passed to __init__ + + + + + Couples a MemberGroup and the name which produces the member group together + + + + + Represents an ops-extension which adds a new slot. The slot can have arbitrary + get/set behavior above and beyond normal .NET methods or properties. This is + typically in regards to how it processes access from instances or subtypes. + + + + + Provides a slot object for the dictionary to allow setting of the dictionary. + + + + + Calculates the method resolution order for a Python class + the rules are: + If A is a subtype of B, then A has precedence (A > B) + If C appears before D in the list of bases then C > D + If E > F in one __mro__ then E > F in all __mro__'s for our subtype + + class A(object): pass + class B(object): pass + class C(B): pass + class N(A,B,C): pass # illegal + + This is because: + C.__mro__ == (C, B, object) + N.__mro__ == (N, A, B, C, object) + which would conflict, but: + + N(B,A) is ok (N, B, a, object) + N(C, B, A) is ok (N, C, B, A, object) + + Calculates a C3 MRO as described in "The Python 2.3 Method Resolution Order" + plus support for old-style classes. + + We build up a list of our base classes MRO's plus our base classes themselves. + We go through the list in order. Look at the 1st class in the current list, and + if it's not the non-first class in any other list then remove it from all the lists + and append it to the mro. Otherwise continue to the next list. If all the classes at + the start are no-good then the MRO is bad and we throw. + + For old-style classes if the old-style class is the only one in the list of bases add + it as a depth-first old-style MRO, otherwise compute a new-style mro for all the classes + and use that. + + + + + + + + + Returns the dictionary used to store state for this object + + + + + Python module. Stores classes, functions, and data. Usually a module + is created by importing a file or package from disk. But a module can also + be directly created by calling the module type and providing a name or + optionally a documentation string. + + + + + Creates a new module backed by a Scope. Used for creating modules for foreign Scope's. + + + + + Creates a new PythonModule with the specified dictionary. + + Used for creating modules for builtin modules which don't have any code associated with them. + + + + + Represents a member of a user-defined type which defines __slots__. The names listed in + __slots__ have storage allocated for them with the type and provide fast get/set access. + + + + + Gets the index into the object array to be used for the slot storage. + + + + + Helpers for interacting w/ .NET types. This includes: + + Member resolution via GetMember/GetMembers. This performs a member lookup which includes the registered + extension types in the PythonBinder. Internally the class has many MemberResolver's which provide + the various resolution behaviors. + + Cached member access - this is via static classes such as Object and provides various MemberInfo's so we're + not constantly looking up via reflection. + + + + list of resolvers which we run to resolve items + + + + Gets the statically known member from the type with the specific name. Searches the entire type hierarchy to find the specified member. + + + + + Gets all the statically known members from the specified type. Searches the entire type hierarchy to get all possible members. + + The result may include multiple resolution. It is the callers responsibility to only treat the 1st one by name as existing. + + + + + Gets the statically known member from the type with the specific name. Searches only the specified type to find the member. + + + + + Gets all the statically known members from the specified type. Searches only the specified type to find the members. + + The result may include multiple resolution. It is the callers responsibility to only treat the 1st one by name as existing. + + + + + Creates the resolver table which includes all the possible resolutions. + + + + + + Provides a resolution for __str__. + + + + + Provides a resolution for __repr__ + + + + + Helper to see if the type explicitly overrides the method. This ignores members + defined on object. + + + + + Provides a resolution for __hash__, first looking for IStructuralEquatable.GetHashCode, + then IValueEquality.GetValueHashCode. + + + + + Provides a resolution for __new__. For standard .NET types __new__ resolves to their + constructor. For Python types they inherit __new__ from their base class. + + TODO: Can we just always fallback to object.__new__? If not why not? + + + + + Provides a resolution for next + + + + + Provides a resolution for __len__ + + + + + Provides a resolution for __iter__ + + + + + Looks for an Equals overload defined on the type and if one is present binds __ne__ to an + InstanceOps helper. + + + + + Provides an implementation of __contains__. We can pull contains from: + ICollection of T which defines Contains directly + IList which defines Contains directly + IDictionary which defines Contains directly + IDictionary of K,V which defines Contains directly + IEnumerable of K which we have an InstaceOps helper for + IEnumerable which we have an instance ops helper for + IEnumerator of K which we have an InstanceOps helper for + IEnumerator which we have an instance ops helper for + + String is ignored here because it defines __contains__ via extension methods already. + + The lookup is well ordered and not dependent upon the order of values returned by reflection. + + + + + Helper for IEnumerable/IEnumerator __contains__ + + + + + Primary worker for getting the member(s) associated with a single name. Can be called with different MemberBinder's to alter the + scope of the search. + + + + + Primary worker for returning a list of all members in a type. Can be called with different MemberBinder's to alter the scope + of the search. + + + + + Helper to get a MemberGroup for methods declared on InstanceOps + + + + + Helper to get the proper typecasting method, according to the following precedence rules: + + 1. Strongest (most specific) declaring type + 2. Strongest (most specific) parameter type + 3. Type of conversion + i. Implicit + ii. Explicit + 4. Return type (order specified in toTypes) + + + + + Helper for creating a typecast resolver + + + + + Helper for creating __getitem__/__setitem__ resolvers + + false for a getter, true for a setter + + + + Filters out methods which are present on standard .NET types but shouldn't be there in Python + + + + + When private binding is enabled we can have a collision between the private Event + and private field backing the event. We filter this out and favor the event. + + This matches the v1.0 behavior of private binding. + + + + + Filters down to include only protected methods + + + + + If an operator is a reverisble operator (e.g. addition) then we need to filter down to just the forward/reverse + versions of the .NET method. For example consider: + + String.op_Multiplication(int, string) + String.op_Multiplication(string, int) + + If this method were defined on string it defines that you can do: + 2 * 'abc' + or: + 'abc' * 2 + + either of which will produce 'abcabc'. The 1st form is considered the reverse form because it is declared on string + but takes a non-string for the 1st argument. The 2nd is considered the forward form because it takes a string as the + 1st argument. + + When dynamically dispatching for 2 * 'abc' we'll first try __mul__ on int, which will fail with a string argument. Then we'll try + __rmul__ on a string which will succeed and dispatch to the (int, string) overload. + + For multiplication in this case it's not too interesting because it's commutative. For addition this might be more interesting + if, for example, we had unicode and ASCII strings. In that case Unicode strings would define addition taking both unicode and + ASCII strings in both forms. + + + + + Checks to see if the parameter type and the declaring type are compatible to determine + if an operator is forward or reverse. + + + + + Checks to see if this is an operator method which Python recognizes. For example + op_Comma is not recognized by Python and therefore should exposed to the user as + a method that is callable by name. + + + + + Provides a resolution for __complex__ + + + + + Provides a resolution for __float__ + + + + + Provides a resolution for __int__ + + + + + Provides a resolution for __long__ + + + + + Provides a resolution for __getitem__ + + + + + Provides a resolution for __setitem__ + + + + + Abstract class used for resolving members. This provides two methods of member look. The first is looking + up a single member by name. The other is getting all of the members. + + There are various subclasses of this which have different methods of resolving the members. The primary + function of the resolvers are to provide the name->value lookup. They also need to provide a simple name + enumerator. The enumerator is kept simple because it's allowed to return duplicate names as well as return + names of members that don't exist. The base MemberResolver will then verify their existance as well as + filter duplicates. + + + + + Looks up an individual member and returns a MemberGroup with the given members. + + + + + Returns a list of members that exist on the type. The ResolvedMember structure indicates both + the name and provides the MemberGroup. + + + + + Returns a list of possible members which could exist. ResolveMember needs to be called to verify their existance. Duplicate + names can also be returned. + + + + + One off resolver for various special methods which are known by name. A delegate is provided to provide the actual member which + will be resolved. + + + + + Standard resolver for looking up .NET members. Uses reflection to get the members by name. + + + + + Resolves methods mapped to __eq__ and __ne__ from: + 1. IStructuralEquatable.Equals + 2. IValueEquality.Equals (CLR2 only) + + + + + Resolves methods mapped to __gt__, __lt__, __ge__, __le__, as well as providing an alternate resolution + for __eq__ and __ne__, from the comparable type's CompareTo method. + + This should be run after the EqualityResolver. + + + + + Resolves methods mapped to __*__ methods automatically from the .NET operator. + + + + + Filters alternative methods out that don't match the expected signature and therefore + are just sharing a common method name. + + + + + Removes Object.Equals methods as we never return these for PythonOperationKind. + + + + + Provides bindings to private members when that global option is enabled. + + + + + Provides resolutions for protected members that haven't yet been + subclassed by NewTypeMaker. + + + + + Base class used for resolving a name into a member on the type. + + + + + Gets an instance op method for the given type and name. + + Instance ops methods appaer on the base most class that's required to expose it. So + if we have: Array[int], Array, object we'd only add an instance op method to Array and + Array[int] inherits it. It's obviously not on object because if it was there we'd just + put the method in ObjectOps. + + Therefore the different binders expose this at the appropriate times. + + + + + MemberBinder which searches the entire type hierarchy and their extension types to find a member. + + + + + MemberBinder which searches only the current type and it's extension types to find a member. + + + + + BuiltinFunction represents any standard CLR function exposed to Python. + This is used for both methods on standard Python types such as list or tuple + and for methods from arbitrary .NET assemblies. + + All calls are made through the optimizedTarget which is created lazily. + + TODO: Back BuiltinFunction's by MethodGroup's. + + + + + Creates a new builtin function for a static .NET function. This is used for module methods + and well-known __new__ methods. + + + + + Creates a built-in function for a .NET method declared on a type. + + + + + Creates a bound built-in function. The instance may be null for built-in functions + accessed for None. + + + + + Returns a BuiltinFunction bound to the provided type arguments. Returns null if the binding + cannot be performed. + + + + + Returns a descriptor for the built-in function if one is + neededed + + + + + Makes a test for the built-in function against the private _data + which is unique per built-in function. + + + + + Helper for generating the call to a builtin function. This is used for calls from built-in method + descriptors and built-in functions w/ and w/o a bound instance. + + This provides all sorts of common checks on top of the call while the caller provides a delegate + to do the actual call. The common checks include: + check for generic-only methods + reversed operator support + transforming arguments so the default binder can understand them (currently user defined mapping types to PythonDictionary) + returning NotImplemented from binary operators + Warning when calling certain built-in functions + + + The call binder we're doing the call for + An expression which points to the code context + the meta object for the built in function + true if we're calling with an instance + The arguments being passed to the function + A restriction for the built-in function, method desc, etc... + A delegate to perform the actual call to the method. + + + + Gets the target methods that we'll be calling. + + + + + True if the method should be visible to non-CLS opt-in callers + + + + + Provides (for reflected methods) a mapping from a signature to the exact target + which takes this signature. + signature with syntax like the following: + someClass.SomeMethod.Overloads[str, int]("Foo", 123) + + + + + Gets the overload dictionary for the logical function. These overloads + are never bound to an instance. + + + + + Returns the instance used for binding. This differs on module functions implemented + using instance methods so the built-in functions there don't expose the instance. + + + + + A custom built-in function which supports indexing + + + + + Use indexing on generic methods to provide a new reflected method with targets bound with + the supplied type arguments. + + + + + The unbound representation of an event property + + + + + BoundEvent is the object that gets returned when the user gets an event object. An + BoundEvent tracks where the event was received from and is used to verify we get + a proper add when dealing w/ statics events. + + + + + Represents a ReflectedProperty created for an extension method. Logically the property is an + instance property but the method implementing it is static. + + + + + Base class for properties backed by methods. These include our slot properties, + indexers, and normal properties. This class provides the storage of these as well + as the storage of our optimized getter/setter methods, documentation for the property, + etc... + + + + + Convenience function for users to call directly + + + + + This function can be used to set a field on a value type without emitting a warning. Otherwise it is provided only to have symmetry with properties which have GetValue/SetValue for supporting explicitly implemented interfaces. + + Setting fields on value types usually warns because it can silently fail to update the value you expect. For example consider this example where Point is a value type with the public fields X and Y: + + arr = System.Array.CreateInstance(Point, 10) + arr[0].X = 42 + print arr[0].X + + prints 0. This is because reading the value from the array creates a copy of the value. Setting the value then mutates the copy and the array does not get updated. The same problem exists when accessing members of a class. + + + + + Provides access to non-default .NET indexers (aka properties w/ parameters). + + C# doesn't support these, but both COM and VB.NET do. The types dictionary + gets populated w/a ReflectedGetterSetter indexer which is a descriptor. Getting + the descriptor returns a bound indexer. The bound indexer supports indexing. + We support multiple indexer parameters via expandable tuples. + + + + + Convenience function for users to call directly + + + + + Convenience function for users to call directly + + + + + True if generating code for gets can result in more optimal accesses. + + + + + single finalizable instance used to track and deliver all the + callbacks for a single object that has been weakly referenced by + one or more references and proxies. The reference to this object + is held in objects that implement IWeakReferenceable. + + + + + Finalizable object used to hook up finalization calls for OldInstances. + + We create one of these each time an object w/ a finalizer gets created. The + only reference to this object is the instance so when that goes out of context + this does as well and this will get finalized. + + + + + Marks a method/field/property as being a wrapper descriptor. A wrapper desriptor + is a member defined on PythonType but is available both for type and other + instances of type. For example type.__bases__. + + + + diff --git a/Reference/System.Threading.dll b/Reference/System.Threading.dll new file mode 100644 index 000000000..9c89a8572 Binary files /dev/null and b/Reference/System.Threading.dll differ diff --git a/Reference/log4net.dll b/Reference/log4net.dll new file mode 100644 index 000000000..c3ced3548 Binary files /dev/null and b/Reference/log4net.dll differ diff --git a/Reference/nunit.framework.dll b/Reference/nunit.framework.dll new file mode 100644 index 000000000..07e4c6eae Binary files /dev/null and b/Reference/nunit.framework.dll differ diff --git a/SocketBase/AppServer.cs b/SocketBase/AppServer.cs new file mode 100644 index 000000000..17d6c4401 --- /dev/null +++ b/SocketBase/AppServer.cs @@ -0,0 +1,377 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Reflection; +using System.Security.Authentication; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using SuperSocket.Common; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Config; +using SuperSocket.SocketBase.Protocol; +using SuperSocket.SocketBase.Security; + +namespace SuperSocket.SocketBase +{ + /// + /// AppServer basic class + /// + public abstract class AppServer : AppServer + { + /// + /// Initializes a new instance of the class. + /// + public AppServer() + : base() + { + + } + + /// + /// Initializes a new instance of the class. + /// + /// The request filter factory. + public AppServer(IRequestFilterFactory requestFilterFactory) + : base(requestFilterFactory) + { + + } + } + + /// + /// AppServer basic class + /// + /// The type of the app session. + public abstract class AppServer : AppServer + where TAppSession : AppSession, IAppSession, new() + { + /// + /// Initializes a new instance of the class. + /// + public AppServer() + : base(new CommandLineRequestFilterFactory()) + { + + } + + /// + /// Initializes a new instance of the class. + /// + /// The request filter factory. + public AppServer(IRequestFilterFactory requestFilterFactory) + : base(requestFilterFactory) + { + + } + } + + + /// + /// AppServer basic class + /// + /// The type of the app session. + /// The type of the request info. + public abstract class AppServer : AppServerBase, IPerformanceDataSource + where TRequestInfo : class, IRequestInfo + where TAppSession : AppSession, IAppSession, new() + { + /// + /// Initializes a new instance of the class. + /// + public AppServer() + : base() + { + + } + + /// + /// Initializes a new instance of the class. + /// + /// The protocol. + protected AppServer(IRequestFilterFactory protocol) + : base(protocol) + { + + } + + /// + /// Starts this AppServer instance. + /// + /// + public override bool Start() + { + if (!base.Start()) + return false; + + if (!Config.DisableSessionSnapshot) + StartSessionSnapshotTimer(); + + if (Config.ClearIdleSession) + StartClearSessionTimer(); + + return true; + } + + private ConcurrentDictionary m_SessionDict = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); + + /// + /// Registers the session into the session container. + /// + /// The session ID. + /// The app session. + /// + protected override bool RegisterSession(string sessionID, TAppSession appSession) + { + if (m_SessionDict.TryAdd(sessionID, appSession)) + return true; + + if (Logger.IsErrorEnabled) + Logger.Error(appSession, "The session is refused because the it's ID already exists!"); + + return false; + } + + /// + /// Gets the app session by ID. + /// + /// The session ID. + /// + public override TAppSession GetAppSessionByID(string sessionID) + { + if (string.IsNullOrEmpty(sessionID)) + return NullAppSession; + + TAppSession targetSession; + m_SessionDict.TryGetValue(sessionID, out targetSession); + return targetSession; + } + + /// + /// Called when [socket session closed]. + /// + /// The session. + /// The reason. + protected override void OnSessionClosed(TAppSession session, CloseReason reason) + { + string sessionID = session.SessionID; + + if (!string.IsNullOrEmpty(sessionID)) + { + TAppSession removedSession; + if (!m_SessionDict.TryRemove(sessionID, out removedSession)) + { + if (Logger.IsErrorEnabled) + Logger.Error(session, "Failed to remove this session, Because it has't been in session container!"); + } + } + + base.OnSessionClosed(session, reason); + } + + /// + /// Gets the total session count. + /// + public override int SessionCount + { + get + { + return m_SessionDict.Count; + } + } + + #region Clear idle sessions + + private System.Threading.Timer m_ClearIdleSessionTimer = null; + + private void StartClearSessionTimer() + { + int interval = Config.ClearIdleSessionInterval * 1000;//in milliseconds + m_ClearIdleSessionTimer = new System.Threading.Timer(ClearIdleSession, new object(), interval, interval); + } + + /// + /// Clears the idle session. + /// + /// The state. + private void ClearIdleSession(object state) + { + if (Monitor.TryEnter(state)) + { + try + { + DateTime now = DateTime.Now; + DateTime timeOut = now.AddSeconds(0 - Config.IdleSessionTimeOut); + + var timeOutSessions = SessionSource.Where(s => s.Value.LastActiveTime <= timeOut).Select(s => s.Value); + System.Threading.Tasks.Parallel.ForEach(timeOutSessions, s => + { + if (Logger.IsInfoEnabled) + Logger.Info(s, string.Format("The session will be closed for {0} timeout, the session start time: {1}, last active time: {2}!", now.Subtract(s.LastActiveTime).TotalSeconds, s.StartTime, s.LastActiveTime)); + s.Close(CloseReason.TimeOut); + }); + } + catch (Exception e) + { + if(Logger.IsErrorEnabled) + Logger.Error("Clear idle session error!", e); + } + finally + { + Monitor.Exit(state); + } + } + } + + private KeyValuePair[] SessionSource + { + get + { + if (Config.DisableSessionSnapshot) + return m_SessionDict.ToArray(); + else + return m_SessionsSnapshot; + } + } + + #endregion + + #region Take session snapshot + + private System.Threading.Timer m_SessionSnapshotTimer = null; + + private KeyValuePair[] m_SessionsSnapshot = new KeyValuePair[0]; + + private void StartSessionSnapshotTimer() + { + int interval = Math.Max(Config.SessionSnapshotInterval, 1) * 1000;//in milliseconds + m_SessionSnapshotTimer = new System.Threading.Timer(TakeSessionSnapshot, new object(), interval, interval); + } + + private void TakeSessionSnapshot(object state) + { + if (Monitor.TryEnter(state)) + { + Interlocked.Exchange(ref m_SessionsSnapshot, m_SessionDict.ToArray()); + Monitor.Exit(state); + } + } + + #endregion + + #region Search session utils + + /// + /// Gets the matched sessions from sessions snapshot. + /// + /// The prediction critera. + /// + public override IEnumerable GetSessions(Func critera) + { + return SessionSource.Select(p => p.Value).Where(critera); + } + + /// + /// Gets all sessions in sessions snapshot. + /// + /// + public override IEnumerable GetAllSessions() + { + return SessionSource.Select(p => p.Value); + } + + #endregion + + #region Performance logging + + private PerformanceData m_PerformanceData = new PerformanceData(); + + /// + /// Collects the performance data. + /// + /// The global perf data. + /// + public PerformanceData CollectPerformanceData(GlobalPerformanceData globalPerfData) + { + m_PerformanceData.PushRecord(new PerformanceRecord + { + TotalConnections = m_SessionDict.Count, + TotalHandledRequests = TotalHandledRequests + }); + + //User can process the performance data by self + this.AsyncRun(() => OnPerformanceDataCollected(globalPerfData, m_PerformanceData), e => Logger.Error(e)); + + return m_PerformanceData; + } + + /// + /// Called when [performance data collected], you can override this method to get collected performance data + /// + /// The global perf data. + /// The performance data. + protected virtual void OnPerformanceDataCollected(GlobalPerformanceData globalPerfData, PerformanceData performanceData) + { + + } + + #endregion + + #region IDisposable Members + + /// + /// Releases unmanaged and - optionally - managed resources + /// + /// true to release both managed and unmanaged resources; false to release only unmanaged resources. + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + + if (disposing) + { + if (m_SessionSnapshotTimer != null) + { + m_SessionSnapshotTimer.Change(Timeout.Infinite, Timeout.Infinite); + m_SessionSnapshotTimer.Dispose(); + m_SessionSnapshotTimer = null; + } + + if (m_ClearIdleSessionTimer != null) + { + m_ClearIdleSessionTimer.Change(Timeout.Infinite, Timeout.Infinite); + m_ClearIdleSessionTimer.Dispose(); + m_ClearIdleSessionTimer = null; + } + + var sessions = m_SessionDict.ToArray(); + + if(sessions.Length > 0) + { + var tasks = new Task[sessions.Length]; + + for(var i = 0; i < tasks.Length; i++) + { + tasks[i] = Task.Factory.StartNew((s) => + { + var session = s as TAppSession; + + if (session != null) + { + session.Close(CloseReason.ServerShutdown); + } + + }, sessions[i].Value); + } + + Task.WaitAll(tasks); + } + } + } + + #endregion + } +} diff --git a/SocketBase/AppServerBase.cs b/SocketBase/AppServerBase.cs new file mode 100644 index 000000000..eb2999d3b --- /dev/null +++ b/SocketBase/AppServerBase.cs @@ -0,0 +1,1214 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Security.Authentication; +using System.Security.Cryptography.X509Certificates; +using System.Threading; +using SuperSocket.Common; +using SuperSocket.SocketBase.Logging; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Config; +using SuperSocket.SocketBase.Protocol; +using SuperSocket.SocketBase.Security; +using SuperSocket.SocketBase.Provider; + +namespace SuperSocket.SocketBase +{ + /// + /// AppServer base class + /// + /// The type of the app session. + /// The type of the request info. + public abstract partial class AppServerBase : IAppServer, ICommandSource>, IRawDataProcessor, IRequestHandler + where TRequestInfo : class, IRequestInfo + where TAppSession : AppSession, IAppSession, new() + { + /// + /// Null appSession instance + /// + protected readonly TAppSession NullAppSession = default(TAppSession); + + /// + /// Gets the server's config. + /// + public IServerConfig Config { get; private set; } + + /// + /// Gets the certificate of current server. + /// + public X509Certificate Certificate { get; private set; } + + /// + /// Gets or sets the request filter factory. + /// + /// + /// The request filter factory. + /// + public virtual IRequestFilterFactory RequestFilterFactory { get; protected set; } + + /// + /// Gets the request filter factory. + /// + object IAppServer.RequestFilterFactory + { + get { return this.RequestFilterFactory; } + } + + private List m_CommandLoaders; + + private Dictionary> m_CommandContainer = new Dictionary>(StringComparer.OrdinalIgnoreCase); + + private ISocketServerFactory m_SocketServerFactory; + + /// + /// Gets the basic transfer layer security protocol. + /// + public SslProtocols BasicSecurity { get; private set; } + + /// + /// Gets the root config. + /// + protected IRootConfig RootConfig { get; private set; } + + /// + /// Gets the logger assosiated with this object. + /// + public ILog Logger { get; private set; } + + /// + /// Gets the bootstrap of this appServer instance. + /// + protected IBootstrap Bootstrap { get; private set; } + + private static bool m_ThreadPoolConfigured = false; + + private List m_ConnectionFilters; + + private Dictionary> m_CommandFilterDict; + + private long m_TotalHandledRequests = 0; + + /// + /// Gets the total handled requests number. + /// + protected long TotalHandledRequests + { + get { return m_TotalHandledRequests; } + } + + private ListenerInfo[] m_Listeners; + + /// + /// Gets or sets the listeners inforamtion. + /// + /// + /// The listeners. + /// + public ListenerInfo[] Listeners + { + get { return m_Listeners; } + } + + /// + /// Gets the started time of this server instance. + /// + /// + /// The started time. + /// + public DateTime StartedTime { get; private set; } + + + /// + /// Gets or sets the log factory. + /// + /// + /// The log factory. + /// + public ILogFactory LogFactory { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + public AppServerBase() + { + + } + + /// + /// Initializes a new instance of the class. + /// + /// The request filter factory. + public AppServerBase(IRequestFilterFactory requestFilterFactory) + { + this.RequestFilterFactory = requestFilterFactory; + } + + + /// + /// Setups the command into command dictionary + /// + /// + protected virtual bool SetupCommands(Dictionary> commandContainer) + { + foreach (var loader in m_CommandLoaders) + { + loader.Error += new EventHandler(CommandLoaderOnError); + loader.Updated += new EventHandler>(CommandLoaderOnCommandsUpdated); + + if (!loader.Initialize>(RootConfig, this)) + { + if (Logger.IsErrorEnabled) + Logger.ErrorFormat("Failed initialize the command loader {0}.", loader.ToString()); + return false; + } + + IEnumerable commands; + if (!loader.TryLoadCommands(out commands)) + { + if (Logger.IsErrorEnabled) + Logger.ErrorFormat("Failed load commands from the command loader {0}.", loader.ToString()); + return false; + } + + if (commands != null && commands.Any()) + { + foreach (var c in commands) + { + if (commandContainer.ContainsKey(c.Name)) + { + if (Logger.IsErrorEnabled) + Logger.Error("Duplicated name command has been found! Command name: " + c.Name); + return false; + } + + var castedCommand = c as ICommand; + + if (castedCommand == null) + { + if (Logger.IsErrorEnabled) + Logger.Error("Invalid command has been found! Command name: " + c.Name); + return false; + } + + commandContainer.Add(c.Name, castedCommand); + } + } + } + + m_CommandFilterDict = CommandFilterFactory.GenerateCommandFilterLibrary(this.GetType(), m_CommandContainer.Values.Cast()); + return true; + } + + void CommandLoaderOnCommandsUpdated(object sender, CommandUpdateEventArgs e) + { + var workingDict = m_CommandContainer.Values.ToDictionary(c => c.Name, StringComparer.OrdinalIgnoreCase); + var updatedCommands = 0; + + foreach (var c in e.Commands) + { + if (c == null) + continue; + + var castedCommand = c.Command as ICommand; + + if (castedCommand == null) + { + if (Logger.IsErrorEnabled) + Logger.Error("Invalid command has been found! Command name: " + c.Command.Name); + + continue; + } + + if (c.UpdateAction == CommandUpdateAction.Remove) + { + workingDict.Remove(castedCommand.Name); + if (Logger.IsInfoEnabled) + Logger.InfoFormat("The command '{0}' has been removed from this server!", c.Command.Name); + } + else if (c.UpdateAction == CommandUpdateAction.Add) + { + workingDict.Add(castedCommand.Name, castedCommand); + if (Logger.IsInfoEnabled) + Logger.InfoFormat("The command '{0}' has been added into this server!", c.Command.Name); + } + else + { + workingDict[c.Command.Name] = castedCommand; + if (Logger.IsInfoEnabled) + Logger.InfoFormat("The command '{0}' has been updated!", c.Command.Name); + } + + updatedCommands++; + } + + if (updatedCommands > 0) + { + var commandFilters = CommandFilterFactory.GenerateCommandFilterLibrary(this.GetType(), workingDict.Values.Cast()); + + Interlocked.Exchange(ref m_CommandContainer, workingDict); + Interlocked.Exchange(ref m_CommandFilterDict, commandFilters); + } + } + + void CommandLoaderOnError(object sender, ErrorEventArgs e) + { + if (!Logger.IsErrorEnabled) + return; + + Logger.Error(e.Exception); + } + + /// + /// Setups the specified root config. + /// + /// The root config. + /// The config. + /// + protected virtual bool Setup(IRootConfig rootConfig, IServerConfig config) + { + return true; + } + + private void SetupBasic(IRootConfig rootConfig, IServerConfig config, ISocketServerFactory socketServerFactory) + { + if (rootConfig == null) + throw new ArgumentNullException("rootConfig"); + + RootConfig = rootConfig; + + if (config == null) + throw new ArgumentNullException("config"); + + Config = config; + + if (!m_ThreadPoolConfigured) + { + if (!TheadPoolEx.ResetThreadPool(rootConfig.MaxWorkingThreads >= 0 ? rootConfig.MaxWorkingThreads : new Nullable(), + rootConfig.MaxCompletionPortThreads >= 0 ? rootConfig.MaxCompletionPortThreads : new Nullable(), + rootConfig.MinWorkingThreads >= 0 ? rootConfig.MinWorkingThreads : new Nullable(), + rootConfig.MinCompletionPortThreads >= 0 ? rootConfig.MinCompletionPortThreads : new Nullable())) + { + throw new Exception("Failed to configure thread pool!"); + } + + m_ThreadPoolConfigured = true; + } + + if (socketServerFactory == null) + throw new ArgumentNullException("socketServerFactory"); + + m_SocketServerFactory = socketServerFactory; + } + + private bool SetupMedium(IRequestFilterFactory requestFilterFactory, IEnumerable connectionFilters, IEnumerable commandLoaders) + { + if (requestFilterFactory != null) + RequestFilterFactory = requestFilterFactory; + + if (connectionFilters != null && connectionFilters.Any()) + { + if (m_ConnectionFilters == null) + m_ConnectionFilters = new List(); + + m_ConnectionFilters.AddRange(connectionFilters); + } + + SetupCommandLoader(commandLoaders); + + return true; + } + + private bool SetupAdvanced(IServerConfig config) + { + if (!SetupSecurity(config)) + return false; + + if (!SetupListeners(config)) + return false; + + if (!SetupCommands(m_CommandContainer)) + return false; + + return true; + } + + + private bool SetupFinal() + { + var plainConfig = Config as ServerConfig; + + if (plainConfig == null) + { + //Using plain config model instead of .NET configuration element to improve performance + plainConfig = new ServerConfig(); + Config.CopyPropertiesTo(plainConfig); + Config = plainConfig; + } + + return SetupSocketServer(); + } + +#if NET_35 + /// + /// Setups the specified root config, used for programming setup + /// + /// The root config. + /// The config. + /// The socket server factory. + /// The providers. + /// + public virtual bool Setup(IRootConfig rootConfig, IServerConfig config, ISocketServerFactory socketServerFactory, params object[] providers) + { + SetupBasic(rootConfig, config, socketServerFactory); + + if (!SetupLogFactory(GetProviderInstance(providers))) + return false; + + Logger = CreateLogger(this.Name); + + if (!SetupMedium(GetProviderInstance>(providers), GetProviderInstance>(providers), GetProviderInstance>(providers))) + return false; + + if (!SetupAdvanced(config)) + return false; + + if (!Setup(rootConfig, config)) + return false; + + return SetupFinal(); + } + + private T GetProviderInstance(object[] providers) + { + if (providers == null || !providers.Any()) + return default(T); + + var providerType = typeof(T); + return (T)providers.FirstOrDefault(p => p != null && providerType.IsAssignableFrom(p.GetType())); + } +#else + + /// + /// Setups the specified root config, this method used for programming setup + /// + /// The root config. + /// The config. + /// The socket server factory. + /// The request filter factory. + /// The log factory. + /// The connection filters. + /// The command loaders. + /// + public bool Setup(IRootConfig rootConfig, IServerConfig config, ISocketServerFactory socketServerFactory, IRequestFilterFactory requestFilterFactory = null, ILogFactory logFactory = null, IEnumerable connectionFilters = null, IEnumerable commandLoaders = null) + { + SetupBasic(rootConfig, config, socketServerFactory); + + if (!SetupLogFactory(logFactory)) + return false; + + Logger = CreateLogger(this.Name); + + if (!SetupMedium(requestFilterFactory, connectionFilters, commandLoaders)) + return false; + + if (!SetupAdvanced(config)) + return false; + + if (!Setup(rootConfig, config)) + return false; + + return SetupFinal(); + } +#endif + + /// + /// Setups the specified root config. + /// + /// The bootstrap. + /// The socket server instance config. + /// The factories. + /// + bool IWorkItem.Setup(IBootstrap bootstrap, IServerConfig config, ProviderFactoryInfo[] factories) + { + if (bootstrap == null) + throw new ArgumentNullException("bootstrap"); + + Bootstrap = bootstrap; + + if (factories == null) + throw new ArgumentNullException("factories"); + + var rootConfig = bootstrap.Config; + + SetupBasic(rootConfig, config, GetSingleProviderInstance(factories, ProviderKey.SocketServerFactory)); + + if (!SetupLogFactory(GetSingleProviderInstance(factories, ProviderKey.LogFactory))) + return false; + + Logger = CreateLogger(this.Name); + + if (!SetupMedium( + GetSingleProviderInstance>(factories, ProviderKey.RequestFilterFactory), + GetProviderInstances(factories, ProviderKey.ConnectionFilter), + GetProviderInstances(factories, ProviderKey.CommandLoader))) + { + return false; + } + + if (!SetupAdvanced(config)) + return false; + + if (!Setup(rootConfig, config)) + return false; + + return SetupFinal(); + } + + + private TProvider GetSingleProviderInstance(ProviderFactoryInfo[] factories, ProviderKey key) + { + var factory = factories.FirstOrDefault(p => p.Key.Name == key.Name); + + if (factory == null) + return default(TProvider); + + return factory.ExportFactory.CreateExport(); + } + + private IEnumerable GetProviderInstances(ProviderFactoryInfo[] factories, ProviderKey key) + where TProvider : class + { + IEnumerable selectedFactories = factories.Where(p => p.Key.Name == key.Name); + + if (!selectedFactories.Any()) + return null; + + return selectedFactories.Select(f => f.ExportFactory.CreateExport()); + } + + private bool SetupLogFactory(ILogFactory logFactory) + { + if (logFactory != null) + { + LogFactory = logFactory; + return true; + } + + //Log4NetLogFactory is default log factory + if (LogFactory == null) + LogFactory = new Log4NetLogFactory(); + + return true; + } + + private bool SetupCommandLoader(IEnumerable commandLoaders) + { + m_CommandLoaders = new List(); + m_CommandLoaders.Add(new ReflectCommandLoader()); + + if (commandLoaders != null && commandLoaders.Any()) + m_CommandLoaders.AddRange(commandLoaders); + + return true; + } + + /// + /// Creates the logger for the AppServer. + /// + /// Name of the logger. + /// + protected virtual ILog CreateLogger(string loggerName) + { + return LogFactory.GetLog(loggerName); + } + + /// + /// Setups the security option of socket communications. + /// + /// The config of the server instance. + /// + private bool SetupSecurity(IServerConfig config) + { + if (!string.IsNullOrEmpty(config.Security)) + { + SslProtocols configProtocol; + if (!config.Security.TryParseEnum(true, out configProtocol)) + { + if (Logger.IsErrorEnabled) + Logger.ErrorFormat("Failed to parse '{0}' to SslProtocol!", config.Security); + + return false; + } + + if (configProtocol != SslProtocols.None) + { + try + { + var certificate = GetCertificate(config); + + if (certificate == null) + return false; + + Certificate = certificate; + } + catch (Exception e) + { + if (Logger.IsErrorEnabled) + Logger.Error("Failed to initialize certificate!", e); + + return false; + } + } + + BasicSecurity = configProtocol; + } + else + { + BasicSecurity = SslProtocols.None; + } + + return true; + } + + /// + /// Gets the certificate from server configuguration. + /// + /// The config. + /// + protected virtual X509Certificate GetCertificate(IServerConfig config) + { + if (config.Certificate == null) + { + if (Logger.IsErrorEnabled) + Logger.Error("There is no certificate defined!"); + return null; + } + + if (string.IsNullOrEmpty(config.Certificate.FilePath) && string.IsNullOrEmpty(config.Certificate.Thumbprint)) + { + if (Logger.IsErrorEnabled) + Logger.Error("You should define certificate node and either attribute 'filePath' or 'thumbprint' is required!"); + + return null; + } + + return CertificateManager.Initialize(config.Certificate); + } + + /// + /// Setups the socket server.instance + /// + /// + private bool SetupSocketServer() + { + try + { + m_SocketServer = m_SocketServerFactory.CreateSocketServer(this, m_Listeners, Config, RequestFilterFactory); + return m_SocketServer != null; + } + catch (Exception e) + { + if (Logger.IsErrorEnabled) + Logger.Error(e); + + return false; + } + } + + private IPAddress ParseIPAddress(string ip) + { + if (string.IsNullOrEmpty(ip) || "Any".Equals(ip, StringComparison.OrdinalIgnoreCase)) + return IPAddress.Any; + else if ("IPv6Any".Equals(ip, StringComparison.OrdinalIgnoreCase)) + return IPAddress.IPv6Any; + else + return IPAddress.Parse(ip); + } + + /// + /// Setups the listeners base on server configuration + /// + /// The config. + /// + private bool SetupListeners(IServerConfig config) + { + var listeners = new List(); + + try + { + if (config.Port > 0) + { + listeners.Add(new ListenerInfo + { + EndPoint = new IPEndPoint(ParseIPAddress(config.Ip), config.Port), + BackLog = config.ListenBacklog, + Security = BasicSecurity + }); + } + else + { + if (!string.IsNullOrEmpty(config.Ip)) + { + if (Logger.IsErrorEnabled) + Logger.Error("Ip is required in config!"); + + return false; + } + } + + //There are listener defined + if (config.Listeners != null && config.Listeners.Any()) + { + //But ip and port were configured in server node + //We don't allow this case + if (listeners.Count > 0) + { + if (Logger.IsErrorEnabled) + Logger.Error("If you configured Ip and Port in server node, you cannot defined listeners any more!"); + + return false; + } + + foreach (var l in config.Listeners) + { + SslProtocols configProtocol; + + if (string.IsNullOrEmpty(l.Security) && BasicSecurity != SslProtocols.None) + { + configProtocol = BasicSecurity; + } + else if (!l.Security.TryParseEnum(true, out configProtocol)) + { + if (Logger.IsErrorEnabled) + Logger.ErrorFormat("Failed to parse '{0}' to SslProtocol!", config.Security); + + return false; + } + + if (configProtocol != SslProtocols.None && (config.Certificate == null)) + { + if (Logger.IsErrorEnabled) + Logger.Error("There is no certificate defined and enabled!"); + return false; + } + + listeners.Add(new ListenerInfo + { + EndPoint = new IPEndPoint(ParseIPAddress(l.Ip), l.Port), + BackLog = l.Backlog, + Security = configProtocol + }); + } + } + + if (!listeners.Any()) + { + if (Logger.IsErrorEnabled) + Logger.Error("No listener defined!"); + + return false; + } + + m_Listeners = listeners.ToArray(); + + return true; + } + catch (Exception e) + { + if (Logger.IsErrorEnabled) + Logger.Error(e); + + return false; + } + } + + /// + /// Gets the name of the server instance. + /// + public string Name + { + get { return Config.Name; } + } + + private ISocketServer m_SocketServer; + + /// + /// Starts this server instance. + /// + /// + /// return true if start successfull, else false + /// + public virtual bool Start() + { + if (this.IsRunning) + { + if (Logger.IsErrorEnabled) + Logger.Error("This socket server is running already, you needn't start it."); + + return false; + } + + if (!m_SocketServer.Start()) + return false; + + StartedTime = DateTime.Now; + + OnStartup(); + + return true; + } + + /// + /// Called when [startup]. + /// + protected virtual void OnStartup() + { + + } + + /// + /// Called when [stopped]. + /// + protected virtual void OnStopped() + { + + } + + /// + /// Stops this server instance. + /// + public virtual void Stop() + { + Dispose(true); + GC.SuppressFinalize(this); + OnStopped(); + } + + /// + /// Gets a value indicating whether this instance is running. + /// + /// + /// true if this instance is running; otherwise, false. + /// + public bool IsRunning + { + get + { + if (m_SocketServer == null) + return false; + + return m_SocketServer.IsRunning; + } + } + + /// + /// Gets command by command name. + /// + /// Name of the command. + /// + public ICommand GetCommandByName(string commandName) + { + ICommand command; + + if (m_CommandContainer.TryGetValue(commandName, out command)) + return command; + else + return null; + } + + + private Func m_RawDataReceivedHandler; + + /// + /// Gets or sets the raw binary data received event handler. + /// TAppSession: session + /// byte[]: receive buffer + /// int: receive buffer offset + /// int: receive lenght + /// bool: whether process the received data further + /// + event Func IRawDataProcessor.RawDataReceived + { + add { m_RawDataReceivedHandler += value; } + remove { m_RawDataReceivedHandler -= value; } + } + + /// + /// Called when [raw data received]. + /// + /// The session. + /// The buffer. + /// The offset. + /// The length. + internal bool OnRawDataReceived(IAppSession session, byte[] buffer, int offset, int length) + { + var handler = m_RawDataReceivedHandler; + if (handler == null) + return true; + + return handler((TAppSession)session, buffer, offset, length); + } + + private RequestHandler m_RequestHandler; + + /// + /// Occurs when a full request item received. + /// + public event RequestHandler RequestHandler + { + add { m_RequestHandler += value; } + remove { m_RequestHandler -= value; } + } + + /// + /// Executes the command filters. + /// + /// The filters. + /// The session. + /// The command. + /// The filter action. + private void ExecuteCommandFilters(List filters, TAppSession session, ICommand command, Action filterAction) + { + if (filters == null || filters.Count <= 0) + return; + + for (var i = 0; i < filters.Count; i++) + { + var filter = filters[i]; + filterAction(filter, session, command); + } + } + + private Action m_CommandFilterExecutingAction = (f, s, c) => f.OnCommandExecuting(s, c); + + private Action m_CommandFilterExecutedAction = (f, s, c) => f.OnCommandExecuted(s, c); + + /// + /// Executes the command. + /// + /// The session. + /// The request info. + protected virtual void ExecuteCommand(TAppSession session, TRequestInfo requestInfo) + { + if (m_RequestHandler == null) + { + var command = GetCommandByName(requestInfo.Key); + + if (command != null) + { + List commandFilters = null; + + if (m_CommandFilterDict != null) + m_CommandFilterDict.TryGetValue(command.Name, out commandFilters); + + session.CurrentCommand = requestInfo.Key; + + if (commandFilters != null) + ExecuteCommandFilters(commandFilters, session, command, m_CommandFilterExecutingAction); + + //Command filter may close the session, + //so detect whether session is connected before execute command + if (session.Connected) + { + command.ExecuteCommand(session, requestInfo); + + if (commandFilters != null) + ExecuteCommandFilters(commandFilters, session, command, m_CommandFilterExecutedAction); + } + + session.PrevCommand = requestInfo.Key; + + if (Config.LogCommand && Logger.IsInfoEnabled) + Logger.Info(session, string.Format("Command - {0}", requestInfo.Key)); + } + else + { + session.HandleUnknownRequest(requestInfo); + } + + session.LastActiveTime = DateTime.Now; + } + else + { + session.CurrentCommand = requestInfo.Key; + m_RequestHandler(session, requestInfo); + session.PrevCommand = requestInfo.Key; + session.LastActiveTime = DateTime.Now; + + if (Config.LogCommand && Logger.IsInfoEnabled) + Logger.Info(session, string.Format("Command - {0}", requestInfo.Key)); + } + + Interlocked.Increment(ref m_TotalHandledRequests); + } + + /// + /// Executes the command for the session. + /// + /// The session. + /// The request info. + internal void ExecuteCommand(IAppSession session, TRequestInfo requestInfo) + { + this.ExecuteCommand((TAppSession)session, requestInfo); + } + + /// + /// Executes the command. + /// + /// The session. + /// The request info. + void IRequestHandler.ExecuteCommand(IAppSession session, TRequestInfo requestInfo) + { + this.ExecuteCommand((TAppSession)session, requestInfo); + } + + /// + /// Gets or sets the server's connection filter + /// + /// + /// The server's connection filters + /// + public IEnumerable ConnectionFilters + { + get { return m_ConnectionFilters; } + } + + /// + /// Executes the connection filters. + /// + /// The remote address. + /// + private bool ExecuteConnectionFilters(IPEndPoint remoteAddress) + { + if (m_ConnectionFilters == null) + return true; + + for (var i = 0; i < m_ConnectionFilters.Count; i++) + { + var currentFilter = m_ConnectionFilters[i]; + if (!currentFilter.AllowConnect(remoteAddress)) + { + if (Logger.IsInfoEnabled) + Logger.InfoFormat("A connection from {0} has been refused by filter {1}!", remoteAddress, currentFilter.Name); + return false; + } + } + + return true; + } + + /// + /// Creates the app session. + /// + /// The socket session. + /// + IAppSession IAppServer.CreateAppSession(ISocketSession socketSession) + { + if (!ExecuteConnectionFilters(socketSession.RemoteEndPoint)) + return NullAppSession; + + var appSession = new TAppSession(); + + if (!RegisterSession(socketSession.SessionID, appSession)) + return NullAppSession; + + appSession.Initialize(this, socketSession, RequestFilterFactory.CreateFilter(this, socketSession)); + socketSession.Closed += OnSocketSessionClosed; + + if (Logger.IsInfoEnabled) + Logger.InfoFormat("A new session connected!"); + + OnNewSessionConnected(appSession); + + return appSession; + } + + /// + /// Registers the session into session container. + /// + /// The session ID. + /// The app session. + /// + protected virtual bool RegisterSession(string sessionID, TAppSession appSession) + { + return true; + } + + + private Action m_NewSessionConnected; + + /// + /// The action which will be executed after a new session connect + /// + public event Action NewSessionConnected + { + add { m_NewSessionConnected += value; } + remove { m_NewSessionConnected -= value; } + } + + /// + /// Called when [new session connected]. + /// + /// The session. + protected virtual void OnNewSessionConnected(TAppSession session) + { + var handler = m_NewSessionConnected; + if (handler == null) + return; + + handler.BeginInvoke(session, OnNewSessionConnectedCallback, handler); + } + + private void OnNewSessionConnectedCallback(IAsyncResult result) + { + try + { + var handler = (Action)result.AsyncState; + handler.EndInvoke(result); + } + catch (Exception e) + { + Logger.Error(e); + } + } + + /// + /// Resets the session's security protocol. + /// + /// The session. + /// The security protocol. + public void ResetSessionSecurity(IAppSession session, SslProtocols security) + { + m_SocketServer.ResetSessionSecurity(session, security); + } + + /// + /// Called when [socket session closed]. + /// + /// The socket session. + /// The reason. + private void OnSocketSessionClosed(ISocketSession session, CloseReason reason) + { + if (Logger.IsInfoEnabled) + Logger.Info(session, string.Format("This session was closed for {0}!", reason)); + + OnSessionClosed((TAppSession)session.AppSession, reason); + } + + private Action m_SessionClosed; + /// + /// Gets/sets the session closed event handler. + /// + public event Action SessionClosed + { + add { m_SessionClosed += value; } + remove { m_SessionClosed -= value; } + } + + /// + /// Called when [session closed]. + /// + /// The appSession. + /// The reason. + protected virtual void OnSessionClosed(TAppSession session, CloseReason reason) + { + session.Connected = false; + + var handler = m_SessionClosed; + + if (handler != null) + { + handler.BeginInvoke(session, reason, OnSessionClosedCallback, handler); + } + + session.OnSessionClosed(reason); + } + + private void OnSessionClosedCallback(IAsyncResult result) + { + try + { + var handler = (Action)result.AsyncState; + handler.EndInvoke(result); + } + catch (Exception e) + { + Logger.Error(e); + } + } + + /// + /// Gets the app session by ID. + /// + /// The session ID. + /// + public abstract TAppSession GetAppSessionByID(string sessionID); + + /// + /// Gets the app session by ID. + /// + /// + /// + IAppSession IAppServer.GetAppSessionByID(string sessionID) + { + return this.GetAppSessionByID(sessionID); + } + + /// + /// Gets the matched sessions from sessions snapshot. + /// + /// The prediction critera. + public virtual IEnumerable GetSessions(Func critera) + { + throw new NotSupportedException(); + } + + /// + /// Gets all sessions in sessions snapshot. + /// + public virtual IEnumerable GetAllSessions() + { + throw new NotSupportedException(); + } + + /// + /// Gets the total session count. + /// + public virtual int SessionCount + { + get + { + throw new NotSupportedException(); + } + } + + #region IDisposable Members + + /// + /// Releases unmanaged and - optionally - managed resources + /// + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + /// + /// Releases unmanaged and - optionally - managed resources + /// + /// true to release both managed and unmanaged resources; false to release only unmanaged resources. + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + if (IsRunning) + { + m_SocketServer.Stop(); + } + } + } + + #endregion + } +} diff --git a/SocketBase/AppSession.cs b/SocketBase/AppSession.cs new file mode 100644 index 000000000..b448e29ec --- /dev/null +++ b/SocketBase/AppSession.cs @@ -0,0 +1,714 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Security.Authentication; +using System.Text; +using System.Threading; +using SuperSocket.Common; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Config; +using SuperSocket.SocketBase.Logging; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.SocketBase +{ + /// + /// AppSession base class + /// + /// The type of the app session. + /// The type of the request info. + public abstract class AppSession : IAppSession, IAppSession + where TAppSession : AppSession, IAppSession, new() + where TRequestInfo : class, IRequestInfo + { + #region Attributes + + /// + /// Gets the app server instance assosiated with the session. + /// + public virtual AppServerBase AppServer { get; private set; } + + /// + /// Gets the app server instance assosiated with the session. + /// + IAppServer IAppSession.AppServer + { + get { return this.AppServer; } + } + + /// + /// Gets or sets the charset which is used for transfering text message. + /// + /// + /// The charset. + /// + public Encoding Charset { get; set; } + + private IDictionary m_Items; + + /// + /// Gets the items dictionary, only support 10 items maximum + /// + public IDictionary Items + { + get + { + if (m_Items == null) + m_Items = new Dictionary(10); + + return m_Items; + } + } + + /// + /// Gets a value indicating whether this is connected. + /// + /// + /// true if connected; otherwise, false. + /// + public bool Connected { get; internal set; } + + /// + /// Gets or sets the previous command. + /// + /// + /// The prev command. + /// + public string PrevCommand { get; set; } + + /// + /// Gets or sets the current executing command. + /// + /// + /// The current command. + /// + public string CurrentCommand { get; set; } + + + /// + /// Gets or sets the secure protocol of transportation layer. + /// + /// + /// The secure protocol. + /// + public SslProtocols SecureProtocol + { + get { return SocketSession.SecureProtocol; } + set { SocketSession.SecureProtocol = value; } + } + + /// + /// Gets the local listening endpoint. + /// + public IPEndPoint LocalEndPoint + { + get { return SocketSession.LocalEndPoint; } + } + + /// + /// Gets the remote endpoint of client. + /// + public IPEndPoint RemoteEndPoint + { + get { return SocketSession.RemoteEndPoint; } + } + + /// + /// Gets the logger. + /// + public ILog Logger + { + get { return AppServer.Logger; } + } + + /// + /// Gets or sets the last active time of the session. + /// + /// + /// The last active time. + /// + public DateTime LastActiveTime { get; set; } + + /// + /// Gets the start time of the session. + /// + public DateTime StartTime { get; private set; } + + /// + /// Gets the session ID. + /// + public string SessionID { get; private set; } + + /// + /// Gets the socket session of the AppSession. + /// + public ISocketSession SocketSession { get; private set; } + + /// + /// Gets the config of the server. + /// + public IServerConfig Config + { + get { return AppServer.Config; } + } + + /// + /// Gets or sets the m_ request filter. + /// + /// + /// The m_ request filter. + /// + IRequestFilter m_RequestFilter { get; set; } + + #endregion + + /// + /// Initializes a new instance of the class. + /// + public AppSession() + { + this.StartTime = DateTime.Now; + this.LastActiveTime = this.StartTime; + this.Charset = Encoding.UTF8; + } + + + /// + /// Initializes the specified app session by AppServer and SocketSession. + /// + /// The app server. + /// The socket session. + /// The request filter. + public virtual void Initialize(IAppServer appServer, ISocketSession socketSession, IRequestFilter requestFilter) + { + AppServer = (AppServerBase)appServer; + SocketSession = socketSession; + SessionID = socketSession.SessionID; + Connected = true; + m_RequestFilter = requestFilter; + OnInit(); + } + + /// + /// Starts the session. + /// + public void StartSession() + { + OnSessionStarted(); + } + + /// + /// Called when [init]. + /// + protected virtual void OnInit() + { + + } + + /// + /// Called when [session started]. + /// + protected virtual void OnSessionStarted() + { + + } + + /// + /// Called when [session closed]. + /// + /// The reason. + internal protected virtual void OnSessionClosed(CloseReason reason) + { + + } + + + /// + /// Handles the exceptional error. + /// + /// The exception. + public virtual void HandleException(Exception e) + { + Logger.Error(this, e); + } + + /// + /// Executes the command. + /// + /// The session. + /// The CMD info. + public void ExecuteCommand(TAppSession session, TRequestInfo cmdInfo) + { + AppServer.ExecuteCommand(session, cmdInfo); + } + + /// + /// Handles the unknown request. + /// + /// The request info. + public virtual void HandleUnknownRequest(TRequestInfo requestInfo) + { + Send("Unknown request: " + requestInfo.Key); + } + + /// + /// Closes the session by the specified reason. + /// + /// The close reason. + public virtual void Close(CloseReason reason) + { + this.SocketSession.Close(reason); + } + + /// + /// Closes this session. + /// + public virtual void Close() + { + Close(CloseReason.ServerClosing); + } + + #region sending processing + + private IBatchQueue> m_SendingQueue; + + private IBatchQueue> GetSendingQueue() + { + if (m_SendingQueue != null) + return m_SendingQueue; + + lock (this) + { + if (m_SendingQueue != null) + return m_SendingQueue; + + //Sending queue size must be greater than 3 + m_SendingQueue = new ConcurrentBatchQueue>(Math.Max(Config.SendingQueueSize, 3), (t) => t.Array == null); + return m_SendingQueue; + } + } + + /// + /// Tries to get the data segment to be sent. + /// + /// The segments. + /// + /// return whether has data to send + /// + bool IAppSession.TryGetSendingData(IList> segments) + { + return GetSendingQueue().TryDequeue(segments); + } + + /// + /// Try to send the message to client. + /// + /// The message which will be sent. + /// Indicate whether the message was pushed into the sending queue + public virtual bool TrySend(string message) + { + var data = this.Charset.GetBytes(message); + return InternalTrySend(new ArraySegment(data, 0, data.Length)); + } + + /// + /// Sends the message to client. + /// + /// The message which will be sent. + public virtual void Send(string message) + { + var data = this.Charset.GetBytes(message); + Send(data, 0, data.Length); + } + + /// + /// Sends the response. + /// + /// The message which will be sent. + /// Indicate whether the message was pushed into the sending queue + [Obsolete("Use 'Send(string message)' instead")] + public virtual void SendResponse(string message) + { + Send(message); + } + + /// + /// Try to send the data to client. + /// + /// The data which will be sent. + /// The offset. + /// The length. + /// Indicate whether the message was pushed into the sending queue + public virtual bool TrySend(byte[] data, int offset, int length) + { + return InternalTrySend(new ArraySegment(data, offset, length)); + } + + /// + /// Sends the data to client. + /// + /// The data which will be sent. + /// The offset. + /// The length. + public virtual void Send(byte[] data, int offset, int length) + { + InternalSend(new ArraySegment(data, offset, length)); + } + + /// + /// Sends the response. + /// + /// The data which will be sent. + /// The offset. + /// The length. + [Obsolete("Use 'Send(byte[] data, int offset, int length)' instead")] + public virtual void SendResponse(byte[] data, int offset, int length) + { + Send(data, offset, length); + } + + private bool InternalTrySend(ArraySegment segment) + { + if (!GetSendingQueue().Enqueue(segment)) + return false; + + SocketSession.StartSend(); + LastActiveTime = DateTime.Now; + + return true; + } + + /// + /// Try to send the data segment to client. + /// + /// The segment which will be sent. + /// Indicate whether the message was pushed into the sending queue + public virtual bool TrySend(ArraySegment segment) + { + return InternalTrySend(segment); + } + + + private void InternalSend(ArraySegment segment) + { + if (InternalTrySend(segment)) + return; + + var spinWait = new SpinWait(); + + while (this.Connected) + { + spinWait.SpinOnce(); + + if (InternalTrySend(segment)) + return; + } + } + + /// + /// Sends the data segment to client. + /// + /// The segment which will be sent. + public virtual void Send(ArraySegment segment) + { + InternalSend(segment); + } + + /// + /// Sends the response. + /// + /// The segment which will be sent. + /// Indicate whether the message was pushed into the sending queue + [Obsolete("Use 'Send(ArraySegment segment)' instead")] + public virtual void SendResponse(ArraySegment segment) + { + InternalSend(segment); + } + + + private bool InternalTrySend(IList> segments) + { + if (!GetSendingQueue().Enqueue(segments)) + return false; + + SocketSession.StartSend(); + LastActiveTime = DateTime.Now; + + return true; + } + + /// + /// Try to send the data segments to clinet. + /// + /// The segments. + /// Indicate whether the message was pushed into the sending queue + public virtual bool TrySend(IList> segments) + { + return InternalTrySend(segments); + } + + private void InternalSend(IList> segments) + { + if (InternalTrySend(segments)) + return; + + var spinWait = new SpinWait(); + + while (this.Connected) + { + spinWait.SpinOnce(); + + if (InternalTrySend(segments)) + return; + } + } + + /// + /// Sends the data segments to clinet. + /// + /// The segments. + public virtual void Send(IList> segments) + { + InternalSend(segments); + } + + /// + /// Sends the response. + /// + /// The segments. + /// Indicate whether the message was pushed into the sending queue + [Obsolete("Use 'Send(IList> segments)' instead")] + public virtual void SendResponse(IList> segments) + { + InternalSend(segments); + } + + /// + /// Sends the response. + /// + /// The message which will be sent. + /// The parameter values. + public virtual void Send(string message, params object[] paramValues) + { + var data = this.Charset.GetBytes(string.Format(message, paramValues)); + InternalSend(new ArraySegment(data, 0, data.Length)); + } + + /// + /// Sends the response. + /// + /// The message which will be sent. + /// The parameter values. + /// Indicate whether the message was pushed into the sending queue + [Obsolete("Use 'Send(string message, params object[] paramValues)' instead")] + public virtual void SendResponse(string message, params object[] paramValues) + { + var data = this.Charset.GetBytes(string.Format(message, paramValues)); + InternalSend(new ArraySegment(data, 0, data.Length)); + } + + #endregion + + #region receiving processing + + /// + /// Sets the next request filter which will be used when next data block received + /// + /// The next request filter. + protected void SetNextRequestFilter(IRequestFilter nextRequestFilter) + { + m_RequestFilter = nextRequestFilter; + } + + /// + /// Filters the request. + /// + /// The read buffer. + /// The offset. + /// The length. + /// if set to true [to be copied]. + /// The left, the size of the data which has not been processed + /// return offset delta of next receiving buffer. + /// + TRequestInfo FilterRequest(byte[] readBuffer, int offset, int length, bool toBeCopied, out int left, out int offsetDelta) + { + if (!AppServer.OnRawDataReceived(this, readBuffer, offset, length)) + { + left = 0; + offsetDelta = 0; + return null; + } + + var requestInfo = m_RequestFilter.Filter(this, readBuffer, offset, length, toBeCopied, out left); + + var offsetAdapter = m_RequestFilter as IOffsetAdapter; + + offsetDelta = offsetAdapter != null ? offsetAdapter.OffsetDelta : 0; + + if (requestInfo == null) + { + int leftBufferCount = m_RequestFilter.LeftBufferSize; + if (leftBufferCount >= AppServer.Config.MaxRequestLength) + { + if (Logger.IsErrorEnabled) + Logger.ErrorFormat("Max request length: {0}, current processed length: {1}", AppServer.Config.MaxRequestLength, leftBufferCount); + Close(CloseReason.ServerClosing); + return null; + } + } + + //If next request filter wasn't set, still use current request filter in next round received data processing + if (m_RequestFilter.NextRequestFilter != null) + m_RequestFilter = m_RequestFilter.NextRequestFilter; + + return requestInfo; + } + + /// + /// Processes the request data. + /// + /// The read buffer. + /// The offset. + /// The length. + /// if set to true [to be copied]. + /// + /// return offset delta of next receiving buffer + /// + int IAppSession.ProcessRequest(byte[] readBuffer, int offset, int length, bool toBeCopied) + { + int left, offsetDelta; + + while (true) + { + var requestInfo = FilterRequest(readBuffer, offset, length, toBeCopied, out left, out offsetDelta); + + if (requestInfo == null) + return offsetDelta; + + AppServer.ExecuteCommand(this, requestInfo); + + if (left <= 0) + return offsetDelta; + + offset = offset + length - left; + length = left; + + continue; + } + } + + #endregion + } + + /// + /// AppServer basic class for whose request infoe type is StringRequestInfo + /// + /// The type of the app session. + public abstract class AppSession : AppSession + where TAppSession : AppSession, IAppSession, new() + { + + private bool m_AppendNewLineForResponse = false; + + /// + /// Initializes a new instance of the class. + /// + public AppSession() + : this(true) + { + + } + + /// + /// Initializes a new instance of the class. + /// + /// if set to true [append new line for response]. + public AppSession(bool appendNewLineForResponse) + { + m_AppendNewLineForResponse = appendNewLineForResponse; + } + + /// + /// Processes the sending message. + /// + /// The raw message. + /// + protected virtual string ProcessSendingMessage(string rawMessage) + { + if (!m_AppendNewLineForResponse) + return rawMessage; + + if (AppServer.Config.Mode == SocketMode.Udp) + return rawMessage; + + if (string.IsNullOrEmpty(rawMessage) || !rawMessage.EndsWith(Environment.NewLine)) + return rawMessage + Environment.NewLine; + else + return rawMessage; + } + + /// + /// Try to send the specified message. + /// + /// The message. + /// Indicate whether the message was pushed into the sending queue + public override bool TrySend(string message) + { + return base.TrySend(message); + } + + /// + /// Sends the specified message. + /// + /// The message. + /// + public override void Send(string message) + { + base.Send(ProcessSendingMessage(message)); + } + + /// + /// Sends the response. + /// + /// The message. + /// Indicate whether the message was pushed into the sending queue + [Obsolete("Use 'Send(string message)' instead")] + public override void SendResponse(string message) + { + base.Send(ProcessSendingMessage(message)); + } + + /// + /// Sends the response. + /// + /// The message. + /// The param values. + /// Indicate whether the message was pushed into the sending queue + public override void Send(string message, params object[] paramValues) + { + base.Send(ProcessSendingMessage(message), paramValues); + } + + /// + /// Sends the response. + /// + /// The message. + /// The param values. + /// Indicate whether the message was pushed into the sending queue + [Obsolete("Use 'Send(string message, params object[] paramValues)' instead")] + public override void SendResponse(string message, params object[] paramValues) + { + base.Send(ProcessSendingMessage(message), paramValues); + } + } + + /// + /// AppServer basic class for whose request infoe type is StringRequestInfo + /// + public class AppSession : AppSession + { + + } +} diff --git a/SocketBase/Async.cs b/SocketBase/Async.cs new file mode 100644 index 000000000..631ce405b --- /dev/null +++ b/SocketBase/Async.cs @@ -0,0 +1,143 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using SuperSocket.SocketBase.Logging; + +namespace SuperSocket.SocketBase +{ + /// + /// Async extension class + /// + public static class Async + { + /// + /// Runs the specified task. + /// + /// The log provider. + /// The task. + /// + public static Task AsyncRun(this ILoggerProvider logProvider, Action task) + { + return AsyncRun(logProvider, task, TaskCreationOptions.None); + } + + /// + /// Runs the specified task. + /// + /// The log provider. + /// The task. + /// The task option. + /// + public static Task AsyncRun(this ILoggerProvider logProvider, Action task, TaskCreationOptions taskOption) + { + return AsyncRun(logProvider, task, taskOption, null); + } + + /// + /// Runs the specified task. + /// + /// The log provider. + /// The task. + /// The exception handler. + /// + public static Task AsyncRun(this ILoggerProvider logProvider, Action task, Action exceptionHandler) + { + return AsyncRun(logProvider, task, TaskCreationOptions.None, exceptionHandler); + } + + /// + /// Runs the specified task. + /// + /// The log provider. + /// The task. + /// The task option. + /// The exception handler. + /// + public static Task AsyncRun(this ILoggerProvider logProvider, Action task, TaskCreationOptions taskOption, Action exceptionHandler) + { + return Task.Factory.StartNew(task, taskOption).ContinueWith(t => + { + if (exceptionHandler != null) + exceptionHandler(t.Exception); + else + { + if (logProvider.Logger.IsErrorEnabled) + { + for (var i = 0; i < t.Exception.InnerExceptions.Count; i++) + { + logProvider.Logger.Error(t.Exception.InnerExceptions[i]); + } + } + } + }, TaskContinuationOptions.OnlyOnFaulted); + } + + /// + /// Runs the specified task. + /// + /// The log provider. + /// The task. + /// The state. + /// + public static Task AsyncRun(this ILoggerProvider logProvider, Action task, object state) + { + return AsyncRun(logProvider, task, state, TaskCreationOptions.None); + } + + /// + /// Runs the specified task. + /// + /// The log provider. + /// The task. + /// The state. + /// The task option. + /// + public static Task AsyncRun(this ILoggerProvider logProvider, Action task, object state, TaskCreationOptions taskOption) + { + return AsyncRun(logProvider, task, state, taskOption, null); + } + + /// + /// Runs the specified task. + /// + /// The log provider. + /// The task. + /// The state. + /// The exception handler. + /// + public static Task AsyncRun(this ILoggerProvider logProvider, Action task, object state, Action exceptionHandler) + { + return AsyncRun(logProvider, task, state, TaskCreationOptions.None, exceptionHandler); + } + + /// + /// Runs the specified task. + /// + /// The log provider. + /// The task. + /// The state. + /// The task option. + /// The exception handler. + /// + public static Task AsyncRun(this ILoggerProvider logProvider, Action task, object state, TaskCreationOptions taskOption, Action exceptionHandler) + { + return Task.Factory.StartNew(task, state, taskOption).ContinueWith(t => + { + if (exceptionHandler != null) + exceptionHandler(t.Exception); + else + { + if (logProvider.Logger.IsErrorEnabled) + { + for (var i = 0; i < t.Exception.InnerExceptions.Count; i++) + { + logProvider.Logger.Error(t.Exception.InnerExceptions[i]); + } + } + } + }, TaskContinuationOptions.OnlyOnFaulted); + } + } +} diff --git a/SocketBase/CommanFilterFactory.cs b/SocketBase/CommanFilterFactory.cs new file mode 100644 index 000000000..0c8f97a2d --- /dev/null +++ b/SocketBase/CommanFilterFactory.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using SuperSocket.SocketBase.Command; + +namespace SuperSocket.SocketBase +{ + /// + /// Command filter factory + /// + public static class CommandFilterFactory + { + /// + /// Generates the command filter library. + /// + /// Type of the server. + /// The commands. + /// + public static Dictionary> GenerateCommandFilterLibrary(Type serverType, IEnumerable commands) + { + var library = new Dictionary>(StringComparer.OrdinalIgnoreCase); + + //Get global command filters + var globalFilters = GetFilterAttributes(serverType); + + foreach(var command in commands) + { + //Get command specified filters + var commandAttrs = GetFilterAttributes(command.GetType()); + var applyAttrs = new List(commandAttrs.Length + globalFilters.Length); + if(globalFilters.Length > 0) + applyAttrs.AddRange(globalFilters); + if(commandAttrs.Length > 0) + applyAttrs.AddRange(commandAttrs); + if(applyAttrs.Count > 0) + library.Add(command.Name, applyAttrs); + } + + return library; + } + + /// + /// Gets the filter attributes. + /// + /// The type. + /// + private static CommandFilterAttribute[] GetFilterAttributes(Type type) + { + var attrs = type.GetCustomAttributes(true); + return attrs.OfType().ToArray(); + } + } +} + diff --git a/SocketBase/Command/CommandBase.cs b/SocketBase/Command/CommandBase.cs new file mode 100644 index 000000000..5c656f3a6 --- /dev/null +++ b/SocketBase/Command/CommandBase.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.SocketBase.Command +{ + /// + /// Command base class + /// + /// The type of the app session. + /// The type of the request info. + public abstract class CommandBase : ICommand + where TAppSession : IAppSession, IAppSession, new() + where TRequestInfo : IRequestInfo + { + + #region ICommand Members + + /// + /// Executes the command. + /// + /// The session. + /// The request info. + public abstract void ExecuteCommand(TAppSession session, TRequestInfo requestInfo); + + #endregion + + #region ICommand Members + + /// + /// Gets the name. + /// + public virtual string Name + { + get { return this.GetType().Name; } + } + + #endregion + } +} diff --git a/SocketBase/Command/CommandLoaderBase.cs b/SocketBase/Command/CommandLoaderBase.cs new file mode 100644 index 000000000..459266587 --- /dev/null +++ b/SocketBase/Command/CommandLoaderBase.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.Common; +using SuperSocket.SocketBase.Config; + +namespace SuperSocket.SocketBase.Command +{ + /// + /// CommandLoader base class + /// + public abstract class CommandLoaderBase : ICommandLoader + { + /// + /// Initializes the command loader + /// + /// The type of the command. + /// The root config. + /// The app server. + /// + public abstract bool Initialize(IRootConfig rootConfig, IAppServer appServer) where TCommand : ICommand; + + /// + /// Tries to load commands. + /// + /// The commands. + /// + public abstract bool TryLoadCommands(out IEnumerable commands); + + /// + /// Called when [updated]. + /// + /// The commands. + protected void OnUpdated(IEnumerable> commands) + { + var handler = Updated; + + if (handler != null) + handler(this, new CommandUpdateEventArgs(commands)); + } + + /// + /// Occurs when [updated]. + /// + public event EventHandler> Updated; + + /// + /// Called when [error]. + /// + /// The message. + protected void OnError(string message) + { + OnError(new Exception(message)); + } + + /// + /// Called when [error]. + /// + /// The e. + protected void OnError(Exception e) + { + var handler = Error; + + if (handler != null) + handler(this, new ErrorEventArgs(e)); + } + + /// + /// Occurs when [error]. + /// + public event EventHandler Error; + } +} diff --git a/SocketBase/Command/CommandUpdateEventArgs.cs b/SocketBase/Command/CommandUpdateEventArgs.cs new file mode 100644 index 000000000..3a4a50a64 --- /dev/null +++ b/SocketBase/Command/CommandUpdateEventArgs.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.SocketBase.Command +{ + /// + /// CommandUpdateEventArgs + /// + /// + public class CommandUpdateEventArgs : EventArgs + { + /// + /// Gets the commands updated. + /// + public IEnumerable> Commands { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// The commands. + public CommandUpdateEventArgs(IEnumerable> commands) + { + Commands = commands; + } + } +} diff --git a/SocketBase/Command/CommandUpdateInfo.cs b/SocketBase/Command/CommandUpdateInfo.cs new file mode 100644 index 000000000..6946eae7d --- /dev/null +++ b/SocketBase/Command/CommandUpdateInfo.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.SocketBase.Command +{ + /// + /// Command update action enum + /// + public enum CommandUpdateAction + { + /// + /// Add command + /// + Add, + + /// + /// Remove command + /// + Remove, + + /// + /// Update command + /// + Update + } + + /// + /// Command update information + /// + /// + public class CommandUpdateInfo + { + /// + /// Gets or sets the update action. + /// + /// + /// The update action. + /// + public CommandUpdateAction UpdateAction { get; set; } + + /// + /// Gets or sets the target command. + /// + /// + /// The command. + /// + public T Command { get; set; } + } +} \ No newline at end of file diff --git a/SocketBase/Command/ICommand.cs b/SocketBase/Command/ICommand.cs new file mode 100644 index 000000000..2f310bbdd --- /dev/null +++ b/SocketBase/Command/ICommand.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.SocketBase.Command +{ + /// + /// Command basic interface + /// + public interface ICommand + { + /// + /// Gets the name. + /// + string Name { get; } + } + + /// + /// Command basic interface + /// + /// The type of the app session. + /// The type of the request info. + public interface ICommand : ICommand + where TRequestInfo : IRequestInfo + where TAppSession : IAppSession + { + /// + /// Executes the command. + /// + /// The session. + /// The request info. + void ExecuteCommand(TAppSession session, TRequestInfo requestInfo); + } + + /// + /// Mockup command + /// + /// The type of the app session. + /// The type of the request info. + public class MockupCommand : ICommand + where TRequestInfo : IRequestInfo + where TAppSession : IAppSession + { + /// + /// Initializes a new instance of the class. + /// + /// The name. + public MockupCommand(string name) + { + Name = name; + } + + /// + /// Executes the command. + /// + /// The session. + /// The request info. + public void ExecuteCommand(TAppSession session, TRequestInfo requestInfo) + { + + } + + /// + /// Gets the name. + /// + public string Name { get; private set; } + } +} \ No newline at end of file diff --git a/SocketBase/Command/ICommandLoader.cs b/SocketBase/Command/ICommandLoader.cs new file mode 100644 index 000000000..e223efd2d --- /dev/null +++ b/SocketBase/Command/ICommandLoader.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.Common; +using SuperSocket.SocketBase.Protocol; +using SuperSocket.SocketBase.Config; + +namespace SuperSocket.SocketBase.Command +{ + /// + /// Command loader's interface + /// + public interface ICommandLoader + { + /// + /// Initializes the command loader + /// + /// The type of the command. + /// The root config. + /// The app server. + /// + bool Initialize(IRootConfig rootConfig, IAppServer appServer) + where TCommand : ICommand; + + /// + /// Tries to load commands. + /// + /// The commands. + /// + bool TryLoadCommands(out IEnumerable commands); + + /// + /// Occurs when [updated]. + /// + event EventHandler> Updated; + + /// + /// Occurs when [error]. + /// + event EventHandler Error; + } +} diff --git a/SocketBase/Command/ReflectCommandLoader.cs b/SocketBase/Command/ReflectCommandLoader.cs new file mode 100644 index 000000000..07c440c02 --- /dev/null +++ b/SocketBase/Command/ReflectCommandLoader.cs @@ -0,0 +1,93 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Reflection; +using SuperSocket.Common; +using SuperSocket.SocketBase.Protocol; +using SuperSocket.SocketBase.Config; + +namespace SuperSocket.SocketBase.Command +{ + /// + /// A command loader which loads commands from assembly by reflection + /// + public class ReflectCommandLoader : CommandLoaderBase + { + private Type m_CommandType; + + private IAppServer m_AppServer; + + /// + /// Initializes the command loader + /// + /// The type of the command. + /// The root config. + /// The app server. + /// + public override bool Initialize(IRootConfig rootConfig, IAppServer appServer) + { + m_CommandType = typeof(TCommand); + m_AppServer = appServer; + return true; + } + + /// + /// Tries to load commands. + /// + /// The commands. + /// + public override bool TryLoadCommands(out IEnumerable commands) + { + commands = null; + + var commandAssemblies = new List(); + + if (m_AppServer.GetType().Assembly != this.GetType().Assembly) + commandAssemblies.Add(m_AppServer.GetType().Assembly); + + string commandAssembly = m_AppServer.Config.Options.GetValue("commandAssembly"); + + if (!string.IsNullOrEmpty(commandAssembly)) + { + try + { + var definedAssemblies = AssemblyUtil.GetAssembliesFromString(commandAssembly); + + if (definedAssemblies.Any()) + commandAssemblies.AddRange(definedAssemblies); + } + catch (Exception e) + { + OnError(new Exception("Failed to load defined command assemblies!", e)); + return false; + } + } + + if (!commandAssemblies.Any()) + { + OnError("You should configure the commandAssembly value!"); + return false; + } + + var outputCommands = new List(); + + foreach (var assembly in commandAssemblies) + { + try + { + outputCommands.AddRange(assembly.GetImplementedObjectsByInterface(m_CommandType)); + } + catch (Exception exc) + { + OnError(new Exception(string.Format("Failed to get commands from the assembly {0}!", assembly.FullName), exc)); + return false; + } + } + + commands = outputCommands; + + return true; + } + } +} diff --git a/SocketBase/Command/StringCommandBase.cs b/SocketBase/Command/StringCommandBase.cs new file mode 100644 index 000000000..806378160 --- /dev/null +++ b/SocketBase/Command/StringCommandBase.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.SocketBase.Command +{ + /// + /// A command type for whose request info type is StringRequestInfo + /// + /// The type of the app session. + public abstract class StringCommandBase : CommandBase + where TAppSession : IAppSession, IAppSession, new() + { + + } + + /// + /// A command type for whose request info type is StringRequestInfo + /// + public abstract class StringCommandBase : StringCommandBase + { + + } +} diff --git a/SocketBase/CommandFilterAttribute.cs b/SocketBase/CommandFilterAttribute.cs new file mode 100644 index 000000000..5b2e4970e --- /dev/null +++ b/SocketBase/CommandFilterAttribute.cs @@ -0,0 +1,28 @@ +using System; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Command; + +namespace SuperSocket.SocketBase +{ + /// + /// Command filter attribute + /// + [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] + public abstract class CommandFilterAttribute : Attribute + { + /// + /// Called when [command executing]. + /// + /// The session. + /// The command. + public abstract void OnCommandExecuting(IAppSession session, ICommand command); + + /// + /// Called when [command executed]. + /// + /// The session. + /// The command. + public abstract void OnCommandExecuted(IAppSession session, ICommand command); + } +} + diff --git a/SocketBase/Config/CertificateConfig.cs b/SocketBase/Config/CertificateConfig.cs new file mode 100644 index 000000000..3b067fa05 --- /dev/null +++ b/SocketBase/Config/CertificateConfig.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.SocketBase.Config +{ + /// + /// Certificate config model class + /// + [Serializable] + public class CertificateConfig : ICertificateConfig + { + #region ICertificateConfig Members + + /// + /// Gets/sets the file path. + /// + public string FilePath { get; set; } + + /// + /// Gets/sets the password. + /// + public string Password { get; set; } + + /// + /// Gets/sets the the store where certificate locates. + /// + /// + /// The name of the store. + /// + public string StoreName { get; set; } + + /// + /// Gets/sets the thumbprint. + /// + public string Thumbprint { get; set; } + + #endregion + } +} diff --git a/SocketBase/Config/ConfigurationSource.cs b/SocketBase/Config/ConfigurationSource.cs new file mode 100644 index 000000000..c4758a469 --- /dev/null +++ b/SocketBase/Config/ConfigurationSource.cs @@ -0,0 +1,92 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.Common; + +namespace SuperSocket.SocketBase.Config +{ + /// + /// Poco configuration source + /// + [Serializable] + public class ConfigurationSource : RootConfig, IConfigurationSource + { + /// + /// Initializes a new instance of the class. + /// + public ConfigurationSource() + { + + } + + /// + /// Initializes a new instance of the class. + /// + /// The source. + public ConfigurationSource(IConfigurationSource source) + : base(source) + { + if (source.Servers != null && source.Servers.Any()) + { + this.Servers = source.Servers.Select(s => new ServerConfig(s)).ToArray(); + } + + if (source.ServerTypes != null && source.ServerTypes.Any()) + { + this.ServerTypes = source.ServerTypes.Select(s => s.CopyPropertiesTo(new TypeProviderConfig())).ToArray(); + } + + if (source.ConnectionFilters != null && source.ConnectionFilters.Any()) + { + this.ConnectionFilters = source.ConnectionFilters.Select(s => s.CopyPropertiesTo(new TypeProviderConfig())).ToArray(); + } + + if (source.LogFactories != null && source.LogFactories.Any()) + { + this.LogFactories = source.LogFactories.Select(s => s.CopyPropertiesTo(new TypeProviderConfig())).ToArray(); + } + + if (source.RequestFilterFactories != null && source.RequestFilterFactories.Any()) + { + this.RequestFilterFactories = source.RequestFilterFactories.Select(s => s.CopyPropertiesTo(new TypeProviderConfig())).ToArray(); + } + + if (source.CommandLoaders != null && source.CommandLoaders.Any()) + { + this.CommandLoaders = source.CommandLoaders.Select(s => s.CopyPropertiesTo(new TypeProviderConfig())).ToArray(); + } + } + + + /// + /// Gets the servers definitions. + /// + public IEnumerable Servers { get; set; } + + /// + /// Gets/sets the server types definition. + /// + public IEnumerable ServerTypes { get; set; } + + /// + /// Gets/sets the connection filters definition. + /// + public IEnumerable ConnectionFilters { get; set; } + + /// + /// Gets/sets the log factories definition. + /// + public IEnumerable LogFactories { get; set; } + + /// + /// Gets/sets the request filter factories definition. + /// + public IEnumerable RequestFilterFactories { get; set; } + + /// + /// Gets/sets the command loaders definition. + /// + public IEnumerable CommandLoaders { get; set; } + } +} diff --git a/SocketBase/Config/ICertificateConfig.cs b/SocketBase/Config/ICertificateConfig.cs new file mode 100644 index 000000000..aeb827561 --- /dev/null +++ b/SocketBase/Config/ICertificateConfig.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace SuperSocket.SocketBase.Config +{ + /// + /// Certificate configuration interface + /// + public interface ICertificateConfig + { + /// + /// Gets the file path. + /// + string FilePath { get; } + + /// + /// Gets the password. + /// + string Password { get; } + + /// + /// Gets the the store where certificate locates. + /// + /// + /// The name of the store. + /// + string StoreName { get; } + + /// + /// Gets the thumbprint. + /// + string Thumbprint { get; } + } +} diff --git a/SocketBase/Config/IConfigurationSource.cs b/SocketBase/Config/IConfigurationSource.cs new file mode 100644 index 000000000..92febab5f --- /dev/null +++ b/SocketBase/Config/IConfigurationSource.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace SuperSocket.SocketBase.Config +{ + /// + /// Configuration source interface + /// + public interface IConfigurationSource : IRootConfig + { + /// + /// Gets the servers definitions. + /// + IEnumerable Servers { get; } + + /// + /// Gets the appServer types definition. + /// + IEnumerable ServerTypes { get; } + + /// + /// Gets the connection filters definition. + /// + IEnumerable ConnectionFilters { get; } + + /// + /// Gets the log factories definition. + /// + IEnumerable LogFactories { get; } + + /// + /// Gets the request filter factories definition. + /// + IEnumerable RequestFilterFactories { get; } + + /// + /// Gets the command loaders definition. + /// + IEnumerable CommandLoaders { get; } + } +} diff --git a/SocketBase/Config/IListenerConfig.cs b/SocketBase/Config/IListenerConfig.cs new file mode 100644 index 000000000..7fb2a5784 --- /dev/null +++ b/SocketBase/Config/IListenerConfig.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.SocketBase.Config +{ + /// + /// The listener configuration interface + /// + public interface IListenerConfig + { + /// + /// Gets the ip of listener + /// + string Ip { get; } + + /// + /// Gets the port of listener + /// + int Port { get; } + + /// + /// Gets the backlog. + /// + int Backlog { get; } + + /// + /// Gets the security option, None/Default/Tls/Ssl/... + /// + string Security { get; } + } +} diff --git a/SocketBase/Config/IRootConfig.cs b/SocketBase/Config/IRootConfig.cs new file mode 100644 index 000000000..1d3091460 --- /dev/null +++ b/SocketBase/Config/IRootConfig.cs @@ -0,0 +1,79 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Configuration; +using System.Collections.Specialized; + +namespace SuperSocket.SocketBase.Config +{ + /// + /// The root configuration interface + /// + public interface IRootConfig + { + /// + /// Gets the max working threads. + /// + int MaxWorkingThreads { get; } + + /// + /// Gets the min working threads. + /// + int MinWorkingThreads { get; } + + /// + /// Gets the max completion port threads. + /// + int MaxCompletionPortThreads { get; } + + /// + /// Gets the min completion port threads. + /// + int MinCompletionPortThreads { get; } + + + /// + /// Gets a value indicating whether [disable performance data collector]. + /// + /// + /// true if [disable performance data collector]; otherwise, false. + /// + bool DisablePerformanceDataCollector { get; } + + /// + /// Gets the performance data collect interval, in seconds. + /// + int PerformanceDataCollectInterval { get; } + + + /// + /// Gets the log factory name. + /// + /// + /// The log factory. + /// + string LogFactory { get; } + + + /// + /// Gets the isolation mode. + /// + IsolationMode Isolation { get; } + + + /// + /// Gets the option elements. + /// + NameValueCollection OptionElements { get; } + + /// + /// Gets the child config. + /// + /// The type of the config. + /// Name of the child config. + /// + TConfig GetChildConfig(string childConfigName) + where TConfig : ConfigurationElement, new(); + } +} diff --git a/SocketBase/Config/IServerConfig.cs b/SocketBase/Config/IServerConfig.cs new file mode 100644 index 000000000..461fe727f --- /dev/null +++ b/SocketBase/Config/IServerConfig.cs @@ -0,0 +1,235 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Configuration; +using System.Security.Authentication; +using System.Collections.Specialized; + +namespace SuperSocket.SocketBase.Config +{ + /// + /// Server instance configuation interface + /// + public interface IServerConfig + { + /// + /// Gets the name of the server type this appServer want to use. + /// + /// + /// The name of the server type. + /// + string ServerTypeName { get; } + + /// + /// Gets the type definition of the appserver. + /// + /// + /// The type of the server. + /// + string ServerType { get; } + + /// + /// Gets the request filter factory. + /// + string RequestFilterFactory { get; } + + /// + /// Gets the ip. + /// + string Ip { get; } + + /// + /// Gets the port. + /// + int Port { get; } + + /// + /// Gets the options. + /// + NameValueCollection Options { get; } + + + /// + /// Gets the option elements. + /// + NameValueCollection OptionElements { get; } + + /// + /// Gets a value indicating whether this is disabled. + /// + /// + /// true if disabled; otherwise, false. + /// + bool Disabled { get; } + + /// + /// Gets the name. + /// + string Name { get; } + + /// + /// Gets the mode. + /// + SocketMode Mode { get; } + + /// + /// Gets the send time out. + /// + int SendTimeOut { get; } + + /// + /// Gets the max connection number. + /// + int MaxConnectionNumber { get; } + + /// + /// Gets the size of the receive buffer. + /// + /// + /// The size of the receive buffer. + /// + int ReceiveBufferSize { get; } + + /// + /// Gets the size of the send buffer. + /// + /// + /// The size of the send buffer. + /// + int SendBufferSize { get; } + + + /// + /// Gets a value indicating whether sending is in synchronous mode. + /// + /// + /// true if [sync send]; otherwise, false. + /// + bool SyncSend { get; } + + /// + /// Gets a value indicating whether log command in log file. + /// + /// true if log command; otherwise, false. + bool LogCommand { get; } + + /// + /// Gets a value indicating whether clear idle session. + /// + /// true if clear idle session; otherwise, false. + bool ClearIdleSession { get; } + + /// + /// Gets the clear idle session interval, in seconds. + /// + /// The clear idle session interval. + int ClearIdleSessionInterval { get; } + + + /// + /// Gets the idle session timeout time length, in seconds. + /// + /// The idle session time out. + int IdleSessionTimeOut { get; } + + /// + /// Gets X509Certificate configuration. + /// + /// X509Certificate configuration. + ICertificateConfig Certificate { get; } + + + /// + /// Gets the security protocol, X509 certificate. + /// + string Security { get; } + + + /// + /// Gets the length of the max request. + /// + /// + /// The length of the max request. + /// + int MaxRequestLength { get; } + + + /// + /// Gets a value indicating whether [disable session snapshot]. + /// + /// + /// true if [disable session snapshot]; otherwise, false. + /// + bool DisableSessionSnapshot { get; } + /// + /// Gets the interval to taking snapshot for all live sessions. + /// + int SessionSnapshotInterval { get; } + + /// + /// Gets the connection filters used by this server instance. + /// + /// + /// The connection filter's name list, seperated by comma + /// + string ConnectionFilter { get; } + + /// + /// Gets the command loader, multiple values should be separated by comma. + /// + string CommandLoader { get; } + + /// + /// Gets the start keep alive time, in seconds + /// + int KeepAliveTime { get; } + + + /// + /// Gets the keep alive interval, in seconds. + /// + int KeepAliveInterval { get; } + + + /// + /// Gets the backlog size of socket listening. + /// + int ListenBacklog { get; } + + + /// + /// Gets the startup order of the server instance. + /// + int StartupOrder { get; } + + + /// + /// Gets the child config. + /// + /// The type of the config. + /// Name of the child config. + /// + TConfig GetChildConfig(string childConfigName) + where TConfig : ConfigurationElement, new(); + + + /// + /// Gets the listeners' configuration. + /// + IEnumerable Listeners { get; } + + /// + /// Gets the log factory name. + /// + string LogFactory { get; } + + + /// + /// Gets the size of the sending queue. + /// + /// + /// The size of the sending queue. + /// + int SendingQueueSize { get; } + } +} diff --git a/SocketBase/Config/ITypeProvider.cs b/SocketBase/Config/ITypeProvider.cs new file mode 100644 index 000000000..2543e86c8 --- /dev/null +++ b/SocketBase/Config/ITypeProvider.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace SuperSocket.SocketBase.Config +{ + /// + /// TypeProvider's interface + /// + public interface ITypeProvider + { + /// + /// Gets the name. + /// + string Name { get; } + + /// + /// Gets the type. + /// + string Type { get; } + } +} diff --git a/SocketBase/Config/ListenerConfig.cs b/SocketBase/Config/ListenerConfig.cs new file mode 100644 index 000000000..4dcef360c --- /dev/null +++ b/SocketBase/Config/ListenerConfig.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.SocketBase.Config +{ + /// + /// Listener configuration model + /// + [Serializable] + public class ListenerConfig : IListenerConfig + { + /// + /// Initializes a new instance of the class. + /// + public ListenerConfig() + { + Backlog = 100; + } + + /// + /// Gets the ip of listener + /// + public string Ip { get; set; } + + /// + /// Gets the port of listener + /// + public int Port { get; set; } + + + /// + /// Gets the backlog. + /// + public int Backlog { get; set; } + + /// + /// Gets/sets the security option, None/Default/Tls/Ssl/... + /// + public string Security { get; set; } + } +} diff --git a/SocketBase/Config/RootConfig.cs b/SocketBase/Config/RootConfig.cs new file mode 100644 index 000000000..3516f9fce --- /dev/null +++ b/SocketBase/Config/RootConfig.cs @@ -0,0 +1,115 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using SuperSocket.Common; +using System.Collections.Specialized; +using System.Configuration; + +namespace SuperSocket.SocketBase.Config +{ + /// + /// Root configuration model + /// + [Serializable] + public class RootConfig : IRootConfig + { + /// + /// Initializes a new instance of the class. + /// + /// The root config. + public RootConfig(IRootConfig rootConfig) + { + rootConfig.CopyPropertiesTo(this); + this.OptionElements = rootConfig.OptionElements; + } + + /// + /// Initializes a new instance of the class. + /// + public RootConfig() + { + int maxWorkingThread, maxCompletionPortThreads; + ThreadPool.GetMaxThreads(out maxWorkingThread, out maxCompletionPortThreads); + MaxWorkingThreads = maxWorkingThread; + MaxCompletionPortThreads = maxCompletionPortThreads; + + int minWorkingThread, minCompletionPortThreads; + ThreadPool.GetMinThreads(out minWorkingThread, out minCompletionPortThreads); + MinWorkingThreads = minWorkingThread; + MinCompletionPortThreads = minCompletionPortThreads; + + PerformanceDataCollectInterval = 60; + + Isolation = IsolationMode.None; + } + + #region IRootConfig Members + + /// + /// Gets/Sets the max working threads. + /// + public int MaxWorkingThreads { get; set; } + + /// + /// Gets/sets the min working threads. + /// + public int MinWorkingThreads { get; set; } + + /// + /// Gets/sets the max completion port threads. + /// + public int MaxCompletionPortThreads { get; set; } + + /// + /// Gets/sets the min completion port threads. + /// + public int MinCompletionPortThreads { get; set; } + + /// + /// Gets/sets the performance data collect interval, in seconds. + /// + public int PerformanceDataCollectInterval { get; set; } + + /// + /// Gets/sets a value indicating whether [disable performance data collector]. + /// + /// + /// true if [disable performance data collector]; otherwise, false. + /// + public bool DisablePerformanceDataCollector { get; set; } + + /// + /// Gets/sets the isolation mode. + /// + public IsolationMode Isolation { get; set; } + + /// + /// Gets/sets the log factory name. + /// + /// + /// The log factory. + /// + public string LogFactory { get; set; } + + /// + /// Gets/sets the option elements. + /// + public NameValueCollection OptionElements { get; set; } + + /// + /// Gets the child config. + /// + /// The type of the config. + /// Name of the child config. + /// + public virtual TConfig GetChildConfig(string childConfigName) + where TConfig : ConfigurationElement, new() + { + return this.OptionElements.GetChildConfig(childConfigName); + } + + #endregion + } +} diff --git a/SocketBase/Config/ServerConfig.cs b/SocketBase/Config/ServerConfig.cs new file mode 100644 index 000000000..ce23377cb --- /dev/null +++ b/SocketBase/Config/ServerConfig.cs @@ -0,0 +1,280 @@ +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Configuration; +using System.Linq; +using System.Security.Authentication; +using System.Text; +using SuperSocket.Common; + +namespace SuperSocket.SocketBase.Config +{ + /// + /// Server configruation model + /// + [Serializable] + public class ServerConfig : IServerConfig + { + /// + /// Initializes a new instance of the class. + /// + /// The server config. + public ServerConfig(IServerConfig serverConfig) + { + serverConfig.CopyPropertiesTo(this); + + this.Options = serverConfig.Options; + this.OptionElements = serverConfig.OptionElements; + + if (serverConfig.Certificate != null) + this.Certificate = serverConfig.Certificate.CopyPropertiesTo(new CertificateConfig()); + + if (serverConfig.Listeners != null && serverConfig.Listeners.Any()) + { + this.Listeners = serverConfig.Listeners.Select(l => l.CopyPropertiesTo(new ListenerConfig())); + } + } + + /// + /// Initializes a new instance of the class. + /// + public ServerConfig() + { + Security = "None"; + MaxConnectionNumber = 100; + Mode = SocketMode.Tcp; + MaxRequestLength = 1024; + KeepAliveTime = 10 * 60;// 10 minutes + KeepAliveInterval = 60;// 60 seconds + ListenBacklog = 100; + } + + #region IServerConfig Members + + /// + /// Gets/sets the name of the server type of this appServer want to use. + /// + /// + /// The name of the server type. + /// + public string ServerTypeName { get; set; } + + + /// + /// Gets/sets the type definition of the appserver. + /// + /// + /// The type of the server. + /// + public string ServerType { get; set; } + + /// + /// Gets/sets the request filter factory. + /// + public string RequestFilterFactory { get; set; } + + /// + /// Gets/sets the ip. + /// + public string Ip { get; set; } + + /// + /// Gets/sets the port. + /// + public int Port { get; set; } + + /// + /// Gets/sets the options. + /// + public NameValueCollection Options { get; set; } + + /// + /// Gets the option elements. + /// + public NameValueCollection OptionElements { get; set; } + + /// + /// Gets/sets a value indicating whether this is disabled. + /// + /// + /// true if disabled; otherwise, false. + /// + public bool Disabled { get; set; } + + /// + /// Gets the name. + /// + public string Name { get; set; } + + /// + /// Gets/sets the mode. + /// + public SocketMode Mode { get; set; } + + /// + /// Gets/sets the send time out. + /// + public int SendTimeOut { get; set; } + + /// + /// Gets the max connection number. + /// + public int MaxConnectionNumber { get; set; } + + /// + /// Gets the size of the receive buffer. + /// + /// + /// The size of the receive buffer. + /// + public int ReceiveBufferSize { get; set; } + + /// + /// Gets the size of the send buffer. + /// + /// + /// The size of the send buffer. + /// + public int SendBufferSize { get; set; } + + + /// + /// Gets a value indicating whether sending is in synchronous mode. + /// + /// + /// true if [sync send]; otherwise, false. + /// + public bool SyncSend { get; set; } + + /// + /// Gets/sets a value indicating whether log command in log file. + /// + /// + /// true if log command; otherwise, false. + /// + public bool LogCommand { get; set; } + + /// + /// Gets/sets a value indicating whether clear idle session. + /// + /// + /// true if clear idle session; otherwise, false. + /// + public bool ClearIdleSession { get; set; } + + /// + /// Gets/sets the clear idle session interval, in seconds. + /// + /// + /// The clear idle session interval. + /// + public int ClearIdleSessionInterval { get; set; } + + /// + /// Gets/sets the idle session timeout time length, in seconds. + /// + /// + /// The idle session time out. + /// + public int IdleSessionTimeOut { get; set; } + + /// + /// Gets/sets X509Certificate configuration. + /// + /// + /// X509Certificate configuration. + /// + public ICertificateConfig Certificate { get; set; } + + /// + /// Gets/sets the security protocol, X509 certificate. + /// + public string Security { get; set; } + + /// + /// Gets/sets the length of the max request. + /// + /// + /// The length of the max request. + /// + public int MaxRequestLength { get; set; } + + /// + /// Gets/sets a value indicating whether [disable session snapshot]. + /// + /// + /// true if [disable session snapshot]; otherwise, false. + /// + public bool DisableSessionSnapshot { get; set; } + + /// + /// Gets/sets the interval to taking snapshot for all live sessions. + /// + public int SessionSnapshotInterval { get; set; } + + /// + /// Gets/sets the connection filters used by this server instance. + /// + /// + /// The connection filter's name list, seperated by comma + /// + public string ConnectionFilter { get; set; } + + /// + /// Gets the command loader, multiple values should be separated by comma. + /// + public string CommandLoader { get; set; } + + /// + /// Gets/sets the start keep alive time, in seconds + /// + public int KeepAliveTime { get; set; } + + /// + /// Gets/sets the keep alive interval, in seconds. + /// + public int KeepAliveInterval { get; set; } + + /// + /// Gets the backlog size of socket listening. + /// + public int ListenBacklog { get; set; } + + /// + /// Gets/sets the startup order of the server instance. + /// + public int StartupOrder { get; set; } + + /// + /// Gets the child config. + /// + /// The type of the config. + /// Name of the child config. + /// + public virtual TConfig GetChildConfig(string childConfigName) + where TConfig : ConfigurationElement, new() + { + return this.OptionElements.GetChildConfig(childConfigName); + } + + /// + /// Gets and sets the listeners' configuration. + /// + public IEnumerable Listeners { get; set; } + + /// + /// Gets/sets the log factory name. + /// + public string LogFactory { get; set; } + + /// + /// Gets/sets the size of the sending queue. + /// + /// + /// The size of the sending queue. + /// + public int SendingQueueSize { get; set; } + + #endregion + } +} diff --git a/SocketBase/Config/TypeProvider.cs b/SocketBase/Config/TypeProvider.cs new file mode 100644 index 000000000..2278b8b6a --- /dev/null +++ b/SocketBase/Config/TypeProvider.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Configuration; + +namespace SuperSocket.SocketBase.Config +{ + /// + /// Type provider configuration + /// + public class TypeProvider : ConfigurationElement, ITypeProvider + { + /// + /// Gets the name. + /// + [ConfigurationProperty("name", IsRequired = true)] + public string Name + { + get { return this["name"] as string; } + } + + /// + /// Gets the type. + /// + [ConfigurationProperty("type", IsRequired = true)] + public string Type + { + get { return this["type"] as string; } + } + } +} diff --git a/SocketBase/Config/TypeProviderCollection.cs b/SocketBase/Config/TypeProviderCollection.cs new file mode 100644 index 000000000..3800006b2 --- /dev/null +++ b/SocketBase/Config/TypeProviderCollection.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Configuration; + +namespace SuperSocket.SocketBase.Config +{ + /// + /// Type provider colletion configuration + /// + [ConfigurationCollection(typeof(TypeProvider))] + public class TypeProviderCollection : ConfigurationElementCollection, IEnumerable + { + /// + /// When overridden in a derived class, creates a new . + /// + /// + /// A new . + /// + protected override ConfigurationElement CreateNewElement() + { + return new TypeProvider() as ConfigurationElement; + } + + /// + /// Gets the element key for a specified configuration element when overridden in a derived class. + /// + /// The to return the key for. + /// + /// An that acts as the key for the specified . + /// + protected override object GetElementKey(ConfigurationElement element) + { + var provider = element as TypeProvider; + + if (provider == null) + return null; + + return provider.Name; + } + + /// + /// Returns an enumerator that iterates through the collection. + /// + /// + /// A that can be used to iterate through the collection. + /// + public new IEnumerator GetEnumerator() + { + int count = base.Count; + + for (int i = 0; i < count; i++) + { + yield return (ITypeProvider)base.BaseGet(i); + } + } + } +} diff --git a/SocketBase/Config/TypeProviderConfig.cs b/SocketBase/Config/TypeProviderConfig.cs new file mode 100644 index 000000000..a99417fcb --- /dev/null +++ b/SocketBase/Config/TypeProviderConfig.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.SocketBase.Config +{ + /// + /// TypeProviderConfig + /// + [Serializable] + public class TypeProviderConfig : ITypeProvider + { + /// + /// Gets the name. + /// + public string Name { get; set; } + + /// + /// Gets the type. + /// + public string Type { get; set; } + } +} diff --git a/SocketBase/IAppServer.cs b/SocketBase/IAppServer.cs new file mode 100644 index 000000000..2d4aa6c21 --- /dev/null +++ b/SocketBase/IAppServer.cs @@ -0,0 +1,224 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Authentication; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using SuperSocket.Common; +using SuperSocket.SocketBase.Logging; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Config; +using SuperSocket.SocketBase.Protocol; +using System.Collections; +using SuperSocket.SocketBase.Provider; + +namespace SuperSocket.SocketBase +{ + /// + /// The interface for who will react with performance collecting + /// + public interface IPerformanceDataSource + { + /// + /// Collects the performance data. + /// + /// The global perf data. + /// + PerformanceData CollectPerformanceData(GlobalPerformanceData globalPerfData); + } + + /// + /// An item can be started and stopped + /// + public interface IWorkItem + { + /// + /// Gets the name. + /// + string Name { get; } + + /// + /// Setups with the specified root config. + /// + /// The bootstrap. + /// The socket server instance config. + /// The factories. + /// + bool Setup(IBootstrap bootstrap, IServerConfig config, ProviderFactoryInfo[] factories); + + + /// + /// Starts this server instance. + /// + /// return true if start successfull, else false + bool Start(); + + + /// + /// Gets a value indicating whether this instance is running. + /// + /// + /// true if this instance is running; otherwise, false. + /// + bool IsRunning { get; } + + /// + /// Stops this server instance. + /// + void Stop(); + + /// + /// Gets the total session count. + /// + int SessionCount { get; } + } + + /// + /// The interface for AppServer + /// + public interface IAppServer : IWorkItem, ILoggerProvider + { + /// + /// Gets the started time. + /// + /// + /// The started time. + /// + DateTime StartedTime { get; } + + + /// + /// Gets or sets the listeners. + /// + /// + /// The listeners. + /// + ListenerInfo[] Listeners { get; } + + /// + /// Gets the request filter factory. + /// + object RequestFilterFactory { get; } + + + /// + /// Gets the server's config. + /// + IServerConfig Config { get; } + + /// + /// Gets the certificate of current server. + /// + X509Certificate Certificate { get; } + + /// + /// Gets the transfer layer security protocol. + /// + SslProtocols BasicSecurity { get; } + + /// + /// Creates the app session. + /// + /// The socket session. + /// + IAppSession CreateAppSession(ISocketSession socketSession); + + /// + /// Gets the app session by ID. + /// + /// The session ID. + /// + IAppSession GetAppSessionByID(string sessionID); + + /// + /// Resets the session's security protocol. + /// + /// The session. + /// The security protocol. + void ResetSessionSecurity(IAppSession session, SslProtocols security); + + /// + /// Gets the log factory. + /// + ILogFactory LogFactory { get; } + } + + /// + /// The raw data processor + /// + /// The type of the app session. + public interface IRawDataProcessor + where TAppSession : IAppSession + { + /// + /// Gets or sets the raw binary data received event handler. + /// TAppSession: session + /// byte[]: receive buffer + /// int: receive buffer offset + /// int: receive lenght + /// bool: whether process the received data further + /// + event Func RawDataReceived; + } + + /// + /// The interface for AppServer + /// + /// The type of the app session. + public interface IAppServer : IAppServer + where TAppSession : IAppSession + { + /// + /// Gets the matched sessions from sessions snapshot. + /// + /// The prediction critera. + /// + IEnumerable GetSessions(Func critera); + + /// + /// Gets all sessions in sessions snapshot. + /// + /// + IEnumerable GetAllSessions(); + + /// + /// Gets/sets the new session connected event handler. + /// + event Action NewSessionConnected; + + /// + /// Gets/sets the session closed event handler. + /// + event Action SessionClosed; + } + + /// + /// The interface for AppServer + /// + /// The type of the app session. + /// The type of the request info. + public interface IAppServer : IAppServer + where TRequestInfo : IRequestInfo + where TAppSession : IAppSession, IAppSession, new() + { + /// + /// Occurs when [request comming]. + /// + event RequestHandler RequestHandler; + } + + /// + /// The interface for handler of session request + /// + /// The type of the request info. + public interface IRequestHandler + where TRequestInfo : IRequestInfo + { + /// + /// Executes the command. + /// + /// The session. + /// The request info. + void ExecuteCommand(IAppSession session, TRequestInfo requestInfo); + } +} diff --git a/SocketBase/IAppSession.cs b/SocketBase/IAppSession.cs new file mode 100644 index 000000000..d26656d0c --- /dev/null +++ b/SocketBase/IAppSession.cs @@ -0,0 +1,173 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Text; +using SuperSocket.Common; +using SuperSocket.SocketBase.Logging; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Config; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.SocketBase +{ + /// + /// The basic interface for appSession + /// + public interface IAppSession : ISessionBase + { + /// + /// Gets the app server. + /// + IAppServer AppServer { get; } + /// + /// Gets the socket session of the AppSession. + /// + ISocketSession SocketSession { get; } + + /// + /// Gets the items. + /// + IDictionary Items { get; } + + /// + /// Gets the config of the server. + /// + IServerConfig Config { get; } + + /// + /// Gets the local listening endpoint. + /// + IPEndPoint LocalEndPoint { get; } + + /// + /// Gets or sets the last active time of the session. + /// + /// + /// The last active time. + /// + DateTime LastActiveTime { get; set; } + + /// + /// Gets the start time of the session. + /// + DateTime StartTime { get; } + + /// + /// Closes this session. + /// + void Close(); + + /// + /// Closes the session by the specified reason. + /// + /// The close reason. + void Close(CloseReason reason); + + /// + /// Handles the exceptional error. + /// + /// The e. + void HandleException(Exception e); + + /// + /// Gets a value indicating whether this is connected. + /// + /// + /// true if connected; otherwise, false. + /// + bool Connected { get; } + + /// + /// Gets or sets the charset which is used for transfering text message. + /// + /// The charset. + Encoding Charset { get; set; } + + /// + /// Gets or sets the previous command. + /// + /// + /// The prev command. + /// + string PrevCommand { get; set; } + + /// + /// Gets or sets the current executing command. + /// + /// + /// The current command. + /// + string CurrentCommand { get; set; } + + /// + /// Gets the logger assosiated with this session. + /// + ILog Logger { get; } + + /// + /// Processes the request. + /// + /// The read buffer. + /// The offset. + /// The length. + /// if set to true [to be copied]. + /// return offset delta of next receiving buffer + int ProcessRequest(byte[] readBuffer, int offset, int length, bool toBeCopied); + + /// + /// Starts the session. + /// + void StartSession(); + + + /// + /// Tries to get the data segment to be sent. + /// + /// The segments. + /// + /// return whether has data to send + /// + bool TryGetSendingData(IList> segments); + } + + /// + /// The interface for appSession + /// + /// The type of the request info. + public interface IAppSession : IAppSession + where TRequestInfo : IRequestInfo + { + /// + /// Handles the unknown request. + /// + /// The request info. + void HandleUnknownRequest(TRequestInfo requestInfo); + } + + /// + /// The interface for appSession + /// + /// The type of the app session. + /// The type of the request info. + public interface IAppSession : IAppSession + where TRequestInfo : IRequestInfo + where TAppSession : IAppSession, IAppSession, new() + { + /// + /// Initializes the specified session. + /// + /// The server. + /// The socket session. + /// The request filter. + void Initialize(IAppServer server, ISocketSession socketSession, IRequestFilter requestFilter); + + /// + /// Executes the command. + /// + /// The session. + /// The request info. + void ExecuteCommand(TAppSession session, TRequestInfo cmdInfo); + } +} diff --git a/SocketBase/IBootstrap.cs b/SocketBase/IBootstrap.cs new file mode 100644 index 000000000..8996e2717 --- /dev/null +++ b/SocketBase/IBootstrap.cs @@ -0,0 +1,101 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Config; +using SuperSocket.SocketBase.Logging; + +namespace SuperSocket.SocketBase +{ + /// + /// The bookstrap start result + /// + public enum StartResult + { + /// + /// No appserver has been set in the bootstrap, so nothing was started + /// + None, + /// + /// All appserver instances were started successfully + /// + Success, + /// + /// Some appserver instances were started successfully, but some of them failed + /// + PartialSuccess, + /// + /// All appserver instances failed to start + /// + Failed + } + + /// + /// SuperSocket bootstrap + /// + public interface IBootstrap + { + /// + /// Gets all the app servers running in this bootstrap + /// + IEnumerable AppServers { get; } + + /// + /// Gets the config. + /// + IRootConfig Config { get; } + + /// + /// Initializes the bootstrap with the configuration + /// + /// + bool Initialize(); + + + /// + /// Initializes the bootstrap with the configuration + /// + /// The server config resolver. + /// + bool Initialize(Func serverConfigResolver); + + + /// + /// Initializes the bootstrap with the configuration + /// + /// The log factory. + /// + bool Initialize(ILogFactory logFactory); + + /// + /// Initializes the bootstrap with the configuration + /// + /// The server config resolver. + /// The log factory. + /// + bool Initialize(Func serverConfigResolver, ILogFactory logFactory); + + /// + /// Starts this bootstrap. + /// + /// + StartResult Start(); + + /// + /// Stops this bootstrap. + /// + void Stop(); + + /// + /// Occurs when [performance data collected]. + /// + event EventHandler PerformanceDataCollected; + + /// + /// Gets the startup config file. + /// + string StartupConfigFile { get; } + } +} diff --git a/SocketBase/ICommandSource.cs b/SocketBase/ICommandSource.cs new file mode 100644 index 000000000..33ec5968b --- /dev/null +++ b/SocketBase/ICommandSource.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Command; + +namespace SuperSocket.SocketBase +{ + /// + /// The interface for class who provides commands source + /// + /// The type of the command. + public interface ICommandSource where TCommand : ICommand + { + /// + /// Gets the command by it's name. + /// + /// Name of the command. + /// + TCommand GetCommandByName(string commandName); + } +} diff --git a/SocketBase/IConnectionFilter.cs b/SocketBase/IConnectionFilter.cs new file mode 100644 index 000000000..275d9c860 --- /dev/null +++ b/SocketBase/IConnectionFilter.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Specialized; +using System.Configuration.Provider; +using System.Net; +using SuperSocket.SocketBase.Config; + +namespace SuperSocket.SocketBase +{ + /// + /// The basic interface of connection filter + /// + public interface IConnectionFilter + { + /// + /// Initializes the connection filter + /// + /// The name. + /// The app server. + /// + bool Initialize(string name, IAppServer appServer); + + /// + /// Gets the name of the filter. + /// + string Name { get; } + + /// + /// Whether allows the connect according the remote endpoint + /// + /// The remote address. + /// + bool AllowConnect(IPEndPoint remoteAddress); + } +} + diff --git a/SocketBase/ILoggerProvider.cs b/SocketBase/ILoggerProvider.cs new file mode 100644 index 000000000..313524bda --- /dev/null +++ b/SocketBase/ILoggerProvider.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Logging; + +namespace SuperSocket.SocketBase +{ + /// + /// The interface for who provides logger + /// + public interface ILoggerProvider + { + /// + /// Gets the logger assosiated with this object. + /// + ILog Logger { get; } + } +} diff --git a/SocketBase/ISessionBase.cs b/SocketBase/ISessionBase.cs new file mode 100644 index 000000000..9a6cb79b3 --- /dev/null +++ b/SocketBase/ISessionBase.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Net; + +namespace SuperSocket.SocketBase +{ + /// + /// The basic session interface + /// + public interface ISessionBase + { + /// + /// Gets the session ID. + /// + string SessionID { get; } + + /// + /// Gets the remote endpoint. + /// + IPEndPoint RemoteEndPoint { get; } + } +} diff --git a/SocketBase/ISocketServer.cs b/SocketBase/ISocketServer.cs new file mode 100644 index 000000000..49b8b1b8a --- /dev/null +++ b/SocketBase/ISocketServer.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Security.Authentication; + +namespace SuperSocket.SocketBase +{ + /// + /// It is the basic interface of SocketServer, + /// SocketServer is the abstract server who really listen the comming sockets directly. + /// + public interface ISocketServer + { + /// + /// Starts this instance. + /// + /// + bool Start(); + + /// + /// Resets the session's security protocol. + /// + /// The session. + /// The security protocol. + void ResetSessionSecurity(IAppSession session, SslProtocols security); + /// + /// Gets a value indicating whether this instance is running. + /// + /// + /// true if this instance is running; otherwise, false. + /// + bool IsRunning { get; } + + /// + /// Stops this instance. + /// + void Stop(); + } +} diff --git a/SocketBase/ISocketServerFactory.cs b/SocketBase/ISocketServerFactory.cs new file mode 100644 index 000000000..aa973d97f --- /dev/null +++ b/SocketBase/ISocketServerFactory.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Text; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Config; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.SocketBase +{ + /// + /// The interface for socket server factory + /// + public interface ISocketServerFactory + { + /// + /// Creates the socket server instance. + /// + /// The type of the request info. + /// The app server. + /// The listeners. + /// The config. + /// The request filter factory. + /// + ISocketServer CreateSocketServer(IAppServer appServer, ListenerInfo[] listeners, IServerConfig config, IRequestFilterFactory requestFilterFactory) + where TRequestInfo : IRequestInfo; + } +} diff --git a/SocketBase/ISocketSession.cs b/SocketBase/ISocketSession.cs new file mode 100644 index 000000000..26d30aebf --- /dev/null +++ b/SocketBase/ISocketSession.cs @@ -0,0 +1,119 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.IO; +using System.Net; +using System.Security.Authentication; +using System.Net.Sockets; +using SuperSocket.SocketBase.Command; + +namespace SuperSocket.SocketBase +{ + /// + /// CloseReason enum + /// + public enum CloseReason + { + /// + /// Close for server shutdown + /// + ServerShutdown, + + /// + /// The client close the socket + /// + ClientClosing, + + /// + /// The server side close the socket + /// + ServerClosing, + + /// + /// Application error + /// + ApplicationError, + + /// + /// The socket is closed for a socket error + /// + SocketError, + + /// + /// The socket is closed by server for timeout + /// + TimeOut, + + /// + /// Protocol error + /// + ProtocolError, + + /// + /// The socket is closed for unknown reason + /// + Unknown + } + + /// + /// The interface for socket session + /// + public interface ISocketSession : ISessionBase + { + /// + /// Initializes the specified app session. + /// + /// The app session. + void Initialize(IAppSession appSession); + + /// + /// Starts this instance. + /// + void Start(); + + /// + /// Closes the socket session for the specified reason. + /// + /// The reason. + void Close(CloseReason reason); + + /// + /// Starts the sending. + /// + void StartSend(); + + /// + /// Applies the secure protocol. + /// + void ApplySecureProtocol(); + + /// + /// Gets the client socket. + /// + Socket Client { get; } + + /// + /// Gets the local listening endpoint. + /// + IPEndPoint LocalEndPoint { get; } + + /// + /// Gets or sets the secure protocol. + /// + /// + /// The secure protocol. + /// + SslProtocols SecureProtocol { get; set; } + + /// + /// Occurs when [closed]. + /// + Action Closed { get; set; } + + /// + /// Gets the app session assosiated with this socket session. + /// + IAppSession AppSession { get; } + } +} diff --git a/SocketBase/IsolationMode.cs b/SocketBase/IsolationMode.cs new file mode 100644 index 000000000..8203a4a70 --- /dev/null +++ b/SocketBase/IsolationMode.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.SocketBase +{ + /// + /// AppServer instance running isolation mode + /// + public enum IsolationMode + { + /// + /// No isolation + /// + None, + /// + /// Isolation by AppDomain + /// + AppDomain + } +} diff --git a/SocketBase/ListenerInfo.cs b/SocketBase/ListenerInfo.cs new file mode 100644 index 000000000..5e3763d01 --- /dev/null +++ b/SocketBase/ListenerInfo.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Net; +using System.Security.Authentication; + +namespace SuperSocket.SocketBase +{ + /// + /// Listener inforamtion + /// + public class ListenerInfo + { + /// + /// Gets or sets the listen endpoint. + /// + /// + /// The end point. + /// + public IPEndPoint EndPoint { get; set; } + + /// + /// Gets or sets the listen backlog. + /// + /// + /// The back log. + /// + public int BackLog { get; set; } + + /// + /// Gets or sets the security protocol. + /// + /// + /// The security. + /// + public SslProtocols Security { get; set; } + } +} diff --git a/SocketBase/LoggerExtension.cs b/SocketBase/LoggerExtension.cs new file mode 100644 index 000000000..98fab2faf --- /dev/null +++ b/SocketBase/LoggerExtension.cs @@ -0,0 +1,103 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.Common; +using SuperSocket.SocketBase.Logging; + +namespace SuperSocket.SocketBase +{ + /// + /// Logger extension class + /// + public static class LoggerExtension + { + private readonly static string m_SessionInfoTemplate = "Session: {0}/{1}"; + + /// + /// Logs the error + /// + /// The logger. + /// The session. + /// The e. + public static void Error(this ILog logger, ISessionBase session, Exception e) + { + logger.Error(string.Format(m_SessionInfoTemplate, session.SessionID, session.RemoteEndPoint), e); + } + + /// + /// Logs the error + /// + /// The logger. + /// The session. + /// The title. + /// The e. + public static void Error(this ILog logger, ISessionBase session, string title, Exception e) + { + logger.Error(string.Format(m_SessionInfoTemplate, session.SessionID, session.RemoteEndPoint) + Environment.NewLine + title, e); + } + + /// + /// Logs the error + /// + /// The logger. + /// The session. + /// The message. + public static void Error(this ILog logger, ISessionBase session, string message) + { + logger.Error(string.Format(m_SessionInfoTemplate, session.SessionID, session.RemoteEndPoint) + Environment.NewLine + message); + } + + /// + /// Logs the information + /// + /// The logger. + /// The session. + /// The message. + public static void Info(this ILog logger, ISessionBase session, string message) + { + string info = string.Format(m_SessionInfoTemplate, session.SessionID, session.RemoteEndPoint) + Environment.NewLine + message; + logger.Info(info); + } + + /// + /// Logs the debug message + /// + /// The logger. + /// The session. + /// The message. + public static void Debug(this ILog logger, ISessionBase session, string message) + { + if (!logger.IsDebugEnabled) + return; + + logger.Debug(string.Format(m_SessionInfoTemplate, session.SessionID, session.RemoteEndPoint) + Environment.NewLine + message); + } + + private const string m_PerfLogName = "Perf"; + + private static ILog m_PerfLog; + + /// + /// Logs the performance message + /// + /// The app server. + /// The message. + public static void LogPerf(this IAppServer appServer, string message) + { + if (m_PerfLog == null) + { + lock (m_PerfLogName) + { + if (m_PerfLog == null) + { + m_PerfLog = appServer.LogFactory.GetLog(m_PerfLogName); + } + } + } + + if (m_PerfLog != null && m_PerfLog.IsInfoEnabled) + m_PerfLog.Info(message); + } + } +} diff --git a/SocketBase/Logging/ConsoleLog.cs b/SocketBase/Logging/ConsoleLog.cs new file mode 100644 index 000000000..1e2119443 --- /dev/null +++ b/SocketBase/Logging/ConsoleLog.cs @@ -0,0 +1,456 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.SocketBase.Logging +{ + /// + /// Console Log + /// + public class ConsoleLog : ILog + { + private string m_Name; + + private const string m_MessageTemplate = "{0}-{1}: {2}"; + + private const string m_Debug = "DEBUG"; + + private const string m_Error = "ERROR"; + + private const string m_Fatal = "FATAL"; + + private const string m_Info = "INFO"; + + private const string m_Warn = "WARN"; + + /// + /// Initializes a new instance of the class. + /// + /// The name. + public ConsoleLog(string name) + { + m_Name = name; + } + + /// + /// Gets a value indicating whether this instance is debug enabled. + /// + /// + /// true if this instance is debug enabled; otherwise, false. + /// + public bool IsDebugEnabled + { + get { return true; } + } + + /// + /// Gets a value indicating whether this instance is error enabled. + /// + /// + /// true if this instance is error enabled; otherwise, false. + /// + public bool IsErrorEnabled + { + get { return true; } + } + + /// + /// Gets a value indicating whether this instance is fatal enabled. + /// + /// + /// true if this instance is fatal enabled; otherwise, false. + /// + public bool IsFatalEnabled + { + get { return true; } + } + + /// + /// Gets a value indicating whether this instance is info enabled. + /// + /// + /// true if this instance is info enabled; otherwise, false. + /// + public bool IsInfoEnabled + { + get { return true; } + } + + /// + /// Gets a value indicating whether this instance is warn enabled. + /// + /// + /// true if this instance is warn enabled; otherwise, false. + /// + public bool IsWarnEnabled + { + get { return true; } + } + + /// + /// Logs the debug message. + /// + /// The message. + public void Debug(object message) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Debug, message); + } + + /// + /// Logs the debug message. + /// + /// The message. + /// The exception. + public void Debug(object message, Exception exception) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Debug, message + Environment.NewLine + exception.Message + Environment.StackTrace); + } + + /// + /// Logs the debug message. + /// + /// The format. + /// The arg0. + public void DebugFormat(string format, object arg0) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Debug, string.Format(format, arg0)); + } + + /// + /// Logs the debug message. + /// + /// The format. + /// The args. + public void DebugFormat(string format, params object[] args) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Debug, string.Format(format, args)); + } + + /// + /// Logs the debug message. + /// + /// The provider. + /// The format. + /// The args. + public void DebugFormat(IFormatProvider provider, string format, params object[] args) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Debug, string.Format(provider, format, args)); + } + + /// + /// Logs the debug message. + /// + /// The format. + /// The arg0. + /// The arg1. + public void DebugFormat(string format, object arg0, object arg1) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Debug, string.Format(format, arg0, arg1)); + } + + /// + /// Logs the debug message. + /// + /// The format. + /// The arg0. + /// The arg1. + /// The arg2. + public void DebugFormat(string format, object arg0, object arg1, object arg2) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Debug, string.Format(format, arg0, arg1, arg2)); + } + + /// + /// Logs the error message. + /// + /// The message. + public void Error(object message) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Error, message); + } + + /// + /// Logs the error message. + /// + /// The message. + /// The exception. + public void Error(object message, Exception exception) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Error, message + Environment.NewLine + exception.Message + Environment.StackTrace); + } + + /// + /// Logs the error message. + /// + /// The format. + /// The arg0. + public void ErrorFormat(string format, object arg0) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Error, string.Format(format, arg0)); + } + + /// + /// Logs the error message. + /// + /// The format. + /// The args. + public void ErrorFormat(string format, params object[] args) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Error, string.Format(format, args)); + } + + /// + /// Logs the error message. + /// + /// The provider. + /// The format. + /// The args. + public void ErrorFormat(IFormatProvider provider, string format, params object[] args) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Error, string.Format(provider, format, args)); + } + + /// + /// Logs the error message. + /// + /// The format. + /// The arg0. + /// The arg1. + public void ErrorFormat(string format, object arg0, object arg1) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Error, string.Format(format, arg0, arg1)); + } + + /// + /// Logs the error message. + /// + /// The format. + /// The arg0. + /// The arg1. + /// The arg2. + public void ErrorFormat(string format, object arg0, object arg1, object arg2) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Error, string.Format(format, arg0, arg2)); + } + + /// + /// Logs the fatal error message. + /// + /// The message. + public void Fatal(object message) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Fatal, message); + } + + /// + /// Logs the fatal error message. + /// + /// The message. + /// The exception. + public void Fatal(object message, Exception exception) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Fatal, message + Environment.NewLine + exception.Message + Environment.StackTrace); + } + + /// + /// Logs the fatal error message. + /// + /// The format. + /// The arg0. + public void FatalFormat(string format, object arg0) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Fatal, string.Format(format, arg0)); + } + + /// + /// Logs the fatal error message. + /// + /// The format. + /// The args. + public void FatalFormat(string format, params object[] args) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Fatal, string.Format(format, args)); + } + + /// + /// Logs the fatal error message. + /// + /// The provider. + /// The format. + /// The args. + public void FatalFormat(IFormatProvider provider, string format, params object[] args) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Fatal, string.Format(provider, format, args)); + } + + /// + /// Logs the fatal error message. + /// + /// The format. + /// The arg0. + /// The arg1. + public void FatalFormat(string format, object arg0, object arg1) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Fatal, string.Format(format, arg0, arg1)); + } + + /// + /// Logs the fatal error message. + /// + /// The format. + /// The arg0. + /// The arg1. + /// The arg2. + public void FatalFormat(string format, object arg0, object arg1, object arg2) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Fatal, string.Format(format, arg0, arg1, arg2)); + } + + /// + /// Logs the info message. + /// + /// The message. + public void Info(object message) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Info, message); + } + + /// + /// Logs the info message. + /// + /// The message. + /// The exception. + public void Info(object message, Exception exception) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Info, message + Environment.NewLine + exception.Message + Environment.StackTrace); + } + + /// + /// Logs the info message. + /// + /// The format. + /// The arg0. + public void InfoFormat(string format, object arg0) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Info, string.Format(format, arg0)); + } + + /// + /// Logs the info message. + /// + /// The format. + /// The args. + public void InfoFormat(string format, params object[] args) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Info, string.Format(format, args)); + } + + /// + /// Logs the info message. + /// + /// The provider. + /// The format. + /// The args. + public void InfoFormat(IFormatProvider provider, string format, params object[] args) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Info, string.Format(provider, format, args)); + } + + /// + /// Logs the info message. + /// + /// The format. + /// The arg0. + /// The arg1. + public void InfoFormat(string format, object arg0, object arg1) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Info, string.Format(format, arg0, arg1)); + } + + /// + /// Logs the info message. + /// + /// The format. + /// The arg0. + /// The arg1. + /// The arg2. + public void InfoFormat(string format, object arg0, object arg1, object arg2) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Info, string.Format(format, arg0, arg1, arg2)); + } + + /// + /// Logs the warning message. + /// + /// The message. + public void Warn(object message) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Warn, message); + } + + /// + /// Logs the warning message. + /// + /// The message. + /// The exception. + public void Warn(object message, Exception exception) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Warn, message + Environment.NewLine + exception.Message + Environment.StackTrace); + } + + /// + /// Logs the warning message. + /// + /// The format. + /// The arg0. + public void WarnFormat(string format, object arg0) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Warn, string.Format(format, arg0)); + } + + /// + /// Logs the warning message. + /// + /// The format. + /// The args. + public void WarnFormat(string format, params object[] args) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Warn, string.Format(format, args)); + } + + /// + /// Logs the warning message. + /// + /// The provider. + /// The format. + /// The args. + public void WarnFormat(IFormatProvider provider, string format, params object[] args) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Warn, string.Format(provider, format, args)); + } + + /// + /// Logs the warning message. + /// + /// The format. + /// The arg0. + /// The arg1. + public void WarnFormat(string format, object arg0, object arg1) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Warn, string.Format(format, arg0, arg1)); + } + + /// + /// Logs the warning message. + /// + /// The format. + /// The arg0. + /// The arg1. + /// The arg2. + public void WarnFormat(string format, object arg0, object arg1, object arg2) + { + Console.WriteLine(m_MessageTemplate, m_Name, m_Warn, string.Format(format, arg0, arg1, arg2)); + } + } +} diff --git a/SocketBase/Logging/ConsoleLogFactory.cs b/SocketBase/Logging/ConsoleLogFactory.cs new file mode 100644 index 000000000..146538b06 --- /dev/null +++ b/SocketBase/Logging/ConsoleLogFactory.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.SocketBase.Logging +{ + /// + /// Console log factory + /// + public class ConsoleLogFactory : ILogFactory + { + /// + /// Gets the log by name. + /// + /// The name. + /// + public ILog GetLog(string name) + { + return new ConsoleLog(name); + } + } +} diff --git a/SocketBase/Logging/ILog.cs b/SocketBase/Logging/ILog.cs new file mode 100644 index 000000000..d53ade86a --- /dev/null +++ b/SocketBase/Logging/ILog.cs @@ -0,0 +1,313 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.SocketBase.Logging +{ + /// + /// Log interface + /// + public interface ILog + { + /// + /// Gets a value indicating whether this instance is debug enabled. + /// + /// + /// true if this instance is debug enabled; otherwise, false. + /// + bool IsDebugEnabled { get; } + + /// + /// Gets a value indicating whether this instance is error enabled. + /// + /// + /// true if this instance is error enabled; otherwise, false. + /// + bool IsErrorEnabled { get; } + + /// + /// Gets a value indicating whether this instance is fatal enabled. + /// + /// + /// true if this instance is fatal enabled; otherwise, false. + /// + bool IsFatalEnabled { get; } + + /// + /// Gets a value indicating whether this instance is info enabled. + /// + /// + /// true if this instance is info enabled; otherwise, false. + /// + bool IsInfoEnabled { get; } + + /// + /// Gets a value indicating whether this instance is warn enabled. + /// + /// + /// true if this instance is warn enabled; otherwise, false. + /// + bool IsWarnEnabled { get; } + + /// + /// Logs the debug message. + /// + /// The message. + void Debug(object message); + + /// + /// Logs the debug message. + /// + /// The message. + /// The exception. + void Debug(object message, Exception exception); + + /// + /// Logs the debug message. + /// + /// The format. + /// The arg0. + void DebugFormat(string format, object arg0); + + /// + /// Logs the debug message. + /// + /// The format. + /// The args. + void DebugFormat(string format, params object[] args); + + /// + /// Logs the debug message. + /// + /// The provider. + /// The format. + /// The args. + void DebugFormat(IFormatProvider provider, string format, params object[] args); + + /// + /// Logs the debug message. + /// + /// The format. + /// The arg0. + /// The arg1. + void DebugFormat(string format, object arg0, object arg1); + + /// + /// Logs the debug message. + /// + /// The format. + /// The arg0. + /// The arg1. + /// The arg2. + void DebugFormat(string format, object arg0, object arg1, object arg2); + + /// + /// Logs the error message. + /// + /// The message. + void Error(object message); + + /// + /// Logs the error message. + /// + /// The message. + /// The exception. + void Error(object message, Exception exception); + + /// + /// Logs the error message. + /// + /// The format. + /// The arg0. + void ErrorFormat(string format, object arg0); + + /// + /// Logs the error message. + /// + /// The format. + /// The args. + void ErrorFormat(string format, params object[] args); + + /// + /// Logs the error message. + /// + /// The provider. + /// The format. + /// The args. + void ErrorFormat(IFormatProvider provider, string format, params object[] args); + + /// + /// Logs the error message. + /// + /// The format. + /// The arg0. + /// The arg1. + void ErrorFormat(string format, object arg0, object arg1); + + /// + /// Logs the error message. + /// + /// The format. + /// The arg0. + /// The arg1. + /// The arg2. + void ErrorFormat(string format, object arg0, object arg1, object arg2); + + /// + /// Logs the fatal error message. + /// + /// The message. + void Fatal(object message); + + /// + /// Logs the fatal error message. + /// + /// The message. + /// The exception. + void Fatal(object message, Exception exception); + + /// + /// Logs the fatal error message. + /// + /// The format. + /// The arg0. + void FatalFormat(string format, object arg0); + + /// + /// Logs the fatal error message. + /// + /// The format. + /// The args. + void FatalFormat(string format, params object[] args); + + /// + /// Logs the fatal error message. + /// + /// The provider. + /// The format. + /// The args. + void FatalFormat(IFormatProvider provider, string format, params object[] args); + + /// + /// Logs the fatal error message. + /// + /// The format. + /// The arg0. + /// The arg1. + void FatalFormat(string format, object arg0, object arg1); + + /// + /// Logs the fatal error message. + /// + /// The format. + /// The arg0. + /// The arg1. + /// The arg2. + void FatalFormat(string format, object arg0, object arg1, object arg2); + + /// + /// Logs the info message. + /// + /// The message. + void Info(object message); + + /// + /// Logs the info message. + /// + /// The message. + /// The exception. + void Info(object message, Exception exception); + + /// + /// Logs the info message. + /// + /// The format. + /// The arg0. + void InfoFormat(string format, object arg0); + + /// + /// Logs the info message. + /// + /// The format. + /// The args. + void InfoFormat(string format, params object[] args); + + /// + /// Logs the info message. + /// + /// The provider. + /// The format. + /// The args. + void InfoFormat(IFormatProvider provider, string format, params object[] args); + + /// + /// Logs the info message. + /// + /// The format. + /// The arg0. + /// The arg1. + void InfoFormat(string format, object arg0, object arg1); + + /// + /// Logs the info message. + /// + /// The format. + /// The arg0. + /// The arg1. + /// The arg2. + void InfoFormat(string format, object arg0, object arg1, object arg2); + + /// + /// Logs the warning message. + /// + /// The message. + void Warn(object message); + + /// + /// Logs the warning message. + /// + /// The message. + /// The exception. + void Warn(object message, Exception exception); + + /// + /// Logs the warning message. + /// + /// The format. + /// The arg0. + void WarnFormat(string format, object arg0); + + /// + /// Logs the warning message. + /// + /// The format. + /// The args. + void WarnFormat(string format, params object[] args); + + /// + /// Logs the warning message. + /// + /// The provider. + /// The format. + /// The args. + void WarnFormat(IFormatProvider provider, string format, params object[] args); + + /// + /// Logs the warning message. + /// + /// The format. + /// The arg0. + /// The arg1. + void WarnFormat(string format, object arg0, object arg1); + + /// + /// Logs the warning message. + /// + /// The format. + /// The arg0. + /// The arg1. + /// The arg2. + void WarnFormat(string format, object arg0, object arg1, object arg2); + } +} diff --git a/SocketBase/Logging/ILogFactory.cs b/SocketBase/Logging/ILogFactory.cs new file mode 100644 index 000000000..3668d9c51 --- /dev/null +++ b/SocketBase/Logging/ILogFactory.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.SocketBase.Logging +{ + /// + /// LogFactory Interface + /// + public interface ILogFactory + { + /// + /// Gets the log by name. + /// + /// The name. + /// + ILog GetLog(string name); + } +} diff --git a/SocketBase/Logging/Log4NetLog.cs b/SocketBase/Logging/Log4NetLog.cs new file mode 100644 index 000000000..32fe9b77a --- /dev/null +++ b/SocketBase/Logging/Log4NetLog.cs @@ -0,0 +1,447 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.SocketBase.Logging +{ + /// + /// Log4NetLog + /// + public class Log4NetLog : ILog + { + private log4net.ILog m_Log; + + /// + /// Initializes a new instance of the class. + /// + /// The log. + public Log4NetLog(log4net.ILog log) + { + if (log == null) + throw new ArgumentNullException("log"); + + m_Log = log; + } + + /// + /// Gets a value indicating whether this instance is debug enabled. + /// + /// + /// true if this instance is debug enabled; otherwise, false. + /// + public bool IsDebugEnabled + { + get { return m_Log.IsDebugEnabled; } + } + + /// + /// Gets a value indicating whether this instance is error enabled. + /// + /// + /// true if this instance is error enabled; otherwise, false. + /// + public bool IsErrorEnabled + { + get { return m_Log.IsErrorEnabled; } + } + + /// + /// Gets a value indicating whether this instance is fatal enabled. + /// + /// + /// true if this instance is fatal enabled; otherwise, false. + /// + public bool IsFatalEnabled + { + get { return m_Log.IsFatalEnabled; } + } + + /// + /// Gets a value indicating whether this instance is info enabled. + /// + /// + /// true if this instance is info enabled; otherwise, false. + /// + public bool IsInfoEnabled + { + get { return m_Log.IsInfoEnabled; } + } + + /// + /// Gets a value indicating whether this instance is warn enabled. + /// + /// + /// true if this instance is warn enabled; otherwise, false. + /// + public bool IsWarnEnabled + { + get { return m_Log.IsWarnEnabled; } + } + + /// + /// Logs the debug message. + /// + /// The message. + public void Debug(object message) + { + m_Log.Debug(message); + } + + /// + /// Logs the debug message. + /// + /// The message. + /// The exception. + public void Debug(object message, Exception exception) + { + m_Log.Debug(message, exception); + } + + /// + /// Logs the debug message. + /// + /// The format. + /// The arg0. + public void DebugFormat(string format, object arg0) + { + m_Log.DebugFormat(format, arg0); + } + + /// + /// Logs the debug message. + /// + /// The format. + /// The args. + public void DebugFormat(string format, params object[] args) + { + m_Log.DebugFormat(format, args); + } + + /// + /// Logs the debug message. + /// + /// The provider. + /// The format. + /// The args. + public void DebugFormat(IFormatProvider provider, string format, params object[] args) + { + m_Log.DebugFormat(provider, format, args); + } + + /// + /// Logs the debug message. + /// + /// The format. + /// The arg0. + /// The arg1. + public void DebugFormat(string format, object arg0, object arg1) + { + m_Log.DebugFormat(format, arg0, arg1); + } + + /// + /// Logs the debug message. + /// + /// The format. + /// The arg0. + /// The arg1. + /// The arg2. + public void DebugFormat(string format, object arg0, object arg1, object arg2) + { + m_Log.DebugFormat(format, arg0, arg1, arg2); + } + + /// + /// Logs the error message. + /// + /// The message. + public void Error(object message) + { + m_Log.Error(message); + } + + /// + /// Logs the error message. + /// + /// The message. + /// The exception. + public void Error(object message, Exception exception) + { + m_Log.Error(message, exception); + } + + /// + /// Logs the error message. + /// + /// The format. + /// The arg0. + public void ErrorFormat(string format, object arg0) + { + m_Log.ErrorFormat(format, arg0); + } + + /// + /// Logs the error message. + /// + /// The format. + /// The args. + public void ErrorFormat(string format, params object[] args) + { + m_Log.ErrorFormat(format, args); + } + + /// + /// Logs the error message. + /// + /// The provider. + /// The format. + /// The args. + public void ErrorFormat(IFormatProvider provider, string format, params object[] args) + { + m_Log.ErrorFormat(provider, format, args); + } + + /// + /// Logs the error message. + /// + /// The format. + /// The arg0. + /// The arg1. + public void ErrorFormat(string format, object arg0, object arg1) + { + m_Log.ErrorFormat(format, arg0, arg1); + } + + /// + /// Logs the error message. + /// + /// The format. + /// The arg0. + /// The arg1. + /// The arg2. + public void ErrorFormat(string format, object arg0, object arg1, object arg2) + { + m_Log.ErrorFormat(format, arg0, arg1, arg2); + } + + /// + /// Logs the fatal error message. + /// + /// The message. + public void Fatal(object message) + { + m_Log.Fatal(message); + } + + /// + /// Logs the fatal error message. + /// + /// The message. + /// The exception. + public void Fatal(object message, Exception exception) + { + m_Log.Fatal(message, exception); + } + + /// + /// Logs the fatal error message. + /// + /// The format. + /// The arg0. + public void FatalFormat(string format, object arg0) + { + m_Log.FatalFormat(format, arg0); + } + + /// + /// Logs the fatal error message. + /// + /// The format. + /// The args. + public void FatalFormat(string format, params object[] args) + { + m_Log.FatalFormat(format, args); + } + + /// + /// Logs the fatal error message. + /// + /// The provider. + /// The format. + /// The args. + public void FatalFormat(IFormatProvider provider, string format, params object[] args) + { + m_Log.FatalFormat(provider, format, args); + } + + /// + /// Logs the fatal error message. + /// + /// The format. + /// The arg0. + /// The arg1. + public void FatalFormat(string format, object arg0, object arg1) + { + m_Log.FatalFormat(format, arg0, arg1); + } + + /// + /// Logs the fatal error message. + /// + /// The format. + /// The arg0. + /// The arg1. + /// The arg2. + public void FatalFormat(string format, object arg0, object arg1, object arg2) + { + m_Log.FatalFormat(format, arg0, arg1, arg2); + } + + /// + /// Logs the info message. + /// + /// The message. + public void Info(object message) + { + m_Log.Info(message); + } + + /// + /// Logs the info message. + /// + /// The message. + /// The exception. + public void Info(object message, Exception exception) + { + m_Log.Info(message, exception); + } + + /// + /// Logs the info message. + /// + /// The format. + /// The arg0. + public void InfoFormat(string format, object arg0) + { + m_Log.InfoFormat(format, arg0); + } + + /// + /// Logs the info message. + /// + /// The format. + /// The args. + public void InfoFormat(string format, params object[] args) + { + m_Log.InfoFormat(format, args); + } + + /// + /// Logs the info message. + /// + /// The provider. + /// The format. + /// The args. + public void InfoFormat(IFormatProvider provider, string format, params object[] args) + { + m_Log.InfoFormat(provider, format, args); + } + + /// + /// Logs the info message. + /// + /// The format. + /// The arg0. + /// The arg1. + public void InfoFormat(string format, object arg0, object arg1) + { + m_Log.InfoFormat(format, arg0, arg1); + } + + /// + /// Logs the info message. + /// + /// The format. + /// The arg0. + /// The arg1. + /// The arg2. + public void InfoFormat(string format, object arg0, object arg1, object arg2) + { + m_Log.InfoFormat(format, arg0, arg1, arg2); + } + + /// + /// Logs the warning message. + /// + /// The message. + public void Warn(object message) + { + m_Log.Warn(message); + } + + /// + /// Logs the warning message. + /// + /// The message. + /// The exception. + public void Warn(object message, Exception exception) + { + m_Log.Warn(message, exception); + } + + /// + /// Logs the warning message. + /// + /// The format. + /// The arg0. + public void WarnFormat(string format, object arg0) + { + m_Log.WarnFormat(format, arg0); + } + + /// + /// Logs the warning message. + /// + /// The format. + /// The args. + public void WarnFormat(string format, params object[] args) + { + m_Log.WarnFormat(format, args); + } + + /// + /// Logs the warning message. + /// + /// The provider. + /// The format. + /// The args. + public void WarnFormat(IFormatProvider provider, string format, params object[] args) + { + m_Log.WarnFormat(provider, format, args); + } + + /// + /// Logs the warning message. + /// + /// The format. + /// The arg0. + /// The arg1. + public void WarnFormat(string format, object arg0, object arg1) + { + m_Log.WarnFormat(format, arg0, arg1); + } + + /// + /// Logs the warning message. + /// + /// The format. + /// The arg0. + /// The arg1. + /// The arg2. + public void WarnFormat(string format, object arg0, object arg1, object arg2) + { + m_Log.WarnFormat(format, arg0, arg1, arg2); + } + } +} diff --git a/SocketBase/Logging/Log4NetLogFactory.cs b/SocketBase/Logging/Log4NetLogFactory.cs new file mode 100644 index 000000000..c13a2deca --- /dev/null +++ b/SocketBase/Logging/Log4NetLogFactory.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using log4net; +using log4net.Config; + +namespace SuperSocket.SocketBase.Logging +{ + /// + /// Log4NetLogFactory + /// + public class Log4NetLogFactory : LogFactoryBase + { + /// + /// Initializes a new instance of the class. + /// + public Log4NetLogFactory() + : this("log4net.config") + { + + } + + /// + /// Initializes a new instance of the class. + /// + /// The log4net config. + public Log4NetLogFactory(string log4netConfig) + : base(log4netConfig) + { + log4net.Config.XmlConfigurator.Configure(new FileInfo(ConfigFile)); + } + + /// + /// Gets the log by name. + /// + /// The name. + /// + public override ILog GetLog(string name) + { + return new Log4NetLog(LogManager.GetLogger(name)); + } + } +} diff --git a/SocketBase/Logging/LogFactoryBase.cs b/SocketBase/Logging/LogFactoryBase.cs new file mode 100644 index 000000000..73b3d03b7 --- /dev/null +++ b/SocketBase/Logging/LogFactoryBase.cs @@ -0,0 +1,123 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.IO; +using System.Diagnostics; + +namespace SuperSocket.SocketBase.Logging +{ + /// + /// LogFactory Base class + /// + public abstract class LogFactoryBase : ILogFactory + { + /// + /// Gets the config file file path. + /// + protected string ConfigFile { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// The config file. + protected LogFactoryBase(string configFile) + { + if (Path.IsPathRooted(configFile)) + { + ConfigFile = configFile; + return; + } + + if (Path.DirectorySeparatorChar != '\\') + { + configFile = Path.GetFileNameWithoutExtension(configFile) + ".unix" + Path.GetExtension(configFile); + } + + if (AppDomain.CurrentDomain.IsDefaultAppDomain()) + { + var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, configFile); + + if (File.Exists(filePath)) + { + ConfigFile = filePath; + return; + } + + filePath = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config"), configFile); + + if (File.Exists(filePath)) + { + ConfigFile = filePath; + return; + } + + ConfigFile = configFile; + return; + } + else //The running AppServer is in isolated appdomain + { + //1. search the appDomain's base directory + var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, configFile); + + if (File.Exists(filePath)) + { + ConfigFile = filePath; + return; + } + + //go to the application's root + //the appdomain's root is /WorkingDir/DomainName, so get parent path twice to reach the application root + var rootDir = Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory).Parent.FullName; + + //2. search the file with appdomain's name as prefix in the application's root + //the config file whose name have appDomain's name has higher priority + filePath = Path.Combine(rootDir, AppDomain.CurrentDomain.FriendlyName + "." + configFile); + + if (File.Exists(filePath)) + { + ConfigFile = filePath; + return; + } + + //3. search in the application's root without appdomain's name as prefix + filePath = Path.Combine(rootDir, configFile); + + if (File.Exists(filePath)) + { + ConfigFile = filePath; + return; + } + + + rootDir = Path.Combine(rootDir, "Config"); + //Search the config file with appdomain's name as prefix in the Config dir + filePath = Path.Combine(rootDir, AppDomain.CurrentDomain.FriendlyName + "." + configFile); + + if (File.Exists(filePath)) + { + ConfigFile = filePath; + return; + } + + filePath = Path.Combine(rootDir, configFile); + + if (File.Exists(filePath)) + { + ConfigFile = filePath; + return; + } + + ConfigFile = configFile; + return; + } + } + + /// + /// Gets the log by name. + /// + /// The name. + /// + public abstract ILog GetLog(string name); + } +} diff --git a/SocketBase/PerformanceData.cs b/SocketBase/PerformanceData.cs new file mode 100644 index 000000000..4485fd066 --- /dev/null +++ b/SocketBase/PerformanceData.cs @@ -0,0 +1,155 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.SocketBase +{ + /// + /// PerformanceData class + /// + public class PerformanceData + { + /// + /// Gets or sets the current record sample. + /// + /// + /// The current record. + /// + public PerformanceRecord CurrentRecord { get; set; } + + /// + /// Gets or sets the previous record sample. + /// + /// + /// The previous record. + /// + public PerformanceRecord PreviousRecord { get; set; } + + /// + /// Initializes a new instance of the class. + /// + public PerformanceData() + { + CurrentRecord = new PerformanceRecord(); + } + + /// + /// Pushes the latest record sample. + /// + /// The record. + /// + public PerformanceData PushRecord(PerformanceRecord record) + { + PreviousRecord = CurrentRecord; + CurrentRecord = record; + CurrentRecord.RecordSpan = CurrentRecord.RecordTime.Subtract(PreviousRecord.RecordTime).TotalSeconds; + return this; + } + } + + /// + /// Performance record sample + /// + public class PerformanceRecord + { + /// + /// Initializes a new instance of the class. + /// + public PerformanceRecord() + { + RecordTime = DateTime.Now; + } + + /// + /// Gets or sets the total connections. + /// + /// + /// The total connections. + /// + public int TotalConnections { get; set; } + + /// + /// Gets or sets the total handled requests. + /// + /// + /// The total handled requests. + /// + public long TotalHandledRequests { get; set; } + + /// + /// Gets the record time. + /// + public DateTime RecordTime { get; private set; } + + /// + /// Gets or sets the record span. + /// + /// + /// The record span. + /// + public double RecordSpan { get; set; } + } + + /// + /// GlobalPerformanceData class + /// + public class GlobalPerformanceData + { + /// + /// Gets or sets the available working threads. + /// + /// + /// The available working threads. + /// + public int AvailableWorkingThreads { get; set; } + + /// + /// Gets or sets the available completion port threads. + /// + /// + /// The available completion port threads. + /// + public int AvailableCompletionPortThreads { get; set; } + + /// + /// Gets or sets the max working threads. + /// + /// + /// The max working threads. + /// + public int MaxWorkingThreads { get; set; } + + /// + /// Gets or sets the max completion port threads. + /// + /// + /// The max completion port threads. + /// + public int MaxCompletionPortThreads { get; set; } + + /// + /// Gets or sets the total thread count. + /// + /// + /// The total thread count. + /// + public int TotalThreadCount { get; set; } + + /// + /// Gets or sets the cpu usage. + /// + /// + /// The cpu usage. + /// + public double CpuUsage { get; set; } + + /// + /// Gets or sets the working set. + /// + /// + /// The working set. + /// + public long WorkingSet { get; set; } + } +} diff --git a/SocketBase/PerformanceDataInfo.cs b/SocketBase/PerformanceDataInfo.cs new file mode 100644 index 000000000..d23584990 --- /dev/null +++ b/SocketBase/PerformanceDataInfo.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.SocketBase +{ + /// + /// PerformanceDataInfo class, which assosiates server with performance data + /// + public class PerformanceDataInfo + { + /// + /// Gets or sets the name of the server instance. + /// + /// + /// The name of the server. + /// + public string ServerName { get; set; } + + /// + /// Gets or sets the performance data. + /// + /// + /// The data. + /// + public PerformanceData Data { get; set; } + } +} diff --git a/SocketBase/PermformanceDataEventArgs.cs b/SocketBase/PermformanceDataEventArgs.cs new file mode 100644 index 000000000..5fafb86fc --- /dev/null +++ b/SocketBase/PermformanceDataEventArgs.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.SocketBase +{ + /// + /// PermformanceData event argument + /// + public class PermformanceDataEventArgs : EventArgs + { + /// + /// Gets the global data. + /// + public GlobalPerformanceData GlobalData { get; private set; } + + /// + /// Gets all the instances performance data. + /// + public PerformanceDataInfo[] InstancesData { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + /// The global data. + /// The instances data. + public PermformanceDataEventArgs(GlobalPerformanceData globalData, PerformanceDataInfo[] instancesData) + { + GlobalData = globalData; + InstancesData = instancesData; + } + } +} diff --git a/SocketBase/Properties/AssemblyInfo.cs b/SocketBase/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..26c076962 --- /dev/null +++ b/SocketBase/Properties/AssemblyInfo.cs @@ -0,0 +1,18 @@ +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("SuperSocket.SocketBase")] +[assembly: AssemblyDescription("SuperSocket.SocketBase")] +[assembly: AssemblyConfiguration("")] + +// 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)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("427204a0-fa48-4c22-97d6-4daf08ee4354")] diff --git a/SocketBase/Protocol/BasicRequestInfoParser.cs b/SocketBase/Protocol/BasicRequestInfoParser.cs new file mode 100644 index 000000000..3b2503f58 --- /dev/null +++ b/SocketBase/Protocol/BasicRequestInfoParser.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.SocketBase.Protocol +{ + /// + /// Basic request info parser, which parse request info by separating + /// + public class BasicRequestInfoParser : IRequestInfoParser + { + private string m_Spliter; + private string[] m_ParameterSpliters; + + private const string m_OneSpace = " "; + + /// + /// Initializes a new instance of the class. + /// + public BasicRequestInfoParser() + : this(m_OneSpace, m_OneSpace) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The spliter between command name and command parameters. + /// The parameter spliter. + public BasicRequestInfoParser(string spliter, string parameterSpliter) + { + m_Spliter = spliter; + m_ParameterSpliters = new string[] { parameterSpliter }; + } + + #region IRequestInfoParser Members + + /// + /// Parses the request info. + /// + /// The source. + /// + public StringRequestInfo ParseRequestInfo(string source) + { + int pos = source.IndexOf(m_Spliter); + + string name = string.Empty; + string param = string.Empty; + + if (pos > 0) + { + name = source.Substring(0, pos); + param = source.Substring(pos + 1); + } + else + { + name = source; + } + + return new StringRequestInfo(name, param, + param.Split(m_ParameterSpliters, StringSplitOptions.RemoveEmptyEntries)); + } + + #endregion + } +} diff --git a/SocketBase/Protocol/BinaryRequestInfo.cs b/SocketBase/Protocol/BinaryRequestInfo.cs new file mode 100644 index 000000000..060b246d5 --- /dev/null +++ b/SocketBase/Protocol/BinaryRequestInfo.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.SocketBase.Protocol +{ + /// + /// Binary type request information + /// + public class BinaryRequestInfo : RequestInfo + { + /// + /// Initializes a new instance of the class. + /// + /// The key. + /// The data. + public BinaryRequestInfo(string key, byte[] data) + : base(key, data) + { + + } + } +} diff --git a/SocketBase/Protocol/CommandLineRequestFilterFactory.cs b/SocketBase/Protocol/CommandLineRequestFilterFactory.cs new file mode 100644 index 000000000..8462b9559 --- /dev/null +++ b/SocketBase/Protocol/CommandLineRequestFilterFactory.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.SocketBase.Protocol +{ + /// + /// CommandLineRequestFilterFactory + /// + public class CommandLineRequestFilterFactory : IRequestFilterFactory + { + private Encoding m_Encoding; + private byte[] m_LineTerminator; + private IRequestInfoParser m_LineParser; + + /// + /// Initializes a new instance of the class. + /// + public CommandLineRequestFilterFactory() + : this(Encoding.ASCII, new BasicRequestInfoParser()) + { + + } + + /// + /// Initializes a new instance of the class. + /// + /// The encoding. + /// The line parser. + public CommandLineRequestFilterFactory(Encoding encoding, IRequestInfoParser lineParser) + { + m_Encoding = encoding; + m_LineTerminator = encoding.GetBytes(Environment.NewLine); + m_LineParser = lineParser; + } + + /// + /// Creates the request filter. + /// + /// The app server. + /// The socket session. + /// the new created request filer assosiated with this socketSession + public virtual IRequestFilter CreateFilter(IAppServer appServer, ISocketSession socketSession) + { + return new TerminatorRequestFilter(m_LineTerminator, m_Encoding, m_LineParser); + } + } +} diff --git a/SocketBase/Protocol/DefaultRequestFilterFactory.cs b/SocketBase/Protocol/DefaultRequestFilterFactory.cs new file mode 100644 index 000000000..5b81672e3 --- /dev/null +++ b/SocketBase/Protocol/DefaultRequestFilterFactory.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.SocketBase.Protocol +{ + /// + /// DefaultRequestFilterFactory + /// + /// The type of the request filter. + /// The type of the request info. + public class DefaultRequestFilterFactory : IRequestFilterFactory + where TRequestInfo : IRequestInfo + where TRequestFilter : IRequestFilter, new() + { + /// + /// Creates the request filter. + /// + /// The app server. + /// The socket session. + /// the new created request filer assosiated with this socketSession + public IRequestFilter CreateFilter(IAppServer appServer, ISocketSession socketSession) + { + return new TRequestFilter(); + } + } +} diff --git a/SocketBase/Protocol/FixHeaderRequestFilter.cs b/SocketBase/Protocol/FixHeaderRequestFilter.cs new file mode 100644 index 000000000..22fe25c89 --- /dev/null +++ b/SocketBase/Protocol/FixHeaderRequestFilter.cs @@ -0,0 +1,158 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.Common; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.SocketBase.Protocol +{ + /// + /// FixHeaderRequestFilter, + /// it is the request filter base for the protocol which define fixed length header and the header contains the request body length, + /// you can implement your own request filter for this kind protocol easily by inheriting this class + /// + /// The type of the request info. + public abstract class FixHeaderRequestFilter : FixedSizeRequestFilter + where TRequestInfo : IRequestInfo + { + private bool m_FoundHeader = false; + + private ArraySegment m_Header; + + private int m_BodyLength; + + private ArraySegmentList m_BodyBuffer; + + /// + /// Initializes a new instance of the class. + /// + /// Size of the header. + public FixHeaderRequestFilter(int headerSize) + : base(headerSize) + { + + } + + /// + /// Filters the specified session. + /// + /// The session. + /// The read buffer. + /// The offset. + /// The length. + /// if set to true [to be copied]. + /// The left. + /// + public override TRequestInfo Filter(IAppSession session, byte[] readBuffer, int offset, int length, bool toBeCopied, out int left) + { + if (!m_FoundHeader) + return base.Filter(session, readBuffer, offset, length, toBeCopied, out left); + + if (m_BodyBuffer == null || m_BodyBuffer.Count == 0) + { + if (length < m_BodyLength) + { + if (m_BodyBuffer == null) + m_BodyBuffer = new ArraySegmentList(); + + m_BodyBuffer.AddSegment(readBuffer, offset, length, toBeCopied); + left = 0; + return default(TRequestInfo); + } + else if (length == m_BodyLength) + { + left = 0; + m_FoundHeader = false; + return ResolveRequestData(m_Header, readBuffer, offset, length); + } + else + { + left = length - m_BodyLength; + m_FoundHeader = false; + return ResolveRequestData(m_Header, readBuffer, offset, m_BodyLength); + } + } + else + { + int required = m_BodyLength - m_BodyBuffer.Count; + + if (length < required) + { + m_BodyBuffer.AddSegment(readBuffer, offset, length, toBeCopied); + left = 0; + return default(TRequestInfo); + } + else if (length == required) + { + m_BodyBuffer.AddSegment(readBuffer, offset, length, toBeCopied); + left = 0; + m_FoundHeader = false; + var requestInfo = ResolveRequestData(m_Header, m_BodyBuffer.ToArrayData()); + m_BodyBuffer.ClearSegements(); + return requestInfo; + } + else + { + m_BodyBuffer.AddSegment(readBuffer, offset, required, toBeCopied); + left = length - required; + m_FoundHeader = false; + var requestInfo = ResolveRequestData(m_Header, m_BodyBuffer.ToArrayData(0, m_BodyLength)); + m_BodyBuffer.ClearSegements(); + return requestInfo; + } + } + } + + /// + /// Processes the fix size request. + /// + /// The session. + /// The buffer. + /// The offset. + /// The length. + /// if set to true [to be copied]. + /// The left. + /// + protected override TRequestInfo ProcessFixSizeRequest(IAppSession session, byte[] buffer, int offset, int length, bool toBeCopied, out int left) + { + m_FoundHeader = true; + + left = length - this.Size; + + m_BodyLength = GetBodyLengthFromHeader(buffer, offset, Size); + + if (toBeCopied) + m_Header = new ArraySegment(buffer.CloneRange(offset, Size)); + else + m_Header = new ArraySegment(buffer, offset, Size); + + return default(TRequestInfo); + } + + private TRequestInfo ResolveRequestData(ArraySegment header, byte[] bodyBuffer) + { + return ResolveRequestData(header, bodyBuffer, 0, bodyBuffer.Length); + } + + /// + /// Gets the body length from header. + /// + /// The header. + /// The offset. + /// The length. + /// + protected abstract int GetBodyLengthFromHeader(byte[] header, int offset, int length); + + /// + /// Resolves the request data. + /// + /// The header. + /// The body buffer. + /// The offset. + /// The length. + /// + protected abstract TRequestInfo ResolveRequestData(ArraySegment header, byte[] bodyBuffer, int offset, int length); + } +} diff --git a/SocketBase/Protocol/FixedSizeRequestFilter.cs b/SocketBase/Protocol/FixedSizeRequestFilter.cs new file mode 100644 index 000000000..dbb5bd0ba --- /dev/null +++ b/SocketBase/Protocol/FixedSizeRequestFilter.cs @@ -0,0 +1,106 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.SocketBase.Protocol +{ + /// + /// FixedSizeRequestFilter + /// + /// The type of the request info. + public abstract class FixedSizeRequestFilter : IRequestFilter, IOffsetAdapter + where TRequestInfo : IRequestInfo + { + private int m_ParsedLength; + + private int m_Size; + + /// + /// Gets the size of the fixed size request filter. + /// + public int Size + { + get { return m_Size; } + } + + private static TRequestInfo m_NullRequestInfo = default(TRequestInfo); + + /// + /// Initializes a new instance of the class. + /// + /// The size. + public FixedSizeRequestFilter(int size) + { + m_Size = size; + } + + /// + /// Filters the specified session. + /// + /// The session. + /// The read buffer. + /// The offset. + /// The length. + /// if set to true [to be copied]. + /// The left. + /// + public virtual TRequestInfo Filter(IAppSession session, byte[] readBuffer, int offset, int length, bool toBeCopied, out int left) + { + if (m_ParsedLength + length >= m_Size) + { + m_OffsetDelta = 0 - m_ParsedLength; + return ProcessFixSizeRequest(session, readBuffer, offset - m_ParsedLength, m_ParsedLength + length, toBeCopied, out left); + } + else + { + m_ParsedLength += length; + m_OffsetDelta = length; + left = 0; + return m_NullRequestInfo; + } + } + + /// + /// Filters the buffer after the server receive the enough size of data. + /// + /// The session. + /// The buffer. + /// The offset. + /// The length. + /// if set to true [to be copied]. + /// The left. + /// + protected abstract TRequestInfo ProcessFixSizeRequest(IAppSession session, byte[] buffer, int offset, int length, bool toBeCopied, out int left); + + /// + /// Gets the size of the left buffer. + /// + /// + /// The size of the left buffer. + /// + public int LeftBufferSize { get; private set; } + + /// + /// Gets the next request filter. + /// + public virtual IRequestFilter NextRequestFilter + { + get { return null; } + } + + + private int m_OffsetDelta; + + /// + /// Gets the offset delta. + /// + int IOffsetAdapter.OffsetDelta + { + get + { + return m_OffsetDelta; + } + } + } +} diff --git a/SocketBase/Protocol/IOffsetAdapter.cs b/SocketBase/Protocol/IOffsetAdapter.cs new file mode 100644 index 000000000..86dd59dcc --- /dev/null +++ b/SocketBase/Protocol/IOffsetAdapter.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.SocketBase.Protocol +{ + /// + /// The interface for a request filter to adapt receiving buffer offset + /// + public interface IOffsetAdapter + { + /// + /// Gets the offset delta. + /// + int OffsetDelta { get; } + } +} diff --git a/SocketBase/Protocol/IRequestFilter.cs b/SocketBase/Protocol/IRequestFilter.cs new file mode 100644 index 000000000..dd96f847e --- /dev/null +++ b/SocketBase/Protocol/IRequestFilter.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Command; + +namespace SuperSocket.SocketBase.Protocol +{ + /// + /// Request filter interface + /// + /// The type of the request info. + public interface IRequestFilter + where TRequestInfo : IRequestInfo + { + /// + /// Filters received data of the specific session into request info. + /// + /// The session. + /// The read buffer. + /// The offset of the current received data in this read buffer. + /// The length of the current received data. + /// if set to true [to be copied]. + /// The left, the length of the data which hasn't been parsed. + /// + TRequestInfo Filter(IAppSession session, byte[] readBuffer, int offset, int length, bool toBeCopied, out int left); + + /// + /// Gets the size of the left buffer. + /// + /// + /// The size of the left buffer. + /// + int LeftBufferSize { get; } + + /// + /// Gets the next request filter. + /// + IRequestFilter NextRequestFilter { get; } + } +} diff --git a/SocketBase/Protocol/IRequestFilterFactory.cs b/SocketBase/Protocol/IRequestFilterFactory.cs new file mode 100644 index 000000000..24388f435 --- /dev/null +++ b/SocketBase/Protocol/IRequestFilterFactory.cs @@ -0,0 +1,27 @@ +using System; + +namespace SuperSocket.SocketBase.Protocol +{ + /// + /// Request filter factory interface + /// + public interface IRequestFilterFactory + { + + } + /// + /// Request filter factory interface + /// + /// The type of the request info. + public interface IRequestFilterFactory : IRequestFilterFactory + where TRequestInfo : IRequestInfo + { + /// + /// Creates the request filter. + /// + /// The app server. + /// The socket session. + /// the new created request filer assosiated with this socketSession + IRequestFilter CreateFilter(IAppServer appServer, ISocketSession socketSession); + } +} diff --git a/SocketBase/Protocol/IRequestInfo.cs b/SocketBase/Protocol/IRequestInfo.cs new file mode 100644 index 000000000..13b18e7a4 --- /dev/null +++ b/SocketBase/Protocol/IRequestInfo.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.SocketBase.Protocol +{ + /// + /// Request information interface + /// + public interface IRequestInfo + { + /// + /// Gets the key of this request. + /// + string Key { get; } + } + + /// + /// Request information interface + /// + /// The type of the request data. + public interface IRequestInfo : IRequestInfo + { + /// + /// Gets the data of this request. + /// + TRequestData Data { get; } + } +} diff --git a/SocketBase/Protocol/IRequestInfoParser.cs b/SocketBase/Protocol/IRequestInfoParser.cs new file mode 100644 index 000000000..2d1fec375 --- /dev/null +++ b/SocketBase/Protocol/IRequestInfoParser.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.SocketBase.Protocol +{ + /// + /// The interface for request info parser + /// + public interface IRequestInfoParser + where TRequestInfo : IRequestInfo + { + /// + /// Parses the request info from the source string. + /// + /// The source. + /// + TRequestInfo ParseRequestInfo(string source); + } +} diff --git a/SocketBase/Protocol/RequestFilterBase.cs b/SocketBase/Protocol/RequestFilterBase.cs new file mode 100644 index 000000000..cc8a7f6d4 --- /dev/null +++ b/SocketBase/Protocol/RequestFilterBase.cs @@ -0,0 +1,119 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.Common; + +namespace SuperSocket.SocketBase.Protocol +{ + /// + /// Request filter base class + /// + /// The type of the request info. + public abstract class RequestFilterBase : IRequestFilter + where TRequestInfo : IRequestInfo + { + private ArraySegmentList m_BufferSegments; + + /// + /// Gets the buffer segments which can help you parse your request info conviniently. + /// + protected ArraySegmentList BufferSegments + { + get { return m_BufferSegments; } + } + + /// + /// Initializes a new instance of the class. + /// + protected RequestFilterBase() + { + m_BufferSegments = new ArraySegmentList(); + } + + /// + /// Initializes a new instance of the class. + /// + /// The previous request filter. + protected RequestFilterBase(RequestFilterBase previousRequestFilter) + { + Initialize(previousRequestFilter); + } + + /// + /// Initializes the specified previous request filter. + /// + /// The previous request filter. + public void Initialize(RequestFilterBase previousRequestFilter) + { + m_BufferSegments = previousRequestFilter.BufferSegments; + } + + #region IRequestFilter Members + + + /// + /// Filters received data of the specific session into request info. + /// + /// The session. + /// The read buffer. + /// The offset of the current received data in this read buffer. + /// The length of the current received data. + /// if set to true [to be copied]. + /// The left, the length of the data which hasn't been parsed. + /// + public abstract TRequestInfo Filter(IAppSession session, byte[] readBuffer, int offset, int length, bool toBeCopied, out int left); + + + /// + /// Gets the left buffer. + /// + /// + [Obsolete] + protected byte[] GetLeftBuffer() + { + return m_BufferSegments.ToArrayData(); + } + + /// + /// Gets the size of the left buffer. + /// + /// + /// The size of the left buffer. + /// + public int LeftBufferSize + { + get { return m_BufferSegments.Count; } + } + + /// + /// Gets or sets the next request filter. + /// + /// + /// The next request filter. + /// + public IRequestFilter NextRequestFilter { get; protected set; } + + #endregion + + /// + /// Adds the array segment. + /// + /// The buffer. + /// The offset. + /// The length. + /// if set to true [to be copied]. + protected void AddArraySegment(byte[] buffer, int offset, int length, bool toBeCopied) + { + m_BufferSegments.AddSegment(buffer, offset, length, toBeCopied); + } + + /// + /// Clears the buffer segments. + /// + protected void ClearBufferSegments() + { + m_BufferSegments.ClearSegements(); + } + } +} diff --git a/SocketBase/Protocol/RequestInfo.cs b/SocketBase/Protocol/RequestInfo.cs new file mode 100644 index 000000000..c49612ed6 --- /dev/null +++ b/SocketBase/Protocol/RequestInfo.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.SocketBase.Protocol +{ + /// + /// RequestInfo basic class + /// + /// The type of the request data. + public class RequestInfo : IRequestInfo + { + /// + /// Initializes a new instance of the class. + /// + /// The key. + /// The data. + protected RequestInfo(string key, TRequestData data) + { + Key = key; + Data = data; + } + + /// + /// Gets the key of this request. + /// + public string Key { get; private set; } + + /// + /// Gets the data. + /// + public TRequestData Data { get; private set; } + } +} diff --git a/SocketBase/Protocol/StringRequestInfo.cs b/SocketBase/Protocol/StringRequestInfo.cs new file mode 100644 index 000000000..317efb474 --- /dev/null +++ b/SocketBase/Protocol/StringRequestInfo.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.SocketBase.Protocol +{ + /// + /// String type request information + /// + public class StringRequestInfo : RequestInfo + { + /// + /// Initializes a new instance of the class. + /// + /// The key. + /// The data. + /// The parameters. + public StringRequestInfo(string key, string data, string[] parameters) + : base(key, data) + { + Parameters = parameters; + } + + /// + /// Gets the parameters. + /// + public string[] Parameters { get; private set; } + + /// + /// Gets the first param. + /// + /// + public string GetFirstParam() + { + if(Parameters.Length > 0) + return Parameters[0]; + + return string.Empty; + } + + /// + /// Gets the at the specified index. + /// + public string this[int index] + { + get { return Parameters[index]; } + } + } +} diff --git a/SocketBase/Protocol/TerminatorRequestFilter.cs b/SocketBase/Protocol/TerminatorRequestFilter.cs new file mode 100644 index 000000000..a1990bd1d --- /dev/null +++ b/SocketBase/Protocol/TerminatorRequestFilter.cs @@ -0,0 +1,111 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.Common; + +namespace SuperSocket.SocketBase.Protocol +{ + /// + /// Terminator Request Filter + /// + /// The type of the request info. + public abstract class TerminatorRequestFilter : RequestFilterBase + where TRequestInfo : IRequestInfo + { + private SearchMarkState m_SearchState; + private static readonly TRequestInfo m_NullRequestInfo = default(TRequestInfo); + + /// + /// Initializes a new instance of the class. + /// + /// The terminator. + public TerminatorRequestFilter(byte[] terminator) + { + m_SearchState = new SearchMarkState(terminator); + } + + /// + /// Filters received data of the specific session into request info. + /// + /// The session. + /// The read buffer. + /// The offset of the current received data in this read buffer. + /// The length of the current received data. + /// if set to true [to be copied]. + /// The left, the length of the data which hasn't been parsed. + /// return the parsed TRequestInfo + public override TRequestInfo Filter(IAppSession session, byte[] readBuffer, int offset, int length, bool toBeCopied, out int left) + { + left = 0; + + int prevMatched = m_SearchState.Matched; + + int result = readBuffer.SearchMark(offset, length, m_SearchState); + + if (result < 0) + { + this.AddArraySegment(readBuffer, offset, length, toBeCopied); + return m_NullRequestInfo; + } + + int findLen = result - offset; + + if (findLen > 0) + { + this.AddArraySegment(readBuffer, offset, findLen, false); + } + else if (prevMatched > 0) + { + BufferSegments.TrimEnd(prevMatched); + } + + var requestInfo = Resolve(BufferSegments); + + ClearBufferSegments(); + + left = length - findLen - (m_SearchState.Mark.Length - prevMatched); + + return requestInfo; + } + + /// + /// Resolves the specified data to TRequestInfo. + /// + /// The data. + /// + protected abstract TRequestInfo Resolve(ArraySegmentList data); + } + + /// + /// TerminatorRequestFilter + /// + public class TerminatorRequestFilter : TerminatorRequestFilter + { + private Encoding m_Encoding; + private IRequestInfoParser m_RequestParser; + + /// + /// Initializes a new instance of the class. + /// + /// The terminator. + /// The encoding. + /// The request parser. + public TerminatorRequestFilter(byte[] terminator, Encoding encoding, IRequestInfoParser requestParser) + : base(terminator) + { + m_Encoding = encoding; + m_RequestParser = requestParser; + } + + /// + /// Resolves the specified data to StringRequestInfo. + /// + /// The data. + /// + protected override StringRequestInfo Resolve(ArraySegmentList data) + { + return m_RequestParser.ParseRequestInfo(data.Decode(m_Encoding)); + } + } +} diff --git a/SocketBase/Protocol/UdpRequestInfo.cs b/SocketBase/Protocol/UdpRequestInfo.cs new file mode 100644 index 000000000..aaa74ad16 --- /dev/null +++ b/SocketBase/Protocol/UdpRequestInfo.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.SocketBase.Protocol +{ + /// + /// UdpRequestInfo, it is designed for passing in business session ID to udp request info + /// + public class UdpRequestInfo : IRequestInfo + { + /// + /// Initializes a new instance of the class. + /// + /// The key. + /// The session ID. + public UdpRequestInfo(string key, string sessionID) + { + Key = key; + SessionID = sessionID; + } + + /// + /// Gets the key of this request. + /// + public string Key { get; private set; } + + /// + /// Gets the session ID. + /// + public string SessionID { get; private set; } + } +} diff --git a/SocketBase/Provider/ExportFactory.cs b/SocketBase/Provider/ExportFactory.cs new file mode 100644 index 000000000..0c62116fe --- /dev/null +++ b/SocketBase/Provider/ExportFactory.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.SocketBase.Provider +{ + /// + /// Export Factory + /// + [Serializable] + public class ExportFactory + { + /// + /// Gets or sets the type. + /// + /// + /// The type. + /// + public string TypeName { get; set; } + + private Type m_LoadedType; + + [NonSerialized] + private object m_Instance; + + /// + /// Initializes a new instance of the class. + /// + public ExportFactory() + { + + } + + /// + /// Initializes a new instance of the class. + /// + /// The instance. + public ExportFactory(object instance) + { + m_Instance = instance; + } + + /// + /// Initializes a new instance of the class. + /// + /// Name of the type. + public ExportFactory(string typeName) + { + TypeName = typeName; + } + + /// + /// Ensures the instance's existance. + /// + public void EnsureInstance() + { + if (m_Instance != null) + return; + + m_Instance = CreateInstance(); + } + + private object CreateInstance() + { + if (m_LoadedType == null) + { + m_LoadedType = System.Type.GetType(TypeName, true); + } + + return Activator.CreateInstance(m_LoadedType); + } + + /// + /// Creates the export type instance. + /// + /// + /// + public T CreateExport() + { + if (m_Instance != null) + return (T)m_Instance; + + return (T)CreateInstance(); + } + } +} diff --git a/SocketBase/Provider/ProviderFactoryInfo.cs b/SocketBase/Provider/ProviderFactoryInfo.cs new file mode 100644 index 000000000..786705b79 --- /dev/null +++ b/SocketBase/Provider/ProviderFactoryInfo.cs @@ -0,0 +1,82 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.SocketBase.Provider +{ + /// + /// Provider factory infomation + /// + [Serializable] + public class ProviderFactoryInfo + { + /// + /// Gets the key. + /// + public ProviderKey Key { get; set; } + + /// + /// Gets or sets the name. + /// + /// + /// The name. + /// + public string Name { get; set; } + + + /// + /// Gets or sets the export factory. + /// + /// + /// The export factory. + /// + public ExportFactory ExportFactory { get; set; } + + /// + /// Initializes a new instance of the class. + /// + public ProviderFactoryInfo() + { + + } + + /// + /// Initializes a new instance of the class. + /// + /// The key. + /// The name. + /// The instance. + public ProviderFactoryInfo(ProviderKey key, string name, object instance) + { + Key = key; + Name = name; + ExportFactory = new ExportFactory(instance); + } + + /// + /// Initializes a new instance of the class. + /// + /// The key. + /// The name. + /// Name of the type. + public ProviderFactoryInfo(ProviderKey key, string name, string typeName) + { + Key = key; + Name = name; + ExportFactory = new ExportFactory(typeName); + } + + /// + /// Initializes a new instance of the class. + /// + /// The key. + /// The name. + /// The type. + public ProviderFactoryInfo(ProviderKey key, string name, Type type) + : this(key, name, type.AssemblyQualifiedName) + { + + } + } +} diff --git a/SocketBase/Provider/ProviderKey.cs b/SocketBase/Provider/ProviderKey.cs new file mode 100644 index 000000000..11c780a83 --- /dev/null +++ b/SocketBase/Provider/ProviderKey.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Logging; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.SocketBase.Provider +{ + /// + /// ProviderKey + /// + [Serializable] + public class ProviderKey + { + /// + /// Gets or sets the name. + /// + /// + /// The name. + /// + public string Name { get; private set; } + + /// + /// Gets or sets the type. + /// + /// + /// The type. + /// + public Type Type { get; private set; } + + private ProviderKey() + { + + } + + static ProviderKey() + { + ServerType = new ProviderKey { Name = "ServerType", Type = typeof(IAppServer) }; + SocketServerFactory = new ProviderKey { Name = "SocketServerFactory", Type = typeof(ISocketServerFactory) }; + ConnectionFilter = new ProviderKey { Name = "ConnectionFilter", Type = typeof(IConnectionFilter) }; + LogFactory = new ProviderKey { Name = "LogFactory", Type = typeof(ILogFactory) }; + RequestFilterFactory = new ProviderKey { Name = "RequestFilterFactory", Type = typeof(IRequestFilterFactory) }; + CommandLoader = new ProviderKey { Name = "CommandLoader", Type = typeof(ICommandLoader) }; + } + + /// + /// Gets the service. + /// + public static ProviderKey ServerType { get; private set; } + + /// + /// Gets the socket server factory. + /// + public static ProviderKey SocketServerFactory { get; private set; } + + /// + /// Gets the connection filter. + /// + public static ProviderKey ConnectionFilter { get; private set; } + + /// + /// Gets the log factory. + /// + public static ProviderKey LogFactory { get; private set; } + + /// + /// Gets the request filter factory. + /// + public static ProviderKey RequestFilterFactory { get; private set; } + + /// + /// Gets the command loader. + /// + public static ProviderKey CommandLoader { get; private set; } + } +} diff --git a/SocketBase/RequestHandler.cs b/SocketBase/RequestHandler.cs new file mode 100644 index 000000000..85ed9f5c8 --- /dev/null +++ b/SocketBase/RequestHandler.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.SocketBase +{ + /// + /// Request handler + /// + /// The type of the app session. + /// The type of the request info. + /// The session. + /// The request info. + public delegate void RequestHandler(TAppSession session, TRequestInfo requestInfo) + where TAppSession : IAppSession, IAppSession, new() + where TRequestInfo : IRequestInfo; +} diff --git a/SocketBase/Security/CertificateManager.cs b/SocketBase/Security/CertificateManager.cs new file mode 100644 index 000000000..83b8e35a3 --- /dev/null +++ b/SocketBase/Security/CertificateManager.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using SuperSocket.Common; +using SuperSocket.SocketBase.Config; + +namespace SuperSocket.SocketBase.Security +{ + static class CertificateManager + { + internal static X509Certificate Initialize(ICertificateConfig cerConfig) + { + if (!string.IsNullOrEmpty(cerConfig.FilePath)) + { + //To keep compatible with website hosting + string filePath; + + if (Path.IsPathRooted(cerConfig.FilePath)) + filePath = cerConfig.FilePath; + else + { + filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, cerConfig.FilePath); + } + + return new X509Certificate2(filePath, cerConfig.Password); + } + else + { + var storeName = cerConfig.StoreName; + if (string.IsNullOrEmpty(storeName)) + storeName = "Root"; + + var store = new X509Store(storeName); + + store.Open(OpenFlags.ReadOnly); + + var cert = store.Certificates.OfType().Where(c => + c.Thumbprint.Equals(cerConfig.Thumbprint, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); + + store.Close(); + + return cert; + } + } + } +} diff --git a/SocketBase/SocketMode.cs b/SocketBase/SocketMode.cs new file mode 100644 index 000000000..5c1b06468 --- /dev/null +++ b/SocketBase/SocketMode.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace SuperSocket.SocketBase +{ + /// + /// Socket server running mode + /// + public enum SocketMode + { + /// + /// Tcp mode + /// + Tcp, + + /// + /// Udp mode + /// + Udp + } +} diff --git a/SocketBase/SuperSocket.SocketBase.Net35.csproj b/SocketBase/SuperSocket.SocketBase.Net35.csproj new file mode 100644 index 000000000..2ca2ecdca --- /dev/null +++ b/SocketBase/SuperSocket.SocketBase.Net35.csproj @@ -0,0 +1,151 @@ + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {40B77789-EA11-4C05-8F52-86711D7BCAAF} + Library + Properties + SuperSocket.SocketBase + SuperSocket.SocketBase + v3.5 + 512 + + + + true + full + false + bin\Debug\ + TRACE;DEBUG;NET_35 + prompt + 4 + true + bin\Debug\SuperSocket.SocketBase.XML + + + pdbonly + true + bin\Release\ + TRACE;NET_35 + prompt + 4 + true + bin\Release\SuperSocket.SocketBase.XML + + + true + + + ..\supersocket.snk + + + + ..\Reference\log4net.dll + False + + + + + + False + ..\Reference\System.Threading.dll + + + + + + GlobalAssemblyInfo.cs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A} + SuperSocket.Common.Net35 + + + + + \ No newline at end of file diff --git a/SocketBase/SuperSocket.SocketBase.csproj b/SocketBase/SuperSocket.SocketBase.csproj new file mode 100644 index 000000000..595348a37 --- /dev/null +++ b/SocketBase/SuperSocket.SocketBase.csproj @@ -0,0 +1,185 @@ + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {40B77789-EA11-4C05-8F52-86711D7BCAAF} + Library + Properties + SuperSocket.SocketBase + SuperSocket.SocketBase + 512 + false + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + AllRules.ruleset + true + bin\Debug\SuperSocket.SocketBase.XML + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + AllRules.ruleset + true + bin\Release\SuperSocket.SocketBase.XML + + + true + + + ..\supersocket.snk + + + + ..\Reference\log4net.dll + False + + + + + + + + + + GlobalAssemblyInfo.cs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A} + SuperSocket.Common + + + + + False + Microsoft .NET Framework 4 %28x86 and x64%29 + true + + + False + .NET Framework 3.5 SP1 Client Profile + false + + + False + .NET Framework 3.5 SP1 + false + + + False + Windows Installer 3.1 + true + + + + + \ No newline at end of file diff --git a/SocketEngine/AppDomainAppServer.cs b/SocketEngine/AppDomainAppServer.cs new file mode 100644 index 000000000..ef899e79e --- /dev/null +++ b/SocketEngine/AppDomainAppServer.cs @@ -0,0 +1,204 @@ +using System; +using System.Reflection; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Config; +using SuperSocket.SocketBase.Provider; +using System.IO; + +namespace SuperSocket.SocketEngine +{ + /// + /// AppDomainAppServer + /// + public class AppDomainAppServer : IWorkItem + { + private IWorkItem m_AppServer; + + private string m_ServiceTypeName; + + private IBootstrap m_Bootstrap; + + private IServerConfig m_ServerConfig; + + private ProviderFactoryInfo[] m_Factories; + + private AppDomain m_HostDomain; + + private const string m_WorkingDir = "WorkRoot"; + + /// + /// Initializes a new instance of the class. + /// + /// Name of the service type. + public AppDomainAppServer(string serviceTypeName) + { + m_ServiceTypeName = serviceTypeName; + } + + /// + /// Initializes a new instance of the class. + /// + /// Type of the service. + public AppDomainAppServer(Type serviceType) + { + m_ServiceTypeName = serviceType.AssemblyQualifiedName; + } + + /// + /// Gets the name of the server instance. + /// + public string Name + { + get { return m_ServerConfig.Name; } + } + + /// + /// Setups the specified root config. + /// + /// The bootstrap. + /// The socket server instance config. + /// The factories. + /// + public bool Setup(IBootstrap bootstrap, IServerConfig config, ProviderFactoryInfo[] factories) + { + m_Bootstrap = bootstrap; + m_ServerConfig = config; + m_Factories = factories; + return true; + } + + /// + /// Starts this server instance. + /// + /// + /// return true if start successfull, else false + /// + public bool Start() + { + try + { + var currentDomain = AppDomain.CurrentDomain; + var marshalServerType = typeof(MarshalAppServer); + + var workingDir = Path.Combine(Path.Combine(currentDomain.BaseDirectory, m_WorkingDir), Name); + + if (!Directory.Exists(workingDir)) + Directory.CreateDirectory(workingDir); + + var startupConfigFile = m_Bootstrap.StartupConfigFile; + + if (!string.IsNullOrEmpty(startupConfigFile)) + { + if (!Path.IsPathRooted(startupConfigFile)) + startupConfigFile = Path.Combine(currentDomain.BaseDirectory, startupConfigFile); + } + + m_HostDomain = AppDomain.CreateDomain(m_ServerConfig.Name, currentDomain.Evidence, new AppDomainSetup + { + ApplicationName = m_ServerConfig.Name, + ApplicationBase = workingDir, + ConfigurationFile = startupConfigFile + }); + + var assemblyImportType = typeof(AssemblyImport); + + m_HostDomain.CreateInstanceFrom(assemblyImportType.Assembly.CodeBase, + assemblyImportType.FullName, + true, + BindingFlags.CreateInstance, + null, + new object[] { currentDomain.BaseDirectory }, + null, + new object[0]); + + m_AppServer = (IWorkItem)m_HostDomain.CreateInstanceAndUnwrap(marshalServerType.Assembly.FullName, + marshalServerType.FullName, + true, + BindingFlags.CreateInstance, + null, + new object[] { m_ServiceTypeName }, + null, + new object[0]); + + if (!m_AppServer.Setup(m_Bootstrap, m_ServerConfig, m_Factories)) + throw new Exception("Failed tp setup MarshalAppServer"); + } + catch (Exception) + { + if (m_HostDomain != null) + { + AppDomain.Unload(m_HostDomain); + m_HostDomain = null; + } + + if (m_AppServer != null) + { + m_AppServer = null; + } + + throw; + } + + return m_AppServer.Start(); + } + + /// + /// Stops this server instance. + /// + public void Stop() + { + try + { + m_AppServer.Stop(); + m_AppServer = null; + } + catch (Exception) + { + throw; + } + finally + { + try + { + AppDomain.Unload(m_HostDomain); + } + finally + { + m_HostDomain = null; + } + } + } + + /// + /// Gets a value indicating whether this instance is running. + /// + /// + /// true if this instance is running; otherwise, false. + /// + public bool IsRunning + { + get + { + if (m_AppServer == null) + return false; + + return m_AppServer.IsRunning; + } + } + + + /// + /// Gets the total session count. + /// + public int SessionCount + { + get + { + if (m_AppServer == null) + return 0; + + return m_AppServer.SessionCount; + } + } + } +} diff --git a/SocketEngine/AppDomainBootstrap.cs b/SocketEngine/AppDomainBootstrap.cs new file mode 100644 index 000000000..060785e35 --- /dev/null +++ b/SocketEngine/AppDomainBootstrap.cs @@ -0,0 +1,229 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Linq; +using System.Text; +using SuperSocket.Common; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Config; +using SuperSocket.SocketBase.Logging; +using SuperSocket.SocketBase.Provider; +using SuperSocket.SocketEngine.Configuration; + +namespace SuperSocket.SocketEngine +{ + /// + /// AppDomainBootstrap + /// + public sealed class AppDomainBootstrap : MarshalByRefObject, IBootstrap + { + class AppDomainWorkItemFactoryInfoLoader : WorkItemFactoryInfoLoader + { + class TypeValidator : MarshalByRefObject + { + public bool ValidateTypeName(string typeName) + { + Type type = null; + + try + { + type = Type.GetType(typeName, false); + } + catch + { + + } + + return type != null; + } + } + + public AppDomainWorkItemFactoryInfoLoader(IConfigurationSource config, ILogFactory passedInLogFactory) + : base(config, passedInLogFactory) + { + InitliazeValidationAppDomain(); + } + + public AppDomainWorkItemFactoryInfoLoader(IConfigurationSource config) + : base(config) + { + InitliazeValidationAppDomain(); + } + + private AppDomain m_ValidationAppDomain; + + private TypeValidator m_Validator; + + private void InitliazeValidationAppDomain() + { + m_ValidationAppDomain = AppDomain.CreateDomain("ValidationDomain", AppDomain.CurrentDomain.Evidence, AppDomain.CurrentDomain.BaseDirectory, string.Empty, false); + + var validatorType = typeof(TypeValidator); + m_Validator = (TypeValidator)m_ValidationAppDomain.CreateInstanceAndUnwrap(validatorType.Assembly.FullName, validatorType.FullName); + } + + protected override string ValidateProviderType(string typeName) + { + if (!m_Validator.ValidateTypeName(typeName)) + throw new Exception(string.Format("Failed to load type {0}!", typeName)); + + return typeName; + } + + public override void Dispose() + { + if (m_ValidationAppDomain != null) + { + AppDomain.Unload(m_ValidationAppDomain); + m_ValidationAppDomain = null; + } + + base.Dispose(); + } + } + + class DefaultBootstrapAppDomainWrap : DefaultBootstrap + { + private AppDomainBootstrap m_AppDomainBootstrap; + + public DefaultBootstrapAppDomainWrap(AppDomainBootstrap appDomainBootstrap, IConfigurationSource config, string startupConfigFile) + : base(config, startupConfigFile) + { + m_AppDomainBootstrap = appDomainBootstrap; + } + + protected override IWorkItem CreateWorkItemInstance(string serviceTypeName) + { + return new AppDomainAppServer(serviceTypeName); + } + + internal override bool SetupWorkItemInstance(IWorkItem workItem, WorkItemFactoryInfo factoryInfo) + { + return workItem.Setup(m_AppDomainBootstrap, factoryInfo.Config, factoryInfo.ProviderFactories.ToArray()); + } + + internal override WorkItemFactoryInfoLoader GetWorkItemFactoryInfoLoader(IConfigurationSource config, ILogFactory logFactory) + { + return new AppDomainWorkItemFactoryInfoLoader(config, logFactory); + } + } + + private IBootstrap m_InnerBootstrap; + + /// + /// Gets all the app servers running in this bootstrap + /// + public IEnumerable AppServers + { + get { return m_InnerBootstrap.AppServers; } + } + + /// + /// Gets the config. + /// + public IRootConfig Config + { + get { return m_InnerBootstrap.Config; } + } + + /// + /// Gets the startup config file. + /// + public string StartupConfigFile + { + get { return m_InnerBootstrap.StartupConfigFile; } + } + + /// + /// Initializes a new instance of the class. + /// + public AppDomainBootstrap(IConfigurationSource config) + { + string startupConfigFile = string.Empty; + + if (config == null) + throw new ArgumentNullException("config"); + + var configSectionSource = config as ConfigurationSection; + + if (configSectionSource != null) + startupConfigFile = configSectionSource.GetConfigSource(); + + //Keep serializable version of configuration + if(!config.GetType().IsSerializable) + config = new ConfigurationSource(config); + + //Still use raw configuration type to bootstrap + m_InnerBootstrap = new DefaultBootstrapAppDomainWrap(this, config, startupConfigFile); + } + + /// + /// Initializes the bootstrap with the configuration + /// + /// + public bool Initialize() + { + return m_InnerBootstrap.Initialize(); + } + + /// + /// Initializes the bootstrap with the configuration and config resolver. + /// + /// The server config resolver. + /// + public bool Initialize(Func serverConfigResolver) + { + return m_InnerBootstrap.Initialize(serverConfigResolver); + } + + /// + /// Initializes the bootstrap with the configuration and config resolver. + /// + /// The log factory. + /// + public bool Initialize(ILogFactory logFactory) + { + return m_InnerBootstrap.Initialize(logFactory); + } + + /// + /// Initializes the bootstrap with the configuration + /// + /// The server config resolver. + /// The log factory. + /// + public bool Initialize(Func serverConfigResolver, ILogFactory logFactory) + { + if (logFactory != null) + throw new Exception("You cannot pass in logFactory, if your isolation level is AppDomain!"); + + return m_InnerBootstrap.Initialize(serverConfigResolver, logFactory); + } + + /// + /// Starts this bootstrap. + /// + /// + public StartResult Start() + { + return m_InnerBootstrap.Start(); + } + + /// + /// Stops this bootstrap. + /// + public void Stop() + { + m_InnerBootstrap.Stop(); + } + + /// + /// Occurs when [performance data collected]. + /// + public event EventHandler PerformanceDataCollected + { + add { m_InnerBootstrap.PerformanceDataCollected += value; } + remove { m_InnerBootstrap.PerformanceDataCollected -= value; } + } + } +} diff --git a/SocketEngine/AssemblyImport.cs b/SocketEngine/AssemblyImport.cs new file mode 100644 index 000000000..066af1a48 --- /dev/null +++ b/SocketEngine/AssemblyImport.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.IO; +using System.Reflection; + +namespace SuperSocket.SocketEngine +{ + /// + /// AssemblyImport, used for importing assembly to the current AppDomain + /// + class AssemblyImport : MarshalByRefObject + { + private string m_ImportRoot; + + /// + /// Initializes a new instance of the class. + /// + public AssemblyImport(string importRoot) + { + m_ImportRoot = importRoot; + AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve); + } + + //Process cannot resolved assemblies + Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) + { + AssemblyName name = new AssemblyName(args.Name); + + var assemblyFilePath = Path.Combine(m_ImportRoot, name.Name + ".dll"); + + if (!File.Exists(assemblyFilePath)) + return null; + + return Assembly.LoadFrom(assemblyFilePath); + } + } +} diff --git a/SocketEngine/AsyncSocket/SocketAsyncEventArgsProxy.cs b/SocketEngine/AsyncSocket/SocketAsyncEventArgsProxy.cs new file mode 100644 index 000000000..51c18ca96 --- /dev/null +++ b/SocketEngine/AsyncSocket/SocketAsyncEventArgsProxy.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Sockets; +using System.Text; +using SuperSocket.Common; +using SuperSocket.SocketBase; + +namespace SuperSocket.SocketEngine.AsyncSocket +{ + class SocketAsyncEventArgsProxy + { + public SocketAsyncEventArgs SocketEventArgs { get; private set; } + + private SocketAsyncEventArgsProxy() + { + + } + + public SocketAsyncEventArgsProxy(SocketAsyncEventArgs socketEventArgs) + { + SocketEventArgs = socketEventArgs; + SocketEventArgs.Completed += new EventHandler(SocketEventArgs_Completed); + } + + static void SocketEventArgs_Completed(object sender, SocketAsyncEventArgs e) + { + var socketSession = e.UserToken as IAsyncSocketSession; + + if (socketSession == null) + return; + + if (e.LastOperation == SocketAsyncOperation.Receive) + { + socketSession.AsyncRun(() => socketSession.ProcessReceive(e)); + } + else + { + throw new ArgumentException("The last operation completed on the socket was not a receive"); + } + } + + public void Initialize(IAsyncSocketSession socketSession) + { + SocketEventArgs.UserToken = socketSession; + } + + public void Reset() + { + SocketEventArgs.UserToken = null; + } + } +} diff --git a/SocketEngine/AsyncSocketServer.cs b/SocketEngine/AsyncSocketServer.cs new file mode 100644 index 000000000..4bff57102 --- /dev/null +++ b/SocketEngine/AsyncSocketServer.cs @@ -0,0 +1,167 @@ +using System; +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Security.Authentication; +using System.Text; +using System.Threading; +using SuperSocket.Common; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; +using SuperSocket.SocketEngine.AsyncSocket; + +namespace SuperSocket.SocketEngine +{ + class AsyncSocketServer : TcpSocketServerBase + { + public AsyncSocketServer(IAppServer appServer, ListenerInfo[] listeners) + : base(appServer, listeners) + { + + } + + private BufferManager m_BufferManager; + + private ConcurrentStack m_ReadWritePool; + + public override bool Start() + { + try + { + int bufferSize = AppServer.Config.ReceiveBufferSize; + + if (bufferSize <= 0) + bufferSize = 1024 * 4; + + m_BufferManager = new BufferManager(bufferSize * AppServer.Config.MaxConnectionNumber, bufferSize); + + try + { + m_BufferManager.InitBuffer(); + } + catch (Exception e) + { + AppServer.Logger.Error("Failed to allocate buffer for async socket communication, may because there is no enough memory, please decrease maxConnectionNumber in configuration!", e); + return false; + } + + // preallocate pool of SocketAsyncEventArgs objects + SocketAsyncEventArgs socketEventArg; + + var socketArgsProxyList = new List(AppServer.Config.MaxConnectionNumber); + + for (int i = 0; i < AppServer.Config.MaxConnectionNumber; i++) + { + //Pre-allocate a set of reusable SocketAsyncEventArgs + socketEventArg = new SocketAsyncEventArgs(); + m_BufferManager.SetBuffer(socketEventArg); + + socketArgsProxyList.Add(new SocketAsyncEventArgsProxy(socketEventArg)); + } + + m_ReadWritePool = new ConcurrentStack(socketArgsProxyList); + + if (!base.Start()) + return false; + + IsRunning = true; + return true; + } + catch (Exception e) + { + AppServer.Logger.Error(e); + return false; + } + } + + protected override void OnNewClientAccepted(ISocketListener listener, Socket client, object state) + { + if (IsStopped) + return; + + //Get the socket for the accepted client connection and put it into the + //ReadEventArg object user token + SocketAsyncEventArgsProxy socketEventArgsProxy; + if (!m_ReadWritePool.TryPop(out socketEventArgsProxy)) + { + AppServer.AsyncRun(() => client.SafeClose()); + if (AppServer.Logger.IsErrorEnabled) + AppServer.Logger.ErrorFormat("Max connection number {0} was reached!", AppServer.Config.MaxConnectionNumber); + return; + } + + ISocketSession session; + + var security = listener.Info.Security; + + if (security == SslProtocols.None) + session = RegisterSession(client, new AsyncSocketSession(client, socketEventArgsProxy)); + else + session = RegisterSession(client, new AsyncStreamSocketSession(client, security, socketEventArgsProxy)); + + if (session == null) + { + socketEventArgsProxy.Reset(); + this.m_ReadWritePool.Push(socketEventArgsProxy); + AppServer.AsyncRun(() => client.SafeClose()); + return; + } + + session.Closed += session_Closed; + AppServer.AsyncRun(() => session.Start()); + } + + public override void ResetSessionSecurity(IAppSession session, SslProtocols security) + { + ISocketSession socketSession; + + var socketAsyncProxy = ((IAsyncSocketSessionBase)session.SocketSession).SocketAsyncProxy; + + if (security == SslProtocols.None) + socketSession = new AsyncSocketSession(session.SocketSession.Client, socketAsyncProxy, true); + else + socketSession = new AsyncStreamSocketSession(session.SocketSession.Client, security, socketAsyncProxy, true); + + socketSession.Initialize(session); + socketSession.Start(); + } + + void session_Closed(ISocketSession session, CloseReason reason) + { + IAsyncSocketSessionBase socketSession = session as IAsyncSocketSessionBase; + if (socketSession != null && this.m_ReadWritePool != null) + { + socketSession.SocketAsyncProxy.Reset(); + + if (m_ReadWritePool != null) + m_ReadWritePool.Push(socketSession.SocketAsyncProxy); + } + } + + public override void Stop() + { + if (IsStopped) + return; + + lock (SyncRoot) + { + if (IsStopped) + return; + + base.Stop(); + + if (m_ReadWritePool != null) + m_ReadWritePool = null; + + if (m_BufferManager != null) + m_BufferManager = null; + + IsRunning = false; + } + } + } +} diff --git a/SocketEngine/AsyncSocketSession.cs b/SocketEngine/AsyncSocketSession.cs new file mode 100644 index 000000000..e63cb2520 --- /dev/null +++ b/SocketEngine/AsyncSocketSession.cs @@ -0,0 +1,248 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net.Sockets; +using System.Text; +using System.Threading; +using SuperSocket.Common; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Logging; +using SuperSocket.SocketBase.Protocol; +using SuperSocket.SocketEngine.AsyncSocket; + +namespace SuperSocket.SocketEngine +{ + class AsyncSocketSession : SocketSession, IAsyncSocketSession + { + private bool m_IsReset; + + private SocketAsyncEventArgs m_SocketEventArgSend; + + public AsyncSocketSession(Socket client, SocketAsyncEventArgsProxy socketAsyncProxy) + : this(client, socketAsyncProxy, false) + { + + } + + public AsyncSocketSession(Socket client, SocketAsyncEventArgsProxy socketAsyncProxy, bool isReset) + : base(client) + { + SocketAsyncProxy = socketAsyncProxy; + m_IsReset = isReset; + } + + ILog ILoggerProvider.Logger + { + get { return AppSession.Logger; } + } + + public override void Start() + { + SocketAsyncProxy.Initialize(this); + StartReceive(SocketAsyncProxy.SocketEventArgs); + + if (!SyncSend) + { + m_SocketEventArgSend = new SocketAsyncEventArgs(); + m_SocketEventArgSend.Completed += new EventHandler(OnSendingCompleted); + } + + if (!m_IsReset) + StartSession(); + } + + bool ProcessCompleted(SocketAsyncEventArgs e) + { + // check if the remote host closed the connection + if (e.BytesTransferred <= 0) + { + Close(CloseReason.ClientClosing); + return false; + } + + if (e.SocketError != SocketError.Success) + { + if (e.SocketError != SocketError.ConnectionAborted + && e.SocketError != SocketError.ConnectionReset + && e.SocketError != SocketError.Interrupted + && e.SocketError != SocketError.Shutdown) + { + AppSession.Logger.Error(AppSession, new SocketException((int)e.SocketError)); + } + + Close(CloseReason.SocketError); + return false; + } + + return true; + } + + void OnSendingCompleted(object sender, SocketAsyncEventArgs e) + { + if (!ProcessCompleted(e)) + return; + + base.OnSendingCompleted(); + } + + private bool IsIgnorableException(Exception e) + { + if (e is ObjectDisposedException) + return true; + + if (e is SocketException) + { + var se = e as SocketException; + + if (se.ErrorCode == 10004 || se.ErrorCode == 10053 || se.ErrorCode == 10054 || se.ErrorCode == 10058) + return true; + } + + return false; + } + + private void StartReceive(SocketAsyncEventArgs e) + { + StartReceive(e, 0); + } + + private void StartReceive(SocketAsyncEventArgs e, int offsetDelta) + { + if (IsClosed) + return; + + bool willRaiseEvent = false; + + try + { + if (offsetDelta != 0) + { + e.SetBuffer(e.Offset + offsetDelta, e.Count - offsetDelta); + + if (e.Count > AppSession.AppServer.Config.ReceiveBufferSize) + throw new ArgumentException("Illigal offsetDelta", "offsetDelta"); + } + + willRaiseEvent = Client.ReceiveAsync(e); + } + catch (Exception exc) + { + if (!IsIgnorableException(exc)) + AppSession.Logger.Error(AppSession, exc); + + Close(CloseReason.SocketError); + return; + } + + if (!willRaiseEvent) + { + ProcessReceive(e); + } + } + + protected override void SendSync(IPosList> items) + { + try + { + for (var i = 0; i < items.Count; i++) + { + var item = items[i]; + + var client = Client; + + if (client == null) + return; + + client.Send(item.Array, item.Offset, item.Count, SocketFlags.None); + } + } + catch (Exception e) + { + if (!IsIgnorableException(e)) + AppSession.Logger.Error(AppSession, e); + + Close(CloseReason.SocketError); + return; + } + + OnSendingCompleted(); + } + + protected override void SendAsync(IPosList> items) + { + try + { + if (items.Count > 1) + { + if (m_SocketEventArgSend.Buffer != null) + m_SocketEventArgSend.SetBuffer(null, 0, 0); + + m_SocketEventArgSend.BufferList = items; + } + else + { + var currentItem = items[0]; + + try + { + if (m_SocketEventArgSend.BufferList != null) + m_SocketEventArgSend.BufferList = null; + } + catch (Exception e) //a strange NullReference exception + { + AppSession.Logger.Error(AppSession, e); + } + + m_SocketEventArgSend.SetBuffer(currentItem.Array, 0, currentItem.Count); + } + + var client = Client; + + if (client == null) + return; + + if (!client.SendAsync(m_SocketEventArgSend)) + OnSendingCompleted(client, m_SocketEventArgSend); + } + catch (Exception e) + { + if (!IsIgnorableException(e)) + AppSession.Logger.Error(AppSession, e); + + Close(CloseReason.SocketError); + } + } + + public SocketAsyncEventArgsProxy SocketAsyncProxy { get; private set; } + + public void ProcessReceive(SocketAsyncEventArgs e) + { + if (!ProcessCompleted(e)) + return; + + int offsetDelta; + + try + { + offsetDelta = this.AppSession.ProcessRequest(e.Buffer, e.Offset, e.BytesTransferred, true); + } + catch (Exception exc) + { + AppSession.Logger.Error(AppSession, "protocol error", exc); + this.Close(CloseReason.ProtocolError); + return; + } + + //read the next block of data sent from the client + StartReceive(e, offsetDelta); + } + + public override void ApplySecureProtocol() + { + //TODO: Implement async socket SSL/TLS encryption + } + } +} diff --git a/SocketEngine/AsyncStreamSocketSession.cs b/SocketEngine/AsyncStreamSocketSession.cs new file mode 100644 index 000000000..b3533205c --- /dev/null +++ b/SocketEngine/AsyncStreamSocketSession.cs @@ -0,0 +1,327 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net.Security; +using System.Net.Sockets; +using System.Security.Authentication; +using System.Text; +using SuperSocket.Common; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Logging; +using SuperSocket.SocketBase.Protocol; +using SuperSocket.SocketEngine.AsyncSocket; + +namespace SuperSocket.SocketEngine +{ + class AsyncStreamSocketSession : SocketSession, IAsyncSocketSessionBase + { + private byte[] m_ReadBuffer; + private int m_Offset; + private int m_Length; + + private bool m_IsReset; + + public AsyncStreamSocketSession(Socket client, SslProtocols security, SocketAsyncEventArgsProxy socketAsyncProxy) + : this(client, security, socketAsyncProxy, false) + { + + } + + public AsyncStreamSocketSession(Socket client, SslProtocols security, SocketAsyncEventArgsProxy socketAsyncProxy, bool isReset) + : base(client) + { + SecureProtocol = security; + SocketAsyncProxy = socketAsyncProxy; + SocketAsyncEventArgs e = socketAsyncProxy.SocketEventArgs; + m_ReadBuffer = e.Buffer; + m_Offset = e.Offset; + m_Length = e.Count; + + m_IsReset = isReset; + } + + private bool IsIgnorableException(Exception e) + { + if (e is ObjectDisposedException) + return true; + + if (e is IOException) + { + if (e.InnerException is ObjectDisposedException) + return true; + + if (e.InnerException is SocketException) + { + var se = e.InnerException as SocketException; + + if (se.ErrorCode == 10004 || se.ErrorCode == 10053 || se.ErrorCode == 10054 || se.ErrorCode == 10058 || se.ErrorCode == -1073741299) + return true; + } + } + + return false; + } + + /// + /// Starts this session communication. + /// + public override void Start() + { + //Hasn't started, but already closed + if (IsClosed) + return; + + try + { + var asyncResult = BeginInitStream(OnBeginInitStreamOnSessionStarted); + + //If the operation is synchronous + if (asyncResult == null) + OnSessionStarting(); + } + catch (Exception e) + { + if(!IsIgnorableException(e)) + AppSession.Logger.Error(AppSession, e); + + Close(CloseReason.SocketError); + return; + } + } + + private void OnSessionStarting() + { + try + { + m_Stream.BeginRead(m_ReadBuffer, m_Offset, m_Length, OnStreamEndRead, m_Stream); + } + catch (Exception e) + { + if (!IsIgnorableException(e)) + AppSession.Logger.Error(AppSession, e); + + this.Close(CloseReason.SocketError); + } + + if (!m_IsReset) + StartSession(); + } + + private void OnStreamEndRead(IAsyncResult result) + { + var stream = result.AsyncState as Stream; + + int thisRead = 0; + + try + { + thisRead = stream.EndRead(result); + } + catch (Exception e) + { + if (!IsIgnorableException(e)) + AppSession.Logger.Error(AppSession, e); + + this.Close(CloseReason.SocketError); + return; + } + + if (thisRead <= 0) + { + this.Close(CloseReason.ClientClosing); + return; + } + + int offsetDelta; + + try + { + offsetDelta = AppSession.ProcessRequest(m_ReadBuffer, m_Offset, thisRead, true); + } + catch (Exception ex) + { + AppSession.Logger.Error(AppSession, "protocol error", ex); + this.Close(CloseReason.ProtocolError); + return; + } + + try + { + if (offsetDelta != 0) + { + m_Offset += offsetDelta; + m_Length -= offsetDelta; + + if (m_Length > AppSession.AppServer.Config.ReceiveBufferSize) + throw new Exception("Illigal offsetDelta"); + } + + m_Stream.BeginRead(m_ReadBuffer, m_Offset, m_Length, OnStreamEndRead, m_Stream); + } + catch (Exception exc) + { + if (!IsIgnorableException(exc)) + AppSession.Logger.Error(AppSession, exc); + + this.Close(CloseReason.SocketError); + return; + } + } + + private Stream m_Stream; + + private IAsyncResult BeginInitStream(AsyncCallback asyncCallback) + { + IAsyncResult result = null; + + switch (SecureProtocol) + { + case (SslProtocols.Default): + case (SslProtocols.Tls): + case (SslProtocols.Ssl3): + SslStream sslStream = new SslStream(new NetworkStream(Client), false); + result = sslStream.BeginAuthenticateAsServer(AppSession.AppServer.Certificate, false, SslProtocols.Default, false, asyncCallback, sslStream); + break; + case (SslProtocols.Ssl2): + SslStream ssl2Stream = new SslStream(new NetworkStream(Client), false); + result = ssl2Stream.BeginAuthenticateAsServer(AppSession.AppServer.Certificate, false, SslProtocols.Ssl2, false, asyncCallback, ssl2Stream); + break; + default: + m_Stream = new NetworkStream(Client); + break; + } + + return result; + } + + private void OnBeginInitStreamOnSessionStarted(IAsyncResult result) + { + OnBeginInitStream(result); + + if (m_Stream != null) + OnSessionStarting(); + } + + private void OnBeginInitStream(IAsyncResult result) + { + var sslStream = result.AsyncState as SslStream; + + try + { + sslStream.EndAuthenticateAsServer(result); + } + catch (Exception e) + { + if(!IsIgnorableException(e)) + AppSession.Logger.Error(AppSession, e); + + this.Close(CloseReason.SocketError); + return; + } + + m_Stream = sslStream; + } + + protected override void SendSync(IPosList> items) + { + try + { + for (var i = 0; i < items.Count; i++) + { + var item = items[i]; + m_Stream.Write(item.Array, item.Offset, item.Count); + } + } + catch (Exception e) + { + if (!IsIgnorableException(e)) + AppSession.Logger.Error(AppSession, e); + + Close(CloseReason.SocketError); + return; + } + + OnSendingCompleted(); + } + + protected override void OnSendingCompleted() + { + try + { + m_Stream.Flush(); + } + catch (Exception e) + { + if (!IsIgnorableException(e)) + AppSession.Logger.Error(AppSession, e); + + Close(CloseReason.SocketError); + return; + } + + base.OnSendingCompleted(); + } + + protected override void SendAsync(IPosList> items) + { + try + { + var item = items[items.Position]; + m_Stream.BeginWrite(item.Array, item.Offset, item.Count, OnEndWrite, items); + } + catch (Exception e) + { + if (!IsIgnorableException(e)) + AppSession.Logger.Error(AppSession, e); + + Close(CloseReason.SocketError); + } + } + + private void OnEndWrite(IAsyncResult result) + { + try + { + m_Stream.EndWrite(result); + } + catch (Exception e) + { + if (!IsIgnorableException(e)) + AppSession.Logger.Error(AppSession, e); + + Close(CloseReason.SocketError); + return; + } + + var items = result.AsyncState as IPosList>; + var nextPos = items.Position + 1; + + //Has more data to send + if (nextPos < items.Count) + { + items.Position = nextPos; + SendAsync(items); + return; + } + + OnSendingCompleted(); + } + + public override void ApplySecureProtocol() + { + var asyncResult = BeginInitStream(OnBeginInitStream); + + if (asyncResult != null) + asyncResult.AsyncWaitHandle.WaitOne(); + } + + public SocketAsyncEventArgsProxy SocketAsyncProxy { get; private set; } + + ILog ILoggerProvider.Logger + { + get { return AppSession.Logger; } + } + } +} diff --git a/SocketEngine/BootstrapFactory.cs b/SocketEngine/BootstrapFactory.cs new file mode 100644 index 000000000..167b50c57 --- /dev/null +++ b/SocketEngine/BootstrapFactory.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase; +using SuperSocket.SocketEngine.Configuration; +using SuperSocket.SocketBase.Config; +using System.Configuration; + +namespace SuperSocket.SocketEngine +{ + /// + /// Bootstrap Factory + /// + public static class BootstrapFactory + { + /// + /// Creates the bootstrap. + /// + /// The config. + /// + public static IBootstrap CreateBootstrap(IConfigurationSource config) + { + if (config.Isolation == IsolationMode.AppDomain) + return new AppDomainBootstrap(config); + else + return new DefaultBootstrap(config); + } + + /// + /// Creates the bootstrap from app configuration's socketServer section. + /// + /// + public static IBootstrap CreateBootstrap() + { + return CreateBootstrap("socketServer"); + } + + /// + /// Creates the bootstrap. + /// + /// Name of the config section. + /// + public static IBootstrap CreateBootstrap(string configSectionName) + { + return CreateBootstrap(ConfigurationManager.GetSection(configSectionName) as IConfigurationSource); + } + + /// + /// Creates the bootstrap from configuration file. + /// + /// The configuration file. + /// + public static IBootstrap CreateBootstrapFromConfigFile(string configFile) + { + ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap(); + fileMap.ExeConfigFilename = configFile; + + var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); + var configSource = config.GetSection("socketServer") as IConfigurationSource; + + return CreateBootstrap(configSource); + } + } +} diff --git a/SocketEngine/Configuration/CertificateConfig.cs b/SocketEngine/Configuration/CertificateConfig.cs new file mode 100644 index 000000000..e16d351c5 --- /dev/null +++ b/SocketEngine/Configuration/CertificateConfig.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Configuration; +using SuperSocket.SocketBase.Config; + +namespace SuperSocket.SocketEngine.Configuration +{ + /// + /// Certificate configuration + /// + public class CertificateConfig : ConfigurationElement, ICertificateConfig + { + #region ICertificateConfig Members + + /// + /// Gets the certificate file path. + /// + [ConfigurationProperty("filePath", IsRequired = false)] + public string FilePath + { + get + { + return this["filePath"] as string; + } + } + + /// + /// Gets the password. + /// + [ConfigurationProperty("password", IsRequired = false)] + public string Password + { + get + { + return this["password"] as string; + } + } + + /// + /// Gets the the store where certificate locates. + /// + /// + /// The name of the store. + /// + [ConfigurationProperty("storeName", IsRequired = false)] + public string StoreName + { + get + { + return this["storeName"] as string; + } + } + + /// + /// Gets the thumbprint. + /// + [ConfigurationProperty("thumbprint", IsRequired = false)] + public string Thumbprint + { + get + { + return this["thumbprint"] as string; + } + } + + #endregion ICertificateConfig Members + } +} diff --git a/SocketEngine/Configuration/Listener.cs b/SocketEngine/Configuration/Listener.cs new file mode 100644 index 000000000..4cca34759 --- /dev/null +++ b/SocketEngine/Configuration/Listener.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Config; +using System.Configuration; +using SuperSocket.Common; + +namespace SuperSocket.SocketEngine.Configuration +{ + /// + /// Listener configuration + /// + public class Listener : ConfigurationElement, IListenerConfig + { + /// + /// Gets the ip of listener + /// + [ConfigurationProperty("ip", IsRequired = true)] + public string Ip + { + get { return this["ip"] as string; } + } + + /// + /// Gets the port of listener + /// + [ConfigurationProperty("port", IsRequired = true)] + public int Port + { + get { return (int)this["port"]; } + } + + /// + /// Gets the backlog. + /// + [ConfigurationProperty("backlog", IsRequired = false, DefaultValue = 100)] + public int Backlog + { + get { return (int)this["backlog"]; } + } + + /// + /// Gets the security option, None/Default/Tls/Ssl/... + /// + [ConfigurationProperty("security", IsRequired = false, DefaultValue = "None")] + public string Security + { + get + { + return (string)this["security"]; + } + } + } + + /// + /// Listener configuration collection + /// + [ConfigurationCollection(typeof(Listener))] + public class ListenerConfigCollection : GenericConfigurationElementCollectionBase + { + + } +} diff --git a/SocketEngine/Configuration/Server.cs b/SocketEngine/Configuration/Server.cs new file mode 100644 index 000000000..be9a07aef --- /dev/null +++ b/SocketEngine/Configuration/Server.cs @@ -0,0 +1,420 @@ +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Configuration; +using System.IO; +using System.Security.Authentication; +using System.Text; +using System.Xml; +using System.Linq; +using SuperSocket.Common; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Config; + +namespace SuperSocket.SocketEngine.Configuration +{ + /// + /// Server configuration + /// + [Serializable] + public class Server : ConfigurationElementBase, IServerConfig + { + /// + /// Gets the name of the server type this appServer want to use. + /// + /// + /// The name of the server type. + /// + [ConfigurationProperty("serverTypeName", IsRequired = false)] + public string ServerTypeName + { + get { return this["serverTypeName"] as string; } + } + + /// + /// Gets the type definition of the appserver. + /// + /// + /// The type of the server. + /// + [ConfigurationProperty("serverType", IsRequired = false)] + public string ServerType + { + get { return this["serverType"] as string; } + } + + /// + /// Gets the request filter factory. + /// + [ConfigurationProperty("requestFilterFactory", IsRequired = false)] + public string RequestFilterFactory + { + get { return this["requestFilterFactory"] as string; } + } + + /// + /// Gets the ip. + /// + [ConfigurationProperty("ip", IsRequired = false)] + public string Ip + { + get { return this["ip"] as string; } + } + + /// + /// Gets the port. + /// + [ConfigurationProperty("port", IsRequired = false)] + public int Port + { + get { return (int)this["port"]; } + } + + /// + /// Gets the mode. + /// + [ConfigurationProperty("mode", IsRequired = false, DefaultValue = "Tcp")] + public SocketMode Mode + { + get { return (SocketMode)this["mode"]; } + } + + /// + /// Gets a value indicating whether this is disabled. + /// + /// + /// true if disabled; otherwise, false. + /// + [ConfigurationProperty("disabled", DefaultValue = "false")] + public bool Disabled + { + get { return (bool)this["disabled"]; } + } + + /// + /// Gets the send time out. + /// + [ConfigurationProperty("sendTimeOut", IsRequired = false, DefaultValue = 0)] + public int SendTimeOut + { + get { return (int)this["sendTimeOut"]; } + } + + /// + /// Gets the max connection number. + /// + [ConfigurationProperty("maxConnectionNumber", IsRequired = false, DefaultValue = 100)] + public int MaxConnectionNumber + { + get { return (int)this["maxConnectionNumber"]; } + } + + /// + /// Gets the size of the receive buffer. + /// + /// + /// The size of the receive buffer. + /// + [ConfigurationProperty("receiveBufferSize", IsRequired = false, DefaultValue = 2048)] + public int ReceiveBufferSize + { + get { return (int)this["receiveBufferSize"]; } + } + + /// + /// Gets the size of the send buffer. + /// + /// + /// The size of the send buffer. + /// + [ConfigurationProperty("sendBufferSize", IsRequired = false, DefaultValue = 2048)] + public int SendBufferSize + { + get { return (int)this["sendBufferSize"]; } + } + + /// + /// Gets a value indicating whether sending is in synchronous mode. + /// + /// + /// true if [sync send]; otherwise, false. + /// + [ConfigurationProperty("syncSend", IsRequired = false, DefaultValue = false)] + public bool SyncSend + { + get { return (bool)this["syncSend"]; } + } + + /// + /// Gets a value indicating whether log command in log file. + /// + /// true if log command; otherwise, false. + [ConfigurationProperty("logCommand", IsRequired = false, DefaultValue = false)] + public bool LogCommand + { + get { return (bool)this["logCommand"]; } + } + + /// + /// Gets a value indicating whether clear idle session. + /// + /// true if clear idle session; otherwise, false. + [ConfigurationProperty("clearIdleSession", IsRequired = false, DefaultValue = false)] + public bool ClearIdleSession + { + get { return (bool)this["clearIdleSession"]; } + } + + /// + /// Gets the clear idle session interval, in seconds. + /// + /// The clear idle session interval. + [ConfigurationProperty("clearIdleSessionInterval", IsRequired = false, DefaultValue = 120)] + public int ClearIdleSessionInterval + { + get { return (int)this["clearIdleSessionInterval"]; } + } + + + /// + /// Gets the idle session timeout time length, in seconds. + /// + /// The idle session time out. + [ConfigurationProperty("idleSessionTimeOut", IsRequired = false, DefaultValue = 300)] + public int IdleSessionTimeOut + { + get { return (int)this["idleSessionTimeOut"]; } + } + + /// + /// Gets the certificate config. + /// + /// The certificate config. + [ConfigurationProperty("certificate", IsRequired = false)] + public CertificateConfig CertificateConfig + { + get + { + return (CertificateConfig)this["certificate"]; + } + } + + /// + /// Gets X509Certificate configuration. + /// + /// + /// X509Certificate configuration. + /// + public ICertificateConfig Certificate + { + get { return CertificateConfig; } + } + + /// + /// Gets the security protocol, X509 certificate. + /// + [ConfigurationProperty("security", IsRequired = false, DefaultValue = "None")] + public string Security + { + get + { + return (string)this["security"]; + } + } + + /// + /// Gets the max allowed length of request. + /// + /// + /// The max allowed length of request. + /// + [ConfigurationProperty("maxRequestLength", IsRequired = false, DefaultValue = 1024)] + public int MaxRequestLength + { + get + { + return (int)this["maxRequestLength"]; + } + } + + /// + /// Gets a value indicating whether [disable session snapshot] + /// + [ConfigurationProperty("disableSessionSnapshot", IsRequired = false, DefaultValue = false)] + public bool DisableSessionSnapshot + { + get + { + return (bool)this["disableSessionSnapshot"]; + } + } + + /// + /// Gets the interval to taking snapshot for all live sessions. + /// + [ConfigurationProperty("sessionSnapshotInterval", IsRequired = false, DefaultValue = 5)] + public int SessionSnapshotInterval + { + get + { + return (int)this["sessionSnapshotInterval"]; + } + } + + /// + /// Gets the connection filters used by this server instance. + /// + /// + /// The connection filters's name list, seperated by comma + /// + [ConfigurationProperty("connectionFilter", IsRequired = false)] + public string ConnectionFilter + { + get + { + return (string)this["connectionFilter"]; + } + } + + /// + /// Gets the command loader, multiple values should be separated by comma. + /// + [ConfigurationProperty("commandLoader", IsRequired = false)] + public string CommandLoader + { + get + { + return (string)this["commandLoader"]; + } + } + + /// + /// Gets the start keep alive time, in seconds + /// + [ConfigurationProperty("keepAliveTime", IsRequired = false, DefaultValue = 600)] + public int KeepAliveTime + { + get + { + return (int)this["keepAliveTime"]; + } + } + + /// + /// Gets the keep alive interval, in seconds. + /// + [ConfigurationProperty("keepAliveInterval", IsRequired = false, DefaultValue = 60)] + public int KeepAliveInterval + { + get + { + return (int)this["keepAliveInterval"]; + } + } + + /// + /// Gets the backlog size of socket listening. + /// + [ConfigurationProperty("listenBacklog", IsRequired = false, DefaultValue = 100)] + public int ListenBacklog + { + get + { + return (int)this["listenBacklog"]; + } + } + + /// + /// Gets the startup order of the server instance. + /// + [ConfigurationProperty("startupOrder", IsRequired = false, DefaultValue = 0)] + public int StartupOrder + { + get + { + return (int)this["startupOrder"]; + } + } + + /// + /// Gets/sets the size of the sending queue. + /// + /// + /// The size of the sending queue. + /// + [ConfigurationProperty("sendingQueueSize", IsRequired = false, DefaultValue = 16)] + public int SendingQueueSize + { + get + { + return (int)this["sendingQueueSize"]; + } + } + + /// + /// Gets the logfactory name of the server instance. + /// + [ConfigurationProperty("logFactory", IsRequired = false, DefaultValue = "")] + public string LogFactory + { + get + { + return (string)this["logFactory"]; + } + } + + /// + /// Gets the listeners' configuration. + /// + [ConfigurationProperty("listeners", IsRequired = false)] + public ListenerConfigCollection Listeners + { + get + { + return this["listeners"] as ListenerConfigCollection; + } + } + + /// + /// Gets the listeners' configuration. + /// + IEnumerable IServerConfig.Listeners + { + get + { + return this.Listeners; + } + } + + /// + /// Gets the child config. + /// + /// The type of the config. + /// Name of the child config. + /// + public TConfig GetChildConfig(string childConfigName) + where TConfig : ConfigurationElement, new() + { + return this.OptionElements.GetChildConfig(childConfigName); + } + + /// + /// Gets a value indicating whether an unknown attribute is encountered during deserialization. + /// To keep compatible with old configuration + /// + /// The name of the unrecognized attribute. + /// The value of the unrecognized attribute. + /// + /// true when an unknown attribute is encountered while deserializing; otherwise, false. + /// + protected override bool OnDeserializeUnrecognizedAttribute(string name, string value) + { + //To keep compatible with old configuration + if (!"serviceName".Equals(name, StringComparison.OrdinalIgnoreCase)) + return base.OnDeserializeUnrecognizedAttribute(name, value); + + this["serverTypeName"] = value; + return true; + } + } +} diff --git a/SocketEngine/Configuration/ServerCollection.cs b/SocketEngine/Configuration/ServerCollection.cs new file mode 100644 index 000000000..8ee849605 --- /dev/null +++ b/SocketEngine/Configuration/ServerCollection.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Text; +using SuperSocket.Common; +using SuperSocket.SocketBase.Config; + +namespace SuperSocket.SocketEngine.Configuration +{ + /// + /// Server configuration collection + /// + [ConfigurationCollection(typeof(Server), AddItemName = "server")] + public class ServerCollection : GenericConfigurationElementCollection + { + } +} diff --git a/SocketEngine/Configuration/SocketServiceConfig.cs b/SocketEngine/Configuration/SocketServiceConfig.cs new file mode 100644 index 000000000..2132d784a --- /dev/null +++ b/SocketEngine/Configuration/SocketServiceConfig.cs @@ -0,0 +1,283 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Linq; +using System.Text; +using SuperSocket.Common; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Config; +using System.Collections.Specialized; + +namespace SuperSocket.SocketEngine.Configuration +{ + /// + /// SuperSocket's root configuration node + /// + public class SocketServiceConfig : ConfigurationSection, IConfigurationSource + { + /// + /// Gets all the server configurations + /// + [ConfigurationProperty("servers")] + public ServerCollection Servers + { + get + { + return this["servers"] as ServerCollection; + } + } + + /// + /// Gets the service configurations + /// + [ConfigurationProperty("serverTypes")] + public TypeProviderCollection ServerTypes + { + get + { + return this["serverTypes"] as TypeProviderCollection; + } + } + + /// + /// Gets all the connection filter configurations. + /// + [ConfigurationProperty("connectionFilters", IsRequired = false)] + public TypeProviderCollection ConnectionFilters + { + get + { + return this["connectionFilters"] as TypeProviderCollection; + } + } + + /// + /// Gets the defined log factory types. + /// + [ConfigurationProperty("logFactories", IsRequired = false)] + public TypeProviderCollection LogFactories + { + get + { + return this["logFactories"] as TypeProviderCollection; + } + } + + /// + /// Gets the logfactory name of the bootstrap. + /// + [ConfigurationProperty("requestFilterFactories", IsRequired = false)] + public TypeProviderCollection RequestFilterFactories + { + get + { + return this["requestFilterFactories"] as TypeProviderCollection; + } + } + + /// + /// Gets the command loaders definition. + /// + [ConfigurationProperty("commandLoaders", IsRequired = false)] + public TypeProviderCollection CommandLoaders + { + get + { + return this["commandLoaders"] as TypeProviderCollection; + } + } + + /// + /// Gets the max working threads. + /// + [ConfigurationProperty("maxWorkingThreads", IsRequired = false, DefaultValue = -1)] + public int MaxWorkingThreads + { + get + { + return (int)this["maxWorkingThreads"]; + } + } + + /// + /// Gets the min working threads. + /// + [ConfigurationProperty("minWorkingThreads", IsRequired = false, DefaultValue = -1)] + public int MinWorkingThreads + { + get + { + return (int)this["minWorkingThreads"]; + } + } + + /// + /// Gets the max completion port threads. + /// + [ConfigurationProperty("maxCompletionPortThreads", IsRequired = false, DefaultValue = -1)] + public int MaxCompletionPortThreads + { + get + { + return (int)this["maxCompletionPortThreads"]; + } + } + + /// + /// Gets the min completion port threads. + /// + [ConfigurationProperty("minCompletionPortThreads", IsRequired = false, DefaultValue = -1)] + public int MinCompletionPortThreads + { + get + { + return (int)this["minCompletionPortThreads"]; + } + } + + /// + /// Gets the performance data collect interval, in seconds. + /// + [ConfigurationProperty("performanceDataCollectInterval", IsRequired = false, DefaultValue = 60)] + public int PerformanceDataCollectInterval + { + get + { + return (int)this["performanceDataCollectInterval"]; + } + } + + /// + /// Gets a value indicating whether [disable performance data collector]. + /// + /// + /// true if [disable performance data collector]; otherwise, false. + /// + [ConfigurationProperty("disablePerformanceDataCollector", IsRequired = false, DefaultValue = false)] + public bool DisablePerformanceDataCollector + { + get + { + return (bool)this["disablePerformanceDataCollector"]; + } + } + + /// + /// Gets the isolation mode. + /// + [ConfigurationProperty("isolation", IsRequired = false, DefaultValue = IsolationMode.None)] + public IsolationMode Isolation + { + get { return (IsolationMode)this["isolation"]; } + } + + /// + /// Gets the logfactory name of the bootstrap. + /// + [ConfigurationProperty("logFactory", IsRequired = false, DefaultValue = "")] + public string LogFactory + { + get + { + return (string)this["logFactory"]; + } + } + + /// + /// Gets the option elements. + /// + public NameValueCollection OptionElements { get; private set; } + + /// + /// Gets a value indicating whether an unknown element is encountered during deserialization. + /// To keep compatible with old configuration + /// + /// The name of the unknown subelement. + /// The being used for deserialization. + /// + /// true when an unknown element is encountered while deserializing; otherwise, false. + /// + /// The element identified by is locked.- or -One or more of the element's attributes is locked.- or - is unrecognized, or the element has an unrecognized attribute.- or -The element has a Boolean attribute with an invalid value.- or -An attempt was made to deserialize a property more than once.- or -An attempt was made to deserialize a property that is not a valid member of the element.- or -The element cannot contain a CDATA or text element. + protected override bool OnDeserializeUnrecognizedElement(string elementName, System.Xml.XmlReader reader) + { + //To keep compatible with old configuration + if (!"services".Equals(elementName, StringComparison.OrdinalIgnoreCase)) + { + if (OptionElements == null) + OptionElements = new NameValueCollection(); + + OptionElements.Add(elementName, reader.ReadOuterXml()); + return true; + } + + var serverTypes = new TypeProviderCollection(); + reader.Read(); + serverTypes.Deserialize(reader); + + this["serverTypes"] = serverTypes; + + return true; + } + + /// + /// Gets the child config. + /// + /// The type of the config. + /// Name of the child config. + /// + public TConfig GetChildConfig(string childConfigName) + where TConfig : ConfigurationElement, new() + { + return this.OptionElements.GetChildConfig(childConfigName); + } + + IEnumerable IConfigurationSource.Servers + { + get + { + return this.Servers; + } + } + + IEnumerable IConfigurationSource.ServerTypes + { + get + { + return this.ServerTypes; + } + } + + IEnumerable IConfigurationSource.ConnectionFilters + { + get + { + return this.ConnectionFilters; + } + } + + IEnumerable IConfigurationSource.LogFactories + { + get + { + return this.LogFactories; + } + } + + IEnumerable IConfigurationSource.RequestFilterFactories + { + get + { + return this.RequestFilterFactories; + } + } + + + IEnumerable IConfigurationSource.CommandLoaders + { + get + { + return this.CommandLoaders; + } + } + } +} diff --git a/SocketEngine/DefaultBootstrap.cs b/SocketEngine/DefaultBootstrap.cs new file mode 100644 index 000000000..1fb7f199d --- /dev/null +++ b/SocketEngine/DefaultBootstrap.cs @@ -0,0 +1,408 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Diagnostics; +using System.Linq; +using System.Text; +using System.Threading; +using SuperSocket.Common; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Config; +using SuperSocket.SocketBase.Logging; +using SuperSocket.SocketBase.Provider; +using SuperSocket.SocketEngine.Configuration; + +namespace SuperSocket.SocketEngine +{ + /// + /// SuperSocket default bootstrap + /// + public class DefaultBootstrap : IBootstrap + { + private List m_AppServers; + + /// + /// Indicates whether the bootstrap is initialized + /// + private bool m_Initialized = false; + + /// + /// Global configuration + /// + private IConfigurationSource m_Config; + + /// + /// Global log + /// + private ILog m_GlobalLog; + + /// + /// Gets the log factory. + /// + protected ILogFactory LogFactory { get; private set; } + + /// + /// Gets all the app servers running in this bootstrap + /// + public IEnumerable AppServers + { + get { return m_AppServers; } + } + + private IRootConfig m_RootConfig; + + /// + /// Gets the config. + /// + public IRootConfig Config + { + get + { + if (m_Config != null) + return m_Config; + + return m_RootConfig; + } + } + + /// + /// Gets the startup config file. + /// + public string StartupConfigFile { get; private set; } + + private PerformanceMonitor m_PerfMonitor; + + /// + /// Initializes a new instance of the class. + /// + /// The app servers. + public DefaultBootstrap(IEnumerable appServers) + : this(new RootConfig(), appServers, new Log4NetLogFactory()) + { + + } + + /// + /// Initializes a new instance of the class. + /// + /// The root config. + /// The app servers. + public DefaultBootstrap(IRootConfig rootConfig, IEnumerable appServers) + : this(rootConfig, appServers, new Log4NetLogFactory()) + { + + } + + /// + /// Initializes a new instance of the class. + /// + /// The root config. + /// The app servers. + /// The log factory. + public DefaultBootstrap(IRootConfig rootConfig, IEnumerable appServers, ILogFactory logFactory) + { + if (rootConfig == null) + throw new ArgumentNullException("rootConfig"); + + if (appServers == null) + throw new ArgumentNullException("appServers"); + + if(!appServers.Any()) + throw new ArgumentException("appServers must have one item at least", "appServers"); + + if (logFactory == null) + throw new ArgumentNullException("logFactory"); + + m_RootConfig = rootConfig; + + m_AppServers = appServers.ToList(); + + m_GlobalLog = logFactory.GetLog(this.GetType().Name); + + if (!rootConfig.DisablePerformanceDataCollector) + { + m_PerfMonitor = new PerformanceMonitor(rootConfig, m_AppServers, logFactory); + m_PerfMonitor.Collected += new EventHandler(m_PerfMonitor_Collected); + } + + m_Initialized = true; + } + + /// + /// Initializes a new instance of the class. + /// + /// The config. + public DefaultBootstrap(IConfigurationSource config) + { + if (config == null) + throw new ArgumentNullException("config"); + + var fileConfigSource = config as ConfigurationSection; + + if (fileConfigSource != null) + StartupConfigFile = fileConfigSource.GetConfigSource(); + + m_Config = config; + } + + /// + /// Initializes a new instance of the class. + /// + /// The config. + /// The startup config file. + public DefaultBootstrap(IConfigurationSource config, string startupConfigFile) + { + if (config == null) + throw new ArgumentNullException("config"); + + if (!string.IsNullOrEmpty(startupConfigFile)) + StartupConfigFile = startupConfigFile; + + m_Config = config; + } + + /// + /// Creates the work item instance. + /// + /// Name of the service type. + /// + protected virtual IWorkItem CreateWorkItemInstance(string serviceTypeName) + { + var serviceType = Type.GetType(serviceTypeName, true); + return Activator.CreateInstance(serviceType) as IWorkItem; + } + + internal virtual bool SetupWorkItemInstance(IWorkItem workItem, WorkItemFactoryInfo factoryInfo) + { + try + { + //Share AppDomain AppServers also share same socket server factory and log factory instances + factoryInfo.SocketServerFactory.ExportFactory.EnsureInstance(); + factoryInfo.LogFactory.ExportFactory.EnsureInstance(); + } + catch (Exception e) + { + if (m_GlobalLog.IsErrorEnabled) + m_GlobalLog.Error(e); + + return false; + } + + return workItem.Setup(this, factoryInfo.Config, factoryInfo.ProviderFactories.ToArray()); + } + + /// + /// Gets the work item factory info loader. + /// + /// The config. + /// The log factory. + /// + internal virtual WorkItemFactoryInfoLoader GetWorkItemFactoryInfoLoader(IConfigurationSource config, ILogFactory logFactory) + { + return new WorkItemFactoryInfoLoader(config, logFactory); + } + + /// + /// Initializes the bootstrap with the configuration, config resolver and log factory. + /// + /// The server config resolver. + /// The log factory. + /// + public virtual bool Initialize(Func serverConfigResolver, ILogFactory logFactory) + { + if (m_Initialized) + throw new Exception("The server had been initialized already, you cannot initialize it again!"); + + if (logFactory != null && !string.IsNullOrEmpty(m_Config.LogFactory)) + { + throw new ArgumentException("You cannot pass in a logFactory parameter, if you have configured a root log factory.", "logFactory"); + } + + IEnumerable workItemFactories; + + using (var factoryInfoLoader = GetWorkItemFactoryInfoLoader(m_Config, logFactory)) + { + var bootstrapLogFactory = factoryInfoLoader.GetBootstrapLogFactory(); + + logFactory = bootstrapLogFactory.ExportFactory.CreateExport(); + + LogFactory = logFactory; + m_GlobalLog = logFactory.GetLog(this.GetType().Name); + + try + { + workItemFactories = factoryInfoLoader.LoadResult(serverConfigResolver); + } + catch (Exception e) + { + if (m_GlobalLog.IsErrorEnabled) + m_GlobalLog.Error(e); + + return false; + } + } + + m_AppServers = new List(m_Config.Servers.Count()); + //Initialize servers + foreach (var factoryInfo in workItemFactories) + { + IWorkItem appServer; + + try + { + appServer = CreateWorkItemInstance(factoryInfo.ServerType); + } + catch (Exception e) + { + if (m_GlobalLog.IsErrorEnabled) + m_GlobalLog.Error(string.Format("Failed to create server instance {0}!", factoryInfo.Config.Name), e); + return false; + } + + + var setupResult = false; + + try + { + setupResult = SetupWorkItemInstance(appServer, factoryInfo); + setupResult = true; + } + catch (Exception e) + { + m_GlobalLog.Error(e); + setupResult = false; + } + + if (!setupResult) + { + if (m_GlobalLog.IsErrorEnabled) + m_GlobalLog.Error("Failed to setup server instance!"); + return false; + } + + m_AppServers.Add(appServer); + } + + if (!m_Config.DisablePerformanceDataCollector) + { + m_PerfMonitor = new PerformanceMonitor(m_Config, m_AppServers, logFactory); + m_PerfMonitor.Collected += new EventHandler(m_PerfMonitor_Collected); + } + + m_Initialized = true; + + return true; + } + + /// + /// Initializes the bootstrap with the configuration and config resolver. + /// + /// The server config resolver. + /// + public virtual bool Initialize(Func serverConfigResolver) + { + return Initialize(serverConfigResolver, null); + } + + /// + /// Initializes the bootstrap with the configuration + /// + /// The log factory. + /// + public virtual bool Initialize(ILogFactory logFactory) + { + return Initialize(c => c, logFactory); + } + + /// + /// Initializes the bootstrap with the configuration + /// + /// + public virtual bool Initialize() + { + return Initialize(c => c); + } + + /// + /// Starts this bootstrap. + /// + /// + public StartResult Start() + { + if (!m_Initialized) + { + if (m_GlobalLog.IsErrorEnabled) + m_GlobalLog.Error("You cannot invoke method Start() before initializing!"); + + return StartResult.Failed; + } + + var result = StartResult.None; + + var succeeded = 0; + + foreach (var server in m_AppServers) + { + if (!server.Start()) + { + if (m_GlobalLog.IsErrorEnabled) + m_GlobalLog.Error("Failed to start " + server.Name + " server!"); + } + else + { + succeeded++; + if (m_GlobalLog.IsErrorEnabled) + m_GlobalLog.Info(server.Name + " has been started"); + } + } + + if (m_AppServers.Any()) + { + if (m_AppServers.Count == succeeded) + result = StartResult.Success; + else if (m_AppServers.Count == 0) + result = StartResult.Failed; + else + result = StartResult.PartialSuccess; + } + + if (m_PerfMonitor != null) + m_PerfMonitor.Start(); + + return result; + } + + /// + /// Stops this bootstrap. + /// + public void Stop() + { + foreach (var server in m_AppServers) + { + if (server.IsRunning) + { + server.Stop(); + + if (m_GlobalLog.IsInfoEnabled) + m_GlobalLog.Info(server.Name + " has been stopped"); + } + } + + if (m_PerfMonitor != null) + m_PerfMonitor.Stop(); + } + + void m_PerfMonitor_Collected(object sender, PermformanceDataEventArgs e) + { + var handler = PerformanceDataCollected; + + if (handler != null) + handler(sender, e); + } + + /// + /// Occurs when [performance data collected]. + /// + public event EventHandler PerformanceDataCollected; + } +} diff --git a/SocketEngine/Extensions.Net35.cs b/SocketEngine/Extensions.Net35.cs new file mode 100644 index 000000000..a408d6a0e --- /dev/null +++ b/SocketEngine/Extensions.Net35.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Reflection; +using System.Globalization; + +namespace SuperSocket.SocketEngine +{ + /// + /// Extensions for .Net 3.5 + /// + public static class Extensions + { + /// + /// Creates a new instance of the specified type defined in the specified assembly file. + /// + /// The app domain. + /// The assembly file. + /// Name of the type. + /// if set to true [ignore case]. + /// The binding attr. + /// The binder. + /// The args. + /// The culture. + /// The activation attributes. + /// + public static object CreateInstanceAndUnwrap(this AppDomain appDomain, string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes) + { + return appDomain.CreateInstanceAndUnwrap(assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, AppDomain.CurrentDomain.Evidence); + } + + /// + /// Creates the instance from. + /// + /// The app domain. + /// The assembly file. + /// Name of the type. + /// if set to true [ignore case]. + /// The binding attr. + /// The binder. + /// The args. + /// The culture. + /// The activation attributes. + /// + public static object CreateInstanceFrom(this AppDomain appDomain, string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes) + { + return appDomain.CreateInstanceFrom(assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, AppDomain.CurrentDomain.Evidence); + } + } +} diff --git a/SocketEngine/IAsyncSocketSession.cs b/SocketEngine/IAsyncSocketSession.cs new file mode 100644 index 000000000..9fd1cf2a1 --- /dev/null +++ b/SocketEngine/IAsyncSocketSession.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.Sockets; +using System.Text; +using SuperSocket.Common; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Logging; +using SuperSocket.SocketEngine.AsyncSocket; + +namespace SuperSocket.SocketEngine +{ + interface IAsyncSocketSessionBase : ILoggerProvider + { + SocketAsyncEventArgsProxy SocketAsyncProxy { get; } + + Socket Client { get; } + } + + interface IAsyncSocketSession : IAsyncSocketSessionBase + { + void ProcessReceive(SocketAsyncEventArgs e); + } +} diff --git a/SocketEngine/ISocketListener.cs b/SocketEngine/ISocketListener.cs new file mode 100644 index 000000000..e1cec3d74 --- /dev/null +++ b/SocketEngine/ISocketListener.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Config; +using System.Net.Sockets; +using System.Net; + +namespace SuperSocket.SocketEngine +{ + delegate void ErrorHandler(ISocketListener listener, Exception e); + + delegate void NewClientAcceptHandler(ISocketListener listener, Socket client, object state); + + /// + /// The interface for socket listener + /// + interface ISocketListener + { + /// + /// Gets the info of listener + /// + ListenerInfo Info { get; } + + /// + /// Gets the end point the listener is working on + /// + IPEndPoint EndPoint { get; } + + /// + /// Starts to listen + /// + /// The server config. + /// + bool Start(IServerConfig config); + + /// + /// Stops listening + /// + void Stop(); + + /// + /// Occurs when new client accepted. + /// + event NewClientAcceptHandler NewClientAccepted; + + /// + /// Occurs when error got. + /// + event ErrorHandler Error; + + + /// + /// Occurs when [stopped]. + /// + event EventHandler Stopped; + } +} diff --git a/SocketEngine/MarshalAppServer.cs b/SocketEngine/MarshalAppServer.cs new file mode 100644 index 000000000..5e0488136 --- /dev/null +++ b/SocketEngine/MarshalAppServer.cs @@ -0,0 +1,84 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Provider; +using SuperSocket.SocketBase.Config; +using System.Reflection; + +namespace SuperSocket.SocketEngine +{ + class MarshalAppServer : MarshalByRefObject, IWorkItem + { + private IWorkItem m_AppServer; + + /// + /// Initializes a new instance of the class. + /// + /// Name of the service type. + public MarshalAppServer(string serviceTypeName) + { + var serviceType = Type.GetType(serviceTypeName); + m_AppServer = (IWorkItem)Activator.CreateInstance(serviceType); + } + + /// + /// Gets the name of the server instance. + /// + public string Name + { + get { return m_AppServer.Name; } + } + + /// + /// Setups the specified root config. + /// + /// The bootstrap. + /// The socket server instance config. + /// The providers. + /// + public bool Setup(IBootstrap bootstrap, IServerConfig config, ProviderFactoryInfo[] factories) + { + return m_AppServer.Setup(bootstrap, config, factories); + } + + /// + /// Starts this server instance. + /// + /// + /// return true if start successfull, else false + /// + public bool Start() + { + return m_AppServer.Start(); + } + + /// + /// Stops this server instance. + /// + public void Stop() + { + m_AppServer.Stop(); + } + + /// + /// Gets a value indicating whether this instance is running. + /// + /// + /// true if this instance is running; otherwise, false. + /// + public bool IsRunning + { + get { return m_AppServer.IsRunning; } + } + + /// + /// Gets the total session count. + /// + public int SessionCount + { + get { return m_AppServer.SessionCount; } + } + } +} diff --git a/SocketEngine/PerformanceMonitor.cs b/SocketEngine/PerformanceMonitor.cs new file mode 100644 index 000000000..fd7e51299 --- /dev/null +++ b/SocketEngine/PerformanceMonitor.cs @@ -0,0 +1,153 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Text; +using System.Threading; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Config; +using SuperSocket.SocketBase.Logging; + +namespace SuperSocket.SocketEngine +{ + class PerformanceMonitor : IDisposable + { + private Timer m_PerformanceTimer; + private int m_TimerInterval; + private ILog m_PerfLog; + + private PerformanceCounter m_CpuUsagePC; + private PerformanceCounter m_ThreadCountPC; + private PerformanceCounter m_WorkingSetPC; + + private int m_CpuCores = 1; + + private EventHandler m_Collected; + + private IWorkItem[] m_AppServers; + + public PerformanceMonitor(IRootConfig config, IEnumerable appServers, ILogFactory logFactory) + { + m_AppServers = appServers.ToArray(); + + Process process = Process.GetCurrentProcess(); + + m_CpuCores = Environment.ProcessorCount; + + var isUnix = Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX; + var instanceName = isUnix ? string.Format("{0}/{1}", process.Id, process.ProcessName) : process.ProcessName; + + m_CpuUsagePC = new PerformanceCounter("Process", "% Processor Time", instanceName); + m_ThreadCountPC = new PerformanceCounter("Process", "Thread Count", instanceName); + m_WorkingSetPC = new PerformanceCounter("Process", "Working Set", instanceName); + + m_PerfLog = logFactory.GetLog("performance"); + + m_TimerInterval = config.PerformanceDataCollectInterval * 1000; + m_PerformanceTimer = new Timer(OnPerformanceTimerCallback); + } + + /// + /// Occurs when [performance data collected]. + /// + public event EventHandler Collected + { + add { m_Collected += value; } + remove { m_Collected -= value; } + } + + public void Start() + { + m_PerformanceTimer.Change(0, m_TimerInterval); + } + + public void Stop() + { + m_PerformanceTimer.Change(Timeout.Infinite, Timeout.Infinite); + } + + private void OnPerformanceTimerCallback(object state) + { + int availableWorkingThreads, availableCompletionPortThreads; + ThreadPool.GetAvailableThreads(out availableWorkingThreads, out availableCompletionPortThreads); + + int maxWorkingThreads; + int maxCompletionPortThreads; + ThreadPool.GetMaxThreads(out maxWorkingThreads, out maxCompletionPortThreads); + + var globalPerfData = new GlobalPerformanceData + { + AvailableWorkingThreads = availableWorkingThreads, + AvailableCompletionPortThreads = availableCompletionPortThreads, + MaxCompletionPortThreads = maxCompletionPortThreads, + MaxWorkingThreads = maxWorkingThreads, + CpuUsage = m_CpuUsagePC.NextValue() / m_CpuCores, + TotalThreadCount = (int)m_ThreadCountPC.NextValue(), + WorkingSet = (long)m_WorkingSetPC.NextValue() + }; + + var perfBuilder = new StringBuilder(); + + perfBuilder.AppendLine("---------------------------------------------------"); + perfBuilder.AppendLine(string.Format("CPU Usage: {0}%, Physical Memory Usage: {1:N}, Total Thread Count: {2}", globalPerfData.CpuUsage.ToString("0.00"), globalPerfData.WorkingSet, globalPerfData.TotalThreadCount)); + perfBuilder.AppendLine(string.Format("AvailableWorkingThreads: {0}, AvailableCompletionPortThreads: {1}", globalPerfData.AvailableWorkingThreads, globalPerfData.AvailableCompletionPortThreads)); + perfBuilder.AppendLine(string.Format("MaxWorkingThreads: {0}, MaxCompletionPortThreads: {1}", globalPerfData.MaxWorkingThreads, globalPerfData.MaxCompletionPortThreads)); + + var instancesData = new PerformanceDataInfo[m_AppServers.Length]; + + for (var i = 0; i < m_AppServers.Length; i++) + { + var s = m_AppServers[i]; + + var perfSource = s as IPerformanceDataSource; + if (perfSource != null) + { + var perfData = perfSource.CollectPerformanceData(globalPerfData); + + instancesData[i] = new PerformanceDataInfo { ServerName = s.Name, Data = perfData }; + + perfBuilder.AppendLine(string.Format("{0} - Total Connections: {1}, Total Handled Requests: {2}, Request Handling Speed: {3:f0}/s", + s.Name, + perfData.CurrentRecord.TotalConnections, + perfData.CurrentRecord.TotalHandledRequests, + (perfData.CurrentRecord.TotalHandledRequests - perfData.PreviousRecord.TotalHandledRequests) / perfData.CurrentRecord.RecordSpan)); + } + } + + m_PerfLog.Info(perfBuilder.ToString()); + + var handler = m_Collected; + if (handler == null) + return; + + handler.BeginInvoke(this, new PermformanceDataEventArgs(globalPerfData, instancesData), null, null); + } + + public void Dispose() + { + if (m_PerformanceTimer != null) + { + m_PerformanceTimer.Dispose(); + m_PerformanceTimer = null; + } + + if (m_CpuUsagePC != null) + { + m_CpuUsagePC.Close(); + m_CpuUsagePC = null; + } + + if (m_ThreadCountPC != null) + { + m_ThreadCountPC.Close(); + m_ThreadCountPC = null; + } + + if (m_WorkingSetPC != null) + { + m_WorkingSetPC.Close(); + m_WorkingSetPC = null; + } + } + } +} diff --git a/SocketEngine/Properties/AssemblyInfo.cs b/SocketEngine/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..fdd45f7de --- /dev/null +++ b/SocketEngine/Properties/AssemblyInfo.cs @@ -0,0 +1,17 @@ +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("SuperSocket.SocketEngine")] +[assembly: AssemblyDescription("SuperSocket.SocketEngine")] +[assembly: AssemblyConfiguration("")] +// 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)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("a9e989e2-6cd5-461c-a171-0eacec4e9c0a")] \ No newline at end of file diff --git a/SocketEngine/SocketListenerBase.cs b/SocketEngine/SocketListenerBase.cs new file mode 100644 index 000000000..0d723e4bd --- /dev/null +++ b/SocketEngine/SocketListenerBase.cs @@ -0,0 +1,70 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Config; + +namespace SuperSocket.SocketEngine +{ + abstract class SocketListenerBase : ISocketListener + { + public ListenerInfo Info { get; private set; } + + public IPEndPoint EndPoint + { + get { return Info.EndPoint; } + } + + protected SocketListenerBase(ListenerInfo info) + { + Info = info; + } + + /// + /// Starts to listen + /// + /// The server config. + /// + public abstract bool Start(IServerConfig config); + + public abstract void Stop(); + + public event NewClientAcceptHandler NewClientAccepted; + + public event ErrorHandler Error; + + protected void OnError(Exception e) + { + var handler = Error; + + if(handler != null) + handler(this, e); + } + + protected void OnError(string errorMessage) + { + OnError(new Exception(errorMessage)); + } + + protected virtual void OnNewClientAccepted(Socket socket, object state) + { + NewClientAccepted.BeginInvoke(this, socket, state, null, null); + } + + /// + /// Occurs when [stopped]. + /// + public event EventHandler Stopped; + + protected void OnStopped() + { + var handler = Stopped; + + if (handler != null) + handler(this, EventArgs.Empty); + } + } +} diff --git a/SocketEngine/SocketServerBase.cs b/SocketEngine/SocketServerBase.cs new file mode 100644 index 000000000..aa419d7e7 --- /dev/null +++ b/SocketEngine/SocketServerBase.cs @@ -0,0 +1,159 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Reflection; +using System.Security.Authentication; +using System.Text; +using System.Threading; +using SuperSocket.Common; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Logging; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.SocketEngine +{ + abstract class SocketServerBase : ISocketServer, IDisposable + { + protected object SyncRoot = new object(); + + public IAppServer AppServer { get; private set; } + + public bool IsRunning { get; protected set; } + + protected ListenerInfo[] ListenerInfos { get; private set; } + + protected List Listeners { get; private set; } + + protected bool IsStopped { get; set; } + + public SocketServerBase(IAppServer appServer, ListenerInfo[] listeners) + { + AppServer = appServer; + IsRunning = false; + ListenerInfos = listeners; + Listeners = new List(listeners.Length); + } + + public abstract void ResetSessionSecurity(IAppSession session, SslProtocols security); + + public virtual bool Start() + { + IsStopped = false; + + ILog log = AppServer.Logger; + + for (var i = 0; i < ListenerInfos.Length; i++) + { + var listener = CreateListener(ListenerInfos[i]); + listener.Error += new ErrorHandler(OnListenerError); + listener.Stopped += new EventHandler(OnListenerStopped); + listener.NewClientAccepted += new NewClientAcceptHandler(OnNewClientAccepted); + + if (listener.Start(AppServer.Config)) + { + Listeners.Add(listener); + + if (log.IsDebugEnabled) + { + log.DebugFormat("Listener ({0}) was started", listener.EndPoint); + } + } + else //If one listener failed to start, stop started listeners + { + if (log.IsDebugEnabled) + { + log.DebugFormat("Listener ({0}) failed to start", listener.EndPoint); + } + + for (var j = 0; j < Listeners.Count; j++) + { + Listeners[j].Stop(); + } + + Listeners.Clear(); + return false; + } + } + + IsRunning = true; + return true; + } + + protected abstract void OnNewClientAccepted(ISocketListener listener, Socket client, object state); + + void OnListenerError(ISocketListener listener, Exception e) + { + listener.Stop(); + + var logger = this.AppServer.Logger; + + if(!logger.IsErrorEnabled) + return; + + if (e is ObjectDisposedException || e is NullReferenceException) + return; + + var socketException = e as SocketException; + + if (socketException != null) + { + if (socketException.ErrorCode == 995 || socketException.ErrorCode == 10004 || socketException.ErrorCode == 10038) + return; + } + + logger.ErrorFormat(string.Format("Listener ({0}) error: {1}", listener.EndPoint, e.Message), e); + } + + void OnListenerStopped(object sender, EventArgs e) + { + var listener = sender as ISocketListener; + + ILog log = AppServer.Logger; + + if (log.IsDebugEnabled) + log.DebugFormat("Listener ({0}) was stoppped", listener.EndPoint); + } + + protected abstract ISocketListener CreateListener(ListenerInfo listenerInfo); + + public virtual void Stop() + { + IsStopped = true; + + for (var i = 0; i < Listeners.Count; i++) + { + var listener = Listeners[i]; + + listener.Stop(); + } + + Listeners.Clear(); + + IsRunning = false; + } + + #region IDisposable Members + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + if (IsRunning) + Stop(); + } + } + + #endregion + } +} diff --git a/SocketEngine/SocketServerFactory.cs b/SocketEngine/SocketServerFactory.cs new file mode 100644 index 000000000..62f1d3b06 --- /dev/null +++ b/SocketEngine/SocketServerFactory.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Protocol; +using SuperSocket.SocketBase.Config; +using System.Net; + +namespace SuperSocket.SocketEngine +{ + /// + /// Default socket server factory + /// + public class SocketServerFactory : ISocketServerFactory + { + private static ISocketServerFactory m_Instance; + + /// + /// Gets the instance. + /// + public static ISocketServerFactory Instance + { + get { return m_Instance; } + } + + static SocketServerFactory() + { + m_Instance = new SocketServerFactory(); + } + + private const string m_SecurityNone = "None"; + + #region ISocketServerFactory Members + + /// + /// Creates the socket server. + /// + /// The type of the request info. + /// The app server. + /// The listeners. + /// The config. + /// The request filter factory. + /// + public ISocketServer CreateSocketServer(IAppServer appServer, ListenerInfo[] listeners, IServerConfig config, IRequestFilterFactory requestFilterFactory) + where TRequestInfo : IRequestInfo + { + if (requestFilterFactory == null) + throw new ArgumentNullException("requestFilterFactory"); + + switch(config.Mode) + { + case(SocketMode.Tcp): + return new AsyncSocketServer(appServer, listeners); + case(SocketMode.Udp): + return new UdpSocketServer(appServer, listeners); + default: + throw new NotSupportedException("Unsupported SocketMode:" + config.Mode); + } + } + + #endregion + } +} diff --git a/SocketEngine/SocketSession.cs b/SocketEngine/SocketSession.cs new file mode 100644 index 000000000..cd832374a --- /dev/null +++ b/SocketEngine/SocketSession.cs @@ -0,0 +1,219 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.IO; +using System.Net; +using System.Net.Sockets; +using System.Security.Authentication; +using System.Text; +using System.Threading; +using SuperSocket.Common; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Config; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.SocketEngine +{ + /// + /// Socket Session, all application session should base on this class + /// + abstract class SocketSession : ISocketSession + { + public IAppSession AppSession { get; private set; } + + protected readonly object SyncRoot = new object(); + + private int m_InSending = 0; + + protected bool SyncSend { get; private set; } + + public SocketSession(Socket client) + : this(Guid.NewGuid().ToString()) + { + if (client == null) + throw new ArgumentNullException("client"); + + m_Client = client; + LocalEndPoint = (IPEndPoint)client.LocalEndPoint; + RemoteEndPoint = (IPEndPoint)client.RemoteEndPoint; + } + + public SocketSession(string sessionID) + { + SessionID = sessionID; + } + + public virtual void Initialize(IAppSession appSession) + { + AppSession = appSession; + SyncSend = appSession.Config.SyncSend; + } + + /// + /// Gets or sets the session ID. + /// + /// The session ID. + public string SessionID { get; private set; } + + + /// + /// Gets or sets the config. + /// + /// + /// The config. + /// + public IServerConfig Config { get; set; } + + /// + /// Starts this session. + /// + public abstract void Start(); + + /// + /// Says the welcome information when a client connectted. + /// + protected virtual void StartSession() + { + AppSession.StartSession(); + } + + /// + /// Called when [close]. + /// + protected virtual void OnClose(CloseReason reason) + { + m_IsClosed = true; + + Interlocked.CompareExchange(ref m_InSending, 0, 1); + + var closedHandler = Closed; + if (closedHandler != null) + { + closedHandler(this, reason); + } + } + + /// + /// Occurs when [closed]. + /// + public Action Closed { get; set; } + + IPosList> m_SendingItems; + + private IPosList> GetSendingItems() + { + if (m_SendingItems == null) + { + m_SendingItems = new PosList>(); + } + + return m_SendingItems; + } + + /// + /// Starts the sending. + /// + public void StartSend() + { + if (Interlocked.CompareExchange(ref m_InSending, 1, 0) == 1) + return; + + var sendingItems = GetSendingItems(); + + if (!AppSession.TryGetSendingData(sendingItems)) + Interlocked.Decrement(ref m_InSending); + + Send(sendingItems); + } + + protected abstract void SendAsync(IPosList> items); + + protected abstract void SendSync(IPosList> items); + + private void Send(IPosList> items) + { + if (SyncSend) + { + SendSync(items); + } + else + { + SendAsync(items); + } + } + + protected virtual void OnSendingCompleted() + { + var sendingItems = GetSendingItems(); + sendingItems.Clear(); + sendingItems.Position = 0; + + if (AppSession.TryGetSendingData(sendingItems)) + { + Send(sendingItems); + } + else + { + Interlocked.Decrement(ref m_InSending); + } + } + + public abstract void ApplySecureProtocol(); + + public Stream GetUnderlyStream() + { + return new NetworkStream(Client); + } + + + private Socket m_Client; + /// + /// Gets or sets the client. + /// + /// The client. + public Socket Client + { + get { return m_Client; } + } + + private bool m_IsClosed = false; + + protected bool IsClosed + { + get { return m_IsClosed; } + } + + /// + /// Gets the local end point. + /// + /// The local end point. + public virtual IPEndPoint LocalEndPoint { get; protected set; } + + /// + /// Gets the remote end point. + /// + /// The remote end point. + public virtual IPEndPoint RemoteEndPoint { get; protected set; } + + /// + /// Gets or sets the secure protocol. + /// + /// The secure protocol. + public SslProtocols SecureProtocol { get; set; } + + public virtual void Close(CloseReason reason) + { + var client = m_Client; + + if(client == null) + return; + + if (Interlocked.CompareExchange(ref m_Client, null, client) == client) + { + client.SafeClose(); + OnClose(reason); + } + } + } +} diff --git a/SocketEngine/SuperSocket.SocketEngine.Net35.csproj b/SocketEngine/SuperSocket.SocketEngine.Net35.csproj new file mode 100644 index 000000000..b734c431a --- /dev/null +++ b/SocketEngine/SuperSocket.SocketEngine.Net35.csproj @@ -0,0 +1,154 @@ + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {153FEF72-191C-43D9-BE71-2B351C7AC760} + Library + Properties + SuperSocket.SocketEngine + SuperSocket.SocketEngine + + + 3.5 + + + v3.5 + false + + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + true + AllRules.ruleset + bin\Debug\SuperSocket.SocketEngine.XML + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + AllRules.ruleset + true + bin\Release\SuperSocket.SocketEngine.XML + + + true + + + ..\supersocket.snk + + + + + + 3.5 + + + False + ..\Reference\System.Threading.dll + + + + + + GlobalAssemblyInfo.cs + + + + + + Code + + + Code + + + Code + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + False + .NET Framework 3.5 SP1 Client Profile + false + + + False + .NET Framework 3.5 SP1 + false + + + False + Windows Installer 3.1 + true + + + + + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A} + SuperSocket.Common.Net35 + + + {40B77789-EA11-4C05-8F52-86711D7BCAAF} + SuperSocket.SocketBase.Net35 + + + + + \ No newline at end of file diff --git a/SocketEngine/SuperSocket.SocketEngine.csproj b/SocketEngine/SuperSocket.SocketEngine.csproj new file mode 100644 index 000000000..72cd697ba --- /dev/null +++ b/SocketEngine/SuperSocket.SocketEngine.csproj @@ -0,0 +1,156 @@ + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {153FEF72-191C-43D9-BE71-2B351C7AC760} + Library + Properties + SuperSocket.SocketEngine + SuperSocket.SocketEngine + + + 3.5 + + + v4.0 + false + + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + true + AllRules.ruleset + bin\Debug\SuperSocket.SocketEngine.XML + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + AllRules.ruleset + bin\Release\SuperSocket.SocketEngine.XML + true + + + true + + + ..\supersocket.snk + + + + + + 3.5 + + + + + + + GlobalAssemblyInfo.cs + + + + + + + + + + + + + + + Code + + + Code + + + Code + + + + + + + + + + + + + + + + + + + + False + Microsoft .NET Framework 4 %28x86 and x64%29 + true + + + False + .NET Framework 3.5 SP1 Client Profile + false + + + False + .NET Framework 3.5 SP1 + false + + + False + Windows Installer 3.1 + true + + + + + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A} + SuperSocket.Common + + + {40B77789-EA11-4C05-8F52-86711D7BCAAF} + SuperSocket.SocketBase + + + + + + \ No newline at end of file diff --git a/SocketEngine/TcpAsyncSocketListener.cs b/SocketEngine/TcpAsyncSocketListener.cs new file mode 100644 index 000000000..719e21b6e --- /dev/null +++ b/SocketEngine/TcpAsyncSocketListener.cs @@ -0,0 +1,118 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Config; +using SuperSocket.SocketBase.Logging; + +namespace SuperSocket.SocketEngine +{ + /// + /// Tcp socket listener in async mode + /// + class TcpAsyncSocketListener : SocketListenerBase + { + private int m_ListenBackLog; + + private Socket m_ListenSocket; + + public TcpAsyncSocketListener(ListenerInfo info) + : base(info) + { + m_ListenBackLog = info.BackLog; + } + + /// + /// Starts to listen + /// + /// The server config. + /// + public override bool Start(IServerConfig config) + { + m_ListenSocket = new Socket(this.Info.EndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); + + try + { + m_ListenSocket.Bind(this.Info.EndPoint); + m_ListenSocket.Listen(m_ListenBackLog); + + m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); + m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true); + + SocketAsyncEventArgs acceptEventArg = new SocketAsyncEventArgs(); + acceptEventArg.Completed += new EventHandler(acceptEventArg_Completed); + + if (!m_ListenSocket.AcceptAsync(acceptEventArg)) + ProcessAccept(acceptEventArg); + + return true; + + } + catch (Exception e) + { + OnError(e); + return false; + } + } + + + void acceptEventArg_Completed(object sender, SocketAsyncEventArgs e) + { + ProcessAccept(e); + } + + void ProcessAccept(SocketAsyncEventArgs e) + { + if (e.SocketError != SocketError.Success) + { + OnError(new SocketException((int)e.SocketError)); + return; + } + + OnNewClientAccepted(e.AcceptSocket, null); + + e.AcceptSocket = null; + + bool willRaiseEvent = false; + + try + { + willRaiseEvent = m_ListenSocket.AcceptAsync(e); + } + catch (Exception exc) + { + OnError(exc); + return; + } + + if (!willRaiseEvent) + ProcessAccept(e); + } + + public override void Stop() + { + if (m_ListenSocket == null) + return; + + lock (this) + { + if (m_ListenSocket == null) + return; + + try + { + m_ListenSocket.Close(); + } + finally + { + m_ListenSocket = null; + } + } + + OnStopped(); + } + } +} diff --git a/SocketEngine/TcpSocketServerBase.cs b/SocketEngine/TcpSocketServerBase.cs new file mode 100644 index 000000000..05b34e798 --- /dev/null +++ b/SocketEngine/TcpSocketServerBase.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.InteropServices; +using System.Text; +using SuperSocket.Common; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Logging; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.SocketEngine +{ + abstract class TcpSocketServerBase : SocketServerBase + { + private readonly byte[] m_KeepAliveOptionValues; + private readonly int m_SendTimeOut; + private readonly int m_ReceiveBufferSize; + private readonly int m_SendBufferSize; + + public TcpSocketServerBase(IAppServer appServer, ListenerInfo[] listeners) + : base(appServer, listeners) + { + var config = appServer.Config; + + uint dummy = 0; + m_KeepAliveOptionValues = new byte[Marshal.SizeOf(dummy) * 3]; + //whether enable KeepAlive + BitConverter.GetBytes((uint)1).CopyTo(m_KeepAliveOptionValues, 0); + //how long will start first keep alive + BitConverter.GetBytes((uint)(config.KeepAliveTime * 1000)).CopyTo(m_KeepAliveOptionValues, Marshal.SizeOf(dummy)); + //keep alive interval + BitConverter.GetBytes((uint)(config.KeepAliveInterval * 1000)).CopyTo(m_KeepAliveOptionValues, Marshal.SizeOf(dummy) * 2); + + m_SendTimeOut = config.SendTimeOut; + m_ReceiveBufferSize = config.ReceiveBufferSize; + m_SendBufferSize = config.SendBufferSize; + } + + protected ISocketSession RegisterSession(Socket client, ISocketSession session) + { + if (m_SendTimeOut > 0) + client.SendTimeout = m_SendTimeOut; + + if (m_ReceiveBufferSize > 0) + client.ReceiveBufferSize = m_ReceiveBufferSize; + + if (m_SendBufferSize > 0) + client.SendBufferSize = m_SendBufferSize; + + if(!Platform.SupportSocketIOControlByCodeEnum) + client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); + else + client.IOControl(IOControlCode.KeepAliveValues, m_KeepAliveOptionValues, null); + + client.NoDelay = true; + client.UseOnlyOverlappedIO = true; + client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true); + + IAppSession appSession = this.AppServer.CreateAppSession(session); + + if (appSession == null) + return null; + + session.Initialize(appSession); + + return session; + } + + protected override ISocketListener CreateListener(ListenerInfo listenerInfo) + { + return new TcpAsyncSocketListener(listenerInfo); + } + } +} diff --git a/SocketEngine/UdpSocketListener.cs b/SocketEngine/UdpSocketListener.cs new file mode 100644 index 000000000..e5e3dc0ab --- /dev/null +++ b/SocketEngine/UdpSocketListener.cs @@ -0,0 +1,118 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text; +using SuperSocket.Common; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Config; + +namespace SuperSocket.SocketEngine +{ + class UdpSocketListener : SocketListenerBase + { + private Socket m_ListenSocket; + + public UdpSocketListener(ListenerInfo info) + : base(info) + { + + } + + /// + /// Starts to listen + /// + /// The server config. + /// + public override bool Start(IServerConfig config) + { + try + { + m_ListenSocket = new Socket(this.EndPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp); + m_ListenSocket.Bind(this.EndPoint); + + uint IOC_IN = 0x80000000; + uint IOC_VENDOR = 0x18000000; + uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12; + + byte[] optionInValue = { Convert.ToByte(false) }; + byte[] optionOutValue = new byte[4]; + m_ListenSocket.IOControl((int)SIO_UDP_CONNRESET, optionInValue, optionOutValue); + + var eventArgs = new SocketAsyncEventArgs(); + + eventArgs.Completed += new EventHandler(eventArgs_Completed); + eventArgs.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0); + + int receiveBufferSize = config.ReceiveBufferSize <= 0 ? 2048 : config.ReceiveBufferSize; + var buffer = new byte[receiveBufferSize]; + eventArgs.SetBuffer(buffer, 0, buffer.Length); + + m_ListenSocket.ReceiveFromAsync(eventArgs); + + return true; + } + catch (Exception e) + { + OnError(e); + return false; + } + } + + void eventArgs_Completed(object sender, SocketAsyncEventArgs e) + { + if (e.SocketError != SocketError.Success) + { + OnError(new SocketException((int)e.SocketError)); + return; + } + + if (e.LastOperation == SocketAsyncOperation.ReceiveFrom) + { + try + { + OnNewClientAccepted(m_ListenSocket, new object[] { e.Buffer.CloneRange(e.Offset, e.BytesTransferred), e.RemoteEndPoint.Serialize() }); + m_ListenSocket.ReceiveFromAsync(e); + } + catch (Exception exc) + { + OnError(exc); + } + } + } + + public override void Stop() + { + if (m_ListenSocket == null) + return; + + lock(this) + { + if (m_ListenSocket == null) + return; + + if(!Platform.IsMono) + { + try + { + m_ListenSocket.Shutdown(SocketShutdown.Both); + } + catch { } + } + + try + { + m_ListenSocket.Close(); + } + catch { } + finally + { + m_ListenSocket = null; + } + } + + OnStopped(); + } + } +} diff --git a/SocketEngine/UdpSocketServer.cs b/SocketEngine/UdpSocketServer.cs new file mode 100644 index 000000000..df7f49cfc --- /dev/null +++ b/SocketEngine/UdpSocketServer.cs @@ -0,0 +1,207 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Threading; +using SuperSocket.Common; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; +using SuperSocket.SocketEngine.AsyncSocket; + +namespace SuperSocket.SocketEngine +{ + class UdpSocketServer : SocketServerBase + where TRequestInfo : IRequestInfo + { + private IPEndPoint m_EndPointIPv4; + + private IPEndPoint m_EndPointIPv6; + + private bool m_IsUdpRequestInfo = false; + + private IRequestFilter m_UdpRequestFilter; + + private int m_ConnectionCount = 0; + + private IRequestHandler m_RequestHandler; + + /// + /// Initializes a new instance of the class. + /// + /// The app server. + /// The listeners. + public UdpSocketServer(IAppServer appServer, ListenerInfo[] listeners) + : base(appServer, listeners) + { + m_RequestHandler = appServer as IRequestHandler; + + m_EndPointIPv4 = new IPEndPoint(IPAddress.Any, 0); + m_EndPointIPv6 = new IPEndPoint(IPAddress.IPv6Any, 0); + + m_IsUdpRequestInfo = typeof(TRequestInfo).IsSubclassOf(typeof(UdpRequestInfo)); + + m_UdpRequestFilter = ((IRequestFilterFactory)appServer.RequestFilterFactory).CreateFilter(appServer, null); + } + + /// + /// Called when [new client accepted]. + /// + /// The listener. + /// The client. + /// The state. + protected override void OnNewClientAccepted(ISocketListener listener, Socket client, object state) + { + var paramArray = state as object[]; + + var receivedData = paramArray[0] as byte[]; + var socketAddress = paramArray[1] as SocketAddress; + var remoteEndPoint = (socketAddress.Family == AddressFamily.InterNetworkV6 ? m_EndPointIPv6.Create(socketAddress) : m_EndPointIPv4.Create(socketAddress)) as IPEndPoint; + + if (m_IsUdpRequestInfo) + { + ProcessPackageWithSessionID(client, remoteEndPoint, receivedData); + } + else + { + ProcessPackageWithoutSessionID(client, remoteEndPoint, receivedData); + } + } + + void ProcessPackageWithSessionID(Socket listenSocket, IPEndPoint remoteEndPoint, byte[] receivedData) + { + TRequestInfo requestInfo; + + string sessionID; + + int left; + + try + { + requestInfo = this.m_UdpRequestFilter.Filter(null, receivedData, 0, receivedData.Length, false, out left); + } + catch (Exception exc) + { + if(AppServer.Logger.IsErrorEnabled) + AppServer.Logger.Error("Failed to parse UDP package!", exc); + return; + } + + var udpRequestInfo = requestInfo as UdpRequestInfo; + + if (left > 0) + { + if (AppServer.Logger.IsErrorEnabled) + AppServer.Logger.Error("The output parameter left must be zero in this case!"); + return; + } + + if (udpRequestInfo == null) + { + if (AppServer.Logger.IsErrorEnabled) + AppServer.Logger.Error("Invalid UDP package format!"); + return; + } + + if (string.IsNullOrEmpty(udpRequestInfo.SessionID)) + { + if (AppServer.Logger.IsErrorEnabled) + AppServer.Logger.Error("Failed to get session key from UDP package!"); + return; + } + + sessionID = udpRequestInfo.SessionID; + + var appSession = AppServer.GetAppSessionByID(sessionID); + + if (appSession == null) + { + if (!DetectConnectionNumber(remoteEndPoint)) + return; + + var socketSession = new UdpSocketSession(listenSocket, remoteEndPoint, sessionID); + appSession = AppServer.CreateAppSession(socketSession); + + if (appSession == null) + return; + + socketSession.Initialize(appSession); + + Interlocked.Increment(ref m_ConnectionCount); + + socketSession.Closed += OnSocketSessionClosed; + socketSession.Start(); + } + else + { + var socketSession = appSession.SocketSession as UdpSocketSession; + //Client remote endpoint may change, so update session to ensure the server can find client correctly + socketSession.UpdateRemoteEndPoint(remoteEndPoint); + } + + m_RequestHandler.ExecuteCommand(appSession, requestInfo); + } + + void ProcessPackageWithoutSessionID(Socket listenSocket, IPEndPoint remoteEndPoint, byte[] receivedData) + { + var sessionID = remoteEndPoint.ToString(); + var appSession = AppServer.GetAppSessionByID(sessionID); + + if (appSession == null) //New session + { + if (!DetectConnectionNumber(remoteEndPoint)) + return; + + var socketSession = new UdpSocketSession(listenSocket, remoteEndPoint, sessionID); + + appSession = AppServer.CreateAppSession(socketSession); + + if (appSession == null) + return; + + socketSession.Initialize(appSession); + + Interlocked.Increment(ref m_ConnectionCount); + socketSession.Closed += OnSocketSessionClosed; + socketSession.Start(); + + appSession.ProcessRequest(receivedData, 0, receivedData.Length, false); + } + else //Existing session + { + appSession.ProcessRequest(receivedData, 0, receivedData.Length, false); + } + } + + void OnSocketSessionClosed(ISocketSession socketSession, CloseReason closeReason) + { + Interlocked.Decrement(ref m_ConnectionCount); + } + + bool DetectConnectionNumber(EndPoint remoteEndPoint) + { + if (m_ConnectionCount >= AppServer.Config.MaxConnectionNumber) + { + if (AppServer.Logger.IsErrorEnabled) + AppServer.Logger.ErrorFormat("Cannot accept a new UDP connection from {0}, the max connection number {1} has been exceed!", + remoteEndPoint.ToString(), AppServer.Config.MaxConnectionNumber); + + return false; + } + + return true; + } + + protected override ISocketListener CreateListener(ListenerInfo listenerInfo) + { + return new UdpSocketListener(listenerInfo); + } + + public override void ResetSessionSecurity(IAppSession session, System.Security.Authentication.SslProtocols security) + { + throw new NotSupportedException(); + } + } +} diff --git a/SocketEngine/UdpSocketSession.cs b/SocketEngine/UdpSocketSession.cs new file mode 100644 index 000000000..5364a0598 --- /dev/null +++ b/SocketEngine/UdpSocketSession.cs @@ -0,0 +1,98 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text; +using SuperSocket.Common; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.SocketEngine +{ + class UdpSocketSession : SocketSession + { + private Socket m_ServerSocket; + + public UdpSocketSession(Socket serverSocket, IPEndPoint remoteEndPoint) + : base(remoteEndPoint.ToString()) + { + m_ServerSocket = serverSocket; + RemoteEndPoint = remoteEndPoint; + } + + public UdpSocketSession(Socket serverSocket, IPEndPoint remoteEndPoint, string sessionID) + : base(sessionID) + { + m_ServerSocket = serverSocket; + RemoteEndPoint = remoteEndPoint; + } + + public override IPEndPoint LocalEndPoint + { + get { return (IPEndPoint)m_ServerSocket.LocalEndPoint; } + } + + /// + /// Updates the remote end point of the client. + /// + /// The remote end point. + internal void UpdateRemoteEndPoint(IPEndPoint remoteEndPoint) + { + this.RemoteEndPoint = remoteEndPoint; + } + + public override void Start() + { + StartSession(); + } + + protected override void SendAsync(IPosList> items) + { + var e = new SocketAsyncEventArgs(); + e.Completed += new EventHandler(SendingCompleted); + e.RemoteEndPoint = RemoteEndPoint; + e.BufferList = items; + m_ServerSocket.SendToAsync(e); + } + + void SendingCompleted(object sender, SocketAsyncEventArgs e) + { + if (e.SocketError != SocketError.Success) + { + var log = AppSession.Logger; + + if (log.IsErrorEnabled) + log.Error(new SocketException((int)e.SocketError)); + + return; + } + + OnSendingCompleted(); + } + + protected override void SendSync(IPosList> items) + { + for (var i = 0; i < items.Count; i++) + { + var item = items[i]; + m_ServerSocket.SendTo(item.Array, item.Offset, item.Count, SocketFlags.None, RemoteEndPoint); + } + + OnSendingCompleted(); + } + + public override void ApplySecureProtocol() + { + throw new NotSupportedException(); + } + + public override void Close(CloseReason reason) + { + if (!IsClosed) + OnClose(reason); + } + } +} diff --git a/SocketEngine/WorkItemFactoryInfo.cs b/SocketEngine/WorkItemFactoryInfo.cs new file mode 100644 index 000000000..7d212ee41 --- /dev/null +++ b/SocketEngine/WorkItemFactoryInfo.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Config; +using SuperSocket.SocketBase.Provider; + +namespace SuperSocket.SocketEngine +{ + class WorkItemFactoryInfo + { + public string ServerType { get; set; } + + public IServerConfig Config { get; set; } + + public IEnumerable ProviderFactories { get; set; } + + public ProviderFactoryInfo LogFactory { get; set; } + + public ProviderFactoryInfo SocketServerFactory { get; set; } + } +} diff --git a/SocketEngine/WorkItemFactoryInfoLoader.cs b/SocketEngine/WorkItemFactoryInfoLoader.cs new file mode 100644 index 000000000..be0a1321b --- /dev/null +++ b/SocketEngine/WorkItemFactoryInfoLoader.cs @@ -0,0 +1,244 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Config; +using SuperSocket.SocketBase.Logging; +using SuperSocket.SocketBase.Provider; +using SuperSocket.SocketEngine.Configuration; + +namespace SuperSocket.SocketEngine +{ + class WorkItemFactoryInfoLoader : IDisposable + { + private ProviderFactoryInfo m_DefaultLogFactory; + + private IConfigurationSource m_Config; + + public WorkItemFactoryInfoLoader(IConfigurationSource config, ILogFactory passedInLogFactory) + : this(config) + { + if (passedInLogFactory != null) + m_DefaultLogFactory = new ProviderFactoryInfo(ProviderKey.LogFactory, string.Empty, passedInLogFactory); + } + + public WorkItemFactoryInfoLoader(IConfigurationSource config) + { + m_Config = config; + } + + public ProviderFactoryInfo GetBootstrapLogFactory() + { + if (m_DefaultLogFactory != null) + return m_DefaultLogFactory; + + if (string.IsNullOrEmpty(m_Config.LogFactory)) + { + m_DefaultLogFactory = new ProviderFactoryInfo(ProviderKey.LogFactory, string.Empty, typeof(Log4NetLogFactory)); + return m_DefaultLogFactory; + } + + ProviderFactoryInfo factory = null; + + if (m_Config.LogFactories != null && m_Config.LogFactories.Count() > 0) + { + var logConfig = m_Config.LogFactories.FirstOrDefault(f => + f.Name.Equals(m_Config.LogFactory, StringComparison.OrdinalIgnoreCase)); + + if (logConfig != null) + { + factory = new ProviderFactoryInfo(ProviderKey.LogFactory, m_Config.LogFactory, ValidateProviderType(logConfig.Type)); + } + } + + if (factory == null) + throw new Exception(string.Format("the specific log factory '{0}' cannot be found!", m_Config.LogFactory)); + + m_DefaultLogFactory = factory; + + return factory; + } + + public List LoadResult(Func serverConfigResolver) + { + var workItemFactories = new List(m_Config.Servers.Count()); + + //var providerFactories = new List(); + + //Initialize server types + var serverTypeFactories = InitializeProviderFactories(ProviderKey.ServerType, m_Config.ServerTypes); + + //Initialize connection filters + var connectionFilterFactories = InitializeProviderFactories(ProviderKey.ConnectionFilter, m_Config.ConnectionFilters); + + //Initialize log factories + var logFactoryFactories = InitializeProviderFactories(ProviderKey.LogFactory, m_Config.LogFactories, m_DefaultLogFactory); + + //Initialize request filter factories + var requestFilterFactories = InitializeProviderFactories(ProviderKey.RequestFilterFactory, m_Config.RequestFilterFactories); + + + //Initialize command loader factories + var commandLoaderFactories = InitializeProviderFactories(ProviderKey.CommandLoader, m_Config.CommandLoaders); + + //Initialize servers + foreach (var c in m_Config.Servers.OrderBy(s => s.StartupOrder)) + { + var serverConfig = serverConfigResolver(c); + + if (string.IsNullOrEmpty(serverConfig.Name)) + throw new Exception("The name attribute of server node is required!"); + + string serverType; + + if (string.IsNullOrEmpty(serverConfig.ServerTypeName)) + { + if (string.IsNullOrEmpty(serverConfig.ServerType)) + throw new Exception("Either serverTypeName or serverType attribute of the server node is required!"); + + serverType = ValidateProviderType(serverConfig.ServerType); + } + else + { + var serviceFactory = serverTypeFactories.FirstOrDefault(p => p.Name.Equals(serverConfig.ServerTypeName, StringComparison.OrdinalIgnoreCase)); + + if (serviceFactory == null) + throw new Exception(string.Format("Failed to find a service for server {0}!", serverConfig.Name)); + + serverType = serviceFactory.ExportFactory.TypeName; + } + + var workItemFactory = new WorkItemFactoryInfo(); + workItemFactory.Config = serverConfig; + workItemFactory.ServerType = serverType; + + var factories = new List(); + + workItemFactory.SocketServerFactory = new ProviderFactoryInfo(ProviderKey.SocketServerFactory, string.Empty, typeof(SocketServerFactory)); + + factories.Add(workItemFactory.SocketServerFactory); + + //Initialize connection filters + if(!string.IsNullOrEmpty(serverConfig.ConnectionFilter)) + { + var currentFactories = GetSelectedFactories(connectionFilterFactories, serverConfig.ConnectionFilter); + + if (currentFactories.Any()) + factories.AddRange(currentFactories); + } + + //Initialize command loaders + if (!string.IsNullOrEmpty(serverConfig.CommandLoader)) + { + var currentFactories = GetSelectedFactories(commandLoaderFactories, serverConfig.CommandLoader); + + if (currentFactories.Any()) + factories.AddRange(currentFactories); + } + + var logFactoryName = c.LogFactory; + + if (!string.IsNullOrEmpty(logFactoryName)) + { + logFactoryName = logFactoryName.Trim(); + + var logProviderFactory = logFactoryFactories.FirstOrDefault(p => p.Name.Equals(logFactoryName, StringComparison.OrdinalIgnoreCase)); + + if (logProviderFactory == null) + throw new Exception(string.Format("the specific log factory '{0}' cannot be found!", logFactoryName)); + + workItemFactory.LogFactory = logProviderFactory; + } + else + { + workItemFactory.LogFactory = m_DefaultLogFactory; + } + + factories.Add(workItemFactory.LogFactory); + + //Initialize request filter factory + if (!string.IsNullOrEmpty(serverConfig.RequestFilterFactory)) + { + var currentRequestFilterFactory = requestFilterFactories.FirstOrDefault(p => p.Name.Equals(serverConfig.RequestFilterFactory, StringComparison.OrdinalIgnoreCase)); + + if (currentRequestFilterFactory == null) + throw new Exception(string.Format("the specific request filter factory '{0}' cannot be found!", serverConfig.RequestFilterFactory)); + + factories.Add(currentRequestFilterFactory); + } + + workItemFactory.ProviderFactories = factories; + + workItemFactories.Add(workItemFactory); + } + + return workItemFactories; + } + + private IEnumerable GetSelectedFactories(List source, string selectedItems) + { + var items = selectedItems.Split(new char[] { ',', ';' }); + + if (items == null && !items.Any()) + return null; + + items = items.Select(f => f.Trim()).ToArray(); + + return source.Where(p => items.Contains(p.Name, StringComparer.OrdinalIgnoreCase)); + } + + private List InitializeProviderFactories(ProviderKey key, IEnumerable providerCollection) + { + return InitializeProviderFactories(key, providerCollection, null); + } + + private List InitializeProviderFactories(ProviderKey key, IEnumerable providerCollection, ProviderFactoryInfo loadedFactory) + { + var loadedFactoryPassedIn = false; + + if(loadedFactory != null && !string.IsNullOrEmpty(loadedFactory.Name)) + loadedFactoryPassedIn = true; + + var factories = new List(); + + if (providerCollection == null || !providerCollection.Any()) + { + return factories; + } + + foreach (var provider in providerCollection) + { + if (loadedFactoryPassedIn) + { + if (loadedFactory.Name.Equals(provider.Name, StringComparison.OrdinalIgnoreCase)) + { + factories.Add(loadedFactory); + continue; + } + } + + factories.Add(new ProviderFactoryInfo(key, provider.Name, ValidateProviderType(provider.Type))); + } + + return factories; + } + + /// + /// Validates the type of the provider, needn't validate in default mode, because it will be validate later when initializing. + /// + /// Name of the type. + /// + protected virtual string ValidateProviderType(string typeName) + { + return typeName; + } + + /// + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + /// + public virtual void Dispose() + { + + } + } +} diff --git a/SocketService/InstallService.bat b/SocketService/InstallService.bat new file mode 100644 index 000000000..50530656e --- /dev/null +++ b/SocketService/InstallService.bat @@ -0,0 +1,2 @@ +SuperSocket.SocketService.exe -i +pause \ No newline at end of file diff --git a/SocketService/MainService.Designer.cs b/SocketService/MainService.Designer.cs new file mode 100644 index 000000000..c5833a513 --- /dev/null +++ b/SocketService/MainService.Designer.cs @@ -0,0 +1,38 @@ +using System.Configuration; +namespace SuperSocket.SocketService +{ + partial class MainService + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Component Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + this.ServiceName = ConfigurationManager.AppSettings["ServiceName"]; + } + + #endregion + } +} diff --git a/SocketService/MainService.cs b/SocketService/MainService.cs new file mode 100644 index 000000000..6aa1581a3 --- /dev/null +++ b/SocketService/MainService.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Configuration; +using System.Diagnostics; +using System.ServiceProcess; +using System.Text; +using SuperSocket.Common; +using SuperSocket.SocketBase; +using SuperSocket.SocketEngine; +using SuperSocket.SocketEngine.Configuration; + +namespace SuperSocket.SocketService +{ + partial class MainService : ServiceBase + { + private IBootstrap m_Bootstrap; + + public MainService() + { + InitializeComponent(); + m_Bootstrap = BootstrapFactory.CreateBootstrap(); + } + + protected override void OnStart(string[] args) + { + if (!m_Bootstrap.Initialize()) + return; + + m_Bootstrap.Start(); + } + + protected override void OnStop() + { + m_Bootstrap.Stop(); + base.OnStop(); + } + + protected override void OnShutdown() + { + m_Bootstrap.Stop(); + base.OnShutdown(); + } + } +} diff --git a/SocketService/Program.cs b/SocketService/Program.cs new file mode 100644 index 000000000..b020e9c0d --- /dev/null +++ b/SocketService/Program.cs @@ -0,0 +1,116 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.IO; +using System.ServiceProcess; +using System.Text; +using System.Reflection; +using SuperSocket.Common; +using SuperSocket.SocketBase; +using SuperSocket.SocketEngine; +using SuperSocket.SocketEngine.Configuration; + + +namespace SuperSocket.SocketService +{ + static partial class Program + { + /// + /// The main entry point for the application. + /// + static void Main(string[] args) + { + if ((!Platform.IsMono && !Environment.UserInteractive)//Windows Service + || (Platform.IsMono && !AppDomain.CurrentDomain.FriendlyName.Equals(Path.GetFileName(Assembly.GetEntryAssembly().CodeBase))))//MonoService + { + RunAsService(); + return; + } + + if (args != null && args.Length > 0) + { + if (args[0].Equals("-i", StringComparison.OrdinalIgnoreCase)) + { + SelfInstaller.InstallMe(); + return; + } + else if (args[0].Equals("-u", StringComparison.OrdinalIgnoreCase)) + { + SelfInstaller.UninstallMe(); + return; + } + + Console.WriteLine("Invalid argument!"); + return; + } + + Console.WriteLine("Press any key to start the SuperSocket Server Engine!"); + Console.ReadKey(); + Console.WriteLine(); + RunAsConsole(); + Console.ReadKey(); + } + + static void RunAsConsole() + { + IBootstrap bootstrap = BootstrapFactory.CreateBootstrap(); + + if (!bootstrap.Initialize()) + { + Console.WriteLine("Failed to initialize SuperSocket server! Please check error log for more information!"); + return; + } + + var result = bootstrap.Start(); + + foreach (var server in bootstrap.AppServers) + { + if (server.IsRunning) + Console.WriteLine("- {0} has been started", server.Name); + else + Console.WriteLine("- {0} failed to start", server.Name); + } + + switch(result) + { + case(StartResult.None): + Console.WriteLine("No server is configured, please check you configuration!"); + break; + + case(StartResult.Success): + Console.WriteLine("The server engine has been started!"); + break; + + case (StartResult.Failed): + Console.WriteLine("Failed to start the server engine! Please check error log for more information!"); + break; + + case (StartResult.PartialSuccess): + Console.WriteLine("Some server instances were started successfully, but the others failed to start! Please check error log for more information!"); + break; + } + + Console.WriteLine("Press key 'q' to stop the server engine."); + + while (Console.ReadKey().Key != ConsoleKey.Q) + { + Console.WriteLine(); + continue; + } + + bootstrap.Stop(); + + Console.WriteLine(); + Console.WriteLine("The server engine has been stopped!"); + } + + static void RunAsService() + { + ServiceBase[] servicesToRun; + + servicesToRun = new ServiceBase[] { new MainService() }; + + ServiceBase.Run(servicesToRun); + } + } +} \ No newline at end of file diff --git a/SocketService/Properties/AssemblyInfo.cs b/SocketService/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..41994447c --- /dev/null +++ b/SocketService/Properties/AssemblyInfo.cs @@ -0,0 +1,17 @@ +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("SuperSocket.SocketService")] +[assembly: AssemblyDescription("SuperSocket.SocketService")] +[assembly: AssemblyConfiguration("")] +// 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)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("641eff4a-4a63-482a-bc40-7d34e2fb4b26")] diff --git a/SocketService/RunServer.bat b/SocketService/RunServer.bat new file mode 100644 index 000000000..8099737ec --- /dev/null +++ b/SocketService/RunServer.bat @@ -0,0 +1,2 @@ +SuperSocket.SocketService.exe -c +pause \ No newline at end of file diff --git a/SocketService/SelfInstaller.cs b/SocketService/SelfInstaller.cs new file mode 100644 index 000000000..d85811750 --- /dev/null +++ b/SocketService/SelfInstaller.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Configuration.Install; +using System.Linq; +using System.Reflection; +using System.Text; + +namespace SuperSocket.SocketService +{ + public static class SelfInstaller + { + private static readonly string _exePath = Assembly.GetExecutingAssembly().Location; + + public static bool InstallMe() + { + try + { + ManagedInstallerClass.InstallHelper(new string[] { _exePath }); + } + catch + { + return false; + } + return true; + } + + public static bool UninstallMe() + { + try + { + ManagedInstallerClass.InstallHelper(new string[] { "/u", _exePath }); + } + catch + { + return false; + } + return true; + } + } +} diff --git a/SocketService/SocketServiceInstaller.Designer.cs b/SocketService/SocketServiceInstaller.Designer.cs new file mode 100644 index 000000000..435bb011c --- /dev/null +++ b/SocketService/SocketServiceInstaller.Designer.cs @@ -0,0 +1,36 @@ +namespace SuperSocket.SocketService +{ + partial class SocketServiceInstaller + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Component Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + } + + #endregion + } +} \ No newline at end of file diff --git a/SocketService/SocketServiceInstaller.cs b/SocketService/SocketServiceInstaller.cs new file mode 100644 index 000000000..7ed6d48bc --- /dev/null +++ b/SocketService/SocketServiceInstaller.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Configuration; +using System.Configuration.Install; +using System.ServiceProcess; + +namespace SuperSocket.SocketService +{ + [RunInstaller(true)] + public partial class SocketServiceInstaller : Installer + { + private ServiceInstaller serviceInstaller; + private ServiceProcessInstaller processInstaller; + + public SocketServiceInstaller() + { + InitializeComponent(); + + processInstaller = new ServiceProcessInstaller(); + serviceInstaller = new ServiceInstaller(); + + processInstaller.Account = ServiceAccount.LocalSystem; + serviceInstaller.StartType = ServiceStartMode.Automatic; + serviceInstaller.ServiceName = ConfigurationManager.AppSettings["ServiceName"]; + + var serviceDescription = ConfigurationManager.AppSettings["ServiceDescription"]; + if (!string.IsNullOrEmpty(serviceDescription)) + serviceInstaller.Description = serviceDescription; + + var servicesDependedOn = new List { "tcpip" }; + var servicesDependedOnConfig = ConfigurationManager.AppSettings["ServicesDependedOn"]; + + if (!string.IsNullOrEmpty(servicesDependedOnConfig)) + servicesDependedOn.AddRange(servicesDependedOnConfig.Split(new char[] { ',', ';' })); + + serviceInstaller.ServicesDependedOn = servicesDependedOn.ToArray(); + + Installers.Add(serviceInstaller); + Installers.Add(processInstaller); + } + } +} \ No newline at end of file diff --git a/SocketService/SuperSocket.SocketService.Net35.csproj b/SocketService/SuperSocket.SocketService.Net35.csproj new file mode 100644 index 000000000..88b7c185d --- /dev/null +++ b/SocketService/SuperSocket.SocketService.Net35.csproj @@ -0,0 +1,165 @@ + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {B9113694-7226-4152-938D-3172B11571A1} + Exe + Properties + SuperSocket.SocketService + SuperSocket.SocketService + + + 3.5 + + + v3.5 + + + false + + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + true + AnyCPU + AllRules.ruleset + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + AllRules.ruleset + + + OnBuildSuccess + + + true + + + ..\supersocket.snk + + + + + + + 3.5 + + + + + + + + + GlobalAssemblyInfo.cs + + + Component + + + MainService.cs + + + + + + Component + + + SocketServiceInstaller.cs + + + + + PreserveNewest + + + PreserveNewest + + + + + False + .NET Framework 3.5 SP1 Client Profile + false + + + False + .NET Framework 3.5 SP1 + false + + + False + Windows Installer 3.1 + true + + + + + Config\log4net.config + PreserveNewest + + + App.config + + + + + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A} + SuperSocket.Common.Net35 + + + {40B77789-EA11-4C05-8F52-86711D7BCAAF} + SuperSocket.SocketBase.Net35 + + + {153FEF72-191C-43D9-BE71-2B351C7AC760} + SuperSocket.SocketEngine.Net35 + + + + + + + + + + + + + + \ No newline at end of file diff --git a/SocketService/SuperSocket.SocketService.csproj b/SocketService/SuperSocket.SocketService.csproj new file mode 100644 index 000000000..0821ba259 --- /dev/null +++ b/SocketService/SuperSocket.SocketService.csproj @@ -0,0 +1,164 @@ + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {B9113694-7226-4152-938D-3172B11571A1} + Exe + Properties + SuperSocket.SocketService + SuperSocket.SocketService + + + 3.5 + + + v4.0 + + + false + + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + true + AnyCPU + AllRules.ruleset + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + AllRules.ruleset + + + true + + + ..\supersocket.snk + + + + + + + 3.5 + + + + + + + + GlobalAssemblyInfo.cs + + + Component + + + MainService.cs + + + + + + Component + + + SocketServiceInstaller.cs + + + + + PreserveNewest + + + PreserveNewest + + + + + False + Microsoft .NET Framework 4 %28x86 and x64%29 + true + + + False + .NET Framework 3.5 SP1 Client Profile + false + + + False + .NET Framework 3.5 SP1 + false + + + False + Windows Installer 3.1 + true + + + + + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A} + SuperSocket.Common + + + {40B77789-EA11-4C05-8F52-86711D7BCAAF} + SuperSocket.SocketBase + + + {153FEF72-191C-43D9-BE71-2B351C7AC760} + SuperSocket.SocketEngine + + + + + Config\log4net.config + PreserveNewest + + + Config\log4net.unix.config + PreserveNewest + Designer + + + App.config + Designer + + + + + + \ No newline at end of file diff --git a/SocketService/UninstallService.bat b/SocketService/UninstallService.bat new file mode 100644 index 000000000..9948b8064 --- /dev/null +++ b/SocketService/UninstallService.bat @@ -0,0 +1,2 @@ +SuperSocket.SocketService.exe -u +pause \ No newline at end of file diff --git a/Solution Items/GlobalAssemblyInfo.cs b/Solution Items/GlobalAssemblyInfo.cs new file mode 100644 index 000000000..289085539 --- /dev/null +++ b/Solution Items/GlobalAssemblyInfo.cs @@ -0,0 +1,18 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +[assembly: AssemblyVersion("1.5.0.4")] +[assembly: AssemblyFileVersion("1.5.0.4")] +[assembly: AssemblyCompany("SuperSocket")] +[assembly: AssemblyProduct("SuperSocket")] +[assembly: AssemblyInformationalVersion("1.5.0.4")] +[assembly: AssemblyCopyright("Copyright © supersocket.codeplex.com 2012")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] \ No newline at end of file diff --git a/Solution Items/Net35/App.config b/Solution Items/Net35/App.config new file mode 100644 index 000000000..5eef8b0dd --- /dev/null +++ b/Solution Items/Net35/App.config @@ -0,0 +1,25 @@ + + + +
+ + + + + + + + + + + + + + + + + + diff --git a/Solution Items/Net40/App.Dynamic.config b/Solution Items/Net40/App.Dynamic.config new file mode 100644 index 000000000..0b68cf9d8 --- /dev/null +++ b/Solution Items/Net40/App.Dynamic.config @@ -0,0 +1,35 @@ + + + +
+
+ + + + + + + + + + + + + + + + + + + + + + + diff --git a/Solution Items/Net40/App.config b/Solution Items/Net40/App.config new file mode 100644 index 000000000..013ef0d69 --- /dev/null +++ b/Solution Items/Net40/App.config @@ -0,0 +1,24 @@ + + + +
+ + + + + + + + + + + + + + + + + diff --git a/Solution Items/log4net.config b/Solution Items/log4net.config new file mode 100644 index 000000000..a5dbce412 --- /dev/null +++ b/Solution Items/log4net.config @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Solution Items/log4net.unix.config b/Solution Items/log4net.unix.config new file mode 100644 index 000000000..bfc88c44b --- /dev/null +++ b/Solution Items/log4net.unix.config @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/SuperSocket.2008.sln b/SuperSocket.2008.sln new file mode 100644 index 000000000..060e1c816 --- /dev/null +++ b/SuperSocket.2008.sln @@ -0,0 +1,44 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocket.SocketService.Net35", "SocketService\SuperSocket.SocketService.Net35.csproj", "{B9113694-7226-4152-938D-3172B11571A1}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocket.Common.Net35", "Common\SuperSocket.Common.Net35.csproj", "{A24F4D38-BA9C-4FD6-95B7-4980DE36131A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocket.SocketBase.Net35", "SocketBase\SuperSocket.SocketBase.Net35.csproj", "{40B77789-EA11-4C05-8F52-86711D7BCAAF}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocket.SocketEngine.Net35", "SocketEngine\SuperSocket.SocketEngine.Net35.csproj", "{153FEF72-191C-43D9-BE71-2B351C7AC760}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocket.Test.NET35", "Test\SuperSocket.Test.NET35.csproj", "{BDBB6CE9-C3CE-49C1-A05E-2D7628430A02}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B9113694-7226-4152-938D-3172B11571A1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B9113694-7226-4152-938D-3172B11571A1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B9113694-7226-4152-938D-3172B11571A1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B9113694-7226-4152-938D-3172B11571A1}.Release|Any CPU.Build.0 = Release|Any CPU + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A}.Release|Any CPU.Build.0 = Release|Any CPU + {40B77789-EA11-4C05-8F52-86711D7BCAAF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {40B77789-EA11-4C05-8F52-86711D7BCAAF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {40B77789-EA11-4C05-8F52-86711D7BCAAF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {40B77789-EA11-4C05-8F52-86711D7BCAAF}.Release|Any CPU.Build.0 = Release|Any CPU + {153FEF72-191C-43D9-BE71-2B351C7AC760}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {153FEF72-191C-43D9-BE71-2B351C7AC760}.Debug|Any CPU.Build.0 = Debug|Any CPU + {153FEF72-191C-43D9-BE71-2B351C7AC760}.Release|Any CPU.ActiveCfg = Release|Any CPU + {153FEF72-191C-43D9-BE71-2B351C7AC760}.Release|Any CPU.Build.0 = Release|Any CPU + {BDBB6CE9-C3CE-49C1-A05E-2D7628430A02}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BDBB6CE9-C3CE-49C1-A05E-2D7628430A02}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BDBB6CE9-C3CE-49C1-A05E-2D7628430A02}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BDBB6CE9-C3CE-49C1-A05E-2D7628430A02}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/SuperSocket.2010.NET35.sln b/SuperSocket.2010.NET35.sln new file mode 100644 index 000000000..6427b3fc3 --- /dev/null +++ b/SuperSocket.2010.NET35.sln @@ -0,0 +1,77 @@ + +Microsoft Visual Studio Solution File, Format Version 11.00 +# Visual Studio 2010 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocket.SocketService.Net35", "SocketService\SuperSocket.SocketService.Net35.csproj", "{B9113694-7226-4152-938D-3172B11571A1}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocket.Common.Net35", "Common\SuperSocket.Common.Net35.csproj", "{A24F4D38-BA9C-4FD6-95B7-4980DE36131A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocket.SocketBase.Net35", "SocketBase\SuperSocket.SocketBase.Net35.csproj", "{40B77789-EA11-4C05-8F52-86711D7BCAAF}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocket.SocketEngine.Net35", "SocketEngine\SuperSocket.SocketEngine.Net35.csproj", "{153FEF72-191C-43D9-BE71-2B351C7AC760}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocket.Test.NET35", "Test\SuperSocket.Test.NET35.csproj", "{BDBB6CE9-C3CE-49C1-A05E-2D7628430A02}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{310FD673-1D6B-41B3-9BFF-8E0F984B524C}" + ProjectSection(SolutionItems) = preProject + Solution Items\GlobalAssemblyInfo.cs = Solution Items\GlobalAssemblyInfo.cs + Solution Items\log4net.config = Solution Items\log4net.config + Solution Items\log4net.unix.config = Solution Items\log4net.unix.config + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Net40", "Net40", "{09AA86CA-0CF7-48CE-891C-F64BFD544AD4}" + ProjectSection(SolutionItems) = preProject + Solution Items\Net40\App.config = Solution Items\Net40\App.config + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Net35", "Net35", "{0E2D03FA-3792-4F50-9CA4-77E4C4598746}" + ProjectSection(SolutionItems) = preProject + Solution Items\Net35\App.config = Solution Items\Net35\App.config + EndProjectSection +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocket.Facility.Net35", "Facility\SuperSocket.Facility.Net35.csproj", "{01987BAC-C498-44DD-B274-62EA2506B51D}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocket.Dlr.Net35", "Dlr\SuperSocket.Dlr.Net35.csproj", "{55BAA051-CE62-4D4A-81B6-68B042CC78E9}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B9113694-7226-4152-938D-3172B11571A1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B9113694-7226-4152-938D-3172B11571A1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B9113694-7226-4152-938D-3172B11571A1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B9113694-7226-4152-938D-3172B11571A1}.Release|Any CPU.Build.0 = Release|Any CPU + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A}.Release|Any CPU.Build.0 = Release|Any CPU + {40B77789-EA11-4C05-8F52-86711D7BCAAF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {40B77789-EA11-4C05-8F52-86711D7BCAAF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {40B77789-EA11-4C05-8F52-86711D7BCAAF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {40B77789-EA11-4C05-8F52-86711D7BCAAF}.Release|Any CPU.Build.0 = Release|Any CPU + {153FEF72-191C-43D9-BE71-2B351C7AC760}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {153FEF72-191C-43D9-BE71-2B351C7AC760}.Debug|Any CPU.Build.0 = Debug|Any CPU + {153FEF72-191C-43D9-BE71-2B351C7AC760}.Release|Any CPU.ActiveCfg = Release|Any CPU + {153FEF72-191C-43D9-BE71-2B351C7AC760}.Release|Any CPU.Build.0 = Release|Any CPU + {BDBB6CE9-C3CE-49C1-A05E-2D7628430A02}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BDBB6CE9-C3CE-49C1-A05E-2D7628430A02}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BDBB6CE9-C3CE-49C1-A05E-2D7628430A02}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BDBB6CE9-C3CE-49C1-A05E-2D7628430A02}.Release|Any CPU.Build.0 = Release|Any CPU + {01987BAC-C498-44DD-B274-62EA2506B51D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {01987BAC-C498-44DD-B274-62EA2506B51D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {01987BAC-C498-44DD-B274-62EA2506B51D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {01987BAC-C498-44DD-B274-62EA2506B51D}.Release|Any CPU.Build.0 = Release|Any CPU + {55BAA051-CE62-4D4A-81B6-68B042CC78E9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {55BAA051-CE62-4D4A-81B6-68B042CC78E9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {55BAA051-CE62-4D4A-81B6-68B042CC78E9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {55BAA051-CE62-4D4A-81B6-68B042CC78E9}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {09AA86CA-0CF7-48CE-891C-F64BFD544AD4} = {310FD673-1D6B-41B3-9BFF-8E0F984B524C} + {0E2D03FA-3792-4F50-9CA4-77E4C4598746} = {310FD673-1D6B-41B3-9BFF-8E0F984B524C} + EndGlobalSection +EndGlobal diff --git a/SuperSocket.2010.sln b/SuperSocket.2010.sln new file mode 100644 index 000000000..f0a9e1e6a --- /dev/null +++ b/SuperSocket.2010.sln @@ -0,0 +1,77 @@ + +Microsoft Visual Studio Solution File, Format Version 11.00 +# Visual Studio 2010 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocket.SocketService", "SocketService\SuperSocket.SocketService.csproj", "{B9113694-7226-4152-938D-3172B11571A1}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocket.Common", "Common\SuperSocket.Common.csproj", "{A24F4D38-BA9C-4FD6-95B7-4980DE36131A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocket.Test", "Test\SuperSocket.Test.csproj", "{BDBB6CE9-C3CE-49C1-A05E-2D7628430A02}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocket.SocketBase", "SocketBase\SuperSocket.SocketBase.csproj", "{40B77789-EA11-4C05-8F52-86711D7BCAAF}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocket.SocketEngine", "SocketEngine\SuperSocket.SocketEngine.csproj", "{153FEF72-191C-43D9-BE71-2B351C7AC760}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{BEAF6CBD-16DD-456B-A889-421E0DFAB783}" + ProjectSection(SolutionItems) = preProject + Solution Items\GlobalAssemblyInfo.cs = Solution Items\GlobalAssemblyInfo.cs + Solution Items\log4net.config = Solution Items\log4net.config + Solution Items\log4net.unix.config = Solution Items\log4net.unix.config + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Net35", "Net35", "{FC181BA8-9DE5-444C-899F-9C554BC65629}" + ProjectSection(SolutionItems) = preProject + Solution Items\Net35\App.config = Solution Items\Net35\App.config + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Net40", "Net40", "{ACCCC9EB-6386-44DC-8147-D69751FC6D93}" + ProjectSection(SolutionItems) = preProject + Solution Items\Net40\App.config = Solution Items\Net40\App.config + EndProjectSection +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocket.Facility", "Facility\SuperSocket.Facility.csproj", "{01987BAC-C498-44DD-B274-62EA2506B51D}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocket.Dlr", "Dlr\SuperSocket.Dlr.csproj", "{55BAA051-CE62-4D4A-81B6-68B042CC78E9}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {B9113694-7226-4152-938D-3172B11571A1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B9113694-7226-4152-938D-3172B11571A1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B9113694-7226-4152-938D-3172B11571A1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B9113694-7226-4152-938D-3172B11571A1}.Release|Any CPU.Build.0 = Release|Any CPU + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A}.Release|Any CPU.Build.0 = Release|Any CPU + {BDBB6CE9-C3CE-49C1-A05E-2D7628430A02}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BDBB6CE9-C3CE-49C1-A05E-2D7628430A02}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BDBB6CE9-C3CE-49C1-A05E-2D7628430A02}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BDBB6CE9-C3CE-49C1-A05E-2D7628430A02}.Release|Any CPU.Build.0 = Release|Any CPU + {40B77789-EA11-4C05-8F52-86711D7BCAAF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {40B77789-EA11-4C05-8F52-86711D7BCAAF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {40B77789-EA11-4C05-8F52-86711D7BCAAF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {40B77789-EA11-4C05-8F52-86711D7BCAAF}.Release|Any CPU.Build.0 = Release|Any CPU + {153FEF72-191C-43D9-BE71-2B351C7AC760}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {153FEF72-191C-43D9-BE71-2B351C7AC760}.Debug|Any CPU.Build.0 = Debug|Any CPU + {153FEF72-191C-43D9-BE71-2B351C7AC760}.Release|Any CPU.ActiveCfg = Release|Any CPU + {153FEF72-191C-43D9-BE71-2B351C7AC760}.Release|Any CPU.Build.0 = Release|Any CPU + {01987BAC-C498-44DD-B274-62EA2506B51D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {01987BAC-C498-44DD-B274-62EA2506B51D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {01987BAC-C498-44DD-B274-62EA2506B51D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {01987BAC-C498-44DD-B274-62EA2506B51D}.Release|Any CPU.Build.0 = Release|Any CPU + {55BAA051-CE62-4D4A-81B6-68B042CC78E9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {55BAA051-CE62-4D4A-81B6-68B042CC78E9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {55BAA051-CE62-4D4A-81B6-68B042CC78E9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {55BAA051-CE62-4D4A-81B6-68B042CC78E9}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {FC181BA8-9DE5-444C-899F-9C554BC65629} = {BEAF6CBD-16DD-456B-A889-421E0DFAB783} + {ACCCC9EB-6386-44DC-8147-D69751FC6D93} = {BEAF6CBD-16DD-456B-A889-421E0DFAB783} + EndGlobalSection +EndGlobal diff --git a/Test/AppDomainSocketServerTest.cs b/Test/AppDomainSocketServerTest.cs new file mode 100644 index 000000000..fb8ab3540 --- /dev/null +++ b/Test/AppDomainSocketServerTest.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.InteropServices; +using System.Text; +using NUnit.Framework; +using SuperSocket.Common; +using SuperSocket.SocketBase.Logging; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Config; +using SuperSocket.SocketBase.Provider; +using SuperSocket.SocketEngine; + + +namespace SuperSocket.Test +{ + [TestFixture] + public class AppDomainSocketServerTest : TcpSocketServerTest + { + protected override IWorkItem CreateAppServer(IRootConfig rootConfig, IServerConfig serverConfig) + { + var appServer = new AppDomainAppServer(typeof(T)); + + var config = new ConfigurationSource(); + rootConfig.CopyPropertiesTo(config); + + appServer.Setup(new AppDomainBootstrap(config), serverConfig, new ProviderFactoryInfo[] + { + new ProviderFactoryInfo(ProviderKey.SocketServerFactory, ProviderKey.SocketServerFactory.Name, typeof(SocketServerFactory)), + new ProviderFactoryInfo(ProviderKey.LogFactory, ProviderKey.LogFactory.Name, typeof(ConsoleLogFactory)) + }); + + return appServer; + } + + [Test] + public void TestAppDomain() + { + StartServer(); + + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port); + + using (Socket socket = CreateClientSocket()) + { + socket.Connect(serverAddress); + Stream socketStream = GetSocketStream(socket); + using (StreamReader reader = new StreamReader(socketStream, m_Encoding, true)) + using (StreamWriter writer = new StreamWriter(socketStream, m_Encoding, 1024 * 8)) + { + string welcomeString = reader.ReadLine(); + + Console.WriteLine("Welcome: " + welcomeString); + + writer.WriteLine("DOMAIN"); + writer.Flush(); + + var line = reader.ReadLine(); + + Assert.AreEqual(m_Config.Name, line); + } + } + } + } +} diff --git a/Test/BootstrapTest.cs b/Test/BootstrapTest.cs new file mode 100644 index 000000000..86875e950 --- /dev/null +++ b/Test/BootstrapTest.cs @@ -0,0 +1,217 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text; +using NUnit.Framework; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Config; +using SuperSocket.SocketEngine; + +namespace SuperSocket.Test +{ + [TestFixture] + public class BootstrapTest + { + private IBootstrap m_BootStrap; + + private Encoding m_Encoding = new UTF8Encoding(); + + [TearDown] + public void ClearBootstrap() + { + if(m_BootStrap != null) + { + m_BootStrap.Stop(); + m_BootStrap = null; + } + } + + private IConfigurationSource SetupBootstrap(string configFile) + { + ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap(); + fileMap.ExeConfigFilename = Path.Combine(@"Config", configFile); + + var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); + var configSource = config.GetSection("socketServer") as IConfigurationSource; + + m_BootStrap = BootstrapFactory.CreateBootstrap(configSource); + + Assert.IsTrue(m_BootStrap.Initialize()); + + var result = m_BootStrap.Start(); + + Assert.AreEqual(StartResult.Success, result); + + return configSource; + } + + [Test] + public void TestBasicConfig() + { + TestBasicConfig("Basic.config"); + } + + private void TestBasicConfig(string configFile) + { + var configSource = SetupBootstrap(configFile); + + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), configSource.Servers.FirstOrDefault().Port); + + using (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) + { + socket.Connect(serverAddress); + Stream socketStream = new NetworkStream(socket); + using (StreamReader reader = new StreamReader(socketStream, m_Encoding, true)) + using (StreamWriter writer = new StreamWriter(socketStream, m_Encoding, 1024 * 8)) + { + reader.ReadLine(); + + for (var i = 0; i < 10; i++) + { + var message = Guid.NewGuid().ToString(); + writer.WriteLine("ECHO {0}", message); + writer.Flush(); + Assert.AreEqual(message, reader.ReadLine()); + } + } + } + } + + [Test] + public void TestServerTypeConfig() + { + TestBasicConfig("ServerType.config"); + } + + + [Test] + public void TestListenersConfig() + { + var configSource = SetupBootstrap("Listeners.config"); + + var serverConfig = configSource.Servers.FirstOrDefault(); + + foreach (var listener in serverConfig.Listeners) + { + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), listener.Port); + + using (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) + { + socket.Connect(serverAddress); + Stream socketStream = new NetworkStream(socket); + using (StreamReader reader = new StreamReader(socketStream, m_Encoding, true)) + using (StreamWriter writer = new StreamWriter(socketStream, m_Encoding, 1024 * 8)) + { + reader.ReadLine(); + + for (var i = 0; i < 5; i++) + { + var message = Guid.NewGuid().ToString(); + writer.WriteLine("ECHO {0}", message); + writer.Flush(); + Assert.AreEqual(message, reader.ReadLine()); + } + } + } + } + } + + [Test] + public void TestAppDomainConfig() + { + var configSource = SetupBootstrap("AppDomain.config"); + + var serverConfig = configSource.Servers.FirstOrDefault(); + + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), serverConfig.Port); + + using (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) + { + socket.Connect(serverAddress); + Stream socketStream = new NetworkStream(socket); + using (StreamReader reader = new StreamReader(socketStream, m_Encoding, true)) + using (StreamWriter writer = new StreamWriter(socketStream, m_Encoding, 1024 * 8)) + { + reader.ReadLine(); + + writer.WriteLine("DOMAIN"); + writer.Flush(); + Assert.AreEqual(serverConfig.Name, reader.ReadLine()); + } + } + } + + [Test] + public void TestDLRConfig() + { + var configSource = SetupBootstrap("DLR.config"); + + var serverConfig = configSource.Servers.FirstOrDefault(); + + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), serverConfig.Port); + + using (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) + { + socket.Connect(serverAddress); + Stream socketStream = new NetworkStream(socket); + using (StreamReader reader = new StreamReader(socketStream, m_Encoding, true)) + using (StreamWriter writer = new StreamWriter(socketStream, m_Encoding, 1024 * 8)) + { + reader.ReadLine(); + + Random rd = new Random(); + + for (int i = 0; i < 5; i++) + { + int x = rd.Next(1, 1000), y = rd.Next(1, 1000); + string command = string.Format("{0} {1} {2}", "ADD", x, y); + Console.WriteLine(command); + writer.WriteLine(command); + writer.Flush(); + string line = reader.ReadLine(); + Console.WriteLine(line); + Assert.AreEqual(x + y, int.Parse(line)); + } + + for (int i = 0; i < 5; i++) + { + int x = rd.Next(1, 1000), y = rd.Next(1, 1000); + string command = string.Format("{0} {1} {2}", "MULT", x, y); + Console.WriteLine(command); + writer.WriteLine(command); + writer.Flush(); + string line = reader.ReadLine(); + Console.WriteLine(line); + Assert.AreEqual(x * y, int.Parse(line)); + } + } + } + } + + + [Test] + public void TestCustomChildConfig() + { + SetupBootstrap("ChildConfigA.config"); + Assert.AreEqual(168, ChildConfigTestServer.ChildConfigValue); + ClearBootstrap(); + + SetupBootstrap("ChildConfigB.config"); + Assert.AreEqual(192, ChildConfigTestServer.ChildConfigValue); + ClearBootstrap(); + + SetupBootstrap("ChildConfigC.config"); + Assert.AreEqual(200, ChildConfigTestServer.ChildConfigValue); + ClearBootstrap(); + + SetupBootstrap("ChildConfigD.config"); + Assert.AreEqual(8848, ChildrenConfigTestServer.ChildConfigGlobalValue); + Assert.AreEqual(10 + 20 + 30, ChildrenConfigTestServer.ChildConfigValueSum); + Assert.AreEqual(10 * 20 * 30, ChildrenConfigTestServer.ChildConfigValueMultiplyProduct); + } + } +} diff --git a/Test/ChildConfigTestServer.cs b/Test/ChildConfigTestServer.cs new file mode 100644 index 000000000..172896b11 --- /dev/null +++ b/Test/ChildConfigTestServer.cs @@ -0,0 +1,52 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Config; +using SuperSocket.Test.Config; + +namespace SuperSocket.Test +{ + public class ChildConfigTestServer : AppServer + { + protected override bool Setup(IRootConfig rootConfig, IServerConfig config) + { + var childConfig = config.GetChildConfig("child"); + ChildConfigValue = childConfig.Value; + return true; + } + + public static int ChildConfigValue { get; private set; } + } + + public class ChildrenConfigTestServer : AppServer + { + protected override bool Setup(IRootConfig rootConfig, IServerConfig config) + { + var childrenConfig = config.GetChildConfig("children"); + + ChildConfigGlobalValue = childrenConfig.GlobalValue; + + var sum = 0; + var pro = 1; + + foreach (var c in childrenConfig.OfType()) + { + sum += c.Value; + pro *= c.Value; + } + + ChildConfigValueSum = sum; + ChildConfigValueMultiplyProduct = pro; + + return true; + } + + public static int ChildConfigValueSum { get; private set; } + + public static int ChildConfigValueMultiplyProduct { get; private set; } + + public static int ChildConfigGlobalValue { get; private set; } + } +} diff --git a/Test/Command/ADD.py b/Test/Command/ADD.py new file mode 100644 index 000000000..95f7cd139 --- /dev/null +++ b/Test/Command/ADD.py @@ -0,0 +1,7 @@ +import clr +clr.AddReference("System") + +from System import * + +def execute(session, request): + session.Send((Convert.ToInt32(request[0]) + Convert.ToInt32(request[1])).ToString()) \ No newline at end of file diff --git a/Test/Command/ADDCS.cs b/Test/Command/ADDCS.cs new file mode 100644 index 000000000..7928cea00 --- /dev/null +++ b/Test/Command/ADDCS.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.Test.Command +{ + public class ADDCS : StringCommandBase + { + public override void ExecuteCommand(TestSession session, StringRequestInfo requestInfo) + { + session.Send((Convert.ToInt32(requestInfo[0]) + Convert.ToInt32(requestInfo[1])).ToString()); + } + } +} diff --git a/Test/Command/DOMAIN.cs b/Test/Command/DOMAIN.cs new file mode 100644 index 000000000..804141757 --- /dev/null +++ b/Test/Command/DOMAIN.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.Test.Command +{ + public class DOMAIN : StringCommandBase + { + public override void ExecuteCommand(TestSession session, StringRequestInfo requestInfo) + { + session.Send(AppDomain.CurrentDomain.FriendlyName); + } + } +} diff --git a/Test/Command/ECHO.cs b/Test/Command/ECHO.cs new file mode 100644 index 000000000..6fe93de37 --- /dev/null +++ b/Test/Command/ECHO.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.Test.Command +{ + public class ECHO : StringCommandBase + { + public override void ExecuteCommand(TestSession session, StringRequestInfo commandData) + { + Console.WriteLine("R:" + commandData.Data); + session.Send(commandData.Data); + } + } +} diff --git a/Test/Command/MULT.py b/Test/Command/MULT.py new file mode 100644 index 000000000..943a9c41d --- /dev/null +++ b/Test/Command/MULT.py @@ -0,0 +1,7 @@ +import clr +clr.AddReference("System") + +from System import * + +def execute(session, request): + session.Send((Convert.ToInt32(request[0]) * Convert.ToInt32(request[1])).ToString()) \ No newline at end of file diff --git a/Test/Command/MULTCS.cs b/Test/Command/MULTCS.cs new file mode 100644 index 000000000..60a3b2a95 --- /dev/null +++ b/Test/Command/MULTCS.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.Test.Command +{ + public class MULTCS : StringCommandBase + { + public override void ExecuteCommand(TestSession session, StringRequestInfo requestInfo) + { + session.Send((Convert.ToInt32(requestInfo[0]) * Convert.ToInt32(requestInfo[1])).ToString()); + } + } +} diff --git a/Test/Command/NUM.cs b/Test/Command/NUM.cs new file mode 100644 index 000000000..7e2df824b --- /dev/null +++ b/Test/Command/NUM.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.Test.Command +{ + public class NUM : StringCommandBase + { + public const string ReplyFormat = "325 received {0}!"; + + public override void ExecuteCommand(TestSession session, StringRequestInfo commandData) + { + session.Send(string.Format(ReplyFormat, commandData.Data)); + } + + public override string Name + { + get + { + return "325"; + } + } + } +} diff --git a/Test/Command/PARA.cs b/Test/Command/PARA.cs new file mode 100644 index 000000000..b769057b5 --- /dev/null +++ b/Test/Command/PARA.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.Test.Command +{ + public class PARA : StringCommandBase + { + public override void ExecuteCommand(TestSession session, StringRequestInfo commandData) + { + foreach (var p in commandData.Parameters) + { + Console.WriteLine("S: " + p); + session.Send(p); + } + } + } +} diff --git a/Test/Command/SEND.cs b/Test/Command/SEND.cs new file mode 100644 index 000000000..3f12023c6 --- /dev/null +++ b/Test/Command/SEND.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Protocol; +using System.Threading.Tasks; +using System.IO; + +namespace SuperSocket.Test.Command +{ + public class SEND : StringCommandBase + { + public static string[] GetStringSource() + { + var filePath = Path.Combine(Path.GetDirectoryName(new Uri(typeof(SEND).Assembly.CodeBase).LocalPath), "Strings.txt"); + + var list = new List(); + + using (var reader = new StreamReader(filePath, Encoding.UTF8, true)) + { + while(true) + { + var line = reader.ReadLine(); + + if (string.IsNullOrEmpty(line)) + break; + + list.Add(line); + } + + reader.Close(); + } + + return list.ToArray(); + } + + public override void ExecuteCommand(TestSession session, StringRequestInfo commandData) + { + string[] source = GetStringSource(); + + Parallel.For(0, source.Length, (i) => + { + session.Send(source[i]); + }); + } + } +} diff --git a/Test/Common/ArraySegmentTest.cs b/Test/Common/ArraySegmentTest.cs new file mode 100644 index 000000000..bc945ef89 --- /dev/null +++ b/Test/Common/ArraySegmentTest.cs @@ -0,0 +1,420 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using NUnit.Framework; +using SuperSocket.Common; +using System.Diagnostics; + +namespace SuperSocket.Test.Common +{ + [TestFixture] + public class ArraySegmentTest + { + [Test] + public void TestCount() + { + ArraySegmentList source = new ArraySegmentList(); + + source.AddSegment("I love you,".ToCharArray(), 0, 5); + source.AddSegment("Hello world!".ToCharArray(), 0, 4); + + Assert.AreEqual(9, source.Count); + + source.RemoveSegmentAt(0); + Assert.AreEqual(4, source.Count); + + source.RemoveSegmentAt(0); + Assert.AreEqual(0, source.Count); + + source.AddSegment("I love you,".ToCharArray(), 0, 5); + source.AddSegment("Hello world!".ToCharArray(), 0, 4); + + Assert.AreEqual(9, source.Count); + } + + [Test] + public void TestOutOfIndex() + { + ArraySegmentList source = new ArraySegmentList(); + + source.AddSegment("I love you,".ToCharArray(), 0, 5); + source.AddSegment("Hello world!".ToCharArray(), 0, 4); + + char currentChar = ' '; + + Assert.Throws(delegate + { + currentChar = source[-1]; + }); + + Assert.Throws(delegate + { + currentChar = source[10]; + }); + + source.RemoveSegmentAt(0); + Assert.Throws(delegate + { + currentChar = source[4]; + }); + + source.RemoveSegmentAt(0); + Assert.Throws(delegate + { + currentChar = source[0]; + }); + + source.AddSegment("I love you,".ToCharArray(), 0, 5); + source.AddSegment("Hello world!".ToCharArray(), 0, 4); + + Assert.Throws(delegate + { + currentChar = source[10]; + }); + + Console.Write(currentChar); + } + + [Test] + public void TestIndexAccess() + { + ArraySegmentList source = new ArraySegmentList(); + + source.AddSegment("I love you,".ToCharArray(), 0, 5); + source.AddSegment("Hello world!".ToCharArray(), 0, 4); + + char[] exptected = "I lovHell".ToCharArray(); + + for (int i = source.Count - 1; i >= 0; i--) + { + Assert.AreEqual(exptected[i], source[i]); + } + + for (int i = 0; i < source.Count; i++) + { + Assert.AreEqual(exptected[i], source[i]); + } + + source.RemoveSegmentAt(0); + source.RemoveSegmentAt(0); + + source.AddSegment("I love you,".ToCharArray(), 0, 5); + source.AddSegment("Hello world!".ToCharArray(), 0, 4); + + for (int i = 0; i < source.Count; i++) + { + Assert.AreEqual(exptected[i], source[i], i + " is expected!"); + } + } + + [Test] + public void TestIndexAccess2() + { + ArraySegmentList sourceA = new ArraySegmentList(); + List sourceB = new List(); + + char[] element = null; + + for (var i = 0; i < 100; i++) + { + element = Guid.NewGuid().ToString().ToCharArray(); + sourceA.AddSegment(element, 0, element.Length); + sourceB.AddRange(element); + } + + Random rd = new Random(); + + for (int i = 0; i < 1000; i++) + { + int index = rd.Next(0, sourceA.Count - 1); + Assert.AreEqual(sourceB[index], sourceA[index]); + } + + int testCount = 10000; + + GC.Collect(); + + Stopwatch watch = new Stopwatch(); + + watch.Start(); + + char tt = ' '; + + for (var i = 0; i < testCount; i++) + { + int index = rd.Next(0, sourceA.Count - 1); + tt = sourceA[index]; + } + + watch.Stop(); + + Console.WriteLine(watch.ElapsedMilliseconds); + + watch.Reset(); + + GC.Collect(); + + watch.Start(); + + for (var i = 0; i < testCount; i++) + { + int index = rd.Next(0, sourceA.Count - 1); + tt = sourceB[index]; + } + + watch.Stop(); + + Console.WriteLine(watch.ElapsedMilliseconds); + Console.WriteLine(tt); + } + + [Test] + public void TestIndexOf() + { + ArraySegmentList source = new ArraySegmentList(); + + source.AddSegment("I love you,".ToCharArray(), 3, 7); + source.AddSegment("Hello world!".ToCharArray(), 0, 4); + + //string exptected = "ove youHell"; + Assert.AreEqual(-1, source.IndexOf('I')); + Assert.AreEqual(9, source.IndexOf('l')); + Assert.AreEqual(0, source.IndexOf('o')); + Assert.AreEqual(1, source.IndexOf('v')); + } + + [Test] + public void TestEndsWith() + { + ArraySegmentList source = new ArraySegmentList(); + + source.AddSegment("I love you,".ToCharArray(), 0, 5); + source.AddSegment("Hello world!".ToCharArray(), 0, 4); + + Assert.AreEqual(true, source.EndsWith("Hell".ToCharArray())); + } + + [Test] + public void TestToArray() + { + ArraySegmentList source = new ArraySegmentList(); + + source.AddSegment("I love you,".ToCharArray(), 0, 5); + source.AddSegment("Hello world!".ToCharArray(), 0, 4); + + char[] exptected = "I lovHell".ToCharArray(); + + Assert.AreEqual(exptected, source.ToArrayData()); + Assert.AreEqual("He", new string(source.ToArrayData(5, 2))); + Assert.AreEqual("ovHe", new string(source.ToArrayData(3, 4))); + } + + [Test] + public void TestRemoveSegment() + { + ArraySegmentList source = new ArraySegmentList(); + + source.AddSegment("I love you,".ToCharArray(), 0, 5); + source.AddSegment("Hello world!".ToCharArray(), 0, 4); + + Assert.AreEqual(9, source.Count); + Assert.AreEqual(2, source.SegmentCount); + + source.RemoveSegmentAt(1); + Assert.AreEqual(5, source.Count); + Assert.AreEqual(1, source.SegmentCount); + + char[] exptected = "I lov".ToCharArray(); + + for (var i = 0; i < exptected.Length; i++) + { + Assert.AreEqual(exptected[i], source[i]); + } + } + + [Test] + public void TestAddSegment() + { + ArraySegmentList source = new ArraySegmentList(); + + Assert.AreEqual(0, source.Count); + + source.AddSegment("I love you,".ToCharArray(), 0, 5); + Assert.AreEqual(5, source.Count); + Assert.AreEqual(1, source.SegmentCount); + + source.AddSegment("Hello world!".ToCharArray(), 0, 4); + Assert.AreEqual(9, source.Count); + Assert.AreEqual(2, source.SegmentCount); + + char[] exptected = "I lovHell".ToCharArray(); + + for (var i = 0; i < exptected.Length; i++) + { + Assert.AreEqual(exptected[i], source[i]); + } + } + + [Test] + public void TestSearchPerformance() + { + ArraySegmentList sourceA = new ArraySegmentList(); + List sourceB = new List(); + + char[] element = null; + + for (var i = 0; i < 100; i++) + { + element = Guid.NewGuid().ToString().ToCharArray(); + sourceA.AddSegment(element, 0, element.Length); + sourceB.AddRange(element); + } + + char[] mark = element.Take(4).ToArray(); + + int testCount = 1000; + + GC.Collect(); + + Stopwatch watch = new Stopwatch(); + + watch.Start(); + + for (var i = 0; i < testCount; i++) + { + sourceA.SearchMark(mark); + } + + watch.Stop(); + + Console.WriteLine(watch.ElapsedMilliseconds); + + watch.Reset(); + + GC.Collect(); + + watch.Start(); + + for (var i = 0; i < testCount; i++) + { + sourceB.SearchMark(mark); + } + + watch.Stop(); + + Console.WriteLine(watch.ElapsedMilliseconds); + } + + [Test, Repeat(10)] + public void TestDecode() + { + ArraySegmentList source = new ArraySegmentList(); + + StringBuilder sb = new StringBuilder(); + + List countArray = new List(); + + int from, to; + + Random rd = new Random(); + + from = rd.Next(0, 19); + to = rd.Next(from + 1, 20); + + for (var i = 0; i < 20; i++) + { + var line = Guid.NewGuid().ToString(); + var element = Encoding.UTF8.GetBytes(line); + + if (i >= from && i <= to) + { + countArray.Add(source.Count); + Console.WriteLine(source.Count); + sb.Append(line); + source.AddSegment(element, 0, element.Length); + countArray.Add(source.Count); + Console.WriteLine(source.Count); + } + else + { + source.AddSegment(element, 0, element.Length); + } + } + + Assert.AreEqual(sb.ToString(), source.Decode(Encoding.UTF8, countArray[0], countArray[countArray.Count - 1] - countArray[0])); + } + + [Test] + public void TestDecodeMaskPerformance() + { + ArraySegmentList source = new ArraySegmentList(); + + for (var i = 0; i < 100; i++) + { + var element = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString()); + source.AddSegment(element, 0, element.Length); + } + + byte[] mask = new byte[] { source[5], source[100], source[150], source[200] }; + + int testCount = 1000; + + GC.Collect(); + + Stopwatch watch = new Stopwatch(); + + watch.Start(); + + for (var i = 0; i < testCount; i++) + { + source.DecodeMask(mask, 100, source.Count - 100); + } + + watch.Stop(); + + Console.WriteLine(watch.ElapsedMilliseconds); + + watch.Reset(); + + GC.Collect(); + + watch.Start(); + + for (var i = 0; i < testCount; i++) + { + var data = source.ToArrayData(100, source.Count - 100); + DecodeMask(data, mask, 0, data.Length); + } + + watch.Stop(); + + Console.WriteLine(watch.ElapsedMilliseconds); + + watch.Reset(); + + GC.Collect(); + + watch.Start(); + + for (var i = 0; i < testCount; i++) + { + DecodeMask(source, mask, 100, source.Count - 100); + } + + watch.Stop(); + + Console.WriteLine(watch.ElapsedMilliseconds); + } + + private void DecodeMask(IList data, byte[] mask, int offset, int length) + { + var index = 0; + + for (var i = offset; i < length; i++) + { + data[i] = (byte)(data[i] ^ mask[index++ % 4]); + } + } + } +} diff --git a/Test/Common/AssemblyUtilTest.cs b/Test/Common/AssemblyUtilTest.cs new file mode 100644 index 000000000..bc686118f --- /dev/null +++ b/Test/Common/AssemblyUtilTest.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using NUnit.Framework; +using SuperSocket.SocketBase.Config; +using SuperSocket.Common; + +namespace SuperSocket.Test.Common +{ + [TestFixture] + public class AssemblyUtilTest + { + [Test] + public void TestCopyProperties() + { + var config = new ServerConfig(); + config.Name = "Kerry"; + config.Port = 21; + var newConfig = new ServerConfig(); + config.CopyPropertiesTo(newConfig); + + Assert.AreEqual(config.Name, newConfig.Name); + Assert.AreEqual(config.Port, newConfig.Port); + } + } +} diff --git a/Test/Common/BatchQueueTest.cs b/Test/Common/BatchQueueTest.cs new file mode 100644 index 000000000..efbd95fca --- /dev/null +++ b/Test/Common/BatchQueueTest.cs @@ -0,0 +1,206 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using NUnit.Framework; +using SuperSocket.Common; +using System.Threading; + +namespace SuperSocket.Test.Common +{ + [TestFixture] + public class BatchQueueTest + { + [Test, Repeat(100)] + public void TestFastEnqueue() + { + int count = 1000; + + var source = new string[count * 3]; + var output = new string[count * 3]; + + for (var i = 0; i < source.Length; i++) + { + source[i] = Guid.NewGuid().ToString(); + } + + IBatchQueue queue = new ConcurrentBatchQueue(output); + + Parallel.For(0, count, (i) => + { + var index = (int)i; + var sw = new SpinWait(); + + queue.Enqueue(source[index * 3]); + + sw.SpinOnce(); + sw.SpinOnce(); + sw.SpinOnce(); + sw.SpinOnce(); + + queue.Enqueue(source[index * 3 + 1]); + + sw.SpinOnce(); + sw.SpinOnce(); + sw.SpinOnce(); + sw.SpinOnce(); + + queue.Enqueue(source[index * 3 + 2]); + }); + + for (var i = 0; i < queue.Count; i++) + { + if (null == output[i]) + Assert.Fail(); + } + } + + [Test, Repeat(100)] + public void TestFastBatchEnqueue() + { + int count = 1000; + + var source = new string[count * 3]; + var output = new string[count * 3]; + + for (var i = 0; i < source.Length; i++) + { + source[i] = Guid.NewGuid().ToString(); + } + + IBatchQueue queue = new ConcurrentBatchQueue(output); + + Parallel.For(0, count, (i) => + { + var index = (int)i; + queue.Enqueue(new string[] { source[index * 3], source[index * 3 + 1], source[index * 3 + 2] }); + }); + + for (var i = 0; i < queue.Count; i++) + { + if (null == output[i]) + Assert.Fail(); + } + } + + + [Test, Repeat(100)] + public void TestFastEnqueueDequeue() + { + int count = 1000; + + var source = new string[count * 3]; + + for (var i = 0; i < source.Length; i++) + { + source[i] = Guid.NewGuid().ToString(); + } + + IBatchQueue queue = new ConcurrentBatchQueue(count * 3); + + Task[] tasks = new Task[count]; + + for (var i = 0; i < count; i++) + { + tasks[i] = new Task((j) => + { + var index = (int)j; + var sw = new SpinWait(); + + queue.Enqueue(source[index * 3]); + + sw.SpinOnce(); + sw.SpinOnce(); + sw.SpinOnce(); + sw.SpinOnce(); + + queue.Enqueue(source[index * 3 + 1]); + + sw.SpinOnce(); + sw.SpinOnce(); + sw.SpinOnce(); + sw.SpinOnce(); + + queue.Enqueue(source[index * 3 + 2]); + }, i); + } + + tasks.ToList().ForEach(t => t.Start()); + + var outputList = new List(); + + var spinWait = new SpinWait(); + + while (outputList.Count < source.Length) + { + if (!queue.TryDequeue(outputList)) + spinWait.SpinOnce(); + } + + var dict = source.ToDictionary(s => s); + + for (var i = 0; i < outputList.Count; i++) + { + var line = outputList[i]; + + if (!dict.Remove(line)) + Assert.Fail("Dequeue error"); + } + + Assert.AreEqual(0, dict.Count); + } + + [Test, Repeat(100)] + public void TestFastBatchEnqueueDequeue() + { + int count = 1000; + + var source = new string[count * 3]; + + for (var i = 0; i < source.Length; i++) + { + source[i] = Guid.NewGuid().ToString(); + } + + IBatchQueue queue = new ConcurrentBatchQueue(count * 3); + + Task[] tasks = new Task[count]; + + for (var i = 0; i < count; i++) + { + tasks[i] = new Task((j) => + { + var index = (int)j; + queue.Enqueue(new string[] { source[index * 3], source[index * 3 + 1], source[index * 3 + 2] }); + }, i); + } + + tasks.ToList().ForEach(t => t.Start()); + + var outputList = new List(); + + var spinWait = new SpinWait(); + + while (outputList.Count < source.Length) + { + if (!queue.TryDequeue(outputList)) + spinWait.SpinOnce(); + else + Console.WriteLine("Count:" + outputList.Count); + } + + var dict = source.ToDictionary(s => s); + + for (var i = 0; i < outputList.Count; i++) + { + var line = outputList[i]; + + if (!dict.Remove(line)) + Assert.Fail("Dequeue error"); + } + + Assert.AreEqual(0, dict.Count); + } + } +} diff --git a/Test/Common/BinaryUtilTest.cs b/Test/Common/BinaryUtilTest.cs new file mode 100644 index 000000000..c285f6f76 --- /dev/null +++ b/Test/Common/BinaryUtilTest.cs @@ -0,0 +1,110 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using NUnit.Framework; +using SuperSocket.Common; + +namespace SuperSocket.Test.Common +{ + [TestFixture] + public class BinaryUtilTest + { + [Test] + public void SearchMarkNotFound() + { + byte[] source = Encoding.ASCII.GetBytes("I love you so much!"); + byte[] mark = Encoding.ASCII.GetBytes("XY"); + + Assert.IsFalse(BinaryUtil.SearchMark(source, mark).HasValue); + } + + [Test] + public void SearchMarkFake() + { + byte[] bytes = { 0x17, 0x17, 0x17, 0x17, 0x18 }; + byte[] mark = { 0x17, 0x17, 0x17, 0x18 }; + + var actual = BinaryUtil.SearchMark(bytes, mark); + + var expected = 1; + + Assert.AreEqual(expected, actual); + } + + [Test] + public void SearchMarkBegin() + { + byte[] source = Encoding.ASCII.GetBytes("I love you so much!"); + byte[] mark = Encoding.ASCII.GetBytes("I love"); + + Assert.AreEqual(0, BinaryUtil.SearchMark(source, mark).Value); + } + + [Test] + public void SearchMarkMiddle() + { + byte[] source = Encoding.ASCII.GetBytes("I love you so much!"); + byte[] mark = Encoding.ASCII.GetBytes("you"); + byte[] start = Encoding.ASCII.GetBytes("I love "); + + Assert.AreEqual(start.Length, BinaryUtil.SearchMark(source, mark).Value); + } + + [Test] + public void SearchMarkEnd() + { + byte[] source = Encoding.ASCII.GetBytes("I love you so much!"); + byte[] mark = Encoding.ASCII.GetBytes("much!"); + byte[] start = Encoding.ASCII.GetBytes("I love you so "); + + Assert.AreEqual(start.Length, BinaryUtil.SearchMark(source, mark).Value); + } + + [Test] + public void SearchMarkMatchCount() + { + byte[] source = Encoding.ASCII.GetBytes("I love you so mu"); + byte[] mark = Encoding.ASCII.GetBytes("much!"); + + Assert.AreEqual(-2, BinaryUtil.SearchMark(source, mark).Value); + } + + [Test] + public void StartWithNotFound() + { + byte[] source = Encoding.ASCII.GetBytes("I love you so mu"); + byte[] mark = Encoding.ASCII.GetBytes("xxx"); + + Assert.AreEqual(-1, BinaryUtil.StartsWith(source, mark)); + } + + [Test] + public void StartWithLenth() + { + byte[] source = Encoding.ASCII.GetBytes("I love you so mu"); + byte[] mark = Encoding.ASCII.GetBytes("I love"); + + Assert.AreEqual(mark.Length, BinaryUtil.StartsWith(source, mark)); + } + + [Test] + public void StartWithLenth2() + { + byte[] source = Encoding.ASCII.GetBytes("I love"); + byte[] mark = Encoding.ASCII.GetBytes("I love you so much"); + + Assert.AreEqual(source.Length, BinaryUtil.StartsWith(source, mark)); + } + + [Test] + public void TestEndsWith() + { + byte[] source = Encoding.ASCII.GetBytes("I love you so much"); + byte[] markA = Encoding.ASCII.GetBytes("much"); + byte[] markB = Encoding.ASCII.GetBytes("much1"); + Assert.AreEqual(true, source.EndsWith(markA)); + Assert.AreEqual(false, source.EndsWith(markB)); + } + } +} diff --git a/Test/Common/PerformanceTest.cs b/Test/Common/PerformanceTest.cs new file mode 100644 index 000000000..a00fb4abd --- /dev/null +++ b/Test/Common/PerformanceTest.cs @@ -0,0 +1,84 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using NUnit.Framework; +using System.Diagnostics; + +namespace SuperSocket.Test.Common +{ + [TestFixture] + public class PerformanceTest + { + //[Test] + public void TestCopyArrayByLINQ() + { + byte[] source = new byte[1024 * 1024 * 10]; //10MB + + int offset = 1024 * 1024 * 5; + int length = 1024 * 1024 * 5; + + Stopwatch watch = new Stopwatch(); + + watch.Start(); + + for (int i = 0; i < 100; i++) + { + source.Skip(offset).Take(length).ToArray(); + Console.WriteLine(i); + } + + watch.Stop(); + + Console.WriteLine(watch.ElapsedMilliseconds); + } + + [Test] + public void TestCopyArray() + { + byte[] source = new byte[1024 * 1024 * 10]; //10MB + + int offset = 1024 * 1024 * 5; + int length = 1024 * 1024 * 5; + + byte[] target = new byte[length]; + + Stopwatch watch = new Stopwatch(); + + watch.Start(); + + for (int i = 0; i < 100; i++) + { + Array.Copy(source, offset, target, 0, length); + } + + watch.Stop(); + + Console.WriteLine(watch.ElapsedMilliseconds); + } + + [Test] + public void TestCopyArrayByBlockCopy() + { + byte[] source = new byte[1024 * 1024 * 10]; //10MB + + int offset = 1024 * 1024 * 5; + int length = 1024 * 1024 * 5; + + byte[] target = new byte[length]; + + Stopwatch watch = new Stopwatch(); + + watch.Start(); + + for (int i = 0; i < 100; i++) + { + Buffer.BlockCopy(source, offset, target, 0, length); + } + + watch.Stop(); + + Console.WriteLine(watch.ElapsedMilliseconds); + } + } +} diff --git a/Test/Config/AppDomain.config b/Test/Config/AppDomain.config new file mode 100644 index 000000000..55c77f444 --- /dev/null +++ b/Test/Config/AppDomain.config @@ -0,0 +1,24 @@ + + + +
+ + + + + + + + + + + + + + + + + diff --git a/Test/Config/Basic.config b/Test/Config/Basic.config new file mode 100644 index 000000000..e913dd84f --- /dev/null +++ b/Test/Config/Basic.config @@ -0,0 +1,24 @@ + + + +
+ + + + + + + + + + + + + + + + + diff --git a/Test/Config/ChildConfig.cs b/Test/Config/ChildConfig.cs new file mode 100644 index 000000000..4c6e48ad9 --- /dev/null +++ b/Test/Config/ChildConfig.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Configuration; + +namespace SuperSocket.Test.Config +{ + public class ChildConfig : ConfigurationElement + { + [ConfigurationProperty("value", IsRequired = true)] + public int Value + { + get { return (int)this["value"]; } + } + } + + [ConfigurationCollection(typeof(ChildConfig))] + public class ChildConfigCollection : ConfigurationElementCollection + { + [ConfigurationProperty("globalValue", IsRequired = true)] + public int GlobalValue + { + get { return (int)this["globalValue"]; } + } + + protected override ConfigurationElement CreateNewElement() + { + return new ChildConfig(); + } + + protected override object GetElementKey(ConfigurationElement element) + { + return element; + } + + public new IEnumerator GetEnumerator() + { + int count = base.Count; + + for (int i = 0; i < count; i++) + { + yield return (ChildConfig)base.BaseGet(i); + } + } + } +} diff --git a/Test/Config/ChildConfigA.config b/Test/Config/ChildConfigA.config new file mode 100644 index 000000000..b739b76a2 --- /dev/null +++ b/Test/Config/ChildConfigA.config @@ -0,0 +1,25 @@ + + + +
+ + + + + + + + + + + + + + + + + + diff --git a/Test/Config/ChildConfigB.config b/Test/Config/ChildConfigB.config new file mode 100644 index 000000000..39bdee161 --- /dev/null +++ b/Test/Config/ChildConfigB.config @@ -0,0 +1,24 @@ + + + +
+ + + + + + + + + + + + + + + + + diff --git a/Test/Config/ChildConfigC.config b/Test/Config/ChildConfigC.config new file mode 100644 index 000000000..8a5951993 --- /dev/null +++ b/Test/Config/ChildConfigC.config @@ -0,0 +1,25 @@ + + + +
+ + + + + + + + + + + + + + + + + diff --git a/Test/Config/ChildConfigD.config b/Test/Config/ChildConfigD.config new file mode 100644 index 000000000..27e44c9ea --- /dev/null +++ b/Test/Config/ChildConfigD.config @@ -0,0 +1,29 @@ + + + +
+ + + + + + + + + + + + + + + + + + + + + + diff --git a/Test/Config/DLR.config b/Test/Config/DLR.config new file mode 100644 index 000000000..d683bddc6 --- /dev/null +++ b/Test/Config/DLR.config @@ -0,0 +1,39 @@ + + + +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Test/Config/Listeners.config b/Test/Config/Listeners.config new file mode 100644 index 000000000..d933c74b9 --- /dev/null +++ b/Test/Config/Listeners.config @@ -0,0 +1,27 @@ + + + +
+ + + + + + + + + + + + + + + + + + + + + diff --git a/Test/Config/ServerType.config b/Test/Config/ServerType.config new file mode 100644 index 000000000..067ab4baf --- /dev/null +++ b/Test/Config/ServerType.config @@ -0,0 +1,20 @@ + + + +
+ + + + + + + + + + + + + + diff --git a/Test/ConnectionFilter/TestConnectionFilter.cs b/Test/ConnectionFilter/TestConnectionFilter.cs new file mode 100644 index 000000000..05fc57526 --- /dev/null +++ b/Test/ConnectionFilter/TestConnectionFilter.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase; +using System.Threading; + +namespace SuperSocket.Test.ConnectionFilter +{ + public class TestConnectionFilter : IConnectionFilter + { + public bool Initialize(string name, IAppServer appServer) + { + Name = name; + return true; + } + + public string Name { get; private set; } + + public static bool Allow { get; set; } + + private static int m_ConnectedCount = 0; + + public static int ConnectedCount + { + get { return m_ConnectedCount; } + } + + public bool AllowConnect(System.Net.IPEndPoint remoteAddress) + { + if (!Allow) + return false; + + Interlocked.Increment(ref m_ConnectedCount); + return true; + } + } +} diff --git a/Test/ConnectionFilterTest.cs b/Test/ConnectionFilterTest.cs new file mode 100644 index 000000000..ca929b979 --- /dev/null +++ b/Test/ConnectionFilterTest.cs @@ -0,0 +1,122 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using NUnit.Framework; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Config; +using SuperSocket.SocketBase.Logging; +using SuperSocket.SocketEngine; +using SuperSocket.Test.ConnectionFilter; + +namespace SuperSocket.Test +{ + [TestFixture] + public class ConnectionFilterTest + { + private TestServer m_Server; + + private IServerConfig m_ServerConfig; + + [TestFixtureSetUp] + public void Setup() + { + m_ServerConfig = new ServerConfig + { + Ip = "Any", + LogCommand = false, + MaxConnectionNumber = 1, + Mode = SocketMode.Tcp, + Name = "TestServer", + Port = 2012, + ClearIdleSession = false + }; + + m_Server = new TestServer(); + m_Server.NewSessionConnected += new Action(m_Server_NewSessionConnected); + m_Server.Setup(new RootConfig(), m_ServerConfig, SocketServerFactory.Instance, null, new ConsoleLogFactory(), new IConnectionFilter[] { new TestConnectionFilter() }, null); + } + + + private AutoResetEvent m_NewSessionConnectedEvent = new AutoResetEvent(false); + + void m_Server_NewSessionConnected(TestSession obj) + { + m_NewSessionConnectedEvent.Set(); + } + + [TearDown] + public void StopServer() + { + if (m_Server.IsRunning) + m_Server.Stop(); + } + + [Test] + public void TestAllow() + { + if (!m_Server.IsRunning) + m_Server.Start(); + + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_ServerConfig.Port); + + using (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) + { + TestConnectionFilter.Allow = true; + int oldCount = TestConnectionFilter.ConnectedCount; + + var signal = new ManualResetEventSlim(false); + + ThreadPool.QueueUserWorkItem((o) => + { + var s = o as Socket; + s.Connect(serverAddress); + signal.Set(); + }, socket); + + Assert.IsTrue(signal.Wait(2000)); + Thread.Sleep(100); + Assert.AreEqual(oldCount + 1, TestConnectionFilter.ConnectedCount); + + if (!m_NewSessionConnectedEvent.WaitOne(1000)) + Assert.Fail("New session hasnot been accept on time!"); + } + } + + [Test] + public void TestDisallow() + { + if (!m_Server.IsRunning) + m_Server.Start(); + + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_ServerConfig.Port); + + using (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) + { + TestConnectionFilter.Allow = false; + + var signal = new ManualResetEventSlim(false); + + int oldCount = TestConnectionFilter.ConnectedCount; + + Task.Factory.StartNew((o) => + { + var s = o as Socket; + s.Connect(serverAddress); + signal.Set(); + }, socket); + + Assert.IsTrue(signal.Wait(2000)); + Thread.Sleep(100); + Assert.AreEqual(oldCount, TestConnectionFilter.ConnectedCount); + + if (m_NewSessionConnectedEvent.WaitOne(1000)) + Assert.Fail("The connection filter doesn't work as requirement!"); + } + } + } +} diff --git a/Test/DLRSocketServerTest.cs b/Test/DLRSocketServerTest.cs new file mode 100644 index 000000000..2b9498e44 --- /dev/null +++ b/Test/DLRSocketServerTest.cs @@ -0,0 +1,207 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text; +using Microsoft.Scripting.Hosting; +using NUnit.Framework; +using SuperSocket.Dlr; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Config; +using SuperSocket.SocketBase.Logging; +using SuperSocket.SocketEngine; + +namespace SuperSocket.Test +{ + [TestFixture] + public class DLRSocketServerTest + { + private TestServer m_Server; + + private IServerConfig m_ServerConfig; + + private Encoding m_Encoding; + + [TestFixtureSetUp] + public void Setup() + { + m_Encoding = new UTF8Encoding(); + m_ServerConfig = new ServerConfig + { + Ip = "Any", + LogCommand = false, + MaxConnectionNumber = 100, + Mode = SocketMode.Tcp, + Name = "DLR Socket Server", + Port = 2012, + ClearIdleSession = true + }; + + m_Server = new TestServer(); + var scriptRuntime = new ScriptRuntime(new ScriptRuntimeSetup + { + LanguageSetups = + { + new LanguageSetup("IronPython.Runtime.PythonContext, IronPython", "IronPython", "IronPython;Python;py".Split(';'), new string[] { ".py" }) + } + }); + m_Server.Setup(new RootConfig(), m_ServerConfig, SocketServerFactory.Instance, null, new ConsoleLogFactory(), null, new ICommandLoader[] { new DynamicCommandLoader(scriptRuntime) }); + } + + [TearDown] + public void StopServer() + { + if (m_Server.IsRunning) + m_Server.Stop(); + } + + [Test] + public void TestCommands() + { + if (!m_Server.IsRunning) + m_Server.Start(); + + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_ServerConfig.Port); + + using (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) + { + socket.Connect(serverAddress); + Stream socketStream = new NetworkStream(socket); + using (StreamReader reader = new StreamReader(socketStream, m_Encoding, true)) + using (StreamWriter writer = new StreamWriter(socketStream, m_Encoding, 1024 * 8)) + { + reader.ReadLine(); + + Random rd = new Random(); + + for (int i = 0; i < 10; i++) + { + int x = rd.Next(1, 1000), y = rd.Next(1, 1000); + string command = string.Format("{0} {1} {2}", "ADD", x, y); + Console.WriteLine(command); + writer.WriteLine(command); + writer.Flush(); + string line = reader.ReadLine(); + Console.WriteLine(line); + Assert.AreEqual(x + y, int.Parse(line)); + } + + for (int i = 0; i < 10; i++) + { + int x = rd.Next(1, 1000), y = rd.Next(1, 1000); + string command = string.Format("{0} {1} {2}", "MULT", x, y); + Console.WriteLine(command); + writer.WriteLine(command); + writer.Flush(); + string line = reader.ReadLine(); + Console.WriteLine(line); + Assert.AreEqual(x * y, int.Parse(line)); + } + } + } + } + + + [Test] + public void TestPerformance() + { + if (!m_Server.IsRunning) + m_Server.Start(); + + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_ServerConfig.Port); + + using (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) + { + socket.Connect(serverAddress); + Stream socketStream = new NetworkStream(socket); + using (StreamReader reader = new StreamReader(socketStream, m_Encoding, true)) + using (StreamWriter writer = new StreamWriter(socketStream, m_Encoding, 1024 * 8)) + { + reader.ReadLine(); + + Random rd = new Random(); + + for (int i = 0; i < 10; i++) + { + int x = rd.Next(1, 1000), y = rd.Next(1, 1000); + string command = string.Format("{0} {1} {2}", "ADD", x, y); + writer.WriteLine(command); + writer.Flush(); + string line = reader.ReadLine(); + Assert.AreEqual(x + y, int.Parse(line)); + } + + for (int i = 0; i < 10; i++) + { + int x = rd.Next(1, 1000), y = rd.Next(1, 1000); + string command = string.Format("{0} {1} {2}", "MULT", x, y); + writer.WriteLine(command); + writer.Flush(); + string line = reader.ReadLine(); + Assert.AreEqual(x * y, int.Parse(line)); + } + + var watch = new Stopwatch(); + + watch.Start(); + + for (int i = 0; i < 500; i++) + { + int x = rd.Next(1, 1000), y = rd.Next(1, 1000); + string command = string.Format("{0} {1} {2}", "ADD", x, y); + writer.WriteLine(command); + writer.Flush(); + string line = reader.ReadLine(); + Assert.AreEqual(x + y, int.Parse(line)); + } + + for (int i = 0; i < 500; i++) + { + int x = rd.Next(1, 1000), y = rd.Next(1, 1000); + string command = string.Format("{0} {1} {2}", "MULT", x, y); + writer.WriteLine(command); + writer.Flush(); + string line = reader.ReadLine(); + Assert.AreEqual(x * y, int.Parse(line)); + } + + watch.Stop(); + + var dynamicTime = watch.ElapsedMilliseconds; + + watch.Reset(); + watch.Start(); + + for (int i = 0; i < 500; i++) + { + int x = rd.Next(1, 1000), y = rd.Next(1, 1000); + string command = string.Format("{0} {1} {2}", "ADDCS", x, y); + writer.WriteLine(command); + writer.Flush(); + string line = reader.ReadLine(); + Assert.AreEqual(x + y, int.Parse(line)); + } + + for (int i = 0; i < 500; i++) + { + int x = rd.Next(1, 1000), y = rd.Next(1, 1000); + string command = string.Format("{0} {1} {2}", "MULTCS", x, y); + writer.WriteLine(command); + writer.Flush(); + string line = reader.ReadLine(); + Assert.AreEqual(x * y, int.Parse(line)); + } + + watch.Stop(); + var staticTime = watch.ElapsedMilliseconds; + + Console.WriteLine("{0}/{1} = {2}", dynamicTime, staticTime, ((decimal)dynamicTime / (decimal)staticTime).ToString("0.0")); + } + } + } + } +} diff --git a/Test/ITestSetup.cs b/Test/ITestSetup.cs new file mode 100644 index 000000000..ddae1b498 --- /dev/null +++ b/Test/ITestSetup.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Config; + +namespace SuperSocket.Test +{ + public interface ITestSetup + { + void Setup(IRootConfig rootConfig, IServerConfig serverConfig); + } +} diff --git a/Test/Properties/AssemblyInfo.cs b/Test/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..8a9c8e316 --- /dev/null +++ b/Test/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +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("Test")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("Test")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2010")] +[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)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("09c402bb-907e-4632-9302-3746d4cca716")] + +// 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")] diff --git a/Test/Resources/TestFile.txt b/Test/Resources/TestFile.txt new file mode 100644 index 000000000..d91f1f75f --- /dev/null +++ b/Test/Resources/TestFile.txt @@ -0,0 +1,29 @@ +[ERROR] 04-06 15:48:22 1 CdcSoftware.Iaf.Services.Commands.CommandService.GetNavigationNode +Problem configuring filters and providers: Failed to load type "CdcSoftware.Erp.Reporting.Ssrs.MRSAddInCommandProvider, CdcSoftware.Erp.Reporting.Ssrs.ClientUI" in assembly "CdcSoftware.Erp.Reporting.Ssrs.ClientUI". +No IErrors provided. +Inner Exception: System.ArgumentException: Failed to load type "CdcSoftware.Erp.Reporting.Ssrs.MRSAddInCommandProvider, CdcSoftware.Erp.Reporting.Ssrs.ClientUI" in assembly "CdcSoftware.Erp.Reporting.Ssrs.ClientUI". + at CdcSoftware.Shared.IosObject.GetType(String assemblyName, String className) + at CdcSoftware.Shared.IosObject.GetType(IEnvSection env) + at CdcSoftware.Iaf.SmartClient.Core.ContainerWorkItem.GetInstance(IEnvSection definition, Boolean ensureExists) + at CdcSoftware.Iaf.SmartClient.Core.ContainerWorkItem.GetInstance[T](IEnvSection definition) + at CdcSoftware.Iaf.Services.Commands.CommandService.GetConfigElement(ConfigElement& configElement) + + at CdcSoftware.Shared.IosObject.GetType(String assemblyName, String className) + at CdcSoftware.Shared.IosObject.GetType(IEnvSection env) + at CdcSoftware.Iaf.SmartClient.Core.ContainerWorkItem.GetInstance(IEnvSection definition, Boolean ensureExists) + at CdcSoftware.Iaf.SmartClient.Core.ContainerWorkItem.GetInstance[T](IEnvSection definition) + at CdcSoftware.Iaf.Services.Commands.CommandService.GetConfigElement(ConfigElement& configElement)Failed to load type "CdcSoftware.Erp.Reporting.Ssrs.MRSAddInCommandProvider, CdcSoftware.Erp.Reporting.Ssrs.ClientUI" in assembly "CdcSoftware.Erp.Reporting.Ssrs.ClientUI". +No IErrors provided. +Inner Exception: System.ArgumentException: Failed to load type "CdcSoftware.Erp.Reporting.Ssrs.MRSAddInCommandProvider, CdcSoftware.Erp.Reporting.Ssrs.ClientUI" in assembly "CdcSoftware.Erp.Reporting.Ssrs.ClientUI". + at CdcSoftware.Shared.IosObject.GetType(String assemblyName, String className) + at CdcSoftware.Shared.IosObject.GetType(IEnvSection env) + at CdcSoftware.Iaf.SmartClient.Core.ContainerWorkItem.GetInstance(IEnvSection definition, Boolean ensureExists) + at CdcSoftware.Iaf.SmartClient.Core.ContainerWorkItem.GetInstance[T](IEnvSection definition) + at CdcSoftware.Iaf.Services.Commands.CommandService.GetConfigElement(ConfigElement& configElement) + + at CdcSoftware.Shared.IosObject.GetType(String assemblyName, String className) + at CdcSoftware.Shared.IosObject.GetType(IEnvSection env) + at CdcSoftware.Iaf.SmartClient.Core.ContainerWorkItem.GetInstance(IEnvSection definition, Boolean ensureExists) + at CdcSoftware.Iaf.SmartClient.Core.ContainerWorkItem.GetInstance[T](IEnvSection definition) + at CdcSoftware.Iaf.Services.Commands.CommandService.GetConfigElement(ConfigElement& configElement) + diff --git a/Test/SecureTcpSocketServerTest.cs b/Test/SecureTcpSocketServerTest.cs new file mode 100644 index 000000000..a63c448fd --- /dev/null +++ b/Test/SecureTcpSocketServerTest.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Config; +using NUnit.Framework; +using SuperSocket.SocketBase; +using System.IO; +using System.Net.Security; +using System.Net.Sockets; +using System.Security.Cryptography.X509Certificates; +using System.Security.Authentication; + +namespace SuperSocket.Test +{ + [TestFixture] + public class SecureTcpSocketServerTest : SocketServerTest + { + protected override IServerConfig DefaultServerConfig + { + get + { + return new ServerConfig + { + Ip = "Any", + LogCommand = true, + MaxConnectionNumber = 100, + Mode = SocketMode.Tcp, + Name = "Secure Test Socket Server", + Port = 2012, + ClearIdleSession = true, + ClearIdleSessionInterval = 1, + IdleSessionTimeOut = 5, + Security = "Tls", + SendingQueueSize = 100, + Certificate = new CertificateConfig + { + Password = "supersocket", + FilePath = "supersocket.pfx" + } + }; + } + } + + protected override Stream GetSocketStream(System.Net.Sockets.Socket socket) + { + SslStream stream = new SslStream(new NetworkStream(socket), false, new RemoteCertificateValidationCallback(ValidateRemoteCertificate)); + stream.AuthenticateAsClient("supersocket"); + return stream; + } + + private bool ValidateRemoteCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) + { + if (sslPolicyErrors != SslPolicyErrors.None) + { + Console.WriteLine("SSL Certificate Validation Error!"); + Console.WriteLine(sslPolicyErrors.ToString()); + Console.WriteLine("Chain status:"); + foreach (var s in chain.ChainStatus) + { + Console.WriteLine("\t" + s.Status + " : " + s.StatusInformation); + } + return false; + } + + return true; + } + } +} diff --git a/Test/Setup.cs b/Test/Setup.cs new file mode 100644 index 000000000..90332e647 --- /dev/null +++ b/Test/Setup.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using NUnit.Framework; +using SuperSocket.SocketBase.Logging; +using System.Threading; + +namespace SuperSocket.Test +{ + [SetUpFixture] + public class Setup + { + [SetUp] + public void RunBeforeAllTest() + { + + } + } +} diff --git a/Test/SocketServerTest.cs b/Test/SocketServerTest.cs new file mode 100644 index 000000000..9fbb5e26f --- /dev/null +++ b/Test/SocketServerTest.cs @@ -0,0 +1,659 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Threading; +using NUnit.Framework; +using SuperSocket.Common; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Config; +using SuperSocket.SocketBase.Logging; +using SuperSocket.SocketEngine; +using SuperSocket.Test.Command; + + +namespace SuperSocket.Test +{ + public abstract class SocketServerTest + { + private static Dictionary m_Servers = new Dictionary(); + + protected readonly IServerConfig m_Config; + + private IRootConfig m_RootConfig; + + protected Encoding m_Encoding; + + public SocketServerTest() + { + m_Config = DefaultServerConfig; + m_RootConfig = new RootConfig + { + MaxWorkingThreads = 500, + MaxCompletionPortThreads = 500, + MinWorkingThreads = 5, + MinCompletionPortThreads = 5, + DisablePerformanceDataCollector = true + }; + + m_Encoding = new UTF8Encoding(); + } + + private IWorkItem GetServerByIndex(int index) + { + IWorkItem[] servers = new IWorkItem[0]; + + if (!m_Servers.TryGetValue(m_Config, out servers)) + return null; + + return servers[index]; + } + + private IWorkItem ServerX + { + get + { + return GetServerByIndex(0); + } + } + + private IWorkItem ServerY + { + get + { + return GetServerByIndex(1); + } + } + + protected abstract IServerConfig DefaultServerConfig { get; } + + [TestFixtureSetUp] + public void Setup() + { + if (m_Servers.ContainsKey(m_Config)) + return; + + var serverX = CreateAppServer(); + + var serverY = CreateAppServer(); + + m_Servers[m_Config] = new IWorkItem[] + { + serverX, + serverY + }; + } + + private IWorkItem CreateAppServer() + where T : IWorkItem, ITestSetup, new() + { + return CreateAppServer(m_RootConfig, m_Config); + } + + protected virtual IWorkItem CreateAppServer(IRootConfig rootConfig, IServerConfig serverConfig) + where T : IWorkItem, ITestSetup, new() + { + var appServer = new T(); + appServer.Setup(rootConfig, serverConfig); + return appServer; + } + + [TestFixtureTearDown] + public void StopAllServers() + { + StopServer(); + } + + [Test, Repeat(10)] + public void TestStartStop() + { + StartServer(); + Assert.IsTrue(ServerX.IsRunning); + StopServer(); + Assert.IsFalse(ServerX.IsRunning); + } + + private bool CanConnect() + { + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port); + + using (Socket socket = CreateClientSocket()) + { + try + { + socket.Connect(serverAddress); + return true; + } + catch (Exception) + { + return false; + } + } + } + + protected void StartServer() + { + if (ServerX.IsRunning) + ServerX.Stop(); + + ServerX.Start(); + Console.WriteLine("Socket server X has been started!"); + } + + [TearDown] + public void StopServer() + { + if (ServerX.IsRunning) + { + ServerX.Stop(); + Console.WriteLine("Socket server X has been stopped!"); + } + + if (ServerY != null && ServerY.IsRunning) + { + ServerY.Stop(); + Console.WriteLine("Socket server Y has been stopped!"); + } + } + + protected virtual Socket CreateClientSocket() + { + return new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + } + + protected virtual Stream GetSocketStream(Socket socket) + { + return new NetworkStream(socket); + } + + [Test, Repeat(3)] + public void TestWelcomeMessage() + { + StartServer(); + + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port); + + using (Socket socket = CreateClientSocket()) + { + socket.Connect(serverAddress); + Stream socketStream = GetSocketStream(socket); + using (StreamReader reader = new StreamReader(socketStream, m_Encoding, true)) + using (StreamWriter writer = new StreamWriter(socketStream, m_Encoding, 1024 * 8)) + { + string welcomeString = reader.ReadLine(); + Assert.AreEqual(string.Format(TestSession.WelcomeMessageFormat, m_Config.Name), welcomeString); + } + } + } + + private bool TestMaxConnectionNumber(int maxConnectionNumber) + { + var defaultConfig = DefaultServerConfig; + + var config = new ServerConfig + { + Ip = defaultConfig.Ip, + LogCommand = defaultConfig.LogCommand, + MaxConnectionNumber = maxConnectionNumber, + Mode = defaultConfig.Mode, + Name = defaultConfig.Name, + Port = defaultConfig.Port, + Security = defaultConfig.Security, + Certificate = defaultConfig.Certificate + }; + + var server = CreateAppServer(m_RootConfig, config); + + List sockets = new List(); + + try + { + server.Start(); + + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port); + + for (int i = 0; i < maxConnectionNumber; i++) + { + Socket socket = CreateClientSocket(); + socket.Connect(serverAddress); + Stream socketStream = GetSocketStream(socket); + StreamReader reader = new StreamReader(socketStream, m_Encoding, true); + reader.ReadLine(); + sockets.Add(socket); + } + + try + { + using (Socket trySocket = CreateClientSocket()) + { + trySocket.Connect(serverAddress); + var innerSocketStream = new NetworkStream(trySocket); + innerSocketStream.ReadTimeout = 500; + + using (StreamReader tryReader = new StreamReader(innerSocketStream, m_Encoding, true)) + { + string welcome = tryReader.ReadLine(); + Console.WriteLine(welcome); + return true; + } + } + } + catch (Exception) + { + return true; + } + } + catch (Exception e) + { + Console.WriteLine(e.Message + " " + e.StackTrace); + return false; + } + finally + { + server.Stop(); + } + } + + [Test, Category("Concurrency")] + public void TestMaxConnectionNumber() + { + Assert.IsTrue(TestMaxConnectionNumber(1)); + Assert.IsTrue(TestMaxConnectionNumber(2)); + Assert.IsTrue(TestMaxConnectionNumber(5)); + Assert.IsTrue(TestMaxConnectionNumber(15)); + } + + [Test, Repeat(2)] + public void TestUnknownCommand() + { + StartServer(); + + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port); + + using (Socket socket = CreateClientSocket()) + { + socket.Connect(serverAddress); + Stream socketStream = GetSocketStream(socket); + using (StreamReader reader = new StreamReader(socketStream, m_Encoding, true)) + using (StreamWriter writer = new StreamWriter(socketStream, m_Encoding, 1024 * 8)) + { + reader.ReadLine(); + + for (int i = 0; i < 10; i++) + { + string commandName = Guid.NewGuid().ToString().Substring(i, 3); + string command = commandName + " " + DateTime.Now; + writer.WriteLine(command); + writer.Flush(); + string line = reader.ReadLine(); + Console.WriteLine(line); + Assert.AreEqual(string.Format(TestSession.UnknownCommandMessageFormat, commandName), line); + } + } + } + } + + [Test] + public void TestEchoMessage() + { + StartServer(); + + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port); + + using (Socket socket = CreateClientSocket()) + { + socket.Connect(serverAddress); + Stream socketStream = GetSocketStream(socket); + using (StreamReader reader = new StreamReader(socketStream, m_Encoding, true)) + using (StreamWriter writer = new StreamWriter(socketStream, m_Encoding, 1024 * 8)) + { + string welcomeString = reader.ReadLine(); + + Console.WriteLine("Welcome: " + welcomeString); + + char[] chars = new char[] { 'a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F', 'g', 'G', 'h', 'H' }; + + Random rd = new Random(1); + + StringBuilder sb = new StringBuilder(); + + for (int i = 0; i < 100; i++) + { + sb.Append(chars[rd.Next(0, chars.Length - 1)]); + string command = sb.ToString(); + writer.WriteLine("ECHO " + command); + writer.Flush(); + string echoMessage = reader.ReadLine(); + Console.WriteLine("C:" + echoMessage); + Assert.AreEqual(command, echoMessage); + } + } + } + } + + + [Test] + public void TestCommandCombining() + { + StartServer(); + + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port); + + using (Socket socket = CreateClientSocket()) + { + socket.Connect(serverAddress); + Stream socketStream = GetSocketStream(socket); + using (StreamReader reader = new StreamReader(socketStream, m_Encoding, true)) + using (StreamWriter writer = new StreamWriter(socketStream, m_Encoding, 1024 * 8)) + { + string welcomeString = reader.ReadLine(); + + Console.WriteLine("Welcome: " + welcomeString); + + char[] chars = new char[] { 'a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F', 'g', 'G', 'h', 'H' }; + + Random rd = new Random(1); + + for (int j = 0; j < 10; j++) + { + StringBuilder sb = new StringBuilder(); + + List source = new List(5); + + for (int i = 0; i < 5; i++) + { + sb.Append(chars[rd.Next(0, chars.Length - 1)]); + string command = sb.ToString(); + source.Add(command); + writer.WriteLine("ECHO " + command); + } + + writer.Flush(); + + for (int i = 0; i < 5; i++) + { + string line = reader.ReadLine(); + Assert.AreEqual(source[i], line); + } + } + } + } + } + + + [Test] + public void TestBrokenCommandBlock() + { + StartServer(); + + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port); + + using (Socket socket = CreateClientSocket()) + { + socket.Connect(serverAddress); + Stream socketStream = GetSocketStream(socket); + using (StreamReader reader = new StreamReader(socketStream, m_Encoding, true)) + using (StreamWriter writer = new StreamWriter(socketStream, m_Encoding, 1024 * 8)) + { + string welcomeString = reader.ReadLine(); + + Console.WriteLine("Welcome: " + welcomeString); + + char[] chars = new char[] { 'a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F', 'g', 'G', 'h', 'H' }; + + Random rd = new Random(1); + + StringBuilder sb = new StringBuilder(); + + for (int i = 0; i < 50; i++) + { + sb.Append(chars[rd.Next(0, chars.Length - 1)]); + } + + string command = sb.ToString(); + + var commandSource = ("ECHO " + command).ToList(); + + while (commandSource.Count > 0) + { + int readLen = rd.Next(1, commandSource.Count); + writer.Write(commandSource.Take(readLen).ToArray()); + Console.WriteLine(commandSource.Take(readLen).ToArray()); + writer.Flush(); + commandSource.RemoveRange(0, readLen); + Thread.Sleep(200); + } + + writer.WriteLine(); + writer.Flush(); + + string echoMessage = reader.ReadLine(); + Console.WriteLine("C:" + echoMessage); + Assert.AreEqual(command, echoMessage); + } + } + } + + private bool RunEchoMessage(int runIndex) + { + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port); + + Socket socket = CreateClientSocket(); + socket.Connect(serverAddress); + Stream socketStream = GetSocketStream(socket); + using (StreamReader reader = new StreamReader(socketStream, m_Encoding, true)) + using (StreamWriter writer = new StreamWriter(socketStream, m_Encoding, 1024 * 8)) + { + string welcomeString = reader.ReadLine(); + Console.WriteLine(welcomeString); + + char[] chars = new char[] { 'a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F', 'g', 'G', 'h', 'H' }; + + Random rd = new Random(1); + + StringBuilder sb = new StringBuilder(); + + for (int i = 0; i < 10; i++) + { + sb.Append(chars[rd.Next(0, chars.Length - 1)]); + string command = sb.ToString(); + writer.WriteLine("ECHO " + command); + writer.Flush(); + string echoMessage = reader.ReadLine(); + if (!string.Equals(command, echoMessage)) + { + return false; + } + Thread.Sleep(50); + } + } + + return true; + } + + [Test, Repeat(3), Category("Concurrency")] + public void TestConcurrencyCommunication() + { + StartServer(); + + int concurrencyCount = 100; + + Semaphore semaphore = new Semaphore(0, concurrencyCount); + + bool[] resultArray = new bool[concurrencyCount]; + + System.Threading.Tasks.Parallel.For(0, concurrencyCount, i => + { + resultArray[i] = RunEchoMessage(i); + semaphore.Release(); + }); + + for (var i = 0; i < concurrencyCount; i++) + { + semaphore.WaitOne(); + Console.WriteLine("Got " + i); + } + + bool result = true; + + for (var i = 0; i < concurrencyCount; i++) + { + Console.WriteLine(i + ":" + resultArray[i]); + if (!resultArray[i]) + result = false; + } + + if (!result) + Assert.Fail("Concurrent Communications fault!"); + } + + [Test, Repeat(5)] + public virtual void TestClearTimeoutSession() + { + StartServer(); + + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port); + + Socket socket = CreateClientSocket(); + socket.Connect(serverAddress); + Stream socketStream = GetSocketStream(socket); + using (StreamReader reader = new StreamReader(socketStream, m_Encoding, true)) + using (StreamWriter writer = new StreamWriter(socketStream, m_Encoding, 1024 * 8)) + { + reader.ReadLine(); + } + + Assert.AreEqual(1, ServerX.SessionCount); + Thread.Sleep(2000); + Assert.AreEqual(1, ServerX.SessionCount); + Thread.Sleep(5000); + Assert.AreEqual(0, ServerX.SessionCount); + } + + [Test] + public void TestCustomCommandName() + { + StartServer(); + + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port); + + using (Socket socket = CreateClientSocket()) + { + socket.Connect(serverAddress); + Stream socketStream = GetSocketStream(socket); + using (StreamReader reader = new StreamReader(socketStream, m_Encoding, true)) + using (StreamWriter writer = new StreamWriter(socketStream, m_Encoding, 1024 * 8)) + { + reader.ReadLine(); + string param = Guid.NewGuid().ToString(); + writer.WriteLine("325 " + param); + writer.Flush(); + string echoMessage = reader.ReadLine(); + Console.WriteLine("C:" + echoMessage); + Assert.AreEqual(string.Format(SuperSocket.Test.Command.NUM.ReplyFormat, param), echoMessage); + } + } + } + + [Test, Repeat(3)] + public void TestCommandParser() + { + if (ServerY.IsRunning) + ServerY.Stop(); + + ServerY.Start(); + Console.WriteLine("Socket server Y has been started!"); + + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port); + + using (Socket socket = CreateClientSocket()) + { + socket.Connect(serverAddress); + Stream socketStream = GetSocketStream(socket); + using (StreamReader reader = new StreamReader(socketStream, m_Encoding, true)) + using (StreamWriter writer = new StreamWriter(socketStream, m_Encoding, 1024 * 8)) + { + reader.ReadLine(); + string command = string.Format("Hello World ({0})!", Guid.NewGuid().ToString()); + writer.WriteLine("ECHO:" + command); + writer.Flush(); + string echoMessage = reader.ReadLine(); + Assert.AreEqual(command, echoMessage); + } + } + } + + [Test, Repeat(3)] + public void TestConcurrentSending() + { + StartServer(); + + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port); + + string[] source = SEND.GetStringSource(); + + string[] received = new string[source.Length]; + + using (Socket socket = CreateClientSocket()) + { + socket.Connect(serverAddress); + Stream socketStream = GetSocketStream(socket); + using (StreamReader reader = new StreamReader(socketStream, m_Encoding, true)) + using (StreamWriter writer = new StreamWriter(socketStream, m_Encoding, 1024 * 8)) + { + reader.ReadLine(); + writer.WriteLine("SEND"); + writer.Flush(); + + for (var i = 0; i < received.Length; i++) + { + var line = reader.ReadLine(); + received[i] = line; + Console.WriteLine(line); + } + } + } + + var dict = source.ToDictionary(i => i); + + for (var i = 0; i < received.Length; i++) + { + if (!dict.Remove(received[i])) + Assert.Fail(received[i]); + } + + if (dict.Count > 0) + Assert.Fail(); + } + + private byte[] ReadStreamToBytes(Stream stream) + { + return ReadStreamToBytes(stream, null); + } + + private byte[] ReadStreamToBytes(Stream stream, byte[] endMark) + { + MemoryStream ms = new MemoryStream(); + + byte[] buffer = new byte[1024 * 10]; + + while (true) + { + int read = stream.Read(buffer, 0, buffer.Length); + + if (read <= 0) + break; + + ms.Write(buffer, 0, read); + } + + if (endMark != null && endMark.Length > 0) + ms.Write(endMark, 0, endMark.Length); + + return ms.ToArray(); + } + } +} diff --git a/Test/Strings.txt b/Test/Strings.txt new file mode 100644 index 000000000..7a90d787d --- /dev/null +++ b/Test/Strings.txt @@ -0,0 +1,100 @@ +89fc04b5-c7ae-4f58-96ce-14c71c99dfce +3b0349f4-cf41-4d1f-a69c-2d844923ede5 +e44834fc-986c-4482-b453-e74698c48df8 +9e4b8b1f-7363-4d36-aabc-f25a3979c60e +c29728d3-0e77-4d02-8b31-731e3771c65a +320f95ed-443e-489d-a6e7-b7c7ae48d447 +9d9bfc58-b2d0-4624-b747-192b6c867880 +d97c31c4-1931-461c-81cd-87993761643c +9a31818c-3bc3-4933-b6eb-6b95bf8968a1 +7de726c3-ac89-443a-b2e1-3385618d6a9d +302610d6-311d-4156-9ad9-b532b7c8d426 +3b011933-8386-4418-b1ce-bf8ad6382230 +2559a9ad-d788-4321-a5ff-c215d4984894 +e59e2b0b-b04c-451f-b936-271736852c26 +33452a5d-b2c0-4c59-a75f-2baa540d81d9 +1fc6e60b-de9a-4190-8ff7-4df14a2d9e7d +d495f1b4-9765-45c5-ba1a-93e7068e0763 +c0d3337f-a4d0-4104-b172-d170c70ba188 +94b179e1-f4d0-4f55-b299-8e13b61ce5ab +14c3b267-463d-49d5-95d1-c28f85fc5fc1 +489791da-552c-4873-9bc4-298106d2445e +6eec47dd-d062-444e-93d1-d60411318d11 +1e127848-844d-4076-a132-c05d98987eb4 +d8ccb9f6-79ba-4ca6-8de4-1c481e864694 +8770bfe1-a249-4aff-abf1-21ab59083ad7 +0acafe2d-960e-4c5c-80b5-cf69a6192add +95a81679-4fe1-424d-8a5e-1cb7ebf557f2 +7fc40b02-c63f-418e-8f1a-20c3de683b06 +79cc3d1f-7d56-47c6-82ad-c52a16e5ccd3 +f836341c-c107-4808-a89d-964b161cb801 +6ffc25bb-ea11-400e-bb6d-359daa3eaeed +91b50389-ca5e-4bec-bcbb-3138ee7c4821 +dd5f325b-1b1d-416c-b8a9-0282da3bd2e9 +02be3c64-ef62-460e-b750-fc2ed71cafd4 +abd6da41-deb2-4ffd-bdc4-7c158571dd1c +3d9d5aec-a7e2-474d-8903-29a667549394 +66a408e5-a867-4d02-8751-c4360941c098 +9feb50ed-d411-4d16-8fcb-175063c6f279 +1201ef46-9c0f-4b77-b579-797a65a4c257 +009ed921-3a67-498a-8c33-517842ec0880 +3b557bb8-a8f1-47e7-bfd5-044c5c302f7b +1b9fcfe1-b5bb-4c53-a445-8e186c6abfc0 +896c7aa3-9ba6-4faf-91b8-cdc6bd0be50b +b56cc6c8-0dde-4dcf-90cb-5326553bdbf1 +4f66b04a-1102-45ad-90cb-27440a58b7dd +115310db-d46d-4332-b9d1-44e51a6d1748 +26a1b641-3e75-4bfc-9eae-76fa8e6a1982 +b6a6daf6-d982-4c75-9279-8230b86f6b2a +08a777e9-e42e-4496-b2b9-bd2dd76929fe +65efec25-54b2-4836-95b9-d7f3609d7171 +edb3c116-5f65-4431-8174-8c142b481fd8 +76e5e24c-cfc9-4aaa-ae65-05dbae936b28 +8a6ae05e-da91-471b-bc71-90ac71e194af +46f40725-0eec-4bf2-8076-fc5e163f97e5 +d7908949-e618-4d4f-a687-9f153f1851d3 +fc9f1bb1-9eb9-47de-a167-6b274663c6c4 +508eda29-c050-4fcb-9640-742aac77e677 +29ea6626-e78a-499b-a988-f92b79719993 +6fbb95ba-20de-4077-a205-b7df96837f96 +3bc26f1a-9095-4d76-b504-a11f95c4c573 +32f5d9ff-8d02-4a09-8267-26910fbc9b0c +3edffec0-6235-4dc1-a1e0-92dc6fccdb03 +1cce8a69-c9a3-4175-b5a2-1396b4629668 +6f319052-d371-4205-b6be-10a9f9422311 +b41be68b-0cba-48a6-9601-6f3f75a4a547 +d339e6ed-d3e0-4350-a0b0-53312a7f52e7 +06365021-e232-49b9-8a68-941f952d1127 +bacfa22b-d4c1-46fd-ba5e-5532fd880f32 +45508489-fe0b-4ae2-bf26-03358c41e7c5 +9d6497e0-5d53-4453-b435-7880d7a8082b +97f02960-6a5d-4b0a-984d-a88c7a399127 +b2590bad-ed63-4484-b4f3-19edfb8e9bf2 +12680a5f-1323-4eb9-9535-c5b31e0da6d4 +c56c3709-62ef-48b9-b245-6a751edffc31 +51d331ee-f264-421d-87e6-ce7aadef2937 +599e45cb-c01f-430c-8cc7-07253bd48960 +beea4c62-4c73-4994-9f01-85008230bef7 +e2386765-5f67-4e07-ae5f-bc2ec2093f66 +120f951b-d386-4703-b9f6-d83d47c6c9b9 +206fbf8c-401a-4770-8cc8-f28a0cb34b30 +fdb5ebf1-c250-465d-bd6b-53a6d91b8f07 +0e1495a8-de5c-4abe-a99f-da02bdce1b96 +21c993c3-e5eb-4233-ab8e-a543aa35d1e1 +63ea4b8d-acc4-442b-b212-608494abd262 +ad2c03c0-7d7c-4243-b7ff-dc401e5f8c42 +d71c5f81-0e90-4202-9087-9acec2eb257d +ac011f4b-aa29-4b30-87d7-09ce8a5cb624 +e1e50243-44d8-4ee7-9aa1-de73c6cbeed5 +ad9305ba-9533-4316-a002-02bec2c8e661 +d8f21c34-29a4-43a0-b0b5-fe5124892ac3 +8167d783-b229-4333-8128-cbbdebb83c33 +3103c012-330c-4d83-8b05-83c8105f10cc +a7fb01fd-cfca-4c18-8d4c-e4c7092f6471 +0de4be78-19f4-45f9-899b-0dfcba111df6 +b4387f5d-728f-47c8-8ce2-4d8e64190924 +ffbdab05-32db-4d84-9098-44f66337ef54 +85d71a9d-5083-4676-9c8e-eef18d601839 +6a843ba5-8064-4885-a284-59bdfc4a376a +82ae97cb-7504-47fa-86be-667dc2413663 +f8d2a6e5-15d9-4996-ac9f-5142c78aaf27 diff --git a/Test/SuperSocket.Test.NET35.csproj b/Test/SuperSocket.Test.NET35.csproj new file mode 100644 index 000000000..d33a22fd0 --- /dev/null +++ b/Test/SuperSocket.Test.NET35.csproj @@ -0,0 +1,186 @@ + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {BDBB6CE9-C3CE-49C1-A05E-2D7628430A02} + Library + Properties + SuperSocket.Test + SuperSocket.Test + v3.5 + 512 + + + 3.5 + + + + + true + full + false + bin\Debug\ + TRACE;DEBUG;IL20 + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE;IL20 + prompt + 4 + + + + False + ..\Reference\IronPython\Net35\IronPython.dll + + + False + ..\Reference\DLR\Net35\Microsoft.Dynamic.dll + + + False + ..\Reference\DLR\Net35\Microsoft.Scripting.dll + + + False + ..\Reference\nunit.framework.dll + + + + + 3.5 + + + False + ..\Reference\System.Threading.dll + + + 3.5 + + + 3.5 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + + + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A} + SuperSocket.Common.Net35 + + + {55BAA051-CE62-4D4A-81B6-68B042CC78E9} + SuperSocket.Dlr.Net35 + + + {40B77789-EA11-4C05-8F52-86711D7BCAAF} + SuperSocket.SocketBase.Net35 + + + {153FEF72-191C-43D9-BE71-2B351C7AC760} + SuperSocket.SocketEngine.Net35 + + + + + PreserveNewest + + + PreserveNewest + Designer + + + PreserveNewest + + + PreserveNewest + + + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + + + PreserveNewest + + + + + \ No newline at end of file diff --git a/Test/SuperSocket.Test.csproj b/Test/SuperSocket.Test.csproj new file mode 100644 index 000000000..eeb56acd6 --- /dev/null +++ b/Test/SuperSocket.Test.csproj @@ -0,0 +1,192 @@ + + + + Debug + AnyCPU + 9.0.30729 + 2.0 + {BDBB6CE9-C3CE-49C1-A05E-2D7628430A02} + Library + Properties + SuperSocket.Test + SuperSocket.Test + v4.0 + 512 + + + 3.5 + + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + true + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\Reference\IronPython\Net40\IronPython.dll + + + ..\Reference\DLR\Net40\Microsoft.Dynamic.dll + + + False + ..\Reference\DLR\Net40\Microsoft.Scripting.dll + + + False + ..\Reference\nunit.framework.dll + + + + + 3.5 + + + 3.5 + + + 3.5 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A} + SuperSocket.Common + + + {55BAA051-CE62-4D4A-81B6-68B042CC78E9} + SuperSocket.Dlr + + + {40B77789-EA11-4C05-8F52-86711D7BCAAF} + SuperSocket.SocketBase + + + {153FEF72-191C-43D9-BE71-2B351C7AC760} + SuperSocket.SocketEngine + + + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + PreserveNewest + + + + + PreserveNewest + + + PreserveNewest + + + + + PreserveNewest + Designer + + + + + PreserveNewest + + + + + PreserveNewest + Designer + + + + + PreserveNewest + + + + + PreserveNewest + + + + + PreserveNewest + + + + + PreserveNewest + + + + + \ No newline at end of file diff --git a/Test/TcpSocketServerTest.cs b/Test/TcpSocketServerTest.cs new file mode 100644 index 000000000..021766fb0 --- /dev/null +++ b/Test/TcpSocketServerTest.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using NUnit.Framework; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Config; + +namespace SuperSocket.Test +{ + [TestFixture] + public class TcpSocketServerTest : SocketServerTest + { + protected override IServerConfig DefaultServerConfig + { + get + { + return new ServerConfig + { + Ip = "Any", + LogCommand = true, + MaxConnectionNumber = 100, + Mode = SocketMode.Tcp, + Name = "Async Test Socket Server", + Port = 2012, + ClearIdleSession = true, + ClearIdleSessionInterval = 1, + IdleSessionTimeOut = 5, + SendingQueueSize = 100 + }; + } + } + } +} diff --git a/Test/TestRequestParser.cs b/Test/TestRequestParser.cs new file mode 100644 index 000000000..984b17a0b --- /dev/null +++ b/Test/TestRequestParser.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Protocol; +using SuperSocket.SocketBase.Command; + +namespace SuperSocket.Test +{ + public class TestRequestParser : IRequestInfoParser + { + #region ICommandParser Members + + public StringRequestInfo ParseRequestInfo(string source) + { + int pos = source.IndexOf(':'); + + if(pos <= 0) + return null; + + string param = source.Substring(pos + 1); + + return new StringRequestInfo(source.Substring(0, pos), param, + param.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)); + } + + #endregion + } +} diff --git a/Test/TestServer.cs b/Test/TestServer.cs new file mode 100644 index 000000000..0fee5f684 --- /dev/null +++ b/Test/TestServer.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.Dlr; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Config; +using SuperSocket.SocketBase.Logging; +using SuperSocket.SocketBase.Protocol; +using SuperSocket.SocketEngine; + +namespace SuperSocket.Test +{ + public class TestServerWithCustomRequestFilter : TestServer + { + public TestServerWithCustomRequestFilter() + : base(new TestRequestParser()) + { + + } + } + + public class TestServer : AppServer, ITestSetup + { + public TestServer() + : base() + { + + } + + public TestServer(IRequestInfoParser requestInfoParser) + : base(new CommandLineRequestFilterFactory(Encoding.UTF8, requestInfoParser)) + { + + } + + void ITestSetup.Setup(IRootConfig rootConfig, IServerConfig serverConfig) + { + base.Setup(rootConfig, serverConfig, SocketServerFactory.Instance, null, new ConsoleLogFactory(), null); + } + } +} diff --git a/Test/TestSession.cs b/Test/TestSession.cs new file mode 100644 index 000000000..413f48b09 --- /dev/null +++ b/Test/TestSession.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Protocol; + +namespace SuperSocket.Test +{ + public class TestSession : AppSession + { + public const string WelcomeMessageFormat = "Welcome to {0}"; + public const string UnknownCommandMessageFormat = "Unknown command: {0}"; + + protected override void OnSessionStarted() + { + if(AppServer.Config.Mode != SocketMode.Udp) + Send(string.Format(WelcomeMessageFormat, AppServer.Name)); + } + + public override void HandleException(Exception e) + { + + } + + public override void HandleUnknownRequest(StringRequestInfo cmdInfo) + { + string response = string.Format(UnknownCommandMessageFormat, cmdInfo.Key); + Send(response); + } + } +} diff --git a/Test/Udp/MyRequestFilter.cs b/Test/Udp/MyRequestFilter.cs new file mode 100644 index 000000000..29aa2de1d --- /dev/null +++ b/Test/Udp/MyRequestFilter.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Protocol; +using SuperSocket.SocketBase; + +namespace SuperSocket.Test.Udp +{ + class MyRequestFilter : IRequestFilter + { + public MyUdpRequestInfo Filter(IAppSession session, byte[] readBuffer, int offset, int length, bool toBeCopied, out int left) + { + left = 0; + + if (length <= 40) + return null; + + var key = Encoding.ASCII.GetString(readBuffer, offset, 4); + var sessionID = Encoding.ASCII.GetString(readBuffer, offset + 4, 36); + + var data = Encoding.UTF8.GetString(readBuffer, offset + 40, length - 40); + + return new MyUdpRequestInfo(key, sessionID) { Value = data }; + } + + public int LeftBufferSize + { + get { return 0; } + } + + public IRequestFilter NextRequestFilter + { + get { return this; } + } + } +} diff --git a/Test/Udp/MyUdpProtocol.cs b/Test/Udp/MyUdpProtocol.cs new file mode 100644 index 000000000..2637e7bdb --- /dev/null +++ b/Test/Udp/MyUdpProtocol.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Protocol; +using SuperSocket.SocketBase; + +namespace SuperSocket.Test.Udp +{ + class MyUdpProtocol : IRequestFilterFactory + { + public IRequestFilter CreateFilter(IAppServer appServer, ISocketSession socketSession) + { + return new MyRequestFilter(); + } + } +} diff --git a/Test/Udp/SESS.cs b/Test/Udp/SESS.cs new file mode 100644 index 000000000..a07df760d --- /dev/null +++ b/Test/Udp/SESS.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase.Command; + +namespace SuperSocket.Test.Udp +{ + public class SESS : CommandBase + { + public override void ExecuteCommand(UdpTestSession session, MyUdpRequestInfo requestInfo) + { + session.Send(session.SessionID + " " + requestInfo.Value); + } + } +} diff --git a/Test/Udp/UdpAppServer.cs b/Test/Udp/UdpAppServer.cs new file mode 100644 index 000000000..bc2040f8a --- /dev/null +++ b/Test/Udp/UdpAppServer.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.Dlr; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Config; +using SuperSocket.SocketBase.Logging; +using SuperSocket.SocketBase.Protocol; +using SuperSocket.SocketEngine; + +namespace SuperSocket.Test.Udp +{ + class UdpAppServer : AppServer, ITestSetup + { + public UdpAppServer() + : base(new DefaultRequestFilterFactory()) + { + + } + + void ITestSetup.Setup(IRootConfig rootConfig, IServerConfig serverConfig) + { + base.Setup(rootConfig, serverConfig, SocketServerFactory.Instance, null, new ConsoleLogFactory(), null); + } + } +} diff --git a/Test/Udp/UdpTestSession.cs b/Test/Udp/UdpTestSession.cs new file mode 100644 index 000000000..5a4e5d5d6 --- /dev/null +++ b/Test/Udp/UdpTestSession.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using SuperSocket.SocketBase; + +namespace SuperSocket.Test.Udp +{ + public class UdpTestSession : AppSession + { + + } +} diff --git a/Test/UdpSocketServerTest.cs b/Test/UdpSocketServerTest.cs new file mode 100644 index 000000000..426035998 --- /dev/null +++ b/Test/UdpSocketServerTest.cs @@ -0,0 +1,490 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Threading; +using NUnit.Framework; +using SuperSocket.Common; +using SuperSocket.SocketBase; +using SuperSocket.SocketBase.Command; +using SuperSocket.SocketBase.Config; +using SuperSocket.SocketBase.Protocol; +using SuperSocket.SocketEngine; +using SuperSocket.Test.Udp; +using SuperSocket.SocketBase.Logging; +using System.Threading.Tasks; + +namespace SuperSocket.Test +{ + public class MyUdpRequestInfo : UdpRequestInfo + { + public MyUdpRequestInfo(string key, string sessionID) + : base(key, sessionID) + { + + } + + public string Value { get; set; } + + public byte[] ToData() + { + List data = new List(); + + data.AddRange(Encoding.ASCII.GetBytes(Key)); + data.AddRange(Encoding.ASCII.GetBytes(SessionID)); + + int expectedLen = 36 + 4; + + if (data.Count < expectedLen) + { + for (var i = 0; i < expectedLen - data.Count; i++) + { + data.Add(0x00); + } + } + + data.AddRange(Encoding.UTF8.GetBytes(Value)); + + return data.ToArray(); + } + } + + [TestFixture] + public class UdpSocketServerTest + { + private TestServer m_Server; + private IServerConfig m_Config; + private IRootConfig m_RootConfig; + private Encoding m_Encoding; + + protected IServerConfig DefaultServerConfig + { + get + { + return new ServerConfig + { + Ip = "127.0.0.1", + LogCommand = true, + MaxConnectionNumber = 100, + Mode = SocketMode.Udp, + Name = "Udp Test Socket Server", + Port = 2196, + ClearIdleSession = true, + ClearIdleSessionInterval = 1, + IdleSessionTimeOut = 5, + SendingQueueSize = 100 + }; + } + } + + public UdpSocketServerTest() + { + m_Config = DefaultServerConfig; + m_RootConfig = new RootConfig(); + m_Encoding = new System.Text.UTF8Encoding(); + } + + [TestFixtureSetUp] + public void Setup() + { + m_Server = new TestServer(); + m_Server.Setup(m_RootConfig, m_Config, SocketServerFactory.Instance, null, new ConsoleLogFactory(), null, null); + } + + [TestFixtureTearDown] + [TearDown] + public void Stop() + { + StopServer(); + } + + protected Socket CreateClientSocket() + { + return new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); + } + + private void StartServer() + { + m_Server.Start(); + Console.WriteLine("The UDP Socket server is started!"); + } + + private void StopServer() + { + if (m_Server.IsRunning) + { + m_Server.Stop(); + Console.WriteLine("The UDP Socket server is stopped!"); + } + } + + [Test, Repeat(5)] + public void TestStartStop() + { + StartServer(); + Assert.IsTrue(m_Server.IsRunning); + + StopServer(); + Assert.IsFalse(m_Server.IsRunning); + } + + [Test, Timeout(10000)] + public void TestEchoMessage() + { + StartServer(); + + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port); + + using (Socket socket = CreateClientSocket()) + { + char[] chars = new char[] { 'a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F', 'g', 'G', 'h', 'H' }; + + Random rd = new Random(1); + + StringBuilder sb = new StringBuilder(); + + for (int i = 0; i < 100; i++) + { + sb.Append(chars[rd.Next(0, chars.Length - 1)]); + string command = sb.ToString(); + Console.WriteLine("Client prepare sent:" + command); + socket.SendTo(m_Encoding.GetBytes("ECHO " + command + Environment.NewLine), serverAddress); + Console.WriteLine("Client sent:" + command); + string echoMessage = m_Encoding.GetString(ReceiveMessage(socket, serverAddress).ToArray()); + Console.WriteLine("C:" + echoMessage); + Assert.AreEqual(command, echoMessage); + } + } + } + + [Test, Timeout(6000)] + public void TestUdpCommand() + { + var testServer = new UdpAppServer(); + + testServer.Setup(m_RootConfig, m_Config, SocketServerFactory.Instance); + + testServer.Start(); + + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port); + + using (Socket socket = CreateClientSocket()) + { + char[] chars = new char[] { 'a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F', 'g', 'G', 'h', 'H' }; + + Random rd = new Random(1); + + StringBuilder sb = new StringBuilder(); + + var sessionID = Guid.NewGuid().ToString(); + + for (int i = 0; i < 100; i++) + { + sb.Append(chars[rd.Next(0, chars.Length - 1)]); + string command = sb.ToString(); + + Console.WriteLine("Client prepare sent:" + command); + + var cmdInfo = new MyUdpRequestInfo("SESS", sessionID); + cmdInfo.Value = command; + + socket.SendTo(cmdInfo.ToData(), serverAddress); + + Console.WriteLine("Client sent:" + command); + + string[] res = m_Encoding.GetString(ReceiveMessage(socket, serverAddress).ToArray()).Split(' '); + + Assert.AreEqual(sessionID, res[0]); + Assert.AreEqual(command, res[1]); + } + } + + testServer.Stop(); + } + + [Test] + public void TestCommandCombining() + { + StartServer(); + + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port); + + using (Socket socket = CreateClientSocket()) + { + char[] chars = new char[] { 'a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F', 'g', 'G', 'h', 'H' }; + + Random rd = new Random(1); + + for (int j = 0; j < 10; j++) + { + StringBuilder sb = new StringBuilder(); + + List source = new List(5); + + StringBuilder sbCombile = new StringBuilder(); + + for (int i = 0; i < 5; i++) + { + sb.Append(chars[rd.Next(0, chars.Length - 1)]); + string command = sb.ToString(); + source.Add(command); + sbCombile.AppendLine("ECHO " + command); + } + + socket.SendTo(m_Encoding.GetBytes(sbCombile.ToString()), serverAddress); + + for (int i = 0; i < 5; i++) + { + byte[] receivedData = ReceiveMessage(socket, serverAddress).ToArray(); + string receivedContent = m_Encoding.GetString(receivedData); + StringReader reader = new StringReader(receivedContent); + string line = reader.ReadLine(); + Assert.AreEqual(source[i], line); + } + } + } + } + + private bool RunEchoMessage() + { + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port); + + using (Socket socket = CreateClientSocket()) + { + char[] chars = new char[] { 'a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F', 'g', 'G', 'h', 'H' }; + + Random rd = new Random(1); + + StringBuilder sb = new StringBuilder(); + + for (int i = 0; i < 10; i++) + { + sb.Append(chars[rd.Next(0, chars.Length - 1)]); + string command = sb.ToString(); + + socket.SendTo(m_Encoding.GetBytes("ECHO " + command + Environment.NewLine), serverAddress); + string echoMessage = m_Encoding.GetString(ReceiveMessage(socket, serverAddress).ToArray()); + if (!string.Equals(command, echoMessage)) + { + Console.WriteLine("Incorrect response: {0}, {1}", command, echoMessage); + return false; + } + + Thread.Sleep(100); + } + } + + return true; + } + + [Test] + public void TestConcurrencyCommunication() + { + StartServer(); + + int concurrencyCount = 64; + + bool[] resultArray = new bool[concurrencyCount]; + + Semaphore semaphore = new Semaphore(0, concurrencyCount); + + System.Threading.Tasks.Parallel.For(0, concurrencyCount, i => + { + resultArray[i] = RunEchoMessage(); + semaphore.Release(); + }); + + for (var i = 0; i < concurrencyCount; i++) + { + semaphore.WaitOne(); + Console.WriteLine("Got {0}", i); + } + + Assert.AreEqual(false, resultArray.Any(b => !b)); + } + + [Test, Repeat(2)] + public void TestUnknownCommand() + { + StartServer(); + + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port); + + using (Socket socket = CreateClientSocket()) + { + for (int i = 0; i < 10; i++) + { + string commandName = Guid.NewGuid().ToString().Substring(0, 3); + string command = commandName + " " + DateTime.Now; + socket.SendTo(m_Encoding.GetBytes(command + Environment.NewLine), serverAddress); + string line = m_Encoding.GetString(ReceiveMessage(socket, serverAddress).ToArray()); + Console.WriteLine(line); + Assert.AreEqual(string.Format(TestSession.UnknownCommandMessageFormat, commandName), line); + } + } + } + + [Test, Repeat(3)] + public void TestCustomCommandName() + { + StartServer(); + + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port); + + using (Socket socket = CreateClientSocket()) + { + string param = Guid.NewGuid().ToString(); + string command = "325 " + param + Environment.NewLine; + socket.SendTo(m_Encoding.GetBytes(command), serverAddress); + string echoMessage = m_Encoding.GetString(ReceiveMessage(socket, serverAddress).ToArray()); + Console.WriteLine("C:" + echoMessage); + Assert.AreEqual(string.Format(SuperSocket.Test.Command.NUM.ReplyFormat, param), echoMessage); + } + } + + [Test, Repeat(3)] + public void TestCommandParser() + { + var server = new TestServer(new TestRequestParser()); + server.Setup(m_RootConfig, m_Config, SocketServerFactory.Instance); + + try + { + server.Start(); + + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port); + + using (Socket socket = CreateClientSocket()) + { + string command = string.Format("Hello World ({0})!", Guid.NewGuid().ToString()); + socket.SendTo(m_Encoding.GetBytes("ECHO:" + command + Environment.NewLine), serverAddress); + string echoMessage = m_Encoding.GetString(ReceiveMessage(socket, serverAddress).ToArray()); + Assert.AreEqual(command, echoMessage); + } + } + catch (Exception e) + { + throw e; + } + finally + { + if (server.IsRunning) + server.Stop(); + } + } + + private bool TestMaxConnectionNumber(int maxConnectionNumber) + { + var server = new TestServer(); + var defaultConfig = DefaultServerConfig; + + var config = new ServerConfig + { + Ip = defaultConfig.Ip, + LogCommand = defaultConfig.LogCommand, + MaxConnectionNumber = maxConnectionNumber, + Mode = defaultConfig.Mode, + Name = defaultConfig.Name, + Port = defaultConfig.Port + }; + + server.Setup(m_RootConfig, config, SocketServerFactory.Instance); + + List sockets = new List(); + + try + { + server.Start(); + + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port); + + for (int i = 0; i < maxConnectionNumber; i++) + { + Socket socket = CreateClientSocket(); + socket.SendTo(m_Encoding.GetBytes(Guid.NewGuid().ToString() + Environment.NewLine), serverAddress); + Console.WriteLine("C: " + m_Encoding.GetString(ReceiveMessage(socket, serverAddress).ToArray())); + sockets.Add(socket); + } + + using (Socket trySocket = CreateClientSocket()) + { + trySocket.SendTo(m_Encoding.GetBytes(Guid.NewGuid().ToString() + Environment.NewLine), serverAddress); + Thread thread = new Thread(new ThreadStart(() => + { + Console.WriteLine("C: " + m_Encoding.GetString(ReceiveMessage(trySocket, serverAddress).ToArray())); + })); + thread.Start(); + if (thread.Join(500)) + { + //Assert.Fail("Current connection number: {0}, max connectionnumber: {1}", maxConnectionNumber + 1, maxConnectionNumber); + return false; + } + else + { + thread.Abort(); + return true; + } + } + } + catch (Exception e) + { + Console.WriteLine(e.Message + " " + e.StackTrace); + return false; + } + finally + { + server.Stop(); + } + } + + [Test] + public void TestMaxConnectionNumber() + { + Assert.IsTrue(TestMaxConnectionNumber(1)); + Assert.IsTrue(TestMaxConnectionNumber(2)); + Assert.IsTrue(TestMaxConnectionNumber(5)); + Assert.IsTrue(TestMaxConnectionNumber(15)); + } + + [Test, Repeat(5)] + public void TestClearTimeoutSession() + { + StartServer(); + + EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port); + + using (Socket socket = CreateClientSocket()) + { + string param = Guid.NewGuid().ToString(); + string command = "325 " + param + Environment.NewLine; + socket.SendTo(m_Encoding.GetBytes(command), serverAddress); + string echoMessage = m_Encoding.GetString(ReceiveMessage(socket, serverAddress).ToArray()); + Console.WriteLine("C:" + echoMessage); + } + + Assert.AreEqual(1, m_Server.SessionCount); + Thread.Sleep(2000); + Assert.AreEqual(1, m_Server.SessionCount); + Thread.Sleep(5000); + Assert.AreEqual(0, m_Server.SessionCount); + } + + private List ReceiveMessage(Socket socket, EndPoint serverAddress) + { + int length = 1024; + byte[] buffer = new byte[length]; + int read = socket.ReceiveFrom(buffer, ref serverAddress); + if (read < length) + return buffer.Take(read).ToList(); + else + { + var total = buffer.ToList(); + total.AddRange(ReceiveMessage(socket, serverAddress)); + return total; + } + } + } +} diff --git a/Test/supersocket.pfx b/Test/supersocket.pfx new file mode 100644 index 000000000..440c983c6 Binary files /dev/null and b/Test/supersocket.pfx differ diff --git a/WindowsAzure/AzureHost/AzureHost.ccproj b/WindowsAzure/AzureHost/AzureHost.ccproj new file mode 100644 index 000000000..88394a88f --- /dev/null +++ b/WindowsAzure/AzureHost/AzureHost.ccproj @@ -0,0 +1,53 @@ + + + + + Debug + AnyCPU + 1.5.0 + {ac0312ec-ae2c-44bb-bc1d-5d5ac210144b} + Library + Properties + AzureHost + AzureHost + True + AzureHost + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + SuperSocketRole + {552769f6-51e8-48c2-8ba7-857f7879eec9} + True + Worker + SuperSocketRole + + + + + 10.0 + $(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Windows Azure Tools\1.5\ + + + \ No newline at end of file diff --git a/WindowsAzure/AzureHost/ServiceConfiguration.cscfg b/WindowsAzure/AzureHost/ServiceConfiguration.cscfg new file mode 100644 index 000000000..30b5f10fd --- /dev/null +++ b/WindowsAzure/AzureHost/ServiceConfiguration.cscfg @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/WindowsAzure/AzureHost/ServiceDefinition.build.csdef b/WindowsAzure/AzureHost/ServiceDefinition.build.csdef new file mode 100644 index 000000000..e19b2e853 --- /dev/null +++ b/WindowsAzure/AzureHost/ServiceDefinition.build.csdef @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/WindowsAzure/AzureHost/ServiceDefinition.csdef b/WindowsAzure/AzureHost/ServiceDefinition.csdef new file mode 100644 index 000000000..9b26480b7 --- /dev/null +++ b/WindowsAzure/AzureHost/ServiceDefinition.csdef @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/WindowsAzure/Cloud.sln b/WindowsAzure/Cloud.sln new file mode 100644 index 000000000..3441bd470 --- /dev/null +++ b/WindowsAzure/Cloud.sln @@ -0,0 +1,67 @@ + +Microsoft Visual Studio Solution File, Format Version 11.00 +# Visual Studio 2010 +Project("{CC5FD16D-436D-48AD-A40C-5A424C6E3E79}") = "AzureHost", "AzureHost\AzureHost.ccproj", "{AC0312EC-AE2C-44BB-BC1D-5D5AC210144B}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocketRole", "SuperSocketRole\SuperSocketRole.csproj", "{552769F6-51E8-48C2-8BA7-857F7879EEC9}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SuperSocket", "SuperSocket", "{A59169C3-C141-42A9-B2FC-71908841E033}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "QuickStart", "QuickStart", "{17469CB9-FBD3-490C-B502-D7F9C5B5C632}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EchoService", "..\QuickStart\EchoService\EchoService.csproj", "{6967B4E6-474F-4D79-BD4D-BD701A8A6085}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RemoteProcessService", "..\QuickStart\RemoteProcessService\RemoteProcessService.csproj", "{CA67AA73-42D0-4A08-85C4-61FB569231A8}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocket.Common", "..\Common\SuperSocket.Common.csproj", "{A24F4D38-BA9C-4FD6-95B7-4980DE36131A}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocket.SocketBase", "..\SocketBase\SuperSocket.SocketBase.csproj", "{40B77789-EA11-4C05-8F52-86711D7BCAAF}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SuperSocket.SocketEngine", "..\SocketEngine\SuperSocket.SocketEngine.csproj", "{153FEF72-191C-43D9-BE71-2B351C7AC760}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {AC0312EC-AE2C-44BB-BC1D-5D5AC210144B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AC0312EC-AE2C-44BB-BC1D-5D5AC210144B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AC0312EC-AE2C-44BB-BC1D-5D5AC210144B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AC0312EC-AE2C-44BB-BC1D-5D5AC210144B}.Release|Any CPU.Build.0 = Release|Any CPU + {552769F6-51E8-48C2-8BA7-857F7879EEC9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {552769F6-51E8-48C2-8BA7-857F7879EEC9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {552769F6-51E8-48C2-8BA7-857F7879EEC9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {552769F6-51E8-48C2-8BA7-857F7879EEC9}.Release|Any CPU.Build.0 = Release|Any CPU + {6967B4E6-474F-4D79-BD4D-BD701A8A6085}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6967B4E6-474F-4D79-BD4D-BD701A8A6085}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6967B4E6-474F-4D79-BD4D-BD701A8A6085}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6967B4E6-474F-4D79-BD4D-BD701A8A6085}.Release|Any CPU.Build.0 = Release|Any CPU + {CA67AA73-42D0-4A08-85C4-61FB569231A8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {CA67AA73-42D0-4A08-85C4-61FB569231A8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {CA67AA73-42D0-4A08-85C4-61FB569231A8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {CA67AA73-42D0-4A08-85C4-61FB569231A8}.Release|Any CPU.Build.0 = Release|Any CPU + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A}.Release|Any CPU.Build.0 = Release|Any CPU + {40B77789-EA11-4C05-8F52-86711D7BCAAF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {40B77789-EA11-4C05-8F52-86711D7BCAAF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {40B77789-EA11-4C05-8F52-86711D7BCAAF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {40B77789-EA11-4C05-8F52-86711D7BCAAF}.Release|Any CPU.Build.0 = Release|Any CPU + {153FEF72-191C-43D9-BE71-2B351C7AC760}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {153FEF72-191C-43D9-BE71-2B351C7AC760}.Debug|Any CPU.Build.0 = Debug|Any CPU + {153FEF72-191C-43D9-BE71-2B351C7AC760}.Release|Any CPU.ActiveCfg = Release|Any CPU + {153FEF72-191C-43D9-BE71-2B351C7AC760}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A} = {A59169C3-C141-42A9-B2FC-71908841E033} + {40B77789-EA11-4C05-8F52-86711D7BCAAF} = {A59169C3-C141-42A9-B2FC-71908841E033} + {153FEF72-191C-43D9-BE71-2B351C7AC760} = {A59169C3-C141-42A9-B2FC-71908841E033} + {6967B4E6-474F-4D79-BD4D-BD701A8A6085} = {17469CB9-FBD3-490C-B502-D7F9C5B5C632} + {CA67AA73-42D0-4A08-85C4-61FB569231A8} = {17469CB9-FBD3-490C-B502-D7F9C5B5C632} + EndGlobalSection +EndGlobal diff --git a/WindowsAzure/SuperSocketRole/Properties/AssemblyInfo.cs b/WindowsAzure/SuperSocketRole/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..b7bafc959 --- /dev/null +++ b/WindowsAzure/SuperSocketRole/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +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("SuperSocketRole")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("SuperSocketRole")] +[assembly: AssemblyCopyright("Copyright © Microsoft 2011")] +[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)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("79ae8005-17a8-4d3d-9c41-cf57af1138e6")] + +// 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")] diff --git a/WindowsAzure/SuperSocketRole/SuperSocketRole.csproj b/WindowsAzure/SuperSocketRole/SuperSocketRole.csproj new file mode 100644 index 000000000..d81546870 --- /dev/null +++ b/WindowsAzure/SuperSocketRole/SuperSocketRole.csproj @@ -0,0 +1,142 @@ + + + + Debug + AnyCPU + 8.0.30703 + 2.0 + {552769F6-51E8-48C2-8BA7-857F7879EEC9} + Library + Properties + SuperSocket.SuperSocketRole + SuperSocket.SuperSocketRole + v4.0 + 512 + AnyCPU + Worker + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + AllRules.ruleset + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + AllRules.ruleset + + + + False + + + False + true + + + False + true + + + + + 3.5 + + + 3.5 + + + 3.5 + + + 4.0 + + + + + + + + + + + Designer + + + + + {A24F4D38-BA9C-4FD6-95B7-4980DE36131A} + SuperSocket.Common + + + {6967B4E6-474F-4D79-BD4D-BD701A8A6085} + EchoService + + + {CA67AA73-42D0-4A08-85C4-61FB569231A8} + RemoteProcessService + + + {40B77789-EA11-4C05-8F52-86711D7BCAAF} + SuperSocket.SocketBase + + + {153FEF72-191C-43D9-BE71-2B351C7AC760} + SuperSocket.SocketEngine + + + + + False + Microsoft .NET Framework 4 %28x86 and x64%29 + true + + + False + .NET Framework 3.5 SP1 Client Profile + false + + + False + .NET Framework 3.5 SP1 + false + + + False + Windows Installer 3.1 + true + + + + + \ No newline at end of file diff --git a/WindowsAzure/SuperSocketRole/WorkerRole.cs b/WindowsAzure/SuperSocketRole/WorkerRole.cs new file mode 100644 index 000000000..c709cc284 --- /dev/null +++ b/WindowsAzure/SuperSocketRole/WorkerRole.cs @@ -0,0 +1,137 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Threading; +using Microsoft.WindowsAzure; +using Microsoft.WindowsAzure.Diagnostics; +using Microsoft.WindowsAzure.ServiceRuntime; +using Microsoft.WindowsAzure.StorageClient; +using SuperSocket.Common; +using SuperSocket.Common.Logging; +using SuperSocket.SocketBase.Config; +using SuperSocket.SocketEngine; +using SuperSocket.SocketEngine.Configuration; +using SuperSocket.SocketBase; + +namespace SuperSocket.SuperSocketRole +{ + public class WorkerRole : RoleEntryPoint + { + private IBootstrap m_Bootstrap; + + public override void Run() + { + // This is a sample worker implementation. Replace with your logic. + Trace.WriteLine("SuperSocketRole entry point called", "Information"); + + while (true) + { + Thread.Sleep(10000); + Trace.WriteLine("Working", "Information"); + } + } + + public override bool OnStart() + { + // Set the maximum number of concurrent connections + ServicePointManager.DefaultConnectionLimit = 100; + + // For information on handling configuration changes + // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357. + + m_Bootstrap = new DefaultBootstrap(); + + var serverConfig = ConfigurationManager.GetSection("socketServer") as SocketServiceConfig; + + if (!m_Bootstrap.Initialize(serverConfig, ResolveServerConfig)) + { + Trace.WriteLine("Failed to initialize SuperSocket!", "Error"); + return false; + } + + var result = m_Bootstrap.Start(); + + switch (result) + { + case (StartResult.None): + Trace.WriteLine("No server is configured, please check you configuration!"); + return false; + + case (StartResult.Success): + Trace.WriteLine("The server has been started!"); + break; + + case (StartResult.Failed): + Trace.WriteLine("Failed to start SuperSocket server! Please check error log for more information!"); + return false; + + case (StartResult.PartialSuccess): + Trace.WriteLine("Some server instances were started successfully, but the others failed to start! Please check error log for more information!"); + break; + } + + return base.OnStart(); + } + + private IServerConfig ResolveServerConfig(IServerConfig serverConfig) + { + var config = new ServerConfig(); + serverConfig.CopyPropertiesTo(config); + + if (serverConfig.Port > 0) + { + var endPointKey = serverConfig.Name + "_" + serverConfig.Port; + var instanceEndpoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints[endPointKey]; + if (instanceEndpoint == null) + { + Trace.WriteLine(string.Format("Failed to find Input Endpoint configuration {0}!", endPointKey), "Error"); + return serverConfig; + } + + var ipEndpoint = instanceEndpoint.IPEndpoint; + config.Ip = ipEndpoint.Address.ToString(); + config.Port = ipEndpoint.Port; + } + + if(config.Listeners != null && config.Listeners.Any()) + { + var listeners = config.Listeners.ToArray(); + + var newListeners = new List(listeners.Length); + + for (var i = 0; i < listeners.Length; i++) + { + var listener = listeners[i]; + + var endPointKey = serverConfig.Name + "_" + listener.Port; + var instanceEndpoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints[endPointKey]; + if (instanceEndpoint == null) + { + Trace.WriteLine(string.Format("Failed to find Input Endpoint configuration {0}!", endPointKey), "Error"); + return serverConfig; + } + + var newListener = new ListenerConfig(); + newListener.Ip = instanceEndpoint.IPEndpoint.Address.ToString(); + newListener.Port = instanceEndpoint.IPEndpoint.Port; + newListener.Backlog = listener.Backlog; + + newListeners.Add(newListener); + } + + config.Listeners = newListeners; + } + + return config; + } + + public override void OnStop() + { + m_Bootstrap.Stop(); + base.OnStop(); + } + } +} diff --git a/WindowsAzure/SuperSocketRole/app.config b/WindowsAzure/SuperSocketRole/app.config new file mode 100644 index 000000000..b851f31a6 --- /dev/null +++ b/WindowsAzure/SuperSocketRole/app.config @@ -0,0 +1,31 @@ + + + +
+ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/supersocket.snk b/supersocket.snk new file mode 100644 index 000000000..06e794196 Binary files /dev/null and b/supersocket.snk differ