context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // The BigNumber class implements methods for formatting and parsing // big numeric values. To format and parse numeric values, applications should // use the Format and Parse methods provided by the numeric // classes (BigInteger). Those // Format and Parse methods share a common implementation // provided by this class, and are thus documented in detail here. // // Formatting // // The Format methods provided by the numeric classes are all of the // form // // public static String Format(XXX value, String format); // public static String Format(XXX value, String format, NumberFormatInfo info); // // where XXX is the name of the particular numeric class. The methods convert // the numeric value to a string using the format string given by the // format parameter. If the format parameter is null or // an empty string, the number is formatted as if the string "G" (general // format) was specified. The info parameter specifies the // NumberFormatInfo instance to use when formatting the number. If the // info parameter is null or omitted, the numeric formatting information // is obtained from the current culture. The NumberFormatInfo supplies // such information as the characters to use for decimal and thousand // separators, and the spelling and placement of currency symbols in monetary // values. // // Format strings fall into two categories: Standard format strings and // user-defined format strings. A format string consisting of a single // alphabetic character (A-Z or a-z), optionally followed by a sequence of // digits (0-9), is a standard format string. All other format strings are // used-defined format strings. // // A standard format string takes the form Axx, where A is an // alphabetic character called the format specifier and xx is a // sequence of digits called the precision specifier. The format // specifier controls the type of formatting applied to the number and the // precision specifier controls the number of significant digits or decimal // places of the formatting operation. The following table describes the // supported standard formats. // // C c - Currency format. The number is // converted to a string that represents a currency amount. The conversion is // controlled by the currency format information of the NumberFormatInfo // used to format the number. The precision specifier indicates the desired // number of decimal places. If the precision specifier is omitted, the default // currency precision given by the NumberFormatInfo is used. // // D d - Decimal format. This format is // supported for integral types only. The number is converted to a string of // decimal digits, prefixed by a minus sign if the number is negative. The // precision specifier indicates the minimum number of digits desired in the // resulting string. If required, the number will be left-padded with zeros to // produce the number of digits given by the precision specifier. // // E e Engineering (scientific) format. // The number is converted to a string of the form // "-d.ddd...E+ddd" or "-d.ddd...e+ddd", where each // 'd' indicates a digit (0-9). The string starts with a minus sign if the // number is negative, and one digit always precedes the decimal point. The // precision specifier indicates the desired number of digits after the decimal // point. If the precision specifier is omitted, a default of 6 digits after // the decimal point is used. The format specifier indicates whether to prefix // the exponent with an 'E' or an 'e'. The exponent is always consists of a // plus or minus sign and three digits. // // F f Fixed point format. The number is // converted to a string of the form "-ddd.ddd....", where each // 'd' indicates a digit (0-9). The string starts with a minus sign if the // number is negative. The precision specifier indicates the desired number of // decimal places. If the precision specifier is omitted, the default numeric // precision given by the NumberFormatInfo is used. // // G g - General format. The number is // converted to the shortest possible decimal representation using fixed point // or scientific format. The precision specifier determines the number of // significant digits in the resulting string. If the precision specifier is // omitted, the number of significant digits is determined by the type of the // number being converted (10 for int, 19 for long, 7 for // float, 15 for double, 19 for Currency, and 29 for // Decimal). Trailing zeros after the decimal point are removed, and the // resulting string contains a decimal point only if required. The resulting // string uses fixed point format if the exponent of the number is less than // the number of significant digits and greater than or equal to -4. Otherwise, // the resulting string uses scientific format, and the case of the format // specifier controls whether the exponent is prefixed with an 'E' or an // 'e'. // // N n Number format. The number is // converted to a string of the form "-d,ddd,ddd.ddd....", where // each 'd' indicates a digit (0-9). The string starts with a minus sign if the // number is negative. Thousand separators are inserted between each group of // three digits to the left of the decimal point. The precision specifier // indicates the desired number of decimal places. If the precision specifier // is omitted, the default numeric precision given by the // NumberFormatInfo is used. // // X x - Hexadecimal format. This format is // supported for integral types only. The number is converted to a string of // hexadecimal digits. The format specifier indicates whether to use upper or // lower case characters for the hexadecimal digits above 9 ('X' for 'ABCDEF', // and 'x' for 'abcdef'). The precision specifier indicates the minimum number // of digits desired in the resulting string. If required, the number will be // left-padded with zeros to produce the number of digits given by the // precision specifier. // // Some examples of standard format strings and their results are shown in the // table below. (The examples all assume a default NumberFormatInfo.) // // Value Format Result // 12345.6789 C $12,345.68 // -12345.6789 C ($12,345.68) // 12345 D 12345 // 12345 D8 00012345 // 12345.6789 E 1.234568E+004 // 12345.6789 E10 1.2345678900E+004 // 12345.6789 e4 1.2346e+004 // 12345.6789 F 12345.68 // 12345.6789 F0 12346 // 12345.6789 F6 12345.678900 // 12345.6789 G 12345.6789 // 12345.6789 G7 12345.68 // 123456789 G7 1.234568E8 // 12345.6789 N 12,345.68 // 123456789 N4 123,456,789.0000 // 0x2c45e x 2c45e // 0x2c45e X 2C45E // 0x2c45e X8 0002C45E // // Format strings that do not start with an alphabetic character, or that start // with an alphabetic character followed by a non-digit, are called // user-defined format strings. The following table describes the formatting // characters that are supported in user defined format strings. // // // 0 - Digit placeholder. If the value being // formatted has a digit in the position where the '0' appears in the format // string, then that digit is copied to the output string. Otherwise, a '0' is // stored in that position in the output string. The position of the leftmost // '0' before the decimal point and the rightmost '0' after the decimal point // determines the range of digits that are always present in the output // string. // // # - Digit placeholder. If the value being // formatted has a digit in the position where the '#' appears in the format // string, then that digit is copied to the output string. Otherwise, nothing // is stored in that position in the output string. // // . - Decimal point. The first '.' character // in the format string determines the location of the decimal separator in the // formatted value; any additional '.' characters are ignored. The actual // character used as a the decimal separator in the output string is given by // the NumberFormatInfo used to format the number. // // , - Thousand separator and number scaling. // The ',' character serves two purposes. First, if the format string contains // a ',' character between two digit placeholders (0 or #) and to the left of // the decimal point if one is present, then the output will have thousand // separators inserted between each group of three digits to the left of the // decimal separator. The actual character used as a the decimal separator in // the output string is given by the NumberFormatInfo used to format the // number. Second, if the format string contains one or more ',' characters // immediately to the left of the decimal point, or after the last digit // placeholder if there is no decimal point, then the number will be divided by // 1000 times the number of ',' characters before it is formatted. For example, // the format string '0,,' will represent 100 million as just 100. Use of the // ',' character to indicate scaling does not also cause the formatted number // to have thousand separators. Thus, to scale a number by 1 million and insert // thousand separators you would use the format string '#,##0,,'. // // % - Percentage placeholder. The presence of // a '%' character in the format string causes the number to be multiplied by // 100 before it is formatted. The '%' character itself is inserted in the // output string where it appears in the format string. // // E+ E- e+ e- - Scientific notation. // If any of the strings 'E+', 'E-', 'e+', or 'e-' are present in the format // string and are immediately followed by at least one '0' character, then the // number is formatted using scientific notation with an 'E' or 'e' inserted // between the number and the exponent. The number of '0' characters following // the scientific notation indicator determines the minimum number of digits to // output for the exponent. The 'E+' and 'e+' formats indicate that a sign // character (plus or minus) should always precede the exponent. The 'E-' and // 'e-' formats indicate that a sign character should only precede negative // exponents. // // \ - Literal character. A backslash character // causes the next character in the format string to be copied to the output // string as-is. The backslash itself isn't copied, so to place a backslash // character in the output string, use two backslashes (\\) in the format // string. // // 'ABC' "ABC" - Literal string. Characters // enclosed in single or double quotation marks are copied to the output string // as-is and do not affect formatting. // // ; - Section separator. The ';' character is // used to separate sections for positive, negative, and zero numbers in the // format string. // // Other - All other characters are copied to // the output string in the position they appear. // // For fixed point formats (formats not containing an 'E+', 'E-', 'e+', or // 'e-'), the number is rounded to as many decimal places as there are digit // placeholders to the right of the decimal point. If the format string does // not contain a decimal point, the number is rounded to the nearest // integer. If the number has more digits than there are digit placeholders to // the left of the decimal point, the extra digits are copied to the output // string immediately before the first digit placeholder. // // For scientific formats, the number is rounded to as many significant digits // as there are digit placeholders in the format string. // // To allow for different formatting of positive, negative, and zero values, a // user-defined format string may contain up to three sections separated by // semicolons. The results of having one, two, or three sections in the format // string are described in the table below. // // Sections: // // One - The format string applies to all values. // // Two - The first section applies to positive values // and zeros, and the second section applies to negative values. If the number // to be formatted is negative, but becomes zero after rounding according to // the format in the second section, then the resulting zero is formatted // according to the first section. // // Three - The first section applies to positive // values, the second section applies to negative values, and the third section // applies to zeros. The second section may be left empty (by having no // characters between the semicolons), in which case the first section applies // to all non-zero values. If the number to be formatted is non-zero, but // becomes zero after rounding according to the format in the first or second // section, then the resulting zero is formatted according to the third // section. // // For both standard and user-defined formatting operations on values of type // float and double, if the value being formatted is a NaN (Not // a Number) or a positive or negative infinity, then regardless of the format // string, the resulting string is given by the NaNSymbol, // PositiveInfinitySymbol, or NegativeInfinitySymbol property of // the NumberFormatInfo used to format the number. // // Parsing // // The Parse methods provided by the numeric classes are all of the form // // public static XXX Parse(String s); // public static XXX Parse(String s, int style); // public static XXX Parse(String s, int style, NumberFormatInfo info); // // where XXX is the name of the particular numeric class. The methods convert a // string to a numeric value. The optional style parameter specifies the // permitted style of the numeric string. It must be a combination of bit flags // from the NumberStyles enumeration. The optional info parameter // specifies the NumberFormatInfo instance to use when parsing the // string. If the info parameter is null or omitted, the numeric // formatting information is obtained from the current culture. // // Numeric strings produced by the Format methods using the Currency, // Decimal, Engineering, Fixed point, General, or Number standard formats // (the C, D, E, F, G, and N format specifiers) are guaranteed to be parseable // by the Parse methods if the NumberStyles.Any style is // specified. Note, however, that the Parse methods do not accept // NaNs or Infinities. // using System.Buffers; using System.Diagnostics; using System.Globalization; using System.Text; namespace System.Numerics { internal static class BigNumber { private const NumberStyles InvalidNumberStyles = ~(NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign | NumberStyles.AllowParentheses | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands | NumberStyles.AllowExponent | NumberStyles.AllowCurrencySymbol | NumberStyles.AllowHexSpecifier); private struct BigNumberBuffer { public StringBuilder digits; public int precision; public int scale; public bool sign; // negative sign exists public static BigNumberBuffer Create() { BigNumberBuffer number = new BigNumberBuffer(); number.digits = new StringBuilder(); return number; } } internal static bool TryValidateParseStyleInteger(NumberStyles style, out ArgumentException e) { // Check for undefined flags if ((style & InvalidNumberStyles) != 0) { e = new ArgumentException(SR.Format(SR.Argument_InvalidNumberStyles, nameof(style))); return false; } if ((style & NumberStyles.AllowHexSpecifier) != 0) { // Check for hex number if ((style & ~NumberStyles.HexNumber) != 0) { e = new ArgumentException(SR.Argument_InvalidHexStyle); return false; } } e = null; return true; } internal static bool TryParseBigInteger(string value, NumberStyles style, NumberFormatInfo info, out BigInteger result) { if (value == null) { result = default(BigInteger); return false; } return TryParseBigInteger(value.AsSpan(), style, info, out result); } internal static bool TryParseBigInteger(ReadOnlySpan<char> value, NumberStyles style, NumberFormatInfo info, out BigInteger result) { unsafe { result = BigInteger.Zero; ArgumentException e; if (!TryValidateParseStyleInteger(style, out e)) throw e; // TryParse still throws ArgumentException on invalid NumberStyles BigNumberBuffer bignumber = BigNumberBuffer.Create(); if (!FormatProvider.TryStringToBigInteger(value, style, info, bignumber.digits, out bignumber.precision, out bignumber.scale, out bignumber.sign)) return false; if ((style & NumberStyles.AllowHexSpecifier) != 0) { if (!HexNumberToBigInteger(ref bignumber, ref result)) { return false; } } else { if (!NumberToBigInteger(ref bignumber, ref result)) { return false; } } return true; } } internal static BigInteger ParseBigInteger(string value, NumberStyles style, NumberFormatInfo info) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return ParseBigInteger(value.AsSpan(), style, info); } internal static BigInteger ParseBigInteger(ReadOnlySpan<char> value, NumberStyles style, NumberFormatInfo info) { ArgumentException e; if (!TryValidateParseStyleInteger(style, out e)) throw e; BigInteger result = BigInteger.Zero; if (!TryParseBigInteger(value, style, info, out result)) { throw new FormatException(SR.Overflow_ParseBigInteger); } return result; } private static unsafe bool HexNumberToBigInteger(ref BigNumberBuffer number, ref BigInteger value) { if (number.digits == null || number.digits.Length == 0) return false; int len = number.digits.Length - 1; // Ignore trailing '\0' byte[] bits = new byte[(len / 2) + (len % 2)]; bool shift = false; bool isNegative = false; int bitIndex = 0; // Parse the string into a little-endian two's complement byte array // string value : O F E B 7 \0 // string index (i) : 0 1 2 3 4 5 <-- // byte[] (bitIndex): 2 1 1 0 0 <-- // for (int i = len - 1; i > -1; i--) { char c = number.digits[i]; byte b; if (c >= '0' && c <= '9') { b = (byte)(c - '0'); } else if (c >= 'A' && c <= 'F') { b = (byte)((c - 'A') + 10); } else { Debug.Assert(c >= 'a' && c <= 'f'); b = (byte)((c - 'a') + 10); } if (i == 0 && (b & 0x08) == 0x08) isNegative = true; if (shift) { bits[bitIndex] = (byte)(bits[bitIndex] | (b << 4)); bitIndex++; } else { bits[bitIndex] = isNegative ? (byte)(b | 0xF0) : (b); } shift = !shift; } value = new BigInteger(bits); return true; } private static unsafe bool NumberToBigInteger(ref BigNumberBuffer number, ref BigInteger value) { int i = number.scale; int cur = 0; BigInteger ten = 10; value = 0; while (--i >= 0) { value *= ten; if (number.digits[cur] != '\0') { value += number.digits[cur++] - '0'; } } while (number.digits[cur] != '\0') { if (number.digits[cur++] != '0') return false; // Disallow non-zero trailing decimal places } if (number.sign) { value = -value; } return true; } // This function is consistent with VM\COMNumber.cpp!COMNumber::ParseFormatSpecifier internal static char ParseFormatSpecifier(ReadOnlySpan<char> format, out int digits) { digits = -1; if (format.Length == 0) { return 'R'; } int i = 0; char ch = format[i]; if (ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z') { i++; int n = -1; if (i < format.Length && format[i] >= '0' && format[i] <= '9') { n = format[i++] - '0'; while (i < format.Length && format[i] >= '0' && format[i] <= '9') { n = n * 10 + (format[i++] - '0'); if (n >= 10) break; } } if (i >= format.Length || format[i] == '\0') { digits = n; return ch; } } return (char)0; // Custom format } private static string FormatBigIntegerToHex(bool targetSpan, BigInteger value, char format, int digits, NumberFormatInfo info, Span<char> destination, out int charsWritten, out bool spanSuccess) { Debug.Assert(format == 'x' || format == 'X'); // Get the bytes that make up the BigInteger. byte[] arrayToReturnToPool = null; Span<byte> bits = stackalloc byte[64]; // arbitrary threshold if (!value.TryWriteOrCountBytes(bits, out int bytesWrittenOrNeeded)) { bits = arrayToReturnToPool = ArrayPool<byte>.Shared.Rent(bytesWrittenOrNeeded); bool success = value.TryWriteBytes(bits, out bytesWrittenOrNeeded); Debug.Assert(success); } bits = bits.Slice(0, bytesWrittenOrNeeded); Span<char> stackSpace = stackalloc char[128]; // each byte is typically two chars var sb = new ValueStringBuilder(stackSpace); int cur = bits.Length - 1; if (cur > -1) { // [FF..F8] drop the high F as the two's complement negative number remains clear // [F7..08] retain the high bits as the two's complement number is wrong without it // [07..00] drop the high 0 as the two's complement positive number remains clear bool clearHighF = false; byte head = bits[cur]; if (head > 0xF7) { head -= 0xF0; clearHighF = true; } if (head < 0x08 || clearHighF) { // {0xF8-0xFF} print as {8-F} // {0x00-0x07} print as {0-7} sb.Append(head < 10 ? (char)(head + '0') : format == 'X' ? (char)((head & 0xF) - 10 + 'A') : (char)((head & 0xF) - 10 + 'a')); cur--; } } if (cur > -1) { Span<char> chars = sb.AppendSpan((cur + 1) * 2); int charsPos = 0; string hexValues = format == 'x' ? "0123456789abcdef" : "0123456789ABCDEF"; while (cur > -1) { byte b = bits[cur--]; chars[charsPos++] = hexValues[b >> 4]; chars[charsPos++] = hexValues[b & 0xF]; } } if (digits > sb.Length) { // Insert leading zeros, e.g. user specified "X5" so we create "0ABCD" instead of "ABCD" sb.Insert( 0, value._sign >= 0 ? '0' : (format == 'x') ? 'f' : 'F', digits - sb.Length); } if (arrayToReturnToPool != null) { ArrayPool<byte>.Shared.Return(arrayToReturnToPool); } if (targetSpan) { spanSuccess = sb.TryCopyTo(destination, out charsWritten); return null; } else { charsWritten = 0; spanSuccess = false; return sb.ToString(); } } internal static string FormatBigInteger(BigInteger value, string format, NumberFormatInfo info) { return FormatBigInteger(targetSpan: false, value, format, format, info, default, out _, out _); } internal static bool TryFormatBigInteger(BigInteger value, ReadOnlySpan<char> format, NumberFormatInfo info, Span<char> destination, out int charsWritten) { FormatBigInteger(targetSpan: true, value, null, format, info, destination, out charsWritten, out bool spanSuccess); return spanSuccess; } private static string FormatBigInteger( bool targetSpan, BigInteger value, string formatString, ReadOnlySpan<char> formatSpan, NumberFormatInfo info, Span<char> destination, out int charsWritten, out bool spanSuccess) { Debug.Assert(formatString == null || formatString.Length == formatSpan.Length); int digits = 0; char fmt = ParseFormatSpecifier(formatSpan, out digits); if (fmt == 'x' || fmt == 'X') { return FormatBigIntegerToHex(targetSpan, value, fmt, digits, info, destination, out charsWritten, out spanSuccess); } if (value._bits == null) { if (fmt == 'g' || fmt == 'G' || fmt == 'r' || fmt == 'R') { formatSpan = formatString = digits > 0 ? string.Format("D{0}", digits) : "D"; } if (targetSpan) { spanSuccess = value._sign.TryFormat(destination, out charsWritten, formatSpan, info); return null; } else { charsWritten = 0; spanSuccess = false; return value._sign.ToString(formatString, info); } } // First convert to base 10^9. const uint kuBase = 1000000000; // 10^9 const int kcchBase = 9; int cuSrc = value._bits.Length; int cuMax; try { cuMax = checked(cuSrc * 10 / 9 + 2); } catch (OverflowException e) { throw new FormatException(SR.Format_TooLarge, e); } uint[] rguDst = new uint[cuMax]; int cuDst = 0; for (int iuSrc = cuSrc; --iuSrc >= 0;) { uint uCarry = value._bits[iuSrc]; for (int iuDst = 0; iuDst < cuDst; iuDst++) { Debug.Assert(rguDst[iuDst] < kuBase); ulong uuRes = NumericsHelpers.MakeUlong(rguDst[iuDst], uCarry); rguDst[iuDst] = (uint)(uuRes % kuBase); uCarry = (uint)(uuRes / kuBase); } if (uCarry != 0) { rguDst[cuDst++] = uCarry % kuBase; uCarry /= kuBase; if (uCarry != 0) rguDst[cuDst++] = uCarry; } } int cchMax; try { // Each uint contributes at most 9 digits to the decimal representation. cchMax = checked(cuDst * kcchBase); } catch (OverflowException e) { throw new FormatException(SR.Format_TooLarge, e); } bool decimalFmt = (fmt == 'g' || fmt == 'G' || fmt == 'd' || fmt == 'D' || fmt == 'r' || fmt == 'R'); if (decimalFmt) { if (digits > 0 && digits > cchMax) cchMax = digits; if (value._sign < 0) { try { // Leave an extra slot for a minus sign. cchMax = checked(cchMax + info.NegativeSign.Length); } catch (OverflowException e) { throw new FormatException(SR.Format_TooLarge, e); } } } int rgchBufSize; try { // We'll pass the rgch buffer to native code, which is going to treat it like a string of digits, so it needs // to be null terminated. Let's ensure that we can allocate a buffer of that size. rgchBufSize = checked(cchMax + 1); } catch (OverflowException e) { throw new FormatException(SR.Format_TooLarge, e); } char[] rgch = new char[rgchBufSize]; int ichDst = cchMax; for (int iuDst = 0; iuDst < cuDst - 1; iuDst++) { uint uDig = rguDst[iuDst]; Debug.Assert(uDig < kuBase); for (int cch = kcchBase; --cch >= 0;) { rgch[--ichDst] = (char)('0' + uDig % 10); uDig /= 10; } } for (uint uDig = rguDst[cuDst - 1]; uDig != 0;) { rgch[--ichDst] = (char)('0' + uDig % 10); uDig /= 10; } if (!decimalFmt) { // sign = true for negative and false for 0 and positive values bool sign = (value._sign < 0); // The cut-off point to switch (G)eneral from (F)ixed-point to (E)xponential form int precision = 29; int scale = cchMax - ichDst; Span<char> stackSpace = stackalloc char[128]; // arbitrary stack cut-off var sb = new ValueStringBuilder(stackSpace); FormatProvider.FormatBigInteger(ref sb, precision, scale, sign, formatSpan, info, rgch, ichDst); if (targetSpan) { spanSuccess = sb.TryCopyTo(destination, out charsWritten); return null; } else { charsWritten = 0; spanSuccess = false; return sb.ToString(); } } // Format Round-trip decimal // This format is supported for integral types only. The number is converted to a string of // decimal digits (0-9), prefixed by a minus sign if the number is negative. The precision // specifier indicates the minimum number of digits desired in the resulting string. If required, // the number is padded with zeros to its left to produce the number of digits given by the // precision specifier. int numDigitsPrinted = cchMax - ichDst; while (digits > 0 && digits > numDigitsPrinted) { // pad leading zeros rgch[--ichDst] = '0'; digits--; } if (value._sign < 0) { string negativeSign = info.NegativeSign; for (int i = info.NegativeSign.Length - 1; i > -1; i--) rgch[--ichDst] = info.NegativeSign[i]; } int resultLength = cchMax - ichDst; if (!targetSpan) { charsWritten = 0; spanSuccess = false; return new string(rgch, ichDst, cchMax - ichDst); } else if (new ReadOnlySpan<char>(rgch, ichDst, cchMax - ichDst).TryCopyTo(destination)) { charsWritten = resultLength; spanSuccess = true; return null; } else { charsWritten = 0; spanSuccess = false; return null; } } } }
using Loon.Core; using System.Collections.Generic; using Loon.Utils; namespace Loon.Action.Collision { public class GravityHandler : LRelease { public interface GravityUpdate { void Action(Gravity g, float x, float y); } private GravityUpdate listener; private int width, height; private int bindWidth; private int bindHeight; private float bindX; private float bindY; private float velocityX, velocityY; internal bool isBounded; internal bool isListener; internal bool isEnabled; internal Gravity[] lazyObjects; internal List<Gravity> objects; internal List<Gravity> pendingAdd; internal List<Gravity> pendingRemove; public GravityHandler():this(LSystem.screenRect.width, LSystem.screenRect.height) { } public GravityHandler(int w, int h) { this.SetLimit(w, h); this.objects = new List<Gravity>(10); this.pendingAdd = new List<Gravity>(10); this.pendingRemove = new List<Gravity>(10); this.lazyObjects = new Gravity[] {}; this.isEnabled = true; } public bool IsGravityRunning() { if (objects != null) { foreach (Gravity g in objects) { if (g != null && !g.enabled) { return true; } } } return false; } public void SetLimit(int w, int h) { this.width = w; this.height = h; } public void Update(long elapsedTime) { if (!isEnabled) { return; } Commits(); float second = elapsedTime / 1000f; foreach (Gravity g in lazyObjects) { if (g.enabled && g.bind != null) { float accelerationX = g.accelerationX; float accelerationY = g.accelerationY; float angularVelocity = g.angularVelocity; bindWidth = g.bind.GetWidth(); bindHeight = g.bind.GetHeight(); bindX = g.bind.GetX(); bindY = g.bind.GetY(); if (angularVelocity != 0) { float rotate = g.bind.GetRotation() + angularVelocity * second; int[] newObjectRect = MathUtils.GetLimit(bindX, bindY, bindWidth, bindHeight, rotate); bindWidth = newObjectRect[2]; bindHeight = newObjectRect[3]; newObjectRect = null; g.bind.SetRotation(rotate); } if (accelerationX != 0 || accelerationY != 0) { g.velocityX += accelerationX * second; g.velocityY += accelerationY * second; } velocityX = g.velocityX; velocityY = g.velocityY; if (velocityX != 0 || velocityY != 0) { velocityX = bindX + velocityX * second; velocityY = bindY + velocityY * second; if (isBounded) { if (g.g != 0) { velocityY += g.gadd; g.gadd += g.g; } if (g.bounce != 0) { int limitWidth = width - bindWidth; int limitHeight = height - bindHeight; bool chageWidth = bindX >= limitWidth; bool chageHeight = bindY >= limitHeight; if (chageWidth) { bindX -= g.bounce + g.g; if (g.bounce > 0) { g.bounce -= (g.bounce / MathUtils.Random(1, 5)) + second; } else if (g.bounce < 0) { g.bounce = 0; bindX = limitWidth; } } if (chageHeight) { bindY -= g.bounce + g.g; if (g.bounce > 0) { g.bounce -= (g.bounce / MathUtils.Random(1, 5)) + second; } else if (g.bounce < 0) { g.bounce = 0; bindY = limitHeight; } } if (chageWidth || chageHeight) { g.bind.SetLocation(bindX, bindY); if (isListener) { listener.Action(g, bindX, bindY); } return; } } velocityX = LimitValue(velocityX, width - bindWidth); velocityY = LimitValue(velocityY, height - bindHeight); } g.bind.SetLocation(velocityX, velocityY); if (isListener) { listener.Action(g, velocityX, velocityY); } } } } } private float LimitValue(float value_ren, float limit) { if (value_ren < 0) { value_ren = 0; } if (limit < value_ren) { value_ren = limit; } return value_ren; } public void Commits() { bool changes = false; int additionCount = pendingAdd.Count; if (additionCount > 0) { Gravity[] additionsArray = pendingAdd.ToArray(); for (int i = 0; i < additionCount; i++) { Gravity obj0 = additionsArray[i]; CollectionUtils.Add(objects, obj0); } CollectionUtils.Clear(pendingAdd); changes = true; } int removalCount = pendingRemove.Count; if (removalCount > 0) { object[] removalsArray = CollectionUtils.ToArray(pendingRemove); for (int i_0 = 0; i_0 < removalCount; i_0++) { Gravity object_1 = (Gravity)removalsArray[i_0]; CollectionUtils.Remove(objects, object_1); } CollectionUtils.Clear(pendingRemove); changes = true; } if (changes) { lazyObjects = objects.ToArray(); } } public Gravity[] GetObjects() { return lazyObjects; } public int GetCount() { return lazyObjects.Length; } public int GetConcreteCount() { return lazyObjects.Length + pendingAdd.Count - pendingRemove.Count; } public Gravity Get(int index) { return lazyObjects[index]; } public Gravity Add(ActionBind o, float vx, float vy) { return Add(o, vx, vy, 0); } public Gravity Add(ActionBind o, float vx, float vy, float ave) { return Add(o, vx, vy, 0, 0, ave); } public Gravity Add(ActionBind o, float vx, float vy, float ax, float ay, float ave) { Gravity g = new Gravity(o); g.velocityX = vx; g.velocityY = vy; g.accelerationX = ax; g.accelerationY = ay; g.angularVelocity = ave; Add(g); return g; } public void Add(Gravity obj0) { CollectionUtils.Add(pendingAdd,obj0); } public void Remove(Gravity obj0) { CollectionUtils.Add(pendingRemove,obj0); } public void RemoveAll() { int count = objects.Count; object[] objectArray = CollectionUtils.ToArray(objects); for (int i = 0; i < count; i++) { CollectionUtils.Add(pendingRemove,(Gravity) objectArray[i]); } CollectionUtils.Clear(pendingAdd); } public Gravity GetObject(string name) { Commits(); foreach (Gravity obj0 in lazyObjects) { if (obj0 != null) { if (obj0.name != null) { if (obj0.name.Equals(name)) { return obj0; } } } } return null; } public bool IsEnabled() { return isEnabled; } public void SetEnabled(bool isEnabled_0) { this.isEnabled = isEnabled_0; } public bool IsBounded() { return isBounded; } public void SetBounded(bool isBounded_0) { this.isBounded = isBounded_0; } public bool IsListener() { return isListener; } public void OnUpdate(GravityUpdate l) { this.listener = l; if (l != null) { isListener = true; } else { isListener = false; } } public void Dispose() { this.isEnabled = false; if (objects != null) { CollectionUtils.Clear(objects); objects = null; } if (pendingAdd != null) { CollectionUtils.Clear(pendingAdd); pendingAdd = null; } if (pendingAdd != null) { CollectionUtils.Clear(pendingAdd); pendingAdd = null; } if (lazyObjects != null) { foreach (Gravity g in lazyObjects) { if (g != null) { g.Dispose(); } } } } } }
using System; using System.IO; using System.Text; using Microsoft.SPOT; using Microsoft.SPOT.Presentation.Media; using Skewworks.NETMF; using Skewworks.NETMF.Controls; using Skewworks.NETMF.Resources; namespace Skewworks.VDS.Clix { public class Design { #region Public Methods public static Form LoadForm(string filename) { FileStream fs = null; try { fs = new FileStream(filename, FileMode.Open, FileAccess.Read); var b = new byte[4]; // Read header fs.Read(b, 0, b.Length); if (new string(Encoding.UTF8.GetChars(b)) != "CLiX") throw new Exception("Invalid header"); // Read Version fs.Read(b, 0, b.Length); if (b[0] != 2 || b[1] != 2) throw new Exception("Invalid version"); // Load Form return _LoadForm(fs); } catch (Exception) { if (fs != null) fs.Dispose(); } return null; } public static Form LoadForm(byte[] data) { var ms = new MemoryStream(data); var b = new byte[4]; // Read header ms.Read(b, 0, b.Length); if (new string(Encoding.UTF8.GetChars(b)) != "TnkR" && new string(Encoding.UTF8.GetChars(b)) != "CLiX") throw new Exception("Invalid header"); // Read Version ms.Read(b, 0, b.Length); if (b[0] != 2 || b[1] != 2) throw new Exception("Invalid version"); // Load Form return _LoadForm(ms); } #endregion #region Load Methods static void LoadChildren(Stream fs, IContainer parent) { while (true) { int id = fs.ReadByte(); switch (id) { case 0: // Button parent.AddChild(LoadButton(fs)); break; case 1: // Checkbox parent.AddChild(LoadCheckbox(fs)); break; case 2: // Combobox parent.AddChild(LoadCombobox(fs)); break; case 3: // Filebox parent.AddChild(LoadFilebox(fs)); break; case 5: // Label parent.AddChild(LoadLabel(fs)); break; case 6: // Listbox parent.AddChild(LoadListbox(fs)); break; case 7: // ListboxItem break; case 8: // MenuStrip parent.AddChild(LoadMenuStrip(fs)); break; case 9: // MenuItem parent.AddChild(LoadMenuItem(fs)); break; case 10: // NumericUpDown parent.AddChild(LoadNumericUpDown(fs)); break; case 11: // Panel parent.AddChild(LoadPanel(fs)); break; case 12: // Picturebox parent.AddChild(LoadPicturebox(fs)); break; case 13: // Progressbar parent.AddChild(LoadProgressbar(fs)); break; case 14: // RadioButton parent.AddChild(LoadRadioButton(fs)); break; case 15: // RichTextLabel parent.AddChild(LoadRichTextLabel(fs)); break; case 16: // Scrollbar parent.AddChild(LoadScrollbar(fs)); break; case 17: // Slider parent.AddChild(LoadSlider(fs)); break; case 18: // Tab break; case 19: // TabDialog parent.AddChild(LoadTabDialog(fs)); break; case 20: // Textbox parent.AddChild(LoadTextbox(fs)); break; case 21: // Treeview parent.AddChild(LoadTreeview(fs)); break; case 22: // TreviewNode break; case 255: // End of Container return; default: // Unknown/Invalid throw new Exception("Control Ident failure (" + id + ")"); } } } static Button LoadButton(Stream fs) { var btn = new Button(ReadString(fs), ReadString(fs), ReadFont(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs), ReadBool(fs)) { Enabled = ReadBool(fs), Visible = ReadBool(fs), BorderColor = ReadColor(fs), BorderColorPressed = ReadColor(fs), NormalColorBottom = ReadColor(fs), NormalColorTop = ReadColor(fs), NormalTextColor = ReadColor(fs), PressedColorBottom = ReadColor(fs), PressedColorTop = ReadColor(fs), PressedTextColor = ReadColor(fs), BackgroundImageImageScaleModeMode = ReadScaleMode(fs), BackgroundImage = ReadImage(fs) }; return btn; } static Checkbox LoadCheckbox(Stream fs) { var obj = new Checkbox(ReadString(fs), ReadString(fs), ReadFont(fs), ReadInt(fs), ReadInt(fs), ReadBool(fs)) { Enabled = ReadBool(fs), Visible = ReadBool(fs), Width = ReadInt(fs), Height = ReadInt(fs), BackgroundBottom = ReadColor(fs), BackgroundTop = ReadColor(fs), BorderColor = ReadColor(fs), ForeColor = ReadColor(fs), MarkColor = ReadColor(fs), MarkSelectedColor = ReadColor(fs) }; return obj; } static Combobox LoadCombobox(Stream fs) { var obj = new Combobox(ReadString(fs), ReadFont(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs), ReadBool(fs)) { Enabled = ReadBool(fs), Visible = ReadBool(fs), ZebraStripe = ReadBool(fs), ZebraStripeColor = ReadColor(fs), Items = new ListboxItem[ReadInt(fs)] }; for (int i = 0; i < obj.Items.Length; i++) { if (fs.ReadByte() != 7) throw new Exception("Invalid item type; expected 7"); obj.Items[i] = new ListboxItem(ReadString(fs), ReadFont(fs), ReadColor(fs), ReadImage(fs), ReadBool(fs), ReadBool(fs)); } return obj; } static Filebox LoadFilebox(Stream fs) { var obj = new Filebox(ReadString(fs), ReadString(fs), ReadFont(fs), (FileListMode)fs.ReadByte(), ReadInt(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs)) { Enabled = ReadBool(fs), Visible = ReadBool(fs), AutoNavigate = ReadBool(fs) }; return obj; } static Form _LoadForm(Stream fs) { if (fs.ReadByte() != 4) throw new Exception("Invalid control type"); var frm = new Form(ReadString(fs)) { BackColor = ReadColor(fs), Enabled = ReadBool(fs), BackgroundImageScaleMode = ReadScaleMode(fs), BackgroundImage = ReadImage(fs) }; LoadChildren(fs, frm); return frm; } static Label LoadLabel(Stream fs) { var obj = new Label(ReadString(fs), ReadString(fs), ReadFont(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs), ReadColor(fs), ReadBool(fs)) { Enabled = ReadBool(fs), Visible = ReadBool(fs), AutoSize = ReadBool(fs), BackColor = ReadColor(fs), TextAlignment = (HorizontalAlignment)fs.ReadByte() }; return obj; } static Listbox LoadListbox(Stream fs) { var obj = new Listbox(ReadString(fs), ReadFont(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs), ReadBool(fs), ReadBool(fs), ReadSize(fs)) { Enabled = ReadBool(fs), Visible = ReadBool(fs), BackColor = ReadColor(fs), MinimumLineHeight = ReadInt(fs), SelectedBackColor = ReadColor(fs), SelectedTextColor = ReadColor(fs), ZebraStripe = ReadBool(fs), ZebraStripeColor = ReadColor(fs) }; int len = ReadInt(fs); for (int i = 0; i < len; i++) { if (fs.ReadByte() != 7) throw new Exception("Invalid item type; expected 7"); obj.AddItem(new ListboxItem(ReadString(fs), ReadFont(fs), ReadColor(fs), ReadImage(fs), ReadBool(fs), ReadBool(fs))); } return obj; } static MenuStrip LoadMenuStrip(Stream fs) { var obj = new MenuStrip(ReadString(fs), ReadFont(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs)) { Enabled = ReadBool(fs), Visible = ReadBool(fs) }; int len = ReadInt(fs); for (int i = 0; i < len; i++) obj.AddMenuItem(LoadMenuItem(fs)); return obj; } static MenuItem LoadMenuItem(Stream fs) { if (fs.ReadByte() != 9) throw new Exception("Invalid item type; expected 9"); var obj = new MenuItem(ReadString(fs), ReadString(fs)) { Enabled = ReadBool(fs), Visible = ReadBool(fs) }; int len = ReadInt(fs); for (int i = 0; i < len; i++) obj.AddMenuItem(LoadMenuItem(fs)); return obj; } static NumericUpDown LoadNumericUpDown(Stream fs) { var obj = new NumericUpDown(ReadString(fs), ReadFont(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs), ReadBool(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs)) { Enabled = ReadBool(fs), Visible = ReadBool(fs), BackgroundBottom = ReadColor(fs), BackgroundTop = ReadColor(fs), ButtonBackgroundBottom = ReadColor(fs), ButtonBackgroundTop = ReadColor(fs), ButtonTextColor = ReadColor(fs), ButtonTextShadowColor = ReadColor(fs), DisabledTextColor = ReadColor(fs), TextColor = ReadColor(fs) }; return obj; } static Panel LoadPanel(Stream fs) { var obj = new Panel(ReadString(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs), ReadColor(fs)) { Enabled = ReadBool(fs), Visible = ReadBool(fs), AutoScroll = ReadBool(fs), BackgroundImageScaleMode = ReadScaleMode(fs), BackgroundImage = ReadImage(fs) }; LoadChildren(fs, obj); return obj; } static Picturebox LoadPicturebox(Stream fs) { var obj = new Picturebox(ReadString(fs), ReadImage(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs), ReadColor(fs), false, (BorderStyle)fs.ReadByte(), ReadScaleMode(fs)) { Enabled = ReadBool(fs), Visible = ReadBool(fs), AutoSize = ReadBool(fs) }; return obj; } static Progressbar LoadProgressbar(Stream fs) { var obj = new Progressbar(ReadString(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs)) { Enabled = ReadBool(fs), Visible = ReadBool(fs), BackColor = ReadColor(fs), BorderColor = ReadColor(fs), GradientBottom = ReadColor(fs), GradientTop = ReadColor(fs), ProgressAlign = (HorizontalAlignment)fs.ReadByte() }; return obj; } static RadioButton LoadRadioButton(Stream fs) { var obj = new RadioButton(ReadString(fs), ReadString(fs), ReadFont(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs), ReadString(fs), ReadBool(fs)) { Enabled = ReadBool(fs), Visible = ReadBool(fs), Width = ReadInt(fs) }; return obj; } static RichTextLabel LoadRichTextLabel(Stream fs) { var obj = new RichTextLabel(ReadString(fs), ReadString(fs), Fonts.Droid11, Colors.Black, ReadInt(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs)) { Enabled = ReadBool(fs), Visible = ReadBool(fs) }; return obj; } static Scrollbar LoadScrollbar(Stream fs) { var obj = new Scrollbar(ReadString(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs), (Orientation)fs.ReadByte(), ReadInt(fs), ReadInt(fs), ReadInt(fs)) { Enabled = ReadBool(fs), Visible = ReadBool(fs), AutoRepeating = ReadBool(fs), LargeChange = ReadInt(fs), SmallChange = ReadInt(fs) }; return obj; } static Slider LoadSlider(Stream fs) { var obj = new Slider(ReadString(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs), (Orientation)fs.ReadByte(), ReadInt(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs)) { Enabled = ReadBool(fs), Visible = ReadBool(fs), BackColor = ReadColor(fs), GradientBottom = ReadColor(fs), GradientTop = ReadColor(fs), LargeChange = ReadInt(fs) }; return obj; } static TabDialog LoadTabDialog(Stream fs) { var obj = new TabDialog(ReadString(fs), ReadFont(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs)) { Enabled = ReadBool(fs), Visible = ReadBool(fs), ForeColor = ReadColor(fs) }; int len = ReadInt(fs); for (int i = 0; i < len; i++) { if (fs.ReadByte() != 18) throw new Exception("Invalid item type; expected 18"); var t = new Tab("tab" + i, ReadString(fs)); LoadChildren(fs, t); obj.AddChild(t); } return obj; } static Textbox LoadTextbox(Stream fs) { var obj = new Textbox(ReadString(fs), ReadString(fs), ReadFont(fs), ReadColor(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs), (char)fs.ReadByte(), ReadBool(fs)) { Enabled = ReadBool(fs), Visible = ReadBool(fs), EditorFont = ReadFont(fs), EditorLayout = (KeyboardLayout)fs.ReadByte(), EditorTitle = ReadString(fs), ShowCaret = ReadBool(fs) }; return obj; } static Treeview LoadTreeview(Stream fs) { var obj = new Treeview(ReadString(fs), ReadFont(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs), ReadInt(fs)) { Enabled = ReadBool(fs), Visible = ReadBool(fs), SelectedTextColor = ReadColor(fs), TextColor = ReadColor(fs) }; int len = ReadInt(fs); for (int i = 0; i < len; i++) obj.AddNode(LoadTreeviewNode(fs)); return obj; } static TreeviewNode LoadTreeviewNode(Stream fs) { if (fs.ReadByte() != 21) throw new Exception("Invalid item type; expected 21"); var obj = new TreeviewNode(ReadString(fs)) { Expanded = ReadBool(fs) }; int len = ReadInt(fs); for (int i = 0; i < len; i++) obj.AddNode(LoadTreeviewNode(fs)); return obj; } #endregion #region IO Methods static bool ReadBool(Stream fs) { if (fs.ReadByte() == 1) return true; return false; } static Color ReadColor(Stream fs) { return ColorUtility.ColorFromRGB((byte)fs.ReadByte(), (byte)fs.ReadByte(), (byte)fs.ReadByte()); } static Font ReadFont(Stream fs) { switch (fs.ReadByte()) { case 0: return Fonts.Droid8; case 1: return Fonts.Droid8Bold; case 2: return Fonts.Droid8BoldItalic; case 3: return Fonts.Droid8Italic; case 10: return Fonts.Droid9; case 11: return Fonts.Droid9Bold; case 12: return Fonts.Droid9BoldItalic; case 13: return Fonts.Droid9Italic; case 20: return Fonts.Droid11; case 21: return Fonts.Droid11Bold; case 22: return Fonts.Droid11BoldItalic; case 23: return Fonts.Droid11Italic; case 30: return Fonts.Droid12; case 31: return Fonts.Droid12Bold; case 32: return Fonts.Droid12BoldItalic; case 33: return Fonts.Droid12Italic; case 40: return Fonts.Droid16; case 41: return Fonts.Droid16Bold; case 42: return Fonts.Droid16BoldItalic; case 43: return Fonts.Droid16Italic; default: return null; } } static Bitmap ReadImage(Stream fs) { int len = ReadInt(fs); if (len == 0) return null; Debug.GC(true); var b = new byte[len]; fs.Read(b, 0, b.Length); Bitmap bmp = Core.ImageFromBytes(b); Debug.GC(true); return bmp; } static int ReadInt(Stream fs) { var b = new byte[4]; fs.Read(b, 0, b.Length); int i = b[0] << 24; i += b[1] << 16; i += b[2] << 8; i += b[3]; return i; } static ScaleMode ReadScaleMode(Stream fs) { return (ScaleMode)fs.ReadByte(); } static size ReadSize(Stream fs) { return new size(ReadInt(fs), ReadInt(fs)); } static string ReadString(Stream fs) { int len = ReadInt(fs); var b = new byte[len]; fs.Read(b, 0, b.Length); return new string(Encoding.UTF8.GetChars(b)); } #endregion } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore.TestUtilities; using Xunit; // ReSharper disable StringStartsWithIsCultureSpecific // ReSharper disable VirtualMemberCallInConstructor // ReSharper disable ClassNeverInstantiated.Local // ReSharper disable UnusedAutoPropertyAccessor.Local // ReSharper disable InconsistentNaming namespace Microsoft.EntityFrameworkCore { public class MySqlEndToEndTest : IClassFixture<MySqlFixture> { private const string DatabaseName = "MySqlEndToEndTest"; protected MySqlFixture Fixture { get; } public MySqlEndToEndTest(MySqlFixture fixture) { Fixture = fixture; Fixture.TestSqlLoggerFactory.Clear(); } [Fact] public void Can_use_decimal_and_byte_as_identity_columns() { using (var testDatabase = MySqlTestStore.CreateInitialized(DatabaseName)) { var nownNum1 = new NownNum { Id = 77.0m, TheWalrus = "Crying" }; var nownNum2 = new NownNum { Id = 78.0m, TheWalrus = "Walrus" }; var numNum1 = new NumNum { TheWalrus = "I" }; var numNum2 = new NumNum { TheWalrus = "Am" }; var anNum1 = new AnNum { TheWalrus = "Goo goo" }; var anNum2 = new AnNum { TheWalrus = "g'joob" }; var adNum1 = new AdNum { TheWalrus = "Eggman" }; var adNum2 = new AdNum { TheWalrus = "Eggmen" }; var byteNownNum1 = new ByteNownNum { Id = 77, Lucy = "Tangerine" }; var byteNownNum2 = new ByteNownNum { Id = 78, Lucy = "Trees" }; var byteNum1 = new ByteNum { Lucy = "Marmalade" }; var byteNum2 = new ByteNum { Lucy = "Skies" }; var byteAnNum1 = new ByteAnNum { Lucy = "Cellophane" }; var byteAnNum2 = new ByteAnNum { Lucy = "Flowers" }; var byteAdNum1 = new ByteAdNum { Lucy = "Kaleidoscope" }; var byteAdNum2 = new ByteAdNum { Lucy = "Eyes" }; decimal[] preSaveValues; byte[] preSaveByteValues; var options = Fixture.CreateOptions(testDatabase); using (var context = new NumNumContext(options)) { context.Database.EnsureCreatedResiliently(); context.AddRange( nownNum1, nownNum2, numNum1, numNum2, adNum1, adNum2, anNum1, anNum2, byteNownNum1, byteNownNum2, byteNum1, byteNum2, byteAdNum1, byteAdNum2, byteAnNum1, byteAnNum2); preSaveValues = new[] { numNum1.Id, numNum2.Id, adNum1.Id, adNum2.Id, anNum1.Id, anNum2.Id }; preSaveByteValues = new[] { byteNum1.Id, byteNum2.Id, byteAdNum1.Id, byteAdNum2.Id, byteAnNum1.Id, byteAnNum2.Id }; context.SaveChanges(); } using (var context = new NumNumContext(options)) { Assert.Equal(nownNum1.Id, context.NownNums.Single(e => e.TheWalrus == "Crying").Id); Assert.Equal(nownNum2.Id, context.NownNums.Single(e => e.TheWalrus == "Walrus").Id); Assert.Equal(77.0m, nownNum1.Id); Assert.Equal(78.0m, nownNum2.Id); Assert.Equal(numNum1.Id, context.NumNums.Single(e => e.TheWalrus == "I").Id); Assert.Equal(numNum2.Id, context.NumNums.Single(e => e.TheWalrus == "Am").Id); Assert.NotEqual(numNum1.Id, preSaveValues[0]); Assert.NotEqual(numNum2.Id, preSaveValues[1]); Assert.Equal(anNum1.Id, context.AnNums.Single(e => e.TheWalrus == "Goo goo").Id); Assert.Equal(anNum2.Id, context.AnNums.Single(e => e.TheWalrus == "g'joob").Id); Assert.NotEqual(adNum1.Id, preSaveValues[2]); Assert.NotEqual(adNum2.Id, preSaveValues[3]); Assert.Equal(adNum1.Id, context.AdNums.Single(e => e.TheWalrus == "Eggman").Id); Assert.Equal(adNum2.Id, context.AdNums.Single(e => e.TheWalrus == "Eggmen").Id); Assert.NotEqual(anNum1.Id, preSaveValues[4]); Assert.NotEqual(anNum2.Id, preSaveValues[5]); Assert.Equal(byteNownNum1.Id, context.ByteNownNums.Single(e => e.Lucy == "Tangerine").Id); Assert.Equal(byteNownNum2.Id, context.ByteNownNums.Single(e => e.Lucy == "Trees").Id); Assert.Equal(77, byteNownNum1.Id); Assert.Equal(78, byteNownNum2.Id); Assert.Equal(byteNum1.Id, context.ByteNums.Single(e => e.Lucy == "Marmalade").Id); Assert.Equal(byteNum2.Id, context.ByteNums.Single(e => e.Lucy == "Skies").Id); Assert.NotEqual(byteNum1.Id, preSaveByteValues[0]); Assert.NotEqual(byteNum2.Id, preSaveByteValues[1]); Assert.Equal(byteAnNum1.Id, context.ByteAnNums.Single(e => e.Lucy == "Cellophane").Id); Assert.Equal(byteAnNum2.Id, context.ByteAnNums.Single(e => e.Lucy == "Flowers").Id); Assert.NotEqual(byteAdNum1.Id, preSaveByteValues[2]); Assert.NotEqual(byteAdNum2.Id, preSaveByteValues[3]); Assert.Equal(byteAdNum1.Id, context.ByteAdNums.Single(e => e.Lucy == "Kaleidoscope").Id); Assert.Equal(byteAdNum2.Id, context.ByteAdNums.Single(e => e.Lucy == "Eyes").Id); Assert.NotEqual(byteAnNum1.Id, preSaveByteValues[4]); Assert.NotEqual(byteAnNum2.Id, preSaveByteValues[5]); } } } private class NumNumContext : DbContext { public NumNumContext(DbContextOptions options) : base(options) { } public DbSet<NownNum> NownNums { get; set; } public DbSet<NumNum> NumNums { get; set; } public DbSet<AnNum> AnNums { get; set; } public DbSet<AdNum> AdNums { get; set; } public DbSet<ByteNownNum> ByteNownNums { get; set; } public DbSet<ByteNum> ByteNums { get; set; } public DbSet<ByteAnNum> ByteAnNums { get; set; } public DbSet<ByteAdNum> ByteAdNums { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder .Entity<NumNum>() .Property(e => e.Id) .HasColumnType("numeric(18, 0)") .UseMySqlIdentityColumn(); modelBuilder .Entity<AdNum>() .Property(e => e.Id) .HasColumnType("decimal(10, 0)") .ValueGeneratedOnAdd(); modelBuilder .Entity<ByteNum>() .Property(e => e.Id) .UseMySqlIdentityColumn(); modelBuilder .Entity<ByteAdNum>() .Property(e => e.Id) .ValueGeneratedOnAdd(); modelBuilder .Entity<NownNum>() .Property(e => e.Id) .HasColumnType("numeric(18, 0)"); } } private class NownNum { public decimal Id { get; set; } public string TheWalrus { get; set; } } private class NumNum { public decimal Id { get; set; } public string TheWalrus { get; set; } } private class AnNum { [Column(TypeName = "decimal(18, 0)")] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public decimal Id { get; set; } public string TheWalrus { get; set; } } private class AdNum { public decimal Id { get; set; } public string TheWalrus { get; set; } } private class ByteNownNum { public byte Id { get; set; } public string Lucy { get; set; } } private class ByteNum { public byte Id { get; set; } public string Lucy { get; set; } } private class ByteAnNum { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public byte Id { get; set; } public string Lucy { get; set; } } private class ByteAdNum { public byte Id { get; set; } public string Lucy { get; set; } } [Fact] public void Can_use_string_enum_or_byte_array_as_key() { using (var testDatabase = MySqlTestStore.CreateInitialized(DatabaseName)) { var sNum1 = new SNum { TheWalrus = "I" }; var sNum2 = new SNum { TheWalrus = "Am" }; var enNum1 = new EnNum { TheWalrus = "Goo goo", Id = ENum.BNum }; var enNum2 = new EnNum { TheWalrus = "g'joob", Id = ENum.CNum }; var bNum1 = new BNum { TheWalrus = "Eggman" }; var bNum2 = new BNum { TheWalrus = "Eggmen" }; var options = Fixture.CreateOptions(testDatabase); using (var context = new ENumContext(options)) { context.Database.EnsureCreatedResiliently(); context.AddRange(sNum1, sNum2, enNum1, enNum2, bNum1, bNum2); context.SaveChanges(); } using (var context = new ENumContext(options)) { Assert.Equal(sNum1.Id, context.SNums.Single(e => e.TheWalrus == "I").Id); Assert.Equal(sNum2.Id, context.SNums.Single(e => e.TheWalrus == "Am").Id); Assert.Equal(enNum1.Id, context.EnNums.Single(e => e.TheWalrus == "Goo goo").Id); Assert.Equal(enNum2.Id, context.EnNums.Single(e => e.TheWalrus == "g'joob").Id); Assert.Equal(bNum1.Id, context.BNums.Single(e => e.TheWalrus == "Eggman").Id); Assert.Equal(bNum2.Id, context.BNums.Single(e => e.TheWalrus == "Eggmen").Id); } } } [Fact] public void Can_remove_multiple_byte_array_as_key() { using (var testDatabase = MySqlTestStore.CreateInitialized(DatabaseName)) { var bNum1 = new BNum { TheWalrus = "Eggman" }; var bNum2 = new BNum { TheWalrus = "Eggmen" }; var options = Fixture.CreateOptions(testDatabase); using (var context = new ENumContext(options)) { context.Database.EnsureCreatedResiliently(); context.AddRange(bNum1, bNum2); context.SaveChanges(); } using (var context = new ENumContext(options)) { Assert.Equal(bNum1.Id, context.BNums.Single(e => e.TheWalrus == "Eggman").Id); Assert.Equal(bNum2.Id, context.BNums.Single(e => e.TheWalrus == "Eggmen").Id); context.RemoveRange(context.BNums); context.SaveChanges(); } } } private class ENumContext : DbContext { public ENumContext(DbContextOptions options) : base(options) { } public DbSet<SNum> SNums { get; set; } public DbSet<EnNum> EnNums { get; set; } public DbSet<BNum> BNums { get; set; } } private class SNum { public string Id { get; set; } public string TheWalrus { get; set; } } private class EnNum { public ENum Id { get; set; } public string TheWalrus { get; set; } } private enum ENum { // ReSharper disable once UnusedMember.Local ANum, BNum, CNum } private class BNum { public byte[] Id { get; set; } public string TheWalrus { get; set; } } [Fact] public void Can_run_linq_query_on_entity_set() { using (var testStore = MySqlTestStore.GetNorthwindStore()) { using (var db = new NorthwindContext(Fixture.CreateOptions(testStore))) { var results = db.Customers .Where(c => c.CompanyName.StartsWith("A")) .OrderByDescending(c => c.CustomerID) .ToList(); Assert.Equal(4, results.Count); Assert.Equal("AROUT", results[0].CustomerID); Assert.Equal("ANTON", results[1].CustomerID); Assert.Equal("ANATR", results[2].CustomerID); Assert.Equal("ALFKI", results[3].CustomerID); Assert.Equal("(171) 555-6750", results[0].Fax); Assert.Null(results[1].Fax); Assert.Equal("(5) 555-3745", results[2].Fax); Assert.Equal("030-0076545", results[3].Fax); } } } [Fact] public void Can_run_linq_query_on_entity_set_with_value_buffer_reader() { using (var testStore = MySqlTestStore.GetNorthwindStore()) { using (var db = new NorthwindContext(Fixture.CreateOptions(testStore))) { var results = db.Customers .Where(c => c.CompanyName.StartsWith("A")) .OrderByDescending(c => c.CustomerID) .ToList(); Assert.Equal(4, results.Count); Assert.Equal("AROUT", results[0].CustomerID); Assert.Equal("ANTON", results[1].CustomerID); Assert.Equal("ANATR", results[2].CustomerID); Assert.Equal("ALFKI", results[3].CustomerID); Assert.Equal("(171) 555-6750", results[0].Fax); Assert.Null(results[1].Fax); Assert.Equal("(5) 555-3745", results[2].Fax); Assert.Equal("030-0076545", results[3].Fax); } } } [Fact] public void Can_enumerate_entity_set() { using (var testStore = MySqlTestStore.GetNorthwindStore()) { using (var db = new NorthwindContext(Fixture.CreateOptions(testStore))) { var results = new List<Customer>(); foreach (var item in db.Customers) { results.Add(item); } Assert.Equal(91, results.Count); Assert.Equal("ALFKI", results[0].CustomerID); Assert.Equal("Alfreds Futterkiste", results[0].CompanyName); } } } [Fact] public async Task Can_save_changes() { using (var testDatabase = MySqlTestStore.CreateInitialized(DatabaseName)) { var options = Fixture.CreateOptions(testDatabase); using (var db = new BloggingContext(options)) { await CreateBlogDatabaseAsync<Blog>(db); } Fixture.TestSqlLoggerFactory.Clear(); using (var db = new BloggingContext(options)) { var toUpdate = db.Blogs.Single(b => b.Name == "Blog1"); toUpdate.Name = "Blog is Updated"; var updatedId = toUpdate.Id; var toDelete = db.Blogs.Single(b => b.Name == "Blog2"); toDelete.Name = "Blog to delete"; var deletedId = toDelete.Id; db.Entry(toUpdate).State = EntityState.Modified; db.Entry(toDelete).State = EntityState.Deleted; var toAdd = db.Add( new Blog { Name = "Blog to Insert", George = true, TheGu = new Guid("0456AEF1-B7FC-47AA-8102-975D6BA3A9BF"), NotFigTime = new DateTime(1973, 9, 3, 0, 10, 33, 777), ToEat = 64, OrNothing = 0.123456789, Fuse = 777, WayRound = 9876543210, Away = 0.12345f, AndChew = new byte[16] }).Entity; await db.SaveChangesAsync(); var addedId = toAdd.Id; Assert.NotEqual(0, addedId); Assert.Equal(EntityState.Unchanged, db.Entry(toUpdate).State); Assert.Equal(EntityState.Unchanged, db.Entry(toAdd).State); Assert.DoesNotContain(toDelete, db.ChangeTracker.Entries().Select(e => e.Entity)); Assert.Equal(5, Fixture.TestSqlLoggerFactory.SqlStatements.Count); Assert.Contains("SELECT", Fixture.TestSqlLoggerFactory.SqlStatements[0]); Assert.Contains("SELECT", Fixture.TestSqlLoggerFactory.SqlStatements[1]); Assert.Contains("@p0='" + deletedId, Fixture.TestSqlLoggerFactory.SqlStatements[2]); Assert.Contains("DELETE", Fixture.TestSqlLoggerFactory.SqlStatements[2]); Assert.Contains("UPDATE", Fixture.TestSqlLoggerFactory.SqlStatements[3]); Assert.Contains("INSERT", Fixture.TestSqlLoggerFactory.SqlStatements[4]); var rows = await testDatabase.ExecuteScalarAsync<int>( $"SELECT Count(*) FROM [dbo].[Blog] WHERE Id = {updatedId} AND Name = 'Blog is Updated'"); Assert.Equal(1, rows); rows = await testDatabase.ExecuteScalarAsync<int>( $"SELECT Count(*) FROM [dbo].[Blog] WHERE Id = {deletedId}"); Assert.Equal(0, rows); rows = await testDatabase.ExecuteScalarAsync<int>( $"SELECT Count(*) FROM [dbo].[Blog] WHERE Id = {addedId} AND Name = 'Blog to Insert'"); Assert.Equal(1, rows); } } } [Fact] public async Task Can_save_changes_in_tracked_entities() { using (var testDatabase = MySqlTestStore.CreateInitialized(DatabaseName)) { int updatedId; int deletedId; int addedId; var options = Fixture.CreateOptions(testDatabase); using (var db = new BloggingContext(options)) { var blogs = await CreateBlogDatabaseAsync<Blog>(db); var toAdd = db.Blogs.Add( new Blog { Name = "Blog to Insert", George = true, TheGu = new Guid("0456AEF1-B7FC-47AA-8102-975D6BA3A9BF"), NotFigTime = new DateTime(1973, 9, 3, 0, 10, 33, 777), ToEat = 64, OrNothing = 0.123456789, Fuse = 777, WayRound = 9876543210, Away = 0.12345f, AndChew = new byte[16] }).Entity; db.Entry(toAdd).State = EntityState.Detached; var toUpdate = blogs[0]; toUpdate.Name = "Blog is Updated"; updatedId = toUpdate.Id; var toDelete = blogs[1]; toDelete.Name = "Blog to delete"; deletedId = toDelete.Id; db.Remove(toDelete); db.Entry(toAdd).State = EntityState.Added; await db.SaveChangesAsync(); addedId = toAdd.Id; Assert.NotEqual(0, addedId); Assert.Equal(EntityState.Unchanged, db.Entry(toUpdate).State); Assert.Equal(EntityState.Unchanged, db.Entry(toAdd).State); Assert.DoesNotContain(toDelete, db.ChangeTracker.Entries().Select(e => e.Entity)); } using (var db = new BloggingContext(options)) { var toUpdate = db.Blogs.Single(b => b.Id == updatedId); Assert.Equal("Blog is Updated", toUpdate.Name); Assert.Equal(0, db.Blogs.Count(b => b.Id == deletedId)); Assert.Equal("Blog to Insert", db.Blogs.Single(b => b.Id == addedId).Name); } } } [Fact] public void Can_track_an_entity_with_more_than_10_properties() { using (var testDatabase = MySqlTestStore.CreateInitialized(DatabaseName)) { var options = Fixture.CreateOptions(testDatabase); using (var context = new GameDbContext(options)) { context.Database.EnsureCreatedResiliently(); context.Characters.Add( new PlayerCharacter( new Level { Game = new Game() })); context.SaveChanges(); } using (var context = new GameDbContext(options)) { var character = context.Characters .Include(c => c.Level.Game) .OrderBy(c => c.Id) .First(); Assert.NotNull(character.Game); Assert.NotNull(character.Level); Assert.NotNull(character.Level.Game); } } } [Fact] public void Adding_an_item_to_a_collection_marks_it_as_modified() { using (var testDatabase = MySqlTestStore.CreateInitialized(DatabaseName)) { var options = Fixture.CreateOptions(testDatabase); using (var context = new GameDbContext(options)) { context.Database.EnsureCreatedResiliently(); var player = new PlayerCharacter( new Level { Game = new Game() }); var weapon = new Item { Id = 1, Game = player.Game }; context.Characters.Add(player); context.SaveChanges(); player.Items.Add(weapon); context.ChangeTracker.DetectChanges(); Assert.True(context.Entry(player).Collection(p => p.Items).IsModified); } } } [Fact] public void Can_set_reference_twice() { using (var testDatabase = MySqlTestStore.CreateInitialized(DatabaseName)) { var options = Fixture.CreateOptions(testDatabase); using (var context = new GameDbContext(options)) { context.Database.EnsureCreatedResiliently(); var player = new PlayerCharacter( new Level { Game = new Game() }); var weapon = new Item { Id = 1, Game = player.Game }; player.Items.Add(weapon); context.Characters.Add(player); context.SaveChanges(); player.CurrentWeapon = weapon; context.SaveChanges(); player.CurrentWeapon = null; context.SaveChanges(); player.CurrentWeapon = weapon; context.SaveChanges(); } using (var context = new GameDbContext(options)) { var player = context.Characters .Include(c => c.Items) .ToList().Single(); Assert.Equal(player.Items.Single(), player.CurrentWeapon); } } } [Fact] public void Can_include_on_loaded_entity() { using (var testDatabase = MySqlTestStore.CreateInitialized(DatabaseName)) { var options = Fixture.CreateOptions(testDatabase); using (var context = new GameDbContext(options)) { context.Database.EnsureCreatedResiliently(); var player = new PlayerCharacter( new Level { Game = new Game() }); var weapon = new Item { Id = 1, Game = player.Game }; player.Items.Add(weapon); player.Items.Add( new Item { Id = 2, Game = player.Game }); context.Characters.Add(player); context.SaveChanges(); player.CurrentWeapon = weapon; context.SaveChanges(); } using (var context = new GameDbContext(options)) { var player = context.Characters .Include(p => p.CurrentWeapon) .Single(); Assert.Equal(1, player.Items.Count); context.Attach(player); Assert.Equal(1, player.Items.Count); context.Levels .Include(l => l.Actors) .ThenInclude(a => a.Items) .Load(); Assert.Equal(2, player.Items.Count); } using (var context = new GameDbContext(options)) { var player = context.Characters .Include(p => p.CurrentWeapon) .AsNoTracking() .Single(); Assert.Equal(0, player.Items.Count); context.Entry(player.CurrentWeapon).Property("ActorId").CurrentValue = 0; context.Attach(player); Assert.Equal(1, player.Items.Count); context.Levels .Include(l => l.Actors) .ThenInclude(a => a.Items) .Load(); Assert.Equal(2, player.Items.Count); } } } public abstract class Actor { protected Actor() { } protected Actor(Level level) { Level = level; Game = level.Game; } public virtual int Id { get; private set; } public virtual Level Level { get; set; } public virtual int GameId { get; private set; } public virtual Game Game { get; set; } public virtual ICollection<Item> Items { get; set; } = new HashSet<Item>(); } public class PlayerCharacter : Actor { public PlayerCharacter() { } public PlayerCharacter(Level level) : base(level) { } public virtual string Name { get; set; } public virtual int Strength { get; set; } public virtual int Dexterity { get; set; } public virtual int Speed { get; set; } public virtual int Constitution { get; set; } public virtual int Intelligence { get; set; } public virtual int Willpower { get; set; } public virtual int MaxHP { get; set; } public virtual int HP { get; set; } public virtual int MaxMP { get; set; } public virtual int MP { get; set; } public virtual Item CurrentWeapon { get; set; } } public class Level { public virtual int Id { get; set; } public virtual int GameId { get; set; } public virtual Game Game { get; set; } public virtual ICollection<Actor> Actors { get; set; } = new HashSet<Actor>(); public virtual ICollection<Item> Items { get; set; } = new HashSet<Item>(); } public class Item { public virtual int Id { get; set; } public virtual int GameId { get; set; } public virtual Game Game { get; set; } public virtual Level Level { get; set; } public virtual Actor Actor { get; set; } } public class Container : Item { public virtual ICollection<Item> Items { get; set; } = new HashSet<Item>(); } public class Game { public virtual int Id { get; set; } public virtual ICollection<Actor> Actors { get; set; } = new HashSet<Actor>(); public virtual ICollection<Level> Levels { get; set; } = new HashSet<Level>(); } public class GameDbContext : DbContext { public GameDbContext(DbContextOptions options) : base(options) { } public DbSet<Game> Games { get; set; } public DbSet<Level> Levels { get; set; } public DbSet<PlayerCharacter> Characters { get; set; } public DbSet<Item> Items { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Level>( eb => { eb.HasKey( l => new { l.GameId, l.Id }); }); modelBuilder.Entity<Actor>( eb => { eb.HasKey( a => new { a.GameId, a.Id }); eb.HasOne(a => a.Level) .WithMany(l => l.Actors) .HasForeignKey(nameof(Actor.GameId), "LevelId") .IsRequired(); eb.HasMany(a => a.Items) .WithOne(i => i.Actor) .HasForeignKey(nameof(Item.GameId), "ActorId"); }); modelBuilder.Entity<PlayerCharacter>( eb => { eb.HasOne(p => p.CurrentWeapon) .WithOne() .HasForeignKey<PlayerCharacter>(nameof(PlayerCharacter.GameId), "CurrentWeaponId"); }); modelBuilder.Entity<Item>( eb => { eb.HasKey( l => new { l.GameId, l.Id }); }); modelBuilder.Entity<Container>(); modelBuilder.Entity<Game>( eb => { eb.Property(g => g.Id) .ValueGeneratedOnAdd(); eb.HasMany(g => g.Levels) .WithOne(l => l.Game) .HasForeignKey(l => l.GameId); eb.HasMany(g => g.Actors) .WithOne(a => a.Game) .HasForeignKey(a => a.GameId) .OnDelete(DeleteBehavior.Restrict); }); } } [Fact] public async Task Tracking_entities_asynchronously_returns_tracked_entities_back() { using (var testStore = MySqlTestStore.GetNorthwindStore()) { using (var db = new NorthwindContext(Fixture.CreateOptions(testStore))) { var customer = await db.Customers.OrderBy(c => c.CustomerID).FirstOrDefaultAsync(); var trackedCustomerEntry = db.ChangeTracker.Entries().Single(); Assert.Same(trackedCustomerEntry.Entity, customer); // if references are different this will throw db.Customers.Remove(customer); } } } [Fact] // Issue #931 public async Task Can_save_and_query_with_schema() { using (var testStore = MySqlTestStore.CreateInitialized(DatabaseName)) { var options = Fixture.CreateOptions(testStore); await testStore.ExecuteNonQueryAsync("CREATE SCHEMA Apple"); await testStore.ExecuteNonQueryAsync("CREATE TABLE Apple.Jack (MyKey int)"); await testStore.ExecuteNonQueryAsync("CREATE TABLE Apple.Black (MyKey int)"); using (var context = new SchemaContext(options)) { context.Add( new Jack { MyKey = 1 }); context.Add( new Black { MyKey = 2 }); context.SaveChanges(); } using (var context = new SchemaContext(options)) { Assert.Equal(1, context.Jacks.Count()); Assert.Equal(1, context.Blacks.Count()); } } } private class SchemaContext : DbContext { public SchemaContext(DbContextOptions options) : base(options) { } public DbSet<Jack> Jacks { get; set; } public DbSet<Black> Blacks { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder .Entity<Jack>() .ToTable("Jack", "Apple") .HasKey(e => e.MyKey); modelBuilder .Entity<Black>() .ToTable("Black", "Apple") .HasKey(e => e.MyKey); } } private class Jack { public int MyKey { get; set; } } private class Black { public int MyKey { get; set; } } [Fact] public Task Can_round_trip_changes_with_snapshot_change_tracking() { return RoundTripChanges<Blog>(); } [Fact] public Task Can_round_trip_changes_with_full_notification_entities() { return RoundTripChanges<ChangedChangingBlog>(); } [Fact] public Task Can_round_trip_changes_with_changed_only_notification_entities() { return RoundTripChanges<ChangedOnlyBlog>(); } private async Task RoundTripChanges<TBlog>() where TBlog : class, IBlog, new() { using (var testDatabase = MySqlTestStore.CreateInitialized(DatabaseName)) { var options = Fixture.CreateOptions(testDatabase); int blog1Id; int blog2Id; int blog3Id; using (var context = new BloggingContext<TBlog>(options)) { var blogs = await CreateBlogDatabaseAsync<TBlog>(context); blog1Id = blogs[0].Id; blog2Id = blogs[1].Id; Assert.NotEqual(0, blog1Id); Assert.NotEqual(0, blog2Id); Assert.NotEqual(blog1Id, blog2Id); } using (var context = new BloggingContext<TBlog>(options)) { var blogs = context.Blogs.ToList(); Assert.Equal(2, blogs.Count); var blog1 = blogs.Single(b => b.Name == "Blog1"); Assert.Equal(blog1Id, blog1.Id); Assert.Equal("Blog1", blog1.Name); Assert.True(blog1.George); Assert.Equal(new Guid("0456AEF1-B7FC-47AA-8102-975D6BA3A9BF"), blog1.TheGu); Assert.Equal(new DateTime(1973, 9, 3, 0, 10, 33, 777), blog1.NotFigTime); Assert.Equal(64, blog1.ToEat); Assert.Equal(0.123456789, blog1.OrNothing); Assert.Equal(777, blog1.Fuse); Assert.Equal(9876543210, blog1.WayRound); Assert.Equal(0.12345f, blog1.Away); Assert.Equal(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, blog1.AndChew); blog1.Name = "New Name"; var blog2 = blogs.Single(b => b.Name == "Blog2"); Assert.Equal(blog2Id, blog2.Id); blog2.Name = null; blog2.NotFigTime = new DateTime(); blog2.AndChew = null; var blog3 = context.Add(new TBlog()).Entity; await context.SaveChangesAsync(); blog3Id = blog3.Id; Assert.NotEqual(0, blog3Id); } using (var context = new BloggingContext<TBlog>(options)) { var blogs = context.Blogs.ToList(); Assert.Equal(3, blogs.Count); Assert.Equal("New Name", blogs.Single(b => b.Id == blog1Id).Name); var blog2 = blogs.Single(b => b.Id == blog2Id); Assert.Null(blog2.Name); Assert.Equal(blog2.NotFigTime, new DateTime()); Assert.Null(blog2.AndChew); var blog3 = blogs.Single(b => b.Id == blog3Id); Assert.Null(blog3.Name); Assert.Equal(blog3.NotFigTime, new DateTime()); Assert.Null(blog3.AndChew); } } } private static async Task<TBlog[]> CreateBlogDatabaseAsync<TBlog>(DbContext context) where TBlog : class, IBlog, new() { context.Database.EnsureCreatedResiliently(); var blog1 = context.Add( new TBlog { Name = "Blog1", George = true, TheGu = new Guid("0456AEF1-B7FC-47AA-8102-975D6BA3A9BF"), NotFigTime = new DateTime(1973, 9, 3, 0, 10, 33, 777), ToEat = 64, CupOfChar = 'C', OrNothing = 0.123456789, Fuse = 777, WayRound = 9876543210, NotToEat = -64, Away = 0.12345f, OrULong = 888, OrUSkint = 8888888, OrUShort = 888888888888888, AndChew = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } }).Entity; var blog2 = context.Add( new TBlog { Name = "Blog2", George = false, TheGu = new Guid("0456AEF1-B7FC-47AA-8102-975D6BA3A9CF"), NotFigTime = new DateTime(1973, 9, 3, 0, 10, 33, 778), ToEat = 65, CupOfChar = 'D', OrNothing = 0.987654321, Fuse = 778, WayRound = 98765432100, NotToEat = -64, Away = 0.12345f, OrULong = 888, OrUSkint = 8888888, OrUShort = 888888888888888, AndChew = new byte[16] }).Entity; await context.SaveChangesAsync(); return new[] { blog1, blog2 }; } private class NorthwindContext : DbContext { public NorthwindContext(DbContextOptions options) : base(options) { } public DbSet<Customer> Customers { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Customer>( b => { b.HasKey(c => c.CustomerID); b.ToTable("Customers"); }); } } private class Customer { public string CustomerID { get; set; } public string CompanyName { get; set; } public string Fax { get; set; } } private class BloggingContext : BloggingContext<Blog> { public BloggingContext(DbContextOptions options) : base(options) { } } private class Blog : IBlog { public int Id { get; set; } public string Name { get; set; } public bool George { get; set; } public Guid TheGu { get; set; } public DateTime NotFigTime { get; set; } public byte ToEat { get; set; } public char CupOfChar { get; set; } public double OrNothing { get; set; } public short Fuse { get; set; } public long WayRound { get; set; } public sbyte NotToEat { get; set; } public float Away { get; set; } public ushort OrULong { get; set; } public uint OrUSkint { get; set; } public ulong OrUShort { get; set; } public byte[] AndChew { get; set; } } private class BloggingContext<TBlog> : DbContext where TBlog : class, IBlog { public BloggingContext(DbContextOptions options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { if (typeof(INotifyPropertyChanging).GetTypeInfo().IsAssignableFrom(typeof(TBlog).GetTypeInfo())) { modelBuilder.HasChangeTrackingStrategy(ChangeTrackingStrategy.ChangingAndChangedNotifications); } else if (typeof(INotifyPropertyChanged).GetTypeInfo().IsAssignableFrom(typeof(TBlog).GetTypeInfo())) { modelBuilder.HasChangeTrackingStrategy(ChangeTrackingStrategy.ChangedNotifications); } modelBuilder.Entity<TBlog>().ToTable("Blog", "dbo"); } public DbSet<TBlog> Blogs { get; set; } } private interface IBlog { int Id { get; set; } string Name { get; set; } bool George { get; set; } Guid TheGu { get; set; } DateTime NotFigTime { get; set; } byte ToEat { get; set; } char CupOfChar { get; set; } double OrNothing { get; set; } short Fuse { get; set; } long WayRound { get; set; } sbyte NotToEat { get; set; } float Away { get; set; } ushort OrULong { get; set; } uint OrUSkint { get; set; } ulong OrUShort { get; set; } byte[] AndChew { get; set; } } private class ChangedChangingBlog : INotifyPropertyChanging, INotifyPropertyChanged, IBlog { private int _id; private string _name; private bool _george; private Guid _theGu; private DateTime _notFigTime; private byte _toEat; private char _cupOfChar; private double _orNothing; private short _fuse; private long _wayRound; private sbyte _notToEat; private float _away; private ushort _orULong; private uint _orUSkint; private ulong _orUShort; private byte[] _andChew; public int Id { get => _id; set { if (_id != value) { NotifyChanging(); _id = value; NotifyChanged(); } } } public string Name { get => _name; set { if (_name != value) { NotifyChanging(); _name = value; NotifyChanged(); } } } public bool George { get => _george; set { if (_george != value) { NotifyChanging(); _george = value; NotifyChanged(); } } } public Guid TheGu { get => _theGu; set { if (_theGu != value) { NotifyChanging(); _theGu = value; NotifyChanged(); } } } public DateTime NotFigTime { get => _notFigTime; set { if (_notFigTime != value) { NotifyChanging(); _notFigTime = value; NotifyChanged(); } } } public byte ToEat { get => _toEat; set { if (_toEat != value) { NotifyChanging(); _toEat = value; NotifyChanged(); } } } public char CupOfChar { get => _cupOfChar; set { if (_cupOfChar != value) { NotifyChanging(); _cupOfChar = value; NotifyChanged(); } } } public double OrNothing { get => _orNothing; set { if (_orNothing != value) { NotifyChanging(); _orNothing = value; NotifyChanged(); } } } public short Fuse { get => _fuse; set { if (_fuse != value) { NotifyChanging(); _fuse = value; NotifyChanged(); } } } public long WayRound { get => _wayRound; set { if (_wayRound != value) { NotifyChanging(); _wayRound = value; NotifyChanged(); } } } public sbyte NotToEat { get => _notToEat; set { if (_notToEat != value) { NotifyChanging(); _notToEat = value; NotifyChanged(); } } } public float Away { get => _away; set { if (_away != value) { NotifyChanging(); _away = value; NotifyChanged(); } } } public ushort OrULong { get => _orULong; set { if (_orULong != value) { NotifyChanging(); _orULong = value; NotifyChanged(); } } } public uint OrUSkint { get => _orUSkint; set { if (_orUSkint != value) { NotifyChanging(); _orUSkint = value; NotifyChanged(); } } } public ulong OrUShort { get => _orUShort; set { if (_orUShort != value) { NotifyChanging(); _orUShort = value; NotifyChanged(); } } } public byte[] AndChew { get => _andChew; set { if (_andChew != value) // Not a great way to compare byte arrays { NotifyChanging(); _andChew = value; NotifyChanged(); } } } public event PropertyChangingEventHandler PropertyChanging; public event PropertyChangedEventHandler PropertyChanged; private void NotifyChanged([CallerMemberName] string propertyName = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); private void NotifyChanging([CallerMemberName] string propertyName = "") => PropertyChanging?.Invoke(this, new PropertyChangingEventArgs(propertyName)); } private class ChangedOnlyBlog : INotifyPropertyChanged, IBlog { private int _id; private string _name; private bool _george; private Guid _theGu; private DateTime _notFigTime; private byte _toEat; private char _cupOfChar; private double _orNothing; private short _fuse; private long _wayRound; private sbyte _notToEat; private float _away; private ushort _orULong; private uint _orUSkint; private ulong _orUShort; private byte[] _andChew; public int Id { get => _id; set { if (_id != value) { _id = value; NotifyChanged(); } } } public string Name { get => _name; set { if (_name != value) { _name = value; NotifyChanged(); } } } public bool George { get => _george; set { if (_george != value) { _george = value; NotifyChanged(); } } } public Guid TheGu { get => _theGu; set { if (_theGu != value) { _theGu = value; NotifyChanged(); } } } public DateTime NotFigTime { get => _notFigTime; set { if (_notFigTime != value) { _notFigTime = value; NotifyChanged(); } } } public byte ToEat { get => _toEat; set { if (_toEat != value) { _toEat = value; NotifyChanged(); } } } public char CupOfChar { get => _cupOfChar; set { if (_cupOfChar != value) { _cupOfChar = value; NotifyChanged(); } } } public double OrNothing { get => _orNothing; set { if (_orNothing != value) { _orNothing = value; NotifyChanged(); } } } public short Fuse { get => _fuse; set { if (_fuse != value) { _fuse = value; NotifyChanged(); } } } public long WayRound { get => _wayRound; set { if (_wayRound != value) { _wayRound = value; NotifyChanged(); } } } public sbyte NotToEat { get => _notToEat; set { if (_notToEat != value) { _notToEat = value; NotifyChanged(); } } } public float Away { get => _away; set { if (_away != value) { _away = value; NotifyChanged(); } } } public ushort OrULong { get => _orULong; set { if (_orULong != value) { _orULong = value; NotifyChanged(); } } } public uint OrUSkint { get => _orUSkint; set { if (_orUSkint != value) { _orUSkint = value; NotifyChanged(); } } } public ulong OrUShort { get => _orUShort; set { if (_orUShort != value) { _orUShort = value; NotifyChanged(); } } } public byte[] AndChew { get => _andChew; set { if (_andChew != value) // Not a great way to compare byte arrays { _andChew = value; NotifyChanged(); } } } public event PropertyChangedEventHandler PropertyChanged; private void NotifyChanged([CallerMemberName] string propertyName = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Text.RegularExpressions; using System.Threading.Tasks; using Gigya.Microdot.Hosting.Events; using Gigya.Microdot.Interfaces.Events; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.SharedLogic; using Gigya.Microdot.SharedLogic.Configurations; using Gigya.Microdot.SharedLogic.Configurations.Serialization; using Gigya.Microdot.SharedLogic.Events; using Gigya.Microdot.SharedLogic.Exceptions; using Gigya.Microdot.SharedLogic.Security; using NUnit.Framework; using Shouldly; namespace Gigya.Microdot.UnitTests.Events { public class EventSerializationTests { private static readonly CurrentApplicationInfo AppInfo = new CurrentApplicationInfo(nameof(EventSerializationTests), Environment.UserName, Dns.GetHostName()); EventSerializer SerializerWithStackTrace { get; } = new EventSerializer(() => new EventConfiguration(), new NullEnvironment(), new StackTraceEnhancer( () => new StackTraceEnhancerSettings(), new NullEnvironment(), AppInfo, new JsonExceptionSerializationSettings(new ExceptionHierarchySerializationBinder(new MicrodotTypePolicySerializationBinder(new MicrodotSerializationConstraints(()=> new MicrodotSerializationSecurityConfig())))) ), () => new EventConfiguration(), AppInfo); EventSerializer SerializerWithoutStackTrace { get; } = new EventSerializer( () => new EventConfiguration { ExcludeStackTraceRule = new Regex(".*") }, new NullEnvironment(), new StackTraceEnhancer( () => new StackTraceEnhancerSettings(), new NullEnvironment(), AppInfo, new JsonExceptionSerializationSettings(new ExceptionHierarchySerializationBinder(new MicrodotTypePolicySerializationBinder(new MicrodotSerializationConstraints(()=> new MicrodotSerializationSecurityConfig())))) ), () => new EventConfiguration(), AppInfo); [OneTimeSetUp] public void OneTimeSetUp() { Environment.SetEnvironmentVariable("GIGYA_SERVICE_INSTANCE_NAME",null); } [Test] public async Task PublishExceptionEvent_WhileShouldExcludeStackTraceForFlume() { var evt = new ServiceCallEvent { Exception = new ArgumentException("Test Test").ThrowAndCatch() }; var serializedEvent = SerializerWithoutStackTrace.Serialize(evt).ToDictionary(_ => _.Name, _ => _.Value); serializedEvent.ShouldContainKey(EventConsts.exMessage); serializedEvent[EventConsts.exMessage].ShouldBe("Test Test"); serializedEvent.ShouldContainKey(EventConsts.exOneWordMessage); serializedEvent[EventConsts.exOneWordMessage].ShouldBe("Test_Test"); serializedEvent.ShouldContainKey(EventConsts.exType); serializedEvent[EventConsts.exType].ShouldBe(typeof(ArgumentException).FullName); serializedEvent.ShouldNotContainKey(EventConsts.exInnerMessages); serializedEvent.ShouldNotContainKey(EventConsts.exStackTrace); } [Test] public async Task PublishExceptionEvent_WithNotTrownException() { var evt = new Event { Exception = new Exception("Test Test") }; var serializedEvent = SerializerWithoutStackTrace.Serialize(evt).ToDictionary(_ => _.Name, _ => _.Value); serializedEvent.ShouldContainKey(EventConsts.exMessage); serializedEvent[EventConsts.exMessage].ShouldBe("Test Test"); serializedEvent.ShouldContainKey(EventConsts.exOneWordMessage); serializedEvent[EventConsts.exOneWordMessage].ShouldBe("Test_Test"); serializedEvent.ShouldContainKey(EventConsts.exType); serializedEvent[EventConsts.exType].ShouldBe(typeof(Exception).FullName); serializedEvent.ShouldNotContainKey(EventConsts.exInnerMessages); serializedEvent.ShouldNotContainKey(EventConsts.exStackTrace); } [Test] public async Task PublishExceptionEvent_WithEmptyStackTraceAndInnerException() { var exception = new Exception("Test Test", new Exception("Inner Exception").ThrowAndCatch()); exception.Data.Add("details", "details"); var evt = new Event { Exception = exception }; var serializedEvent = SerializerWithStackTrace.Serialize(evt).ToDictionary(_ => _.Name, _ => _.Value); serializedEvent.ShouldContainKey(EventConsts.exMessage); serializedEvent[EventConsts.exMessage].ShouldBe("Test Test"); serializedEvent.ShouldContainKey(EventConsts.exOneWordMessage); serializedEvent[EventConsts.exOneWordMessage].ShouldBe("Test_Test"); serializedEvent.ShouldContainKey(EventConsts.exInnerMessages); serializedEvent[EventConsts.exInnerMessages].ShouldBe("Inner Exception"); serializedEvent.ShouldContainKey(EventConsts.exType); serializedEvent[EventConsts.exType].ShouldBe(typeof(Exception).FullName); serializedEvent.ShouldContainKey(EventConsts.exStackTrace); serializedEvent[EventConsts.exStackTrace].ShouldNotBeNull(); } [Test] public async Task PublishExceptionEventWith_InnerException() { var exception = new Exception("Test Test", new Exception("Inner Exception")).ThrowAndCatch(); exception.Data.Add("details", "details"); var evt = new Event { Exception = exception }; var serializedEvent = SerializerWithStackTrace.Serialize(evt).ToDictionary(_ => _.Name, _ => _.Value); serializedEvent.ShouldContainKey(EventConsts.exMessage); serializedEvent[EventConsts.exMessage].ShouldBe("Test Test"); serializedEvent.ShouldContainKey(EventConsts.exOneWordMessage); serializedEvent[EventConsts.exOneWordMessage].ShouldBe("Test_Test"); serializedEvent.ShouldContainKey(EventConsts.exInnerMessages); serializedEvent[EventConsts.exInnerMessages].ShouldBe("Inner Exception"); serializedEvent.ShouldContainKey(EventConsts.exType); serializedEvent[EventConsts.exType].ShouldBe(typeof(Exception).FullName); serializedEvent.ShouldContainKey(EventConsts.exStackTrace); serializedEvent[EventConsts.exStackTrace].ShouldNotBeNull(); } [Test] public async Task PublishClientCallEvent() { var evt = new ClientCallEvent { Details = EventConsts.details, ErrCode = 1, Message = EventConsts.message, RequestId = EventConsts.callID, RequestStartTimestamp = 0, ResponseEndTimestamp = 2 * Stopwatch.Frequency, TargetHostName = EventConsts.targetHost, TargetMethod = EventConsts.targetMethod, TargetService = EventConsts.targetService, ParentSpanId = EventConsts.parentSpanID, SpanId = EventConsts.spanID, EncryptedTags = new Dictionary<string, object> { { "EncryptedTag", "EncryptedTagValue" } }, UnencryptedTags = new Dictionary<string, object> { { "UnencryptedTag", "UnencryptedTagValue" } } }; var serializedEvent = SerializerWithStackTrace.Serialize(evt).ToDictionary(_ => _.Name, _ => _.Value); serializedEvent.ShouldContainKey(EventConsts.type); serializedEvent[EventConsts.type].ShouldBe(EventConsts.ClientReqType); serializedEvent.ShouldContainKey(EventConsts.callID); serializedEvent[EventConsts.callID].ShouldBe(EventConsts.callID); serializedEvent.ShouldContainKey(EventConsts.parentSpanID); serializedEvent[EventConsts.parentSpanID].ShouldBe(EventConsts.parentSpanID); serializedEvent.ShouldContainKey(EventConsts.spanID); serializedEvent[EventConsts.spanID].ShouldBe(EventConsts.spanID); serializedEvent.ShouldContainKey(EventConsts.statsTotalTime); serializedEvent[EventConsts.statsTotalTime].ShouldBe("2000"); serializedEvent.ShouldContainKey(EventConsts.targetService); serializedEvent[EventConsts.targetService].ShouldBe(EventConsts.targetService); serializedEvent.ShouldContainKey(EventConsts.targetHost); serializedEvent[EventConsts.targetHost].ShouldBe(EventConsts.targetHost); serializedEvent.ShouldContainKey(EventConsts.targetMethod); serializedEvent[EventConsts.targetMethod].ShouldBe(EventConsts.targetMethod); serializedEvent.ShouldContainKey(EventConsts.clnSendTimestamp); serializedEvent[EventConsts.clnSendTimestamp].ShouldBe("0"); serializedEvent.ShouldContainKey(EventConsts.message); serializedEvent[EventConsts.message].ShouldBe(EventConsts.message); serializedEvent.ShouldContainKey(EventConsts.details); serializedEvent[EventConsts.details].ShouldBe(EventConsts.details); serializedEvent.ShouldContainKey(EventConsts.srvSystem); serializedEvent[EventConsts.srvSystem].ShouldBe(AppInfo.Name); serializedEvent.ShouldContainKey(EventConsts.srvVersion); serializedEvent[EventConsts.srvVersion].ShouldBe(AppInfo.Version.ToString(4)); serializedEvent.ShouldContainKey(EventConsts.infrVersion); serializedEvent[EventConsts.infrVersion].ShouldBe(AppInfo.InfraVersion.ToString(4)); serializedEvent.ShouldContainKey(EventConsts.srvSystemInstance); serializedEvent.ShouldContainKey(EventConsts.runtimeHost); serializedEvent[EventConsts.runtimeHost].ShouldBe(CurrentApplicationInfo.HostName); serializedEvent.ShouldContainKey(EventConsts.tags + ".UnencryptedTag"); serializedEvent[EventConsts.tags + ".UnencryptedTag"].ShouldBe("UnencryptedTagValue"); serializedEvent.ShouldContainKey(EventConsts.tags + ".EncryptedTag"); serializedEvent[EventConsts.tags + ".EncryptedTag"].ShouldNotBeNull(); } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Collections.Concurrent; using System.Globalization; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Runtime.Serialization; using System.IO; using System.Diagnostics.CodeAnalysis; using Microsoft.PowerShell.Commands.Internal.Format; using System.Management.Automation.Host; using System.Management.Automation.Internal; #if CORECLR // Use stubs for SerializationInfo, SecurityPermissionAttribute and Serializable using Microsoft.PowerShell.CoreClr.Stubs; #else // TODO:CORECLR Permissions is not available on CORE CLR yet using System.Security.Permissions; #endif namespace System.Management.Automation.Runspaces { /// <summary> /// This exception is used by Formattable constructor to indicate errors /// occured during construction time. /// </summary> [Serializable] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "FormatTable")] public class FormatTableLoadException : RuntimeException { private Collection<string> _errors; #region Constructors /// <summary> /// This is the default constructor. /// </summary> public FormatTableLoadException() : base() { SetDefaultErrorRecord(); } /// <summary> /// This constructor takes a localized error message. /// </summary> /// <param name="message"> /// A localized error message. /// </param> public FormatTableLoadException(string message) : base(message) { SetDefaultErrorRecord(); } /// <summary> /// This constructor takes a localized message and an inner exception. /// </summary> /// <param name="message"> /// Localized error message. /// </param> /// <param name="innerException"> /// Inner exception. /// </param> public FormatTableLoadException(string message, Exception innerException) : base(message, innerException) { SetDefaultErrorRecord(); } /// <summary> /// This constructor takes a colletion of errors occurred during construction /// time. /// </summary> /// <param name="loadErrors"> /// The errors that occured /// </param> internal FormatTableLoadException(ConcurrentBag<string> loadErrors) : base(StringUtil.Format(FormatAndOutXmlLoadingStrings.FormatTableLoadErrors)) { _errors = new Collection<string>(loadErrors.ToArray()); SetDefaultErrorRecord(); } /// <summary> /// This constructor is required by serialization. /// </summary> /// <param name="info"></param> /// <param name="context"></param> protected FormatTableLoadException(SerializationInfo info, StreamingContext context) : base(info, context) { if (info == null) { throw new PSArgumentNullException("info"); } int errorCount = info.GetInt32("ErrorCount"); if (errorCount > 0) { _errors = new Collection<string>(); for (int index = 0; index < errorCount; index++) { string key = string.Format(CultureInfo.InvariantCulture, "Error{0}", index); _errors.Add(info.GetString(key)); } } } #endregion Constructors /// <summary> /// Serializes the exception data. /// </summary> /// <param name="info"> serialization information </param> /// <param name="context"> streaming context </param> [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new PSArgumentNullException("info"); } base.GetObjectData(info, context); // If there are simple fields, serialize them with info.AddValue if (null != _errors) { int errorCount = _errors.Count; info.AddValue("ErrorCount", errorCount); for (int index = 0; index < errorCount; index++) { string key = string.Format(CultureInfo.InvariantCulture, "Error{0}", index); info.AddValue(key, _errors[index]); } } } /// <summary> /// Set the default ErrorRecord. /// </summary> protected void SetDefaultErrorRecord() { SetErrorCategory(ErrorCategory.InvalidData); SetErrorId(typeof(FormatTableLoadException).FullName); } /// <summary> /// The specific Formattable load errors. /// </summary> public Collection<string> Errors { get { return _errors; } } } /// <summary> /// A class that keeps the information from format.ps1xml files in a cache table /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "FormatTable")] public sealed class FormatTable { #region Private Data private TypeInfoDataBaseManager _formatDBMgr; #endregion #region Constructor /// <summary> /// Default Constructor /// </summary> internal FormatTable() { _formatDBMgr = new TypeInfoDataBaseManager(); } /// <summary> /// Constructor that creates a FormatTable from a set of format files. /// </summary> /// <param name="formatFiles"> /// Format files to load for format information. /// </param> /// <exception cref="ArgumentException"> /// 1. Path {0} is not fully qualified. Specify a fully qualified type file path. /// </exception> /// <exception cref="FormatTableLoadException"> /// 1. There were errors loading Formattable. Look in the Errors property to /// get detailed error messages. /// </exception> public FormatTable(IEnumerable<string> formatFiles) : this(formatFiles, null, null) { } /// <summary> /// Append the formatData to the list of formatting configurations, and update the /// entire formatting database. /// </summary> /// <param name="formatData"> /// The formatData is of type 'ExtendedTypeDefinition'. It defines the View configuration /// including TableControl, ListControl, and WideControl. /// </param> /// <exception cref="FormatTableLoadException"> /// 1. There were errors loading Formattable. Look in the Errors property to /// get detailed error messages. /// </exception> public void AppendFormatData(IEnumerable<ExtendedTypeDefinition> formatData) { if (formatData == null) throw PSTraceSource.NewArgumentNullException("formatData"); _formatDBMgr.AddFormatData(formatData, false); } /// <summary> /// Prepend the formatData to the list of formatting configurations, and update the /// entire formatting database. /// </summary> /// <param name="formatData"> /// The formatData is of type 'ExtendedTypeDefinition'. It defines the View configuration /// including TableControl, ListControl, and WideControl. /// </param> /// <exception cref="FormatTableLoadException"> /// 1. There were errors loading Formattable. Look in the Errors property to /// get detailed error messages. /// </exception> public void PrependFormatData(IEnumerable<ExtendedTypeDefinition> formatData) { if (formatData == null) throw PSTraceSource.NewArgumentNullException("formatData"); _formatDBMgr.AddFormatData(formatData, true); } /// <summary> /// Constructor that creates a FormatTable from a set of format files. /// </summary> /// <param name="formatFiles"> /// Format files to load for format information. /// </param> /// <param name="authorizationManager"> /// Authorization manager to perform signature checks before reading ps1xml files (or null of no checks are needed) /// </param> /// <param name="host"> /// Host passed to <paramref name="authorizationManager"/>. Can be null if no interactive questions should be asked. /// </param> /// <exception cref="ArgumentException"> /// 1. Path {0} is not fully qualified. Specify a fully qualified type file path. /// </exception> /// <exception cref="FormatTableLoadException"> /// 1. There were errors loading Formattable. Look in the Errors property to /// get detailed error messages. /// </exception> internal FormatTable(IEnumerable<string> formatFiles, AuthorizationManager authorizationManager, PSHost host) { if (null == formatFiles) { throw PSTraceSource.NewArgumentNullException("formatFiles"); } _formatDBMgr = new TypeInfoDataBaseManager(formatFiles, true, authorizationManager, host); } #endregion #region Internal Methods / Properties internal TypeInfoDataBaseManager FormatDBManager { get { return _formatDBMgr; } } /// <summary> /// Adds the <paramref name="formatFile"/> to the current FormatTable's file list. /// The FormatTable will not reflect the change until Update is called. /// </summary> /// <param name="formatFile"></param> /// <param name="shouldPrepend"> /// if true, <paramref name="formatFile"/> is prepended to the current FormatTable's file list. /// if false, it will be appended. /// </param> internal void Add(string formatFile, bool shouldPrepend) { _formatDBMgr.Add(formatFile, shouldPrepend); } /// <summary> /// Removes the <paramref name="formatFile"/> from the current FormatTable's file list. /// The FormatTable will not reflect the change until Update is called. /// </summary> /// <param name="formatFile"></param> internal void Remove(string formatFile) { _formatDBMgr.Remove(formatFile); } #endregion #region static methods /// <summary> /// Returns a format table instance with all default /// format files loaded /// </summary> /// <returns></returns> public static FormatTable LoadDefaultFormatFiles() { string shellId = Utils.DefaultPowerShellShellID; string psHome = Utils.GetApplicationBase(shellId); List<string> defaultFormatFiles = new List<string>(); if (!string.IsNullOrEmpty(psHome)) { defaultFormatFiles.AddRange(Platform.FormatFileNames.Select(file => Path.Combine(psHome, file))); } return new FormatTable(defaultFormatFiles); } #endregion static methods } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Globalization; /// <summary> ///System.IConvertible.ToBoolean(System.IFormatProvider) /// </summary> public class SingleToBoolean { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; return retVal; } #region Positive Test Cases //CultureInfo.GetCultureInfo has been removed. Replaced by CultureInfo ctor. public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Check a random single."); try { Single i1 = TestLibrary.Generator.GetSingle(-55); CultureInfo myCulture = new CultureInfo("en-us"); bool actualValue = ((IConvertible)i1).ToBoolean(myCulture); if (!actualValue) { TestLibrary.TestFramework.LogError("001.1", "ToBoolean return failed. "); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: check Single which is not a number ."); try { Single i1 = Single.NaN; CultureInfo myCulture = new CultureInfo("en-us"); bool actualValue = ((IConvertible)i1).ToBoolean(myCulture); if (!actualValue) { TestLibrary.TestFramework.LogError("002.1", "ToBoolean return failed. "); retVal = false; } i1 = Single.NegativeInfinity; actualValue = ((IConvertible)i1).ToBoolean(myCulture); if (!actualValue) { TestLibrary.TestFramework.LogError("002.2", "ToBoolean return failed."); retVal = false; } i1 = Single.PositiveInfinity; actualValue = ((IConvertible)i1).ToBoolean(myCulture); if (!actualValue) { TestLibrary.TestFramework.LogError("002.3", "ToBoolean return failed. "); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002.4", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Check a single which is -123456789."); try { Single i1 = -123456789; CultureInfo myCulture = new CultureInfo("en-us"); bool actualValue = ((IConvertible)i1).ToBoolean(myCulture); if (!actualValue) { TestLibrary.TestFramework.LogError("003.1", "ToBoolean return failed. "); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("003.2", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Check a single which is 123.45e+6."); try { Single i1 = (Single)123.45e+6; CultureInfo myCulture = new CultureInfo("en-us"); bool actualValue = ((IConvertible)i1).ToBoolean(myCulture); if (!actualValue) { TestLibrary.TestFramework.LogError("004.1", "ToBoolean return failed. "); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004.2", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Check a single which is -.123."); try { Single i1 = (Single)(-.123); CultureInfo myCulture = new CultureInfo("en-us"); bool actualValue = ((IConvertible)i1).ToBoolean(myCulture); if (!actualValue) { TestLibrary.TestFramework.LogError("005.1", "ToBoolean return failed. "); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("005.2", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest6: Check a single which is +123."); try { Single i1 = (Single)(+123); CultureInfo myCulture = new CultureInfo("en-us"); bool actualValue = ((IConvertible)i1).ToBoolean(myCulture); if (!actualValue) { TestLibrary.TestFramework.LogError("006.1", "ToBoolean return failed. "); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006.2", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #endregion public static int Main() { SingleToBoolean test = new SingleToBoolean(); TestLibrary.TestFramework.BeginTestCase("SingleToBoolean"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic.Utils; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading; namespace System.Linq.Expressions { /// <summary> /// The base type for all nodes in Expression Trees. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] public abstract partial class Expression { private static readonly CacheDict<Type, MethodInfo> s_lambdaDelegateCache = new CacheDict<Type, MethodInfo>(40); private static volatile CacheDict<Type, Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>> s_lambdaFactories; // For 4.0, many frequently used Expression nodes have had their memory // footprint reduced by removing the Type and NodeType fields. This has // large performance benefits to all users of Expression Trees. // // To support the 3.5 protected constructor, we store the fields that // used to be here in a ConditionalWeakTable. private class ExtensionInfo { public ExtensionInfo(ExpressionType nodeType, Type type) { NodeType = nodeType; Type = type; } internal readonly ExpressionType NodeType; internal readonly Type Type; } private static ConditionalWeakTable<Expression, ExtensionInfo> s_legacyCtorSupportTable; /// <summary> /// Constructs a new instance of <see cref="Expression"/>. /// </summary> /// <param name="nodeType">The <see ctype="ExpressionType"/> of the <see cref="Expression"/>.</param> /// <param name="type">The <see cref="Type"/> of the <see cref="Expression"/>.</param> [Obsolete("use a different constructor that does not take ExpressionType. Then override NodeType and Type properties to provide the values that would be specified to this constructor.")] protected Expression(ExpressionType nodeType, Type type) { // Can't enforce anything that V1 didn't if (s_legacyCtorSupportTable == null) { Interlocked.CompareExchange( ref s_legacyCtorSupportTable, new ConditionalWeakTable<Expression, ExtensionInfo>(), null ); } s_legacyCtorSupportTable.Add(this, new ExtensionInfo(nodeType, type)); } /// <summary> /// Constructs a new instance of <see cref="Expression"/>. /// </summary> protected Expression() { } /// <summary> /// The <see cref="ExpressionType"/> of the <see cref="Expression"/>. /// </summary> public virtual ExpressionType NodeType { get { ExtensionInfo extInfo; if (s_legacyCtorSupportTable != null && s_legacyCtorSupportTable.TryGetValue(this, out extInfo)) { return extInfo.NodeType; } // the extension expression failed to override NodeType throw Error.ExtensionNodeMustOverrideProperty("Expression.NodeType"); } } /// <summary> /// The <see cref="Type"/> of the value represented by this <see cref="Expression"/>. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public virtual Type Type { get { ExtensionInfo extInfo; if (s_legacyCtorSupportTable != null && s_legacyCtorSupportTable.TryGetValue(this, out extInfo)) { return extInfo.Type; } // the extension expression failed to override Type throw Error.ExtensionNodeMustOverrideProperty("Expression.Type"); } } /// <summary> /// Indicates that the node can be reduced to a simpler node. If this /// returns true, Reduce() can be called to produce the reduced form. /// </summary> public virtual bool CanReduce { get { return false; } } /// <summary> /// 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. /// </summary> /// <returns>The reduced expression.</returns> public virtual Expression Reduce() { if (CanReduce) throw Error.ReducibleMustOverrideReduce(); return this; } /// <summary> /// Reduces the node and then calls the visitor delegate on the reduced expression. /// Throws an exception if the node isn't reducible. /// </summary> /// <param name="visitor">An instance of <see cref="Func{Expression, Expression}"/>.</param> /// <returns>The expression being visited, or an expression which should replace it in the tree.</returns> /// <remarks> /// 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. /// </remarks> protected internal virtual Expression VisitChildren(ExpressionVisitor visitor) { if (!CanReduce) throw Error.MustBeReducible(); return visitor.Visit(ReduceAndCheck()); } /// <summary> /// Dispatches to the specific visit method for this node type. For /// example, <see cref="MethodCallExpression" /> will call into /// <see cref="ExpressionVisitor.VisitMethodCall" />. /// </summary> /// <param name="visitor">The visitor to visit this node with.</param> /// <returns>The result of visiting this node.</returns> /// <remarks> /// This default implementation for <see cref="ExpressionType.Extension" /> /// nodes will call <see cref="ExpressionVisitor.VisitExtension" />. /// 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. /// </remarks> protected internal virtual Expression Accept(ExpressionVisitor visitor) { return visitor.VisitExtension(this); } /// <summary> /// 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. /// </summary> /// <returns>The reduced expression.</returns> /// <remarks > /// Unlike Reduce, this method checks that the reduced node satisfies /// certain invariants. /// </remarks> public Expression ReduceAndCheck() { if (!CanReduce) throw Error.MustBeReducible(); var newNode = Reduce(); // 1. Reduction must return a new, non-null node // 2. Reduction must return a new node whose result type can be assigned to the type of the original node if (newNode == null || newNode == this) throw Error.MustReduceToDifferent(); if (!TypeUtils.AreReferenceAssignable(Type, newNode.Type)) throw Error.ReducedNotCompatible(); return newNode; } /// <summary> /// 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. /// </summary> /// <returns>The reduced expression.</returns> public Expression ReduceExtensions() { var node = this; while (node.NodeType == ExpressionType.Extension) { node = node.ReduceAndCheck(); } return node; } /// <summary> /// Creates a <see cref="String"/> representation of the Expression. /// </summary> /// <returns>A <see cref="String"/> representation of the Expression.</returns> public override string ToString() { return ExpressionStringBuilder.ExpressionToString(this); } /// <summary> /// Creates a <see cref="String"/> representation of the Expression. /// </summary> /// <returns>A <see cref="String"/> representation of the Expression.</returns> private string DebugView { // Note that this property is often accessed using reflection. As such it will have more dependencies than one // might surmise from its being internal, and removing it requires greater caution than with other internal methods. get { using (System.IO.StringWriter writer = new System.IO.StringWriter(CultureInfo.CurrentCulture)) { DebugViewWriter.WriteTo(this, writer); return writer.ToString(); } } } /// <summary> /// 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. /// </summary> internal static ReadOnlyCollection<T> ReturnReadOnly<T>(ref IList<T> collection) { return ExpressionUtils.ReturnReadOnly<T>(ref collection); } /// <summary> /// 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. /// </summary> internal static ReadOnlyCollection<Expression> ReturnReadOnly(IArgumentProvider provider, ref object collection) { return ExpressionUtils.ReturnReadOnly(provider, ref collection); } /// <summary> /// 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. /// </summary> internal static T ReturnObject<T>(object collectionOrT) where T : class { return ExpressionUtils.ReturnObject<T>(collectionOrT); } private static void RequiresCanRead(Expression expression, string paramName) { ExpressionUtils.RequiresCanRead(expression, paramName); } private static void RequiresCanRead(IReadOnlyList<Expression> items, string paramName) { Debug.Assert(items != null); // this is called a lot, avoid allocating an enumerator if we can... for (int i = 0; i < items.Count; i++) { RequiresCanRead(items[i], paramName); } } private static void RequiresCanWrite(Expression expression, string paramName) { if (expression == null) { throw new ArgumentNullException(paramName); } switch (expression.NodeType) { case ExpressionType.Index: PropertyInfo indexer = ((IndexExpression)expression).Indexer; if (indexer == null || indexer.CanWrite) { return; } break; case ExpressionType.MemberAccess: MemberInfo member = ((MemberExpression)expression).Member; PropertyInfo prop = member as PropertyInfo; if (prop != null) { if(prop.CanWrite) { return; } } else { Debug.Assert(member is FieldInfo); FieldInfo field = (FieldInfo)member; if (!(field.IsInitOnly || field.IsLiteral)) { return; } } break; case ExpressionType.Parameter: return; } throw new ArgumentException(Strings.ExpressionMustBeWriteable, paramName); } } }
// *********************************************************************** // Copyright (c) 2014 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** #if NET_4_0 || NET_4_5 || PORTABLE using System; using NUnit.Framework.Constraints; using NUnit.Framework.Internal; namespace NUnit.Framework { public partial class Assert { #region ThrowsAsync /// <summary> /// Verifies that an async delegate throws a particular exception when called. /// </summary> /// <param name="expression">A constraint to be satisfied by the exception</param> /// <param name="code">A TestSnippet delegate</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static Exception ThrowsAsync(IResolveConstraint expression, AsyncTestDelegate code, string message, params object[] args) { Exception caughtException = null; using (var region = AsyncInvocationRegion.Create(code)) { try { var task = code(); region.WaitForPendingOperationsToComplete(task); } catch (Exception e) { caughtException = e; } } Assert.That(caughtException, expression, message, args); return caughtException; } /// <summary> /// Verifies that an async delegate throws a particular exception when called. /// </summary> /// <param name="expression">A constraint to be satisfied by the exception</param> /// <param name="code">A TestSnippet delegate</param> public static Exception ThrowsAsync(IResolveConstraint expression, AsyncTestDelegate code) { return ThrowsAsync(expression, code, string.Empty, null); } /// <summary> /// Verifies that an async delegate throws a particular exception when called. /// </summary> /// <param name="expectedExceptionType">The exception Type expected</param> /// <param name="code">A TestDelegate</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static Exception ThrowsAsync(Type expectedExceptionType, AsyncTestDelegate code, string message, params object[] args) { return ThrowsAsync(new ExceptionTypeConstraint(expectedExceptionType), code, message, args); } /// <summary> /// Verifies that an async delegate throws a particular exception when called. /// </summary> /// <param name="expectedExceptionType">The exception Type expected</param> /// <param name="code">A TestDelegate</param> public static Exception ThrowsAsync(Type expectedExceptionType, AsyncTestDelegate code) { return ThrowsAsync(new ExceptionTypeConstraint(expectedExceptionType), code, string.Empty, null); } #endregion #region ThrowsAsync<TActual> /// <summary> /// Verifies that an async delegate throws a particular exception when called. /// </summary> /// <typeparam name="TActual">Type of the expected exception</typeparam> /// <param name="code">A TestDelegate</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static TActual ThrowsAsync<TActual>(AsyncTestDelegate code, string message, params object[] args) where TActual : Exception { return (TActual)ThrowsAsync(typeof (TActual), code, message, args); } /// <summary> /// Verifies that an async delegate throws a particular exception when called. /// </summary> /// <typeparam name="TActual">Type of the expected exception</typeparam> /// <param name="code">A TestDelegate</param> public static TActual ThrowsAsync<TActual>(AsyncTestDelegate code) where TActual : Exception { return ThrowsAsync<TActual>(code, string.Empty, null); } #endregion #region CatchAsync /// <summary> /// Verifies that an async delegate throws an exception when called /// and returns it. /// </summary> /// <param name="code">A TestDelegate</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static Exception CatchAsync(AsyncTestDelegate code, string message, params object[] args) { return ThrowsAsync(new InstanceOfTypeConstraint(typeof(Exception)), code, message, args); } /// <summary> /// Verifies that an async delegate throws an exception when called /// and returns it. /// </summary> /// <param name="code">A TestDelegate</param> public static Exception CatchAsync(AsyncTestDelegate code) { return ThrowsAsync(new InstanceOfTypeConstraint(typeof(Exception)), code); } /// <summary> /// Verifies that an async delegate throws an exception of a certain Type /// or one derived from it when called and returns it. /// </summary> /// <param name="expectedExceptionType">The expected Exception Type</param> /// <param name="code">A TestDelegate</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static Exception CatchAsync(Type expectedExceptionType, AsyncTestDelegate code, string message, params object[] args) { return ThrowsAsync(new InstanceOfTypeConstraint(expectedExceptionType), code, message, args); } /// <summary> /// Verifies that an async delegate throws an exception of a certain Type /// or one derived from it when called and returns it. /// </summary> /// <param name="expectedExceptionType">The expected Exception Type</param> /// <param name="code">A TestDelegate</param> public static Exception CatchAsync(Type expectedExceptionType, AsyncTestDelegate code) { return ThrowsAsync(new InstanceOfTypeConstraint(expectedExceptionType), code); } #endregion #region CatchAsync<TActual> /// <summary> /// Verifies that an async delegate throws an exception of a certain Type /// or one derived from it when called and returns it. /// </summary> /// <param name="code">A TestDelegate</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static TActual CatchAsync<TActual>(AsyncTestDelegate code, string message, params object[] args) where TActual : Exception { return (TActual)ThrowsAsync(new InstanceOfTypeConstraint(typeof (TActual)), code, message, args); } /// <summary> /// Verifies that an async delegate throws an exception of a certain Type /// or one derived from it when called and returns it. /// </summary> /// <param name="code">A TestDelegate</param> public static TActual CatchAsync<TActual>(AsyncTestDelegate code) where TActual : Exception { return (TActual)ThrowsAsync(new InstanceOfTypeConstraint(typeof (TActual)), code); } #endregion #region DoesNotThrowAsync /// <summary> /// Verifies that an async delegate does not throw an exception /// </summary> /// <param name="code">A TestDelegate</param> /// <param name="message">The message that will be displayed on failure</param> /// <param name="args">Arguments to be used in formatting the message</param> public static void DoesNotThrowAsync(AsyncTestDelegate code, string message, params object[] args) { Assert.That(code, new ThrowsNothingConstraint(), message, args); } /// <summary> /// Verifies that an async delegate does not throw an exception. /// </summary> /// <param name="code">A TestDelegate</param> public static void DoesNotThrowAsync(AsyncTestDelegate code) { DoesNotThrowAsync(code, string.Empty, null); } #endregion } } #endif
using System; using System.Collections.Generic; using System.Linq; #if !WINDOWS_UWP using System.Security.Cryptography; #else using Windows.Security.Cryptography.Core; #endif using System.Text; using RestSharp.Authenticators.OAuth.Extensions; using System.Runtime.Serialization; namespace RestSharp.Authenticators.OAuth { #if !SILVERLIGHT && !WINDOWS_PHONE && !WINDOWS_UWP [Serializable] #endif #if WINDOWS_UWP [DataContract] #endif internal static class OAuthTools { private const string ALPHA_NUMERIC = UPPER + LOWER + DIGIT; private const string DIGIT = "1234567890"; private const string LOWER = "abcdefghijklmnopqrstuvwxyz"; private const string UNRESERVED = ALPHA_NUMERIC + "-._~"; private const string UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static readonly Random random; private static readonly object randomLock = new object(); #if !SILVERLIGHT && !WINDOWS_PHONE && !WINDOWS_UWP private static readonly RandomNumberGenerator rng = RandomNumberGenerator.Create(); #endif static OAuthTools() { #if !SILVERLIGHT && !WINDOWS_PHONE && !WINDOWS_UWP byte[] bytes = new byte[4]; rng.GetNonZeroBytes(bytes); random = new Random(BitConverter.ToInt32(bytes, 0)); #else random = new Random(); #endif } /// <summary> /// All text parameters are UTF-8 encoded (per section 5.1). /// </summary> /// <seealso cref="http://www.hueniverse.com/hueniverse/2008/10/beginners-gui-1.html"/> private static readonly Encoding encoding = Encoding.UTF8; /// <summary> /// Generates a random 16-byte lowercase alphanumeric string. /// </summary> /// <seealso cref="http://oauth.net/core/1.0#nonce"/> /// <returns></returns> public static string GetNonce() { const string chars = (LOWER + DIGIT); char[] nonce = new char[16]; lock (randomLock) { for (int i = 0; i < nonce.Length; i++) { nonce[i] = chars[random.Next(0, chars.Length)]; } } return new string(nonce); } /// <summary> /// Generates a timestamp based on the current elapsed seconds since '01/01/1970 0000 GMT" /// </summary> /// <seealso cref="http://oauth.net/core/1.0#nonce"/> /// <returns></returns> public static string GetTimestamp() { return GetTimestamp(DateTime.UtcNow); } /// <summary> /// Generates a timestamp based on the elapsed seconds of a given time since '01/01/1970 0000 GMT" /// </summary> /// <seealso cref="http://oauth.net/core/1.0#nonce"/> /// <param name="dateTime">A specified point in time.</param> /// <returns></returns> public static string GetTimestamp(DateTime dateTime) { long timestamp = dateTime.ToUnixTime(); return timestamp.ToString(); } /// <summary> /// The set of characters that are unreserved in RFC 2396 but are NOT unreserved in RFC 3986. /// </summary> /// <seealso cref="http://stackoverflow.com/questions/846487/how-to-get-uri-escapedatastring-to-comply-with-rfc-3986" /> private static readonly string[] uriRfc3986CharsToEscape = { "!", "*", "'", "(", ")" }; private static readonly string[] uriRfc3968EscapedHex = { "%21", "%2A", "%27", "%28", "%29" }; /// <summary> /// URL encodes a string based on section 5.1 of the OAuth spec. /// Namely, percent encoding with [RFC3986], avoiding unreserved characters, /// upper-casing hexadecimal characters, and UTF-8 encoding for text value pairs. /// </summary> /// <param name="value">The value to escape.</param> /// <returns>The escaped value.</returns> /// <remarks> /// The <see cref="Uri.EscapeDataString"/> method is <i>supposed</i> to take on /// RFC 3986 behavior if certain elements are present in a .config file. Even if this /// actually worked (which in my experiments it <i>doesn't</i>), we can't rely on every /// host actually having this configuration element present. /// </remarks> /// <seealso cref="http://oauth.net/core/1.0#encoding_parameters" /> /// <seealso cref="http://stackoverflow.com/questions/846487/how-to-get-uri-escapedatastring-to-comply-with-rfc-3986" /> public static string UrlEncodeRelaxed(string value) { // Start with RFC 2396 escaping by calling the .NET method to do the work. // This MAY sometimes exhibit RFC 3986 behavior (according to the documentation). // If it does, the escaping we do that follows it will be a no-op since the // characters we search for to replace can't possibly exist in the string. StringBuilder escaped = new StringBuilder(Uri.EscapeDataString(value)); // Upgrade the escaping to RFC 3986, if necessary. for (int i = 0; i < uriRfc3986CharsToEscape.Length; i++) { string t = uriRfc3986CharsToEscape[i]; escaped.Replace(t, uriRfc3968EscapedHex[i]); } // Return the fully-RFC3986-escaped string. return escaped.ToString(); } /// <summary> /// URL encodes a string based on section 5.1 of the OAuth spec. /// Namely, percent encoding with [RFC3986], avoiding unreserved characters, /// upper-casing hexadecimal characters, and UTF-8 encoding for text value pairs. /// </summary> /// <param name="value"></param> /// <seealso cref="http://oauth.net/core/1.0#encoding_parameters" /> public static string UrlEncodeStrict(string value) { // From oauth spec above: - // Characters not in the unreserved character set ([RFC3986] // (Berners-Lee, T., "Uniform Resource Identifiers (URI): // Generic Syntax," .) section 2.3) MUST be encoded. // ... // unreserved = ALPHA, DIGIT, '-', '.', '_', '~' string result = ""; value.ForEach(c => { result += UNRESERVED.Contains(c) ? c.ToString() : c.ToString() .PercentEncode(); }); return result; } /// <summary> /// Sorts a collection of key-value pairs by name, and then value if equal, /// concatenating them into a single string. This string should be encoded /// prior to, or after normalization is run. /// </summary> /// <seealso cref="http://oauth.net/core/1.0#rfc.section.9.1.1"/> /// <param name="parameters"></param> /// <returns></returns> public static string NormalizeRequestParameters(WebParameterCollection parameters) { WebParameterCollection copy = SortParametersExcludingSignature(parameters); string concatenated = copy.Concatenate("=", "&"); return concatenated; } /// <summary> /// Sorts a <see cref="WebParameterCollection"/> by name, and then value if equal. /// </summary> /// <param name="parameters">A collection of parameters to sort</param> /// <returns>A sorted parameter collection</returns> public static WebParameterCollection SortParametersExcludingSignature(WebParameterCollection parameters) { WebParameterCollection copy = new WebParameterCollection(parameters); IEnumerable<WebPair> exclusions = copy.Where(n => n.Name.EqualsIgnoreCase("oauth_signature")); copy.RemoveAll(exclusions); copy.ForEach(p => { p.Name = UrlEncodeStrict(p.Name); p.Value = UrlEncodeStrict(p.Value); }); copy.Sort((x, y) => string.CompareOrdinal(x.Name, y.Name) != 0 ? string.CompareOrdinal(x.Name, y.Name) : string.CompareOrdinal(x.Value, y.Value)); return copy; } /// <summary> /// Creates a request URL suitable for making OAuth requests. /// Resulting URLs must exclude port 80 or port 443 when accompanied by HTTP and HTTPS, respectively. /// Resulting URLs must be lower case. /// </summary> /// <seealso cref="http://oauth.net/core/1.0#rfc.section.9.1.2"/> /// <param name="url">The original request URL</param> /// <returns></returns> public static string ConstructRequestUrl(Uri url) { if (url == null) { throw new ArgumentNullException("url"); } StringBuilder sb = new StringBuilder(); string requestUrl = "{0}://{1}".FormatWith(url.Scheme, url.Host); string qualified = ":{0}".FormatWith(url.Port); bool basic = url.Scheme == "http" && url.Port == 80; bool secure = url.Scheme == "https" && url.Port == 443; sb.Append(requestUrl); sb.Append(!basic && !secure ? qualified : ""); sb.Append(url.AbsolutePath); return sb.ToString(); //.ToLower(); } /// <summary> /// Creates a request elements concatentation value to send with a request. /// This is also known as the signature base. /// </summary> /// <seealso cref="http://oauth.net/core/1.0#rfc.section.9.1.3"/> /// <seealso cref="http://oauth.net/core/1.0#sig_base_example"/> /// <param name="method">The request's HTTP method type</param> /// <param name="url">The request URL</param> /// <param name="parameters">The request's parameters</param> /// <returns>A signature base string</returns> public static string ConcatenateRequestElements(string method, string url, WebParameterCollection parameters) { StringBuilder sb = new StringBuilder(); // Separating &'s are not URL encoded string requestMethod = method.ToUpper().Then("&"); string requestUrl = UrlEncodeRelaxed(ConstructRequestUrl(url.AsUri())).Then("&"); string requestParameters = UrlEncodeRelaxed(NormalizeRequestParameters(parameters)); sb.Append(requestMethod); sb.Append(requestUrl); sb.Append(requestParameters); return sb.ToString(); } /// <summary> /// Creates a signature value given a signature base and the consumer secret. /// This method is used when the token secret is currently unknown. /// </summary> /// <seealso cref="http://oauth.net/core/1.0#rfc.section.9.2"/> /// <param name="signatureMethod">The hashing method</param> /// <param name="signatureBase">The signature base</param> /// <param name="consumerSecret">The consumer key</param> /// <returns></returns> public static string GetSignature(OAuthSignatureMethod signatureMethod, string signatureBase, string consumerSecret) { return GetSignature(signatureMethod, OAuthSignatureTreatment.Escaped, signatureBase, consumerSecret, null); } /// <summary> /// Creates a signature value given a signature base and the consumer secret. /// This method is used when the token secret is currently unknown. /// </summary> /// <seealso cref="http://oauth.net/core/1.0#rfc.section.9.2"/> /// <param name="signatureMethod">The hashing method</param> /// <param name="signatureTreatment">The treatment to use on a signature value</param> /// <param name="signatureBase">The signature base</param> /// <param name="consumerSecret">The consumer key</param> /// <returns></returns> public static string GetSignature(OAuthSignatureMethod signatureMethod, OAuthSignatureTreatment signatureTreatment, string signatureBase, string consumerSecret) { return GetSignature(signatureMethod, signatureTreatment, signatureBase, consumerSecret, null); } /// <summary> /// Creates a signature value given a signature base and the consumer secret and a known token secret. /// </summary> /// <seealso cref="http://oauth.net/core/1.0#rfc.section.9.2"/> /// <param name="signatureMethod">The hashing method</param> /// <param name="signatureBase">The signature base</param> /// <param name="consumerSecret">The consumer secret</param> /// <param name="tokenSecret">The token secret</param> /// <returns></returns> public static string GetSignature(OAuthSignatureMethod signatureMethod, string signatureBase, string consumerSecret, string tokenSecret) { return GetSignature(signatureMethod, OAuthSignatureTreatment.Escaped, consumerSecret, tokenSecret); } /// <summary> /// Creates a signature value given a signature base and the consumer secret and a known token secret. /// </summary> /// <seealso cref="http://oauth.net/core/1.0#rfc.section.9.2"/> /// <param name="signatureMethod">The hashing method</param> /// <param name="signatureTreatment">The treatment to use on a signature value</param> /// <param name="signatureBase">The signature base</param> /// <param name="consumerSecret">The consumer secret</param> /// <param name="tokenSecret">The token secret</param> /// <returns></returns> public static string GetSignature(OAuthSignatureMethod signatureMethod, OAuthSignatureTreatment signatureTreatment, string signatureBase, string consumerSecret, string tokenSecret) { if (tokenSecret.IsNullOrBlank()) { tokenSecret = string.Empty; } consumerSecret = UrlEncodeRelaxed(consumerSecret); tokenSecret = UrlEncodeRelaxed(tokenSecret); string signature; switch (signatureMethod) { case OAuthSignatureMethod.HmacSha1: { #if !WINDOWS_UWP HMACSHA1 crypto = new HMACSHA1(); string key = "{0}&{1}".FormatWith(consumerSecret, tokenSecret); crypto.Key = encoding.GetBytes(key); signature = signatureBase.HashWith(crypto); #else signature = signatureBase.HashWith(HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1)); #endif break; } case OAuthSignatureMethod.HmacSha256: { HMACSHA256 crypto = new HMACSHA256(); string key = "{0}&{1}".FormatWith(consumerSecret, tokenSecret); crypto.Key = encoding.GetBytes(key); signature = signatureBase.HashWith(crypto); break; } case OAuthSignatureMethod.PlainText: { signature = "{0}&{1}".FormatWith(consumerSecret, tokenSecret); break; } default: throw new NotImplementedException("Only HMAC-SHA1 and HMAC-SHA256 are currently supported."); } string result = signatureTreatment == OAuthSignatureTreatment.Escaped ? UrlEncodeRelaxed(signature) : signature; return result; } } }
using System; using System.Threading; using System.Threading.Tasks; using SharpEssentials.Concurrency; using Xunit; namespace SharpEssentials.Tests.Unit.SharpEssentials.Concurrency { public class TaskExtensionsTests { [Fact] public void Test_Then_WithResults_BothComplete() { // Act. Task<int> task = Task.Factory.StartNew(() => 1m, _cts.Token, TaskCreationOptions.None, _taskScheduler) .Then(result => Task<int>.Factory.StartNew(() => (int)result + 1, _cts.Token, TaskCreationOptions.None, _taskScheduler)); task.Wait(); // Assert. Assert.Equal(2, task.Result); Assert.Equal(TaskStatus.RanToCompletion, task.Status); } [Fact] public void Test_Then_WithResults_FirstCompletes_SecondFails() { // Act. Task<int> task = Task.Factory.StartNew(() => 1m, _cts.Token, TaskCreationOptions.None, _taskScheduler) .Then(result => Task<int>.Factory.StartNew(() => throw new InvalidOperationException(), _cts.Token, TaskCreationOptions.None, _taskScheduler)); // Assert. Assert.Throws<AggregateException>(() => task.Wait()); Assert.True(task.IsFaulted); Assert.NotNull(task.Exception); Assert.IsType<InvalidOperationException>(task.Exception.InnerException); } [Fact] public void Test_Then_WithResults_FirstCompletes_SecondFailsCreation() { // Act. Task<int> task = Task.Factory.StartNew(() => 1m, _cts.Token, TaskCreationOptions.None, _taskScheduler) .Then(result => (Task<int>)null); // Assert. var exception = Assert.Throws<AggregateException>(() => task.Wait()); Assert.True(task.IsCanceled); Assert.IsType<TaskCanceledException>(exception.InnerException); } [Fact] public void Test_Then_WithResults_FirstCompletes_SecondCanceled() { // Act. Task<int> task = Task.Factory.StartNew(() => 1m, _cts.Token, TaskCreationOptions.None, _taskScheduler) .Then(result => Task<int>.Factory.StartNew(() => { _cts.Cancel(); _cts.Token.ThrowIfCancellationRequested(); return 1; }, _cts.Token, TaskCreationOptions.None, _taskScheduler)); // Assert. var exception = Assert.Throws<AggregateException>(() => task.Wait()); Assert.True(task.IsCanceled); Assert.IsType<TaskCanceledException>(exception.InnerException); } [Fact] public void Test_Then_WithResults_FirstFails() { // Act. Task<int> task = Task<decimal>.Factory.StartNew(() => throw new InvalidOperationException(), _cts.Token, TaskCreationOptions.None, _taskScheduler) .Then(result => Task<int>.Factory.StartNew(() => (int)result + 1, _cts.Token, TaskCreationOptions.None, _taskScheduler)); // Assert. Assert.Throws<AggregateException>(() => task.Wait()); Assert.True(task.IsFaulted); Assert.NotNull(task.Exception); Assert.IsType<InvalidOperationException>(task.Exception.InnerException); } [Fact] public void Test_Then_WithResults_FirstCanceled() { // Act. Task<int> task = Task.Factory.StartNew(() => { _cts.Cancel(); _cts.Token.ThrowIfCancellationRequested(); return 1m; }, _cts.Token, TaskCreationOptions.None, _taskScheduler) .Then(result => Task<int>.Factory.StartNew(() => (int)result + 1, _cts.Token, TaskCreationOptions.None, _taskScheduler)); // Assert. var exception = Assert.Throws<AggregateException>(() => task.Wait()); Assert.True(task.IsCanceled); Assert.IsType<TaskCanceledException>(exception.InnerException); } [Fact] public void Test_Then_WithoutResults_BothComplete() { // Act. Task task = Task.Factory.StartNew(() => { }, _cts.Token, TaskCreationOptions.None, _taskScheduler) .Then(() => Task.Factory.StartNew(() => { }, _cts.Token, TaskCreationOptions.None, _taskScheduler)); task.Wait(); // Assert. Assert.Equal(TaskStatus.RanToCompletion, task.Status); } [Fact] public void Test_Then_WithoutResults_FirstCompletes_SecondFails() { // Act. Task task = Task.Factory.StartNew(() => { }, _cts.Token, TaskCreationOptions.None, _taskScheduler) .Then(() => Task.Factory.StartNew(() => throw new InvalidOperationException(), _cts.Token, TaskCreationOptions.None, _taskScheduler)); // Assert. Assert.Throws<AggregateException>(() => task.Wait()); Assert.True(task.IsFaulted); Assert.NotNull(task.Exception); Assert.IsType<InvalidOperationException>(task.Exception.InnerException); } [Fact] public void Test_Then_WithoutResults_FirstCompletes_SecondFailsCreation() { // Act. Task task = Task.Factory.StartNew(() => 1m, _cts.Token, TaskCreationOptions.None, _taskScheduler) .Then(() => (Task)null); // Assert. var exception = Assert.Throws<AggregateException>(() => task.Wait()); Assert.True(task.IsCanceled); Assert.IsType<TaskCanceledException>(exception.InnerException); } [Fact] public void Test_Then_WithoutResults_FirstCompletes_SecondCanceled() { // Act. Task task = Task.Factory.StartNew(() => 1m, _cts.Token, TaskCreationOptions.None, _taskScheduler) .Then(() => Task.Factory.StartNew(() => { _cts.Cancel(); _cts.Token.ThrowIfCancellationRequested();; }, _cts.Token, TaskCreationOptions.None, _taskScheduler)); // Assert. var exception = Assert.Throws<AggregateException>(() => task.Wait()); Assert.True(task.IsCanceled); Assert.IsType<TaskCanceledException>(exception.InnerException); } [Fact] public void Test_Then_WithoutResults_FirstFails() { // Act. Task task = Task<decimal>.Factory.StartNew(() => throw new InvalidOperationException(), _cts.Token, TaskCreationOptions.None, _taskScheduler) .Then(() => Task.Factory.StartNew(() => { }, _cts.Token, TaskCreationOptions.None, _taskScheduler)); // Assert. Assert.Throws<AggregateException>(() => task.Wait()); Assert.True(task.IsFaulted); Assert.NotNull(task.Exception); Assert.IsType<InvalidOperationException>(task.Exception.InnerException); } [Fact] public void Test_Then_WithoutResults_FirstCanceled() { // Act. Task task = Task.Factory.StartNew(() => { _cts.Cancel(); _cts.Token.ThrowIfCancellationRequested(); }, _cts.Token, TaskCreationOptions.None, _taskScheduler) .Then(() => Task.Factory.StartNew(() => { }, _cts.Token, TaskCreationOptions.None, _taskScheduler)); // Assert. var exception = Assert.Throws<AggregateException>(() => task.Wait()); Assert.True(task.IsCanceled); Assert.IsType<TaskCanceledException>(exception.InnerException); } [Fact] public void Test_Then_OnlySecondHasResults_BothComplete() { // Act. Task<int> task = Task.Factory.StartNew(() => { }, _cts.Token, TaskCreationOptions.None, _taskScheduler) .Then(() => Task<int>.Factory.StartNew(() => 1, _cts.Token, TaskCreationOptions.None, _taskScheduler)); task.Wait(); // Assert. Assert.Equal(1, task.Result); Assert.Equal(TaskStatus.RanToCompletion, task.Status); } [Fact] public void Test_Then_OnlySecondHasResults_FirstCompletes_SecondFails() { // Act. Task<int> task = Task.Factory.StartNew(() => { }, _cts.Token, TaskCreationOptions.None, _taskScheduler) .Then(() => Task<int>.Factory.StartNew(() => throw new InvalidOperationException(), _cts.Token, TaskCreationOptions.None, _taskScheduler)); // Assert. Assert.Throws<AggregateException>(() => task.Wait()); Assert.True(task.IsFaulted); Assert.NotNull(task.Exception); Assert.IsType<InvalidOperationException>(task.Exception.InnerException); } [Fact] public void Test_Then_OnlySecondHasResults_FirstCompletes_SecondFailsCreation() { // Act. Task<int> task = Task.Factory.StartNew(() => { }, _cts.Token, TaskCreationOptions.None, _taskScheduler) .Then(() => (Task<int>)null); // Assert. var exception = Assert.Throws<AggregateException>(() => task.Wait()); Assert.True(task.IsCanceled); Assert.IsType<TaskCanceledException>(exception.InnerException); } [Fact] public void Test_Then_OnlySecondHasResults_FirstCompletes_SecondCanceled() { // Act. Task<int> task = Task.Factory.StartNew(() => { }, _cts.Token, TaskCreationOptions.None, _taskScheduler) .Then(() => Task<int>.Factory.StartNew(() => { _cts.Cancel(); _cts.Token.ThrowIfCancellationRequested(); return 1; }, _cts.Token, TaskCreationOptions.None, _taskScheduler)); // Assert. var exception = Assert.Throws<AggregateException>(() => task.Wait()); Assert.True(task.IsCanceled); Assert.IsType<TaskCanceledException>(exception.InnerException); } [Fact] public void Test_Then_OnlySecondHasResults_FirstFails() { // Act. Task<int> task = Task.Factory.StartNew(() => throw new InvalidOperationException(), _cts.Token, TaskCreationOptions.None, _taskScheduler) .Then(() => Task<int>.Factory.StartNew(() => 1, _cts.Token, TaskCreationOptions.None, _taskScheduler)); // Assert. Assert.Throws<AggregateException>(() => task.Wait()); Assert.True(task.IsFaulted); Assert.NotNull(task.Exception); Assert.IsType<InvalidOperationException>(task.Exception.InnerException); } [Fact] public void Test_Then_OnlySecondHasResults_FirstCanceled() { // Act. Task<int> task = Task.Factory.StartNew(() => { _cts.Cancel(); _cts.Token.ThrowIfCancellationRequested(); }, _cts.Token, TaskCreationOptions.None, _taskScheduler) .Then(() => Task<int>.Factory.StartNew(() => 1, _cts.Token, TaskCreationOptions.None, _taskScheduler)); // Assert. var exception = Assert.Throws<AggregateException>(() => task.Wait()); Assert.True(task.IsCanceled); Assert.IsType<TaskCanceledException>(exception.InnerException); } [Fact] public void Test_Then_WithResult_Continuation_BothComplete() { // Act. Task<string> task = Task.Factory.StartNew(() => 1m, _cts.Token, TaskCreationOptions.None, _taskScheduler) .Then(result => result.ToString()); task.Wait(); // Assert. Assert.Equal("1", task.Result); } [Fact] public void Test_Then_WithResult_Continuation_TaskFails() { // Act. Task<string> task = Task<int>.Factory.StartNew(() => throw new InvalidOperationException(), _cts.Token, TaskCreationOptions.None, _taskScheduler) .Then(result => result.ToString()); // Assert. Assert.Throws<AggregateException>(() => task.Wait()); Assert.True(task.IsFaulted); Assert.NotNull(task.Exception); Assert.IsType<InvalidOperationException>(task.Exception.InnerException); } [Fact] public void Test_Then_WithResult_Continuation_TaskCancelled() { // Act. Task<string> task = Task<decimal>.Factory.StartNew(() => { _cts.Cancel(); _cts.Token.ThrowIfCancellationRequested(); return 1m; }, _cts.Token, TaskCreationOptions.None, _taskScheduler) .Then(result => result.ToString()); // Assert. var exception = Assert.Throws<AggregateException>(() => task.Wait()); Assert.True(task.IsCanceled); Assert.IsType<TaskCanceledException>(exception.InnerException); } [Fact] public void Test_Then_WithResult_Continuation_ContinuationFails() { // Act. Task<string> task = Task.Factory.StartNew(() => 1m, _cts.Token, TaskCreationOptions.None, _taskScheduler) .Then(new Func<decimal, string>(result => throw new InvalidOperationException())); // Assert. Assert.Throws<AggregateException>(() => task.Wait()); Assert.True(task.IsFaulted); Assert.NotNull(task.Exception); Assert.IsType<InvalidOperationException>(task.Exception.InnerException); } [Fact] public void Test_Then_WithoutResult_Continuation_BothComplete() { // Arrange. bool continued = false; // Act. Task task = Task.Factory.StartNew(() => { }, _cts.Token, TaskCreationOptions.None, _taskScheduler) .Then(() => continued = true); task.Wait(); // Assert. Assert.True(continued); } [Fact] public void Test_Then_WithoutResult_Continuation_TaskFails() { // Arrange. bool continued = false; // Act. Task task = Task.Factory.StartNew(() => throw new InvalidOperationException(), _cts.Token, TaskCreationOptions.None, _taskScheduler) .Then(() => continued = true); // Assert. Assert.Throws<AggregateException>(() => task.Wait()); Assert.True(task.IsFaulted); Assert.NotNull(task.Exception); Assert.IsType<InvalidOperationException>(task.Exception.InnerException); Assert.False(continued); } [Fact] public void Test_Then_WithoutResult_Continuation_TaskCancelled() { // Arrange. bool continued = false; // Act. Task task = Task.Factory.StartNew(() => { _cts.Cancel(); _cts.Token.ThrowIfCancellationRequested(); }, _cts.Token, TaskCreationOptions.None, _taskScheduler) .Then(() => continued = true); // Assert. var exception = Assert.Throws<AggregateException>(() => task.Wait()); Assert.True(task.IsCanceled); Assert.IsType<TaskCanceledException>(exception.InnerException); Assert.False(continued); } [Fact] public void Test_Then_WithoutResult_Continuation_ContinuationFails() { // Act. Task task = Task.Factory.StartNew(() => { }, _cts.Token, TaskCreationOptions.None, _taskScheduler) .Then(new Action(() => throw new InvalidOperationException())); // Assert. Assert.Throws<AggregateException>(() => task.Wait()); Assert.True(task.IsFaulted); Assert.NotNull(task.Exception); Assert.IsType<InvalidOperationException>(task.Exception.InnerException); } private readonly TaskScheduler _taskScheduler = new SynchronousTaskScheduler(); private readonly CancellationTokenSource _cts = new CancellationTokenSource(); } }
using System.Collections.Generic; using System.Text; using com.calitha.goldparser; using Epi.Core.EnterInterpreter.Rules; using EpiInfo.Plugin; namespace Epi.Core.EnterInterpreter { public abstract class EnterRule : ICommand { protected List<string> NumericTypeList = new List<string>(new string[] { "INT", "FLOAT", "INT16", "INT32", "INT64", "SINGLE", "DOUBLE", "BYTE", "DECIMAL" }); public Rule_Context Context; #region Constructors public EnterRule() { this.Context = new Rule_Context(); } public EnterRule(Rule_Context pContext) { this.Context = pContext; } #endregion Constructors public abstract object Execute(); public virtual void ToJavaScript(StringBuilder pJavaScriptBuilder) { return; } public override string ToString() { return ""; } public virtual bool IsNull() { return false; } protected string BoolVal(bool isTrue) { if (isTrue) { return "true"; } else { return "false"; } } protected bool IsNumeric(string value) { System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(@"^[-+]?\d+\.?\d*$|^[-+]?\d*\.?\d+$"); return re.IsMatch(value); } protected object ConvertStringToBoolean(string pValue) { object result = null; switch (pValue.ToUpper()) { case "(+)": case "YES": case "Y": case "TRUE": case "T": result = true; break; case "(-)": case "NO": case "N": case "FALSE": case "F": result = false; break; } return result; } /// <summary> /// Returns the DataType enumeration for the data type name passed /// </summary> /// <param name="typeName"></param> /// <returns>DataType</returns> protected EpiInfo.Plugin.DataType GetDataType(string typeName) { EpiInfo.Plugin.DataType type = EpiInfo.Plugin.DataType.Unknown; if (!string.IsNullOrWhiteSpace(typeName)) { switch (typeName.ToUpper()) { case "NUMERIC": case "NUMBER": type = EpiInfo.Plugin.DataType.Number; break; case "TEXT": case "TEXTINPUT": type = EpiInfo.Plugin.DataType.Text; break; case "DATE": case "DATEFORMAT": type = EpiInfo.Plugin.DataType.Date; break; case "TIME": case "TIMEFORMAT": type = EpiInfo.Plugin.DataType.Time; break; case "DATETIME": case "DATETIMEFORMAT": type = EpiInfo.Plugin.DataType.DateTime; break; case "PHONENUMBER": type = EpiInfo.Plugin.DataType.PhoneNumber; break; case "BOOLEAN": case "YESNO": case "YN": type = EpiInfo.Plugin.DataType.Boolean; break; case "GUID": type = EpiInfo.Plugin.DataType.GUID; break; case "DLLOBJECT": case "OBJECT": type = EpiInfo.Plugin.DataType.Object; break; case "UNKNOWN": default: type = EpiInfo.Plugin.DataType.Unknown; break; } } return type; } // zack 1/10/2008, for getting command parameter element without parsing strings /// <summary> /// Developer can get Command parameter element without parsing tokens /// </summary> /// <param name="tokens">tokens parameter from the parser</param> /// <param name="index">Element Index in the command</param> /// <returns></returns> protected string GetCommandElement(Token[] tokens, int index) { if (tokens[0] is NonterminalToken) { if (((NonterminalToken)tokens[0]).Tokens[index] is NonterminalToken) { return ExtractTokens(((NonterminalToken)((NonterminalToken)tokens[0]).Tokens[index]).Tokens).Trim(); } else { return (((NonterminalToken)tokens[0]).Tokens[index]).ToString(); } } else { if (tokens[index] is NonterminalToken) { return ExtractTokens(((NonterminalToken)tokens[index]).Tokens).Trim(); } else { return (tokens[index]).ToString(); } } } /// <summary> /// Build a string composed of all tokens in tree. /// </summary> /// <param name="tokens">tokens</param> /// <returns>string</returns> protected string ExtractTokens(Token[] tokens) { int max = tokens.GetUpperBound(0); string tokensInTree = ""; for (int i = tokens.GetLowerBound(0); i <= max; i++) { if (tokens[i] is NonterminalToken) { tokensInTree += ExtractTokens(((NonterminalToken)tokens[i]).Tokens); } else { tokensInTree += tokens[i].ToString() + " "; } } return tokensInTree; } /// <summary> /// Build a string composed of all tokens in tree. /// </summary> /// <param name="tokens">tokens</param> /// <returns>string</returns> protected string ExtractTokensWithFormat(Token[] tokens) { int max = tokens.GetUpperBound(0); string tokensInTree = ""; for (int i = tokens.GetLowerBound(0); i <= max; i++) { if (tokens[i] is NonterminalToken) { tokensInTree += "\t" + ExtractTokensWithFormat(((NonterminalToken)tokens[i]).Tokens); } else { tokensInTree += tokens[i].ToString() + " "; } } return tokensInTree + "\n"; } private static bool FoundName(string[] varNames, string name) { foreach (string variableName in varNames) { if (string.Compare(variableName, name, true) == 0) { return true; } } return false; } /// <summary> /// creates a negateexp from a token /// </summary> /// <returns>Rule_NegateExp</returns> public string CreateNegateRecode(Token pToken) { NonterminalToken T = (NonterminalToken)((NonterminalToken)pToken).Tokens[0]; Rule_NegateExp result = new Rule_NegateExp(this.Context, T); return result.Execute().ToString(); } static public EnterRule BuildStatments(Rule_Context pContext, Token pToken) { EnterRule result = null; if (pToken is NonterminalToken) { NonterminalToken NT = (NonterminalToken)pToken; switch (NT.Symbol.ToString()) { // H1N1 case "<Program>": result = new Rule_Program(pContext, NT); break; case "<Always_Statement>": result = new Rule_Always(pContext, NT); break; case "<Simple_Assign_Statement>": case "<Let_Statement>": case "<Assign_Statement>": result = new Rule_Assign(pContext, NT); break; case "<Assign_DLL_Statement>": result = new Rule_Assign_DLL_Statement(pContext, NT); break; case "<If_Statement>": case "<If_Else_Statement>": result = new Rule_If_Then_Else_End(pContext, NT); break; case "<Else_If_Statement>": result = new Rule_Else_If_Statement(pContext, NT); break; case "<Define_Variable_Statement>": result = new Rule_Define(pContext, NT); break; case "<Define_Dll_Statement>": result = new Rule_DLL_Statement(pContext, NT); break; case "<FuncName2>": case "<FunctionCall>": result = new Rule_FunctionCall(pContext, NT); break; case "<Hide_Some_Statement>": case "<Hide_Except_Statement>": result = new Rule_Hide(pContext, NT); break; case "<Unhide_Some_Statement>": case "<Unhide_Except_Statement>": result = new Rule_UnHide(pContext, NT); break; case "<Go_To_Variable_Statement>": case "<Go_To_Page_Statement>": result = new Rule_GoTo(pContext, NT); break; case "<Simple_Dialog_Statement>": case "<Numeric_Dialog_Implicit_Statement>": case "<Numeric_Dialog_Explicit_Statement>": case "<TextBox_Dialog_Statement>": case "<Db_Values_Dialog_Statement>": case "<YN_Dialog_Statement>": case "<Db_Views_Dialog_Statement>": case "<Databases_Dialog_Statement>": case "<Db_Variables_Dialog_Statement>": case "<Multiple_Choice_Dialog_Statement>": case "<Dialog_Read_Statement>": case "<Dialog_Write_Statement>": case "<Dialog_Read_Filter_Statement>": case "<Dialog_Write_Filter_Statement>": case "<Dialog_Date_Statement>": case "<Dialog_Date_Mask_Statement>": result = new Rule_Dialog(pContext, NT); break; case "<Comment_Line>": result = new Rule_CommentLine(pContext, NT); break; case "<Simple_Execute_Statement>": case "<Execute_File_Statement>": case "<Execute_Url_Statement>": case "<Execute_Wait_For_Exit_File_Statement>": case "<Execute_Wait_For_Exit_String_Statement>": case "<Execute_Wait_For_Exit_Url_Statement>": case "<Execute_No_Wait_For_Exit_File_Statement>": case "<Execute_No_Wait_For_Exit_String_Statement>": case "<Execute_No_Wait_For_Exit_Url_Statement>": result = new Rule_Execute(pContext, NT); break; case "<Beep_Statement>": result = new Rule_Beep(pContext, NT); break; case "<Auto_Search_Statement>": result = new Rule_AutoSearch(pContext, NT); break; case "<Quit_Statement>": result = new Rule_Quit(pContext); break; case "<Clear_Statement>": result = new Rule_Clear(pContext, NT); break; case "<New_Record_Statement>": result = new Rule_NewRecord(pContext, NT); break; case "<Simple_Undefine_Statement>": result = new Rule_Undefine(pContext, NT); break; case "<Geocode_Statement>": result = new Rule_Geocode(pContext, NT); break; case "<DefineVariables_Statement>": result = new Rule_DefineVariables_Statement(pContext, NT); break; case "<Field_Checkcode_Statement>": result = new Rule_Field_Checkcode_Statement(pContext, NT); break; case "<View_Checkcode_Statement>": result = new Rule_View_Checkcode_Statement(pContext, NT); break; case "<Record_Checkcode_Statement>": result = new Rule_Record_Checkcode_Statement(pContext, NT); break; case "<Page_Checkcode_Statement>": result = new Rule_Page_Checkcode_Statement(pContext, NT); break; case "<Subroutine_Statement>": result = new Rule_Subroutine_Statement(pContext, NT); break; case "<Call_Statement>": result = new Rule_Call(pContext, NT); break; case "<Expr List>": result = new Rule_ExprList(pContext, NT); break; case "<Expression>": result = new Rule_Expression(pContext, NT); break; case "<And Exp>": result = new Rule_AndExp(pContext, NT); break; case "<Not Exp>": result = new Rule_NotExp(pContext, NT); break; case "<Compare Exp>": result = new Rule_CompareExp(pContext, NT); break; case "<Concat Exp>": result = new Rule_ConcatExp(pContext, NT); break; case "<Add Exp>": result = new Rule_AddExp(pContext, NT); break; case "<Mult Exp>": result = new Rule_MultExp(pContext, NT); break; case "<Pow Exp>": result = new Rule_PowExp(pContext, NT); break; case "<Negate Exp>": result = new Rule_NegateExp(pContext, NT); break; case "<Begin_Before_statement>": result = new Rule_Begin_Before_Statement(pContext, NT); break; case "<Begin_After_statement>": result = new Rule_Begin_After_Statement(pContext, NT); break; case "<Begin_Click_statement>": result = new Rule_Begin_Click_Statement(pContext, NT); break; case "<CheckCodeBlock>": result = new Rule_CheckCodeBlock(pContext, NT); break; case "<CheckCodeBlocks>": result = new Rule_CheckCodeBlocks(pContext, NT); break; case "<Simple_Run_Statement>": break; case "<Statements>": result = new Rule_Statements(pContext, NT); break; case "<Statement>": result = new Rule_Statement(pContext, NT); break; case "<Define_Statement_Group>": result = new Rule_Define_Statement_Group(pContext, NT); break; case "<Define_Statement_Type>": result = new Rule_Define_Statement_Type(pContext, NT); break; case "<Highlight_Statement>": result = new Rule_Highlight(pContext, NT); break; case "<UnHighlight_Statement>": result = new Rule_UnHighlight(pContext, NT); break; case "<Enable_Statement>": result = new Rule_Enable(pContext, NT); break; case "<Disable_Statement>": result = new Rule_Disable(pContext, NT); break; case "<Set_Required_Statement>": result = new Rule_SetRequired(pContext, NT); break; case "<Set_Not_Required_Statement>": result = new Rule_SetNOTRequired(pContext, NT); break; case "<Value>": default: result = new Rule_Value(pContext, NT); break; //result = new Rule_Value(pContext, NT); //throw new Exception("Missing rule in EnterRule.BuildStatments " + NT.Symbol.ToString()); } } else // terminal token { TerminalToken TT = (TerminalToken)pToken; switch (TT.Symbol.ToString()) { case "<Value>": default: result = new Rule_Value(pContext, TT); break; } } return result; } static public List<EnterRule> GetFunctionParameters(Rule_Context pContext, Token pToken) { List<EnterRule> result = new List<EnterRule>(); if (pToken is NonterminalToken) { NonterminalToken NT = (NonterminalToken)pToken; switch (NT.Symbol.ToString()) { case "<NonEmptyFunctionParameterList>": //this.paramList.Push(new Rule_NonEmptyFunctionParameterList(T, this.paramList)); result.AddRange(EnterRule.GetFunctionParameters(pContext, NT)); break; case "<SingleFunctionParameterList>": result.AddRange(EnterRule.GetFunctionParameters(pContext, NT)); break; case "<EmptyFunctionParameterList>": //this.paramList = new Rule_EmptyFunctionParameterList(T); // do nothing the parameterlist is empty break; case "<MultipleFunctionParameterList>": //this.MultipleParameterList = new Rule_MultipleFunctionParameterList(pToken); //<NonEmptyFunctionParameterList> ',' <Expression> //result.Add(AnalysisRule.BuildStatments(pContext, NT.Tokens[0])); result.AddRange(EnterRule.GetFunctionParameters(pContext, NT.Tokens[0])); result.Add(EnterRule.BuildStatments(pContext, NT.Tokens[2])); break; case "<FuncName2>": case "<Expression>": case "<expression>": case "<FunctionCall>": default: result.Add(EnterRule.BuildStatments(pContext, NT)); break; } } else { TerminalToken TT = (TerminalToken)pToken; if (TT.Text != ",") { result.Add(new Rule_Value(pContext, pToken)); } } /* <FunctionCall> ::= Identifier '(' <FunctionParameterList> ')' | FORMAT '(' <FunctionParameterList> ')' | <FuncName2> ! | <FuncName1> '(' <FunctionCall> ')' <FunctionParameterList> ::= <EmptyFunctionParameterList> | <NonEmptyFunctionParameterList> <NonEmptyFunctionParameterList> ::= <MultipleFunctionParameterList> | <SingleFunctionParameterList> <MultipleFunctionParameterList> ::= <NonEmptyFunctionParameterList> ',' <Expression> <SingleFunctionParameterList> ::= <expression> <EmptyFunctionParameterList> ::= */ /* foreach (Token T in pToken.Tokens) { if (T is NonterminalToken) { NonterminalToken NT = (NonterminalToken)T; switch (NT.Rule.Lhs.ToString()) { case "<NonEmptyFunctionParameterList>": //this.paramList.Push(new Rule_NonEmptyFunctionParameterList(T, this.paramList)); result.AddRange(EnterRule.GetFunctionParameters(pContext, NT)); break; case "<SingleFunctionParameterList>": result.AddRange(EnterRule.GetFunctionParameters(pContext, NT)); break; case "<EmptyFunctionParameterList>": //this.paramList = new Rule_EmptyFunctionParameterList(T); // do nothing the parameterlist is empty break; case "<MultipleFunctionParameterList>": //this.MultipleParameterList = new Rule_MultipleFunctionParameterList(pToken); result.AddRange(EnterRule.GetFunctionParameters(pContext, NT)); break; case "<FuncName2>": case "<Expression>": case "<expression>": case "<FunctionCall>": result.Add(EnterRule.BuildStatments(pContext, NT)); break; default: result.Add(new Rule_Value(pContext, T)); break; } } else { TerminalToken TT = (TerminalToken)T; if (TT.Text != ",") { result.Add(new Rule_Value(pContext, TT)); } } }*/ return result; } } }
using System; /// <summary> /// ctor(System.Int32,System.Int32,System.Int32) /// </summary> public class DateTimeCtor1 { #region Private Fields private int m_ErrorNo = 0; #endregion #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: We can call ctor(System.Int32,System.Int32,System.Int32) to constructor a new DateTime instance by using valid value"); try { retVal = retVal && VerifyDateTimeHelper(2006, 8, 28); } catch (Exception e) { m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: We can call ctor(System.Int32,System.Int32,System.Int32) to constructor a new DateTime instance by using MAX/MIN values"); try { retVal = retVal && VerifyDateTimeHelper(1, 1, 1); retVal = retVal && VerifyDateTimeHelper(9999, 12, 31); retVal = retVal && VerifyDateTimeHelper(1, 12, 31); retVal = retVal && VerifyDateTimeHelper(9999, 1, 1); retVal = retVal && VerifyDateTimeHelper(2000, 1, 31); retVal = retVal && VerifyDateTimeHelper(2000, 2, 29); retVal = retVal && VerifyDateTimeHelper(2001, 2, 28); retVal = retVal && VerifyDateTimeHelper(2001, 4, 30); } catch (Exception e) { m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: We can call ctor(System.Int32,System.Int32,System.Int32) to constructor a new DateTime instance by using correct day/month pair"); try { retVal = retVal && VerifyDateTimeHelper(2000, 2, 29); retVal = retVal && VerifyDateTimeHelper(2006, 2, 28); retVal = retVal && VerifyDateTimeHelper(2006, 4, 30); } catch (Exception e) { m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentOutOfRangeException should be thrown when year is less than 1 or greater than 9999."); try { DateTime value = new DateTime(0, 1, 1); m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when year is less than 1"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } try { DateTime value = new DateTime(10000, 1, 1); m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when year is greater than 9999"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: ArgumentOutOfRangeException should be thrown when month is less than 1 or greater than 12"); try { DateTime value = new DateTime(2006, 0, 1); m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when month is less than 1"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } try { DateTime value = new DateTime(2006, 13, 1); m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when month is greater than 12"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3: ArgumentOutOfRangeException should be thrown when day is less than 1 or greater than the number of days in month"); try { DateTime value = new DateTime(2006, 1, 0); m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when day is less than 1"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } try { DateTime value = new DateTime(2006, 1, 32); m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when day is greater than the number of days in month"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } try { DateTime value = new DateTime(2006, 2, 29); m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when day is greater than the number of days in month"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } try { DateTime value = new DateTime(2006, 4, 31); m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "ArgumentOutOfRangeException is not thrown when day is greater than the number of days in month"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { m_ErrorNo++; TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { DateTimeCtor1 test = new DateTimeCtor1(); TestLibrary.TestFramework.BeginTestCase("DateTimeCtor1"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } #region Private Methods private bool VerifyDateTimeHelper(int desiredYear, int desiredMonth, int desiredDay) { bool retVal = true; DateTime value = new DateTime(desiredYear, desiredMonth, desiredDay); m_ErrorNo++; if ((desiredYear != value.Year) || (desiredMonth != value.Month) || (desiredDay != value.Day)) { TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "We can call ctor(System.Int32,System.Int32,System.Int32) to constructor a wrong DateTime instance by using valid value"); TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] desiredYear = " + desiredYear.ToString() + ", desiredMonth = " + desiredMonth.ToString() + ", desiredDay = " + desiredDay.ToString() + ", actualYear = " + value.Year.ToString() + ", actualMonth = " + value.Month.ToString() + ", actualDay = " + value.Day.ToString()); retVal = false; } m_ErrorNo++; if ((value.Hour != 0) || (value.Minute != 0) || (value.Second != 0)) { TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "We can call ctor(System.Int32,System.Int32,System.Int32) to constructor a wrong DateTime instance by using valid value"); TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] desiredHour = 0, desiredMinute = 0, desiredSecond = 0, actualHour = " + value.Hour.ToString() + ", actualMinute = " + value.Minute.ToString() + ", actualSecond = " + value.Second.ToString()); retVal = false; } m_ErrorNo++; if (value.Kind != DateTimeKind.Unspecified) { TestLibrary.TestFramework.LogError(m_ErrorNo.ToString(), "We can call ctor(System.Int32,System.Int32,System.Int32) to constructor a wrong DateTime instance by using valid value"); TestLibrary.TestFramework.LogInformation("[LOCAL VARIABLES] desiredKind = DateTimeKind.Unspecified" + ", actualKind = " + value.Kind.ToString()); retVal = false; } return retVal; } #endregion }
/* * Copyright 2002-2015 Drew Noakes * * Modified by Yakov Danilov <yakodani@gmail.com> for Imazen LLC (Ported from Java to C#) * 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. * * More information about this project is available at: * * https://drewnoakes.com/code/exif/ * https://github.com/drewnoakes/metadata-extractor */ using System; using System.Collections.Generic; using System.IO; using Com.Drew.Imaging.Bmp; using Com.Drew.Imaging.Gif; using Com.Drew.Imaging.Ico; using Com.Drew.Imaging.Jpeg; using Com.Drew.Imaging.Pcx; using Com.Drew.Imaging.Png; using Com.Drew.Imaging.Psd; using Com.Drew.Imaging.Tiff; using Com.Drew.Imaging.Webp; using Com.Drew.Lang; using Com.Drew.Metadata; using Com.Drew.Metadata.Exif; using Com.Drew.Metadata.File; using JetBrains.Annotations; using Sharpen; namespace Com.Drew.Imaging { /// <summary> /// Obtains /// <see cref="Com.Drew.Metadata.Metadata"/> /// from all supported file formats. /// <p> /// This class a lightweight wrapper around specific file type processors: /// <ul> /// <li> /// <see cref="Com.Drew.Imaging.Jpeg.JpegMetadataReader"/> /// for JPEG files</li> /// <li> /// <see cref="Com.Drew.Imaging.Tiff.TiffMetadataReader"/> /// for TIFF and (most) RAW files</li> /// <li> /// <see cref="Com.Drew.Imaging.Psd.PsdMetadataReader"/> /// for Photoshop files</li> /// <li> /// <see cref="Com.Drew.Imaging.Png.PngMetadataReader"/> /// for BMP files</li> /// <li> /// <see cref="Com.Drew.Imaging.Bmp.BmpMetadataReader"/> /// for BMP files</li> /// <li> /// <see cref="Com.Drew.Imaging.Gif.GifMetadataReader"/> /// for GIF files</li> /// </ul> /// If you know the file type you're working with, you may use one of the above processors directly. /// For most scenarios it is simpler, more convenient and more robust to use this class. /// <p> /// <see cref="FileTypeDetector"/> /// is used to determine the provided image's file type, and therefore /// the appropriate metadata reader to use. /// </summary> /// <author>Drew Noakes https://drewnoakes.com</author> public class ImageMetadataReader { /// <summary> /// Reads metadata from an /// <see cref="System.IO.InputStream"/> /// . /// <p> /// The file type is determined by inspecting the leading bytes of the stream, and parsing of the file /// is delegated to one of: /// <ul> /// <li> /// <see cref="Com.Drew.Imaging.Jpeg.JpegMetadataReader"/> /// for JPEG files</li> /// <li> /// <see cref="Com.Drew.Imaging.Tiff.TiffMetadataReader"/> /// for TIFF and (most) RAW files</li> /// <li> /// <see cref="Com.Drew.Imaging.Psd.PsdMetadataReader"/> /// for Photoshop files</li> /// <li> /// <see cref="Com.Drew.Imaging.Png.PngMetadataReader"/> /// for PNG files</li> /// <li> /// <see cref="Com.Drew.Imaging.Bmp.BmpMetadataReader"/> /// for BMP files</li> /// <li> /// <see cref="Com.Drew.Imaging.Gif.GifMetadataReader"/> /// for GIF files</li> /// </ul> /// </summary> /// <param name="inputStream"> /// a stream from which the file data may be read. The stream must be positioned at the /// beginning of the file's data. /// </param> /// <returns> /// a populated /// <see cref="Com.Drew.Metadata.Metadata"/> /// object containing directories of tags with values and any processing errors. /// </returns> /// <exception cref="ImageProcessingException">if the file type is unknown, or for general processing errors.</exception> /// <exception cref="Com.Drew.Imaging.ImageProcessingException"/> /// <exception cref="System.IO.IOException"/> [NotNull] public static Com.Drew.Metadata.Metadata ReadMetadata([NotNull] InputStream inputStream) { BufferedInputStream bufferedInputStream = inputStream is BufferedInputStream ? (BufferedInputStream)inputStream : new BufferedInputStream(inputStream); FileType fileType = FileTypeDetector.DetectFileType(bufferedInputStream) ?? FileType.Unknown; if (fileType == FileType.Jpeg) { return JpegMetadataReader.ReadMetadata(bufferedInputStream); } if (fileType == FileType.Tiff || fileType == FileType.Arw || fileType == FileType.Cr2 || fileType == FileType.Nef || fileType == FileType.Orf || fileType == FileType.Rw2) { return TiffMetadataReader.ReadMetadata(bufferedInputStream); } if (fileType == FileType.Psd) { return PsdMetadataReader.ReadMetadata(bufferedInputStream); } if (fileType == FileType.Png) { return PngMetadataReader.ReadMetadata(bufferedInputStream); } if (fileType == FileType.Bmp) { return BmpMetadataReader.ReadMetadata(bufferedInputStream); } if (fileType == FileType.Gif) { return GifMetadataReader.ReadMetadata(bufferedInputStream); } if (fileType == FileType.Ico) { return IcoMetadataReader.ReadMetadata(bufferedInputStream); } if (fileType == FileType.Pcx) { return PcxMetadataReader.ReadMetadata(bufferedInputStream); } if (fileType == FileType.Riff) { return WebpMetadataReader.ReadMetadata(bufferedInputStream); } throw new ImageProcessingException("File format is not supported"); } /// <summary> /// Reads /// <see cref="Com.Drew.Metadata.Metadata"/> /// from a /// <see cref="Sharpen.FilePath"/> /// object. /// <p> /// The file type is determined by inspecting the leading bytes of the stream, and parsing of the file /// is delegated to one of: /// <ul> /// <li> /// <see cref="Com.Drew.Imaging.Jpeg.JpegMetadataReader"/> /// for JPEG files</li> /// <li> /// <see cref="Com.Drew.Imaging.Tiff.TiffMetadataReader"/> /// for TIFF and (most) RAW files</li> /// <li> /// <see cref="Com.Drew.Imaging.Psd.PsdMetadataReader"/> /// for Photoshop files</li> /// <li> /// <see cref="Com.Drew.Imaging.Png.PngMetadataReader"/> /// for PNG files</li> /// <li> /// <see cref="Com.Drew.Imaging.Bmp.BmpMetadataReader"/> /// for BMP files</li> /// <li> /// <see cref="Com.Drew.Imaging.Gif.GifMetadataReader"/> /// for GIF files</li> /// </ul> /// </summary> /// <param name="file">a file from which the image data may be read.</param> /// <returns> /// a populated /// <see cref="Com.Drew.Metadata.Metadata"/> /// object containing directories of tags with values and any processing errors. /// </returns> /// <exception cref="ImageProcessingException">for general processing errors.</exception> /// <exception cref="Com.Drew.Imaging.ImageProcessingException"/> /// <exception cref="System.IO.IOException"/> [NotNull] public static Com.Drew.Metadata.Metadata ReadMetadata([NotNull] FilePath file) { InputStream inputStream = new FileInputStream(file); Com.Drew.Metadata.Metadata metadata; try { metadata = ReadMetadata(inputStream); } finally { inputStream.Close(); } new FileMetadataReader().Read(file, metadata); return metadata; } /// <exception cref="System.Exception"/> private ImageMetadataReader() { throw new Exception("Not intended for instantiation"); } /// <summary>An application entry point.</summary> /// <remarks> /// An application entry point. Takes the name of one or more files as arguments and prints the contents of all /// metadata directories to <code>System.out</code>. /// <p> /// If <code>-thumb</code> is passed, then any thumbnail data will be written to a file with name of the /// input file having <code>.thumb.jpg</code> appended. /// <p> /// If <code>-markdown</code> is passed, then output will be in markdown format. /// <p> /// If <code>-hex</code> is passed, then the ID of each tag will be displayed in hexadecimal. /// </remarks> /// <param name="args">the command line arguments</param> /// <exception cref="Com.Drew.Metadata.MetadataException"/> /// <exception cref="System.IO.IOException"/> public static void Main([NotNull] string[] args) { ICollection<string> argList = new AList<string>(Arrays.AsList(args)); bool thumbRequested = argList.Remove("-thumb"); bool markdownFormat = argList.Remove("-markdown"); bool showHex = argList.Remove("-hex"); if (argList.Count < 1) { string version = typeof(Com.Drew.Imaging.ImageMetadataReader).Assembly.GetImplementationVersion(); System.Console.Out.Println("metadata-extractor version " + version); System.Console.Out.Println(); System.Console.Out.Println(Sharpen.Extensions.StringFormat("Usage: java -jar metadata-extractor-%s.jar <filename> [<filename>] [-thumb] [-markdown] [-hex]", version == null ? "a.b.c" : version)); System.Environment.Exit(1); } foreach (string filePath in argList) { long startTime = Runtime.NanoTime(); FilePath file = new FilePath(filePath); if (!markdownFormat && argList.Count > 1) { System.Console.Out.Printf("\n***** PROCESSING: %s\n%n", filePath); } Com.Drew.Metadata.Metadata metadata = null; try { metadata = Com.Drew.Imaging.ImageMetadataReader.ReadMetadata(file); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e, System.Console.Error); System.Environment.Exit(1); } long took = Runtime.NanoTime() - startTime; if (!markdownFormat) { System.Console.Out.Printf("Processed %.3f MB file in %.2f ms%n%n", file.Length() / (1024d * 1024), took / 1000000d); } if (markdownFormat) { string fileName = file.GetName(); string urlName = StringUtil.UrlEncode(filePath); ExifIFD0Directory exifIFD0Directory = metadata.GetFirstDirectoryOfType<ExifIFD0Directory>(); string make = exifIFD0Directory == null ? string.Empty : exifIFD0Directory.GetString(ExifIFD0Directory.TagMake); string model = exifIFD0Directory == null ? string.Empty : exifIFD0Directory.GetString(ExifIFD0Directory.TagModel); System.Console.Out.Println(); System.Console.Out.Println("---"); System.Console.Out.Println(); System.Console.Out.Printf("# %s - %s%n", make, model); System.Console.Out.Println(); System.Console.Out.Printf("<a href=\"https://raw.githubusercontent.com/drewnoakes/metadata-extractor-images/master/%s\">%n", urlName); System.Console.Out.Printf("<img src=\"https://raw.githubusercontent.com/drewnoakes/metadata-extractor-images/master/%s\" width=\"300\"/><br/>%n", urlName); System.Console.Out.Println(fileName); System.Console.Out.Println("</a>"); System.Console.Out.Println(); System.Console.Out.Println("Directory | Tag Id | Tag Name | Extracted Value"); System.Console.Out.Println(":--------:|-------:|----------|----------------"); } // iterate over the metadata and print to System.out foreach (Com.Drew.Metadata.Directory directory in metadata.GetDirectories()) { string directoryName = directory.GetName(); foreach (Tag tag in directory.GetTags()) { string tagName = tag.GetTagName(); string description = tag.GetDescription(); // truncate the description if it's too long if (description != null && description.Length > 1024) { description = Sharpen.Runtime.Substring(description, 0, 1024) + "..."; } if (markdownFormat) { System.Console.Out.Printf("%s|0x%s|%s|%s%n", directoryName, Sharpen.Extensions.ToHexString(tag.GetTagType()), tagName, description); } else { // simple formatting if (showHex) { System.Console.Out.Printf("[%s - %s] %s = %s%n", directoryName, tag.GetTagTypeHex(), tagName, description); } else { System.Console.Out.Printf("[%s] %s = %s%n", directoryName, tagName, description); } } } // print out any errors foreach (string error in directory.GetErrors()) { System.Console.Error.Println("ERROR: " + error); } } if (args.Length > 1 && thumbRequested) { ExifThumbnailDirectory directory_1 = metadata.GetFirstDirectoryOfType<ExifThumbnailDirectory>(); if (directory_1 != null && directory_1.HasThumbnailData()) { System.Console.Out.Println("Writing thumbnail..."); directory_1.WriteThumbnail(Sharpen.Extensions.Trim(args[0]) + ".thumb.jpg"); } else { System.Console.Out.Println("No thumbnail data exists in this image"); } } } } } }
/* * DSAParameters.cs - Implementation of the * "System.Security.Cryptography.DSAParameters" structure. * * Copyright (C) 2002 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Security.Cryptography { #if CONFIG_CRYPTO using System; public struct DSAParameters { public int Counter; public byte[] G; public byte[] J; public byte[] P; public byte[] Q; public byte[] Seed; [NonSerialized] public byte[] X; public byte[] Y; // Clear the contents of this structure. internal void Clear() { Counter = 0; if(G != null) { Array.Clear(G, 0, G.Length); G = null; } if(J != null) { Array.Clear(J, 0, J.Length); J = null; } if(P != null) { Array.Clear(P, 0, P.Length); P = null; } if(Q != null) { Array.Clear(Q, 0, Q.Length); Q = null; } if(Seed != null) { Array.Clear(Seed, 0, Seed.Length); Seed = null; } if(X != null) { Array.Clear(X, 0, X.Length); X = null; } if(Y != null) { Array.Clear(Y, 0, Y.Length); Y = null; } } // Clone the public parameters in this structure. internal DSAParameters ClonePublic() { DSAParameters p; p.Counter = Counter; p.G = G; p.J = J; p.P = P; p.Q = Q; p.Seed = Seed; p.X = null; p.Y = Y; return p; } // Object identifier for DSA: "1.2.840.10040.4.1". private static readonly byte[] dsaID = {(byte)0x2A, (byte)0x86, (byte)0x48, (byte)0xCE, (byte)0x38, (byte)0x04, (byte)0x01}; // Convert an ASN.1 buffer into DSA public parameters. internal void ASN1ToPublic(ASN1Parser parser) { parser = parser.GetSequence(); if(parser.Type == ASN1Type.Sequence) { // This looks like it may be a "SubjectPublicKeyInfo" // from an X.509 certificate. Validate the algorithm ID. ASN1Parser alg = parser.GetSequence(); byte[] objid = alg.GetObjectIdentifier(); if(!ASN1Parser.IsObjectID(objid, dsaID)) { throw new CryptographicException (_("Crypto_InvalidASN1")); } // Get the common P, Q, and G parameters. ASN1Parser algParams = alg.GetSequence(); P = algParams.GetBigInt(); Q = algParams.GetBigInt(); G = algParams.GetBigInt(); algParams.AtEnd(); alg.AtEnd(); // Get the public key information (Y). ASN1Parser bitString = parser.GetBitStringContents(); Y = bitString.GetBigInt(); bitString.AtEnd(); parser.AtEnd(); } else { // This looks like a bare list of DSA parameters. P = parser.GetBigInt(); Q = parser.GetBigInt(); G = parser.GetBigInt(); Y = parser.GetBigInt(); if(!parser.IsAtEnd()) { // It looks like we have private DSA parameters also. J = parser.GetBigInt(); X = parser.GetBigInt(); Seed = parser.GetBigInt(); Counter = parser.GetInt32(); } parser.AtEnd(); } } internal void ASN1ToPublic(byte[] buffer, int offset, int count) { ASN1ToPublic(new ASN1Parser(buffer, offset, count)); } // Convert an ASN.1 buffer into DSA private parameters. internal void ASN1ToPrivate(ASN1Parser parser) { parser = parser.GetSequence(); P = parser.GetBigInt(); Q = parser.GetBigInt(); G = parser.GetBigInt(); Y = parser.GetBigInt(); J = parser.GetBigInt(); X = parser.GetBigInt(); Seed = parser.GetBigInt(); Counter = parser.GetInt32(); parser.AtEnd(); } internal void ASN1ToPrivate(byte[] buffer, int offset, int count) { ASN1ToPrivate(new ASN1Parser(buffer, offset, count)); } // Convert DSA public parameters into an ASN.1 buffer. internal void PublicToASN1(ASN1Builder builder, bool x509) { if(x509) { // Output an X.509 "SubjectPublicKeyInfo" block. ASN1Builder alg = builder.AddSequence(); alg.AddObjectIdentifier(dsaID); ASN1Builder inner = alg.AddSequence(); inner.AddBigInt(P); inner.AddBigInt(Q); inner.AddBigInt(G); ASN1Builder bitString = builder.AddBitStringContents(); bitString.AddBigInt(Y); } else { // Output the raw public parameters. builder.AddBigInt(P); builder.AddBigInt(Q); builder.AddBigInt(G); builder.AddBigInt(Y); } } internal byte[] PublicToASN1(bool x509) { ASN1Builder builder = new ASN1Builder(); PublicToASN1(builder, x509); return builder.ToByteArray(); } // Convert DSA private parameters into an ASN.1 buffer. internal void PrivateToASN1(ASN1Builder builder) { builder.AddBigInt(P); builder.AddBigInt(Q); builder.AddBigInt(G); builder.AddBigInt(Y); builder.AddBigInt(J); builder.AddBigInt(X); builder.AddBigInt(Seed); builder.AddInt32(Counter); } internal byte[] PrivateToASN1() { ASN1Builder builder = new ASN1Builder(); PrivateToASN1(builder); return builder.ToByteArray(); } }; // struct DSAParameters #endif // CONFIG_CRYPTO }; // namespace System.Security.Cryptography
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; namespace System.Numerics.Tests { public class arithmaticOperation_BinaryPlus_AddTest { private static void VerifyBinaryPlusResult(double realFirst, double imgFirst, double realSecond, double imgSecond) { // Create complex numbers Complex cFirst = new Complex(realFirst, imgFirst); Complex cSecond = new Complex(realSecond, imgSecond); // calculate the expected results double realExpectedResult = realFirst + realSecond; double imgExpectedResult = imgFirst + imgSecond; // local variable Complex cResult; // arithmetic addition operation cResult = cFirst + cSecond; // verify the result Support.VerifyRealImaginaryProperties(cResult, realExpectedResult, imgExpectedResult, string.Format("Binary Plus test = ({0}, {1}) + ({2}, {3})", realFirst, imgFirst, realSecond, imgSecond)); // arithmetic static addition operation cResult = Complex.Add(cFirst, cSecond); // verify the result Support.VerifyRealImaginaryProperties(cResult, realExpectedResult, imgExpectedResult, string.Format("Add test = ({0}, {1}) + ({2}, {3})", realFirst, imgFirst, realSecond, imgSecond)); } [Fact] public static void RunTests_Zero() { double real = Support.GetRandomDoubleValue(false); double imaginary = Support.GetRandomDoubleValue(false); VerifyBinaryPlusResult(0.0, 0.0, real, imaginary); // Verify 0+x=0 VerifyBinaryPlusResult(real, imaginary, 0.0, 0.0); // Verify 0+x=0 } [Fact] public static void RunTests_BoundaryValues() { double real; double img; // test with 'Max' + (Positive, Positive) real = Support.GetRandomDoubleValue(false); img = Support.GetRandomDoubleValue(false); VerifyBinaryPlusResult(double.MaxValue, double.MaxValue, real, img); // test with 'Max' + (Negative, Negative) real = Support.GetRandomDoubleValue(true); img = Support.GetRandomDoubleValue(true); VerifyBinaryPlusResult(double.MaxValue, double.MaxValue, real, img); // test with 'Min' + (Positive, Positive) real = Support.GetRandomDoubleValue(false); img = Support.GetRandomDoubleValue(false); VerifyBinaryPlusResult(double.MinValue, double.MinValue, real, img); // test with 'Min' + (Negative, Negative) real = Support.GetRandomDoubleValue(true); img = Support.GetRandomDoubleValue(true); VerifyBinaryPlusResult(double.MinValue, double.MinValue, real, img); } [Fact] public static void RunTests_RandomValidValues() { // Verify test results with ComplexInFirstQuad + ComplexInFirstQuad double realFirst = Support.GetRandomDoubleValue(false); double imgFirst = Support.GetRandomDoubleValue(false); double realSecond = Support.GetRandomDoubleValue(false); double imgSecond = Support.GetRandomDoubleValue(false); VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify test results with ComplexInFirstQuad + ComplexInSecondQuad realFirst = Support.GetRandomDoubleValue(false); imgFirst = Support.GetRandomDoubleValue(false); realSecond = Support.GetRandomDoubleValue(true); imgSecond = Support.GetRandomDoubleValue(false); VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify test results with ComplexInFirstQuad + ComplexInThirdQuad realFirst = Support.GetRandomDoubleValue(false); imgFirst = Support.GetRandomDoubleValue(false); realSecond = Support.GetRandomDoubleValue(true); imgSecond = Support.GetRandomDoubleValue(true); VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify test results with ComplexInFirstQuad + ComplexInFourthQuad realFirst = Support.GetRandomDoubleValue(false); imgFirst = Support.GetRandomDoubleValue(false); realSecond = Support.GetRandomDoubleValue(false); imgSecond = Support.GetRandomDoubleValue(true); VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify test results with ComplexInSecondQuad + ComplexInSecondQuad realFirst = Support.GetRandomDoubleValue(true); imgFirst = Support.GetRandomDoubleValue(false); realSecond = Support.GetRandomDoubleValue(true); imgSecond = Support.GetRandomDoubleValue(false); VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify test results with ComplexInSecondQuad + ComplexInThirdQuad realFirst = Support.GetRandomDoubleValue(true); imgFirst = Support.GetRandomDoubleValue(false); realSecond = Support.GetRandomDoubleValue(true); imgSecond = Support.GetRandomDoubleValue(true); VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify test results with ComplexInSecondQuad + ComplexInFourthQuad realFirst = Support.GetRandomDoubleValue(true); imgFirst = Support.GetRandomDoubleValue(false); realSecond = Support.GetRandomDoubleValue(false); imgSecond = Support.GetRandomDoubleValue(true); VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify test results with ComplexInThirdQuad + ComplexInThirdQuad realFirst = Support.GetRandomDoubleValue(true); imgFirst = Support.GetRandomDoubleValue(true); realSecond = Support.GetRandomDoubleValue(true); imgSecond = Support.GetRandomDoubleValue(true); VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify test results with ComplexInThirdQuad + ComplexInFourthQuad realFirst = Support.GetRandomDoubleValue(true); imgFirst = Support.GetRandomDoubleValue(true); realSecond = Support.GetRandomDoubleValue(false); imgSecond = Support.GetRandomDoubleValue(true); VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify test results with ComplexInFourthQuad + ComplexInFourthQuad realFirst = Support.GetRandomDoubleValue(true); imgFirst = Support.GetRandomDoubleValue(false); realSecond = Support.GetRandomDoubleValue(true); imgSecond = Support.GetRandomDoubleValue(false); VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond); } [Fact] public static void RunTests_InvalidImaginaryValues() { double realFirst; double imgFirst; double realSecond; double imgSecond; // Verify with (valid, PositiveInfinity) + (valid, PositiveValid) realFirst = Support.GetRandomDoubleValue(false); imgFirst = double.PositiveInfinity; realSecond = Support.GetRandomDoubleValue(false); imgSecond = Support.GetRandomDoubleValue(false); VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify with (valid, PositiveInfinity) + (valid, NegativeValid) realFirst = Support.GetRandomDoubleValue(false); imgFirst = double.PositiveInfinity; realSecond = Support.GetRandomDoubleValue(false); imgSecond = Support.GetRandomDoubleValue(true); VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify with (valid, NegativeInfinity) + (valid, PositiveValid) realFirst = Support.GetRandomDoubleValue(false); imgFirst = double.NegativeInfinity; realSecond = Support.GetRandomDoubleValue(false); imgSecond = Support.GetRandomDoubleValue(false); VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify with (valid, NegativeInfinity) + (valid, NegativeValid) realFirst = Support.GetRandomDoubleValue(false); imgFirst = double.NegativeInfinity; realSecond = Support.GetRandomDoubleValue(false); imgSecond = Support.GetRandomDoubleValue(true); VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify with (valid, NaN) + (valid, Valid) realFirst = Support.GetRandomDoubleValue(false); imgFirst = double.NaN; realSecond = Support.GetRandomDoubleValue(false); imgSecond = Support.GetRandomDoubleValue(false); VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond); } [Fact] public static void RunTests_InvalidRealValues() { double realFirst; double imgFirst; double realSecond; double imgSecond; // Verify with (PositiveInfinity, valid) + (PositiveValid, valid) realFirst = double.PositiveInfinity; imgFirst = Support.GetRandomDoubleValue(false); realSecond = Support.GetRandomDoubleValue(false); imgSecond = Support.GetRandomDoubleValue(false); VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify with (PositiveInfinity, valid) + (NegativeValid, valid) realFirst = double.PositiveInfinity; imgFirst = Support.GetRandomDoubleValue(false); realSecond = Support.GetRandomDoubleValue(true); imgSecond = Support.GetRandomDoubleValue(false); VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify with (NegativeInfinity, valid) + (PositiveValid, valid) realFirst = double.NegativeInfinity; imgFirst = Support.GetRandomDoubleValue(false); realSecond = Support.GetRandomDoubleValue(false); imgSecond = Support.GetRandomDoubleValue(false); VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify with (NegativeInfinity, valid) + (NegativeValid, valid) realFirst = double.NegativeInfinity; imgFirst = Support.GetRandomDoubleValue(false); realSecond = Support.GetRandomDoubleValue(true); imgSecond = Support.GetRandomDoubleValue(false); VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond); // Verify with (NaN, valid) + (valid, valid) realFirst = double.NaN; imgFirst = Support.GetRandomDoubleValue(false); realSecond = Support.GetRandomDoubleValue(false); imgSecond = Support.GetRandomDoubleValue(false); VerifyBinaryPlusResult(realFirst, imgFirst, realSecond, imgSecond); } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type PlannerGroupPlansCollectionRequest. /// </summary> public partial class PlannerGroupPlansCollectionRequest : BaseRequest, IPlannerGroupPlansCollectionRequest { /// <summary> /// Constructs a new PlannerGroupPlansCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public PlannerGroupPlansCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified PlannerPlan to the collection via POST. /// </summary> /// <param name="plannerPlan">The PlannerPlan to add.</param> /// <returns>The created PlannerPlan.</returns> public System.Threading.Tasks.Task<PlannerPlan> AddAsync(PlannerPlan plannerPlan) { return this.AddAsync(plannerPlan, CancellationToken.None); } /// <summary> /// Adds the specified PlannerPlan to the collection via POST. /// </summary> /// <param name="plannerPlan">The PlannerPlan to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created PlannerPlan.</returns> public System.Threading.Tasks.Task<PlannerPlan> AddAsync(PlannerPlan plannerPlan, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<PlannerPlan>(plannerPlan, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IPlannerGroupPlansCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IPlannerGroupPlansCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<PlannerGroupPlansCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IPlannerGroupPlansCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IPlannerGroupPlansCollectionRequest Expand(Expression<Func<PlannerPlan, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IPlannerGroupPlansCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IPlannerGroupPlansCollectionRequest Select(Expression<Func<PlannerPlan, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IPlannerGroupPlansCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IPlannerGroupPlansCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IPlannerGroupPlansCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IPlannerGroupPlansCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
using System; namespace Python.Runtime { /// <summary> /// Represents a Python integer object. See the documentation at /// PY2: https://docs.python.org/2/c-api/int.html /// PY3: No equivalent /// for details. /// </summary> public class PyInt : PyNumber { /// <summary> /// PyInt Constructor /// </summary> /// <remarks> /// Creates a new PyInt from an existing object reference. Note /// that the instance assumes ownership of the object reference. /// The object reference is not checked for type-correctness. /// </remarks> public PyInt(IntPtr ptr) : base(ptr) { } /// <summary> /// PyInt Constructor /// </summary> /// <remarks> /// Copy constructor - obtain a PyInt from a generic PyObject. An /// ArgumentException will be thrown if the given object is not a /// Python int object. /// </remarks> public PyInt(PyObject o) : base(FromObject(o)) { } private static IntPtr FromObject(PyObject o) { if (o == null || !IsIntType(o)) { throw new ArgumentException("object is not an int"); } Runtime.XIncref(o.obj); return o.obj; } private static IntPtr FromInt(int value) { IntPtr val = Runtime.PyInt_FromInt32(value); PythonException.ThrowIfIsNull(val); return val; } /// <summary> /// PyInt Constructor /// </summary> /// <remarks> /// Creates a new Python int from an int32 value. /// </remarks> public PyInt(int value) : base(FromInt(value)) { } /// <summary> /// PyInt Constructor /// </summary> /// <remarks> /// Creates a new Python int from a uint32 value. /// </remarks> public PyInt(uint value) : base(FromLong(value)) { } /// <summary> /// PyInt Constructor /// </summary> /// <remarks> /// Creates a new Python int from an int64 value. /// </remarks> public PyInt(long value) : base(FromLong(value)) { } private static IntPtr FromLong(long value) { IntPtr val = Runtime.PyInt_FromInt64(value); PythonException.ThrowIfIsNull(val); return val; } /// <summary> /// PyInt Constructor /// </summary> /// <remarks> /// Creates a new Python int from a uint64 value. /// </remarks> public PyInt(ulong value) : base(FromLong((long)value)) { } /// <summary> /// PyInt Constructor /// </summary> /// <remarks> /// Creates a new Python int from an int16 value. /// </remarks> public PyInt(short value) : this((int)value) { } /// <summary> /// PyInt Constructor /// </summary> /// <remarks> /// Creates a new Python int from a uint16 value. /// </remarks> public PyInt(ushort value) : this((int)value) { } /// <summary> /// PyInt Constructor /// </summary> /// <remarks> /// Creates a new Python int from a byte value. /// </remarks> public PyInt(byte value) : this((int)value) { } /// <summary> /// PyInt Constructor /// </summary> /// <remarks> /// Creates a new Python int from an sbyte value. /// </remarks> public PyInt(sbyte value) : this((int)value) { } private static IntPtr FromString(string value) { IntPtr val = Runtime.PyLong_FromString(value, IntPtr.Zero, 0); PythonException.ThrowIfIsNull(val); return val; } /// <summary> /// PyInt Constructor /// </summary> /// <remarks> /// Creates a new Python int from a string value. /// </remarks> public PyInt(string value) : base(FromString(value)) { } /// <summary> /// IsIntType Method /// </summary> /// <remarks> /// Returns true if the given object is a Python int. /// </remarks> public static bool IsIntType(PyObject value) { return Runtime.PyInt_Check(value.obj); } /// <summary> /// AsInt Method /// </summary> /// <remarks> /// Convert a Python object to a Python int if possible, raising /// a PythonException if the conversion is not possible. This is /// equivalent to the Python expression "int(object)". /// </remarks> public static PyInt AsInt(PyObject value) { IntPtr op = Runtime.PyNumber_Int(value.obj); PythonException.ThrowIfIsNull(op); return new PyInt(op); } /// <summary> /// ToInt16 Method /// </summary> /// <remarks> /// Return the value of the Python int object as an int16. /// </remarks> public short ToInt16() { return Convert.ToInt16(ToInt32()); } /// <summary> /// ToInt32 Method /// </summary> /// <remarks> /// Return the value of the Python int object as an int32. /// </remarks> public int ToInt32() { return Runtime.PyInt_AsLong(obj); } /// <summary> /// ToInt64 Method /// </summary> /// <remarks> /// Return the value of the Python int object as an int64. /// </remarks> public long ToInt64() { return Convert.ToInt64(ToInt32()); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using MySql.Data.MySqlClient; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using System; using System.Collections.Generic; using System.Data; using System.Reflection; namespace OpenSim.Data.MySQL { public class MySQLEstateStore : IEstateDataStore { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private const string m_waitTimeoutSelect = "select @@wait_timeout"; private string m_connectionString; private long m_waitTimeout; private long m_waitTimeoutLeeway = 60 * TimeSpan.TicksPerSecond; // private long m_lastConnectionUse; private FieldInfo[] m_Fields; private Dictionary<string, FieldInfo> m_FieldMap = new Dictionary<string, FieldInfo>(); protected virtual Assembly Assembly { get { return GetType().Assembly; } } public MySQLEstateStore() { } public MySQLEstateStore(string connectionString) { Initialise(connectionString); } public void Initialise(string connectionString) { m_connectionString = connectionString; try { m_log.Info("[REGION DB]: MySql - connecting: " + Util.GetDisplayConnectionString(m_connectionString)); } catch (Exception e) { m_log.Debug("Exception: password not found in connection string\n" + e.ToString()); } GetWaitTimeout(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); Migration m = new Migration(dbcon, Assembly, "EstateStore"); m.Update(); Type t = typeof(EstateSettings); m_Fields = t.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly); foreach (FieldInfo f in m_Fields) { if (f.Name.Substring(0, 2) == "m_") m_FieldMap[f.Name.Substring(2)] = f; } } } private string[] FieldList { get { return new List<string>(m_FieldMap.Keys).ToArray(); } } protected void GetWaitTimeout() { using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(m_waitTimeoutSelect, dbcon)) { using (MySqlDataReader dbReader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if (dbReader.Read()) { m_waitTimeout = Convert.ToInt32(dbReader["@@wait_timeout"]) * TimeSpan.TicksPerSecond + m_waitTimeoutLeeway; } } } // m_lastConnectionUse = DateTime.Now.Ticks; m_log.DebugFormat( "[REGION DB]: Connection wait timeout {0} seconds", m_waitTimeout / TimeSpan.TicksPerSecond); } } public EstateSettings LoadEstateSettings(UUID regionID, bool create) { string sql = "select estate_settings." + String.Join(",estate_settings.", FieldList) + " from estate_map left join estate_settings on estate_map.EstateID = estate_settings.EstateID where estate_settings.EstateID is not null and RegionID = ?RegionID"; using (MySqlCommand cmd = new MySqlCommand()) { cmd.CommandText = sql; cmd.Parameters.AddWithValue("?RegionID", regionID.ToString()); return DoLoad(cmd, regionID, create); } } public EstateSettings CreateNewEstate() { EstateSettings es = new EstateSettings(); es.OnSave += StoreEstateSettings; DoCreate(es); LoadBanList(es); es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers"); es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users"); es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups"); return es; } private EstateSettings DoLoad(MySqlCommand cmd, UUID regionID, bool create) { EstateSettings es = new EstateSettings(); es.OnSave += StoreEstateSettings; using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); cmd.Connection = dbcon; bool found = false; using (IDataReader r = cmd.ExecuteReader()) { if (r.Read()) { found = true; foreach (string name in FieldList) { if (m_FieldMap[name].FieldType == typeof(bool)) { m_FieldMap[name].SetValue(es, Convert.ToInt32(r[name]) != 0); } else if (m_FieldMap[name].FieldType == typeof(UUID)) { m_FieldMap[name].SetValue(es, DBGuid.FromDB(r[name])); } else { m_FieldMap[name].SetValue(es, r[name]); } } } } if (!found && create) { DoCreate(es); LinkRegion(regionID, (int)es.EstateID); } } LoadBanList(es); es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers"); es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users"); es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups"); return es; } private void DoCreate(EstateSettings es) { // Migration case List<string> names = new List<string>(FieldList); names.Remove("EstateID"); string sql = "insert into estate_settings (" + String.Join(",", names.ToArray()) + ") values ( ?" + String.Join(", ?", names.ToArray()) + ")"; using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd2 = dbcon.CreateCommand()) { cmd2.CommandText = sql; cmd2.Parameters.Clear(); foreach (string name in FieldList) { if (m_FieldMap[name].GetValue(es) is bool) { if ((bool)m_FieldMap[name].GetValue(es)) cmd2.Parameters.AddWithValue("?" + name, "1"); else cmd2.Parameters.AddWithValue("?" + name, "0"); } else { cmd2.Parameters.AddWithValue("?" + name, m_FieldMap[name].GetValue(es).ToString()); } } cmd2.ExecuteNonQuery(); cmd2.CommandText = "select LAST_INSERT_ID() as id"; cmd2.Parameters.Clear(); using (IDataReader r = cmd2.ExecuteReader()) { r.Read(); es.EstateID = Convert.ToUInt32(r["id"]); } es.Save(); } } } public void StoreEstateSettings(EstateSettings es) { string sql = "replace into estate_settings (" + String.Join(",", FieldList) + ") values ( ?" + String.Join(", ?", FieldList) + ")"; using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = sql; foreach (string name in FieldList) { if (m_FieldMap[name].GetValue(es) is bool) { if ((bool)m_FieldMap[name].GetValue(es)) cmd.Parameters.AddWithValue("?" + name, "1"); else cmd.Parameters.AddWithValue("?" + name, "0"); } else { cmd.Parameters.AddWithValue("?" + name, m_FieldMap[name].GetValue(es).ToString()); } } cmd.ExecuteNonQuery(); } } SaveBanList(es); SaveUUIDList(es.EstateID, "estate_managers", es.EstateManagers); SaveUUIDList(es.EstateID, "estate_users", es.EstateAccess); SaveUUIDList(es.EstateID, "estate_groups", es.EstateGroups); } private void LoadBanList(EstateSettings es) { es.ClearBans(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "select bannedUUID from estateban where EstateID = ?EstateID"; cmd.Parameters.AddWithValue("?EstateID", es.EstateID); using (IDataReader r = cmd.ExecuteReader()) { while (r.Read()) { EstateBan eb = new EstateBan(); UUID uuid = new UUID(); UUID.TryParse(r["bannedUUID"].ToString(), out uuid); eb.BannedUserID = uuid; eb.BannedHostAddress = "0.0.0.0"; eb.BannedHostIPMask = "0.0.0.0"; es.AddBan(eb); } } } } } private void SaveBanList(EstateSettings es) { using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "delete from estateban where EstateID = ?EstateID"; cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString()); cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); cmd.CommandText = "insert into estateban (EstateID, bannedUUID, bannedIp, bannedIpHostMask, bannedNameMask) values ( ?EstateID, ?bannedUUID, '', '', '' )"; foreach (EstateBan b in es.EstateBans) { cmd.Parameters.AddWithValue("?EstateID", es.EstateID.ToString()); cmd.Parameters.AddWithValue("?bannedUUID", b.BannedUserID.ToString()); cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } } } } private void SaveUUIDList(uint EstateID, string table, UUID[] data) { using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "delete from " + table + " where EstateID = ?EstateID"; cmd.Parameters.AddWithValue("?EstateID", EstateID.ToString()); cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); cmd.CommandText = "insert into " + table + " (EstateID, uuid) values ( ?EstateID, ?uuid )"; foreach (UUID uuid in data) { cmd.Parameters.AddWithValue("?EstateID", EstateID.ToString()); cmd.Parameters.AddWithValue("?uuid", uuid.ToString()); cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); } } } } private UUID[] LoadUUIDList(uint EstateID, string table) { List<UUID> uuids = new List<UUID>(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "select uuid from " + table + " where EstateID = ?EstateID"; cmd.Parameters.AddWithValue("?EstateID", EstateID); using (IDataReader r = cmd.ExecuteReader()) { while (r.Read()) { // EstateBan eb = new EstateBan(); uuids.Add(DBGuid.FromDB(r["uuid"])); } } } } return uuids.ToArray(); } public EstateSettings LoadEstateSettings(int estateID) { using (MySqlCommand cmd = new MySqlCommand()) { string sql = "select estate_settings." + String.Join(",estate_settings.", FieldList) + " from estate_settings where EstateID = ?EstateID"; cmd.CommandText = sql; cmd.Parameters.AddWithValue("?EstateID", estateID); return DoLoad(cmd, UUID.Zero, false); } } public List<EstateSettings> LoadEstateSettingsAll() { List<EstateSettings> allEstateSettings = new List<EstateSettings>(); List<int> allEstateIds = GetEstatesAll(); foreach (int estateId in allEstateIds) allEstateSettings.Add(LoadEstateSettings(estateId)); return allEstateSettings; } public List<int> GetEstatesAll() { List<int> result = new List<int>(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "select estateID from estate_settings"; using (IDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { result.Add(Convert.ToInt32(reader["EstateID"])); } reader.Close(); } } dbcon.Close(); } return result; } public List<int> GetEstates(string search) { List<int> result = new List<int>(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "select estateID from estate_settings where EstateName = ?EstateName"; cmd.Parameters.AddWithValue("?EstateName", search); using (IDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { result.Add(Convert.ToInt32(reader["EstateID"])); } reader.Close(); } } dbcon.Close(); } return result; } public List<int> GetEstatesByOwner(UUID ownerID) { List<int> result = new List<int>(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "select estateID from estate_settings where EstateOwner = ?EstateOwner"; cmd.Parameters.AddWithValue("?EstateOwner", ownerID); using (IDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { result.Add(Convert.ToInt32(reader["EstateID"])); } reader.Close(); } } dbcon.Close(); } return result; } public bool LinkRegion(UUID regionID, int estateID) { using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); MySqlTransaction transaction = dbcon.BeginTransaction(); try { // Delete any existing association of this region with an estate. using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.Transaction = transaction; cmd.CommandText = "delete from estate_map where RegionID = ?RegionID"; cmd.Parameters.AddWithValue("?RegionID", regionID); cmd.ExecuteNonQuery(); } using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.Transaction = transaction; cmd.CommandText = "insert into estate_map values (?RegionID, ?EstateID)"; cmd.Parameters.AddWithValue("?RegionID", regionID); cmd.Parameters.AddWithValue("?EstateID", estateID); int ret = cmd.ExecuteNonQuery(); if (ret != 0) transaction.Commit(); else transaction.Rollback(); dbcon.Close(); return (ret != 0); } } catch (MySqlException ex) { m_log.Error("[REGION DB]: LinkRegion failed: " + ex.Message); transaction.Rollback(); } dbcon.Close(); } return false; } public List<UUID> GetRegions(int estateID) { List<UUID> result = new List<UUID>(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); try { using (MySqlCommand cmd = dbcon.CreateCommand()) { cmd.CommandText = "select RegionID from estate_map where EstateID = ?EstateID"; cmd.Parameters.AddWithValue("?EstateID", estateID.ToString()); using (IDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) result.Add(DBGuid.FromDB(reader["RegionID"])); reader.Close(); } } } catch (Exception e) { m_log.Error("[REGION DB]: Error reading estate map. " + e.ToString()); return result; } dbcon.Close(); } return result; } public bool DeleteEstate(int estateID) { return false; } } }
namespace ShowUI { using System; using System.Windows; using System.Windows.Media; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Management.Automation; using System.Windows.Controls; public class ShowUISetting : DependencyObject { public static readonly DependencyProperty ControlNameProperty = DependencyProperty.RegisterAttached( "ControlName", typeof(string), typeof(ShowUISetting), new FrameworkPropertyMetadata()); public static void SetControlName(UIElement element, string value) { element.SetValue(ControlNameProperty, value); } public static string GetControlName(UIElement element) { return (string)element.GetValue(ControlNameProperty); } public static readonly DependencyProperty StyleNameProperty = DependencyProperty.RegisterAttached( "StyleName", typeof(string), typeof(ShowUISetting), new FrameworkPropertyMetadata()); public static void SetStylelName(UIElement element, string value) { element.SetValue(StyleNameProperty, value); } public static string GetStylelName(UIElement element) { return (string)element.GetValue(StyleNameProperty); } } public static class ShowUIExtensions { public static IEnumerable<DependencyObject> GetChildControl(this DependencyObject control, bool peekIntoNestedControl, Type[] byType, string[] byControlName, string[] byName, bool onlyDirectChildren) { bool hasEnumeratedChildren = false; Queue<DependencyObject> queue = new Queue<DependencyObject>(); queue.Enqueue(control); while (queue.Count > 0) { DependencyObject parent = queue.Peek(); string controlName = (string)parent.GetValue(ShowUI.ShowUISetting.ControlNameProperty); string name = String.Empty; if ((parent is FrameworkElement)) { name = (parent as FrameworkElement).Name; } if (byName != null && (!String.IsNullOrEmpty(name))) { foreach (string n in byName) { if (String.Compare(n, name, true) == 0) { yield return parent; } } } else if (byControlName != null && (!String.IsNullOrEmpty(controlName))) { foreach (string n in byControlName) { if (String.Compare(n, controlName, true) == 0) { yield return parent; } } } else if (byType != null) { foreach (Type t in byType) { Type parentType = parent.GetType(); if (t.IsInterface && parentType.GetInterface(t.FullName) != null) { yield return parent; } } } else { yield return parent; } int childCount = VisualTreeHelper.GetChildrenCount(parent); if (childCount > 0) { if (!(hasEnumeratedChildren && onlyDirectChildren)) { if ((!hasEnumeratedChildren) || ((String.IsNullOrEmpty(controlName) || peekIntoNestedControl))) { hasEnumeratedChildren = true; for (int i = 0; i < childCount; i++) { DependencyObject child = VisualTreeHelper.GetChild(parent, i); queue.Enqueue(child); } } } } else { if (parent is ContentControl) { object childObject = (parent as ContentControl).Content; if (childObject != null && childObject is Visual) { queue.Enqueue(childObject as Visual); } } } queue.Dequeue(); } } } } namespace ShowUI { using System; using System.Collections.Generic; using System.Text; using System.ComponentModel; using System.Collections.ObjectModel; using System.Management.Automation; using System.Windows; using System.Collections; using System.Management.Automation.Runspaces; using System.Timers; using System.Windows.Threading; using System.Threading; using System.Windows.Input; public class ShowUICommands { private static RoutedCommand backgroundPowerShellCommand = new RoutedCommand(); public static RoutedCommand BackgroundPowerShellCommand { get { return backgroundPowerShellCommand; } } } } namespace ShowUI { using System; using System.Windows; using System.Windows.Data; using System.Management.Automation; using System.Globalization; public class LanguagePrimitivesValueConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return LanguagePrimitives.ConvertTo(value, targetType); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return LanguagePrimitives.ConvertTo(value, targetType); } } } namespace ShowUI { using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Threading; using System.Windows.Threading; using System.ComponentModel; using System.Collections.Generic; using System.Collections; using System.Collections.ObjectModel; public class WPFJob : Job, INotifyPropertyChanged { Runspace runspace; InitialSessionState initialSessionState; PowerShell powerShellCommand; Dispatcher JobDispatcher; public Window JobWindow; Thread jobThread; Hashtable namedControls; Runspace interopRunspace; Runspace GetWPFCurrentThreadRunspace(InitialSessionState sessionState) { InitialSessionState clone = sessionState.Clone(); clone.ThreadOptions = PSThreadOptions.UseCurrentThread; SessionStateVariableEntry window = new SessionStateVariableEntry("Window", JobWindow, ""); SessionStateVariableEntry namedControls = new SessionStateVariableEntry("NamedControls", this.namedControls, ""); clone.Variables.Add(window); clone.Variables.Add(namedControls); return RunspaceFactory.CreateRunspace(clone); } delegate Collection<PSObject> RunScriptCallback(string script); delegate Collection<PSObject> RunScriptWithParameters(string script, Object parameters); public PSObject[] InvokeScriptInJob(string script, object parameters, bool async) { if (this.JobStateInfo.State == JobState.Running) { for (int i = 0; i < 10; i++) { if (JobWindow != null) { break; } Thread.Sleep(50); } if (JobWindow == null) { return null; } return (PSObject[])RunOnUIThread( new DispatcherOperationCallback( delegate { PowerShell psCmd = PowerShell.Create(); if (interopRunspace == null) { interopRunspace = GetWPFCurrentThreadRunspace(this.initialSessionState); interopRunspace.Open(); } psCmd.Runspace = interopRunspace; psCmd.AddScript(script); if (parameters is IDictionary) { psCmd.AddParameters(parameters as IDictionary); } else { if (parameters is IList) { psCmd.AddParameters(parameters as IList); } } Collection<PSObject> results = psCmd.Invoke(); if (psCmd.InvocationStateInfo.Reason != null) { throw psCmd.InvocationStateInfo.Reason; } PSObject[] resultArray = new PSObject[results.Count + psCmd.Streams.Error.Count]; int count = 0; if (psCmd.Streams.Error.Count > 0) { foreach (ErrorRecord err in psCmd.Streams.Error) { resultArray[count++] = new PSObject(err); } } foreach (PSObject r in results) { resultArray[count++] = r; } return resultArray; }), async); } else { return null; } } object RunOnUIThread(DispatcherOperationCallback dispatcherMethod, bool async) { if (Application.Current != null) { if (Application.Current.Dispatcher.Thread == Thread.CurrentThread) { // This avoids dispatching to the UI thread if we are already in the UI thread. // Without this runing a command like 1/0 was throwing due to nested dispatches. return dispatcherMethod.Invoke(null); } } Exception e = null; object returnValue = null; SynchronizationContext sync = new DispatcherSynchronizationContext(JobWindow.Dispatcher); if (sync == null) { return null; } if (async) { sync.Post( new SendOrPostCallback(delegate(object obj) { try { returnValue = dispatcherMethod.Invoke(obj); } catch (Exception uiException) { e = uiException; } }), null); } else { sync.Send( new SendOrPostCallback(delegate(object obj) { try { returnValue = dispatcherMethod.Invoke(obj); } catch (Exception uiException) { e = uiException; } }), null); } if (e != null) { throw new System.Reflection.TargetInvocationException(e.Message, e); } return returnValue; } public static InitialSessionState GetSessionStateForCommands(CommandInfo[] commands) { InitialSessionState iss = InitialSessionState.CreateDefault(); Dictionary<string, SessionStateCommandEntry> commandCache = new Dictionary<string, SessionStateCommandEntry>(); foreach (SessionStateCommandEntry ssce in iss.Commands) { commandCache[ssce.Name] = ssce; } iss.ApartmentState = ApartmentState.STA; iss.ThreadOptions = PSThreadOptions.ReuseThread; if (commands.Length == 0) { return iss; } foreach (CommandInfo cmd in commands) { if (cmd.Module != null) { string manifestPath = cmd.Module.Path.Replace(".psm1",".psd1").Replace(".dll", ".psd1"); if (System.IO.File.Exists(manifestPath)) { iss.ImportPSModule(new string[] { manifestPath }); } else { iss.ImportPSModule(new string[] { cmd.Module.Path }); } continue; } if (cmd is AliasInfo) { CommandInfo loopCommand = cmd; while (loopCommand is AliasInfo) { SessionStateAliasEntry alias = new SessionStateAliasEntry(loopCommand.Name, loopCommand.Definition); iss.Commands.Add(alias); loopCommand = (loopCommand as AliasInfo).ReferencedCommand; } if (loopCommand is FunctionInfo) { SessionStateFunctionEntry func = new SessionStateFunctionEntry(loopCommand.Name, loopCommand.Definition); iss.Commands.Add(func); } if (loopCommand is CmdletInfo) { CmdletInfo cmdletData = loopCommand as CmdletInfo; SessionStateCmdletEntry cmdlet = new SessionStateCmdletEntry(cmd.Name, cmdletData.ImplementingType, cmdletData.HelpFile); iss.Commands.Add(cmdlet); } } if (cmd is FunctionInfo) { SessionStateFunctionEntry func = new SessionStateFunctionEntry(cmd.Name, cmd.Definition); iss.Commands.Add(func); } if (cmd is CmdletInfo) { CmdletInfo cmdletData = cmd as CmdletInfo; SessionStateCmdletEntry cmdlet = new SessionStateCmdletEntry(cmd.Name, cmdletData.ImplementingType, cmdletData.HelpFile); iss.Commands.Add(cmdlet); } } return iss; } public WPFJob(string name, string command, ScriptBlock scriptBlock) : base(command, name) { this.initialSessionState = InitialSessionState.CreateDefault(); Start(scriptBlock, new Hashtable()); } private WPFJob(ScriptBlock scriptBlock) { Start(scriptBlock, new Hashtable()); } public WPFJob(string name, string command, ScriptBlock scriptBlock, InitialSessionState initalSessionState) : base(command, name) { this.initialSessionState = initalSessionState; Start(scriptBlock, new Hashtable()); } public WPFJob(string name, string command, ScriptBlock scriptBlock, InitialSessionState initalSessionState, Hashtable parameters) : base(command, name) { this.initialSessionState = initalSessionState; Start(scriptBlock, parameters); } private WPFJob(string name, string command, ScriptBlock scriptBlock, InitialSessionState initalSessionState, Hashtable parameters, bool isChildJob) : base(command, name) { this.initialSessionState = initalSessionState; if (isChildJob) { Start(scriptBlock, parameters); } else { WPFJob childJob = new WPFJob(name, command, scriptBlock, initalSessionState, parameters, true); childJob.StateChanged += new EventHandler<JobStateEventArgs>(childJob_StateChanged); this.ChildJobs.Add(childJob); } } void childJob_StateChanged(object sender, JobStateEventArgs e) { this.SetJobState(e.JobStateInfo.State); } /// <summary> /// Synchronizes Job State with Background Runspace /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void powerShellCommand_InvocationStateChanged(object sender, PSInvocationStateChangedEventArgs e) { try { if (e.InvocationStateInfo.State == PSInvocationState.Completed) { runspace.Close(); } if (e.InvocationStateInfo.State == PSInvocationState.Failed) { ErrorRecord err = new ErrorRecord(e.InvocationStateInfo.Reason, "JobFailed", ErrorCategory.OperationStopped, this); Error.Add(err); runspace.Close(); } JobState js = (JobState)Enum.Parse(typeof(JobState), e.InvocationStateInfo.State.ToString(), true); this.SetJobState(js); } catch { } } void Start(ScriptBlock scriptBlock, Hashtable parameters) { SessionStateAssemblyEntry windowsBase = new SessionStateAssemblyEntry(typeof(Dispatcher).Assembly.ToString()); SessionStateAssemblyEntry presentationCore = new SessionStateAssemblyEntry(typeof(UIElement).Assembly.ToString()); SessionStateAssemblyEntry presentationFramework = new SessionStateAssemblyEntry(typeof(Control).Assembly.ToString()); initialSessionState.Assemblies.Add(windowsBase); initialSessionState.Assemblies.Add(presentationCore); initialSessionState.Assemblies.Add(presentationFramework); initialSessionState.Assemblies.Add(presentationFramework); runspace = RunspaceFactory.CreateRunspace(this.initialSessionState); runspace.ThreadOptions = PSThreadOptions.ReuseThread; runspace.ApartmentState = ApartmentState.STA; runspace.Open(); powerShellCommand = PowerShell.Create(); powerShellCommand.Runspace = runspace; jobThread = powerShellCommand.AddScript("[Threading.Thread]::CurrentThread").Invoke<Thread>()[0]; powerShellCommand.Streams.Error = this.Error; this.Error.DataAdded += new EventHandler<DataAddedEventArgs>(Error_DataAdded); powerShellCommand.Streams.Warning = this.Warning; this.Warning.DataAdded += new EventHandler<DataAddedEventArgs>(Warning_DataAdded); powerShellCommand.Streams.Verbose = this.Verbose; this.Verbose.DataAdded += new EventHandler<DataAddedEventArgs>(Verbose_DataAdded); powerShellCommand.Streams.Debug = this.Debug; this.Debug.DataAdded += new EventHandler<DataAddedEventArgs>(Debug_DataAdded); powerShellCommand.Streams.Progress = this.Progress; this.Progress.DataAdded += new EventHandler<DataAddedEventArgs>(Progress_DataAdded); this.Output.DataAdded += new EventHandler<DataAddedEventArgs>(Output_DataAdded); powerShellCommand.Commands.Clear(); powerShellCommand.Commands.AddScript(scriptBlock.ToString(), false); if (parameters.Count > 0) { powerShellCommand.AddParameters(parameters); } Collection<Visual> output = powerShellCommand.Invoke<Visual>(); if (output.Count == 0) { return; } powerShellCommand.Commands.Clear(); powerShellCommand.Commands.AddCommand("Show-Window").AddArgument(output[0]).AddParameter("OutputWindowFirst"); Object var = powerShellCommand.Runspace.SessionStateProxy.GetVariable("NamedControls"); if (var != null && ((var as Hashtable) != null)) { namedControls = var as Hashtable; } JobDispatcher = Dispatcher.FromThread(jobThread); JobDispatcher.UnhandledException += new DispatcherUnhandledExceptionEventHandler(jobDispatcher_UnhandledException); powerShellCommand.InvocationStateChanged += new EventHandler<PSInvocationStateChangedEventArgs>(powerShellCommand_InvocationStateChanged); powerShellCommand.BeginInvoke<Object, PSObject>(null, this.Output); DateTime startTime = DateTime.Now; if (output[0] is FrameworkElement) { while (JobWindow == null) { if ((DateTime.Now - startTime) > TimeSpan.FromSeconds(30)) { this.SetJobState(JobState.Failed); return; } System.Threading.Thread.Sleep(25); } } } void jobDispatcher_UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { ErrorRecord err = new ErrorRecord(e.Exception, "UnhandledException", ErrorCategory.OperationStopped, this); this.Error.Add(err); StopJob(); } void Output_DataAdded(object sender, DataAddedEventArgs e) { PSDataCollection<PSObject> output = sender as PSDataCollection<PSObject>; if (output == null) { return; } if (output[e.Index].BaseObject is Window) { JobWindow = output[e.Index].BaseObject as Window; } if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Output")); } } void Progress_DataAdded(object sender, DataAddedEventArgs e) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Progress")); } } void Debug_DataAdded(object sender, DataAddedEventArgs e) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Debug")); } } void Verbose_DataAdded(object sender, DataAddedEventArgs e) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Verbose")); } } void Warning_DataAdded(object sender, DataAddedEventArgs e) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Warning")); } } void Error_DataAdded(object sender, DataAddedEventArgs e) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Error")); } } /// <summary> /// If the comamnd is running, the job indicates it has more data /// </summary> public override bool HasMoreData { get { if (powerShellCommand.InvocationStateInfo.State == PSInvocationState.Running) { return true; } else { return false; } } } public override string Location { get { if (this.JobStateInfo.State == JobState.Running && (JobWindow != null)) { return (string)RunOnUIThread( new DispatcherOperationCallback( delegate { return "Left: " + JobWindow.Left + " Top: " + JobWindow.Top + " Width: " + JobWindow.ActualWidth + " Height: " + JobWindow.ActualHeight; }), false); } else { return " "; } } } public override string StatusMessage { get { return string.Empty; } } public override void StopJob() { Dispatcher dispatch = Dispatcher.FromThread(jobThread); if (dispatch != null) { if (!dispatch.HasShutdownStarted) { dispatch.InvokeShutdown(); } } powerShellCommand.Stop(); runspace.Close(); } protected override void Dispose(bool disposing) { if (disposing) { powerShellCommand.Dispose(); runspace.Close(); runspace.Dispose(); } base.Dispose(disposing); } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; #endregion } } namespace ShowUI { using System; using System.Collections.Generic; using System.Text; using System.ComponentModel; using System.Collections.ObjectModel; using System.Management.Automation; using System.Windows; using System.Collections; using System.Management.Automation.Runspaces; using System.Timers; using System.Windows.Threading; using System.Threading; public class PowerShellDataSource : INotifyPropertyChanged { Hashtable resources = new Hashtable(); public Hashtable Resources { get { return this.resources; } } public Dispatcher Dispatcher { get; set; } object RunOnUIThread(DispatcherOperationCallback dispatcherMethod, bool async) { if (Application.Current != null) { if (Application.Current.Dispatcher.Thread == Thread.CurrentThread) { // This avoids dispatching to the UI thread if we are already in the UI thread. // Without this runing a command like 1/0 was throwing due to nested dispatches. return dispatcherMethod.Invoke(null); } } Exception e = null; object returnValue = null; SynchronizationContext sync = new DispatcherSynchronizationContext(Dispatcher); if (sync == null) { return null; } if (async) { sync.Post( new SendOrPostCallback(delegate(object obj) { try { returnValue = dispatcherMethod.Invoke(obj); } catch (Exception uiException) { e = uiException; } }), null); } else { sync.Send( new SendOrPostCallback(delegate(object obj) { try { returnValue = dispatcherMethod.Invoke(obj); } catch (Exception uiException) { e = uiException; } }), null); } if (e != null) { throw new System.Reflection.TargetInvocationException(e.Message, e); } return returnValue; } public Object Parent { get { return this.parent; } set { this.parent = value; if (this.parent != null && this.parent.GetType().GetProperty("Dispatcher") != null) { Dispatcher = this.parent.GetType().GetProperty("Dispatcher").GetValue(this.parent, null) as Dispatcher; } } } private Object parent; public PSObject[] Output { get { PSObject[] returnValue = new PSObject[outputCollection.Count]; outputCollection.CopyTo(returnValue, 0); return returnValue; } } PSObject lastOutput; public PSObject LastOutput { get { return lastOutput; } } public ErrorRecord[] Error { get { ErrorRecord[] returnValue = new ErrorRecord[powerShellCommand.Streams.Error.Count]; powerShellCommand.Streams.Error.CopyTo(returnValue, 0); return returnValue; } } ErrorRecord lastError; public ErrorRecord LastError { get { return this.lastError; } } public WarningRecord[] Warning { get { WarningRecord[] returnValue = new WarningRecord[powerShellCommand.Streams.Warning.Count]; powerShellCommand.Streams.Warning.CopyTo(returnValue, 0); return returnValue; } } WarningRecord lastWarning; public WarningRecord LastWarning { get { return lastWarning; } } public VerboseRecord[] Verbose { get { VerboseRecord[] returnValue = new VerboseRecord[powerShellCommand.Streams.Verbose.Count]; powerShellCommand.Streams.Verbose.CopyTo(returnValue, 0); return returnValue; } } VerboseRecord lastVerbose; public VerboseRecord LastVerbose { get { return lastVerbose; } } public DebugRecord[] Debug { get { DebugRecord[] returnValue = new DebugRecord[powerShellCommand.Streams.Debug.Count]; powerShellCommand.Streams.Debug.CopyTo(returnValue, 0); return returnValue; } } DebugRecord lastDebug; public DebugRecord LastDebug { get { return lastDebug; } } public ProgressRecord[] Progress { get { ProgressRecord[] returnValue = new ProgressRecord[powerShellCommand.Streams.Progress.Count]; powerShellCommand.Streams.Progress.CopyTo(returnValue, 0); return returnValue; } } public PSObject[] TimeStampedOutput { get { PSObject[] returnValue = new PSObject[timeStampedOutput.Count]; timeStampedOutput.CopyTo(returnValue, 0); return returnValue; } } private PSObject lastTimeStampedOutput; public PSObject LastTimeStampedOutput { get { return this.lastTimeStampedOutput; } } ProgressRecord lastProgress; public ProgressRecord LastProgress { get { return lastProgress; } } public PowerShell Command { get { return powerShellCommand; } } public bool IsFinished { get { return (powerShellCommand.InvocationStateInfo.State == PSInvocationState.Completed || powerShellCommand.InvocationStateInfo.State == PSInvocationState.Failed || powerShellCommand.InvocationStateInfo.State == PSInvocationState.Stopped); } } public bool IsRunning { get { return (powerShellCommand.InvocationStateInfo.State == PSInvocationState.Running || powerShellCommand.InvocationStateInfo.State == PSInvocationState.Stopping); } } string script; PSDataCollection<PSObject> timeStampedOutput; public string Script { get { return script; } set { script = value; try { powerShellCommand.Commands.Clear(); powerShellCommand.AddScript(script, false); lastDebug = null; lastError = null; lastTimeStampedOutput = null; outputCollection.Clear(); timeStampedOutput.Clear(); lastOutput = null; lastProgress = null; lastVerbose = null; lastWarning = null; powerShellCommand.BeginInvoke<Object, PSObject>(null, outputCollection); } catch { } } } void powerShellCommand_InvocationStateChanged(object sender, PSInvocationStateChangedEventArgs e) { if (e.InvocationStateInfo.State == PSInvocationState.Failed) { ErrorRecord err = new ErrorRecord(e.InvocationStateInfo.Reason, "PowerShellDataSource.TerminatingError", ErrorCategory.InvalidOperation, powerShellCommand); powerShellCommand.Streams.Error.Add(err); } if (Dispatcher != null) { RunOnUIThread( new DispatcherOperationCallback( delegate { NotifyInvocationStateChanged(); return null; }), true); } else { NotifyInvocationStateChanged(); } } PowerShell powerShellCommand; PSDataCollection<PSObject> outputCollection; public PowerShellDataSource() { powerShellCommand = PowerShell.Create(); Runspace runspace = RunspaceFactory.CreateRunspace(); runspace.Open(); powerShellCommand.Runspace = runspace; outputCollection = new PSDataCollection<PSObject>(); timeStampedOutput = new PSDataCollection<PSObject>(); outputCollection.DataAdded += new EventHandler<DataAddedEventArgs>(outputCollection_DataAdded); timeStampedOutput.DataAdded += new EventHandler<DataAddedEventArgs>(timeStampedOutput_DataAdded); powerShellCommand.Streams.Debug.DataAdded += new EventHandler<DataAddedEventArgs>(Debug_DataAdded); powerShellCommand.Streams.Error.DataAdded += new EventHandler<DataAddedEventArgs>(Error_DataAdded); powerShellCommand.Streams.Verbose.DataAdded += new EventHandler<DataAddedEventArgs>(Verbose_DataAdded); powerShellCommand.Streams.Progress.DataAdded += new EventHandler<DataAddedEventArgs>(Progress_DataAdded); powerShellCommand.Streams.Warning.DataAdded += new EventHandler<DataAddedEventArgs>(Warning_DataAdded); } #region Notification Methods void NotifyTimeStampedOutputChanged() { object sender; if (this.Parent != null) { sender = this.Parent; } else { sender = this; } if (PropertyChanged != null) { PropertyChanged(sender, new PropertyChangedEventArgs("TimeStampedOutput")); } if (TimeStampedOutputChanged != null) { TimeStampedOutputChanged(sender, new PropertyChangedEventArgs("TimeStampedOutput")); } } void NotifyInvocationStateChanged() { object sender; if (this.Parent != null) { sender = this.Parent; } else { sender = this; } if (PropertyChanged != null) { PropertyChanged(sender, new PropertyChangedEventArgs("IsFinished")); PropertyChanged(sender, new PropertyChangedEventArgs("IsRunning")); } if (IsFinishedChanged != null) { IsFinishedChanged(sender, new PropertyChangedEventArgs("IsFinished")); } if (IsRunningChanged != null) { IsRunningChanged(sender, new PropertyChangedEventArgs("IsRunning")); } } void NotifyErrorChanged() { object sender; if (this.Parent != null) { sender = this.Parent; } else { sender = this; } if (PropertyChanged != null) { PropertyChanged(sender, new PropertyChangedEventArgs("Error")); PropertyChanged(sender, new PropertyChangedEventArgs("LastError")); } if (ErrorChanged != null) { ErrorChanged(sender, new PropertyChangedEventArgs("Error")); } } void NotifyDebugChanged() { object sender; if (this.Parent != null) { sender = this.Parent; } else { sender = this; } if (PropertyChanged != null) { PropertyChanged(sender, new PropertyChangedEventArgs("Debug")); PropertyChanged(sender, new PropertyChangedEventArgs("LastDebug")); } if (DebugChanged != null) { DebugChanged(sender, new PropertyChangedEventArgs("Debug")); } } void NotifyOutputChanged() { object sender; if (this.Parent != null) { sender = this.Parent; } else { sender = this; } if (PropertyChanged != null) { PropertyChanged(sender, new PropertyChangedEventArgs("Output")); PropertyChanged(sender, new PropertyChangedEventArgs("LastOutput")); } if (OutputChanged != null) { OutputChanged(sender, new PropertyChangedEventArgs("Output")); } } void NotifyWarningChanged() { object sender; if (this.Parent != null) { sender = this.Parent; } else { sender = this; } if (PropertyChanged != null) { PropertyChanged(sender, new PropertyChangedEventArgs("Warning")); PropertyChanged(sender, new PropertyChangedEventArgs("LastWarning")); } if (WarningChanged != null) { WarningChanged(sender, new PropertyChangedEventArgs("Warning")); } } void NotifyVerboseChanged() { object sender; if (this.Parent != null) { sender = this.Parent; } else { sender = this; } if (PropertyChanged != null) { PropertyChanged(sender, new PropertyChangedEventArgs("Verbose")); PropertyChanged(sender, new PropertyChangedEventArgs("LastVerbose")); } if (VerboseChanged != null) { VerboseChanged(sender, new PropertyChangedEventArgs("Verbose")); } } void NotifyProgressChanged() { object sender; if (this.Parent != null) { sender = this.Parent; } else { sender = this; } if (PropertyChanged != null) { PropertyChanged(sender, new PropertyChangedEventArgs("Progress")); PropertyChanged(sender, new PropertyChangedEventArgs("LastProgress")); } if (ProgressChanged != null) { ProgressChanged(sender, new PropertyChangedEventArgs("Progress")); } } #endregion void timeStampedOutput_DataAdded(object sender, DataAddedEventArgs e) { PSDataCollection<PSObject> collection = sender as PSDataCollection<PSObject>; lastTimeStampedOutput = collection[e.Index]; if (Dispatcher != null) { RunOnUIThread( new DispatcherOperationCallback( delegate { NotifyTimeStampedOutputChanged(); return null; }), true); } else { NotifyTimeStampedOutputChanged(); } } void Debug_DataAdded(object sender, DataAddedEventArgs e) { PSDataCollection<DebugRecord> collection = sender as PSDataCollection<DebugRecord>; lastDebug = collection[e.Index]; PSObject psObj = new PSObject(lastDebug); PSPropertyInfo propInfo = new PSNoteProperty("TimeStamp", DateTime.Now); psObj.Properties.Add(new PSNoteProperty("Stream", "Debug")); psObj.Properties.Add(propInfo); timeStampedOutput.Add(psObj); if (Dispatcher != null) { RunOnUIThread( new DispatcherOperationCallback( delegate { NotifyDebugChanged(); return null; }), true); } else { NotifyDebugChanged(); } } void Error_DataAdded(object sender, DataAddedEventArgs e) { PSDataCollection<ErrorRecord> collection = sender as PSDataCollection<ErrorRecord>; this.lastError = collection[e.Index]; PSObject psObj = new PSObject(lastError); PSPropertyInfo propInfo = new PSNoteProperty("TimeStamp", DateTime.Now); psObj.Properties.Add(new PSNoteProperty("Stream", "Error")); psObj.Properties.Add(propInfo); timeStampedOutput.Add(psObj); if (Dispatcher != null) { RunOnUIThread( new DispatcherOperationCallback( delegate { NotifyErrorChanged(); return null; }), true); } else { NotifyErrorChanged(); } } void Warning_DataAdded(object sender, DataAddedEventArgs e) { PSDataCollection<WarningRecord> collection = sender as PSDataCollection<WarningRecord>; lastWarning = collection[e.Index]; PSObject psObj = new PSObject(lastWarning); psObj.Properties.Add(new PSNoteProperty("TimeStamp", DateTime.Now)); psObj.Properties.Add(new PSNoteProperty("Stream", "Warning")); timeStampedOutput.Add(psObj); if (Dispatcher != null) { RunOnUIThread( new DispatcherOperationCallback( delegate { NotifyWarningChanged(); return null; }), true); } else { NotifyWarningChanged(); } } void Verbose_DataAdded(object sender, DataAddedEventArgs e) { PSDataCollection<VerboseRecord> collection = sender as PSDataCollection<VerboseRecord>; lastVerbose = collection[e.Index]; PSObject psObj = new PSObject(lastVerbose); PSPropertyInfo propInfo = new PSNoteProperty("TimeStamp", DateTime.Now); psObj.Properties.Add(new PSNoteProperty("Stream", "Verbose")); psObj.Properties.Add(propInfo); timeStampedOutput.Add(psObj); if (Dispatcher != null) { RunOnUIThread( new DispatcherOperationCallback( delegate { NotifyVerboseChanged(); return null; }), true); } else { NotifyVerboseChanged(); } } void Progress_DataAdded(object sender, DataAddedEventArgs e) { PSDataCollection<ProgressRecord> collection = sender as PSDataCollection<ProgressRecord>; lastProgress = collection[e.Index]; PSObject psObj = new PSObject(lastProgress); PSPropertyInfo propInfo = new PSNoteProperty("TimeStamp", DateTime.Now); psObj.Properties.Add(new PSNoteProperty("Stream", "Progress")); psObj.Properties.Add(propInfo); timeStampedOutput.Add(psObj); if (Dispatcher != null) { RunOnUIThread( new DispatcherOperationCallback( delegate { NotifyProgressChanged(); return null; }), true); } else { NotifyProgressChanged(); } } void outputCollection_DataAdded(object sender, DataAddedEventArgs e) { PSDataCollection<PSObject> collection = sender as PSDataCollection<PSObject>; lastOutput = collection[e.Index]; PSObject psObj = new PSObject(lastOutput); PSPropertyInfo propInfo = new PSNoteProperty("TimeStamp", DateTime.Now); psObj.Properties.Add(new PSNoteProperty("Stream", "Output")); psObj.Properties.Add(propInfo); timeStampedOutput.Add(psObj); if (Dispatcher != null) { RunOnUIThread( new DispatcherOperationCallback( delegate { NotifyOutputChanged(); return null; }), true); } else { NotifyOutputChanged(); } } public event PropertyChangedEventHandler PropertyChanged; public event PropertyChangedEventHandler OutputChanged; public event PropertyChangedEventHandler ErrorChanged; public event PropertyChangedEventHandler WarningChanged; public event PropertyChangedEventHandler DebugChanged; public event PropertyChangedEventHandler VerboseChanged; public event PropertyChangedEventHandler ProgressChanged; public event PropertyChangedEventHandler IsFinishedChanged; public event PropertyChangedEventHandler IsRunningChanged; public event PropertyChangedEventHandler TimeStampedOutputChanged; } } namespace ShowUI { using System; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Management.Automation; using System.Windows; using System.Windows.Data; using System.Windows.Markup; public class BindingTypeDescriptionProvider : TypeDescriptionProvider { private static readonly TypeDescriptionProvider DefaultTypeProvider = TypeDescriptor.GetProvider(typeof(Binding)); public BindingTypeDescriptionProvider() : base(DefaultTypeProvider) { } public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance) { ICustomTypeDescriptor defaultDescriptor = base.GetTypeDescriptor(objectType, instance); return instance == null ? defaultDescriptor : new BindingCustomTypeDescriptor(defaultDescriptor); } } public class BindingCustomTypeDescriptor : CustomTypeDescriptor { public BindingCustomTypeDescriptor(ICustomTypeDescriptor parent) : base(parent) { } public override PropertyDescriptorCollection GetProperties(Attribute[] attributes) { PropertyDescriptor pd; var pdc = new PropertyDescriptorCollection(base.GetProperties(attributes).Cast<PropertyDescriptor>().ToArray()); if ((pd = pdc.Find("Source", false)) != null) { pdc.Add(TypeDescriptor.CreateProperty(typeof(Binding), pd, new Attribute[] { new DefaultValueAttribute("null") })); pdc.Remove(pd); } return pdc; } } public class BindingConverter : ExpressionConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { return (destinationType == typeof(MarkupExtension)) ? true : false; } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(MarkupExtension)) { var bindingExpression = value as BindingExpression; if (bindingExpression == null) throw new Exception(); return bindingExpression.ParentBinding; } return base.ConvertTo(context, culture, value, destinationType); } } public static class XamlTricks { public static void FixSerialization() { // this is absolutely vital: TypeDescriptor.AddProvider(new BindingTypeDescriptionProvider(), typeof(Binding)); TypeDescriptor.AddAttributes(typeof(BindingExpression), new Attribute[] { new TypeConverterAttribute(typeof(BindingConverter)) }); } } }
#define PROTOTYPE #if UNITY_EDITOR || UNITY_STANDALONE using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; using ProBuilder2.Common; using ProBuilder2.MeshOperations; namespace ProBuilder2.Examples { [RequireComponent(typeof(AudioSource))] public class IcoBumpin : MonoBehaviour { pb_Object ico; // A reference to the icosphere pb_Object component Mesh icoMesh; // A reference to the icosphere mesh (cached because we access the vertex array every frame) Transform icoTransform; // A reference to the icosphere transform component. Cached because I can't remember if GameObject.transform is still a performance drain :| AudioSource audioSource;// Cached reference to the audiosource. /** * Holds a pb_Face, the normal of that face, and the index of every vertex that touches it (sharedIndices). */ struct FaceRef { public pb_Face face; public Vector3 nrm; // face normal public int[] indices; // all vertex indices (including shared connected vertices) public FaceRef(pb_Face f, Vector3 n, int[] i) { face = f; nrm = n; indices = i; } } // All faces that have been extruded FaceRef[] outsides; // Keep a copy of the original vertex array to calculate the distance from origin. Vector3[] original_vertices, displaced_vertices; // The radius of the mesh icosphere on instantiation. [Range(1f, 10f)] public float icoRadius = 2f; // The number of subdivisions to give the icosphere. [Range(0, 3)] public int icoSubdivisions = 2; // How far along the normal should each face be extruded when at idle (no audio input). [Range(0f, 1f)] public float startingExtrusion = .1f; // The material to apply to the icosphere. public Material material; // The max distance a frequency range will extrude a face. [Range(1f, 50f)] public float extrusion = 30f; // An FFT returns a spectrum including frequencies that are out of human hearing range - // this restricts the number of bins used from the spectrum to the lower @fftBounds. [Range(8, 128)] public int fftBounds = 32; // How high the icosphere transform will bounce (sample volume determines height). [Range(0f, 10f)] public float verticalBounce = 4f; // Optionally weights the frequency amplitude when calculating extrude distance. public AnimationCurve frequencyCurve; // A reference to the line renderer that will be used to render the raw waveform. public LineRenderer waveform; // The y size of the waveform. public float waveformHeight = 2f; // How far from the icosphere should the waveform be. public float waveformRadius = 20f; // If @rotateWaveformRing is true, this is the speed it will travel. public float waveformSpeed = .1f; // If true, the waveform ring will randomly orbit the icosphere. public bool rotateWaveformRing = false; // If true, the waveform will bounce up and down with the icosphere. public bool bounceWaveform = false; public GameObject missingClipWarning; // Icosphere's starting position. Vector3 icoPosition = Vector3.zero; float faces_length; const float TWOPI = 6.283185f; // 2 * PI const int WAVEFORM_SAMPLES = 1024; // How many samples make up the waveform ring. const int FFT_SAMPLES = 4096; // How many samples are used in the FFT. More means higher resolution. // Keep copy of the last frame's sample data to average with the current when calculating // deformation amounts. Smoothes the visual effect. float[] fft = new float[FFT_SAMPLES], fft_history = new float[FFT_SAMPLES], data = new float[WAVEFORM_SAMPLES], data_history = new float[WAVEFORM_SAMPLES]; // Root mean square of raw data (volume, but not in dB). float rms = 0f, rms_history = 0f; /** * Creates the icosphere, and loads all the cache information. */ void Start() { audioSource = GetComponent<AudioSource>(); if( audioSource.clip == null ) missingClipWarning.SetActive(true); // Create a new icosphere. ico = pb_ShapeGenerator.IcosahedronGenerator(icoRadius, icoSubdivisions); // Shell is all the faces on the new icosphere. pb_Face[] shell = ico.faces; // Materials are set per-face on pb_Object meshes. pb_Objects will automatically // condense the mesh to the smallest set of subMeshes possible based on materials. #if !PROTOTYPE foreach(pb_Face f in shell) f.material = material; #else ico.gameObject.GetComponent<MeshRenderer>().sharedMaterial = material; #endif // Extrude all faces on the icosphere by a small amount. The third boolean parameter // specifies that extrusion should treat each face as an individual, not try to group // all faces together. ico.Extrude(shell, ExtrudeMethod.IndividualFaces, startingExtrusion); // ToMesh builds the mesh positions, submesh, and triangle arrays. Call after adding // or deleting vertices, or changing face properties. ico.ToMesh(); // Refresh builds the normals, tangents, and UVs. ico.Refresh(); outsides = new FaceRef[shell.Length]; Dictionary<int, int> lookup = ico.sharedIndices.ToDictionary(); // Populate the outsides[] cache. This is a reference to the tops of each extruded column, including // copies of the sharedIndices. for(int i = 0; i < shell.Length; ++i) outsides[i] = new FaceRef( shell[i], pb_Math.Normal(ico, shell[i]), ico.sharedIndices.AllIndicesWithValues(lookup, shell[i].distinctIndices).ToArray() ); // Store copy of positions array un-modified original_vertices = new Vector3[ico.vertices.Length]; System.Array.Copy(ico.vertices, original_vertices, ico.vertices.Length); // displaced_vertices should mirror icosphere mesh vertices. displaced_vertices = ico.vertices; icoMesh = ico.msh; icoTransform = ico.transform; faces_length = (float)outsides.Length; // Build the waveform ring. icoPosition = icoTransform.position; #if UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3 || UNITY_5_4 waveform.SetVertexCount(WAVEFORM_SAMPLES); #else waveform.positionCount = WAVEFORM_SAMPLES; #endif if( bounceWaveform ) waveform.transform.parent = icoTransform; audioSource.Play(); } void Update() { // fetch the fft spectrum audioSource.GetSpectrumData(fft, 0, FFTWindow.BlackmanHarris); // get raw data for waveform audioSource.GetOutputData(data, 0); // calculate root mean square (volume) rms = RMS(data); /** * For each face, translate the vertices some distance depending on the frequency range assigned. * Not using the TranslateVertices() pb_Object extension method because as a convenience, that method * gathers the sharedIndices per-face on every call, which while not tremondously expensive in most * contexts, is far too slow for use when dealing with audio, and especially so when the mesh is * somewhat large. */ for(int i = 0; i < outsides.Length; i++) { float normalizedIndex = (i/faces_length); int n = (int)(normalizedIndex*fftBounds); Vector3 displacement = outsides[i].nrm * ( ((fft[n]+fft_history[n]) * .5f) * (frequencyCurve.Evaluate(normalizedIndex) * .5f + .5f)) * extrusion; foreach(int t in outsides[i].indices) { displaced_vertices[t] = original_vertices[t] + displacement; } } Vector3 vec = Vector3.zero; // Waveform ring for(int i = 0; i < WAVEFORM_SAMPLES; i++) { int n = i < WAVEFORM_SAMPLES-1 ? i : 0; vec.x = Mathf.Cos((float)n/WAVEFORM_SAMPLES * TWOPI) * (waveformRadius + (((data[n] + data_history[n]) * .5f) * waveformHeight)); vec.z = Mathf.Sin((float)n/WAVEFORM_SAMPLES * TWOPI) * (waveformRadius + (((data[n] + data_history[n]) * .5f) * waveformHeight)); vec.y = 0f; waveform.SetPosition(i, vec); } // Ring rotation if( rotateWaveformRing ) { Vector3 rot = waveform.transform.localRotation.eulerAngles; rot.x = Mathf.PerlinNoise(Time.time * waveformSpeed, 0f) * 360f; rot.y = Mathf.PerlinNoise(0f, Time.time * waveformSpeed) * 360f; waveform.transform.localRotation = Quaternion.Euler(rot); } icoPosition.y = -verticalBounce + ((rms + rms_history) * verticalBounce); icoTransform.position = icoPosition; // Keep copy of last FFT samples so we can average with the current. Smoothes the movement. System.Array.Copy(fft, fft_history, FFT_SAMPLES); System.Array.Copy(data, data_history, WAVEFORM_SAMPLES); rms_history = rms; icoMesh.vertices = displaced_vertices; } /** * Root mean square is a good approximation of perceived loudness. */ float RMS(float[] arr) { float v = 0f, len = (float)arr.Length; for(int i = 0; i < len; i++) v += Mathf.Abs(arr[i]); return Mathf.Sqrt(v / (float)len); } } } #endif
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using NHibernate; using NHibernate.Transform; using Orchard.ContentManagement.Records; using Orchard.Data.Providers; using Orchard.Environment.Configuration; using Orchard.Utility.Extensions; namespace Orchard.ContentManagement { public class DefaultHqlQuery : IHqlQuery { private readonly ISession _session; private readonly IEnumerable<ISqlStatementProvider> _sqlStatementProviders; private readonly ShellSettings _shellSettings; private VersionOptions _versionOptions; protected IJoin _from; protected readonly List<Tuple<IAlias, Join>> _joins = new List<Tuple<IAlias, Join>>(); protected readonly List<Tuple<IAlias, Action<IHqlExpressionFactory>>> _wheres = new List<Tuple<IAlias, Action<IHqlExpressionFactory>>>(); protected readonly List<Tuple<IAlias, Action<IHqlSortFactory>>> _sortings = new List<Tuple<IAlias, Action<IHqlSortFactory>>>(); private bool cacheable; public IContentManager ContentManager { get; private set; } public DefaultHqlQuery( IContentManager contentManager, ISession session, IEnumerable<ISqlStatementProvider> sqlStatementProviders, ShellSettings shellSettings) { _session = session; _sqlStatementProviders = sqlStatementProviders; _shellSettings = shellSettings; ContentManager = contentManager; } internal string PathToAlias(string path) { if (String.IsNullOrWhiteSpace(path)) { throw new ArgumentException("Path can't be empty"); } return Char.ToLower(path[0], CultureInfo.InvariantCulture) + path.Substring(1); } internal Join BindNamedAlias(string alias) { var tuple = _joins.FirstOrDefault(x => x.Item2.Name == alias); return tuple == null ? null : tuple.Item2; } internal IAlias BindCriteriaByPath(IAlias alias, string path) { return BindCriteriaByAlias(alias, path, PathToAlias(path)); } internal IAlias BindCriteriaByAlias(IAlias alias, string path, string aliasName) { // is this Join already existing (based on aliasName) Join join = BindNamedAlias(aliasName); if (join == null) { join = new Join(path, aliasName); _joins.Add(new Tuple<IAlias, Join>(alias, join)); } return join; } internal IAlias BindTypeCriteria() { // ([ContentItemVersionRecord] >join> [ContentItemRecord]) >join> [ContentType] return BindCriteriaByAlias(BindItemCriteria(), "ContentType", "ct"); } internal IAlias BindItemCriteria() { // [ContentItemVersionRecord] >join> [ContentItemRecord] return BindCriteriaByAlias(BindItemVersionCriteria(), typeof(ContentItemRecord).Name, "ci"); } internal IAlias BindItemVersionCriteria() { return _from ?? (_from = new Join(typeof(ContentItemVersionRecord).FullName, "civ", "")); } internal IAlias BindPartCriteria<TRecord>() where TRecord : ContentPartRecord { return BindPartCriteria(typeof(TRecord)); } internal IAlias BindPartCriteria(Type contentPartRecordType) { if (!contentPartRecordType.IsSubclassOf(typeof(ContentPartRecord))) { throw new ArgumentException("The type must inherit from ContentPartRecord", "contentPartRecordType"); } if (contentPartRecordType.IsSubclassOf(typeof(ContentPartVersionRecord))) { return BindCriteriaByPath(BindItemVersionCriteria(), contentPartRecordType.Name); } return BindCriteriaByPath(BindItemCriteria(), contentPartRecordType.Name); } internal void Where(IAlias alias, Action<IHqlExpressionFactory> predicate) { _wheres.Add(new Tuple<IAlias, Action<IHqlExpressionFactory>>(alias, predicate)); } internal IAlias ApplyHqlVersionOptionsRestrictions(VersionOptions versionOptions) { var alias = BindItemVersionCriteria(); if (versionOptions == null) { Where(alias, x => x.Eq("Published", true)); } else if (versionOptions.IsPublished) { Where(alias, x => x.Eq("Published", true)); } else if (versionOptions.IsLatest) { Where(alias, x => x.Eq("Latest", true)); } else if (versionOptions.IsDraft) { Where(alias, x => x.And(y => y.Eq("Latest", true), y => y.Eq("Published", false))); } else if (versionOptions.IsAllVersions) { // no-op... all versions will be returned by default } else { throw new ApplicationException("Invalid VersionOptions for content query"); } return alias; } public IHqlQuery Join(Action<IAliasFactory> alias) { var aliasFactory = new DefaultAliasFactory(this); alias(aliasFactory); return this; } public IHqlQuery Where(Action<IAliasFactory> alias, Action<IHqlExpressionFactory> predicate) { var aliasFactory = new DefaultAliasFactory(this); alias(aliasFactory); Where(aliasFactory.Current, predicate); return this; } public IHqlQuery OrderBy(Action<IAliasFactory> alias, Action<IHqlSortFactory> order) { var aliasFactory = new DefaultAliasFactory(this); alias(aliasFactory); _sortings.Add(new Tuple<IAlias, Action<IHqlSortFactory>>(aliasFactory.Current, order)); return this; } public IHqlQuery ForType(params string[] contentTypeNames) { if (contentTypeNames != null && contentTypeNames.Length != 0) { Where(BindTypeCriteria(), x => x.InG("Name", contentTypeNames)); } return this; } public IHqlQuery ForVersion(VersionOptions options) { _versionOptions = options; return this; } public IHqlQuery<T> ForPart<T>() where T : IContent { return new DefaultHqlQuery<T>(this); } public IEnumerable<ContentItem> List() { return Slice(0, 0); } public IEnumerable<ContentItem> Slice(int skip, int count) { ApplyHqlVersionOptionsRestrictions(_versionOptions); cacheable = true; var hql = ToHql(false); var query = _session .CreateQuery(hql) .SetCacheable(cacheable) ; if (skip != 0) { query.SetFirstResult(skip); } if (count != 0 && count != Int32.MaxValue) { query.SetMaxResults(count); } var ids = query .SetResultTransformer(Transformers.AliasToEntityMap) .List<IDictionary>() .Select(x => (int)x["Id"]); return ContentManager.GetManyByVersionId(ids, QueryHints.Empty); } public int Count() { ApplyHqlVersionOptionsRestrictions(_versionOptions); var hql = ToHql(true); hql = "select count(Id) from Orchard.ContentManagement.Records.ContentItemVersionRecord where Id in ( " + hql + " )"; return Convert.ToInt32(_session.CreateQuery(hql) .SetCacheable(true) .UniqueResult()) ; } public string ToHql(bool count) { var sb = new StringBuilder(); if (count) { sb.Append("select distinct civ.Id as Id").AppendLine(); } else { sb.Append("select distinct civ.Id as Id"); // add sort properties in the select foreach (var sort in _sortings) { var sortFactory = new DefaultHqlSortFactory(); sort.Item2(sortFactory); if (!sortFactory.Randomize) { sb.Append(", "); sb.Append(sort.Item1.Name).Append(".").Append(sortFactory.PropertyName); } else { // select distinct can't be used with newid() cacheable = false; sb.Replace("select distinct", "select "); } } sb.AppendLine(); } sb.Append("from ").Append(_from.TableName).Append(" as ").Append(_from.Name).AppendLine(); foreach (var join in _joins) { sb.Append(join.Item2.Type).Append(" ").Append(join.Item1.Name + "." + join.Item2.TableName).Append(" as ").Append(join.Item2.Name).AppendLine(); } // generating where clause if (_wheres.Any()) { sb.Append("where "); var expressions = new List<string>(); foreach (var where in _wheres) { var expressionFactory = new DefaultHqlExpressionFactory(); where.Item2(expressionFactory); expressions.Add(expressionFactory.Criterion.ToHql(where.Item1)); } sb.Append("(").Append(String.Join(") AND (", expressions.ToArray())).Append(")").AppendLine(); } // generating order by clause bool firstSort = true; foreach (var sort in _sortings) { if (!firstSort) { sb.Append(", "); } else { sb.Append("order by "); firstSort = false; } var sortFactory = new DefaultHqlSortFactory(); sort.Item2(sortFactory); if (sortFactory.Randomize) { string command = null; foreach (var sqlStatementProvider in _sqlStatementProviders) { if (!String.Equals(sqlStatementProvider.DataProvider, _shellSettings.DataProvider)) { continue; } command = sqlStatementProvider.GetStatement("random") ?? command; } if (command != null) { sb.Append(command); } } else { sb.Append(sort.Item1.Name).Append(".").Append(sortFactory.PropertyName); if (!sortFactory.Ascending) { sb.Append(" desc"); } } } // no order clause was specified, use a default sort order, unless it's a count // query hence it doesn't need one if (firstSort && !count) { sb.Append("order by civ.Id"); } return sb.ToString(); } } public class DefaultHqlQuery<TPart> : IHqlQuery<TPart> where TPart : IContent { private readonly DefaultHqlQuery _query; public DefaultHqlQuery(DefaultHqlQuery query) { _query = query; } public IContentManager ContentManager { get { return _query.ContentManager; } } public IHqlQuery<TPart> ForType(params string[] contentTypes) { _query.ForType(contentTypes); return new DefaultHqlQuery<TPart>(_query); } public IHqlQuery<TPart> ForVersion(VersionOptions options) { _query.ForVersion(options); return new DefaultHqlQuery<TPart>(_query); } IEnumerable<TPart> IHqlQuery<TPart>.List() { return _query.List().AsPart<TPart>(); } IEnumerable<TPart> IHqlQuery<TPart>.Slice(int skip, int count) { return _query.Slice(skip, count).AsPart<TPart>(); } int IHqlQuery<TPart>.Count() { return _query.Count(); } public IHqlQuery<TPart> Join(Action<IAliasFactory> alias) { _query.Join(alias); return new DefaultHqlQuery<TPart>(_query); } public IHqlQuery<TPart> Where(Action<IAliasFactory> alias, Action<IHqlExpressionFactory> predicate) { _query.Where(alias, predicate); return new DefaultHqlQuery<TPart>(_query); } public IHqlQuery<TPart> OrderBy(Action<IAliasFactory> alias, Action<IHqlSortFactory> order) { _query.OrderBy(alias, order); return new DefaultHqlQuery<TPart>(_query); } } public class Alias : IAlias { public Alias(string name) { if (String.IsNullOrEmpty(name)) { throw new ArgumentException("Alias can't be empty"); } Name = name.Strip('-'); } public DefaultHqlQuery<IContent> Query { get; set; } public string Name { get; set; } } public interface IJoin : IAlias { string TableName { get; set; } string Type { get; set; } } public class Sort { public Sort(IAlias alias, string propertyName, bool ascending) { Alias = alias; PropertyName = propertyName; Ascending = ascending; } public IAlias Alias { get; set; } public string PropertyName { get; set; } public bool Ascending { get; set; } } public class Join : Alias, IJoin { public Join(string tableName, string alias) : this(tableName, alias, "join") {} public Join(string tableName, string alias, string type) : base(alias) { if (String.IsNullOrEmpty(tableName)) { throw new ArgumentException("Table Name can't be empty"); } TableName = tableName; Type = type; } public string TableName { get; set; } public string Type { get; set; } } public class DefaultHqlSortFactory : IHqlSortFactory { public bool Ascending { get; set; } public string PropertyName { get; set; } public bool Randomize { get; set; } public void Asc(string propertyName) { PropertyName = propertyName; Ascending = true; } public void Desc(string propertyName) { PropertyName = propertyName; Ascending = false; } public void Random() { Randomize = true; } } public class DefaultAliasFactory : IAliasFactory{ private readonly DefaultHqlQuery _query; public IAlias Current { get; private set; } public DefaultAliasFactory(DefaultHqlQuery query) { _query = query; Current = _query.BindItemCriteria(); } public IAliasFactory ContentPartRecord<TRecord>() where TRecord : ContentPartRecord { Current = _query.BindPartCriteria<TRecord>(); return this; } public IAliasFactory ContentPartRecord(Type contentPartRecord) { if(!contentPartRecord.IsSubclassOf(typeof(ContentPartRecord))) { throw new ArgumentException("Type must inherit from ContentPartRecord", "contentPartRecord"); } Current = _query.BindPartCriteria(contentPartRecord); return this; } public IAliasFactory Property(string propertyName, string alias) { Current = _query.BindCriteriaByAlias(Current, propertyName, alias); return this; } public IAliasFactory Named(string alias) { Current = _query.BindNamedAlias(alias); return this; } public IAliasFactory ContentItem() { return Named("ci"); } public IAliasFactory ContentItemVersion() { Current = _query.BindItemVersionCriteria(); return this; } public IAliasFactory ContentType() { return Named("ct"); } } public class DefaultHqlExpressionFactory : IHqlExpressionFactory { public IHqlCriterion Criterion { get; private set; } public void Eq(string propertyName, object value) { Criterion = HqlRestrictions.Eq(propertyName, value); } public void Like(string propertyName, string value, HqlMatchMode matchMode) { Criterion = HqlRestrictions.Like(propertyName, value, matchMode); } public void InsensitiveLike(string propertyName, string value, HqlMatchMode matchMode) { Criterion = HqlRestrictions.InsensitiveLike(propertyName, value, matchMode); } public void Gt(string propertyName, object value) { Criterion = HqlRestrictions.Gt(propertyName, value); } public void Lt(string propertyName, object value) { Criterion = HqlRestrictions.Lt(propertyName, value); } public void Le(string propertyName, object value) { Criterion = HqlRestrictions.Le(propertyName, value); } public void Ge(string propertyName, object value) { Criterion = HqlRestrictions.Ge(propertyName, value); } public void Between(string propertyName, object lo, object hi) { Criterion = HqlRestrictions.Between(propertyName, lo, hi); } public void In(string propertyName, object[] values) { Criterion = HqlRestrictions.In(propertyName, values); } public void In(string propertyName, ICollection values) { Criterion = HqlRestrictions.In(propertyName, values); } public void InG<T>(string propertyName, ICollection<T> values) { Criterion = HqlRestrictions.InG(propertyName, values); } public void IsNull(string propertyName) { Criterion = HqlRestrictions.IsNull(propertyName); } public void EqProperty(string propertyName, string otherPropertyName) { Criterion = HqlRestrictions.EqProperty(propertyName, otherPropertyName); } public void NotEqProperty(string propertyName, string otherPropertyName) { Criterion = HqlRestrictions.NotEqProperty(propertyName, otherPropertyName); } public void GtProperty(string propertyName, string otherPropertyName) { Criterion = HqlRestrictions.GtProperty(propertyName, otherPropertyName); } public void GeProperty(string propertyName, string otherPropertyName) { Criterion = HqlRestrictions.GeProperty(propertyName, otherPropertyName); } public void LtProperty(string propertyName, string otherPropertyName) { Criterion = HqlRestrictions.LtProperty(propertyName, otherPropertyName); } public void LeProperty(string propertyName, string otherPropertyName) { Criterion = HqlRestrictions.LeProperty(propertyName, otherPropertyName); } public void IsNotNull(string propertyName) { Criterion = HqlRestrictions.IsNotNull(propertyName); } public void IsNotEmpty(string propertyName) { Criterion = HqlRestrictions.IsNotEmpty(propertyName); } public void IsEmpty(string propertyName) { Criterion = HqlRestrictions.IsEmpty(propertyName); } public void And(Action<IHqlExpressionFactory> lhs, Action<IHqlExpressionFactory> rhs) { lhs(this); var a = Criterion; rhs(this); var b = Criterion; Criterion = HqlRestrictions.And(a, b); } public void Or(Action<IHqlExpressionFactory> lhs, Action<IHqlExpressionFactory> rhs) { lhs(this); var a = Criterion; rhs(this); var b = Criterion; Criterion = HqlRestrictions.Or(a, b); } public void Not(Action<IHqlExpressionFactory> expression) { expression(this); var a = Criterion; Criterion = HqlRestrictions.Not(a); } public void Conjunction(Action<IHqlExpressionFactory> expression, params Action<IHqlExpressionFactory>[] otherExpressions) { var junction = HqlRestrictions.Conjunction(); foreach (var exp in Enumerable.Empty<Action<IHqlExpressionFactory>>().Union(new[] { expression }).Union(otherExpressions)) { exp(this); junction.Add(Criterion); } Criterion = junction; } public void Disjunction(Action<IHqlExpressionFactory> expression, params Action<IHqlExpressionFactory>[] otherExpressions) { var junction = HqlRestrictions.Disjunction(); foreach (var exp in Enumerable.Empty<Action<IHqlExpressionFactory>>().Union(new[] { expression }).Union(otherExpressions)) { exp(this); junction.Add(Criterion); } Criterion = junction; } public void AllEq(IDictionary propertyNameValues) { Criterion = HqlRestrictions.AllEq(propertyNameValues); } public void NaturalId() { Criterion = HqlRestrictions.NaturalId(); } } public enum HqlMatchMode { Exact, Start, End, Anywhere } }
using System; using System.Data; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.Text.RegularExpressions; using Epi.Analysis; using Epi; using Epi.Data; using Epi.Core.AnalysisInterpreter; using Epi.Windows; using Epi.Windows.Dialogs; using Epi.Windows.Analysis; namespace Epi.Windows.Analysis.Dialogs { /// <summary> /// Dialog for Delete Records command /// </summary> public partial class DeleteRecordsDialog : CommandDesignDialog { #region Constructor /// <summary> /// Default constructor - NOT TO BE USED FOR INSTANTIATION /// </summary> [Obsolete("Use of default constructor not allowed", true)] public DeleteRecordsDialog() { InitializeComponent(); } /// <summary> /// Constructor for the Delete Records dialog /// </summary> /// <param name="frm"></param> public DeleteRecordsDialog(Epi.Windows.Analysis.Forms.AnalysisMainForm frm) : base(frm) { InitializeComponent(); Construct(); } #endregion Constructors #region Event Handlers /// <summary> /// Common event handler for click event of build expression buttons /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void ClickHandler(object sender, System.EventArgs e) { //Control btn = (Control)sender; //if ((string)btn.Tag == null) //{ // txtRecAffected.Text += btn.Text; //} //else //{ // txtRecAffected.Text += (string)btn.Tag; //} //txtRecAffected.Focus(); //txtRecAffected.SelectionStart = txtRecAffected.TextLength; Button btn = (Button)sender; string strInsert = StringLiterals.SPACE; if (txtRecAffected.SelectionLength > 0) { //Don't replace the trailing comma in // multi-parameter functions like YEARS or // trailing close paren if selected by mistake while (txtRecAffected.SelectionLength > 0 && (txtRecAffected.SelectedText.EndsWith(StringLiterals.SPACE) || txtRecAffected.SelectedText.EndsWith(StringLiterals.COMMA) || txtRecAffected.SelectedText.EndsWith(StringLiterals.PARANTHESES_CLOSE))) { txtRecAffected.SelectionLength -= 1; } } if ((string)btn.Tag == null) { if ((string)btn.Text == StringLiterals.DOUBLEQUOTES) { //if the button is for a double quote, only add a leading space if there is // an even number of quotes in the expression so far. strInsert = ((QuoteCountIsEven(txtRecAffected.Text, txtRecAffected.SelectionStart)) ? StringLiterals.SPACE : string.Empty); } txtRecAffected.SelectedText = strInsert + (string)btn.Text; } else { if ((string)btn.Tag == StringLiterals.DOUBLEQUOTES) { //if the button is for a double quote, only add a leading space if there is // an odd number of quotes in the expression so far. strInsert = ((QuoteCountIsEven(txtRecAffected.Text, txtRecAffected.SelectionStart)) ? StringLiterals.SPACE : string.Empty); } txtRecAffected.SelectedText = strInsert + (string)btn.Tag; } //Remove spaces within (+) (.) and (-) as any spaces within the parentheses // will cause an error. txtRecAffected.Text = ClearSpacesFromParens(txtRecAffected.Text); txtRecAffected.Select(txtRecAffected.Text.Length, 0); txtRecAffected.Focus(); } /// <summary> /// Clears all user input /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void btnClear_Click(object sender, System.EventArgs e) { txtRecAffected.Text = string.Empty; cmbAvailableVar.Text = string.Empty; rdbMarkDel.Checked = true; cbkRunSilent.Checked = false; } /// <summary> /// Sets txtRecAffected text with value selected from cmbAvailableVar /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cmbAvailableVar_SelectedIndexChanged(object sender, System.EventArgs e) { if (!string.IsNullOrEmpty(cmbAvailableVar.Text)) { string AvailableVarString = (FieldNameNeedsBrackets(cmbAvailableVar.Text) ? Util.InsertInSquareBrackets(cmbAvailableVar.Text) : cmbAvailableVar.Text); //insert a space before the variable only when: // * textbox has length and insertion point is at the end and nothing is selected // * there isn't already a space at the end // * there is an even quote at the end (but not if its an odd quote) if ((txtRecAffected.TextLength > 0 && txtRecAffected.SelectionStart.Equals(txtRecAffected.TextLength)) && (txtRecAffected.SelectionLength.Equals(0))) { if (txtRecAffected.Text.EndsWith("\"")) { if (QuoteCountIsEven(txtRecAffected.Text, txtRecAffected.SelectionStart)) { AvailableVarString = StringLiterals.SPACE + AvailableVarString; } } else { AvailableVarString = StringLiterals.SPACE + AvailableVarString; } } if (txtRecAffected.SelectionLength > 0) { //Don't replace the trailing comma in // multi-parameter functions like YEARS or // trailing close paren if selected by mistake while (txtRecAffected.SelectionLength > 0 && (txtRecAffected.SelectedText.EndsWith(StringLiterals.SPACE) || txtRecAffected.SelectedText.EndsWith(StringLiterals.COMMA) || txtRecAffected.SelectedText.EndsWith(StringLiterals.PARANTHESES_CLOSE))) { txtRecAffected.SelectionLength -= 1; } } txtRecAffected.SelectedText = AvailableVarString; txtRecAffected.Focus(); txtRecAffected.Text = ClearSpacesFromParens(txtRecAffected.Text); txtRecAffected.Select(txtRecAffected.Text.Length, 0); } } private void txtRecAffected_Leave(object sender, System.EventArgs e) { CheckForInputSufficiency(); } private void DeleteRecordsDialog_Load(object sender, System.EventArgs e) { LoadVariables(); } /// <summary> /// Opens a process to show the related help topic /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> protected override void btnHelp_Click(object sender, System.EventArgs e) { System.Diagnostics.Process.Start("http://www.cdc.gov/epiinfo/user-guide/command-reference/analysis-commands-delete-records.html"); } #endregion //Event Handlers #region Public Methods /// <summary> /// Sets enabled property of OK and Save Only /// </summary> public override void CheckForInputSufficiency() { bool inputValid = ValidateInput(); btnOK.Enabled = inputValid; btnSaveOnly.Enabled = inputValid; } #endregion Public Methods #region Protected Methods /// <summary> /// Validates user input /// </summary> /// <returns>True/False depending upon whether errors occurred</returns> protected override bool ValidateInput() { base.ValidateInput(); string expression = txtRecAffected.Text.Trim(); if (string.IsNullOrEmpty(expression)) { ErrorMessages.Add(SharedStrings.NO_DELETE_CRITERIA); } return (ErrorMessages.Count == 0); } /// <summary> /// Generates command text /// </summary> protected override void GenerateCommand() { string expression = txtRecAffected.Text.Trim(); #region preconditions if (expression.Trim() != "*" && !ValidExpression(expression)) //dcs0 8/1/2008 { MessageBox.Show(string.Format(SharedStrings.INVALID_EXPRESSION, expression)); CommandText = ""; return; } if (EpiInterpreter.Context.CurrentRead.File.Contains(".xlsx") || EpiInterpreter.Context.CurrentRead.File.Contains(".xls") || EpiInterpreter.Context.CurrentRead.File.Contains("FMT=Delimited")) { MessageBox.Show("Deletion not supported for this datasource", "DELETE RECORDS"); Close(); throw new GeneralException(string.Format(SharedStrings.INVALID_DATA_SOURCE, "Excel")); } #endregion Preconditions WordBuilder command = new WordBuilder(); command.Append(CommandNames.DELETE); if(expression.Trim() != "*") command.Append("("); command.Append(expression); if (expression.Trim() != "*") command.Append(")"); if (rdbPermDeletion.Checked) { command.Append(CommandNames.PERMANENT); } if (cbkRunSilent.Checked) { command.Append(CommandNames.RUNSILENT); } CommandText = command.ToString(); } #endregion Protected Methods #region Private Methods private void Construct() { if (!this.DesignMode) { Configuration config = Configuration.GetNewInstance(); Epi.DataSets.Config.SettingsRow settings = Configuration.GetNewInstance().Settings; this.btnMissing.Text = settings.RepresentationOfMissing; this.btnYes.Text = settings.RepresentationOfYes; this.btnNo.Text = settings.RepresentationOfNo; this.btnOK.Click += new System.EventHandler(this.btnOK_Click); this.btnSaveOnly.Click += new System.EventHandler(this.btnSaveOnly_Click); if (this.EpiInterpreter.Context.CurrentProject != null && this.EpiInterpreter.Context.CurrentProject.Views.Exists(this.EpiInterpreter.Context.CurrentRead.Identifier)) { rdbPermDeletion.Checked = false; rdbMarkDel.Checked = true; rdbMarkDel.Enabled = true; } else { rdbMarkDel.Checked = false; rdbPermDeletion.Checked = true; rdbMarkDel.Enabled = false; } } } private bool ValidExpression(string expression) { Regex valid = new Regex("[A-Z,a-z,0-9,_,(.),(+),(-),\\[,\\]]+ *[<>=]+ *[\",A-Z,a-z,0-9,_,(.),(-),(+),\"]+"); return (valid.Match(expression).Success); } //private bool ValidExpression(string expression) //{ // // The expression must contain a LHS operand and a RHS operand and a comparison operator // string[] exp = expression.Split(new char[] { ' ', '<', '>', '=' }); // if (exp.GetUpperBound(0) < 1) // doesn't have 2 operands // { // return false; // } // return (expression.Contains("<") || expression.Contains(">") || expression.Contains("=")); //} private void LoadVariables() { ////First get the list of all variables //// DataTable variables = GetAllVariablesAsDataTable(true, true, true, false); //DataTable variables = GetMemoryRegion().GetVariablesAsDataTable( // VariableType.DataSource | // VariableType.Standard | // VariableType.Global); ////Sort the data //System.Data.DataView dv = variables.DefaultView; //dv.Sort = ColumnNames.NAME; //cmbAvailableVar.DataSource = dv; //cmbAvailableVar.DisplayMember = ColumnNames.NAME; //cmbAvailableVar.ValueMember = ColumnNames.NAME; VariableType scopeWord = VariableType.DataSource | VariableType.Standard | VariableType.Global; FillVariableCombo(cmbAvailableVar, scopeWord); cmbAvailableVar.SelectedIndex = -1; this.cmbAvailableVar.SelectedIndexChanged += new System.EventHandler(this.cmbAvailableVar_SelectedIndexChanged); } /// <summary> /// Removes any embedded spaces within parentheses that could cause errors with /// yes (+), no (.), and missing (.) and trims leading/trailing spaces. /// also from less than or equal, greater than or equal, and not equal; /// </summary> /// <param name="input">Input string to search</param> private string ClearSpacesFromParens(string input) { string strCheckedA; string strCheckedB; strCheckedA = Regex.Replace(input, @"\s+\(\s+\+\s\)", " (+)"); //removes spaces within ( + ) to make (+) yes strCheckedB = Regex.Replace(strCheckedA, @"\s+\(\s+\-\s+\)", " (-)"); //removes spaces in (-) no strCheckedA = Regex.Replace(strCheckedB, @"\s+\(\s+\.\s+\)", " (.)"); //removes spaces in (.) missing strCheckedB = Regex.Replace(strCheckedA, @"\s+\<\s+\=", " <="); //removes spaces in <= less than or equal strCheckedA = Regex.Replace(strCheckedB, @"\s+\>\s+\=", " >="); // > = becomes >= greater than or equal strCheckedB = Regex.Replace(strCheckedA, @"\s+\<\s+\>", " <>"); // < > becomes <> not equal return strCheckedB.Trim(); } /// <summary> /// Returns TRUE if the count of doublequotes in a string is even. /// </summary> /// <param name="input">String input to check</param> /// <param name="stopPos">String position to end checking (start of selection to be replaced).</param> /// <returns> Returns TRUE if the count of doublequotes in the input string is even.</returns> private static bool QuoteCountIsEven(string input, int stopPos) { int result = 0; char q = '\"'; for (int i = 0; i < stopPos; i++) { if (q == input[i]) result++; } return (0 == result % 2); } #endregion Private Methods #region Function Context Menu /// <summary> /// Handles the MouseDown event of the Fx button /// </summary> /// <param name="sender">Object that fired the event</param> /// <param name="e">.NET supplied event parameters</param> private void btnFunction_MouseDown(object sender, MouseEventArgs e) { BuildFunctionContextMenu().Show((Control)sender, e.Location); } /// <summary> /// Handles the MouseDown event of the Functions button /// </summary> /// <param name="sender">Object that fired the event</param> /// <param name="e">.NET supplied event parameters</param> private void btnFunctions_MouseDown(object sender, MouseEventArgs e) { BuildFunctionContextMenu().Show((Control)sender, e.Location); } /// <summary> /// Handles the Click event of the Functions and Operators context menu /// </summary> /// <param name="sender">Object that fired the event</param> /// <param name="e">.NET supplied event parameters</param> private void FXClickHandler(object sender, System.EventArgs e) { ToolStripMenuItem FXItem = (ToolStripMenuItem)sender; if (txtRecAffected.SelectionLength > 0) { //Don't replace the trailing comma in // multi-parameter functions like YEARS or // trailing close paren if selected by mistake while (txtRecAffected.SelectionLength > 0 && (txtRecAffected.SelectedText.EndsWith(StringLiterals.SPACE) || txtRecAffected.SelectedText.EndsWith(StringLiterals.COMMA) || txtRecAffected.SelectedText.EndsWith(StringLiterals.PARANTHESES_CLOSE))) { txtRecAffected.SelectionLength -= 1; } } txtRecAffected.SelectedText = StringLiterals.SPACE + FXItem.ToolTipText + StringLiterals.SPACE; txtRecAffected.Text = ClearSpacesFromParens(txtRecAffected.Text); txtRecAffected.Select(txtRecAffected.Text.Length, 0); txtRecAffected.Focus(); } /// <summary> /// Builds a context menu for functions and operators /// </summary> /// <returns>A context menu for functions and operators</returns> private ContextMenuStrip BuildFunctionContextMenu() { ContextMenuStrip contextMenu = new ContextMenuStrip(); //================================================================== ToolStripMenuItem mnuOperators = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_NUMCOPS); ToolStripMenuItem mnuExponent = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_NUMCOPS_EXP); mnuExponent.ToolTipText = StringLiterals.CARET; mnuExponent.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuMOD = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_NUMCOPS_MOD); mnuMOD.ToolTipText = CommandNames.MOD; mnuMOD.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuGT = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_NUMCOPS_GT); mnuGT.ToolTipText = StringLiterals.GREATER_THAN; mnuGT.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuGTE = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_NUMCOPS_GTE); mnuGTE.ToolTipText = StringLiterals.GREATER_THAN_OR_EQUAL; mnuGTE.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuEqual = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_NUMCOPS_EQUAL); mnuEqual.ToolTipText = StringLiterals.EQUAL; mnuEqual.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuNE = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_NUMCOPS_LTGT); mnuNE.ToolTipText = StringLiterals.LESS_THAN_OR_GREATER_THAN; mnuNE.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuLT = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_NUMCOPS_LT); mnuLT.ToolTipText = StringLiterals.LESS_THAN; mnuLT.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuLTE = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_NUMCOPS_LTE); mnuLTE.ToolTipText = StringLiterals.LESS_THAN_OR_EQUAL; mnuLTE.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuLIKE = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_NUMCOPS_LIKE); mnuLIKE.ToolTipText = CommandNames.LIKE; mnuLIKE.Click += new EventHandler(FXClickHandler); //====================================================================== ToolStripMenuItem mnuBools = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_LGOPS); ToolStripMenuItem mnuAND = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_LGOPS_AND); mnuAND.ToolTipText = CommandNames.AND; mnuAND.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuOR = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_LGOPS_OR); mnuOR.ToolTipText = CommandNames.OR; mnuOR.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuXOR = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_LGOPS_XOR); mnuXOR.ToolTipText = CommandNames.XOR; mnuXOR.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuNOT = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_LGOPS_NOT); mnuNOT.ToolTipText = CommandNames.NOT; mnuNOT.Click += new EventHandler(FXClickHandler); //===================================================================== ToolStripMenuItem mnuNums = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_NUMFX); ToolStripMenuItem mnuEXP = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_NUMFX_EXP); mnuEXP.ToolTipText = CommandNames.EXP + SharedStrings.CNTXT_FXN_TMPLT_VARIABLE; mnuEXP.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuSIN = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_NUMFX_SIN); mnuSIN.ToolTipText = CommandNames.SIN + SharedStrings.CNTXT_FXN_TMPLT_VARIABLE; mnuSIN.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuCOS = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_NUMFX_COS); mnuCOS.ToolTipText = CommandNames.COS + SharedStrings.CNTXT_FXN_TMPLT_VARIABLE; mnuCOS.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuTAN = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_NUMFX_TAN); mnuTAN.ToolTipText = CommandNames.TAN + SharedStrings.CNTXT_FXN_TMPLT_VARIABLE; mnuTAN.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuLOG = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_NUMFX_LOG); mnuLOG.ToolTipText = CommandNames.LOG + SharedStrings.CNTXT_FXN_TMPLT_VARIABLE; mnuLOG.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuLN = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_NUMFX_LN); mnuLN.ToolTipText = CommandNames.LN + SharedStrings.CNTXT_FXN_TMPLT_VARIABLE; mnuLN.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuABS = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_NUMFX_ABS); mnuABS.ToolTipText = CommandNames.ABS + SharedStrings.CNTXT_FXN_TMPLT_VARIABLE; mnuABS.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuRND = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_NUMFX_RND); mnuRND.ToolTipText = CommandNames.RND + SharedStrings.CNTXT_FXN_TMPLT_VARIABLE; mnuRND.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuSTEP = new ToolStripMenuItem(CommandNames.STEP); mnuSTEP.ToolTipText = CommandNames.STEP + StringLiterals.PARANTHESES_OPEN + StringLiterals.SPACE + SharedStrings.CNTXT_FXN_TMPLT_VAR_PARM + StringLiterals.COMMA + StringLiterals.SPACE + SharedStrings.CNTXT_FXN_TMPLT_VAR_PARM + StringLiterals.SPACE + StringLiterals.PARANTHESES_CLOSE; mnuSTEP.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuTRUNC = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_NUMFX_TRUNC); mnuTRUNC.ToolTipText = CommandNames.TRUNC + SharedStrings.CNTXT_FXN_TMPLT_VARIABLE; mnuTRUNC.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuROUND = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_NUMFX_ROUND); mnuROUND.ToolTipText = CommandNames.ROUND + SharedStrings.CNTXT_FXN_TMPLT_VARIABLE; mnuROUND.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuNTD = new ToolStripMenuItem(CommandNames.NUMTODATE); mnuNTD.ToolTipText = CommandNames.NUMTODATE + SharedStrings.CNTXT_FXN_TMPLT_DATEPARTS; mnuNTD.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuNTT = new ToolStripMenuItem(CommandNames.NUMTOTIME); mnuNTT.ToolTipText = CommandNames.NUMTOTIME + SharedStrings.CNTXT_FXN_TMPLT_TIMEPARTS; mnuNTT.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuPFROMZ = new ToolStripMenuItem(CommandNames.PFROMZ); mnuPFROMZ.ToolTipText = CommandNames.PFROMZ + SharedStrings.CNTXT_FXN_TMPLT_VARIABLE; mnuPFROMZ.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuZSCORE = new ToolStripMenuItem(CommandNames.ZSCORE); mnuZSCORE.ToolTipText = CommandNames.ZSCORE + SharedStrings.CNTXT_FXN_TMPLT_ZSCORE; mnuZSCORE.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuRECORDCOUNT = new ToolStripMenuItem(CommandNames.RECORDCOUNT); mnuRECORDCOUNT.ToolTipText = CommandNames.RECORDCOUNT; mnuRECORDCOUNT.Click += new EventHandler(FXClickHandler); //=================================================================== ToolStripMenuItem mnuDates = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_DATFX); ToolStripMenuItem mnuYRS = new ToolStripMenuItem(CommandNames.YEARS); mnuYRS.ToolTipText = CommandNames.YEARS + SharedStrings.CNTXT_FXN_DATFX_TMPLT2; mnuYRS.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuMOS = new ToolStripMenuItem(CommandNames.MONTHS); mnuMOS.ToolTipText = CommandNames.MONTHS + SharedStrings.CNTXT_FXN_DATFX_TMPLT2; mnuMOS.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuDYS = new ToolStripMenuItem(CommandNames.DAYS); mnuDYS.ToolTipText = CommandNames.DAYS + SharedStrings.CNTXT_FXN_DATFX_TMPLT2; mnuDYS.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuYR = new ToolStripMenuItem(CommandNames.YEAR); mnuYR.ToolTipText = CommandNames.YEAR + SharedStrings.CNTXT_FXN_DATFX_TMPLT1; mnuYR.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuMO = new ToolStripMenuItem(CommandNames.MONTH); mnuMO.ToolTipText = CommandNames.MONTH + SharedStrings.CNTXT_FXN_DATFX_TMPLT1; mnuMO.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuDY = new ToolStripMenuItem(CommandNames.DAY); mnuDY.ToolTipText = CommandNames.DAY + SharedStrings.CNTXT_FXN_DATFX_TMPLT1; mnuDY.Click += new EventHandler(FXClickHandler); //=================================================================== ToolStripMenuItem mnuSys = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_SYSFXN); ToolStripMenuItem mnuCurrUser = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_SYSFXN_CURRUSER); mnuCurrUser.ToolTipText = CommandNames.CURRENTUSER + StringLiterals.PARANTHESES_OPEN + StringLiterals.SPACE + StringLiterals.PARANTHESES_CLOSE; mnuCurrUser.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuEXISTS = new ToolStripMenuItem(CommandNames.EXISTS); mnuEXISTS.ToolTipText = CommandNames.EXISTS + SharedStrings.CNTXT_FXN_TMPLT_FILENAME; mnuEXISTS.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuFILEDATE = new ToolStripMenuItem(CommandNames.FILEDATE); mnuFILEDATE.ToolTipText = CommandNames.FILEDATE + SharedStrings.CNTXT_FXN_TMPLT_FILENAME; mnuFILEDATE.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuSYSTEMDATE = new ToolStripMenuItem(CommandNames.SYSTEMDATE); mnuSYSTEMDATE.ToolTipText = CommandNames.SYSTEMDATE; mnuSYSTEMDATE.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuSYSTEMTIME = new ToolStripMenuItem(CommandNames.SYSTEMTIME); mnuSYSTEMTIME.ToolTipText = CommandNames.SYSTEMTIME; mnuSYSTEMTIME.Click += new EventHandler(FXClickHandler); //ToolStripMenuItem mnuENVIRON = new ToolStripMenuItem("ENVIRON"); //mnuENVIRON.ToolTipText = "ENVIRON( <name_of_env_variable> )"; //mnuENVIRON.Click += new EventHandler(FXClickHandler); //=================================================================== ToolStripMenuItem mnuTimes = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_TIMEFXN); ToolStripMenuItem mnuHOURS = new ToolStripMenuItem(CommandNames.HOURS); mnuHOURS.ToolTipText = CommandNames.HOURS + SharedStrings.CNTXT_FXN_DATFX_TMPLT2; mnuHOURS.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuMINUTES = new ToolStripMenuItem("MINUTES"); mnuMINUTES.ToolTipText = CommandNames.MINUTES + SharedStrings.CNTXT_FXN_DATFX_TMPLT2; mnuMINUTES.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuSECONDS = new ToolStripMenuItem("SECONDS"); mnuSECONDS.ToolTipText = CommandNames.SECONDS + SharedStrings.CNTXT_FXN_DATFX_TMPLT2; mnuSECONDS.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuHOUR = new ToolStripMenuItem("HOUR"); mnuHOUR.ToolTipText = CommandNames.HOUR + SharedStrings.CNTXT_FXN_DATFX_TMPLT1; mnuHOUR.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuMINUTE = new ToolStripMenuItem("MINUTE"); mnuMINUTE.ToolTipText = CommandNames.MINUTE + SharedStrings.CNTXT_FXN_DATFX_TMPLT1; mnuMINUTE.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuSECOND = new ToolStripMenuItem("SECOND"); mnuSECOND.ToolTipText = CommandNames.SECOND + SharedStrings.CNTXT_FXN_DATFX_TMPLT1; mnuSECOND.Click += new EventHandler(FXClickHandler); //================================================================== ToolStripMenuItem mnuTxts = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_TEXTFXN); ToolStripMenuItem mnuTXTTONUM = new ToolStripMenuItem(CommandNames.TXTTONUM); mnuTXTTONUM.ToolTipText = CommandNames.TXTTONUM + SharedStrings.CNTXT_FXN_TMPLT_VARIABLE; mnuTXTTONUM.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuTXTTODATE = new ToolStripMenuItem(CommandNames.TXTTODATE); mnuTXTTODATE.ToolTipText = CommandNames.TXTTODATE + SharedStrings.CNTXT_FXN_TMPLT_VARIABLE; mnuTXTTODATE.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuSUBSTRING = new ToolStripMenuItem(CommandNames.SUBSTRING); mnuSUBSTRING.ToolTipText = CommandNames.SUBSTRING + SharedStrings.CNTXT_FXN_TMPLT_SUBSTRING; mnuSUBSTRING.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuSTRLEN = new ToolStripMenuItem(CommandNames.STRLEN); mnuSTRLEN.ToolTipText = CommandNames.STRLEN + SharedStrings.CNTXT_FXN_TMPLT_VARIABLE; mnuSTRLEN.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuUPPERCASE = new ToolStripMenuItem(CommandNames.UPPERCASE); mnuUPPERCASE.ToolTipText = CommandNames.UPPERCASE + SharedStrings.CNTXT_FXN_TMPLT_VARIABLE; mnuUPPERCASE.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuFINDTEXT = new ToolStripMenuItem(CommandNames.FINDTEXT); mnuFINDTEXT.ToolTipText = CommandNames.FINDTEXT + SharedStrings.CNTXT_FXN_TMPLT_FINDTEXT; mnuFINDTEXT.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuFORMAT = new ToolStripMenuItem(CommandNames.FORMAT); mnuFORMAT.ToolTipText = CommandNames.FORMAT + SharedStrings.CNTXT_FXN_TMPLT_VARIABLE; mnuFORMAT.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuLINEBREAK = new ToolStripMenuItem(CommandNames.LINEBREAK); mnuLINEBREAK.ToolTipText = CommandNames.LINEBREAK + StringLiterals.PARANTHESES_OPEN + StringLiterals.SPACE + StringLiterals.PARANTHESES_CLOSE; mnuLINEBREAK.Click += new EventHandler(FXClickHandler); //======================================================================= ToolStripMenuItem mnuDATEFORMATS = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_FRMT_DATES); ToolStripMenuItem mnuGeneralDate = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_FRMT_DATES_GEN); mnuGeneralDate.ToolTipText = CommandNames.FORMAT + StringLiterals.PARANTHESES_OPEN + StringLiterals.SPACE + SharedStrings.CNTXT_FXN_TMPLT_VAR_PARM + StringLiterals.COMMA + StringLiterals.SPACE + CommandNames.GENERAL_DATE_FORMAT + StringLiterals.PARANTHESES_CLOSE; mnuGeneralDate.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuLongDate = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_FRMT_DATES_LONGDATE); mnuLongDate.ToolTipText = CommandNames.FORMAT + StringLiterals.PARANTHESES_OPEN + StringLiterals.SPACE + SharedStrings.CNTXT_FXN_TMPLT_VAR_PARM + StringLiterals.COMMA + StringLiterals.SPACE + CommandNames.LONG_DATE_FORMAT + StringLiterals.PARANTHESES_CLOSE; mnuLongDate.Click += new EventHandler(FXClickHandler); //ToolStripMenuItem mnuMediumDate = new ToolStripMenuItem("Medium Date"); //mnuMediumDate.ToolTipText = "FORMAT( <variable>, \"Medium Date\")"; //mnuMediumDate.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuShortDate = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_FRMT_DATES_SHORTDATE); mnuShortDate.ToolTipText = CommandNames.FORMAT + StringLiterals.PARANTHESES_OPEN + StringLiterals.SPACE + SharedStrings.CNTXT_FXN_TMPLT_VAR_PARM + StringLiterals.COMMA + StringLiterals.SPACE + CommandNames.SHORT_DATE_FORMAT + StringLiterals.PARANTHESES_CLOSE; mnuShortDate.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuLongTime = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_FRMT_DATES_LONGTIME); mnuLongTime.ToolTipText = CommandNames.FORMAT + StringLiterals.PARANTHESES_OPEN + StringLiterals.SPACE + SharedStrings.CNTXT_FXN_TMPLT_VAR_PARM + StringLiterals.COMMA + StringLiterals.SPACE + CommandNames.LONG_TIME_FORMAT + StringLiterals.PARANTHESES_CLOSE; mnuLongTime.Click += new EventHandler(FXClickHandler); //ToolStripMenuItem mnuMediumTime = new ToolStripMenuItem("Medium Time"); //mnuMediumTime.ToolTipText = "FORMAT( <variable>, \"Medium Time\")"; //mnuMediumTime.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuShortTime = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_FRMT_DATES_SHORTTIME); mnuShortTime.ToolTipText = CommandNames.FORMAT + StringLiterals.PARANTHESES_OPEN + StringLiterals.SPACE + SharedStrings.CNTXT_FXN_TMPLT_VAR_PARM + StringLiterals.COMMA + StringLiterals.SPACE + CommandNames.SHORT_TIME_FORMAT + StringLiterals.PARANTHESES_CLOSE; mnuShortTime.Click += new EventHandler(FXClickHandler); //=========================================================================== ToolStripMenuItem mnuNumberFormats = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_FRMT_NUM); ToolStripMenuItem mnuGeneralNumber = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_FRMT_NUM_GEN); mnuGeneralNumber.ToolTipText = CommandNames.FORMAT + StringLiterals.PARANTHESES_OPEN + StringLiterals.SPACE + SharedStrings.CNTXT_FXN_TMPLT_VAR_PARM + StringLiterals.COMMA + StringLiterals.SPACE + CommandNames.GENERAL_NUMBER_FORMAT + StringLiterals.PARANTHESES_CLOSE; mnuGeneralNumber.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuCurrency = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_FRMT_NUM_CURRENCY); mnuCurrency.ToolTipText = CommandNames.FORMAT + StringLiterals.PARANTHESES_OPEN + StringLiterals.SPACE + SharedStrings.CNTXT_FXN_TMPLT_VAR_PARM + StringLiterals.COMMA + StringLiterals.SPACE + CommandNames.CURRENCY_FORMAT + StringLiterals.PARANTHESES_CLOSE; mnuCurrency.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuFixed = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_FRMT_NUM_FIXED); mnuFixed.ToolTipText = CommandNames.FORMAT + StringLiterals.PARANTHESES_OPEN + StringLiterals.SPACE + SharedStrings.CNTXT_FXN_TMPLT_VAR_PARM + StringLiterals.COMMA + StringLiterals.SPACE + CommandNames.FIXED_FORMAT + StringLiterals.PARANTHESES_CLOSE; mnuFixed.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuStandard = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_FRMT_NUM_STANDARD); mnuStandard.ToolTipText = CommandNames.FORMAT + StringLiterals.PARANTHESES_OPEN + StringLiterals.SPACE + SharedStrings.CNTXT_FXN_TMPLT_VAR_PARM + StringLiterals.COMMA + StringLiterals.SPACE + CommandNames.STANDARD_FORMAT + StringLiterals.PARANTHESES_CLOSE; mnuStandard.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuPercent = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_FRMT_NUM_PERCENT); mnuPercent.ToolTipText = CommandNames.FORMAT + StringLiterals.PARANTHESES_OPEN + StringLiterals.SPACE + SharedStrings.CNTXT_FXN_TMPLT_VAR_PARM + StringLiterals.COMMA + StringLiterals.SPACE + CommandNames.PERCENT_FORMAT + StringLiterals.PARANTHESES_CLOSE; mnuPercent.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuScientific = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_FRMT_NUM_SCIENTIFIC); mnuScientific.ToolTipText = CommandNames.FORMAT + StringLiterals.PARANTHESES_OPEN + StringLiterals.SPACE + SharedStrings.CNTXT_FXN_TMPLT_VAR_PARM + StringLiterals.COMMA + StringLiterals.SPACE + CommandNames.SCIENTIFIC_FORMAT + StringLiterals.PARANTHESES_CLOSE; mnuScientific.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuYN = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_FRMT_NUM_YN); mnuYN.ToolTipText = CommandNames.FORMAT + StringLiterals.PARANTHESES_OPEN + StringLiterals.SPACE + SharedStrings.CNTXT_FXN_TMPLT_VAR_PARM + StringLiterals.COMMA + StringLiterals.SPACE + CommandNames.YESNO_FORMAT + StringLiterals.PARANTHESES_CLOSE; mnuYN.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuTF = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_FRMT_NUM_TF); mnuTF.ToolTipText = CommandNames.FORMAT + StringLiterals.PARANTHESES_OPEN + StringLiterals.SPACE + SharedStrings.CNTXT_FXN_TMPLT_VAR_PARM + StringLiterals.COMMA + StringLiterals.SPACE + CommandNames.TRUE_FALSE_FORMAT + StringLiterals.PARANTHESES_CLOSE; mnuTF.Click += new EventHandler(FXClickHandler); ToolStripMenuItem mnuOnOff = new ToolStripMenuItem(SharedStrings.CNTXT_FXN_FRMT_NUM_ONOFF); mnuOnOff.ToolTipText = CommandNames.FORMAT + StringLiterals.PARANTHESES_OPEN + StringLiterals.SPACE + SharedStrings.CNTXT_FXN_TMPLT_VAR_PARM + StringLiterals.COMMA + StringLiterals.SPACE + CommandNames.ON_OFF_FORMAT + StringLiterals.PARANTHESES_CLOSE; mnuOnOff.Click += new EventHandler(FXClickHandler); contextMenu.Items.Add(mnuOperators); contextMenu.Items.Add(mnuBools); contextMenu.Items.Add(new ToolStripSeparator()); contextMenu.Items.AddRange(new ToolStripMenuItem[] { mnuNums, mnuDates, mnuSys, mnuTimes, mnuTxts }); mnuOperators.DropDown.Items.AddRange(new ToolStripMenuItem[] { mnuExponent, mnuMOD, mnuGT, mnuGTE, mnuEqual, mnuNE, mnuLT, mnuLTE, mnuLIKE }); mnuBools.DropDown.Items.AddRange(new ToolStripMenuItem[] { mnuAND, mnuOR, mnuXOR, mnuNOT }); mnuNums.DropDown.Items.AddRange(new ToolStripMenuItem[] { mnuABS, mnuEXP, mnuLN, mnuLOG, mnuNTD, mnuNTT, mnuRECORDCOUNT, mnuRND, mnuROUND, mnuSTEP, mnuSIN, mnuCOS, mnuTAN, mnuTRUNC, mnuPFROMZ, mnuZSCORE }); mnuDates.DropDown.Items.AddRange(new ToolStripMenuItem[] { mnuYRS, mnuMOS, mnuDYS, mnuYR, mnuMO, mnuDY }); mnuSys.DropDown.Items.AddRange(new ToolStripMenuItem[] { mnuCurrUser, mnuEXISTS, mnuFILEDATE, mnuSYSTEMDATE, mnuSYSTEMTIME }); mnuTimes.DropDown.Items.AddRange(new ToolStripMenuItem[] { mnuHOURS, mnuMINUTES, mnuSECONDS, mnuHOUR, mnuMINUTE, mnuSECOND }); mnuTxts.DropDown.Items.AddRange(new ToolStripMenuItem[] { mnuFINDTEXT, mnuFORMAT, mnuLINEBREAK, mnuSTRLEN, mnuSUBSTRING, mnuTXTTONUM, mnuTXTTODATE, mnuUPPERCASE }); mnuFORMAT.DropDown.Items.AddRange(new ToolStripMenuItem[] { mnuDATEFORMATS, mnuNumberFormats }); mnuDATEFORMATS.DropDown.Items.AddRange(new ToolStripMenuItem[] { mnuGeneralDate, mnuLongDate, mnuShortDate, mnuLongTime, mnuShortTime }); mnuNumberFormats.DropDown.Items.AddRange(new ToolStripMenuItem[] { mnuGeneralNumber, mnuCurrency, mnuFixed, mnuStandard, mnuPercent, mnuScientific, mnuYN, mnuTF, mnuOnOff }); return contextMenu; } #endregion //Function Context Menu private void gbxDelete_Enter(object sender, EventArgs e) { } private void lblRecAffected_Click(object sender, EventArgs e) { } private void btnFunction_Click(object sender, EventArgs e) { } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using OpenMetaverse; namespace OpenSim.Framework { public class EstateSettings { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public delegate void SaveDelegate(EstateSettings rs); public event SaveDelegate OnSave; // Only the client uses these // private uint m_EstateID = 0; public uint EstateID { get { return m_EstateID; } set { m_EstateID = value; } } private string m_EstateName = "My Estate"; public string EstateName { get { return m_EstateName; } set { m_EstateName = value; } } private bool m_AllowLandmark = true; public bool AllowLandmark { get { return m_AllowLandmark; } set { m_AllowLandmark = value; } } private bool m_AllowParcelChanges = true; public bool AllowParcelChanges { get { return m_AllowParcelChanges; } set { m_AllowParcelChanges = value; } } private bool m_AllowSetHome = true; public bool AllowSetHome { get { return m_AllowSetHome; } set { m_AllowSetHome = value; } } private uint m_ParentEstateID = 1; public uint ParentEstateID { get { return m_ParentEstateID; } set { m_ParentEstateID = value; } } private float m_BillableFactor = 0.0f; public float BillableFactor { get { return m_BillableFactor; } set { m_BillableFactor = value; } } private int m_PricePerMeter = 1; public int PricePerMeter { get { return m_PricePerMeter; } set { m_PricePerMeter = value; } } private int m_RedirectGridX = 0; public int RedirectGridX { get { return m_RedirectGridX; } set { m_RedirectGridX = value; } } private int m_RedirectGridY = 0; public int RedirectGridY { get { return m_RedirectGridY; } set { m_RedirectGridY = value; } } // Used by the sim // private bool m_UseGlobalTime = true; public bool UseGlobalTime { get { return m_UseGlobalTime; } set { m_UseGlobalTime = value; } } private bool m_FixedSun = false; public bool FixedSun { get { return m_FixedSun; } set { m_FixedSun = value; } } private double m_SunPosition = 0.0; public double SunPosition { get { return m_SunPosition; } set { m_SunPosition = value; } } private bool m_AllowVoice = true; public bool AllowVoice { get { return m_AllowVoice; } set { m_AllowVoice = value; } } private bool m_AllowDirectTeleport = true; public bool AllowDirectTeleport { get { return m_AllowDirectTeleport; } set { m_AllowDirectTeleport = value; } } private bool m_DenyAnonymous = false; public bool DenyAnonymous { get { return m_DenyAnonymous; } set { m_DenyAnonymous = value; } } private bool m_DenyIdentified = false; public bool DenyIdentified { get { return m_DenyIdentified; } set { m_DenyIdentified = value; } } private bool m_DenyTransacted = false; public bool DenyTransacted { get { return m_DenyTransacted; } set { m_DenyTransacted = value; } } private bool m_AbuseEmailToEstateOwner = false; public bool AbuseEmailToEstateOwner { get { return m_AbuseEmailToEstateOwner; } set { m_AbuseEmailToEstateOwner = value; } } private bool m_BlockDwell = false; public bool BlockDwell { get { return m_BlockDwell; } set { m_BlockDwell = value; } } private bool m_EstateSkipScripts = false; public bool EstateSkipScripts { get { return m_EstateSkipScripts; } set { m_EstateSkipScripts = value; } } private bool m_ResetHomeOnTeleport = false; public bool ResetHomeOnTeleport { get { return m_ResetHomeOnTeleport; } set { m_ResetHomeOnTeleport = value; } } private bool m_TaxFree = false; public bool TaxFree { get { return m_TaxFree; } set { m_TaxFree = value; } } private bool m_PublicAccess = true; public bool PublicAccess { get { return m_PublicAccess; } set { m_PublicAccess = value; } } private string m_AbuseEmail = String.Empty; public string AbuseEmail { get { return m_AbuseEmail; } set { m_AbuseEmail= value; } } private UUID m_EstateOwner = UUID.Zero; public UUID EstateOwner { get { return m_EstateOwner; } set { m_EstateOwner = value; } } private bool m_DenyMinors = false; public bool DenyMinors { get { return m_DenyMinors; } set { m_DenyMinors = value; } } // All those lists... // private List<UUID> l_EstateManagers = new List<UUID>(); public UUID[] EstateManagers { get { return l_EstateManagers.ToArray(); } set { l_EstateManagers = new List<UUID>(value); } } private List<EstateBan> l_EstateBans = new List<EstateBan>(); public EstateBan[] EstateBans { get { return l_EstateBans.ToArray(); } set { l_EstateBans = new List<EstateBan>(value); } } private List<UUID> l_EstateAccess = new List<UUID>(); public UUID[] EstateAccess { get { return l_EstateAccess.ToArray(); } set { l_EstateAccess = new List<UUID>(value); } } private List<UUID> l_EstateGroups = new List<UUID>(); public UUID[] EstateGroups { get { return l_EstateGroups.ToArray(); } set { l_EstateGroups = new List<UUID>(value); } } public EstateSettings() { } public void Save() { if (OnSave != null) OnSave(this); } public void AddEstateUser(UUID avatarID) { if (avatarID == UUID.Zero) return; if (!l_EstateAccess.Contains(avatarID)) l_EstateAccess.Add(avatarID); } public void RemoveEstateUser(UUID avatarID) { if (l_EstateAccess.Contains(avatarID)) l_EstateAccess.Remove(avatarID); } public void AddEstateGroup(UUID avatarID) { if (avatarID == UUID.Zero) return; if (!l_EstateGroups.Contains(avatarID)) l_EstateGroups.Add(avatarID); } public void RemoveEstateGroup(UUID avatarID) { if (l_EstateGroups.Contains(avatarID)) l_EstateGroups.Remove(avatarID); } public void AddEstateManager(UUID avatarID) { if (avatarID == UUID.Zero) return; if (!l_EstateManagers.Contains(avatarID)) l_EstateManagers.Add(avatarID); } public void RemoveEstateManager(UUID avatarID) { if (l_EstateManagers.Contains(avatarID)) l_EstateManagers.Remove(avatarID); } public bool IsEstateManagerOrOwner(UUID avatarID) { if (IsEstateOwner(avatarID)) return true; return l_EstateManagers.Contains(avatarID); } public bool IsEstateOwner(UUID avatarID) { if (avatarID == m_EstateOwner) return true; return false; } public bool IsBanned(UUID avatarID) { foreach (EstateBan ban in l_EstateBans) if (ban.BannedUserID == avatarID) return true; return false; } public void AddBan(EstateBan ban) { if (ban == null) return; if (!IsBanned(ban.BannedUserID)) l_EstateBans.Add(ban); } public void ClearBans() { l_EstateBans.Clear(); } public void RemoveBan(UUID avatarID) { foreach (EstateBan ban in new List<EstateBan>(l_EstateBans)) if (ban.BannedUserID == avatarID) l_EstateBans.Remove(ban); } public bool HasAccess(UUID user) { if (IsEstateManagerOrOwner(user)) return true; return l_EstateAccess.Contains(user); } public void SetFromFlags(ulong regionFlags) { ResetHomeOnTeleport = ((regionFlags & (ulong)OpenMetaverse.RegionFlags.ResetHomeOnTeleport) == (ulong)OpenMetaverse.RegionFlags.ResetHomeOnTeleport); BlockDwell = ((regionFlags & (ulong)OpenMetaverse.RegionFlags.BlockDwell) == (ulong)OpenMetaverse.RegionFlags.BlockDwell); AllowLandmark = ((regionFlags & (ulong)OpenMetaverse.RegionFlags.AllowLandmark) == (ulong)OpenMetaverse.RegionFlags.AllowLandmark); AllowParcelChanges = ((regionFlags & (ulong)OpenMetaverse.RegionFlags.AllowParcelChanges) == (ulong)OpenMetaverse.RegionFlags.AllowParcelChanges); AllowSetHome = ((regionFlags & (ulong)OpenMetaverse.RegionFlags.AllowSetHome) == (ulong)OpenMetaverse.RegionFlags.AllowSetHome); } public bool GroupAccess(UUID groupID) { return l_EstateGroups.Contains(groupID); } } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace RemoteEventsLabWeb { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registered for this add-in</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an add-in event /// </summary> /// <param name="properties">Properties of an add-in event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registered for this add-in</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registered for this add-in</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted add-in. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the add-in should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the add-in should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the add-in should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust add-in. /// </summary> /// <returns>True if this is a high trust add-in.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted add-in configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
/* * Simulator.cs * RVO2 Library C# * * Copyright 2008 University of North Carolina at Chapel Hill * * 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. * * Please send all bug reports to <geom@cs.unc.edu>. * * The authors may be contacted via: * * Jur van den Berg, Stephen J. Guy, Jamie Snape, Ming C. Lin, Dinesh Manocha * Dept. of Computer Science * 201 S. Columbia St. * Frederick P. Brooks, Jr. Computer Science Bldg. * Chapel Hill, N.C. 27599-3175 * United States of America * * <http://gamma.cs.unc.edu/RVO2/> */ using System; using System.Collections.Generic; using System.Threading; namespace RVO { /** * <summary>Defines the simulation.</summary> */ public class Simulator { /** * <summary>Defines a worker.</summary> */ private class Worker { private ManualResetEvent doneEvent_; private int end_; private int start_; /** * <summary>Constructs and initializes a worker.</summary> * * <param name="start">Start.</param> * <param name="end">End.</param> * <param name="doneEvent">Done event.</param> */ internal Worker(int start, int end, ManualResetEvent doneEvent) { start_ = start; end_ = end; doneEvent_ = doneEvent; } /** * <summary>Performs a simulation step.</summary> * * <param name="obj">Unused.</param> */ internal void step(object obj) { for (int agentNo = start_; agentNo < end_; ++agentNo) { Simulator.Instance.agents_[agentNo].computeNeighbors(); Simulator.Instance.agents_[agentNo].computeNewVelocity(); } doneEvent_.Set(); } /** * <summary>updates the two-dimensional position and * two-dimensional velocity of each agent.</summary> * * <param name="obj">Unused.</param> */ internal void update(object obj) { for (int agentNo = start_; agentNo < end_; ++agentNo) { Simulator.Instance.agents_[agentNo].update(); } doneEvent_.Set(); } } internal IList<Agent> agents_; internal IList<Obstacle> obstacles_; internal KdTree kdTree_; internal float timeStep_; private static Simulator instance_ = new Simulator(); private Agent defaultAgent_; private ManualResetEvent[] doneEvents_; private Worker[] workers_; private int numWorkers_; private float globalTime_; public static Simulator Instance { get { return instance_; } } /** * <summary>Adds a new agent with default properties to the simulation. * </summary> * * <returns>The number of the agent, or -1 when the agent defaults have * not been set.</returns> * * <param name="position">The two-dimensional starting position of this * agent.</param> */ public int addAgent(Vector2 position) { if (defaultAgent_ == null) { return -1; } Agent agent = new Agent(); agent.id_ = agents_.Count; agent.maxNeighbors_ = defaultAgent_.maxNeighbors_; agent.maxSpeed_ = defaultAgent_.maxSpeed_; agent.neighborDist_ = defaultAgent_.neighborDist_; agent.position_ = position; agent.radius_ = defaultAgent_.radius_; agent.timeHorizon_ = defaultAgent_.timeHorizon_; agent.timeHorizonObst_ = defaultAgent_.timeHorizonObst_; agent.velocity_ = defaultAgent_.velocity_; agents_.Add(agent); return agent.id_; } /** * <summary>Adds a new agent to the simulation.</summary> * * <returns>The number of the agent.</returns> * * <param name="position">The two-dimensional starting position of this * agent.</param> * <param name="neighborDist">The maximum distance (center point to * center point) to other agents this agent takes into account in the * navigation. The larger this number, the longer the running time of * the simulation. If the number is too low, the simulation will not be * safe. Must be non-negative.</param> * <param name="maxNeighbors">The maximum number of other agents this * agent takes into account in the navigation. The larger this number, * the longer the running time of the simulation. If the number is too * low, the simulation will not be safe.</param> * <param name="timeHorizon">The minimal amount of time for which this * agent's velocities that are computed by the simulation are safe with * respect to other agents. The larger this number, the sooner this * agent will respond to the presence of other agents, but the less * freedom this agent has in choosing its velocities. Must be positive. * </param> * <param name="timeHorizonObst">The minimal amount of time for which * this agent's velocities that are computed by the simulation are safe * with respect to obstacles. The larger this number, the sooner this * agent will respond to the presence of obstacles, but the less freedom * this agent has in choosing its velocities. Must be positive.</param> * <param name="radius">The radius of this agent. Must be non-negative. * </param> * <param name="maxSpeed">The maximum speed of this agent. Must be * non-negative.</param> * <param name="velocity">The initial two-dimensional linear velocity of * this agent.</param> */ public int addAgent(Vector2 position, float neighborDist, int maxNeighbors, float timeHorizon, float timeHorizonObst, float radius, float maxSpeed, Vector2 velocity) { Agent agent = new Agent(); agent.id_ = agents_.Count; agent.maxNeighbors_ = maxNeighbors; agent.maxSpeed_ = maxSpeed; agent.neighborDist_ = neighborDist; agent.position_ = position; agent.radius_ = radius; agent.timeHorizon_ = timeHorizon; agent.timeHorizonObst_ = timeHorizonObst; agent.velocity_ = velocity; agents_.Add(agent); return agent.id_; } /** * <summary>Adds a new obstacle to the simulation.</summary> * * <returns>The number of the first vertex of the obstacle, or -1 when * the number of vertices is less than two.</returns> * * <param name="vertices">List of the vertices of the polygonal obstacle * in counterclockwise order.</param> * * <remarks>To add a "negative" obstacle, e.g. a bounding polygon around * the environment, the vertices should be listed in clockwise order. * </remarks> */ public int addObstacle(IList<Vector2> vertices) { if (vertices.Count < 2) { return -1; } int obstacleNo = obstacles_.Count; for (int i = 0; i < vertices.Count; ++i) { Obstacle obstacle = new Obstacle(); obstacle.point_ = vertices[i]; if (i != 0) { obstacle.previous_ = obstacles_[obstacles_.Count - 1]; obstacle.previous_.next_ = obstacle; } if (i == vertices.Count - 1) { obstacle.next_ = obstacles_[obstacleNo]; obstacle.next_.previous_ = obstacle; } obstacle.direction_ = RVOMath.normalize(vertices[(i == vertices.Count - 1 ? 0 : i + 1)] - vertices[i]); if (vertices.Count == 2) { obstacle.convex_ = true; } else { obstacle.convex_ = (RVOMath.leftOf(vertices[(i == 0 ? vertices.Count - 1 : i - 1)], vertices[i], vertices[(i == vertices.Count - 1 ? 0 : i + 1)]) >= 0.0f); } obstacle.id_ = obstacles_.Count; obstacles_.Add(obstacle); } return obstacleNo; } /** * <summary>Clears the simulation.</summary> */ public void Clear() { agents_ = new List<Agent>(); defaultAgent_ = null; kdTree_ = new KdTree(); obstacles_ = new List<Obstacle>(); globalTime_ = 0.0f; timeStep_ = 0.1f; SetNumWorkers(0); } /** * <summary>Performs a simulation step and updates the two-dimensional * position and two-dimensional velocity of each agent.</summary> * * <returns>The global time after the simulation step.</returns> */ public float doStep() { if (workers_ == null) { workers_ = new Worker[numWorkers_]; doneEvents_ = new ManualResetEvent[workers_.Length]; for (int block = 0; block < workers_.Length; ++block) { doneEvents_[block] = new ManualResetEvent(false); workers_[block] = new Worker(block * getNumAgents() / workers_.Length, (block + 1) * getNumAgents() / workers_.Length, doneEvents_[block]); } } kdTree_.buildAgentTree(); for (int block = 0; block < workers_.Length; ++block) { doneEvents_[block].Reset(); ThreadPool.QueueUserWorkItem(workers_[block].step); } WaitHandle.WaitAll(doneEvents_); for (int block = 0; block < workers_.Length; ++block) { doneEvents_[block].Reset(); ThreadPool.QueueUserWorkItem(workers_[block].update); } WaitHandle.WaitAll(doneEvents_); globalTime_ += timeStep_; return globalTime_; } /** * <summary>Returns the specified agent neighbor of the specified agent. * </summary> * * <returns>The number of the neighboring agent.</returns> * * <param name="agentNo">The number of the agent whose agent neighbor is * to be retrieved.</param> * <param name="neighborNo">The number of the agent neighbor to be * retrieved.</param> */ public int getAgentAgentNeighbor(int agentNo, int neighborNo) { return agents_[agentNo].agentNeighbors_[neighborNo].Value.id_; } /** * <summary>Returns the maximum neighbor count of a specified agent. * </summary> * * <returns>The present maximum neighbor count of the agent.</returns> * * <param name="agentNo">The number of the agent whose maximum neighbor * count is to be retrieved.</param> */ public int getAgentMaxNeighbors(int agentNo) { return agents_[agentNo].maxNeighbors_; } /** * <summary>Returns the maximum speed of a specified agent.</summary> * * <returns>The present maximum speed of the agent.</returns> * * <param name="agentNo">The number of the agent whose maximum speed is * to be retrieved.</param> */ public float getAgentMaxSpeed(int agentNo) { return agents_[agentNo].maxSpeed_; } /** * <summary>Returns the maximum neighbor distance of a specified agent. * </summary> * * <returns>The present maximum neighbor distance of the agent. * </returns> * * <param name="agentNo">The number of the agent whose maximum neighbor * distance is to be retrieved.</param> */ public float getAgentNeighborDist(int agentNo) { return agents_[agentNo].neighborDist_; } /** * <summary>Returns the count of agent neighbors taken into account to * compute the current velocity for the specified agent.</summary> * * <returns>The count of agent neighbors taken into account to compute * the current velocity for the specified agent.</returns> * * <param name="agentNo">The number of the agent whose count of agent * neighbors is to be retrieved.</param> */ public int getAgentNumAgentNeighbors(int agentNo) { return agents_[agentNo].agentNeighbors_.Count; } /** * <summary>Returns the count of obstacle neighbors taken into account * to compute the current velocity for the specified agent.</summary> * * <returns>The count of obstacle neighbors taken into account to * compute the current velocity for the specified agent.</returns> * * <param name="agentNo">The number of the agent whose count of obstacle * neighbors is to be retrieved.</param> */ public int getAgentNumObstacleNeighbors(int agentNo) { return agents_[agentNo].obstacleNeighbors_.Count; } /** * <summary>Returns the specified obstacle neighbor of the specified * agent.</summary> * * <returns>The number of the first vertex of the neighboring obstacle * edge.</returns> * * <param name="agentNo">The number of the agent whose obstacle neighbor * is to be retrieved.</param> * <param name="neighborNo">The number of the obstacle neighbor to be * retrieved.</param> */ public int getAgentObstacleNeighbor(int agentNo, int neighborNo) { return agents_[agentNo].obstacleNeighbors_[neighborNo].Value.id_; } /** * <summary>Returns the ORCA constraints of the specified agent. * </summary> * * <returns>A list of lines representing the ORCA constraints.</returns> * * <param name="agentNo">The number of the agent whose ORCA constraints * are to be retrieved.</param> * * <remarks>The halfplane to the left of each line is the region of * permissible velocities with respect to that ORCA constraint. * </remarks> */ public IList<Line> getAgentOrcaLines(int agentNo) { return agents_[agentNo].orcaLines_; } /** * <summary>Returns the two-dimensional position of a specified agent. * </summary> * * <returns>The present two-dimensional position of the (center of the) * agent.</returns> * * <param name="agentNo">The number of the agent whose two-dimensional * position is to be retrieved.</param> */ public Vector2 getAgentPosition(int agentNo) { return agents_[agentNo].position_; } /** * <summary>Returns the two-dimensional preferred velocity of a * specified agent.</summary> * * <returns>The present two-dimensional preferred velocity of the agent. * </returns> * * <param name="agentNo">The number of the agent whose two-dimensional * preferred velocity is to be retrieved.</param> */ public Vector2 getAgentPrefVelocity(int agentNo) { return agents_[agentNo].prefVelocity_; } /** * <summary>Returns the radius of a specified agent.</summary> * * <returns>The present radius of the agent.</returns> * * <param name="agentNo">The number of the agent whose radius is to be * retrieved.</param> */ public float getAgentRadius(int agentNo) { return agents_[agentNo].radius_; } /** * <summary>Returns the time horizon of a specified agent.</summary> * * <returns>The present time horizon of the agent.</returns> * * <param name="agentNo">The number of the agent whose time horizon is * to be retrieved.</param> */ public float getAgentTimeHorizon(int agentNo) { return agents_[agentNo].timeHorizon_; } /** * <summary>Returns the time horizon with respect to obstacles of a * specified agent.</summary> * * <returns>The present time horizon with respect to obstacles of the * agent.</returns> * * <param name="agentNo">The number of the agent whose time horizon with * respect to obstacles is to be retrieved.</param> */ public float getAgentTimeHorizonObst(int agentNo) { return agents_[agentNo].timeHorizonObst_; } /** * <summary>Returns the two-dimensional linear velocity of a specified * agent.</summary> * * <returns>The present two-dimensional linear velocity of the agent. * </returns> * * <param name="agentNo">The number of the agent whose two-dimensional * linear velocity is to be retrieved.</param> */ public Vector2 getAgentVelocity(int agentNo) { return agents_[agentNo].velocity_; } /** * <summary>Returns the global time of the simulation.</summary> * * <returns>The present global time of the simulation (zero initially). * </returns> */ public float getGlobalTime() { return globalTime_; } /** * <summary>Returns the count of agents in the simulation.</summary> * * <returns>The count of agents in the simulation.</returns> */ public int getNumAgents() { return agents_.Count; } /** * <summary>Returns the count of obstacle vertices in the simulation. * </summary> * * <returns>The count of obstacle vertices in the simulation.</returns> */ public int getNumObstacleVertices() { return obstacles_.Count; } /** * <summary>Returns the count of workers.</summary> * * <returns>The count of workers.</returns> */ public int GetNumWorkers() { return numWorkers_; } /** * <summary>Returns the two-dimensional position of a specified obstacle * vertex.</summary> * * <returns>The two-dimensional position of the specified obstacle * vertex.</returns> * * <param name="vertexNo">The number of the obstacle vertex to be * retrieved.</param> */ public Vector2 getObstacleVertex(int vertexNo) { return obstacles_[vertexNo].point_; } /** * <summary>Returns the number of the obstacle vertex succeeding the * specified obstacle vertex in its polygon.</summary> * * <returns>The number of the obstacle vertex succeeding the specified * obstacle vertex in its polygon.</returns> * * <param name="vertexNo">The number of the obstacle vertex whose * successor is to be retrieved.</param> */ public int getNextObstacleVertexNo(int vertexNo) { return obstacles_[vertexNo].next_.id_; } /** * <summary>Returns the number of the obstacle vertex preceding the * specified obstacle vertex in its polygon.</summary> * * <returns>The number of the obstacle vertex preceding the specified * obstacle vertex in its polygon.</returns> * * <param name="vertexNo">The number of the obstacle vertex whose * predecessor is to be retrieved.</param> */ public int getPrevObstacleVertexNo(int vertexNo) { return obstacles_[vertexNo].previous_.id_; } /** * <summary>Returns the time step of the simulation.</summary> * * <returns>The present time step of the simulation.</returns> */ public float getTimeStep() { return timeStep_; } /** * <summary>Processes the obstacles that have been added so that they * are accounted for in the simulation.</summary> * * <remarks>Obstacles added to the simulation after this function has * been called are not accounted for in the simulation.</remarks> */ public void processObstacles() { kdTree_.buildObstacleTree(); } /** * <summary>Performs a visibility query between the two specified points * with respect to the obstacles.</summary> * * <returns>A boolean specifying whether the two points are mutually * visible. Returns true when the obstacles have not been processed. * </returns> * * <param name="point1">The first point of the query.</param> * <param name="point2">The second point of the query.</param> * <param name="radius">The minimal distance between the line connecting * the two points and the obstacles in order for the points to be * mutually visible (optional). Must be non-negative.</param> */ public bool queryVisibility(Vector2 point1, Vector2 point2, float radius) { return kdTree_.queryVisibility(point1, point2, radius); } /** * <summary>Sets the default properties for any new agent that is added. * </summary> * * <param name="neighborDist">The default maximum distance (center point * to center point) to other agents a new agent takes into account in * the navigation. The larger this number, the longer he running time of * the simulation. If the number is too low, the simulation will not be * safe. Must be non-negative.</param> * <param name="maxNeighbors">The default maximum number of other agents * a new agent takes into account in the navigation. The larger this * number, the longer the running time of the simulation. If the number * is too low, the simulation will not be safe.</param> * <param name="timeHorizon">The default minimal amount of time for * which a new agent's velocities that are computed by the simulation * are safe with respect to other agents. The larger this number, the * sooner an agent will respond to the presence of other agents, but the * less freedom the agent has in choosing its velocities. Must be * positive.</param> * <param name="timeHorizonObst">The default minimal amount of time for * which a new agent's velocities that are computed by the simulation * are safe with respect to obstacles. The larger this number, the * sooner an agent will respond to the presence of obstacles, but the * less freedom the agent has in choosing its velocities. Must be * positive.</param> * <param name="radius">The default radius of a new agent. Must be * non-negative.</param> * <param name="maxSpeed">The default maximum speed of a new agent. Must * be non-negative.</param> * <param name="velocity">The default initial two-dimensional linear * velocity of a new agent.</param> */ public void setAgentDefaults(float neighborDist, int maxNeighbors, float timeHorizon, float timeHorizonObst, float radius, float maxSpeed, Vector2 velocity) { if (defaultAgent_ == null) { defaultAgent_ = new Agent(); } defaultAgent_.maxNeighbors_ = maxNeighbors; defaultAgent_.maxSpeed_ = maxSpeed; defaultAgent_.neighborDist_ = neighborDist; defaultAgent_.radius_ = radius; defaultAgent_.timeHorizon_ = timeHorizon; defaultAgent_.timeHorizonObst_ = timeHorizonObst; defaultAgent_.velocity_ = velocity; } /** * <summary>Sets the maximum neighbor count of a specified agent. * </summary> * * <param name="agentNo">The number of the agent whose maximum neighbor * count is to be modified.</param> * <param name="maxNeighbors">The replacement maximum neighbor count. * </param> */ public void setAgentMaxNeighbors(int agentNo, int maxNeighbors) { agents_[agentNo].maxNeighbors_ = maxNeighbors; } /** * <summary>Sets the maximum speed of a specified agent.</summary> * * <param name="agentNo">The number of the agent whose maximum speed is * to be modified.</param> * <param name="maxSpeed">The replacement maximum speed. Must be * non-negative.</param> */ public void setAgentMaxSpeed(int agentNo, float maxSpeed) { agents_[agentNo].maxSpeed_ = maxSpeed; } /** * <summary>Sets the maximum neighbor distance of a specified agent. * </summary> * * <param name="agentNo">The number of the agent whose maximum neighbor * distance is to be modified.</param> * <param name="neighborDist">The replacement maximum neighbor distance. * Must be non-negative.</param> */ public void setAgentNeighborDist(int agentNo, float neighborDist) { agents_[agentNo].neighborDist_ = neighborDist; } /** * <summary>Sets the two-dimensional position of a specified agent. * </summary> * * <param name="agentNo">The number of the agent whose two-dimensional * position is to be modified.</param> * <param name="position">The replacement of the two-dimensional * position.</param> */ public void setAgentPosition(int agentNo, Vector2 position) { agents_[agentNo].position_ = position; } /** * <summary>Sets the two-dimensional preferred velocity of a specified * agent.</summary> * * <param name="agentNo">The number of the agent whose two-dimensional * preferred velocity is to be modified.</param> * <param name="prefVelocity">The replacement of the two-dimensional * preferred velocity.</param> */ public void setAgentPrefVelocity(int agentNo, Vector2 prefVelocity) { agents_[agentNo].prefVelocity_ = prefVelocity; } /** * <summary>Sets the radius of a specified agent.</summary> * * <param name="agentNo">The number of the agent whose radius is to be * modified.</param> * <param name="radius">The replacement radius. Must be non-negative. * </param> */ public void setAgentRadius(int agentNo, float radius) { agents_[agentNo].radius_ = radius; } /** * <summary>Sets the time horizon of a specified agent with respect to * other agents.</summary> * * <param name="agentNo">The number of the agent whose time horizon is * to be modified.</param> * <param name="timeHorizon">The replacement time horizon with respect * to other agents. Must be positive.</param> */ public void setAgentTimeHorizon(int agentNo, float timeHorizon) { agents_[agentNo].timeHorizon_ = timeHorizon; } /** * <summary>Sets the time horizon of a specified agent with respect to * obstacles.</summary> * * <param name="agentNo">The number of the agent whose time horizon with * respect to obstacles is to be modified.</param> * <param name="timeHorizonObst">The replacement time horizon with * respect to obstacles. Must be positive.</param> */ public void setAgentTimeHorizonObst(int agentNo, float timeHorizonObst) { agents_[agentNo].timeHorizonObst_ = timeHorizonObst; } /** * <summary>Sets the two-dimensional linear velocity of a specified * agent.</summary> * * <param name="agentNo">The number of the agent whose two-dimensional * linear velocity is to be modified.</param> * <param name="velocity">The replacement two-dimensional linear * velocity.</param> */ public void setAgentVelocity(int agentNo, Vector2 velocity) { agents_[agentNo].velocity_ = velocity; } /** * <summary>Sets the global time of the simulation.</summary> * * <param name="globalTime">The global time of the simulation.</param> */ public void setGlobalTime(float globalTime) { globalTime_ = globalTime; } /** * <summary>Sets the number of workers.</summary> * * <param name="numWorkers">The number of workers.</param> */ public void SetNumWorkers(int numWorkers) { numWorkers_ = numWorkers; if (numWorkers_ <= 0) { int completionPorts; ThreadPool.GetMinThreads(out numWorkers_, out completionPorts); } workers_ = null; } /** * <summary>Sets the time step of the simulation.</summary> * * <param name="timeStep">The time step of the simulation. Must be * positive.</param> */ public void setTimeStep(float timeStep) { timeStep_ = timeStep; } /** * <summary>Constructs and initializes a simulation.</summary> */ private Simulator() { Clear(); } } }
namespace Microsoft.Protocols.TestSuites.MS_CPSWS { using System; using System.Collections.Generic; using System.Linq; using Microsoft.Protocols.TestSuites.Common; using Microsoft.VisualStudio.TestTools.UnitTesting; /// <summary> /// The test cases of Scenario 05. /// </summary> [TestClass] public class S05_SearchForEntities : TestSuiteBase { #region Test suite initialization and cleanup /// <summary> /// Initialize the test suite. /// </summary> /// <param name="testContext">The test context instance</param> [ClassInitialize] public static void ClassInitialize(TestContext testContext) { TestSuiteBase.TestSuiteClassInitialize(testContext); } /// <summary> /// Reset the test environment. /// </summary> [ClassCleanup] public static void ClassCleanup() { // Cleanup test site, must be called to ensure closing of logs. TestSuiteBase.TestSuiteClassCleanup(); } #endregion #region Test Cases /// <summary> /// A method used to verify the search operation can successfully find the first claims provider tree that contains a child. /// </summary> [TestCategory("MSCPSWS"), TestMethod] public void MSCPSWS_S05_TC01_Search() { // Set principal type for search. SPPrincipalType principalType = SPPrincipalType.SecurityGroup; // Generate ArrayOfSPProviderSearchArguments. List<SPProviderSearchArguments> arrayOfSPProviderSearchArguments = new List<SPProviderSearchArguments>(); Site.Assume.IsNotNull(this.GenerateProviderSearchArgumentsInput_Valid(), "There should be a valid provider search arguments!"); SPProviderSearchArguments providerSearchArguments = this.GenerateProviderSearchArgumentsInput_Valid(); arrayOfSPProviderSearchArguments.Add(providerSearchArguments); Site.Assume.IsNotNull(TestSuiteBase.SearchPattern, "The search pattern should not be null!"); // Call Search operation. SPProviderHierarchyTree[] responseOfSearchResult = CPSWSAdapter.Search(arrayOfSPProviderSearchArguments.ToArray(), principalType, TestSuiteBase.SearchPattern); Site.Assert.IsNotNull(responseOfSearchResult, "The search result MUST be not null."); Site.Assert.IsTrue(responseOfSearchResult.Length >= 1, "The search result MUST contain at least one claims provider."); // Get the input provider names list. ArrayOfString providerNames = new ArrayOfString(); providerNames.AddRange(arrayOfSPProviderSearchArguments.Select(root => root.ProviderName)); // Requirement capture condition. bool searchSuccess = false; foreach (SPProviderHierarchyTree providerTree in responseOfSearchResult) { if (providerTree.ProviderName.StartsWith(Common.GetConfigurationPropertyValue("HierarchyProviderPrefix", this.Site))) { if (providerNames.Contains(providerTree.ProviderName)) { searchSuccess = true; } else { // Jump over the Hierarchy Provider tree that the server sees fit to return together with the result Claims provider trees. continue; } } else if (providerNames.Contains(providerTree.ProviderName)) { searchSuccess = true; } else { Site.Assert.Fail("The provider names in the search result should be contained in the provider names in the input message!"); } } // Capture requirement 378 by matching the input provider name with the result claims provider name, // The search input claims provider already satisfy the condition 1 and 3 in requirement 378 in test environment configuration. Site.CaptureRequirementIfIsTrue( searchSuccess, 378, @"[In Search] The protocol server MUST search across all claims providers that meet all the following criteria: The claims providers are associated with the Web application (1) specified in the input message. The claims providers are listed in the provider search arguments in the input message. The claims providers support search."); // Capture requirement 398 by matching searchPattern with the result claims provider's Nm attribute. Site.CaptureRequirementIfIsTrue(searchSuccess, 398, @"[In Search] searchPattern: The protocol server MUST search for the string in each claims provider."); // Capture requirement 404 by matching searchPattern with the result claims provider's Nm attribute. Site.CaptureRequirementIfIsTrue(searchSuccess, 404, @"[In SearchResponse] The protocol server MUST return one claims provider hierarchy tree for each claims provider that contains entities that match the search string."); } /// <summary> /// A method used to verify when searchPattern is null as search input, the server will return an ArgumentNullException (searchPattern) message. /// </summary> [TestCategory("MSCPSWS"), TestMethod] public void MSCPSWS_S05_TC02_Search_nullSearchPattern() { // Set principal type for Search. SPPrincipalType principalType = SPPrincipalType.SharePointGroup; // Set ArrayOfSPProviderSearchArguments for Search. List<SPProviderSearchArguments> arrayOfSPProviderSearchArguments = new List<SPProviderSearchArguments>(); Site.Assume.IsNotNull(this.GenerateProviderSearchArgumentsInput_Valid(), "There should be a valid provider search arguments!"); SPProviderSearchArguments providerSearchArguments = this.GenerateProviderSearchArgumentsInput_Valid(); arrayOfSPProviderSearchArguments.Add(providerSearchArguments); bool caughtException = false; try { // Call the Search operation with searchPattern as null. CPSWSAdapter.Search(arrayOfSPProviderSearchArguments.ToArray(), principalType, null); } catch (System.ServiceModel.FaultException faultException) { caughtException = true; // Verify Requirement 652, if the server returns an ArgumentNullException<"searchPattern"> message. Site.CaptureRequirementIfIsTrue(this.VerifyArgumentNullException(faultException, "searchPattern"), 652, @"[In Search] If this [searchPattern] is NULL, the protocol server MUST return an ArgumentNullException<""searchPattern""> message."); } finally { this.Site.Assert.IsTrue(caughtException, "If searchPattern is NULL, the protocol server should return an ArgumentNullException<searchPattern> message."); } } /// <summary> /// A method used to verify the SearchAll operation can successfully find the first claims provider tree that contains a child. /// </summary> [TestCategory("MSCPSWS"), TestMethod] public void MSCPSWS_S05_TC03_SearchAll() { // Get the provider names of all the providers from the hierarchy ArrayOfString providerNames = new ArrayOfString(); SPProviderHierarchyTree[] responseOfGetHierarchyAllResult = TestSuiteBase.GetAllProviders(); providerNames.AddRange(responseOfGetHierarchyAllResult.Select(root => root.ProviderName)); foreach (SPProviderHierarchyNode node in responseOfGetHierarchyAllResult.SelectMany(root => root.Children)) { this.DepthFirstTraverse(node, ref providerNames); } // Set search principal Type. SPPrincipalType principalType = SPPrincipalType.SecurityGroup; // Get the searchPattern string as SearchAll input this.GenerateSearchAllInput_Valid(); // Get max count of matched entities allowed to return for this search. int maxCount = Convert.ToInt32(Common.GetConfigurationPropertyValue("MaxCount", Site)); Site.Assume.IsNotNull(TestSuiteBase.SearchPattern, "The search pattern should not be null!"); // Search the first claims provider tree which has a child. SPProviderHierarchyTree[] responseOfSearchResult = CPSWSAdapter.SearchAll(providerNames, principalType, TestSuiteBase.SearchPattern, maxCount); // Requirement capture condition. bool searchAllSuccess = false; bool isMatchSearchSearchPattern = false; foreach (SPProviderHierarchyTree providerTree in responseOfSearchResult) { if (providerTree.ProviderName.StartsWith(Common.GetConfigurationPropertyValue("HierarchyProviderPrefix", this.Site))) { if (providerNames.Contains(providerTree.ProviderName)) { searchAllSuccess = true; } else { // Jump over the Hierarchy Provider tree that the server sees fit to return together with the result Claims provider trees. continue; } } else if (providerNames.Contains(providerTree.ProviderName)) { searchAllSuccess = true; } else { Site.Assert.Fail("The provider names in the SearchAll result should be contained in the provider names in the input message!"); } if (providerTree.ProviderName == "System") { SPProviderHierarchyNode children = providerTree.Children[0]; if(TestSuiteBase.SearchPattern== children.Nm) { isMatchSearchSearchPattern = true; } } } // Capture requirement 417 by matching the input provider name with the result claims provider name, // The search input claims provider already satisfy the condition 1 and 3 in requirement 417 in test environment configuration. Site.CaptureRequirementIfIsTrue( searchAllSuccess, 417, @"[In SearchAll] The protocol server MUST search across all claims providers that meet all the following criteria: The claims providers are associated with the Web application (1) specified in the input message. The claims providers are listed in the provider names in the input message. The claims providers support search."); Site.CaptureRequirementIfIsTrue( isMatchSearchSearchPattern, 438, @"[In SearchAllResponse] The protocol server MUST return one claims provider hierarchy tree for each claims provider that contains entities that match the search string."); } /// <summary> /// A method used to verify when searchPattern is null as the SearchAll input, the server will return an ArgumentNullException(searchPattern) message. /// </summary> [TestCategory("MSCPSWS"), TestMethod] public void MSCPSWS_S05_TC04_SearchAll_nullSearchPattern() { // Get the provider names of all the providers from the hierarchy ArrayOfString providerNames = new ArrayOfString(); SPProviderHierarchyTree[] responseOfGetHierarchyAllResult = TestSuiteBase.GetAllProviders(); providerNames.AddRange(responseOfGetHierarchyAllResult.Select(root => root.ProviderName)); foreach (SPProviderHierarchyNode node in responseOfGetHierarchyAllResult.SelectMany(root => root.Children)) { this.DepthFirstTraverse(node, ref providerNames); } // Set search principal Type. SPPrincipalType principalType = SPPrincipalType.SharePointGroup; // Get max count of matched entities allowed to return for this search. int maxCount = Convert.ToInt32(Common.GetConfigurationPropertyValue("MaxCount", Site)); bool caughtException = false; try { // Set searchPattern as null and call searchAll. CPSWSAdapter.SearchAll(providerNames, principalType, null, maxCount); } catch (System.ServiceModel.FaultException faultException) { caughtException = true; // Verify Requirement 650, if the server returns an ArgumentNullException<"searchPattern"> message. Site.CaptureRequirementIfIsTrue(this.VerifyArgumentNullException(faultException, "searchPattern"), 650, @"[In SearchAll] If this [searchPattern] is NULL, the protocol server MUST return an ArgumentNullException<""searchPattern""> message."); } finally { this.Site.Assert.IsTrue(caughtException, "If searchPattern is NULL, the protocol server MUST return an ArgumentNullException<searchPattern> message."); } } #endregion } }
using System; using System.Collections.Generic; using Avalonia.Controls; using Avalonia.Controls.Templates; using Avalonia.Data; using Avalonia.UnitTests; using Moq; using Xunit; namespace Avalonia.Styling.UnitTests { public class StyleTests { [Fact] public void Style_With_Only_Type_Selector_Should_Update_Value() { Style style = new Style(x => x.OfType<Class1>()) { Setters = { new Setter(Class1.FooProperty, "Foo"), }, }; var target = new Class1(); style.TryAttach(target, null); Assert.Equal("Foo", target.Foo); } [Fact] public void Style_With_Class_Selector_Should_Update_And_Restore_Value() { Style style = new Style(x => x.OfType<Class1>().Class("foo")) { Setters = { new Setter(Class1.FooProperty, "Foo"), }, }; var target = new Class1(); style.TryAttach(target, null); Assert.Equal("foodefault", target.Foo); target.Classes.Add("foo"); Assert.Equal("Foo", target.Foo); target.Classes.Remove("foo"); Assert.Equal("foodefault", target.Foo); } [Fact] public void Style_With_No_Selector_Should_Apply_To_Containing_Control() { Style style = new Style { Setters = { new Setter(Class1.FooProperty, "Foo"), }, }; var target = new Class1(); style.TryAttach(target, target); Assert.Equal("Foo", target.Foo); } [Fact] public void Style_With_No_Selector_Should_Not_Apply_To_Other_Control() { Style style = new Style { Setters = { new Setter(Class1.FooProperty, "Foo"), }, }; var target = new Class1(); var other = new Class1(); style.TryAttach(target, other); Assert.Equal("foodefault", target.Foo); } [Fact] public void LocalValue_Should_Override_Style() { Style style = new Style(x => x.OfType<Class1>()) { Setters = { new Setter(Class1.FooProperty, "Foo"), }, }; var target = new Class1 { Foo = "Original", }; style.TryAttach(target, null); Assert.Equal("Original", target.Foo); } [Fact] public void Later_Styles_Should_Override_Earlier() { Styles styles = new Styles { new Style(x => x.OfType<Class1>().Class("foo")) { Setters = { new Setter(Class1.FooProperty, "Foo"), }, }, new Style(x => x.OfType<Class1>().Class("foo")) { Setters = { new Setter(Class1.FooProperty, "Bar"), }, } }; var target = new Class1(); List<string> values = new List<string>(); target.GetObservable(Class1.FooProperty).Subscribe(x => values.Add(x)); styles.TryAttach(target, null); target.Classes.Add("foo"); target.Classes.Remove("foo"); Assert.Equal(new[] { "foodefault", "Foo", "Bar", "foodefault" }, values); } [Fact] public void Later_Styles_Should_Override_Earlier_2() { Styles styles = new Styles { new Style(x => x.OfType<Class1>().Class("foo")) { Setters = { new Setter(Class1.FooProperty, "Foo"), }, }, new Style(x => x.OfType<Class1>().Class("bar")) { Setters = { new Setter(Class1.FooProperty, "Bar"), }, } }; var target = new Class1(); List<string> values = new List<string>(); target.GetObservable(Class1.FooProperty).Subscribe(x => values.Add(x)); styles.TryAttach(target, null); target.Classes.Add("bar"); target.Classes.Add("foo"); target.Classes.Remove("foo"); Assert.Equal(new[] { "foodefault", "Bar" }, values); } [Fact] public void Later_Styles_Should_Override_Earlier_3() { Styles styles = new Styles { new Style(x => x.OfType<Class1>().Class("foo")) { Setters = { new Setter(Class1.FooProperty, new Binding("Foo")), }, }, new Style(x => x.OfType<Class1>().Class("bar")) { Setters = { new Setter(Class1.FooProperty, new Binding("Bar")), }, } }; var target = new Class1 { DataContext = new { Foo = "Foo", Bar = "Bar", } }; List<string> values = new List<string>(); target.GetObservable(Class1.FooProperty).Subscribe(x => values.Add(x)); styles.TryAttach(target, null); target.Classes.Add("bar"); target.Classes.Add("foo"); target.Classes.Remove("foo"); Assert.Equal(new[] { "foodefault", "Bar" }, values); } [Fact] public void Inactive_Values_Should_Not_Be_Made_Active_During_Style_Attach() { using var app = UnitTestApplication.Start(TestServices.RealStyler); var root = new TestRoot { Styles = { new Style(x => x.OfType<Class1>()) { Setters = { new Setter(Class1.FooProperty, "Foo"), }, }, new Style(x => x.OfType<Class1>()) { Setters = { new Setter(Class1.FooProperty, "Bar"), }, } } }; var values = new List<string>(); var target = new Class1(); target.GetObservable(Class1.FooProperty).Subscribe(x => values.Add(x)); root.Child = target; Assert.Equal(new[] { "foodefault", "Bar" }, values); } [Fact] public void Inactive_Bindings_Should_Not_Be_Made_Active_During_Style_Attach() { using var app = UnitTestApplication.Start(TestServices.RealStyler); var root = new TestRoot { Styles = { new Style(x => x.OfType<Class1>()) { Setters = { new Setter(Class1.FooProperty, new Binding("Foo")), }, }, new Style(x => x.OfType<Class1>()) { Setters = { new Setter(Class1.FooProperty, new Binding("Bar")), }, } } }; var values = new List<string>(); var target = new Class1 { DataContext = new { Foo = "Foo", Bar = "Bar", } }; target.GetObservable(Class1.FooProperty).Subscribe(x => values.Add(x)); root.Child = target; Assert.Equal(new[] { "foodefault", "Bar" }, values); } [Fact] public void Inactive_Values_Should_Not_Be_Made_Active_During_Style_Detach() { using var app = UnitTestApplication.Start(TestServices.RealStyler); var root = new TestRoot { Styles = { new Style(x => x.OfType<Class1>()) { Setters = { new Setter(Class1.FooProperty, "Foo"), }, }, new Style(x => x.OfType<Class1>()) { Setters = { new Setter(Class1.FooProperty, "Bar"), }, } } }; var target = new Class1(); root.Child = target; var values = new List<string>(); target.GetObservable(Class1.FooProperty).Subscribe(x => values.Add(x)); root.Child = null; Assert.Equal(new[] { "Bar", "foodefault" }, values); } [Fact] public void Inactive_Values_Should_Not_Be_Made_Active_During_Style_Detach_2() { using var app = UnitTestApplication.Start(TestServices.RealStyler); var root = new TestRoot { Styles = { new Style(x => x.OfType<Class1>().Class("foo")) { Setters = { new Setter(Class1.FooProperty, "Foo"), }, }, new Style(x => x.OfType<Class1>()) { Setters = { new Setter(Class1.FooProperty, "Bar"), }, } } }; var target = new Class1 { Classes = { "foo" } }; root.Child = target; var values = new List<string>(); target.GetObservable(Class1.FooProperty).Subscribe(x => values.Add(x)); root.Child = null; Assert.Equal(new[] { "Foo", "foodefault" }, values); } [Fact] public void Inactive_Bindings_Should_Not_Be_Made_Active_During_Style_Detach() { using var app = UnitTestApplication.Start(TestServices.RealStyler); var root = new TestRoot { Styles = { new Style(x => x.OfType<Class1>()) { Setters = { new Setter(Class1.FooProperty, new Binding("Foo")), }, }, new Style(x => x.OfType<Class1>()) { Setters = { new Setter(Class1.FooProperty, new Binding("Bar")), }, } } }; var target = new Class1 { DataContext = new { Foo = "Foo", Bar = "Bar", } }; root.Child = target; var values = new List<string>(); target.GetObservable(Class1.FooProperty).Subscribe(x => values.Add(x)); root.Child = null; Assert.Equal(new[] { "Bar", "foodefault" }, values); } [Fact] public void Template_In_Non_Matching_Style_Is_Not_Built() { var instantiationCount = 0; var template = new FuncTemplate<Class1>(() => { ++instantiationCount; return new Class1(); }); Styles styles = new Styles { new Style(x => x.OfType<Class1>().Class("foo")) { Setters = { new Setter(Class1.ChildProperty, template), }, }, new Style(x => x.OfType<Class1>()) { Setters = { new Setter(Class1.ChildProperty, template), }, } }; var target = new Class1(); styles.TryAttach(target, null); Assert.NotNull(target.Child); Assert.Equal(1, instantiationCount); } [Fact] public void Template_In_Inactive_Style_Is_Not_Built() { var instantiationCount = 0; var template = new FuncTemplate<Class1>(() => { ++instantiationCount; return new Class1(); }); Styles styles = new Styles { new Style(x => x.OfType<Class1>()) { Setters = { new Setter(Class1.ChildProperty, template), }, }, new Style(x => x.OfType<Class1>()) { Setters = { new Setter(Class1.ChildProperty, template), }, } }; var target = new Class1(); target.BeginBatchUpdate(); styles.TryAttach(target, null); target.EndBatchUpdate(); Assert.NotNull(target.Child); Assert.Equal(1, instantiationCount); } [Fact] public void Style_Should_Detach_When_Control_Removed_From_Logical_Tree() { Border border; var style = new Style(x => x.OfType<Border>()) { Setters = { new Setter(Border.BorderThicknessProperty, new Thickness(4)), } }; var root = new TestRoot { Child = border = new Border(), }; style.TryAttach(border, null); Assert.Equal(new Thickness(4), border.BorderThickness); root.Child = null; Assert.Equal(new Thickness(0), border.BorderThickness); } [Fact] public void Removing_Style_Should_Detach_From_Control() { using (UnitTestApplication.Start(TestServices.RealStyler)) { var border = new Border(); var root = new TestRoot { Styles = { new Style(x => x.OfType<Border>()) { Setters = { new Setter(Border.BorderThicknessProperty, new Thickness(4)), } } }, Child = border, }; root.Measure(Size.Infinity); Assert.Equal(new Thickness(4), border.BorderThickness); root.Styles.RemoveAt(0); Assert.Equal(new Thickness(0), border.BorderThickness); } } [Fact] public void Adding_Style_Should_Attach_To_Control() { using (UnitTestApplication.Start(TestServices.RealStyler)) { var border = new Border(); var root = new TestRoot { Styles = { new Style(x => x.OfType<Border>()) { Setters = { new Setter(Border.BorderThicknessProperty, new Thickness(4)), } } }, Child = border, }; root.Measure(Size.Infinity); Assert.Equal(new Thickness(4), border.BorderThickness); root.Styles.Add(new Style(x => x.OfType<Border>()) { Setters = { new Setter(Border.BorderThicknessProperty, new Thickness(6)), } }); root.Measure(Size.Infinity); Assert.Equal(new Thickness(6), border.BorderThickness); } } [Fact] public void Removing_Style_With_Nested_Style_Should_Detach_From_Control() { using (UnitTestApplication.Start(TestServices.RealStyler)) { var border = new Border(); var root = new TestRoot { Styles = { new Styles { new Style(x => x.OfType<Border>()) { Setters = { new Setter(Border.BorderThicknessProperty, new Thickness(4)), } } } }, Child = border, }; root.Measure(Size.Infinity); Assert.Equal(new Thickness(4), border.BorderThickness); root.Styles.RemoveAt(0); Assert.Equal(new Thickness(0), border.BorderThickness); } } [Fact] public void Adding_Nested_Style_Should_Attach_To_Control() { using (UnitTestApplication.Start(TestServices.RealStyler)) { var border = new Border(); var root = new TestRoot { Styles = { new Styles { new Style(x => x.OfType<Border>()) { Setters = { new Setter(Border.BorderThicknessProperty, new Thickness(4)), } } } }, Child = border, }; root.Measure(Size.Infinity); Assert.Equal(new Thickness(4), border.BorderThickness); ((Styles)root.Styles[0]).Add(new Style(x => x.OfType<Border>()) { Setters = { new Setter(Border.BorderThicknessProperty, new Thickness(6)), } }); root.Measure(Size.Infinity); Assert.Equal(new Thickness(6), border.BorderThickness); } } [Fact] public void Removing_Nested_Style_Should_Detach_From_Control() { using (UnitTestApplication.Start(TestServices.RealStyler)) { var border = new Border(); var root = new TestRoot { Styles = { new Styles { new Style(x => x.OfType<Border>()) { Setters = { new Setter(Border.BorderThicknessProperty, new Thickness(4)), } }, new Style(x => x.OfType<Border>()) { Setters = { new Setter(Border.BorderThicknessProperty, new Thickness(6)), } }, } }, Child = border, }; root.Measure(Size.Infinity); Assert.Equal(new Thickness(6), border.BorderThickness); ((Styles)root.Styles[0]).RemoveAt(1); root.Measure(Size.Infinity); Assert.Equal(new Thickness(4), border.BorderThickness); } } [Fact] public void Should_Set_Owner_On_Assigned_Resources() { var host = new Mock<IResourceHost>(); var target = new Style(); ((IResourceProvider)target).AddOwner(host.Object); var resources = new Mock<IResourceDictionary>(); target.Resources = resources.Object; resources.Verify(x => x.AddOwner(host.Object), Times.Once); } [Fact] public void Should_Set_Owner_On_Assigned_Resources_2() { var host = new Mock<IResourceHost>(); var target = new Style(); var resources = new Mock<IResourceDictionary>(); target.Resources = resources.Object; host.Invocations.Clear(); ((IResourceProvider)target).AddOwner(host.Object); resources.Verify(x => x.AddOwner(host.Object), Times.Once); } private class Class1 : Control { public static readonly StyledProperty<string> FooProperty = AvaloniaProperty.Register<Class1, string>(nameof(Foo), "foodefault"); public static readonly StyledProperty<Class1> ChildProperty = AvaloniaProperty.Register<Class1, Class1>(nameof(Child)); public string Foo { get { return GetValue(FooProperty); } set { SetValue(FooProperty, value); } } public Class1 Child { get => GetValue(ChildProperty); set => SetValue(ChildProperty, value); } protected override Size MeasureOverride(Size availableSize) { throw new NotImplementedException(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // //permutations for (((class_s.a+class_s.b)+class_s.c)+class_s.d) //(((class_s.a+class_s.b)+class_s.c)+class_s.d) //(class_s.d+((class_s.a+class_s.b)+class_s.c)) //((class_s.a+class_s.b)+class_s.c) //(class_s.c+(class_s.a+class_s.b)) //(class_s.a+class_s.b) //(class_s.b+class_s.a) //(class_s.a+class_s.b) //(class_s.b+class_s.a) //(class_s.a+(class_s.b+class_s.c)) //(class_s.b+(class_s.a+class_s.c)) //(class_s.b+class_s.c) //(class_s.a+class_s.c) //((class_s.a+class_s.b)+class_s.c) //(class_s.c+(class_s.a+class_s.b)) //((class_s.a+class_s.b)+(class_s.c+class_s.d)) //(class_s.c+((class_s.a+class_s.b)+class_s.d)) //(class_s.c+class_s.d) //((class_s.a+class_s.b)+class_s.d) //(class_s.a+(class_s.b+class_s.d)) //(class_s.b+(class_s.a+class_s.d)) //(class_s.b+class_s.d) //(class_s.a+class_s.d) //(((class_s.a+class_s.b)+class_s.c)+class_s.d) //(class_s.d+((class_s.a+class_s.b)+class_s.c)) namespace CseTest { using System; public class Test_Main { static int Main() { int ret = 100; class_s s = new class_s(); class_s.a = return_int(false, -51); class_s.b = return_int(false, 86); class_s.c = return_int(false, 89); class_s.d = return_int(false, 56); #if LOOP do { #endif #if TRY try { #endif #if LOOP do { for (int i = 0; i < 10; i++) { #endif int v1 = (((class_s.a + class_s.b) + class_s.c) + class_s.d); int v2 = (class_s.d + ((class_s.a + class_s.b) + class_s.c)); int v3 = ((class_s.a + class_s.b) + class_s.c); int v4 = (class_s.c + (class_s.a + class_s.b)); int v5 = (class_s.a + class_s.b); int v6 = (class_s.b + class_s.a); int v7 = (class_s.a + class_s.b); int v8 = (class_s.b + class_s.a); int v9 = (class_s.a + (class_s.b + class_s.c)); int v10 = (class_s.b + (class_s.a + class_s.c)); int v11 = (class_s.b + class_s.c); int v12 = (class_s.a + class_s.c); int v13 = ((class_s.a + class_s.b) + class_s.c); int v14 = (class_s.c + (class_s.a + class_s.b)); int v15 = ((class_s.a + class_s.b) + (class_s.c + class_s.d)); int v16 = (class_s.c + ((class_s.a + class_s.b) + class_s.d)); int v17 = (class_s.c + class_s.d); int v18 = ((class_s.a + class_s.b) + class_s.d); int v19 = (class_s.a + (class_s.b + class_s.d)); int v20 = (class_s.b + (class_s.a + class_s.d)); int v21 = (class_s.b + class_s.d); int v22 = (class_s.a + class_s.d); int v23 = (((class_s.a + class_s.b) + class_s.c) + class_s.d); int v24 = (class_s.d + ((class_s.a + class_s.b) + class_s.c)); if (v1 != 180) { Console.WriteLine("test0: for (((class_s.a+class_s.b)+class_s.c)+class_s.d) failed actual value {0} ", v1); ret = ret + 1; } if (v2 != 180) { Console.WriteLine("test1: for (class_s.d+((class_s.a+class_s.b)+class_s.c)) failed actual value {0} ", v2); ret = ret + 1; } if (v3 != 124) { Console.WriteLine("test2: for ((class_s.a+class_s.b)+class_s.c) failed actual value {0} ", v3); ret = ret + 1; } if (v4 != 124) { Console.WriteLine("test3: for (class_s.c+(class_s.a+class_s.b)) failed actual value {0} ", v4); ret = ret + 1; } if (v5 != 35) { Console.WriteLine("test4: for (class_s.a+class_s.b) failed actual value {0} ", v5); ret = ret + 1; } if (v6 != 35) { Console.WriteLine("test5: for (class_s.b+class_s.a) failed actual value {0} ", v6); ret = ret + 1; } if (v7 != 35) { Console.WriteLine("test6: for (class_s.a+class_s.b) failed actual value {0} ", v7); ret = ret + 1; } if (v8 != 35) { Console.WriteLine("test7: for (class_s.b+class_s.a) failed actual value {0} ", v8); ret = ret + 1; } if (v9 != 124) { Console.WriteLine("test8: for (class_s.a+(class_s.b+class_s.c)) failed actual value {0} ", v9); ret = ret + 1; } if (v10 != 124) { Console.WriteLine("test9: for (class_s.b+(class_s.a+class_s.c)) failed actual value {0} ", v10); ret = ret + 1; } if (v11 != 175) { Console.WriteLine("test10: for (class_s.b+class_s.c) failed actual value {0} ", v11); ret = ret + 1; } if (v12 != 38) { Console.WriteLine("test11: for (class_s.a+class_s.c) failed actual value {0} ", v12); ret = ret + 1; } if (v13 != 124) { Console.WriteLine("test12: for ((class_s.a+class_s.b)+class_s.c) failed actual value {0} ", v13); ret = ret + 1; } if (v14 != 124) { Console.WriteLine("test13: for (class_s.c+(class_s.a+class_s.b)) failed actual value {0} ", v14); ret = ret + 1; } if (v15 != 180) { Console.WriteLine("test14: for ((class_s.a+class_s.b)+(class_s.c+class_s.d)) failed actual value {0} ", v15); ret = ret + 1; } if (v16 != 180) { Console.WriteLine("test15: for (class_s.c+((class_s.a+class_s.b)+class_s.d)) failed actual value {0} ", v16); ret = ret + 1; } if (v17 != 145) { Console.WriteLine("test16: for (class_s.c+class_s.d) failed actual value {0} ", v17); ret = ret + 1; } if (v18 != 91) { Console.WriteLine("test17: for ((class_s.a+class_s.b)+class_s.d) failed actual value {0} ", v18); ret = ret + 1; } if (v19 != 91) { Console.WriteLine("test18: for (class_s.a+(class_s.b+class_s.d)) failed actual value {0} ", v19); ret = ret + 1; } if (v20 != 91) { Console.WriteLine("test19: for (class_s.b+(class_s.a+class_s.d)) failed actual value {0} ", v20); ret = ret + 1; } if (v21 != 142) { Console.WriteLine("test20: for (class_s.b+class_s.d) failed actual value {0} ", v21); ret = ret + 1; } if (v22 != 5) { Console.WriteLine("test21: for (class_s.a+class_s.d) failed actual value {0} ", v22); ret = ret + 1; } if (v23 != 180) { Console.WriteLine("test22: for (((class_s.a+class_s.b)+class_s.c)+class_s.d) failed actual value {0} ", v23); ret = ret + 1; } if (v24 != 180) { Console.WriteLine("test23: for (class_s.d+((class_s.a+class_s.b)+class_s.c)) failed actual value {0} ", v24); ret = ret + 1; } #if LOOP } } while (ret == 1000); #endif #if TRY } finally { } #endif #if LOOP } while (ret== 1000); #endif Console.WriteLine(ret); return ret; } private static int return_int(bool verbose, int input) { int ans; try { ans = input; } finally { if (verbose) { Console.WriteLine("returning : ans"); } } return ans; } } public class class_s { public static volatile int a; public static volatile int b; public static volatile int c; public static volatile int d; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using BasecampAPI; using System.Diagnostics; using System.IO; namespace Scout { public partial class Form1 : Form { public class LogListener : TextWriterTraceListener { public LogListener(System.IO.FileStream fs) : base(fs) { } public override void WriteLine(string message) { base.WriteLine(string.Format("{0}\t{1}", DateTime.Now.ToString(), message)); } } public Form1() { InitializeComponent(); string[] args = Environment.GetCommandLineArgs(); if (args.Length > 1 && (args[1].ToLower() == "-l" || args[1].ToLower() == "--log")) StartLog(); } private static void StartLog() { string filename = @"scout.log"; if (File.Exists(filename)) { try { File.Delete(filename); } catch { } } System.IO.FileStream log = new System.IO.FileStream(Path.Combine(Application.StartupPath, filename), FileMode.Append); TextWriterTraceListener listener = new LogListener(log); Trace.Listeners.Add(listener); Trace.AutoFlush = true; Trace.WriteLine("-----------------------------------------------------------------"); Trace.WriteLine(String.Format("Scout started up at {0}", DateTime.Now.ToLongDateString())); } private void Form1_Load(object sender, EventArgs e) { ShowLogin(); } private void ShowLogin() { LoginForm form = new LoginForm(); Hide(); if (form.ShowDialog(this) == DialogResult.OK) { ListenForWebEvents(false); Show(); tabs.Visible = true; projects.Visible = true; Basecamp = form.BasecampObject; ListenForWebEvents(true); List<Project> p = new List<Project>(Basecamp.Projects.Values); projects.Items.AddRange(p.ToArray()); if (projects.Items.Count > 0) projects.SelectedIndex = 0; toDoListControl1.ItemEdit += new EventHandler<ToDoListEventArgs>(toDoListControl1_ItemEdit); } else { this.Close(); } } private void ListenForWebEvents(bool listen) { if (Basecamp == null) return; if (listen) { Basecamp.WebCallStarted += new EventHandler(Basecamp_WebCallStarted); Basecamp.WebCallFinished += new EventHandler(Basecamp_WebCallFinished); } else { Basecamp.WebCallStarted -= new EventHandler(Basecamp_WebCallStarted); Basecamp.WebCallFinished -= new EventHandler(Basecamp_WebCallFinished); } } Hourglass hourglass; void StartHourglass() { if (hourglass == null) hourglass = new Hourglass("Contacting Basecamp..."); } void Basecamp_WebCallStarted(object sender, EventArgs e) { StartHourglass(); //new MethodInvoker(StartHourglass).BeginInvoke(null, null); } void Basecamp_WebCallFinished(object sender, EventArgs e) { if (hourglass != null) hourglass.Dispose(); hourglass = null; } void toDoListControl1_ItemEdit(object sender, ToDoListEventArgs e) { new EditToDoItemDialog(CurrentProject, e.Item).ShowDialog(this); Refresh(); } private void tabs_Selected(object sender, TabControlEventArgs e) { switch (e.TabPage.Name) { case "todoTab": RefreshToDos(); break; case "messageTab": RefreshMessages(); break; default: RefreshMilestones(); break; } } private void RefreshMessages() { if (CurrentProject == null) return; comments.Visible = false; messages.Visible = true; messages.BringToFront(); messages.SetProject(CurrentProject); label3.Text = "Tap a message to read comments."; label.Text = "Add a message"; } private void RefreshMilestones() { listMilestones.Items.Clear(); listMilestones.ItemChecked -= new ItemCheckedEventHandler(listMilestones_ItemChecked); Project project = projects.SelectedItem as Project; if (project != null) { List<Milestone> stones = project.GetMilestones(); foreach (Milestone stone in stones) { ListViewItem item = new ListViewItem(new string[] { stone.Title, stone.Deadline.ToShortDateString() }); ListViewGroup group = listMilestones.Groups["groupComingUp"]; if (stone.IsCompleted) { group = listMilestones.Groups["groupCompleted"]; item.Checked = true; item.ForeColor = Color.Green; } else if (stone.Deadline < DateTime.Now) { group = listMilestones.Groups["groupPast"]; item.ForeColor = Color.DarkRed; } item.Group = group; item.Tag = stone; listMilestones.Items.Add(item); } } listMilestones.Columns[0].Width = listMilestones.Width * 3 / 4; listMilestones.Columns[1].AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent); listMilestones.ItemChecked += new ItemCheckedEventHandler(listMilestones_ItemChecked); } private void RefreshToDos() { toDoListControl1.SetListCombo(null); toDoListControl1.SetPeople(People); todoList.Items.Clear(); Project project = projects.SelectedItem as Project; if (project != null) { todoList.Items.AddRange(CurrentProject.ToDoLists.ToArray()); if (todoList.Items.Count > 0) todoList.SelectedIndex = 0; toDoListControl1.SetListCombo(todoList); } } public static Basecamp Basecamp; public static List<Person> People; private void projects_SelectedIndexChanged(object sender, EventArgs e) { RefreshPeople(); switch (tabs.SelectedIndex) { case 0: RefreshMessages(); break; case 1: RefreshToDos(); break; case 2: RefreshMilestones(); break; } } private Project CurrentProject { get { return (projects.SelectedItem as Project); } } private void RefreshPeople() { People = new List<Person>(CurrentProject.People.Values); } private void addItem_Recognition(object sender, Microsoft.Ink.InkEditRecognitionEventArgs e) { if (todoList.SelectedIndex > -1 && todoList.SelectedItem != null) { (todoList.SelectedItem as ToDoList).Add(e.RecognitionResult.ToString()); addItem.Text = String.Empty; } ClearInput(); } private void addMilestone_Recognition(object sender, Microsoft.Ink.InkEditRecognitionEventArgs e) { string title = e.RecognitionResult.ToString(); AddMilestoneDialog dlg = new AddMilestoneDialog(CurrentProject, title); if (DialogResult.OK == dlg.ShowDialog(this)) { HourglassDialog dialog = new HourglassDialog(); dialog.Message = "Creating milestone..."; dialog.Show(); Application.DoEvents(); using (dialog) { CurrentProject.CreateMilestone(title, dlg.Deadline, dlg.Responsible, dlg.Notify); } RefreshMilestones(); } ClearInput(); } private void listMilestones_ItemChecked(object sender, ItemCheckedEventArgs e) { Milestone stone = e.Item.Tag as Milestone; if (stone != null) stone.IsCompleted = e.Item.Checked; RefreshMilestones(); } private Milestone SelectedMilestone { get { if (listMilestones.SelectedItems.Count == 0) return null; return listMilestones.SelectedItems[0].Tag as Milestone; } } private void listMilestones_MouseClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { Milestone stone = SelectedMilestone; if (stone != null) { menuMilestones.Show(listMilestones, e.Location); } } } private void deleteThisMilesoneToolStripMenuItem_Click(object sender, EventArgs e) { Project project = CurrentProject; if (project != null) { project.DeleteMilestone(SelectedMilestone); RefreshMilestones(); } } private void editToolStripMenuItem_Click(object sender, EventArgs e) { Milestone milestone = SelectedMilestone; Project project = CurrentProject; if (project != null && milestone != null) { AddMilestoneDialog dlg = new AddMilestoneDialog(project, null, milestone); if (DialogResult.OK == dlg.ShowDialog(this)) { milestone.Update(milestone.Title, dlg.Deadline, dlg.Responsible, dlg.ShiftOthers, dlg.AvoidWeekends, dlg.Notify); RefreshMilestones(); } } } private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { AddListDialog dlg = new AddListDialog(CurrentProject); if (DialogResult.OK == dlg.ShowDialog(this)) { if (dlg.NewList != null) { todoList.Items.Add(dlg.NewList); todoList.SelectedItem = dlg.NewList; } } } private void settings_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { new SettingsForm().ShowDialog(this); } private void logout_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { ShowLogin(); } private void comments_MessageClicked(object sender, MessageListEventArgs e) { RefreshMessages(); } private void messages_MessageClicked(object sender, MessageListEventArgs e) { ShowComments(e.Message); } private void ShowComments(BasecampAPI.Message message) { messages.Visible = false; comments.BringToFront(); comments.SetMessage(message); comments.Visible = true; label3.Text = "Tap anywhere to go back to the list of messages."; label.Text = "Add a comment"; } private void comments_MouseClick(object sender, MouseEventArgs e) { RefreshMessages(); } private void messages_MouseClick(object sender, MouseEventArgs e) { } private void newMessage_Recognition(object sender, Microsoft.Ink.InkEditRecognitionEventArgs e) { if (messages.Visible) { AddMessageDialog form = new AddMessageDialog(CurrentProject, e.RecognitionResult.ToString()); if (DialogResult.OK == form.ShowDialog(this)) { CurrentProject.AddMessage(form.Title, form.Body, form.Category, form.Filename); RefreshMessages(); } } else if (comments.Message != null) { AddMessageDialog form = new AddMessageDialog(comments.Message, e.RecognitionResult.ToString()); if (DialogResult.OK == form.ShowDialog(this)) { comments.Message.AddComment(form.Body); ShowComments(comments.Message); } } ClearInput(); } private void ClearInput() { // This is totally ghetto. timer = new Timer(); timer.Interval = 1; timer.Tick += new EventHandler(timer_Tick); timer.Enabled = true; } void timer_Tick(object sender, EventArgs e) { newMessage.Text = String.Empty; addItem.Text = String.Empty; addMilestone.Text = String.Empty; timer.Tick -= new EventHandler(timer_Tick); } Timer timer; } class Hourglass : IDisposable { HourglassDialog dlg; public Hourglass() : this(null) { } public Hourglass(string message) { try { if (message != null) { dlg = new HourglassDialog(message); dlg.Show(); Application.DoEvents(); } else if (Form.ActiveForm != null) Form.ActiveForm.Cursor = Cursors.WaitCursor; } catch { } } #region IDisposable Members public void Dispose() { try { if (Form.ActiveForm != null) Form.ActiveForm.Cursor = Cursors.Default; if (dlg != null) dlg.BeginInvoke(new MethodInvoker(dlg.Close)); } catch { } } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using System.Threading; using System.Timers; using log4net; using log4net.Appender; using log4net.Core; using log4net.Repository; using OpenSim.Framework.Console; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Framework.Statistics; using Timer=System.Timers.Timer; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace OpenSim.Framework.Servers { /// <summary> /// Common base for the main OpenSimServers (user, grid, inventory, region, etc) /// </summary> public abstract class BaseOpenSimServer { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// This will control a periodic log printout of the current 'show stats' (if they are active) for this /// server. /// </summary> private Timer m_periodicDiagnosticsTimer = new Timer(60 * 60 * 1000); protected CommandConsole m_console; protected OpenSimAppender m_consoleAppender; protected IAppender m_logFileAppender = null; /// <summary> /// Time at which this server was started /// </summary> protected DateTime m_startuptime; /// <summary> /// Record the initial startup directory for info purposes /// </summary> protected string m_startupDirectory = Environment.CurrentDirectory; /// <summary> /// Server version information. Usually VersionInfo + information about git commit, operating system, etc. /// </summary> protected string m_version; protected string m_pidFile = String.Empty; /// <summary> /// Random uuid for private data /// </summary> protected string m_osSecret = String.Empty; protected BaseHttpServer m_httpServer; public BaseHttpServer HttpServer { get { return m_httpServer; } } /// <summary> /// Holds the non-viewer statistics collection object for this service/server /// </summary> protected IStatsCollector m_stats; public BaseOpenSimServer() { m_startuptime = DateTime.Now; m_version = VersionInfo.Version; // Random uuid for private data m_osSecret = UUID.Random().ToString(); m_periodicDiagnosticsTimer.Elapsed += new ElapsedEventHandler(LogDiagnostics); m_periodicDiagnosticsTimer.Enabled = true; // Add ourselves to thread monitoring. This thread will go on to become the console listening thread Thread.CurrentThread.Name = "ConsoleThread"; ThreadTracker.Add(Thread.CurrentThread); ILoggerRepository repository = LogManager.GetRepository(); IAppender[] appenders = repository.GetAppenders(); foreach (IAppender appender in appenders) { if (appender.Name == "LogFileAppender") { m_logFileAppender = appender; } } } /// <summary> /// Must be overriden by child classes for their own server specific startup behaviour. /// </summary> protected virtual void StartupSpecific() { if (m_console != null) { ILoggerRepository repository = LogManager.GetRepository(); IAppender[] appenders = repository.GetAppenders(); foreach (IAppender appender in appenders) { if (appender.Name == "Console") { m_consoleAppender = (OpenSimAppender)appender; break; } } if (null == m_consoleAppender) { Notice("No appender named Console found (see the log4net config file for this executable)!"); } else { m_consoleAppender.Console = m_console; // If there is no threshold set then the threshold is effectively everything. if (null == m_consoleAppender.Threshold) m_consoleAppender.Threshold = Level.All; Notice(String.Format("Console log level is {0}", m_consoleAppender.Threshold)); } m_console.Commands.AddCommand("base", false, "quit", "quit", "Quit the application", HandleQuit); m_console.Commands.AddCommand("base", false, "shutdown", "shutdown", "Quit the application", HandleQuit); m_console.Commands.AddCommand("base", false, "set log level", "set log level <level>", "Set the console logging level", HandleLogLevel); m_console.Commands.AddCommand("base", false, "show info", "show info", "Show general information", HandleShow); m_console.Commands.AddCommand("base", false, "show stats", "show stats", "Show statistics", HandleShow); m_console.Commands.AddCommand("base", false, "show threads", "show threads", "Show thread status", HandleShow); m_console.Commands.AddCommand("base", false, "show uptime", "show uptime", "Show server uptime", HandleShow); m_console.Commands.AddCommand("base", false, "show version", "show version", "Show server version", HandleShow); } } /// <summary> /// Should be overriden and referenced by descendents if they need to perform extra shutdown processing /// </summary> public virtual void ShutdownSpecific() {} /// <summary> /// Provides a list of help topics that are available. Overriding classes should append their topics to the /// information returned when the base method is called. /// </summary> /// /// <returns> /// A list of strings that represent different help topics on which more information is available /// </returns> protected virtual List<string> GetHelpTopics() { return new List<string>(); } /// <summary> /// Print statistics to the logfile, if they are active /// </summary> protected void LogDiagnostics(object source, ElapsedEventArgs e) { StringBuilder sb = new StringBuilder("DIAGNOSTICS\n\n"); sb.Append(GetUptimeReport()); if (m_stats != null) { sb.Append(m_stats.Report()); } sb.Append(Environment.NewLine); sb.Append(GetThreadsReport()); m_log.Debug(sb); } /// <summary> /// Get a report about the registered threads in this server. /// </summary> protected string GetThreadsReport() { StringBuilder sb = new StringBuilder(); List<Thread> threads = ThreadTracker.GetThreads(); if (threads == null) { sb.Append("Thread tracking is only enabled in DEBUG mode."); } else { sb.Append(threads.Count + " threads are being tracked:" + Environment.NewLine); foreach (Thread t in threads) { if (t.IsAlive) { sb.Append( "ID: " + t.ManagedThreadId + ", Name: " + t.Name + ", Alive: " + t.IsAlive + ", Pri: " + t.Priority + ", State: " + t.ThreadState + Environment.NewLine); } else { try { sb.Append("ID: " + t.ManagedThreadId + ", Name: " + t.Name + ", DEAD" + Environment.NewLine); } catch { sb.Append("THREAD ERROR" + Environment.NewLine); } } } } return sb.ToString(); } /// <summary> /// Return a report about the uptime of this server /// </summary> /// <returns></returns> protected string GetUptimeReport() { StringBuilder sb = new StringBuilder(String.Format("Time now is {0}\n", DateTime.Now)); sb.Append(String.Format("Server has been running since {0}, {1}\n", m_startuptime.DayOfWeek, m_startuptime)); sb.Append(String.Format("That is an elapsed time of {0}\n", DateTime.Now - m_startuptime)); return sb.ToString(); } /// <summary> /// Performs initialisation of the scene, such as loading configuration from disk. /// </summary> public virtual void Startup() { m_log.Info("[STARTUP]: Beginning startup processing"); EnhanceVersionInformation(); m_log.Info("[STARTUP]: Version: " + m_version + "\n"); StartupSpecific(); TimeSpan timeTaken = DateTime.Now - m_startuptime; m_log.InfoFormat("[STARTUP]: Startup took {0}m {1}s", timeTaken.Minutes, timeTaken.Seconds); } /// <summary> /// Should be overriden and referenced by descendents if they need to perform extra shutdown processing /// </summary> public virtual void Shutdown() { ShutdownSpecific(); m_log.Info("[SHUTDOWN]: Shutdown processing on main thread complete. Exiting..."); RemovePIDFile(); Environment.Exit(0); } private void HandleQuit(string module, string[] args) { Shutdown(); } private void HandleLogLevel(string module, string[] cmd) { if (null == m_consoleAppender) { Notice("No appender named Console found (see the log4net config file for this executable)!"); return; } string rawLevel = cmd[3]; ILoggerRepository repository = LogManager.GetRepository(); Level consoleLevel = repository.LevelMap[rawLevel]; if (consoleLevel != null) m_consoleAppender.Threshold = consoleLevel; else Notice( String.Format( "{0} is not a valid logging level. Valid logging levels are ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF", rawLevel)); Notice(String.Format("Console log level is {0}", m_consoleAppender.Threshold)); } /// <summary> /// Show help information /// </summary> /// <param name="helpArgs"></param> protected virtual void ShowHelp(string[] helpArgs) { Notice(""); if (helpArgs.Length == 0) { Notice("set log level [level] - change the console logging level only. For example, off or debug."); Notice("show info - show server information (e.g. startup path)."); if (m_stats != null) Notice("show stats - show statistical information for this server"); Notice("show threads - list tracked threads"); Notice("show uptime - show server startup time and uptime."); Notice("show version - show server version."); Notice(""); return; } } public virtual void HandleShow(string module, string[] cmd) { List<string> args = new List<string>(cmd); args.RemoveAt(0); string[] showParams = args.ToArray(); switch (showParams[0]) { case "info": Notice("Version: " + m_version); Notice("Startup directory: " + m_startupDirectory); break; case "stats": if (m_stats != null) Notice(m_stats.Report()); break; case "threads": Notice(GetThreadsReport()); break; case "uptime": Notice(GetUptimeReport()); break; case "version": Notice( String.Format( "Version: {0} (interface version {1})", m_version, VersionInfo.MajorInterfaceVersion)); break; } } /// <summary> /// Console output is only possible if a console has been established. /// That is something that cannot be determined within this class. So /// all attempts to use the console MUST be verified. /// </summary> protected void Notice(string msg) { if (m_console != null) { m_console.Output(msg); } } /// <summary> /// Enhance the version string with extra information if it's available. /// </summary> protected void EnhanceVersionInformation() { string buildVersion = string.Empty; // Add commit hash and date information if available // The commit hash and date are stored in a file bin/.version // This file can automatically created by a post // commit script in the opensim git master repository or // by issuing the follwoing command from the top level // directory of the opensim repository // git log -n 1 --pretty="format:%h: %ci" >bin/.version // For the full git commit hash use %H instead of %h // // The subversion information is deprecated and will be removed at a later date // Add subversion revision information if available // Try file "svn_revision" in the current directory first, then the .svn info. // This allows to make the revision available in simulators not running from the source tree. // FIXME: Making an assumption about the directory we're currently in - we do this all over the place // elsewhere as well string svnRevisionFileName = "svn_revision"; string svnFileName = ".svn/entries"; string gitCommitFileName = ".version"; string inputLine; int strcmp; if (File.Exists(gitCommitFileName)) { StreamReader CommitFile = File.OpenText(gitCommitFileName); buildVersion = Environment.NewLine + "git# " + CommitFile.ReadLine(); CommitFile.Close(); m_version += buildVersion ?? ""; } // Remove the else logic when subversion mirror is no longer used else { if (File.Exists(svnRevisionFileName)) { StreamReader RevisionFile = File.OpenText(svnRevisionFileName); buildVersion = RevisionFile.ReadLine(); buildVersion.Trim(); RevisionFile.Close(); } if (string.IsNullOrEmpty(buildVersion) && File.Exists(svnFileName)) { StreamReader EntriesFile = File.OpenText(svnFileName); inputLine = EntriesFile.ReadLine(); while (inputLine != null) { // using the dir svn revision at the top of entries file strcmp = String.Compare(inputLine, "dir"); if (strcmp == 0) { buildVersion = EntriesFile.ReadLine(); break; } else { inputLine = EntriesFile.ReadLine(); } } EntriesFile.Close(); } m_version += string.IsNullOrEmpty(buildVersion) ? " " : ("." + buildVersion + " ").Substring(0, 6); } } protected void CreatePIDFile(string path) { try { string pidstring = System.Diagnostics.Process.GetCurrentProcess().Id.ToString(); FileStream fs = File.Create(path); System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); Byte[] buf = enc.GetBytes(pidstring); fs.Write(buf, 0, buf.Length); fs.Close(); m_pidFile = path; } catch (Exception) { } } public string osSecret { // Secret uuid for the simulator get { return m_osSecret; } } public string StatReport(OSHttpRequest httpRequest) { // If we catch a request for "callback", wrap the response in the value for jsonp if (httpRequest.Query.ContainsKey("callback")) { return httpRequest.Query["callback"].ToString() + "(" + m_stats.XReport((DateTime.Now - m_startuptime).ToString() , m_version) + ");"; } else { return m_stats.XReport((DateTime.Now - m_startuptime).ToString() , m_version); } } protected void RemovePIDFile() { if (m_pidFile != String.Empty) { try { File.Delete(m_pidFile); m_pidFile = String.Empty; } catch (Exception) { } } } } }
using System.Collections.Generic; using NUnit.Framework; using StructureMap.Pipeline; using System.Linq; namespace StructureMap.Testing.Configuration.DSL { [TestFixture] public class InjectArrayTester { #region Setup/Teardown [SetUp] public void SetUp() { } #endregion public class Processor { private readonly IHandler[] _handlers; private readonly string _name; public Processor(IHandler[] handlers, string name) { _handlers = handlers; _name = name; } public IHandler[] Handlers { get { return _handlers; } } public string Name { get { return _name; } } } public class ProcessorWithList { private readonly IList<IHandler> _handlers; private readonly string _name; public ProcessorWithList(IList<IHandler> handlers, string name) { _handlers = handlers; _name = name; } public IList<IHandler> Handlers { get { return _handlers; } } public string Name { get { return _name; } } } public class Processor2 { private readonly IHandler[] _first; private readonly IHandler[] _second; public Processor2(IHandler[] first, IHandler[] second) { _first = first; _second = second; } public IHandler[] First { get { return _first; } } public IHandler[] Second { get { return _second; } } } public interface IHandler { } public class Handler1 : IHandler { } public class Handler2 : IHandler { } public class Handler3 : IHandler { } [Test] public void CanStillAddOtherPropertiesAfterTheCallToChildArray() { var container = new Container(x => { x.For<Processor>().Use<Processor>() .EnumerableOf<IHandler>().Contains( new SmartInstance<Handler1>(), new SmartInstance<Handler2>(), new SmartInstance<Handler3>() ) .Ctor<string>("name").Is("Jeremy"); }); container.GetInstance<Processor>().Name.ShouldEqual("Jeremy"); } [Test] public void get_a_configured_list() { var container = new Container(x => { x.For<Processor>().Use<Processor>() .EnumerableOf<IHandler>().Contains( new SmartInstance<Handler1>(), new SmartInstance<Handler2>(), new SmartInstance<Handler3>() ) .Ctor<string>("name").Is("Jeremy"); }); container.GetInstance<Processor>().Handlers.Select(x => x.GetType()).ShouldHaveTheSameElementsAs(typeof(Handler1), typeof(Handler2), typeof(Handler3)); } [Test] public void InjectPropertiesByName() { var container = new Container(r => { r.For<Processor2>().Use<Processor2>() .EnumerableOf<IHandler>("first").Contains(x => { x.Type<Handler1>(); x.Type<Handler2>(); }) .EnumerableOf<IHandler>("second").Contains(x => { x.Type<Handler2>(); x.Type<Handler3>(); }); }); var processor = container.GetInstance<Processor2>(); processor.First[0].ShouldBeOfType<Handler1>(); processor.First[1].ShouldBeOfType<Handler2>(); processor.Second[0].ShouldBeOfType<Handler2>(); processor.Second[1].ShouldBeOfType<Handler3>(); } [Test] public void inline_definition_of_enumerable_child_respects_order_of_registration() { IContainer container = new Container(r => { r.For<IHandler>().Add<Handler1>().Named("One"); r.For<IHandler>().Add<Handler2>().Named("Two"); r.For<Processor>().Use<Processor>() .Ctor<string>("name").Is("Jeremy") .EnumerableOf<IHandler>().Contains(x => { x.TheInstanceNamed("Two"); x.TheInstanceNamed("One"); }); }); var processor = container.GetInstance<Processor>(); processor.Handlers[0].ShouldBeOfType<Handler2>(); processor.Handlers[1].ShouldBeOfType<Handler1>(); } [Test] public void PlaceMemberInArrayByReference_with_SmartInstance() { IContainer manager = new Container(registry => { registry.For<IHandler>().Add<Handler1>().Named("One"); registry.For<IHandler>().Add<Handler2>().Named("Two"); registry.For<Processor>().Use<Processor>() .Ctor<string>("name").Is("Jeremy") .EnumerableOf<IHandler>().Contains(x => { x.TheInstanceNamed("Two"); x.TheInstanceNamed("One"); }); }); var processor = manager.GetInstance<Processor>(); processor.Handlers[0].ShouldBeOfType<Handler2>(); processor.Handlers[1].ShouldBeOfType<Handler1>(); } [Test] public void ProgrammaticallyInjectArrayAllInline() { var container = new Container(x => { x.For<Processor>().Use<Processor>() .Ctor<string>("name").Is("Jeremy") .EnumerableOf<IHandler>().Contains(y => { y.Type<Handler1>(); y.Type<Handler2>(); y.Type<Handler3>(); }); }); var processor = container.GetInstance<Processor>(); processor.Handlers[0].ShouldBeOfType<Handler1>(); processor.Handlers[1].ShouldBeOfType<Handler2>(); processor.Handlers[2].ShouldBeOfType<Handler3>(); } [Test] public void ProgrammaticallyInjectArrayAllInline_with_smart_instance() { IContainer container = new Container(r => { r.For<Processor>().Use<Processor>() .Ctor<string>("name").Is("Jeremy") .EnumerableOf<IHandler>().Contains(x => { x.Type<Handler1>(); x.Type<Handler2>(); x.Type<Handler3>(); }); }); var processor = container.GetInstance<Processor>(); processor.Handlers[0].ShouldBeOfType<Handler1>(); processor.Handlers[1].ShouldBeOfType<Handler2>(); processor.Handlers[2].ShouldBeOfType<Handler3>(); } } }
using System; using System.IO; using System.Text; using System.Collections.Generic; using GraphToDSCompiler; using ProtoCore.DSASM.Mirror; using System.Diagnostics; using ProtoCore.Utils; using System.ComponentModel; using System.Threading; using ProtoFFI; using ProtoCore.AssociativeGraph; using ProtoCore.AST.AssociativeAST; using ProtoCore.Mirror; namespace ProtoScript.Runners { public enum EventStatus { OK, Error, Warning } public struct Subtree { public Guid GUID; public List<AssociativeNode> AstNodes; public Subtree(List<AssociativeNode> astNodes) { GUID = Guid.Empty; AstNodes = astNodes; } } public class GraphSyncData { public List<Subtree> DeletedSubtrees { get; private set; } public List<Subtree> AddedSubtrees { get; private set; } public List<Subtree> ModifiedSubtrees { get; private set; } public GraphSyncData(List<Subtree> deleted, List<Subtree> added, List<Subtree> modified) { DeletedSubtrees = deleted; AddedSubtrees = added; ModifiedSubtrees = modified; } } public interface ILiveRunner { void UpdateGraph(GraphToDSCompiler.SynchronizeData syncData); void BeginUpdateGraph(GraphToDSCompiler.SynchronizeData syncData); void BeginConvertNodesToCode(List<SnapshotNode> snapshotNodes); void UpdateGraph(GraphSyncData syncData); void BeginUpdateGraph(GraphSyncData syncData); void BeginConvertNodesToCode(List<Subtree> subtrees); void BeginQueryNodeValue(uint nodeId); void UpdateCmdLineInterpreter(string code); ProtoCore.Mirror.RuntimeMirror QueryNodeValue(uint nodeId); ProtoCore.Mirror.RuntimeMirror QueryNodeValue(string nodeName); ProtoCore.Mirror.RuntimeMirror InspectNodeValue(string nodeName); void BeginQueryNodeValue(List<uint> nodeIds); string GetCoreDump(); void BeginQueryNodeValue(Guid nodeGuid); ProtoCore.Mirror.RuntimeMirror QueryNodeValue(Guid nodeId); void BeginQueryNodeValue(List<Guid> nodeGuid); event NodeValueReadyEventHandler NodeValueReady; event GraphUpdateReadyEventHandler GraphUpdateReady; event NodesToCodeCompletedEventHandler NodesToCodeCompleted; event DynamoNodeValueReadyEventHandler DynamoNodeValueReady; event DynamoGraphUpdateReadyEventHandler DynamoGraphUpdateReady; } public partial class LiveRunner : ILiveRunner { /// <summary> /// These are configuration parameters passed by host application to be consumed by geometry library and persistent manager implementation. /// </summary> public class Options { /// <summary> /// The configuration parameters that needs to be passed to /// different applications. /// </summary> public Dictionary<string, object> PassThroughConfiguration; /// <summary> /// The path of the root graph/module /// </summary> public string RootModulePathName; /// <summary> /// List of search directories to resolve any file reference /// </summary> public List<string> SearchDirectories; /// <summary> /// If the Interpreter mode is true, the LiveRunner takes in code statements as input strings /// and not SyncData /// </summary> public bool InterpreterMode = false; } private Dictionary<uint, string> GetModifiedGuidList() { // Retrieve the actual modified nodes // Execution is complete, get all the modified guids // Get the modified symbol names from the VM List<string> modifiedNames = this.runnerCore.Rmem.GetModifiedSymbolString(); Dictionary<uint, string> modfiedGuidList = new Dictionary<uint, string>(); foreach (string name in modifiedNames) { // Get the uid of the modified symbol if (this.graphCompiler.mapModifiedName.ContainsKey(name)) { uint id = this.graphCompiler.mapModifiedName[name]; if (!modfiedGuidList.ContainsKey(id)) { // Append the modified guid into the modified list modfiedGuidList.Add(this.graphCompiler.mapModifiedName[name], name); } } } return modfiedGuidList; } private void ResetModifiedSymbols() { this.runnerCore.Rmem.ResetModifedSymbols(); } private SynchronizeData CreateSynchronizeDataForGuidList(Dictionary<uint, string> modfiedGuidList) { Dictionary<uint, SnapshotNode> modifiedGuids = new Dictionary<uint, SnapshotNode>(); SynchronizeData syncDataReturn = new SynchronizeData(); if (modfiedGuidList != null) { //foreach (uint guid in modfiedGuidList) foreach (var kvp in modfiedGuidList) { // Get the uid recognized by the graphIDE uint guid = kvp.Key; string name = kvp.Value; SnapshotNode sNode = new SnapshotNode(this.graphCompiler.GetRealUID(guid), SnapshotNodeType.Identifier, name); if (!modifiedGuids.ContainsKey(sNode.Id)) { modifiedGuids.Add(sNode.Id, sNode); } } foreach (KeyValuePair<uint, SnapshotNode> kvp in modifiedGuids) syncDataReturn.ModifiedNodes.Add(kvp.Value); } return syncDataReturn; } private ProtoScriptTestRunner runner; private ProtoRunner.ProtoVMState vmState; private GraphToDSCompiler.GraphCompiler graphCompiler; private ProtoCore.Core runnerCore = null; private ProtoCore.Options coreOptions = null; private Options executionOptions = null; private bool syncCoreConfigurations = false; private int deltaSymbols = 0; private ProtoCore.CompileTime.Context staticContext = null; private readonly Object operationsMutex = new object(); private Queue<Task> taskQueue; private Thread workerThread; public LiveRunner() { InitRunner(new Options()); } public LiveRunner(Options options) { InitRunner(options); } public GraphToDSCompiler.GraphCompiler GetCurrentGraphCompilerInstance() { return graphCompiler; } private void InitRunner(Options options) { graphCompiler = GraphToDSCompiler.GraphCompiler.CreateInstance(); graphCompiler.SetCore(GraphUtilities.GetCore()); runner = new ProtoScriptTestRunner(); executionOptions = options; InitOptions(); InitCore(); taskQueue = new Queue<Task>(); workerThread = new Thread(new ThreadStart(TaskExecMethod)); workerThread.IsBackground = true; workerThread.Start(); staticContext = new ProtoCore.CompileTime.Context(); } private void InitOptions() { // Build the options required by the core Validity.Assert(coreOptions == null); coreOptions = new ProtoCore.Options(); coreOptions.GenerateExprID = true; coreOptions.IsDeltaExecution = true; coreOptions.BuildOptErrorAsWarning = true; coreOptions.WebRunner = false; coreOptions.ExecutionMode = ProtoCore.ExecutionMode.Serial; //coreOptions.DumpByteCode = true; //coreOptions.Verbose = true; // This should have been set in the consturctor Validity.Assert(executionOptions != null); } private void InitCore() { Validity.Assert(coreOptions != null); // Comment Jun: // It must be guaranteed that in delta exeuction, expression id's must not be autogerated // expression Id's must be propagated from the graphcompiler to the DS codegenerators //Validity.Assert(coreOptions.IsDeltaExecution && !coreOptions.GenerateExprID); runnerCore = new ProtoCore.Core(coreOptions); SyncCoreConfigurations(runnerCore, executionOptions); runnerCore.Executives.Add(ProtoCore.Language.kAssociative, new ProtoAssociative.Executive(runnerCore)); runnerCore.Executives.Add(ProtoCore.Language.kImperative, new ProtoImperative.Executive(runnerCore)); runnerCore.FFIPropertyChangedMonitor.FFIPropertyChangedEventHandler += FFIPropertyChanged; vmState = null; } private void FFIPropertyChanged(FFIPropertyChangedEventArgs arg) { lock (taskQueue) { taskQueue.Enqueue(new PropertyChangedTask(this, arg.hostGraphNode)); } } private static void SyncCoreConfigurations(ProtoCore.Core core, Options options) { if (null == options) return; //update the root module path name, if set. if (!string.IsNullOrEmpty(options.RootModulePathName)) core.Options.RootModulePathName = options.RootModulePathName; //then update the search path, if set. if (null != options.SearchDirectories) core.Options.IncludeDirectories = options.SearchDirectories; //Finally update the pass thru configuration values if (null == options.PassThroughConfiguration) return; foreach (var item in options.PassThroughConfiguration) { core.Configurations[item.Key] = item.Value; } } public void SetOptions(Options options) { executionOptions = options; syncCoreConfigurations = true; //request syncing the configuration } #region Public Live Runner Events public event NodeValueReadyEventHandler NodeValueReady = null; public event GraphUpdateReadyEventHandler GraphUpdateReady = null; public event NodesToCodeCompletedEventHandler NodesToCodeCompleted = null; public event DynamoNodeValueReadyEventHandler DynamoNodeValueReady = null; public event DynamoGraphUpdateReadyEventHandler DynamoGraphUpdateReady = null; #endregion /// <summary> /// Push new synchronization data, returns immediately and will /// trigger a GraphUpdateReady when the value when the execution /// is completed /// </summary> /// <param name="syncData"></param> public void BeginUpdateGraph(SynchronizeData syncData) { lock (taskQueue) { taskQueue.Enqueue( new UpdateGraphTask(syncData, this)); } //Todo(Luke) add a Monitor queue to prevent having to have the //work poll } public void BeginUpdateGraph(GraphSyncData syncData) { lock (taskQueue) { taskQueue.Enqueue(new DynamoUpdateGraphTask(syncData, this)); } } /// <summary> /// Async call from command-line interpreter to LiveRunner /// </summary> /// <param name="cmdLineString"></param> public void BeginUpdateCmdLineInterpreter(string cmdLineString) { lock (taskQueue) { taskQueue.Enqueue( new UpdateCmdLineInterpreterTask(cmdLineString, this)); } } /// <summary> /// Takes in a list of SnapshotNode objects, condensing them into one /// or more SnapshotNode objects which caller can then turn into a more /// compact representation of the former SnapshotNode objects. /// </summary> /// <param name="snapshotNodes">A list of source SnapshotNode objects /// from which the resulting list of SnapshotNode is to be computed. /// </param> public void BeginConvertNodesToCode(List<SnapshotNode> snapshotNodes) { if (null == snapshotNodes || (snapshotNodes.Count <= 0)) return; // Do nothing, there's no nodes to be converted. lock (taskQueue) { taskQueue.Enqueue( new ConvertNodesToCodeTask(snapshotNodes, this)); } } public void BeginConvertNodesToCode(List<Subtree> subtrees) { if (null == subtrees || (subtrees.Count <= 0)) return; // Do nothing, there's no nodes to be converted. lock (taskQueue) { taskQueue.Enqueue(new DynamoConvertNodesToCodeTask(subtrees, this)); } } /// <summary> /// Query For a node value this will trigger a NodeValueReady callback /// when the value is available /// </summary> /// <param name="nodeId"></param> public void BeginQueryNodeValue(uint nodeId) { lock (taskQueue) { taskQueue.Enqueue( new NodeValueRequestTask(nodeId, this)); } } /// <summary> /// Query For a node value this will trigger a NodeValueReady callback /// when the value is available /// This version is more efficent than calling the BeginQueryNodeValue(uint) /// repeatedly /// </summary> /// <param name="nodeId"></param> public void BeginQueryNodeValue(List<uint> nodeIds) { lock (taskQueue) { foreach (uint nodeId in nodeIds) { taskQueue.Enqueue( new NodeValueRequestTask(nodeId, this)); } } } public void BeginQueryNodeValue(Guid nodeGuid) { lock (taskQueue) { taskQueue.Enqueue(new DynamoNodeValueRequestTask(nodeGuid, this)); } } public void BeginQueryNodeValue(List<Guid> nodeGuids) { lock (taskQueue) { foreach (Guid nodeGuid in nodeGuids) { taskQueue.Enqueue( new DynamoNodeValueRequestTask(nodeGuid, this)); } } } /// <summary> /// TODO: Deprecate - This will be replaced with the overload that takes in a Guid type /// Query for a node value. This will block until the value is available. /// This uses the expression interpreter to evaluate a node variable's value. /// It will only serviced when all ASync calls have been completed /// </summary> /// <param name="nodeId"></param> /// <returns></returns> public ProtoCore.Mirror.RuntimeMirror QueryNodeValue(uint nodeId) { while (true) { lock (taskQueue) { //Spin waiting for the queue to be empty if (taskQueue.Count == 0) { //No entries and we have the lock //Synchronous query to get the node return InternalGetNodeValue(nodeId); } } Thread.Sleep(0); } } /// <summary> /// Query for a node value given its UID. This will block until the value is available. /// This uses the expression interpreter to evaluate a node variable's value. /// It will only serviced when all ASync calls have been completed /// </summary> /// <param name="nodeId"></param> /// <returns></returns> public ProtoCore.Mirror.RuntimeMirror QueryNodeValue(Guid nodeGuid) { while (true) { lock (taskQueue) { //Spin waiting for the queue to be empty if (taskQueue.Count == 0) { //No entries and we have the lock //Synchronous query to get the node return InternalGetNodeValue(nodeGuid); } } Thread.Sleep(0); } } /// <summary> /// Query for a node value given its variable name. This will block until the value is available. /// This uses the expression interpreter to evaluate a node variable's value. /// It will only serviced when all ASync calls have been completed /// </summary> /// <param name="nodeId"></param> /// <returns></returns> public ProtoCore.Mirror.RuntimeMirror QueryNodeValue(string nodeName) { while (true) { lock (taskQueue) { //Spin waiting for the queue to be empty if (taskQueue.Count == 0) { //No entries and we have the lock //Synchronous query to get the node return InternalGetNodeValue(nodeName); } } Thread.Sleep(0); } } /// <summary> /// Inspects the VM for the value of a node given its variable name. /// As opposed to QueryNodeValue, this does not use the Expression Interpreter /// This will block until the value is available. /// It will only serviced when all ASync calls have been completed /// </summary> /// <param name="nodeId"></param> /// <returns></returns> public ProtoCore.Mirror.RuntimeMirror InspectNodeValue(string nodeName) { while (true) { lock (taskQueue) { //Spin waiting for the queue to be empty if (taskQueue.Count == 0) { //No entries and we have the lock //Synchronous query to get the node // Comment Jun: all symbols are in the global block as there is no notion of scoping the the graphUI yet. const int blockID = 0; ProtoCore.Mirror.RuntimeMirror runtimeMirror = ProtoCore.Mirror.Reflection.Reflect(nodeName, blockID, runnerCore); return runtimeMirror; } } Thread.Sleep(0); } } /// <summary> /// VM Debugging API for general Debugging purposes /// temporarily used by Cmmand Line REPL /// </summary> /// <returns></returns> public string GetCoreDump() { // Prints out the final Value of every symbol in the program // Traverse order: // Exelist, Globals symbols StringBuilder globaltrace = null; ProtoCore.DSASM.Executive exec = runnerCore.CurrentExecutive.CurrentDSASMExec; ProtoCore.DSASM.Mirror.ExecutionMirror execMirror = new ProtoCore.DSASM.Mirror.ExecutionMirror(exec, runnerCore); ProtoCore.DSASM.Executable exe = exec.rmem.Executable; // Only display symbols defined in the default top-most langauge block; // Otherwise garbage information may be displayed. string formattedString = string.Empty; if (exe.runtimeSymbols.Length > 0) { int blockId = 0; ProtoCore.DSASM.SymbolTable symbolTable = exe.runtimeSymbols[blockId]; for (int i = 0; i < symbolTable.symbolList.Count; ++i) { //int n = symbolTable.symbolList.Count - 1; //formatParams.ResetOutputDepth(); ProtoCore.DSASM.SymbolNode symbolNode = symbolTable.symbolList[i]; bool isLocal = ProtoCore.DSASM.Constants.kGlobalScope != symbolNode.functionIndex; bool isStatic = (symbolNode.classScope != ProtoCore.DSASM.Constants.kInvalidIndex && symbolNode.isStatic); if (symbolNode.isArgument || isLocal || isStatic || symbolNode.isTemp) { // These have gone out of scope, their values no longer exist //return ((null == globaltrace) ? string.Empty : globaltrace.ToString()); continue; } ProtoCore.Runtime.RuntimeMemory rmem = exec.rmem; ProtoCore.DSASM.StackValue sv = rmem.GetStackData(blockId, i, ProtoCore.DSASM.Constants.kGlobalScope); formattedString = formattedString + string.Format("{0} = {1}\n", symbolNode.name, execMirror.GetStringValue(sv, rmem.Heap, blockId)); //if (null != globaltrace) //{ // int maxLength = 1020; // while (formattedString.Length > maxLength) // { // globaltrace.AppendLine(formattedString.Substring(0, maxLength)); // formattedString = formattedString.Remove(0, maxLength); // } // globaltrace.AppendLine(formattedString); //} } //formatParams.ResetOutputDepth(); } //return ((null == globaltrace) ? string.Empty : globaltrace.ToString()); return formattedString; } public void UpdateGraph(SynchronizeData syndData) { while (true) { lock (taskQueue) { //Spin waiting for the queue to be empty if (taskQueue.Count == 0) { string code = null; SynchronizeInternal(syndData, out code); return; } } Thread.Sleep(0); } } /// <summary> /// This API needs to be called for every delta AST execution /// </summary> /// <param name="syncData"></param> public void UpdateGraph(GraphSyncData syncData) { while (true) { lock (taskQueue) { if (taskQueue.Count == 0) { string code = null; runnerCore.Options.IsDeltaCompile = true; SynchronizeInternal(syncData, out code); return; } } } } /// <summary> /// This api needs to be called by a command line REPL for each DS command/expression entered to be executed /// </summary> /// <param name="code"></param> public void UpdateCmdLineInterpreter(string code) { while (true) { lock (taskQueue) { //Spin waiting for the queue to be empty if (taskQueue.Count == 0) { runnerCore.Options.IsDeltaCompile = true; SynchronizeInternal(code); return; } } Thread.Sleep(0); } } //Secondary thread private void TaskExecMethod() { while (true) { Task task = null; lock (taskQueue) { if (taskQueue.Count > 0) task = taskQueue.Dequeue(); } if (task != null) { task.Execute(); continue; } Thread.Sleep(50); } } #region Internal Implementation private ProtoCore.Mirror.RuntimeMirror InternalGetNodeValue(string varname) { Validity.Assert(null != vmState); // Comment Jun: all symbols are in the global block as there is no notion of scoping the the graphUI yet. const int blockID = 0; return vmState.LookupName(varname, blockID); } private ProtoCore.Mirror.RuntimeMirror InternalGetNodeValue(uint nodeId) { //ProtoCore.DSASM.Constants.kInvalidIndex tells the UpdateUIDForCodeblock to look for the lastindex for given codeblock nodeId = graphCompiler.UpdateUIDForCodeblock(nodeId, ProtoCore.DSASM.Constants.kInvalidIndex); Validity.Assert(null != vmState); string varname = graphCompiler.GetVarName(nodeId); if (string.IsNullOrEmpty(varname)) { return null; } return InternalGetNodeValue(varname); } private ProtoCore.Mirror.RuntimeMirror InternalGetNodeValue(Guid nodeGuid) { throw new NotImplementedException(); } private bool Compile(string code, out int blockId) { //ProtoCore.CompileTime.Context staticContext = new ProtoCore.CompileTime.Context(code, new Dictionary<string, object>(), graphCompiler.ExecutionFlagList); staticContext.SetData(code, new Dictionary<string, object>(), graphCompiler.ExecutionFlagList); bool succeeded = runner.Compile(staticContext, runnerCore, out blockId); if (succeeded) { // Regenerate the DS executable runnerCore.GenerateExecutable(); // Update the symbol tables // TODO Jun: Expand to accomoadate the list of symbols staticContext.symbolTable = runnerCore.DSExecutable.runtimeSymbols[0]; } return succeeded; } private ProtoRunner.ProtoVMState Execute() { // runnerCore.GlobOffset is the number of global symbols that need to be allocated on the stack // The argument to Reallocate is the number of ONLY THE NEW global symbols as the stack needs to accomodate this delta int newSymbols = runnerCore.GlobOffset - deltaSymbols; // If there are lesser symbols to allocate for this run, then it means nodes were deleted. // TODO Jun: Determine if it is safe to just leave them in the global stack // as no symbols point to this memory location in the stack anyway if (newSymbols >= 0) { runnerCore.Rmem.ReAllocateMemory(newSymbols); } // Store the current number of global symbols deltaSymbols = runnerCore.GlobOffset; // Initialize the runtime context and pass it the execution delta list from the graph compiler ProtoCore.Runtime.Context runtimeContext = new ProtoCore.Runtime.Context(); runtimeContext.execFlagList = graphCompiler.ExecutionFlagList; runner.Execute(runnerCore, runtimeContext); // ExecutionMirror mirror = new ExecutionMirror(runnerCore.CurrentExecutive.CurrentDSASMExec, runnerCore); return new ProtoRunner.ProtoVMState(runnerCore); } private bool CompileAndExecute(string code) { // TODO Jun: Revisit all the Compile functions and remove the blockId out argument int blockId = ProtoCore.DSASM.Constants.kInvalidIndex; bool succeeded = Compile(code, out blockId); if (succeeded) { runnerCore.RunningBlock = blockId; vmState = Execute(); } return succeeded; } private void ResetVMForExecution() { runnerCore.ResetForExecution(); } private void ResetVMForDeltaExecution() { runnerCore.ResetForDeltaExecution(); } /// <summary> /// Resets few states in the core to prepare the core for a new /// delta code compilation and execution /// </summary> private void ResetForDeltaASTExecution() { runnerCore.ResetForDeltaASTExecution(); } /// <summary> /// This function resets properties in LiveRunner core and compileStateTracker required in preparation for a subsequent run /// </summary> private void RetainVMStatesForDeltaExecution() { runnerCore.CompleteCodeBlockList.Clear(); } private void CompileAndExecuteForDeltaExecution(string code) { if (coreOptions.Verbose) { System.Diagnostics.Debug.WriteLine("SyncInternal => " + code); } ResetForDeltaASTExecution(); bool succeeded = CompileAndExecute(code); if (succeeded) { RetainVMStatesForDeltaExecution(); } } private void SynchronizeInternal(GraphSyncData syncData, out string code) { code = string.Empty; if (syncData == null) { ResetForDeltaASTExecution(); return; } if (syncData.AddedSubtrees != null) { foreach (var st in syncData.AddedSubtrees) { Validity.Assert(st.AstNodes != null && st.AstNodes.Count > 0); ProtoCore.CodeGenDS codeGen = new ProtoCore.CodeGenDS(st.AstNodes); code += codeGen.GenerateCode(); } } if (syncData.DeletedSubtrees != null) { foreach (var st in syncData.DeletedSubtrees) { Validity.Assert(st.AstNodes != null && st.AstNodes.Count > 0); List<ProtoCore.AST.AssociativeAST.AssociativeNode> astNodeList = new List<AssociativeNode>(); foreach (var node in st.AstNodes) { if (node is BinaryExpressionNode) { (node as BinaryExpressionNode).RightNode = new NullNode(); astNodeList.Add(node); } } ProtoCore.CodeGenDS codeGen = new ProtoCore.CodeGenDS(astNodeList); code += codeGen.GenerateCode(); } } if (syncData.ModifiedSubtrees != null) { foreach (var st in syncData.ModifiedSubtrees) { Validity.Assert(st.AstNodes != null && st.AstNodes.Count > 0); ProtoCore.CodeGenDS codeGen = new ProtoCore.CodeGenDS(st.AstNodes); code += codeGen.GenerateCode(); } } CompileAndExecuteForDeltaExecution(code); } private void SynchronizeInternal(GraphToDSCompiler.SynchronizeData syncData, out string code) { Validity.Assert(null != runner); Validity.Assert(null != graphCompiler); if (syncData.AddedNodes.Count == 0 && syncData.ModifiedNodes.Count == 0 && syncData.RemovedNodes.Count == 0) { code = ""; ResetVMForDeltaExecution(); return; } else { System.Diagnostics.Debug.WriteLine("Begin SyncInternal: {0}", syncData); GraphToDSCompiler.GraphBuilder g = new GraphBuilder(syncData, graphCompiler); code = g.BuildGraphDAG(); System.Diagnostics.Debug.WriteLine("SyncInternal => " + code); //List<string> deletedVars = new List<string>(); ResetVMForDeltaExecution(); //Synchronize the core configuration before compilation and execution. if (syncCoreConfigurations) { SyncCoreConfigurations(runnerCore, executionOptions); syncCoreConfigurations = false; } bool succeeded = CompileAndExecute(code); if (succeeded) { graphCompiler.ResetPropertiesForNextExecution(); } } } private void SynchronizeInternal(string code) { if (string.IsNullOrEmpty(code)) { code = ""; ResetForDeltaASTExecution(); return; } else { CompileAndExecuteForDeltaExecution(code); } } #endregion } }
// Created by Paul Gonzalez Becerra using System; using System.Runtime.InteropServices; using Saserdote.Mathematics.Collision; namespace Saserdote.Mathematics { [StructLayout(LayoutKind.Sequential)] public struct Point3f { #region --- Field Variables --- // Variables public float x; public float y; public float z; public readonly static Point3f ORIGIN= new Point3f(0f); #endregion // Field Variables #region --- Constructors --- public Point3f(float pmX, float pmY, float pmZ) { x= pmX; y= pmY; z= pmZ; } internal Point3f(float all):this(all, all, all) {} #endregion // Constructors #region --- Methods --- // Converts the point into an integer point public Point3i toPoint3i() { return new Point3i((int)x, (int)y, (int)z); } // Converts the 3d point into a 2d point public Point2f toPoint2f() { return new Point2f(x, y); } // Converts the 3d point into a 2d point public Point2i toPoint2i() { return new Point2i((int)x, (int)y); } // Converts the point into a vector public Vector3 toVector3() { return new Vector3(x, y, z); } // Converts the point into a vector public Vector2 toVector2() { return new Vector2(x, y); } // Adds the point with the vector to get another point public Point3f add(Vector3 vec) { return new Point3f(x+vec.x, y+vec.y, z+vec.z); } // Adds the point with the vector to get another point public Point3f add(Vector2 vec) { return new Point3f(x+vec.x, y+vec.y, z); } // Adds the point with a size to get another point public Point3f add(Size3f size) { return new Point3f(x+size.width, y+size.height, z+size.depth); } // Adds the point with a size to get another point public Point3f add(Size3i size) { return new Point3f(x+(float)size.width, y+(float)size.height, z+(float)size.depth); } // Adds the point with a size to get another point public Point3f add(Size2f size) { return new Point3f(x+size.width, y+size.height, z); } // Adds the point with a size to get another point public Point3f add(Size2i size) { return new Point3f(x+(float)size.width, y+(float)size.height, z); } // Subtracts the point with the vector to get another point public Point3f subtract(Vector3 vec) { return new Point3f(x-vec.x, y-vec.y, z-vec.z); } // Subtracts the point with the vector to get another point public Point3f subtract(Vector2 vec) { return new Point3f(x-vec.x, y-vec.y, z); } // Subtracts the point with a size to get another point public Point3f subtract(Size3f size) { return new Point3f(x-size.width, y-size.height, z-size.depth); } // Subtracts the point with a size to get another point public Point3f subtract(Size3i size) { return new Point3f(x-(float)size.width, y-(float)size.height, z-(float)size.depth); } // Subtracts the point with a size to get another point public Point3f subtract(Size2f size) { return new Point3f(x-size.width, y-size.height, z); } // Subtracts the point with a size to get another point public Point3f subtract(Size2i size) { return new Point3f(x-(float)size.width, y-(float)size.height, z); } // Subtracts the two points to get a vector pointing in between both public Vector3 subtract(Point3f pt) { return new Vector3(x-pt.x, y-pt.y, z-pt.z); } // Subtracts the two points to get a vector pointing in between both public Vector3 subtract(Point3i pt) { return new Vector3(x-(float)pt.x, y-(float)pt.y, z-(float)pt.z); } // Subtracts the two points to get a vector pointing in between both public Vector3 subtract(Point2f pt) { return new Vector3(x-pt.x, y-pt.y, z); } // Subtracts the two points to get a vector pointing in between both public Vector3 subtract(Point2i pt) { return new Vector3(x-(float)pt.x, y-(float)pt.y, z); } // Gets the midpoint of the two points public Point3f getMidpoint(Point3f pt) { return new Point3f((x+pt.x)/2f, (y+pt.y)/2f, (z+pt.z)/2f); } // Gets the midpoint of the two points public Point3f getMidpoint(Point3i pt) { return new Point3f((x+(float)pt.x)/2f, (y+(float)pt.y)/2f, (z+(float)pt.z)/2f); } // Gets the midpoint of the two points public Point3f getMidpoint(Point2f pt) { return new Point3f((x+pt.x)/2f, (y+pt.y)/2f, z/2f); } // Gets the midpoint of the two points public Point3f getMidpoint(Point2i pt) { return new Point3f((x+(float)pt.x)/2f, (y+(float)pt.y)/2f, z/2f); } // Finds if the two points are equal public bool equals(Point3f pt) { return (x== pt.x && y== pt.y && z== pt.z); } // Finds if the two points are equal public bool equals(Point3i pt) { return ((int)x== pt.x && (int)y== pt.y && (int)z== pt.z); } #endregion // Methods #region --- Inherited Methods --- // Finds out if the given object is equal to the point public override bool Equals(object obj) { if(obj== null) return false; if(obj is Point3f) return equals((Point3f)obj); if(obj is Point3i) return equals((Point3i)obj); return false; } // Gets the hash code public override int GetHashCode() { return ((int)x^(int)y^(int)z); } // Prints out the contents of the point public override string ToString() { return "X:"+x+",Y:"+y+",Z:"+z; } #endregion // Inherited Methods #region --- Operators --- // Equality operators public static bool operator ==(Point3f left, Point3f right) { return left.equals(right); } public static bool operator ==(Point3f left, Point3i right) { return left.equals(right); } // Inequality operators public static bool operator !=(Point3f left, Point3f right) { return !left.equals(right); } public static bool operator !=(Point3f left, Point3i right) { return !left.equals(right); } // Addition operators public static Point3f operator +(Point3f left, Vector3 right) { return left.add(right); } public static Point3f operator +(Point3f left, Vector2 right) { return left.add(right); } public static Point3f operator +(Point3f left, Size3f right) { return left.add(right); } public static Point3f operator +(Point3f left, Size3i right) { return left.add(right); } public static Point3f operator +(Point3f left, Size2f right) { return left.add(right); } public static Point3f operator +(Point3f left, Size2i right) { return left.add(right); } // Subtration operators public static Point3f operator -(Point3f left, Vector3 right) { return left.subtract(right); } public static Point3f operator -(Point3f left, Vector2 right) { return left.subtract(right); } public static Point3f operator -(Point3f left, Size3f right) { return left.subtract(right); } public static Point3f operator -(Point3f left, Size3i right) { return left.subtract(right); } public static Point3f operator -(Point3f left, Size2f right) { return left.subtract(right); } public static Point3f operator -(Point3f left, Size2i right) { return left.subtract(right); } public static Vector3 operator -(Point3f left, Point3f right) { return left.subtract(right); } public static Vector3 operator -(Point3f left, Point3i right) { return left.subtract(right); } public static Vector3 operator -(Point3f left, Point2f right) { return left.subtract(right); } public static Vector3 operator -(Point3f left, Point2i right) { return left.subtract(right); } // Multiplication operators public static bool operator *(Point3f left, BoundingVolume right) { return right.contains(left); } public static bool operator *(Point3f left, Ray right) { return right.intersects(ref left); } // Unkown name operators public static Point3f operator |(Point3f left, Point3f right) { return left.getMidpoint(right); } public static Point3f operator |(Point3f left, Point3i right) { return left.getMidpoint(right); } public static Point3f operator |(Point3f left, Point2f right) { return left.getMidpoint(right); } public static Point3f operator |(Point3f left, Point2i right) { return left.getMidpoint(right); } // Conversion operators // [Point3f to Vector3] public static explicit operator Vector3(Point3f castee) { return castee.toVector3(); } // [Point3f to Vector2] public static explicit operator Vector2(Point3f castee) { return castee.toVector2(); } // [Point3f to Point3i] public static implicit operator Point3i(Point3f castee) { return castee.toPoint3i(); } // [Point3f to Point2f] public static explicit operator Point2f(Point3f castee) { return castee.toPoint2f(); } // [Point3f to Point2i] public static explicit operator Point2i(Point3f castee) { return castee.toPoint2i(); } #endregion // Operators } } // End of File
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.DotNet.ProjectModel.Compilation; using Microsoft.DotNet.ProjectModel.Graph; using Microsoft.DotNet.ProjectModel.Resolution; using Microsoft.DotNet.Tools.Test.Utilities; using FluentAssertions; using Xunit; namespace Microsoft.DotNet.ProjectModel.Tests { public class LibraryExporterPackageTests { private const string PackagePath = "PackagePath"; private PackageDescription CreateDescription(LockFileTargetLibrary target = null, LockFilePackageLibrary package = null) { return new PackageDescription(PackagePath, package ?? new LockFilePackageLibrary(), target ?? new LockFileTargetLibrary(), new List<LibraryRange>(), compatible: true, resolved: true); } [Fact] public void ExportsPackageNativeLibraries() { var description = CreateDescription( new LockFileTargetLibrary() { NativeLibraries = new List<LockFileItem>() { { new LockFileItem() { Path = "lib/Native.so" } } } }); var result = ExportSingle(description); result.NativeLibraryGroups.Should().HaveCount(1); var libraryAsset = result.NativeLibraryGroups.GetDefaultAssets().First(); libraryAsset.Name.Should().Be("Native"); libraryAsset.Transform.Should().BeNull(); libraryAsset.RelativePath.Should().Be("lib/Native.so"); libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "lib/Native.so")); } [Fact] public void ExportsPackageCompilationAssebmlies() { var description = CreateDescription( new LockFileTargetLibrary() { CompileTimeAssemblies = new List<LockFileItem>() { { new LockFileItem() { Path = "ref/Native.dll" } } } }); var result = ExportSingle(description); result.CompilationAssemblies.Should().HaveCount(1); var libraryAsset = result.CompilationAssemblies.First(); libraryAsset.Name.Should().Be("Native"); libraryAsset.Transform.Should().BeNull(); libraryAsset.RelativePath.Should().Be("ref/Native.dll"); libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "ref/Native.dll")); } [Fact] public void ExportsPackageRuntimeAssebmlies() { var description = CreateDescription( new LockFileTargetLibrary() { RuntimeAssemblies = new List<LockFileItem>() { { new LockFileItem() { Path = "ref/Native.dll" } } } }); var result = ExportSingle(description); result.RuntimeAssemblyGroups.Should().HaveCount(1); var libraryAsset = result.RuntimeAssemblyGroups.GetDefaultAssets().First(); libraryAsset.Name.Should().Be("Native"); libraryAsset.Transform.Should().BeNull(); libraryAsset.RelativePath.Should().Be("ref/Native.dll"); libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "ref/Native.dll")); } [Fact] public void ExportsPackageRuntimeTargets() { var description = CreateDescription( new LockFileTargetLibrary() { RuntimeTargets = new List<LockFileRuntimeTarget>() { new LockFileRuntimeTarget("native/native.dylib", "osx", "native"), new LockFileRuntimeTarget("lib/Something.OSX.dll", "osx", "runtime") } }); var result = ExportSingle(description); result.RuntimeAssemblyGroups.Should().HaveCount(2); result.RuntimeAssemblyGroups.First(g => g.Runtime == string.Empty).Assets.Should().HaveCount(0); result.RuntimeAssemblyGroups.First(g => g.Runtime == "osx").Assets.Should().HaveCount(1); result.NativeLibraryGroups.Should().HaveCount(2); result.NativeLibraryGroups.First(g => g.Runtime == string.Empty).Assets.Should().HaveCount(0); result.NativeLibraryGroups.First(g => g.Runtime == "osx").Assets.Should().HaveCount(1); var nativeAsset = result.NativeLibraryGroups.GetRuntimeAssets("osx").First(); nativeAsset.Name.Should().Be("native"); nativeAsset.Transform.Should().BeNull(); nativeAsset.RelativePath.Should().Be("native/native.dylib"); nativeAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "native/native.dylib")); var runtimeAsset = result.RuntimeAssemblyGroups.GetRuntimeAssets("osx").First(); runtimeAsset.Name.Should().Be("Something.OSX"); runtimeAsset.Transform.Should().BeNull(); runtimeAsset.RelativePath.Should().Be("lib/Something.OSX.dll"); runtimeAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "lib/Something.OSX.dll")); } [Fact] public void ExportsPackageResourceAssemblies() { var description = CreateDescription( new LockFileTargetLibrary() { ResourceAssemblies = new List<LockFileItem>() { new LockFileItem("resources/en-US/Res.dll", new Dictionary<string, string>() { { "locale", "en-US"} }), new LockFileItem("resources/ru-RU/Res.dll", new Dictionary<string, string>() { { "locale", "ru-RU" } }), } }); var result = ExportSingle(description); result.ResourceAssemblies.Should().HaveCount(2); var asset = result.ResourceAssemblies.Should().Contain(g => g.Locale == "en-US").Subject.Asset; asset.Name.Should().Be("Res"); asset.Transform.Should().BeNull(); asset.RelativePath.Should().Be("resources/en-US/Res.dll"); asset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "resources/en-US/Res.dll")); asset = result.ResourceAssemblies.Should().Contain(g => g.Locale == "ru-RU").Subject.Asset; asset.Name.Should().Be("Res"); asset.Transform.Should().BeNull(); asset.RelativePath.Should().Be("resources/ru-RU/Res.dll"); asset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "resources/ru-RU/Res.dll")); } [Fact] public void ExportsSources() { var description = CreateDescription( package: new LockFilePackageLibrary() { Files = new List<string>() { Path.Combine("shared", "file.cs") } }); var result = ExportSingle(description); result.SourceReferences.Should().HaveCount(1); var libraryAsset = result.SourceReferences.First(); libraryAsset.Name.Should().Be("file"); libraryAsset.Transform.Should().BeNull(); libraryAsset.RelativePath.Should().Be(Path.Combine("shared", "file.cs")); libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "shared", "file.cs")); } [Fact] public void ExportsCopyToOutputContentFiles() { var description = CreateDescription( new LockFileTargetLibrary() { ContentFiles = new List<LockFileContentFile>() { new LockFileContentFile() { CopyToOutput = true, Path = Path.Combine("content", "file.txt"), OutputPath = Path.Combine("Out","Path.txt"), PPOutputPath = "something" } } }); var result = ExportSingle(description); result.RuntimeAssets.Should().HaveCount(1); var libraryAsset = result.RuntimeAssets.First(); libraryAsset.Transform.Should().NotBeNull(); libraryAsset.RelativePath.Should().Be(Path.Combine("Out", "Path.txt")); libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "content", "file.txt")); } [Fact] public void ExportsResourceContentFiles() { var description = CreateDescription( new LockFileTargetLibrary() { ContentFiles = new List<LockFileContentFile>() { new LockFileContentFile() { BuildAction = BuildAction.EmbeddedResource, Path = Path.Combine("content", "file.txt"), PPOutputPath = "something" } } }); var result = ExportSingle(description); result.EmbeddedResources.Should().HaveCount(1); var libraryAsset = result.EmbeddedResources.First(); libraryAsset.Transform.Should().NotBeNull(); libraryAsset.RelativePath.Should().Be(Path.Combine("content", "file.txt")); libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "content", "file.txt")); } [Fact] public void ExportsCompileContentFiles() { var description = CreateDescription( new LockFileTargetLibrary() { ContentFiles = new List<LockFileContentFile>() { new LockFileContentFile() { BuildAction = BuildAction.Compile, Path = Path.Combine("content", "file.cs"), PPOutputPath = "something" } } }); var result = ExportSingle(description); result.SourceReferences.Should().HaveCount(1); var libraryAsset = result.SourceReferences.First(); libraryAsset.Transform.Should().NotBeNull(); libraryAsset.RelativePath.Should().Be(Path.Combine("content", "file.cs")); libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "content", "file.cs")); } [Fact] public void SelectsContentFilesOfProjectCodeLanguage() { var description = CreateDescription( new LockFileTargetLibrary() { ContentFiles = new List<LockFileContentFile>() { new LockFileContentFile() { BuildAction = BuildAction.Compile, Path = Path.Combine("content", "file.cs"), PPOutputPath = "something", CodeLanguage = "cs" }, new LockFileContentFile() { BuildAction = BuildAction.Compile, Path = Path.Combine("content", "file.vb"), PPOutputPath = "something", CodeLanguage = "vb" }, new LockFileContentFile() { BuildAction = BuildAction.Compile, Path = Path.Combine("content", "file.any"), PPOutputPath = "something", } } }); var result = ExportSingle(description); result.SourceReferences.Should().HaveCount(1); var libraryAsset = result.SourceReferences.First(); libraryAsset.Transform.Should().NotBeNull(); libraryAsset.RelativePath.Should().Be(Path.Combine("content", "file.cs")); libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "content", "file.cs")); } [Fact] public void SelectsContentFilesWithNoLanguageIfProjectLanguageNotMathed() { var description = CreateDescription( new LockFileTargetLibrary() { ContentFiles = new List<LockFileContentFile>() { new LockFileContentFile() { BuildAction = BuildAction.Compile, Path = Path.Combine("content", "file.vb"), PPOutputPath = "something", CodeLanguage = "vb" }, new LockFileContentFile() { BuildAction = BuildAction.Compile, Path = Path.Combine("content", "file.any"), PPOutputPath = "something", } } }); var result = ExportSingle(description); result.SourceReferences.Should().HaveCount(1); var libraryAsset = result.SourceReferences.First(); libraryAsset.Transform.Should().NotBeNull(); libraryAsset.RelativePath.Should().Be(Path.Combine("content", "file.any")); libraryAsset.ResolvedPath.Should().Be(Path.Combine(PackagePath, "content", "file.any")); } private LibraryExport ExportSingle(LibraryDescription description = null) { var rootProject = new Project() { Name = "RootProject", CompilerName = "csc" }; var rootProjectDescription = new ProjectDescription( new LibraryRange(), rootProject, new LibraryRange[] { }, new TargetFrameworkInformation(), true); if (description == null) { description = rootProjectDescription; } else { description.Parents.Add(rootProjectDescription); } var libraryManager = new LibraryManager(new[] { description }, new DiagnosticMessage[] { }, ""); var allExports = new LibraryExporter(rootProjectDescription, libraryManager, "config", "runtime", null, "basepath", "solutionroot").GetAllExports(); var export = allExports.Single(); return export; } } }
namespace System.IO.BACnet; // Add FC : from Karg's Stack public enum BacnetUnitsId { UNITS_METERS_PER_SECOND_PER_SECOND = 166, /* Area */ UNITS_SQUARE_METERS = 0, UNITS_SQUARE_CENTIMETERS = 116, UNITS_SQUARE_FEET = 1, UNITS_SQUARE_INCHES = 115, /* Currency */ UNITS_CURRENCY1 = 105, UNITS_CURRENCY2 = 106, UNITS_CURRENCY3 = 107, UNITS_CURRENCY4 = 108, UNITS_CURRENCY5 = 109, UNITS_CURRENCY6 = 110, UNITS_CURRENCY7 = 111, UNITS_CURRENCY8 = 112, UNITS_CURRENCY9 = 113, UNITS_CURRENCY10 = 114, /* Electrical */ UNITS_MILLIAMPERES = 2, UNITS_AMPERES = 3, UNITS_AMPERES_PER_METER = 167, UNITS_AMPERES_PER_SQUARE_METER = 168, UNITS_AMPERE_SQUARE_METERS = 169, UNITS_DECIBELS = 199, UNITS_DECIBELS_MILLIVOLT = 200, UNITS_DECIBELS_VOLT = 201, UNITS_FARADS = 170, UNITS_HENRYS = 171, UNITS_OHMS = 4, UNITS_OHM_METERS = 172, UNITS_MILLIOHMS = 145, UNITS_KILOHMS = 122, UNITS_MEGOHMS = 123, UNITS_MICROSIEMENS = 190, UNITS_MILLISIEMENS = 202, UNITS_SIEMENS = 173, /* 1 mho equals 1 siemens */ UNITS_SIEMENS_PER_METER = 174, UNITS_TESLAS = 175, UNITS_VOLTS = 5, UNITS_MILLIVOLTS = 124, UNITS_KILOVOLTS = 6, UNITS_MEGAVOLTS = 7, UNITS_VOLT_AMPERES = 8, UNITS_KILOVOLT_AMPERES = 9, UNITS_MEGAVOLT_AMPERES = 10, UNITS_VOLT_AMPERES_REACTIVE = 11, UNITS_KILOVOLT_AMPERES_REACTIVE = 12, UNITS_MEGAVOLT_AMPERES_REACTIVE = 13, UNITS_VOLTS_PER_DEGREE_KELVIN = 176, UNITS_VOLTS_PER_METER = 177, UNITS_DEGREES_PHASE = 14, UNITS_POWER_FACTOR = 15, UNITS_WEBERS = 178, /* Energy */ UNITS_JOULES = 16, UNITS_KILOJOULES = 17, UNITS_KILOJOULES_PER_KILOGRAM = 125, UNITS_MEGAJOULES = 126, UNITS_WATT_HOURS = 18, UNITS_KILOWATT_HOURS = 19, UNITS_MEGAWATT_HOURS = 146, UNITS_WATT_HOURS_REACTIVE = 203, UNITS_KILOWATT_HOURS_REACTIVE = 204, UNITS_MEGAWATT_HOURS_REACTIVE = 205, UNITS_BTUS = 20, UNITS_KILO_BTUS = 147, UNITS_MEGA_BTUS = 148, UNITS_THERMS = 21, UNITS_TON_HOURS = 22, /* Enthalpy */ UNITS_JOULES_PER_KILOGRAM_DRY_AIR = 23, UNITS_KILOJOULES_PER_KILOGRAM_DRY_AIR = 149, UNITS_MEGAJOULES_PER_KILOGRAM_DRY_AIR = 150, UNITS_BTUS_PER_POUND_DRY_AIR = 24, UNITS_BTUS_PER_POUND = 117, /* Entropy */ UNITS_JOULES_PER_DEGREE_KELVIN = 127, UNITS_KILOJOULES_PER_DEGREE_KELVIN = 151, UNITS_MEGAJOULES_PER_DEGREE_KELVIN = 152, UNITS_JOULES_PER_KILOGRAM_DEGREE_KELVIN = 128, /* Force */ UNITS_NEWTON = 153, /* Frequency */ UNITS_CYCLES_PER_HOUR = 25, UNITS_CYCLES_PER_MINUTE = 26, UNITS_HERTZ = 27, UNITS_KILOHERTZ = 129, UNITS_MEGAHERTZ = 130, UNITS_PER_HOUR = 131, /* Humidity */ UNITS_GRAMS_OF_WATER_PER_KILOGRAM_DRY_AIR = 28, UNITS_PERCENT_RELATIVE_HUMIDITY = 29, /* Length */ UNITS_MICROMETERS = 194, UNITS_MILLIMETERS = 30, UNITS_CENTIMETERS = 118, UNITS_KILOMETERS = 193, UNITS_METERS = 31, UNITS_INCHES = 32, UNITS_FEET = 33, /* Light */ UNITS_CANDELAS = 179, UNITS_CANDELAS_PER_SQUARE_METER = 180, UNITS_WATTS_PER_SQUARE_FOOT = 34, UNITS_WATTS_PER_SQUARE_METER = 35, UNITS_LUMENS = 36, UNITS_LUXES = 37, UNITS_FOOT_CANDLES = 38, /* Mass */ UNITS_MILLIGRAMS = 196, UNITS_GRAMS = 195, UNITS_KILOGRAMS = 39, UNITS_POUNDS_MASS = 40, UNITS_TONS = 41, /* Mass Flow */ UNITS_GRAMS_PER_SECOND = 154, UNITS_GRAMS_PER_MINUTE = 155, UNITS_KILOGRAMS_PER_SECOND = 42, UNITS_KILOGRAMS_PER_MINUTE = 43, UNITS_KILOGRAMS_PER_HOUR = 44, UNITS_POUNDS_MASS_PER_SECOND = 119, UNITS_POUNDS_MASS_PER_MINUTE = 45, UNITS_POUNDS_MASS_PER_HOUR = 46, UNITS_TONS_PER_HOUR = 156, /* Power */ UNITS_MILLIWATTS = 132, UNITS_WATTS = 47, UNITS_KILOWATTS = 48, UNITS_MEGAWATTS = 49, UNITS_BTUS_PER_HOUR = 50, UNITS_KILO_BTUS_PER_HOUR = 157, UNITS_HORSEPOWER = 51, UNITS_TONS_REFRIGERATION = 52, /* Pressure */ UNITS_PASCALS = 53, UNITS_HECTOPASCALS = 133, UNITS_KILOPASCALS = 54, UNITS_MILLIBARS = 134, UNITS_BARS = 55, UNITS_POUNDS_FORCE_PER_SQUARE_INCH = 56, UNITS_MILLIMETERS_OF_WATER = 206, UNITS_CENTIMETERS_OF_WATER = 57, UNITS_INCHES_OF_WATER = 58, UNITS_MILLIMETERS_OF_MERCURY = 59, UNITS_CENTIMETERS_OF_MERCURY = 60, UNITS_INCHES_OF_MERCURY = 61, /* Temperature */ UNITS_DEGREES_CELSIUS = 62, UNITS_DEGREES_KELVIN = 63, UNITS_DEGREES_KELVIN_PER_HOUR = 181, UNITS_DEGREES_KELVIN_PER_MINUTE = 182, UNITS_DEGREES_FAHRENHEIT = 64, UNITS_DEGREE_DAYS_CELSIUS = 65, UNITS_DEGREE_DAYS_FAHRENHEIT = 66, UNITS_DELTA_DEGREES_FAHRENHEIT = 120, UNITS_DELTA_DEGREES_KELVIN = 121, /* Time */ UNITS_YEARS = 67, UNITS_MONTHS = 68, UNITS_WEEKS = 69, UNITS_DAYS = 70, UNITS_HOURS = 71, UNITS_MINUTES = 72, UNITS_SECONDS = 73, UNITS_HUNDREDTHS_SECONDS = 158, UNITS_MILLISECONDS = 159, /* Torque */ UNITS_NEWTON_METERS = 160, /* Velocity */ UNITS_MILLIMETERS_PER_SECOND = 161, UNITS_MILLIMETERS_PER_MINUTE = 162, UNITS_METERS_PER_SECOND = 74, UNITS_METERS_PER_MINUTE = 163, UNITS_METERS_PER_HOUR = 164, UNITS_KILOMETERS_PER_HOUR = 75, UNITS_FEET_PER_SECOND = 76, UNITS_FEET_PER_MINUTE = 77, UNITS_MILES_PER_HOUR = 78, /* Volume */ UNITS_CUBIC_FEET = 79, UNITS_CUBIC_METERS = 80, UNITS_IMPERIAL_GALLONS = 81, UNITS_MILLILITERS = 197, UNITS_LITERS = 82, UNITS_US_GALLONS = 83, /* Volumetric Flow */ UNITS_CUBIC_FEET_PER_SECOND = 142, UNITS_CUBIC_FEET_PER_MINUTE = 84, // One unit in Addendum 135-2012bg UNITS_MILLION_CUBIC_FEET_PER_MINUTE = 254, UNITS_CUBIC_FEET_PER_HOUR = 191, // five units in Addendum 135-2012bg UNITS_STANDARD_CUBIC_FEET_PER_DAY = 47808, UNITS_MILLION_STANDARD_CUBIC_FEET_PER_DAY = 47809, UNITS_THOUSAND_CUBIC_FEET_PER_DAY = 47810, UNITS_THOUSAND_STANDARD_CUBIC_FEET_PER_DAY = 47811, UINITS_POUNDS_MASS_PER_DAY = 47812, UNITS_CUBIC_METERS_PER_SECOND = 85, UNITS_CUBIC_METERS_PER_MINUTE = 165, UNITS_CUBIC_METERS_PER_HOUR = 135, UNITS_IMPERIAL_GALLONS_PER_MINUTE = 86, UNITS_MILLILITERS_PER_SECOND = 198, UNITS_LITERS_PER_SECOND = 87, UNITS_LITERS_PER_MINUTE = 88, UNITS_LITERS_PER_HOUR = 136, UNITS_US_GALLONS_PER_MINUTE = 89, UNITS_US_GALLONS_PER_HOUR = 192, /* Other */ UNITS_DEGREES_ANGULAR = 90, UNITS_DEGREES_CELSIUS_PER_HOUR = 91, UNITS_DEGREES_CELSIUS_PER_MINUTE = 92, UNITS_DEGREES_FAHRENHEIT_PER_HOUR = 93, UNITS_DEGREES_FAHRENHEIT_PER_MINUTE = 94, UNITS_JOULE_SECONDS = 183, UNITS_KILOGRAMS_PER_CUBIC_METER = 186, UNITS_KW_HOURS_PER_SQUARE_METER = 137, UNITS_KW_HOURS_PER_SQUARE_FOOT = 138, UNITS_MEGAJOULES_PER_SQUARE_METER = 139, UNITS_MEGAJOULES_PER_SQUARE_FOOT = 140, UNITS_NO_UNITS = 95, UNITS_NEWTON_SECONDS = 187, UNITS_NEWTONS_PER_METER = 188, UNITS_PARTS_PER_MILLION = 96, UNITS_PARTS_PER_BILLION = 97, UNITS_PERCENT = 98, UNITS_PERCENT_OBSCURATION_PER_FOOT = 143, UNITS_PERCENT_OBSCURATION_PER_METER = 144, UNITS_PERCENT_PER_SECOND = 99, UNITS_PER_MINUTE = 100, UNITS_PER_SECOND = 101, UNITS_PSI_PER_DEGREE_FAHRENHEIT = 102, UNITS_RADIANS = 103, UNITS_RADIANS_PER_SECOND = 184, UNITS_REVOLUTIONS_PER_MINUTE = 104, UNITS_SQUARE_METERS_PER_NEWTON = 185, UNITS_WATTS_PER_METER_PER_DEGREE_KELVIN = 189, UNITS_WATTS_PER_SQUARE_METER_DEGREE_KELVIN = 141, UNITS_PER_MILLE = 207, UNITS_GRAMS_PER_GRAM = 208, UNITS_KILOGRAMS_PER_KILOGRAM = 209, UNITS_GRAMS_PER_KILOGRAM = 210, UNITS_MILLIGRAMS_PER_GRAM = 211, UNITS_MILLIGRAMS_PER_KILOGRAM = 212, UNITS_GRAMS_PER_MILLILITER = 213, UNITS_GRAMS_PER_LITER = 214, UNITS_MILLIGRAMS_PER_LITER = 215, UNITS_MICROGRAMS_PER_LITER = 216, UNITS_GRAMS_PER_CUBIC_METER = 217, UNITS_MILLIGRAMS_PER_CUBIC_METER = 218, UNITS_MICROGRAMS_PER_CUBIC_METER = 219, UNITS_NANOGRAMS_PER_CUBIC_METER = 220, UNITS_GRAMS_PER_CUBIC_CENTIMETER = 221, UNITS_BECQUERELS = 222, UNITS_KILOBECQUERELS = 223, UNITS_MEGABECQUERELS = 224, UNITS_GRAY = 225, UNITS_MILLIGRAY = 226, UNITS_MICROGRAY = 227, UNITS_SIEVERTS = 228, UNITS_MILLISIEVERTS = 229, UNITS_MICROSIEVERTS = 230, UNITS_MICROSIEVERTS_PER_HOUR = 231, UNITS_DECIBELS_A = 232, UNITS_NEPHELOMETRIC_TURBIDITY_UNIT = 233, UNITS_PH = 234, UNITS_GRAMS_PER_SQUARE_METER = 235, // Since Addendum 135-2012ar UNITS_MINUTES_PER_DEGREE_KELVIN = 236, UNITS_METER_SQUARED_PER_METER = 237, UNITS_AMPERE_SECONDS = 238, UNITS_VOLT_AMPERE_HOURS = 239, UNITS_KILOVOLT_AMPERE_HOURS = 240, UNITS_MEGAVOLT_AMPERE_HOURS = 241, UNITS_VOLT_AMPERE_HOURS_REACTIVE = 242, UNITS_KILOVOLT_AMPERE_HOURS_REACTIVE = 243, UNITS_MEGAVOLT_AMPERE_HOURS_REACTIVE = 244, UNITS_VOLT_SQUARE_HOURS = 245, UNITS_AMPERE_SQUARE_HOURS = 246, UNITS_JOULE_PER_HOURS = 247, UNITS_CUBIC_FEET_PER_DAY = 248, UNITS_CUBIC_METERS_PER_DAY = 249, UNITS_WATT_HOURS_PER_CUBIC_METER = 250, UNITS_JOULES_PER_CUBIC_METER = 251, UNITS_MOLE_PERCENT = 252, UNITS_PASCAL_SECONDS = 253, UNITS_MILLION_STANDARD_CUBIC_FEET_PER_MINUTE = 254 }
using UnityEngine; using System.Collections; using System; using CopyTextureSupport = UnityEngine.Rendering.CopyTextureSupport; using GraphicsDeviceType = UnityEngine.Rendering.GraphicsDeviceType; namespace UMA { /// <summary> /// Texture processing coroutine using rendertextures for atlas building. /// </summary> [Serializable] public class TextureProcessPRO { UMAData umaData; RenderTexture destinationTexture; Texture[] resultingTextures; UMAGeneratorBase umaGenerator; bool fastPath = false; public bool SupportsRTToTexture2D { get { return (CopyTextureSupport.RTToTexture & SystemInfo.copyTextureSupport) == CopyTextureSupport.RTToTexture; } } public static RenderTexture ResizeRenderTexture(RenderTexture source, int newWidth, int newHeight, FilterMode filter) { source.filterMode = filter; RenderTexture rt = new RenderTexture(newWidth, newHeight, 0, source.format, RenderTextureReadWrite.Linear); rt.filterMode = FilterMode.Point; RenderTexture bkup = RenderTexture.active; RenderTexture.active = rt; Graphics.Blit(source, rt); RenderTexture.active = bkup; return rt; } /// <summary> /// Setup data for atlas building. /// </summary> /// <param name="_umaData">UMA data.</param> /// <param name="_umaGenerator">UMA generator.</param> public void ProcessTexture(UMAData _umaData, UMAGeneratorBase _umaGenerator) { umaData = _umaData; umaGenerator = _umaGenerator; if (umaGenerator is UMAGenerator) { fastPath = (umaGenerator as UMAGenerator).fastGeneration; } if (umaData.atlasResolutionScale <= 0) umaData.atlasResolutionScale = 1f; var textureMerge = umaGenerator.textureMerge; textureMerge.RefreshMaterials(); if (textureMerge == null) { if (Debug.isDebugBuild) Debug.LogError("TextureMerge is null!"); // yield return null; } try { for (int atlasIndex = umaData.generatedMaterials.materials.Count - 1; atlasIndex >= 0; atlasIndex--) { var generatedMaterial = umaData.generatedMaterials.materials[atlasIndex]; //Rendering Atlas int moduleCount = 0; //Process all necessary TextureModules for (int i = 0; i < generatedMaterial.materialFragments.Count; i++) { if (!generatedMaterial.materialFragments[i].isRectShared && !generatedMaterial.materialFragments[i].isNoTextures) { moduleCount++; moduleCount = moduleCount + generatedMaterial.materialFragments[i].overlays.Length; } } textureMerge.EnsureCapacity(moduleCount); var slotData = generatedMaterial.materialFragments[0].slotData; resultingTextures = new Texture[slotData.material.channels.Length]; for (int textureType = slotData.material.channels.Length - 1; textureType >= 0; textureType--) { switch (slotData.material.channels[textureType].channelType) { case UMAMaterial.ChannelType.Texture: case UMAMaterial.ChannelType.DiffuseTexture: case UMAMaterial.ChannelType.NormalMap: case UMAMaterial.ChannelType.DetailNormalMap: { bool CopyRTtoTex = SupportsRTToTexture2D && fastPath; textureMerge.Reset(); for (int i = 0; i < generatedMaterial.materialFragments.Count; i++) { textureMerge.SetupModule(generatedMaterial, i, textureType); } //last element for this textureType moduleCount = 0; int width = Mathf.FloorToInt(generatedMaterial.cropResolution.x); int height = Mathf.FloorToInt(generatedMaterial.cropResolution.y); if (width == 0 || height == 0) { continue; } //this should be restricted to >= 1 but 0 was allowed before and projects may have the umaMaterial value serialized to 0. float downSample = (slotData.material.channels[textureType].DownSample == 0) ? 1f : (1f / slotData.material.channels[textureType].DownSample); destinationTexture = new RenderTexture(Mathf.FloorToInt(generatedMaterial.cropResolution.x * umaData.atlasResolutionScale * downSample), Mathf.FloorToInt(generatedMaterial.cropResolution.y * umaData.atlasResolutionScale * downSample), 0, slotData.material.channels[textureType].textureFormat, RenderTextureReadWrite.Linear); destinationTexture.filterMode = FilterMode.Point; destinationTexture.useMipMap = umaGenerator.convertMipMaps && CopyRTtoTex;// && !umaGenerator.convertRenderTexture; destinationTexture.name = slotData.material.name + " Chan " + textureType + " frame: " + Time.frameCount; //Draw all the Rects here Color backgroundColor; UMAMaterial.ChannelType channelType = slotData.material.channels[textureType].channelType; if (slotData.material.MaskWithCurrentColor && (channelType == UMAMaterial.ChannelType.DiffuseTexture || channelType == UMAMaterial.ChannelType.Texture || channelType == UMAMaterial.ChannelType.TintedTexture)) { backgroundColor = slotData.material.maskMultiplier * textureMerge.camBackgroundColor; } else { backgroundColor = UMAMaterial.GetBackgroundColor(slotData.material.channels[textureType].channelType); } textureMerge.DrawAllRects(destinationTexture, width, height, backgroundColor, umaGenerator.SharperFitTextures); //PostProcess textureMerge.PostProcess(destinationTexture, slotData.material.channels[textureType].channelType); if (umaGenerator.convertRenderTexture || slotData.material.channels[textureType].ConvertRenderTexture) { #region Convert Render Textures if(CopyRTtoTex) { // copy the texture with mips to the Texture2D Texture2D tempTexture; tempTexture = new Texture2D(destinationTexture.width, destinationTexture.height, TextureFormat.ARGB32, umaGenerator.convertMipMaps, true); Graphics.CopyTexture(destinationTexture, tempTexture); destinationTexture.Release(); UnityEngine.GameObject.DestroyImmediate(destinationTexture); tempTexture.wrapMode = TextureWrapMode.Repeat; tempTexture.anisoLevel = slotData.material.AnisoLevel; tempTexture.mipMapBias = slotData.material.MipMapBias; tempTexture.filterMode = slotData.material.MatFilterMode; resultingTextures[textureType] = tempTexture as Texture; if(!slotData.material.channels[textureType].NonShaderTexture) { if (generatedMaterial.umaMaterial.translateSRP) { generatedMaterial.material.SetTexture(UMAUtils.TranslatedSRPTextureName(slotData.material.channels[textureType].materialPropertyName), tempTexture); } else { generatedMaterial.material.SetTexture(slotData.material.channels[textureType].materialPropertyName, tempTexture); } } } else { #if USE_ASYNC_GPU_READBACK // Todo: use AsyncGPUReadback to get the texture if possible. // // material == generatedMaterial.material // umaData == ; // slotData == ; // propname == slotData.material.channels[textureType].materialPropertyName // mipcount // mipsconverted[] // Data. //for (int i=0;i< destinationTexture.mipmapCount;i++) //{ // //} #else Texture2D tempTexture; tempTexture = new Texture2D(destinationTexture.width, destinationTexture.height, TextureFormat.ARGB32, umaGenerator.convertMipMaps, true); RenderTexture.active = destinationTexture; tempTexture.ReadPixels(new Rect(0, 0, destinationTexture.width, destinationTexture.height), 0, 0, umaGenerator.convertMipMaps); //resultingTextures[textureType] = tempTexture as Texture; RenderTexture.active = null; destinationTexture.Release(); UnityEngine.GameObject.DestroyImmediate(destinationTexture); // if (!fastPath) yield return 6; //tempTexture = resultingTextures[textureType] as Texture2D; tempTexture.Apply(); tempTexture.wrapMode = TextureWrapMode.Repeat; tempTexture.anisoLevel = slotData.material.AnisoLevel; tempTexture.mipMapBias = slotData.material.MipMapBias; tempTexture.filterMode = slotData.material.MatFilterMode; //if (slotData.asset.material.channels[textureType].Compression != UMAMaterial.CompressionSettings.None) //{ // tempTexture.Compress(slotData.asset.material.channels[textureType].Compression == UMAMaterial.CompressionSettings.HighQuality); // } resultingTextures[textureType] = tempTexture; if(!slotData.material.channels[textureType].NonShaderTexture) { if (generatedMaterial.umaMaterial.translateSRP) { generatedMaterial.material.SetTexture(UMAUtils.TranslatedSRPTextureName(slotData.material.channels[textureType].materialPropertyName), tempTexture); } else { generatedMaterial.material.SetTexture(slotData.material.channels[textureType].materialPropertyName, tempTexture); } generatedMaterial.material.SetTexture(UMAUtils.TranslatedSRPTextureName(slotData.material.channels[textureType].materialPropertyName), tempTexture); } } #endif #endregion } else { destinationTexture.anisoLevel = slotData.material.AnisoLevel; destinationTexture.mipMapBias = slotData.material.MipMapBias; destinationTexture.filterMode = slotData.material.MatFilterMode; destinationTexture.wrapMode = TextureWrapMode.Repeat; resultingTextures[textureType] = destinationTexture; if (!slotData.material.channels[textureType].NonShaderTexture) { if (generatedMaterial.umaMaterial.translateSRP) { generatedMaterial.material.SetTexture(UMAUtils.TranslatedSRPTextureName(slotData.material.channels[textureType].materialPropertyName), destinationTexture); } else { generatedMaterial.material.SetTexture(slotData.material.channels[textureType].materialPropertyName, destinationTexture); } } } break; } case UMAMaterial.ChannelType.MaterialColor: { if (slotData.material.channels[textureType].NonShaderTexture) break; generatedMaterial.material.SetColor(slotData.material.channels[textureType].materialPropertyName, generatedMaterial.materialFragments[0].baseColor); break; } case UMAMaterial.ChannelType.TintedTexture: { for (int i = 0; i < generatedMaterial.materialFragments.Count; i++) { var fragment = generatedMaterial.materialFragments[i]; if (fragment.isRectShared) continue; for (int j = 0; j < fragment.baseOverlay.textureList.Length; j++) { if (fragment.baseOverlay.textureList[j] != null) { if (!slotData.material.channels[textureType].NonShaderTexture) { if (generatedMaterial.umaMaterial.translateSRP) { generatedMaterial.material.SetTexture(UMAUtils.TranslatedSRPTextureName(slotData.material.channels[j].materialPropertyName), fragment.baseOverlay.textureList[j]); } else { generatedMaterial.material.SetTexture(slotData.material.channels[j].materialPropertyName, fragment.baseOverlay.textureList[j]); } } if (j == 0) { generatedMaterial.material.color = fragment.baseColor; } } } foreach (var overlay in fragment.overlays) { if (generatedMaterial.textureNameList == null) for (int j = 0; j < overlay.textureList.Length; j++) { if (overlay.textureList[j] != null) { if (!slotData.material.channels[textureType].NonShaderTexture) { if (generatedMaterial.umaMaterial.translateSRP) { generatedMaterial.material.SetTexture(UMAUtils.TranslatedSRPTextureName(slotData.material.channels[j].materialPropertyName), overlay.textureList[j]); } else { generatedMaterial.material.SetTexture(slotData.material.channels[j].materialPropertyName, overlay.textureList[j]); } } } } } } break; } } } generatedMaterial.resultingAtlasList = resultingTextures; } } finally { RenderTexture.active = null; } } private bool IsOpenGL() { var graphicsDeviceVersion = SystemInfo.graphicsDeviceVersion; return graphicsDeviceVersion.StartsWith("OpenGL"); } } }
//css_dbg /t:winexe; using System; using System.Drawing; using System.Diagnostics; using System.IO; using System.Collections; using System.Windows.Forms; using System.Drawing.Imaging; using System.Drawing.Drawing2D; namespace CSSScript { public class ShellExForm : System.Windows.Forms.Form { int spaceBetweenItems = 2; private TreeView treeView1; private Button upBtn; private Button downBtn; private Button cancelBtn; private Button okBtn; private Button browseBtn; private Button helpBtn; private System.ComponentModel.Container components = null; public bool readOnlyMode = false; private Button refreshBtn; private Button editBtn; public TreeViewEventHandler additionalOnCheckHandler; public ShellExForm(bool readOnlyMode) { this.readOnlyMode = readOnlyMode; InitializeComponent(); upBtn.Text = downBtn.Text = ""; #if NET2 treeView1.DrawMode = TreeViewDrawMode.OwnerDrawText; #endif } public ShellExForm() { InitializeComponent(); upBtn.Text = downBtn.Text = ""; #if NET2 treeView1.DrawMode = TreeViewDrawMode.OwnerDrawText; #endif } protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code private void InitializeComponent() { this.treeView1 = new System.Windows.Forms.TreeView(); this.upBtn = new System.Windows.Forms.Button(); this.downBtn = new System.Windows.Forms.Button(); this.cancelBtn = new System.Windows.Forms.Button(); this.okBtn = new System.Windows.Forms.Button(); this.browseBtn = new System.Windows.Forms.Button(); this.helpBtn = new System.Windows.Forms.Button(); this.refreshBtn = new System.Windows.Forms.Button(); this.editBtn = new System.Windows.Forms.Button(); this.SuspendLayout(); // // treeView1 // this.treeView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.treeView1.HideSelection = false; this.treeView1.Location = new System.Drawing.Point(12, 12); this.treeView1.Name = "treeView1"; this.treeView1.Size = new System.Drawing.Size(383, 375); this.treeView1.TabIndex = 0; this.treeView1.AfterCheck += new System.Windows.Forms.TreeViewEventHandler(this.treeView1_AfterCheck); this.treeView1.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeView1_AfterSelect); // // upBtn // this.upBtn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.upBtn.Location = new System.Drawing.Point(413, 23); this.upBtn.Name = "upBtn"; this.upBtn.Size = new System.Drawing.Size(75, 24); this.upBtn.TabIndex = 1; this.upBtn.Text = "Up"; this.upBtn.Click += new System.EventHandler(this.upBtn_Click); // // downBtn // this.downBtn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.downBtn.Location = new System.Drawing.Point(413, 52); this.downBtn.Name = "downBtn"; this.downBtn.Size = new System.Drawing.Size(75, 24); this.downBtn.TabIndex = 1; this.downBtn.Text = "Down"; this.downBtn.Click += new System.EventHandler(this.downBtn_Click); // // cancelBtn // this.cancelBtn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.cancelBtn.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.cancelBtn.Location = new System.Drawing.Point(413, 363); this.cancelBtn.Name = "cancelBtn"; this.cancelBtn.Size = new System.Drawing.Size(75, 24); this.cancelBtn.TabIndex = 2; this.cancelBtn.Text = "Cancel"; this.cancelBtn.Click += new System.EventHandler(this.cancelBtn_Click); // // okBtn // this.okBtn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.okBtn.DialogResult = System.Windows.Forms.DialogResult.OK; this.okBtn.Location = new System.Drawing.Point(413, 333); this.okBtn.Name = "okBtn"; this.okBtn.Size = new System.Drawing.Size(75, 24); this.okBtn.TabIndex = 2; this.okBtn.Text = "Ok"; this.okBtn.Click += new System.EventHandler(this.okBtn_Click); // // browseBtn // this.browseBtn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.browseBtn.Location = new System.Drawing.Point(413, 114); this.browseBtn.Name = "browseBtn"; this.browseBtn.Size = new System.Drawing.Size(75, 24); this.browseBtn.TabIndex = 2; this.browseBtn.Text = "Browse"; this.browseBtn.Click += new System.EventHandler(this.browseBtn_Click); // // helpBtn // this.helpBtn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.helpBtn.Location = new System.Drawing.Point(413, 174); this.helpBtn.Name = "helpBtn"; this.helpBtn.Size = new System.Drawing.Size(75, 24); this.helpBtn.TabIndex = 2; this.helpBtn.Text = "Help"; this.helpBtn.Click += new System.EventHandler(this.helpBtn_Click); // // refreshBtn // this.refreshBtn.Location = new System.Drawing.Point(413, 82); this.refreshBtn.Name = "refreshBtn"; this.refreshBtn.Size = new System.Drawing.Size(75, 23); this.refreshBtn.TabIndex = 3; this.refreshBtn.Text = "Refresh"; this.refreshBtn.Click += new System.EventHandler(this.refreshBtn_Click); // // editBtn // this.editBtn.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.editBtn.Location = new System.Drawing.Point(413, 144); this.editBtn.Name = "editBtn"; this.editBtn.Size = new System.Drawing.Size(75, 24); this.editBtn.TabIndex = 2; this.editBtn.Text = "Edit"; this.editBtn.Click += new System.EventHandler(this.editBtn_Click); // // ShellExForm // this.AcceptButton = this.okBtn; this.CancelButton = this.cancelBtn; this.ClientSize = new System.Drawing.Size(503, 399); this.Controls.Add(this.refreshBtn); this.Controls.Add(this.helpBtn); this.Controls.Add(this.editBtn); this.Controls.Add(this.browseBtn); this.Controls.Add(this.okBtn); this.Controls.Add(this.cancelBtn); this.Controls.Add(this.downBtn); this.Controls.Add(this.upBtn); this.Controls.Add(this.treeView1); this.KeyPreview = true; this.Name = "ShellExForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "CS-Script Advanced Shell Extension"; this.Load += new System.EventHandler(this.Form1_Load); this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.ShellExForm_KeyDown); this.ResumeLayout(false); } #endregion private void button1_Click(object sender, System.EventArgs e) { this.Close(); } public string baseDirectory = Environment.ExpandEnvironmentVariables(@"%CSSCRIPT_DIR%\Lib\ShellExtensions\CS-Script"); private void Form1_Load(object sender, EventArgs e) { treeView1.CheckBoxes = true; RefreshTreeView(); } public void RefreshTreeView() { treeView1.Nodes.Clear(); ReadShellExtensions(baseDirectory); treeView1.SelectedNode = treeView1.Nodes[0]; if (readOnlyMode) { treeView1.Dock = DockStyle.Fill; treeView1.BackColor = Color.WhiteSmoke; foreach (Control c in this.Controls) if (c is Button) c.Visible = false; } } class SEItem { public SEItem(string path) { this.path = path; this.location = path; Refresh(); } public void Refresh() { string logicalPath = path; isDir = !File.Exists(logicalPath); if (path.EndsWith(".disabled")) { enabled = false; logicalPath = logicalPath.Replace(".disabled", ""); } else { enabled = true; } isSeparator = !isDir && (path.EndsWith("separator") || path.EndsWith("separator.disabled")); isConsole = !isDir && !isSeparator && path.EndsWith(".c.cmd"); level = path.Split(Path.DirectorySeparatorChar).Length - 1; } public override string ToString() { if (isSeparator) return "------------------------"; else { string[] parts = path.Split(Path.DirectorySeparatorChar); return parts[parts.Length - 1].Substring(3).Replace(".c.cmd", "").Replace(".cmd", "").Replace(".disabled", ""); } } public string GetLogicalFileName() { string retval = this.ToString(); if (!isSeparator) { if (!isDir) { if (isConsole) retval += ".c"; retval += ".cmd"; } } else { retval = "separator"; } if (!enabled) retval += ".disabled"; return retval; } public bool isDir; public bool isConsole; public bool isSeparator; bool enabled = false; public bool Enabled { get { return enabled; } set { if (enabled != value) { if (value) path = path.Substring(0, path.Length - ".disabled".Length); else path += ".disabled"; } enabled = value; } } public string path; //note this.path can be changed during the user operations public string location; //original value of this.path public int level; } public void ReadShellExtensions(string path) { int iterator = 0; ArrayList dirList = new ArrayList(); ArrayList itemsList = new ArrayList(); dirList.Add(path); while (iterator < dirList.Count) { foreach (string dir in Directory.GetDirectories(dirList[iterator].ToString())) { dirList.Add(dir); itemsList.Add(dir); } foreach (string file in Directory.GetFiles(dirList[iterator].ToString(), "*.cmd*")) itemsList.Add(file); foreach (string file in Directory.GetFiles(dirList[iterator].ToString(), "*.separator")) itemsList.Add(file); iterator++; } //sort according the ShellExtension sorting algorithm itemsList.Sort(Sorter.instance); //foreach (string item in itemsList) // Trace.WriteLine(item); TreeNode dirNode = null; foreach (string item in itemsList) { SEItem shellEx = new SEItem(item); TreeNode node = new TreeNode(shellEx.ToString()); node.Checked = shellEx.Enabled; node.Tag = shellEx; if (dirNode == null) { treeView1.Nodes.Add(node); } else { TreeNode parentNode = dirNode; SEItem parentShellEx = null; do { parentShellEx = (parentNode.Tag as SEItem); if (parentShellEx == null) { treeView1.Nodes.Add(node); } else if (parentShellEx.level == shellEx.level - 1) { parentNode.Nodes.Add(node); break; } parentNode = parentNode.Parent; } while (parentNode != null); if (parentNode == null) treeView1.Nodes.Add(node); } if (shellEx.isDir) dirNode = node; } treeView1.ExpandAll(); } class Sorter : IComparer { static public Sorter instance = new Sorter(); public int Compare(object x, object y) { return SortMethod(x.ToString(), y.ToString()); } int SortMethod(string x, string y) { string[] partsX = x.Split(Path.DirectorySeparatorChar); string[] partsY = y.Split(Path.DirectorySeparatorChar); for (int i = 0; i < Math.Min(partsX.Length, partsY.Length); i++) { string indexX = partsX[i].Substring(0, Math.Min(2, partsX[i].Length)); string indexY = partsY[i].Substring(0, Math.Min(2, partsX[i].Length)); if (indexX != indexY) return string.Compare(indexX, indexY); } if (partsX.Length < partsY.Length) return -1; else if (partsX.Length == partsY.Length) return 0; else return 1; } } Brush treeViewBackBrush = null; Brush TreeViewBackBrush { get { if (treeViewBackBrush == null) treeViewBackBrush = new SolidBrush(treeView1.BackColor); return treeViewBackBrush; } } #if NET2 private void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e) { SEItem item = (SEItem)e.Node.Tag; Brush b = Brushes.Black; if (item.isConsole) b = Brushes.Blue; if (!item.Enabled) { b = Brushes.Gray; } else { TreeNode parent = e.Node.Parent; while (parent != null) { if (!parent.Checked) { b = Brushes.Gray; break; } parent = parent.Parent; } } Rectangle frame = e.Bounds; if ((e.State & TreeNodeStates.Selected) != 0) { frame.Width = (int)e.Graphics.MeasureString(item.ToString(), treeView1.Font).Width; e.Graphics.FillRectangle(TreeViewBackBrush, frame); frame.Inflate(-1, -1); e.Graphics.DrawRectangle(Pens.Red, frame); } if (item.isSeparator) e.Graphics.DrawLine(Pens.Black, frame.Left + 4, frame.Top + frame.Height / 2, frame.Right - 4, frame.Top + frame.Height / 2); else e.Graphics.DrawString(item.ToString(), treeView1.Font, b, e.Bounds.Left, e.Bounds.Top + 2); } #endif bool ignoreChecking = false; private void treeView1_AfterCheck(object sender, TreeViewEventArgs e) { if (!ignoreChecking) { SEItem item = (SEItem)e.Node.Tag; if (readOnlyMode) { ignoreChecking = true; e.Node.Checked = !e.Node.Checked; ignoreChecking = false; } else { if (item.isDir) //directories cannot be disabled { ignoreChecking = true; e.Node.Checked = !e.Node.Checked; ignoreChecking = false; } else { item.Enabled = !item.Enabled; //if (item.Enabled) // e.Node.Expand(); //else // e.Node.Collapse(); treeView1.Invalidate(); } } if (additionalOnCheckHandler != null) additionalOnCheckHandler(sender, e); } } private void upBtn_Click(object sender, EventArgs e) { TreeNode node = treeView1.SelectedNode; if (node != null) { if (node.Index == 0) //first { if (node.Parent != null) { int nodeIndex = node.Parent.Index; TreeNodeCollection coll = (node.Parent.Parent == null ? treeView1.Nodes : node.Parent.Parent.Nodes); node.Remove(); coll.Insert(nodeIndex, node); } } else { int nodeIndex = node.Index; TreeNodeCollection coll = (node.Parent == null ? treeView1.Nodes : node.Parent.Nodes); if (coll[nodeIndex - 1].Nodes.Count != 0) //has child nodes { node.Remove(); coll[nodeIndex - 1].Nodes.Add(node); } else { node.Remove(); coll.Insert(nodeIndex - 1, node); } } treeView1.SelectedNode = node; } treeView1.Select(); } private void downBtn_Click(object sender, EventArgs e) { TreeNode node = treeView1.SelectedNode; if (node != null) { TreeNodeCollection coll = (node.Parent == null ? treeView1.Nodes : node.Parent.Nodes); if (node.Index == coll.Count - 1) //last { if (node.Parent != null) { TreeNodeCollection parentColl = node.Parent.Parent == null ? treeView1.Nodes : node.Parent.Parent.Nodes; int nodeIndex = node.Parent.Index; node.Remove(); parentColl.Insert(nodeIndex + 1, node); } } else { int nodeIndex = node.Index; if (coll[nodeIndex + 1].Nodes.Count != 0) //has child nodes { node.Remove(); coll[nodeIndex].Nodes.Insert(0, node); } else { node.Remove(); coll.Insert(nodeIndex + 1, node); } } treeView1.SelectedNode = node; } treeView1.Select(); } #region Images static Image DullImage(Image img) { Bitmap newBitmap = new Bitmap(img.Width, img.Height, PixelFormat.Format32bppArgb); using (Graphics g = Graphics.FromImage(newBitmap)) { //g.DrawImage(image, 0.0f, 0.0f); //draw original image ImageAttributes imageAttributes = new ImageAttributes(); int width = img.Width; int height = img.Height; float[][] colorMatrixElements = { new float[] {1, 0, 0, 0, 0}, // red scaling factor of 1 new float[] {0, 1, 0, 0, 0}, // green scaling factor of 1 new float[] {0, 0, 1, 0, 0}, // blue scaling factor of 1 new float[] {0, 0, 0, 1, 0}, // alpha scaling factor of 1 new float[] {.05f, .05f, .05f, 0, 1}}; // three translations of 0.2 ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements); imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); g.DrawImage( img, new Rectangle(0, 0, width, height), // destination rectangle 0, 0, // upper-left corner of source rectangle width, // width of source rectangle height, // height of source rectangle GraphicsUnit.Pixel, imageAttributes); } return newBitmap; } static Image CreateUpImage() { Image img = new Bitmap(25, 25); using (Graphics g = Graphics.FromImage(img)) { LinearGradientBrush lgb = new LinearGradientBrush( new Point(0, 0), new Point(25, 0), Color.YellowGreen, Color.DarkGreen); int xOffset = -4; int yOffset = -1; g.FillPolygon(lgb, new Point[] { new Point(15+xOffset,5+yOffset), new Point(25+xOffset,15+yOffset), new Point(18+xOffset,15+yOffset), new Point(18+xOffset,20+yOffset), new Point(12+xOffset,20+yOffset), new Point(12+xOffset,15+yOffset), new Point(5+xOffset,15+yOffset) }); } return img; } static Image CreateDownImage() { Image img = new Bitmap(CreateUpImage()); img.RotateFlip(RotateFlipType.Rotate180FlipX); return img; } Image imgUp = CreateUpImage(); Image imgDown = CreateDownImage(); Image imgUpDisabled = DullImage(CreateUpImage()); Image imgDownDisabled = DullImage(CreateDownImage()); #endregion private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) { upBtn.Image = upBtn.Enabled ? imgUp : imgUpDisabled; downBtn.Image = downBtn.Enabled ? imgDown : imgDownDisabled; } private void okBtn_Click(object sender, EventArgs e) { Cursor = Cursors.WaitCursor; try { ProcessDirNode(treeView1.Nodes); RemoveEmptyChildDirs(baseDirectory); } finally { Cursor = Cursors.Default; } } void RemoveEmptyChildDirs(string path) { int iterator = 0; ArrayList dirList = new ArrayList(); dirList.Add(path); while (iterator < dirList.Count) { foreach (string dir in Directory.GetDirectories(dirList[iterator].ToString())) dirList.Add(dir); iterator++; } dirList.RemoveAt(0);//remove parent dir foreach (string dir in dirList) if (Directory.Exists(dir) && IsDirEmpty(dir)) Directory.Delete(dir, true); } bool IsDirEmpty(string path) { int iterator = 0; ArrayList dirList = new ArrayList(); ArrayList fileList = new ArrayList(); dirList.Add(path); while (iterator < dirList.Count) { foreach (string dir in Directory.GetDirectories(dirList[iterator].ToString())) dirList.Add(dir); foreach (string file in Directory.GetFiles(dirList[iterator].ToString())) fileList.Add(file); iterator++; } return fileList.Count == 0; } void ProcessFileNode(TreeNode node) { SEItem shellEx = (SEItem)node.Tag; //reconstruct full (File not treeView) path string newPath = (node.Index * spaceBetweenItems).ToString("D2") + "." + shellEx.GetLogicalFileName(); TreeNode child = node; TreeNode parent; while ((parent = child.Parent) != null) { newPath = Path.Combine((parent.Index * spaceBetweenItems).ToString("D2") + "." + (parent.Tag as SEItem).GetLogicalFileName(), newPath); child = parent; } newPath = Path.Combine(baseDirectory, newPath); //Trace.WriteLine(newPath); if (newPath != shellEx.location) { if (!Directory.Exists(Path.GetDirectoryName(newPath))) Directory.CreateDirectory(Path.GetDirectoryName(newPath)); File.Move(shellEx.location, newPath); } } void ProcessDirNode(TreeNodeCollection nodes) { ArrayList dirs = new ArrayList(); foreach (TreeNode node in nodes) { if ((node.Tag as SEItem).isDir) dirs.Add(node); else ProcessFileNode(node); } foreach (TreeNode node in dirs) ProcessDirNode(node.Nodes); } private void browseBtn_Click(object sender, EventArgs e) { Process.Start("explorer.exe", "/e, \"" + Environment.ExpandEnvironmentVariables(@"%CSSCRIPT_DIR%\Lib\ShellExtensions\CS-Script") + "\""); } private void helpBtn_Click(object sender, EventArgs e) { Process.Start(Environment.ExpandEnvironmentVariables(@"%windir%\System32\rundll32.exe"), "\"" + Environment.ExpandEnvironmentVariables(@"%CSSCRIPT_DIR%\Lib\ShellExtensions\CS-Script\ShellExt.cs.{25D84CB0-7345-11D3-A4A1-0080C8ECFED4}.dll") + "\", Help"); } private void ShellExForm_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.F5) RefreshTreeView(); } private void refreshBtn_Click(object sender, EventArgs e) { RefreshTreeView(); } private void editBtn_Click(object sender, EventArgs e) { TreeNode node = treeView1.SelectedNode; if (node != null) Process.Start("notepad.exe", "\"" + (node.Tag as SEItem).location + "\""); } private void cancelBtn_Click(object sender, EventArgs e) { Close(); } } } class Script { const string usage = "Usage: cscscript shellEx ...\nStarts configuration console for CS-Script Advanced Shell Extension.\n"; static public void Main(string[] args) { if (args.Length == 1 && (args[0] == "?" || args[0] == "/?" || args[0] == "-?" || args[0].ToLower() == "help")) Console.WriteLine(usage); else Application.Run(new CSSScript.ShellExForm()); } }
using System.Collections.Generic; namespace SharpKit.JavaScript.Ast { partial class JsNode { public virtual void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public virtual R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsStatement { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } //partial class JsYieldStatement //{ // public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } // public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } //} //partial class JsYieldReturnStatement //{ // public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } // public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } //} //partial class JsYieldBreakStatement //{ // public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } // public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } //} partial class JsUnit { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsExternalFileUnit { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsExpression { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsNodeList { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsCodeStatement { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsSwitchStatement { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsSwitchSection { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsSwitchLabel { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsWhileStatement { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsDoWhileStatement { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsIfStatement { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsUseStrictStatement { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsForStatement { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsForInStatement { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsContinueStatement { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsBlock { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsThrowStatement { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsTryStatement { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsBreakStatement { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsExpressionStatement { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsReturnStatement { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsVariableDeclarationStatement { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsCommentStatement { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsConditionalExpression { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsAssignmentExpression { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsParenthesizedExpression { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsBinaryExpression { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsPostUnaryExpression { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsPreUnaryExpression { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsJsonObjectExpression { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsStringExpression { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsNumberExpression { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsRegexExpression { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsNullExpression { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsVariableDeclarationExpression { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsVariableDeclarator { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsNewObjectExpression { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsFunction { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsInvocationExpression { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsIndexerAccessExpression { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsMemberExpression { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsThis { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsJsonArrayExpression { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsStatementExpressionList { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsCatchClause { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsJsonMember { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsCodeExpression { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } partial class JsJsonNameValue { public override void Visit(IJsNodeVisitor visitor) { visitor.Visit(this); } public override R Visit<R>(IJsNodeVisitor<R> visitor) { return visitor.Visit(this); } } public partial interface IJsNodeVisitor { void Visit(JsNode node); void Visit(JsStatement node); //void Visit(JsYieldStatement node); //void Visit(JsYieldReturnStatement node); //void Visit(JsYieldBreakStatement node); void Visit(JsUnit node); void Visit(JsExternalFileUnit node); void Visit(JsExpression node); void Visit(JsNodeList node); void Visit(JsCodeStatement node); void Visit(JsSwitchStatement node); void Visit(JsSwitchSection node); void Visit(JsSwitchLabel node); void Visit(JsWhileStatement node); void Visit(JsDoWhileStatement node); void Visit(JsIfStatement node); void Visit(JsUseStrictStatement node); void Visit(JsForStatement node); void Visit(JsForInStatement node); void Visit(JsContinueStatement node); void Visit(JsBlock node); void Visit(JsThrowStatement node); void Visit(JsTryStatement node); void Visit(JsBreakStatement node); void Visit(JsExpressionStatement node); void Visit(JsReturnStatement node); void Visit(JsVariableDeclarationStatement node); void Visit(JsCommentStatement node); void Visit(JsConditionalExpression node); void Visit(JsAssignmentExpression node); void Visit(JsParenthesizedExpression node); void Visit(JsBinaryExpression node); void Visit(JsPostUnaryExpression node); void Visit(JsPreUnaryExpression node); void Visit(JsJsonObjectExpression node); void Visit(JsStringExpression node); void Visit(JsNumberExpression node); void Visit(JsRegexExpression node); void Visit(JsNullExpression node); void Visit(JsVariableDeclarationExpression node); void Visit(JsVariableDeclarator node); void Visit(JsNewObjectExpression node); void Visit(JsFunction node); void Visit(JsInvocationExpression node); void Visit(JsIndexerAccessExpression node); void Visit(JsMemberExpression node); void Visit(JsThis node); void Visit(JsJsonArrayExpression node); void Visit(JsStatementExpressionList node); void Visit(JsCatchClause node); void Visit(JsJsonMember node); void Visit(JsCodeExpression node); void Visit(JsJsonNameValue node); } public partial interface IJsNodeVisitor<R> { R Visit(JsNode node); R Visit(JsStatement node); //R Visit(JsYieldStatement node); //R Visit(JsYieldReturnStatement node); //R Visit(JsYieldBreakStatement node); R Visit(JsUnit node); R Visit(JsExternalFileUnit node); R Visit(JsExpression node); R Visit(JsNodeList node); R Visit(JsCodeStatement node); R Visit(JsSwitchStatement node); R Visit(JsSwitchSection node); R Visit(JsSwitchLabel node); R Visit(JsWhileStatement node); R Visit(JsDoWhileStatement node); R Visit(JsIfStatement node); R Visit(JsUseStrictStatement node); R Visit(JsForStatement node); R Visit(JsForInStatement node); R Visit(JsContinueStatement node); R Visit(JsBlock node); R Visit(JsThrowStatement node); R Visit(JsTryStatement node); R Visit(JsBreakStatement node); R Visit(JsExpressionStatement node); R Visit(JsReturnStatement node); R Visit(JsVariableDeclarationStatement node); R Visit(JsCommentStatement node); R Visit(JsConditionalExpression node); R Visit(JsAssignmentExpression node); R Visit(JsParenthesizedExpression node); R Visit(JsBinaryExpression node); R Visit(JsPostUnaryExpression node); R Visit(JsPreUnaryExpression node); R Visit(JsJsonObjectExpression node); R Visit(JsStringExpression node); R Visit(JsNumberExpression node); R Visit(JsRegexExpression node); R Visit(JsNullExpression node); R Visit(JsVariableDeclarationExpression node); R Visit(JsVariableDeclarator node); R Visit(JsNewObjectExpression node); R Visit(JsFunction node); R Visit(JsInvocationExpression node); R Visit(JsIndexerAccessExpression node); R Visit(JsMemberExpression node); R Visit(JsThis node); R Visit(JsJsonArrayExpression node); R Visit(JsStatementExpressionList node); R Visit(JsCatchClause node); R Visit(JsJsonMember node); R Visit(JsCodeExpression node); R Visit(JsJsonNameValue node); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.Diagnostics; namespace System.IO.Packaging { /// <summary> /// This class represents the a PackagePart within a container. /// This is a part of the Packaging Layer APIs /// </summary> public abstract class PackagePart { #region Protected Constructor /// <summary> /// Protected constructor for the abstract Base class. /// This is the current contract between the subclass and the base class /// If we decide some registration mechanism then this might change /// /// You should use this constructor in the rare case when you do not have /// the content type information related to this part and would prefer to /// obtain it later as required. /// /// These parts have the CompressionOption as NotCompressed by default. /// /// NOTE : If you are using this constructor from your subclass or passing a null /// for the content type parameter, be sure to implement the GetContentTypeCore /// method, as that will be called to get the content type value. This is provided /// to enable lazy initialization of the ContentType property. /// /// </summary> /// <param name="package">Package in which this part is being created</param> /// <param name="partUri">uri of the part</param> /// <exception cref="ArgumentNullException">If parameter "package" is null</exception> /// <exception cref="ArgumentNullException">If parameter "partUri" is null</exception> protected PackagePart(Package package, Uri partUri) : this(package, partUri, null, CompressionOption.NotCompressed) { } /// <summary> /// Protected constructor for the abstract Base class. /// This is the current contract between the subclass and the base class /// If we decide some registration mechanism then this might change /// /// These parts have the CompressionOption as NotCompressed by default. /// /// NOTE : If you are using this constructor from your subclass or passing a null /// for the content type parameter, be sure to implement the GetContentTypeCore /// method, as that will be called to get the content type value. This is provided /// to enable lazy initialization of the ContentType property. /// /// </summary> /// <param name="package">Package in which this part is being created</param> /// <param name="partUri">uri of the part</param> /// <param name="contentType">Content Type of the part, can be null if the value /// is unknown at the time of construction. However the value has to be made /// available anytime the ContentType property is called. A null value only indicates /// that the value will be provided later. Every PackagePart must have a valid /// Content Type</param> /// <exception cref="ArgumentNullException">If parameter "package" is null</exception> /// <exception cref="ArgumentNullException">If parameter "partUri" is null</exception> /// <exception cref="ArgumentException">If parameter "partUri" does not conform to the valid partUri syntax</exception> protected PackagePart(Package package, Uri partUri, string contentType) : this(package, partUri, contentType, CompressionOption.NotCompressed) { } /// <summary> /// Protected constructor for the abstract Base class. /// This is the current contract between the subclass and the base class /// If we decide some registration mechanism then this might change /// /// NOTE : If you are using this constructor from your subclass or passing a null /// for the content type parameter, be sure to implement the GetContentTypeCore /// method, as that will be called to get the content type value. This is provided /// to enable lazy initialization of the ContentType property. /// /// </summary> /// <param name="package">Package in which this part is being created</param> /// <param name="partUri">uri of the part</param> /// <param name="contentType">Content Type of the part, can be null if the value /// is unknown at the time of construction. However the value has to be made /// available anytime the ContentType property is called. A null value only indicates /// that the value will be provided later. Every PackagePart must have a valid /// Content Type</param> /// <param name="compressionOption">compression option for this part</param> /// <exception cref="ArgumentNullException">If parameter "package" is null</exception> /// <exception cref="ArgumentNullException">If parameter "partUri" is null</exception> /// <exception cref="ArgumentOutOfRangeException">If CompressionOption enumeration [compressionOption] does not have one of the valid values</exception> /// <exception cref="ArgumentException">If parameter "partUri" does not conform to the valid partUri syntax</exception> protected PackagePart(Package package, Uri partUri, string contentType, CompressionOption compressionOption) { if (package == null) throw new ArgumentNullException(nameof(package)); if (partUri == null) throw new ArgumentNullException(nameof(partUri)); Package.ThrowIfCompressionOptionInvalid(compressionOption); _uri = PackUriHelper.ValidatePartUri(partUri); _container = package; if (contentType == null) _contentType = null; else _contentType = new ContentType(contentType); _requestedStreams = null; _compressionOption = compressionOption; _isRelationshipPart = PackUriHelper.IsRelationshipPartUri(partUri); } #endregion Protected Constructor #region Public Properties /// <summary> /// The Uri for this PackagePart. It is always relative to the Package Root /// The PackagePart properties can not be accessed if the parent container is closed. /// </summary> /// <value></value> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> public Uri Uri { get { CheckInvalidState(); return _uri; } } /// <summary> /// The Content type of the stream that is represented by this part. /// The PackagePart properties can not be accessed if the parent container is closed. /// The content type value can be provided by the underlying physical format /// implementation at the time of creation of the Part object ( constructor ) or /// We can initialize it in a lazy manner when the ContentType property is called /// called for the first time by calling the GetContentTypeCore method. /// Note: This method GetContentTypeCore() is only for lazy initialization of the Content /// type value and will only be called once. There is no way to change the content type of /// the part once it has been assigned. /// </summary> /// <value>Content Type of the Part [can never return null] </value> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="InvalidOperationException">If the subclass fails to provide a non-null content type value.</exception> public string ContentType { get { CheckInvalidState(); if (_contentType == null) { //Lazy initialization for the content type string contentType = GetContentTypeCore(); if (contentType == null) { // We have seen this bug in the past and have said that this should be // treated as exception. If we get a null content type, it's an error. // We want to throw this exception so that anyone sub-classing this class // should not be setting the content type to null. Its like any other // parameter validation. This is the only place we can validate it. We // throw an ArgumentNullException, when the content type is set to null // in the constructor. // // We cannot get rid of this exception. At most, we can change it to // Debug.Assert. But then client code will see an Assert if they make // a mistake and that is also not desirable. // // PackagePart is a public API. throw new InvalidOperationException(SR.NullContentTypeProvided); } _contentType = new ContentType(contentType); } return _contentType.ToString(); } } /// <summary> /// The parent container for this PackagePart /// The PackagePart properties can not be accessed if the parent container is closed. /// </summary> /// <value></value> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> public Package Package { get { CheckInvalidState(); return _container; } } /// <summary> /// CompressionOption class that was provided as a parameter during the original CreatePart call. /// The PackagePart properties can not be accessed if the parent container is closed. /// </summary> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> public CompressionOption CompressionOption { get { CheckInvalidState(); return _compressionOption; } } #endregion Public Properties #region Public Methods #region Content Type Method /// <summary> /// Custom Implementation for the GetContentType Method /// This method should only be implemented by those physical format implementors where /// the value for the content type cannot be provided at the time of construction of /// Part object and if calculating the content type value is a non-trivial or costly /// operation. The return value has to be a valid ContentType. This method will be used in /// real corner cases. The most common usage should be to provide the content type in the /// constructor. /// This method is only for lazy initialization of the Content type value and will only /// be called once. There is no way to change the content type of the part once it is /// assigned. /// </summary> /// <returns>Content type for the Part</returns> /// <exception cref="NotSupportedException">By default, this method throws a NotSupportedException. If a subclass wants to /// initialize the content type for a PackagePart in a lazy manner they must override this method.</exception> protected virtual string GetContentTypeCore() { throw new NotSupportedException(SR.GetContentTypeCoreNotImplemented); } #endregion Content Type Method #region Stream Methods /// <summary> /// Returns the underlying stream that is represented by this part /// with the default FileMode and FileAccess /// Note: If you are requesting a stream for a relationship part and /// at the same time using relationship APIs to manipulate relationships, /// the final persisted data will depend on which data gets flushed last. /// </summary> /// <returns></returns> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="IOException">If the subclass fails to provide a non-null stream object</exception> public Stream GetStream() { CheckInvalidState(); return GetStream(FileMode.OpenOrCreate, _container.FileOpenAccess); } /// <summary> /// Returns the underlying stream in the specified mode and the /// default FileAccess /// Note: If you are requesting a stream for a relationship part for editing /// and at the same time using relationship APIs to manipulate relationships, /// the final persisted data will depend on which data gets flushed last. /// </summary> /// <param name="mode"></param> /// <returns></returns> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="ArgumentOutOfRangeException">If FileMode enumeration [mode] does not have one of the valid values</exception> /// <exception cref="IOException">If FileAccess.Read is provided and FileMode values are any of the following - /// FileMode.Create, FileMode.CreateNew, FileMode.Truncate, FileMode.Append</exception> /// <exception cref="IOException">If the mode and access for the Package and the Stream are not compatible</exception> /// <exception cref="IOException">If the subclass fails to provide a non-null stream object</exception> public Stream GetStream(FileMode mode) { CheckInvalidState(); return GetStream(mode, _container.FileOpenAccess); } /// <summary> /// Returns the underlying stream that is represented by this part /// in the specified mode with the access. /// Note: If you are requesting a stream for a relationship part and /// at the same time using relationship APIs to manipulate relationships, /// the final persisted data will depend on which data gets flushed last. /// </summary> /// <param name="mode"></param> /// <param name="access"></param> /// <returns></returns> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="ArgumentOutOfRangeException">If FileMode enumeration [mode] does not have one of the valid values</exception> /// <exception cref="ArgumentOutOfRangeException">If FileAccess enumeration [access] does not have one of the valid values</exception> /// <exception cref="IOException">If FileAccess.Read is provided and FileMode values are any of the following - /// FileMode.Create, FileMode.CreateNew, FileMode.Truncate, FileMode.Append</exception> /// <exception cref="IOException">If the mode and access for the Package and the Stream are not compatible</exception> /// <exception cref="IOException">If the subclass fails to provide a non-null stream object</exception> public Stream GetStream(FileMode mode, FileAccess access) { CheckInvalidState(); ThrowIfOpenAccessModesAreIncompatible(mode, access); if (mode == FileMode.CreateNew) throw new ArgumentException(SR.CreateNewNotSupported); if (mode == FileMode.Truncate) throw new ArgumentException(SR.TruncateNotSupported); Stream s = GetStreamCore(mode, access); if (s == null) throw new IOException(SR.NullStreamReturned); //Detect if any stream implementations are returning all three //properties - CanSeek, CanWrite and CanRead as false. Such a //stream should be pretty much useless. And as per current programming //practice, these properties are all false, when the stream has been //disposed. Debug.Assert(!IsStreamClosed(s)); //Lazy init if (_requestedStreams == null) _requestedStreams = new List<Stream>(); //Default capacity is 4 //Delete all the closed streams from the _requestedStreams list. //Each time a new stream is handed out, we go through the list //to clean up streams that were handed out and have been closed. //Thus those stream can be garbage collected and we will avoid //keeping around stream objects that have been disposed CleanUpRequestedStreamsList(); _requestedStreams.Add(s); return s; } /// <summary> /// Custom Implementation for the GetSream Method /// </summary> /// <param name="mode"></param> /// <param name="access"></param> /// <returns></returns> protected abstract Stream GetStreamCore(FileMode mode, FileAccess access); #endregion Stream Methods #region PackageRelationship Methods /// <summary> /// Adds a relationship to this PackagePart with the Target PackagePart specified as the Uri /// Initial and trailing spaces in the name of the PackageRelationship are trimmed. /// </summary> /// <param name="targetUri"></param> /// <param name="targetMode">Enumeration indicating the base uri for the target uri</param> /// <param name="relationshipType">PackageRelationship type, having uri like syntax that is used to /// uniquely identify the role of the relationship</param> /// <returns></returns> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="IOException">If the package is readonly, it cannot be modified</exception> /// <exception cref="ArgumentNullException">If parameter "targetUri" is null</exception> /// <exception cref="ArgumentNullException">If parameter "relationshipType" is null</exception> /// <exception cref="ArgumentOutOfRangeException">If parameter "targetMode" enumeration does not have a valid value</exception> /// <exception cref="ArgumentException">If TargetMode is TargetMode.Internal and the targetUri is an absolute Uri </exception> /// <exception cref="ArgumentException">If relationship is being targeted to a relationship part</exception> public PackageRelationship CreateRelationship(Uri targetUri, TargetMode targetMode, string relationshipType) { return CreateRelationship(targetUri, targetMode, relationshipType, null); } /// <summary> /// Adds a relationship to this PackagePart with the Target PackagePart specified as the Uri /// Initial and trailing spaces in the name of the PackageRelationship are trimmed. /// </summary> /// <param name="targetUri"></param> /// <param name="targetMode">Enumeration indicating the base uri for the target uri</param> /// <param name="relationshipType">PackageRelationship type, having uri like syntax that is used to /// uniquely identify the role of the relationship</param> /// <param name="id">String that conforms to the xsd:ID datatype. Unique across the source's /// relationships. Null is OK (ID will be generated). An empty string is an invalid XML ID.</param> /// <returns></returns> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="IOException">If the package is readonly, it cannot be modified</exception> /// <exception cref="ArgumentNullException">If parameter "targetUri" is null</exception> /// <exception cref="ArgumentNullException">If parameter "relationshipType" is null</exception> /// <exception cref="ArgumentOutOfRangeException">If parameter "targetMode" enumeration does not have a valid value</exception> /// <exception cref="ArgumentException">If TargetMode is TargetMode.Internal and the targetUri is an absolute Uri </exception> /// <exception cref="ArgumentException">If relationship is being targeted to a relationship part</exception> /// <exception cref="System.Xml.XmlException">If parameter "id" is not a valid Xsd Id</exception> /// <exception cref="System.Xml.XmlException">If an id is provided in the method, and its not unique</exception> public PackageRelationship CreateRelationship(Uri targetUri, TargetMode targetMode, string relationshipType, string id) { CheckInvalidState(); _container.ThrowIfReadOnly(); EnsureRelationships(); //All parameter validation is done in the following method return _relationships.Add(targetUri, targetMode, relationshipType, id); } /// <summary> /// Deletes a relationship from the PackagePart. This is done based on the /// relationship's ID. The target PackagePart is not affected by this operation. /// </summary> /// <param name="id">The ID of the relationship to delete. An invalid ID will not /// throw an exception, but nothing will be deleted.</param> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="IOException">If the package is readonly, it cannot be modified</exception> /// <exception cref="ArgumentNullException">If parameter "id" is null</exception> /// <exception cref="System.Xml.XmlException">If parameter "id" is not a valid Xsd Id</exception> public void DeleteRelationship(string id) { CheckInvalidState(); _container.ThrowIfReadOnly(); if (id == null) throw new ArgumentNullException(nameof(id)); InternalRelationshipCollection.ThrowIfInvalidXsdId(id); EnsureRelationships(); _relationships.Delete(id); } /// <summary> /// Returns a collection of all the Relationships that are /// owned by this PackagePart /// </summary> /// <returns></returns> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="IOException">If the package is write only, no information can be retrieved from it</exception> public PackageRelationshipCollection GetRelationships() { //All the validations for dispose and file access are done in the //GetRelationshipsHelper method. return GetRelationshipsHelper(null); } /// <summary> /// Returns a collection of filtered Relationships that are /// owned by this PackagePart /// The relationshipType string is compared with the type of the relationships /// in a case sensitive and culture ignorant manner. /// </summary> /// <returns></returns> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="IOException">If the package is write only, no information can be retrieved from it</exception> /// <exception cref="ArgumentNullException">If parameter "relationshipType" is null</exception> /// <exception cref="ArgumentException">If parameter "relationshipType" is an empty string</exception> public PackageRelationshipCollection GetRelationshipsByType(string relationshipType) { //These checks are made in the GetRelationshipsHelper as well, but we make them //here as we need to perform parameter validation CheckInvalidState(); _container.ThrowIfWriteOnly(); if (relationshipType == null) throw new ArgumentNullException(nameof(relationshipType)); InternalRelationshipCollection.ThrowIfInvalidRelationshipType(relationshipType); return GetRelationshipsHelper(relationshipType); } /// <summary> /// Retrieve a relationship per ID. /// </summary> /// <param name="id">The relationship ID.</param> /// <returns>The relationship with ID 'id' or throw an exception if not found.</returns> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="IOException">If the package is write only, no information can be retrieved from it</exception> /// <exception cref="ArgumentNullException">If parameter "id" is null</exception> /// <exception cref="System.Xml.XmlException">If parameter "id" is not a valid Xsd Id</exception> /// <exception cref="InvalidOperationException">If the requested relationship does not exist in the Package</exception> public PackageRelationship GetRelationship(string id) { //All the validations for dispose and file access are done in the //GetRelationshipHelper method. PackageRelationship returnedRelationship = GetRelationshipHelper(id); if (returnedRelationship == null) throw new InvalidOperationException(SR.PackagePartRelationshipDoesNotExist); else return returnedRelationship; } /// <summary> /// Returns whether there is a relationship with the specified ID. /// </summary> /// <param name="id">The relationship ID.</param> /// <returns>true iff a relationship with ID 'id' is defined on this source.</returns> /// <exception cref="InvalidOperationException">If this part has been deleted</exception> /// <exception cref="InvalidOperationException">If the parent package has been closed or disposed</exception> /// <exception cref="IOException">If the package is write only, no information can be retrieved from it</exception> /// <exception cref="ArgumentNullException">If parameter "id" is null</exception> /// <exception cref="System.Xml.XmlException">If parameter "id" is not a valid Xsd Id</exception> public bool RelationshipExists(string id) { //All the validations for dispose and file access are done in the //GetRelationshipHelper method. return (GetRelationshipHelper(id) != null); } #endregion PackageRelationship Methods #endregion Public Methods #region Internal Properties internal bool IsRelationshipPart { get { return _isRelationshipPart; } } //This property can be set to indicate if the part has been deleted internal bool IsDeleted { get { return _deleted; } set { _deleted = value; } } //This property can be set to indicate if the part has been deleted internal bool IsClosed { get { return _disposed; } } /// <summary> /// This property returns the content type of the part /// as a validated strongly typed ContentType object /// </summary> internal ContentType ValidatedContentType { get { return _contentType; } } #endregion Internal Properties #region Internal Methods //Delete all the relationships for this part internal void ClearRelationships() { if (_relationships != null) _relationships.Clear(); } //Flush all the streams that are currently opened for this part and the relationships for this part //Note: This method is never be called on a deleted part internal void Flush() { Debug.Assert(_deleted != true, "PackagePart.Flush should never be called on a deleted part"); if (_requestedStreams != null) { foreach (Stream s in _requestedStreams) { // Streams in this list are never set to null, so we do not need to check for // stream being null; However it could be closed by some external code. In that case // this property (CanWrite) will still be accessible and we can check to see // whether we can call flush or no. if (s.CanWrite) s.Flush(); } } // Relationships for this part should have been flushed earlier in the Package.Flush method. } //Close all the streams that are open for this part. internal void Close() { if (!_disposed) { try { if (_requestedStreams != null) { //Adding this extra check here to optimize delete operation //Every time we delete a part we close it before deleting to //ensure that its deleted in a valid state. However, we do not //need to persist any changes if the part is being deleted. if (!_deleted) { foreach (Stream s in _requestedStreams) { s.Dispose(); } } _requestedStreams.Clear(); } // Relationships for this part should have been flushed/closed earlier in the Package.Close method. } finally { _requestedStreams = null; //InternalRelationshipCollection is not required any more _relationships = null; //Once the container is closed there is no way to get to the stream or any other part //in the container. _container = null; //We do not need to explicitly call GC.SuppressFinalize(this) _disposed = true; } } } /// <summary> /// write the relationships part /// </summary> /// <remarks> /// </remarks> internal void FlushRelationships() { Debug.Assert(_deleted != true, "PackagePart.FlushRelationsips should never be called on a deleted part"); // flush relationships if (_relationships != null && _container.FileOpenAccess != FileAccess.Read) { _relationships.Flush(); } } internal void CloseRelationships() { if (!_deleted) { //Flush the relationships for this part. FlushRelationships(); } } #endregion Internal Methods #region Private Methods // lazy init private void EnsureRelationships() { if (_relationships == null) { // check here ThrowIfRelationship(); // obtain the relationships from the PackageRelationship part (if available) _relationships = new InternalRelationshipCollection(this); } } //Make sure that the access modes for the container and the part are compatible private void ThrowIfOpenAccessModesAreIncompatible(FileMode mode, FileAccess access) { Package.ThrowIfFileModeInvalid(mode); Package.ThrowIfFileAccessInvalid(access); //Creating a part using a readonly stream. if (access == FileAccess.Read && (mode == FileMode.Create || mode == FileMode.CreateNew || mode == FileMode.Truncate || mode == FileMode.Append)) throw new IOException(SR.UnsupportedCombinationOfModeAccess); //Incompatible access modes between container and part stream. if ((_container.FileOpenAccess == FileAccess.Read && access != FileAccess.Read) || (_container.FileOpenAccess == FileAccess.Write && access != FileAccess.Write)) throw new IOException(SR.ContainerAndPartModeIncompatible); } //Check if the part is in an invalid state private void CheckInvalidState() { ThrowIfPackagePartDeleted(); ThrowIfParentContainerClosed(); } //If the parent container is closed then the operations on this part like getting stream make no sense private void ThrowIfParentContainerClosed() { if (_container == null) throw new InvalidOperationException(SR.ParentContainerClosed); } //If the part has been deleted then we throw private void ThrowIfPackagePartDeleted() { if (_deleted == true) throw new InvalidOperationException(SR.PackagePartDeleted); } // some operations are invalid if we are a relationship part private void ThrowIfRelationship() { if (IsRelationshipPart) throw new InvalidOperationException(SR.RelationshipPartsCannotHaveRelationships); } /// <summary> /// Retrieve a relationship per ID. /// </summary> /// <param name="id">The relationship ID.</param> /// <returns>The relationship with ID 'id' or null if not found.</returns> private PackageRelationship GetRelationshipHelper(string id) { CheckInvalidState(); _container.ThrowIfWriteOnly(); if (id == null) throw new ArgumentNullException(nameof(id)); InternalRelationshipCollection.ThrowIfInvalidXsdId(id); EnsureRelationships(); return _relationships.GetRelationship(id); } /// <summary> /// Returns a collection of all the Relationships that are /// owned by this PackagePart, based on the filter string /// </summary> /// <returns></returns> private PackageRelationshipCollection GetRelationshipsHelper(string filterString) { CheckInvalidState(); _container.ThrowIfWriteOnly(); EnsureRelationships(); //Internally null is used to indicate that no filter string was specified and //and all the relationships should be returned. return new PackageRelationshipCollection(_relationships, filterString); } //Deletes all the streams that have been closed from the _requestedStreams list. private void CleanUpRequestedStreamsList() { if (_requestedStreams != null) { for (int i = _requestedStreams.Count - 1; i >= 0; i--) { if (IsStreamClosed(_requestedStreams[i])) _requestedStreams.RemoveAt(i); } } } //Detect if the stream has been closed. //When a stream is closed the three flags - CanSeek, CanRead and CanWrite //return false. These properties do not throw ObjectDisposedException. //So we rely on the values of these properties to determine if a stream //has been closed. private bool IsStreamClosed(Stream s) { return !s.CanRead && !s.CanSeek && !s.CanWrite; } #endregion Private Methods #region Private Members private readonly PackUriHelper.ValidatedPartUri _uri; private Package _container; private ContentType _contentType; private List<Stream> _requestedStreams; private InternalRelationshipCollection _relationships; private readonly CompressionOption _compressionOption = CompressionOption.NotCompressed; private bool _disposed; private bool _deleted; private readonly bool _isRelationshipPart; #endregion Private Members } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace RoslynPad.Roslyn.SignatureHelp { [Export(typeof(ISignatureHelpProvider)), Shared] internal sealed class AggregateSignatureHelpProvider : ISignatureHelpProvider { private ImmutableArray<Microsoft.CodeAnalysis.SignatureHelp.ISignatureHelpProvider> _providers; [ImportingConstructor] public AggregateSignatureHelpProvider([ImportMany] IEnumerable<Lazy<Microsoft.CodeAnalysis.SignatureHelp.ISignatureHelpProvider, OrderableLanguageMetadata>> providers) { _providers = providers.Where(x => x.Metadata.Language == LanguageNames.CSharp) .Select(x => x.Value).ToImmutableArray(); } public bool IsTriggerCharacter(char ch) { return _providers.Any(p => p.IsTriggerCharacter(ch)); } public bool IsRetriggerCharacter(char ch) { return _providers.Any(p => p.IsRetriggerCharacter(ch)); } public async Task<SignatureHelpItems?> GetItemsAsync(Document document, int position, SignatureHelpTriggerInfo trigger, CancellationToken cancellationToken) { Microsoft.CodeAnalysis.SignatureHelp.SignatureHelpItems? bestItems = null; // TODO(cyrusn): We're calling into extensions, we need to make ourselves resilient // to the extension crashing. foreach (var provider in _providers) { cancellationToken.ThrowIfCancellationRequested(); var currentItems = await provider.GetItemsAsync(document, position, trigger.Inner, cancellationToken).ConfigureAwait(false); if (currentItems != null && currentItems.ApplicableSpan.IntersectsWith(position)) { // If another provider provides sig help items, then only take them if they // start after the last batch of items. i.e. we want the set of items that // conceptually are closer to where the caret position is. This way if you have: // // Foo(new Bar($$ // // Then invoking sig help will only show the items for "new Bar(" and not also // the items for "Foo(..." if (IsBetter(bestItems, currentItems.ApplicableSpan)) { bestItems = currentItems; } } } if (bestItems != null) { var items = new SignatureHelpItems(bestItems); if (items.SelectedItemIndex == null) { var selection = DefaultSignatureHelpSelector.GetSelection(items.Items, null, false, items.ArgumentIndex, items.ArgumentCount, items.ArgumentName, isCaseSensitive: true); if (selection.SelectedItem != null) { items.SelectedItemIndex = items.Items.IndexOf(selection.SelectedItem); } } return items; } return null; } private static bool IsBetter(Microsoft.CodeAnalysis.SignatureHelp.SignatureHelpItems? bestItems, TextSpan? currentTextSpan) { return bestItems == null || currentTextSpan?.Start > bestItems.ApplicableSpan.Start; } private struct SignatureHelpSelection { public SignatureHelpSelection(SignatureHelpItem selectedItem, bool userSelected, int? selectedParameter) { SelectedItem = selectedItem; UserSelected = userSelected; SelectedParameter = selectedParameter; } public int? SelectedParameter { get; } public SignatureHelpItem SelectedItem { get; } public bool UserSelected { get; } } private static class DefaultSignatureHelpSelector { public static SignatureHelpSelection GetSelection( IList<SignatureHelpItem> items, SignatureHelpItem? selectedItem, bool userSelected, int argumentIndex, int argumentCount, string? argumentName, bool isCaseSensitive) { selectedItem = SelectBestItem(selectedItem, ref userSelected, items, argumentIndex, argumentCount, argumentName, isCaseSensitive); var selectedParameter = GetSelectedParameter(selectedItem, argumentIndex, argumentName, isCaseSensitive); return new SignatureHelpSelection(selectedItem, userSelected, selectedParameter); } private static int GetSelectedParameter(SignatureHelpItem bestItem, int parameterIndex, string? parameterName, bool isCaseSensitive) { if (!string.IsNullOrEmpty(parameterName)) { var comparer = isCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase; var selected = bestItem.Parameters.Select((p, index) => (p, index)).FirstOrDefault(p => comparer.Equals(p.p.Name, parameterName)); if (selected.p != null) { return selected.index; } } return parameterIndex; } private static SignatureHelpItem SelectBestItem(SignatureHelpItem? currentItem, ref bool userSelected, IList<SignatureHelpItem> filteredItems, int selectedParameter, int argumentCount, string? name, bool isCaseSensitive) { // If the current item is still applicable, then just keep it. if (currentItem != null && filteredItems.Contains(currentItem) && IsApplicable(currentItem, argumentCount, name, isCaseSensitive)) { // If the current item was user-selected, we keep it as such. return currentItem; } // If the current item is no longer applicable, we'll be choosing a new one, // which was definitely not previously user-selected. userSelected = false; // Try to find the first applicable item. If there is none, then that means the // selected parameter was outside the bounds of all methods. i.e. all methods only // went up to 3 parameters, and selected parameter is 3 or higher. In that case, // just pick the very last item as it is closest in parameter count. var result = filteredItems.FirstOrDefault(i => IsApplicable(i, argumentCount, name, isCaseSensitive)); if (result != null) { currentItem = result; return currentItem; } // if we couldn't find a best item, and they provided a name, then try again without // a name. if (name != null) { return SelectBestItem(currentItem, ref userSelected, filteredItems, selectedParameter, argumentCount, null, isCaseSensitive); } // If we don't have an item that can take that number of parameters, then just pick // the last item. Or stick with the current item if the last item isn't any better. var lastItem = filteredItems.Last(); if (currentItem != null && (currentItem.IsVariadic || currentItem.Parameters.Length == lastItem.Parameters.Length)) { return currentItem; } return lastItem; } private static bool IsApplicable(SignatureHelpItem item, int argumentCount, string? name, bool isCaseSensitive) { // If they provided a name, then the item is only valid if it has a parameter that // matches that name. if (name != null) { var comparer = isCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase; return item.Parameters.Any(p => comparer.Equals(p.Name, name)); } // An item is applicable if it has at least as many parameters as the selected // parameter index. i.e. if it has 2 parameters and we're at index 0 or 1 then it's // applicable. However, if it has 2 parameters and we're at index 2, then it's not // applicable. if (item.Parameters.Length >= argumentCount) { return true; } // However, if it is variadic then it is applicable as it can take any number of // items. if (item.IsVariadic) { return true; } // Also, we special case 0. that's because if the user has "Goo(" and goo takes no // arguments, then we'll see that it's arg count is 0. We still want to consider // any item applicable here though. return argumentCount == 0; } } } }
using AirlineTicketOffice.Main.Services.Navigation; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using System.Windows.Input; using GalaSoft.MvvmLight.Messaging; using AirlineTicketOffice.Main.Services.Messenger; using System; using System.Windows; using AirlineTicketOffice.Main.Services.Dialog; using AirlineTicketOffice.Model.IRepository; using System.Threading.Tasks; using AirlineTicketOffice.Main.Properties; namespace AirlineTicketOffice.Main.ViewModel { /// <summary> /// This class contains properties that the main View can data bind to. /// <para> /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel. /// </para> /// <para> /// You can also use Blend to data bind with the tool's support. /// </para> /// <para> /// See http://www.galasoft.ch/mvvm /// </para> /// </summary> public class MainViewModel : ViewModelBase { #region constructor /// <summary> /// Initializes a new instance of the MainViewModel class. /// </summary> public MainViewModel(IMainNavigationService navigationService, IDialogMessage dialogeMessage, ITicketRepository ticketRepository) { this.ForegroundForUser = "#ffffff"; _navigationService = navigationService; _dialogMessage = dialogeMessage; _ticketRepository = ticketRepository; ReceiveStatusFromFlightVM(); } #endregion #region fields private readonly IMainNavigationService _navigationService; private bool connect = true; private readonly IDialogMessage _dialogMessage; private readonly ITicketRepository _ticketRepository; private string _statusWindow; private object locker = new object(); private string _ForegroundForUser; #endregion #region properties public string StatusWindow { get { return _statusWindow; } set { Set(() => StatusWindow, ref _statusWindow, value); } } public string ForegroundForUser { get { return _ForegroundForUser; } set { Set(() => ForegroundForUser, ref _ForegroundForUser, value); } } #endregion #region commands /// <summary> /// Close Main window. /// </summary> private ICommand _minimizeWindow; public ICommand MinimizeWindow { get { if (_minimizeWindow == null) { _minimizeWindow = new RelayCommand(() => { if (Application.Current.MainWindow.WindowState != WindowState.Minimized) { Application.Current.MainWindow.WindowState = WindowState.Minimized; } }); } return _minimizeWindow; } } /// <summary> /// Close Main window. /// </summary> private ICommand _closeWindow; public ICommand CloseWindow { get { if (_closeWindow == null) { _closeWindow = new RelayCommand(() => { if (Application.Current.MainWindow != null) { Application.Current.MainWindow.Close(); } }); } return _closeWindow; } } /// <summary> /// Navigate to 'NewTicket' view. /// </summary> private ICommand _getNewTicketCommand; public ICommand GetNewTicketCommand { get { if (_getNewTicketCommand == null) { _getNewTicketCommand = new RelayCommand(() => { _navigationService.NavigateTo(Resources.NewTicketViewKey); if (this.connect) this.StatusWindow = "New Ticket Window"; }); } return _getNewTicketCommand; } } /// <summary> /// Open message box 'about program'. /// </summary> private ICommand _helpCommand; public ICommand HelpCommand { get { if (_helpCommand == null) { _helpCommand = new RelayCommand(() => { if (_dialogMessage.Show() == false) { if (this.connect) this.StatusWindow = "Error Dialog About."; } }); } return _helpCommand; } } /// <summary> /// Navigate to 'AllPassengers' view. /// </summary> private ICommand _getAllPassengerCommand; public ICommand GetAllPassengerCommand { get { if (_getAllPassengerCommand == null) { _getAllPassengerCommand = new RelayCommand(() => { _navigationService.NavigateTo(Resources.AllPassengerViewKey); if (this.connect) this.StatusWindow = "All Passengers Window"; }); } return _getAllPassengerCommand; } } /// <summary> /// Navigate to 'NewPassenger' view. /// </summary> private ICommand _getNewPassengerCommand; public ICommand GetNewPassengerCommand { get { if (_getNewPassengerCommand == null) { _getNewPassengerCommand = new RelayCommand(() => { _navigationService.NavigateTo(Resources.NewPassengerViewKey); if (this.connect) this.StatusWindow = "New Passenger Window"; }); } return _getNewPassengerCommand; } } /// <summary> /// Navigate to 'purchased tickets' view. /// </summary> private ICommand _getBoughtTicketCommand; public ICommand GetBoughtTicketCommand { get { if (_getBoughtTicketCommand == null) { _getBoughtTicketCommand = new RelayCommand(() => { _navigationService.NavigateTo(Resources.BoughtTicketViewKey); if (this.connect) this.StatusWindow = "Purchased Tickets Window"; }); } return _getBoughtTicketCommand; } } /// <summary> /// Navigate to 'flights' view. /// </summary> private ICommand _getFlightsCommand; public ICommand GetFlightsCommand { get { if (_getFlightsCommand == null) { _getFlightsCommand = new RelayCommand(() => { _navigationService.NavigateTo(Resources.FlightsViewKey); if (this.connect) this.StatusWindow = "Flights Window"; }); } return _getFlightsCommand; } } /// <summary> /// Navigate to 'Tariffs' view. /// </summary> private ICommand _getTariffsCommand; public ICommand GetTariffsCommand { get { if (_getTariffsCommand == null) { _getTariffsCommand = new RelayCommand(() => { _navigationService.NavigateTo(Resources.TariffsViewKey); if (this.connect) this.StatusWindow = "Tariffs Window"; }); } return _getTariffsCommand; } } /// <summary> /// Navigate to 'Cashiers' view. /// </summary> private ICommand _getCashierCommand; public ICommand GetCashierCommand { get { if (_getCashierCommand == null) { _getCashierCommand = new RelayCommand(() => { _navigationService.NavigateTo(Resources.CashierViewKey); if (this.connect) this.StatusWindow = "Cashiers Window"; }); } return _getCashierCommand; } } /// <summary> /// Occur when the window is loaded. /// </summary> private ICommand _loadedCommand; public ICommand LoadedCommand { get { if (_loadedCommand == null) { _loadedCommand = new RelayCommand(() => { BeginLoadingMainWindow(); }); } return _loadedCommand; } set { _loadedCommand = value; } } /// <summary> /// Occur when the window is closed. /// </summary> public ICommand _closingCommand; public ICommand ClosingCommand { get { if (_closingCommand == null) { _closingCommand = new RelayCommand(() => { // some work doing...(I did not invented yet) }); } return _closingCommand; } } #endregion #region methods /// <summary> /// Localization. /// </summary> private void BeginLoadingMainWindow() { // Set culture: System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture; System.Threading.Thread.CurrentThread.CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentCulture; _navigationService.NavigateTo(Resources.NewTicketViewKey); if (this.connect) this.StatusWindow = "New Ticket Window"; CheckConnectionDB(); } /// <summary> /// Receive Status from SendNewTicketCommand(flight view model) /// </summary> private void ReceiveStatusFromFlightVM() { Messenger.Default.Register<MessageStatus>(this, (f) => { if(this.connect) this.StatusWindow = f.MessageStatusFromFlight; }); } /// <summary> /// Check existing database. /// </summary> private void CheckConnectionDB() { Task.Factory.StartNew(() => { lock (locker) { if (!_ticketRepository.CheckConnection()) { Application.Current.Dispatcher.Invoke( new Action(() => { this.ForegroundForUser = "#ff420e"; this.StatusWindow = "CAN NOT CONNECT TO DATABASE."; this.connect = false; })); } } }); } #endregion } }
using System; using System.Collections.Generic; using System.Threading; namespace LiteNetLib { internal sealed class ReliableChannel { private class PendingPacket { public NetPacket Packet; public DateTime? TimeStamp; public bool NotEmpty { get { return Packet != null; } } public NetPacket GetAndClear() { var packet = Packet; Packet = null; TimeStamp = null; return packet; } } private readonly Queue<NetPacket> _outgoingPackets; private readonly bool[] _outgoingAcks; //for send acks private readonly PendingPacket[] _pendingPackets; //for unacked packets and duplicates private readonly NetPacket[] _receivedPackets; //for order private readonly bool[] _earlyReceived; //for unordered private int _localSeqence; private int _remoteSequence; private int _localWindowStart; private int _remoteWindowStart; private readonly NetPeer _peer; private bool _mustSendAcks; private readonly double _resendDelay; private readonly bool _ordered; private readonly int _windowSize; private readonly object _pendingPacketsAccess = new object(); private readonly object _outgoingAcksAccess = new object(); private const int BitsInByte = 8; private int _queueIndex; public int PacketsInQueue { get { return _outgoingPackets.Count; } } public ReliableChannel(NetPeer peer, bool ordered, int windowSize) { _resendDelay = peer.NetManager.ReliableResendTime; _windowSize = windowSize; _peer = peer; _ordered = ordered; _outgoingPackets = new Queue<NetPacket>(_windowSize); _outgoingAcks = new bool[_windowSize]; _pendingPackets = new PendingPacket[_windowSize]; for (int i = 0; i < _pendingPackets.Length; i++) { _pendingPackets[i] = new PendingPacket(); } if (_ordered) _receivedPackets = new NetPacket[_windowSize]; else _earlyReceived = new bool[_windowSize]; _localWindowStart = 0; _localSeqence = 0; _remoteSequence = 0; _remoteWindowStart = 0; } //ProcessAck in packet public void ProcessAck(NetPacket packet) { int validPacketSize = (_windowSize - 1) / BitsInByte + 1 + NetConstants.SequencedHeaderSize; if (packet.RawData.Length != validPacketSize) { _peer.DebugWriteForce("[PA]Invalid acks packet size"); return; } ushort ackWindowStart = packet.Sequence; if (ackWindowStart > NetConstants.MaxSequence) { _peer.DebugWrite("[PA]Bad window start"); return; } //check relevance if (NetUtils.RelativeSequenceNumber(ackWindowStart, _localWindowStart) <= -_windowSize) { _peer.DebugWrite("[PA]Old acks"); return; } byte[] acksData = packet.RawData; _peer.DebugWrite("[PA]AcksStart: {0}", ackWindowStart); int startByte = NetConstants.SequencedHeaderSize; Monitor.Enter(_pendingPacketsAccess); for (int i = 0; i < _windowSize; i++) { int ackSequence = (ackWindowStart + i) % NetConstants.MaxSequence; if (NetUtils.RelativeSequenceNumber(ackSequence, _localWindowStart) < 0) { //Skip old ack continue; } int currentByte = startByte + i / BitsInByte; int currentBit = i % BitsInByte; if ((acksData[currentByte] & (1 << currentBit)) == 0) { //Skip false ack continue; } if (ackSequence == _localWindowStart) { //Move window _localWindowStart = (_localWindowStart + 1) % NetConstants.MaxSequence; } int storeIdx = ackSequence % _windowSize; if (_pendingPackets[storeIdx].NotEmpty) { NetPacket removed = _pendingPackets[storeIdx].GetAndClear(); _peer.Recycle(removed); _peer.DebugWrite("[PA]Removing reliableInOrder ack: {0} - true", ackSequence); } else { _peer.DebugWrite("[PA]Removing reliableInOrder ack: {0} - false", ackSequence); } } Monitor.Exit(_pendingPacketsAccess); } public void AddToQueue(NetPacket packet) { lock (_outgoingPackets) { _outgoingPackets.Enqueue(packet); } } private void ProcessQueuedPackets() { //get packets from queue while (_outgoingPackets.Count > 0) { int relate = NetUtils.RelativeSequenceNumber(_localSeqence, _localWindowStart); if (relate < _windowSize) { NetPacket packet; lock (_outgoingPackets) { packet = _outgoingPackets.Dequeue(); } packet.Sequence = (ushort)_localSeqence; _pendingPackets[_localSeqence % _windowSize].Packet = packet; _localSeqence = (_localSeqence + 1) % NetConstants.MaxSequence; } else //Queue filled { break; } } } public bool SendNextPacket() { //check sending acks DateTime currentTime = DateTime.UtcNow; Monitor.Enter(_pendingPacketsAccess); ProcessQueuedPackets(); //send PendingPacket currentPacket; bool packetFound = false; int startQueueIndex = _queueIndex; do { currentPacket = _pendingPackets[_queueIndex]; if (currentPacket.NotEmpty) { //check send time if(currentPacket.TimeStamp.HasValue) { double packetHoldTime = (currentTime - currentPacket.TimeStamp.Value).TotalMilliseconds; if (packetHoldTime > _resendDelay) { _peer.DebugWrite("[RR]Resend: {0}", (int)packetHoldTime); packetFound = true; } } else //Never sended { packetFound = true; } } _queueIndex = (_queueIndex + 1) % _windowSize; } while (!packetFound && _queueIndex != startQueueIndex); if (packetFound) { currentPacket.TimeStamp = currentTime; _peer.SendRawData(currentPacket.Packet.RawData); _peer.DebugWrite("[RR]Sended"); } Monitor.Exit(_pendingPacketsAccess); return packetFound; } public void SendAcks() { if (!_mustSendAcks) return; _mustSendAcks = false; _peer.DebugWrite("[RR]SendAcks"); //Init packet int bytesCount = (_windowSize - 1) / BitsInByte + 1; PacketProperty property = _ordered ? PacketProperty.AckReliableOrdered : PacketProperty.AckReliable; var acksPacket = _peer.GetPacketFromPool(property, bytesCount); //For quick access byte[] data = acksPacket.RawData; //window start + acks size //Put window start Monitor.Enter(_outgoingAcksAccess); acksPacket.Sequence = (ushort)_remoteWindowStart; //Put acks int startAckIndex = _remoteWindowStart % _windowSize; int currentAckIndex = startAckIndex; int currentBit = 0; int currentByte = NetConstants.SequencedHeaderSize; do { if (_outgoingAcks[currentAckIndex]) { data[currentByte] |= (byte)(1 << currentBit); } currentBit++; if (currentBit == BitsInByte) { currentByte++; currentBit = 0; } currentAckIndex = (currentAckIndex + 1) % _windowSize; } while (currentAckIndex != startAckIndex); Monitor.Exit(_outgoingAcksAccess); _peer.SendRawData(acksPacket.RawData); _peer.Recycle(acksPacket); } //Process incoming packet public void ProcessPacket(NetPacket packet) { if (packet.Sequence >= NetConstants.MaxSequence) { _peer.DebugWrite("[RR]Bad sequence"); return; } int relate = NetUtils.RelativeSequenceNumber(packet.Sequence, _remoteWindowStart); int relateSeq = NetUtils.RelativeSequenceNumber(packet.Sequence, _remoteSequence); if (relateSeq > _windowSize) { _peer.DebugWrite("[RR]Bad sequence"); return; } //Drop bad packets if(relate < 0) { //Too old packet doesn't ack _peer.DebugWrite("[RR]ReliableInOrder too old"); return; } if (relate >= _windowSize * 2) { //Some very new packet _peer.DebugWrite("[RR]ReliableInOrder too new"); return; } //If very new - move window Monitor.Enter(_outgoingAcksAccess); if (relate >= _windowSize) { //New window position int newWindowStart = (_remoteWindowStart + relate - _windowSize + 1) % NetConstants.MaxSequence; //Clean old data while (_remoteWindowStart != newWindowStart) { _outgoingAcks[_remoteWindowStart % _windowSize] = false; _remoteWindowStart = (_remoteWindowStart + 1) % NetConstants.MaxSequence; } } //Final stage - process valid packet //trigger acks send _mustSendAcks = true; if (_outgoingAcks[packet.Sequence % _windowSize]) { _peer.DebugWrite("[RR]ReliableInOrder duplicate"); Monitor.Exit(_outgoingAcksAccess); return; } //save ack _outgoingAcks[packet.Sequence % _windowSize] = true; Monitor.Exit(_outgoingAcksAccess); //detailed check if (packet.Sequence == _remoteSequence) { _peer.DebugWrite("[RR]ReliableInOrder packet succes"); _peer.AddIncomingPacket(packet); _remoteSequence = (_remoteSequence + 1) % NetConstants.MaxSequence; if (_ordered) { NetPacket p; while ( (p = _receivedPackets[_remoteSequence % _windowSize]) != null) { //process holded packet _receivedPackets[_remoteSequence % _windowSize] = null; _peer.AddIncomingPacket(p); _remoteSequence = (_remoteSequence + 1) % NetConstants.MaxSequence; } } else { while (_earlyReceived[_remoteSequence % _windowSize]) { //process early packet _earlyReceived[_remoteSequence % _windowSize] = false; _remoteSequence = (_remoteSequence + 1) % NetConstants.MaxSequence; } } return; } //holded packet if (_ordered) { _receivedPackets[packet.Sequence % _windowSize] = packet; } else { _earlyReceived[packet.Sequence % _windowSize] = true; _peer.AddIncomingPacket(packet); } } } }
//----------------------------------------------------------------------------- // Copyright (c) 2015 Pressure Profile Systems // // Licensed under the MIT license. This file may not be copied, modified, or // distributed except according to those terms. //----------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Text; using System.IO.Ports; using System.Windows.Forms; using System.Threading; namespace SingleTactLibrary { public partial class ArduinoSingleTactDriver : Component { SerialPort serialPort_; List<byte> incommingSerialBuffer_ = new List<byte>(); byte cmdItr_ = 0; public bool isUSB = false; public const int TIMESTAMP_SIZE = 4; const int I2C_ID_BYTE = 6; const int I2C_TIMESTAMP = 7; const int I2C_TOPC_NBYTES = 11; const int I2C_START_OF_DATA = 12; //Minimum packet length is 15 (header + info + footer) const int MINIMUM_FROMARDUINO_PACKET_LENGTH = 15; public ArduinoSingleTactDriver() { InitializeComponent(); } public ArduinoSingleTactDriver(IContainer container) { container.Add(this); InitializeComponent(); } /// <summary> /// Initialise connection /// </summary> /// <param name="serialPort">Serial port name (i.e. COM1)</param> public void Initialise(string serialPort) { serialPort_ = new SerialPort(serialPort); //serialPort_.BaudRate = 115200*4; serialPort_.BaudRate = 115200; serialPort_.ReadBufferSize = 48; serialPort_.WriteBufferSize = 16; serialPort_.ErrorReceived += new System.IO.Ports.SerialErrorReceivedEventHandler(this.SerialErrorReceived); serialPort_.Open(); //Reset the Arduino serialPort_.DtrEnable = true; Thread.Sleep(10); serialPort_.DtrEnable = false; Thread.Sleep(2000); //Give Arduino time to boot after reset serialPort_.RtsEnable = true; } public void ResetArduino() { if (serialPort_.IsOpen) serialPort_.Close(); serialPort_.Open(); //Reset the Arduino serialPort_.DtrEnable = true; Thread.Sleep(10); serialPort_.DtrEnable = false; Thread.Sleep(2000); //Give Arduino time to boot after reset } private void SerialErrorReceived(object sender, SerialErrorReceivedEventArgs e) { MessageBox.Show("Serial General Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } public void Initialise(object portName) { throw new NotImplementedException(); } private void ReadSerialBuffer() { while (serialPort_.BytesToRead > 0) { incommingSerialBuffer_.Add((byte)serialPort_.ReadByte()); } } /// <summary> /// Write to sensor's Main Register /// </summary> /// <param name="toSend">Data to write (max 28 bytes)</param> /// <param name="location">Main register location (can write upto byte 128)</param> /// <param name="i2CAddress">I2C Address</param> /// <returns>Was successful?</returns> public bool WriteToMainRegister(byte[] toSend, byte location, byte i2CAddress) { if (toSend.Length > 28) //Max write length (limited by 32 byte i2c transfer length = 28 bytes of data + header info) { MessageBox.Show("Trying to write a packet that is too large", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (toSend.Length + location > 128) { MessageBox.Show("Trying to write into read only region", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } byte[] cmdToArduino = SerialCommand.GenerateWriteCommand(i2CAddress, cmdItr_++, location, toSend); serialPort_.Write(cmdToArduino, 0, cmdToArduino.Length); bool acknowledged = false; int attempts = 20; //Typically takes 4 - 6 attempts as the chip needs to //write the settings to flash which takes about 50ms. Thread.Sleep(10); //Give comms time to happen while (false == acknowledged && attempts > 0) { byte[] cmdFromArduino = ProcessSerialBuffer(); if (null != cmdFromArduino) { if (cmdToArduino[I2C_ID_BYTE] == cmdFromArduino[I2C_ID_BYTE]) { acknowledged = true; return true; } else { MessageBox.Show("Comms Error - Failed Acknoledge Write Command", "Communications Error", MessageBoxButtons.OK, MessageBoxIcon.Error); acknowledged = true; //Move on anyway return false; } } else { Thread.Sleep(10); //Keep waiting attempts--; } } return false; // no ack, give up } /// <summary> /// Write to sensor's Calibration Register /// </summary> /// <param name="toSend">Data to write (max 28 bytes)</param> /// <param name="location">Main register location (can write upto byte 128)</param> /// <param name="i2CAddress">I2C Address</param> /// <returns>Was successful?</returns> public bool WriteToCalibrationRegister(byte[] toSend, byte location, byte i2CAddress) { if (toSend.Length > 28) //Max write length (limited by 32 byte i2c transfer length = 28 bytes of data + header info) { MessageBox.Show("Trying to write a packet that is too large", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (toSend.Length + location > 1024) { MessageBox.Show("Trying to write into read only region", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } byte[] cmdToArduino = SerialCommand.GenerateWriteCalCommand(i2CAddress, cmdItr_++, location, toSend); serialPort_.Write(cmdToArduino, 0, cmdToArduino.Length); bool acknowledged = false; int attempts = 20; //Typically takes 4 - 6 attempts as the chip needs to //write the settings to flash which takes about 50ms. Thread.Sleep(10); //Give comms time to happen while (false == acknowledged && attempts > 0) { byte[] cmdFromArduino = ProcessSerialBuffer(); if (null != cmdFromArduino) { if (cmdToArduino[I2C_ID_BYTE] == cmdFromArduino[I2C_ID_BYTE]) { acknowledged = true; return true; } else { MessageBox.Show("Comms Error - Failed Acknoledge Write Command", "Communications Error", MessageBoxButtons.OK, MessageBoxIcon.Error); acknowledged = true; //Move on anyway return false; } } else { Thread.Sleep(10); //Keep waiting attempts--; } } return false; // no ack, give up } /// <summary> /// Read from sensor's Main Register /// </summary> /// <param name="location">Location to read (sensor data starts at 128)</param> /// <param name="nBytes">Number of bytes to read (max = 32)</param> /// <param name="i2CAddress">I2C Address</param> /// <returns>4 byte timestamp followed by nBytes of data</returns> public byte[] ReadFromMainRegister(byte location, byte nBytes, byte i2CAddress) { if (nBytes > 32) { MessageBox.Show("Error - Trying to read too much"); return null; } if (location + nBytes > 191) //0 - 191 are valid memory locations { MessageBox.Show("Error - Trying to read off the end of the main register"); return null; } byte[] cmdToArduino = SerialCommand.GenerateReadCommand(i2CAddress, cmdItr_++, location, nBytes); try { serialPort_.Write(cmdToArduino, 0, cmdToArduino.Length); } catch (Exception) // USB has been unplugged { return null; } bool acknowledged = false; long attempts = 50; Thread.Sleep(10); //Give comms time to happen while (false == acknowledged && attempts > 0) { byte[] cmdFromArduino = ProcessSerialBuffer(); if (null != cmdFromArduino) { if (cmdToArduino[I2C_ID_BYTE] == cmdFromArduino[I2C_ID_BYTE]) { acknowledged = true; byte[] toReturn = new byte[nBytes + TIMESTAMP_SIZE]; Array.Copy(cmdFromArduino, I2C_TIMESTAMP, toReturn, 0, TIMESTAMP_SIZE); Array.Copy(cmdFromArduino, I2C_START_OF_DATA, toReturn, TIMESTAMP_SIZE, nBytes); return toReturn; } else { MessageBox.Show("Comms error - failed ack"); acknowledged = true; //Move on anyway return null; } } else { Thread.Sleep(10); attempts--; } } return null; // no ack } /// <summary> /// Write to Toggle the PIN /// </summary> /// <param name="toSend">Pins to Toggle</param> /// <returns>Was successful?</returns> public bool WriteToggleCommand(byte toSend) { byte[] cmdToArduino = SerialCommand.GenerateToggleCommand(4, cmdItr_++, 0, toSend); serialPort_.Write(cmdToArduino, 0, cmdToArduino.Length); bool acknowledged = false; long attempts = 50; Thread.Sleep(10); //Give comms time to happen while (false == acknowledged && attempts > 0) { byte[] cmdFromArduino = ProcessSerialBuffer(); if (null != cmdFromArduino) { if (cmdToArduino[I2C_ID_BYTE] == cmdFromArduino[I2C_ID_BYTE]) { acknowledged = true; return true; } else { MessageBox.Show("Comms Error - Failed Acknoledge Write Command", "Communications Error", MessageBoxButtons.OK, MessageBoxIcon.Error); acknowledged = true; //Move on anyway return false; } } else { Thread.Sleep(10); //Keep waiting attempts--; } } return false; // no ack, give up } /// <summary> /// Check the full footer /// </summary> /// <param name="endOfPacket"></param> /// <returns></returns> private bool CheckUartFooter(int endOfPacket) { for (int i = 0; i < 4; i++) { if (incommingSerialBuffer_[endOfPacket - i] != 0xFE) return false; //Footer corrupt } return true; //Footer all good } /// <summary> /// Check available header bytes /// </summary> /// <returns></returns> private bool CheckUartHeader() { for (int i = 0; i < 4; i++) { if (incommingSerialBuffer_[i] != 0xFF && incommingSerialBuffer_[i] != 0xAA) return false; //Header corrupt } if (incommingSerialBuffer_[0] == 0xAA) isUSB = true; return true; //Header all good } /// <summary> /// Process incomming serial data /// </summary> /// <returns></returns> private byte[] ProcessSerialBuffer() { ReadSerialBuffer(); if (incommingSerialBuffer_.Count > MINIMUM_FROMARDUINO_PACKET_LENGTH) { if (false == CheckUartHeader()) { incommingSerialBuffer_.RemoveAt(0); incommingSerialBuffer_.TrimExcess(); } int i2cPacketLength = incommingSerialBuffer_[I2C_TOPC_NBYTES]; if (incommingSerialBuffer_.Count > (i2cPacketLength + MINIMUM_FROMARDUINO_PACKET_LENGTH)) { if (CheckUartFooter(i2cPacketLength + MINIMUM_FROMARDUINO_PACKET_LENGTH)) { byte[] toReturn = new byte[i2cPacketLength + MINIMUM_FROMARDUINO_PACKET_LENGTH + 1]; incommingSerialBuffer_.GetRange(0, i2cPacketLength + MINIMUM_FROMARDUINO_PACKET_LENGTH + 1).CopyTo(toReturn); incommingSerialBuffer_.RemoveRange(0, i2cPacketLength + MINIMUM_FROMARDUINO_PACKET_LENGTH + 1); return toReturn; //We have a good packet } else { incommingSerialBuffer_.RemoveRange(0, i2cPacketLength + MINIMUM_FROMARDUINO_PACKET_LENGTH + 1); //Bad data return null; } } } return null; } } }
using System.Diagnostics; using System; // //Module : AAINTERPOLATE.CPP //Purpose: Implementation for the algorithms for Interpolation //Created: PJN / 29-12-2003 //History: None // //Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) // //All rights reserved. // //Copyright / Usage Details: // //You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) //when your product is released in binary form. You are allowed to modify the source code in any way you want //except you cannot modify the copyright details at the top of each module. If you want to distribute source //code with your application, then you are only allowed to distribute versions released by the author. This is //to maintain a single distribution point for the source code. // // ////////////////////// Includes /////////////////////////////////////////////// /////////////////////// Classes /////////////////////////////////////////////// public class INTP // was { //Static methods ////////////////////// Implementation ///////////////////////////////////////// public static double Interpolate(double n, double Y1, double Y2, double Y3) { double a = Y2 - Y1; double b = Y3 - Y2; double c = Y1 + Y3 - 2 *Y2; return Y2 + n / 2 * (a + b + n *c); } public static double Interpolate2(double n, double Y1, double Y2, double Y3, double Y4, double Y5) { double A = Y2 - Y1; double B = Y3 - Y2; double C = Y4 - Y3; double D = Y5 - Y4; double E = B - A; double F = C - B; double G = D - C; double H = F - E; double J = G - F; double K = J - H; double N2 = n *n; double N3 = N2 *n; double N4 = N3 *n; return Y3 + n*((B+C)/2 - (H+J)/12) + N2*(F/2 - K/24) + N3*((H+J)/12) + N4*(K/24); } public static double InterpolateToHalves(double Y1, double Y2, double Y3, double Y4) { return (9*(Y2 + Y3) - Y1 - Y4) / 16; } public static double LagrangeInterpolate(double X, int n, double[] pX, double[] pY) { double V = 0; for (int i =1; i<=n; i++) { double C = 1; for (int j =1; j<=n; j++) { if (j != i) C = C*(X - pX[j-1]) / (pX[i-1] - pX[j-1]); } V += C *pY[i - 1]; } return V; } //public static double Extremum(double Y1, double Y2, double Y3, ref double nm) //{ // double a = Y2 - Y1; // double b = Y3 - Y2; // double c = Y1 + Y3 - 2 *Y2; // double ab = a + b; // nm = -ab/(2 *c); // return (Y2 - ((ab *ab)/(8 *c))); //} //public static double Extremum2(double Y1, double Y2, double Y3, double Y4, double Y5, ref double nm) //{ // double A = Y2 - Y1; // double B = Y3 - Y2; // double C = Y4 - Y3; // double D = Y5 - Y4; // double E = B - A; // double F = C - B; // double G = D - C; // double H = F - E; // double J = G - F; // double K = J - H; // bool bRecalc = true; // double nmprev = 0; // nm = nmprev; // while (bRecalc) // { // double NMprev2 = nmprev *nmprev; // double NMprev3 = NMprev2 *nmprev; // nm = (6 *B + 6 *C - H - J +3 *NMprev2*(H+J) + 2 *NMprev3 *K) / (K - 12 *F); // bRecalc = (Math.Abs(nm - nmprev) > 1E-12); // if (bRecalc) // nmprev = nm; // } // return Interpolate2(nm, Y1, Y2, Y3, Y4, Y5); //} public static double Zero(double Y1, double Y2, double Y3) { double a = Y2 - Y1; double b = Y3 - Y2; double c = Y1 + Y3 - 2 *Y2; bool bRecalc = true; double n0prev = 0; double n0 = n0prev; while (bRecalc) { n0 = -2 *Y2/(a + b + c *n0prev); bRecalc = (Math.Abs(n0 - n0prev) > 1E-12); if (bRecalc) n0prev = n0; } return n0; } public static double ZeroB(double Y1, double Y2, double Y3, double Y4, double Y5) { double A = Y2 - Y1; double B = Y3 - Y2; double C = Y4 - Y3; double D = Y5 - Y4; double E = B - A; double F = C - B; double G = D - C; double H = F - E; double J = G - F; double K = J - H; bool bRecalc = true; double n0prev = 0; double n0 = n0prev; while (bRecalc) { double n0prev2 = n0prev *n0prev; double n0prev3 = n0prev2 *n0prev; double n0prev4 = n0prev3 *n0prev; n0 = (-24 *Y3 + n0prev2*(K - 12 *F) - 2 *n0prev3*(H+J) - n0prev4 *K)/(2*(6 *B + 6 *C - H - J)); bRecalc = (Math.Abs(n0 - n0prev) > 1E-12); if (bRecalc) n0prev = n0; } return n0; } public static double Zero2(double Y1, double Y2, double Y3) { double a = Y2 - Y1; double b = Y3 - Y2; double c = Y1 + Y3 - 2 *Y2; bool bRecalc = true; double n0prev = 0; double n0 = n0prev; while (bRecalc) { double deltan0 = - (2 *Y2 + n0prev*(a + b + c *n0prev)) / (a + b + 2 *c *n0prev); n0 = n0prev + deltan0; bRecalc = (Math.Abs(deltan0) > 1E-12); if (bRecalc) n0prev = n0; } return n0; } public static double Zero2B(double Y1, double Y2, double Y3, double Y4, double Y5) { double A = Y2 - Y1; double B = Y3 - Y2; double C = Y4 - Y3; double D = Y5 - Y4; double E = B - A; double F = C - B; double G = D - C; double H = F - E; double J = G - F; double K = J - H; double M = K / 24; double N = (H + J)/12; double P = F/2 - M; double Q = (B+C)/2 - N; bool bRecalc = true; double n0prev = 0; double n0 = n0prev; while (bRecalc) { double n0prev2 = n0prev *n0prev; double n0prev3 = n0prev2 *n0prev; double n0prev4 = n0prev3 *n0prev; double deltan0 = - (M * n0prev4 + N *n0prev3 + P *n0prev2 + Q *n0prev + Y3) / (4 *M *n0prev3 + 3 *N *n0prev2 + 2 *P *n0prev + Q); n0 = n0prev + deltan0; bRecalc = (Math.Abs(deltan0) > 1E-12); if (bRecalc) n0prev = n0; } return n0; } }
using HoloJson.Common; using HoloJson.Core; using HoloJson.Lite; using HoloJson.Util; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Threading.Tasks; namespace HoloJson.Lite.Builder { public sealed class LiteJsonBuilder : Lite.LiteJsonBuilder { // Default value. // private const int DEF_DRILL_DOWN_DEPTH = 2; // Max value: equivalent to -1. private const int MAX_DRILL_DOWN_DEPTH = (int) byte.MaxValue; // Arbitrary. // temporary // private const int maxDepth = MAX_DRILL_DOWN_DEPTH; private const string WS = " "; // either to use space or not after "," and ":". // temporary // Note: // It's important not to keep any "state" as class variables for this class // so that a single instance can be used for multiple/concurrent build operations. // (Often, the recursive implementation may involve multiple objects (each as a node in an object tree), // which may use the same/single instance of this builder class.) // ... public LiteJsonBuilder() { } //public async Task BuildAsync(IStorageFile jsonFile, object obj) //{ // var jsonStr = await BuildAsync(obj); // if (jsonStr != null) { // What about empty string? // await FileIO.WriteTextAsync(jsonFile, jsonStr); // } else { // // What to do??? // } //} public async Task<string> BuildAsync(object jsonObj) { // Which is better? // [1] Using StringBuilder. // StringBuilder sb = new StringBuilder(); // return _Build(sb, jsonObj); // Or, [2] Using StringWriter. string jsonStr = null; var writer = new StringWriter(); try { // _Build(writer, jsonObj, depth, useBeanIntrospection); // writer.flush(); // ??? await BuildAsync(writer, jsonObj); jsonStr = writer.ToString(); // System.Diagnostics.Debug.WriteLine(">>>>>>>>>>>>>>>>>>>> jsonStr = " + jsonStr); // string jsonStr2 = writer.getBuffer().ToString(); // System.Diagnostics.Debug.WriteLine(">>>>>>>>>>>>>>>>>>>> jsonStr2 = " + jsonStr2); System.Diagnostics.Debug.WriteLine("jsonStr = " + jsonStr); } catch (IOException ex) { System.Diagnostics.Debug.WriteLine("Failed to write jsonObj as JSON.", ex); } return jsonStr; } public async Task BuildAsync(TextWriter writer, object obj) { if( (obj == null) || (obj is bool) || (obj is char) || (Number.IsNumber(obj)) || (obj is String)) { throw new HoloJsonMiniException("Top level element should be an object or an array/list."); } object jsonObj = null; // if (obj is IDictionary<String, Object> || obj is IList<Object> || obj.GetType().IsArray || obj is Collection<Object>) { if (GenericUtil.IsDictionary(obj) || GenericUtil.IsList(obj) || obj.GetType().IsArray || obj is Collection<Object>) { jsonObj = obj; } else { // ??? // throw new HoloJsonMiniException("Top level element should be an object or an array/list."); // ... // We support a generic "object" by converting it to a nested map/list structure (most likely, a single level map). // Note that this automatic conversion is for convenience only, and // we only support an object at the top-level object (which recurses down its structure, however), not [object] or {k:object}. // If the user wants such a support for more complex collections, // then he/she needs to call HoloJsonMiniStructureBuilder.BuildJsonStructure(obj/[]/{}, depth) explicitly // before calling HoloJsonMiniBuilder.buildJson(). Lite.LiteJsonStructureBuilder structureBuilder = new LiteJsonStructureBuilder(); jsonObj = await structureBuilder.BuildJsonStructureAsync(obj); } await _BuildAsync(writer, jsonObj, MAX_DRILL_DOWN_DEPTH); // ???? await writer.FlushAsync(); // ??? // string jsonStr = writer.ToString(); // System.Diagnostics.Debug.WriteLine("jsonStr = " + jsonStr); } private async Task _BuildAsync(TextWriter writer, object obj, int depth) { if(depth < 0) { return; } if(obj == null || obj is JsonNull) { await writer.WriteAsync(Literals.NULL); } else { // if(depth == 0) { if(depth <= 0) { // TBD: // This section of code is repeated when depth==0 and and when depth>0, // almost identically... (but not quite exactly the same) // Need to be refactored. // .... string primStr = null; if(obj is bool) { if(((bool) obj) == true) { primStr = Literals.TRUE; } else { primStr = Literals.FALSE; } await writer.WriteAsync(primStr); } else if (obj is char) { // ??? char strChar = (char) obj; await writer.WriteAsync("\""); await writer.WriteAsync(strChar); await writer.WriteAsync("\""); } else if (Number.IsNumber(obj)) { primStr = obj.ToString(); await writer.WriteAsync(primStr); } else if(obj is String) { // ???? // Is there a better/faster way to do this? // ??? primStr = (String) obj; // await writer.WriteAsync("\"").Append(primStr).Append("\""); // ??? await writer.WriteAsync("\""); _AppendEscapedString(writer, primStr); await writer.WriteAsync("\""); // ??? } else { // TBD: // java.util.Date ??? // and other JDK built-in class support??? // .. if(obj is DateTime || obj is DateTimeOffset) { // TBD: // Create a struct ??? primStr = obj.ToString(); // ??? // ... } else if(obj is String) { primStr = (String) obj; } else { // TBD: // POJO/Bean support??? // ... // ???? primStr = obj.ToString(); } // await writer.WriteAsync("\"").Append(primStr).Append("\""); await writer.WriteAsync("\""); _AppendEscapedString(writer, primStr); await writer.WriteAsync("\""); } } else { // if(obj is IDictionary<String,Object>) { if (GenericUtil.IsDictionary(obj)) { // ???? // IDictionary<String, Object> map = null; dynamic map = null; try { // map = (IDictionary<String,Object>) obj; map = obj; } catch(Exception ex) { System.Diagnostics.Debug.WriteLine("Invalid map type.", ex); } await writer.WriteAsync("{"); if(map != null && map.Count > 0) { IEnumerator<String> it = map.Keys.GetEnumerator(); var next = it.MoveNext(); while(next) { string key = it.Current; object val = map[key]; await writer.WriteAsync("\""); await writer.WriteAsync(key); await writer.WriteAsync("\":"); await writer.WriteAsync(WS); await _BuildAsync(writer, val, depth - 1); //// TBD: how to do this???? //// ??? next = it.MoveNext(); if (next) { await writer.WriteAsync(","); await writer.WriteAsync(WS); } //// .... } } await writer.WriteAsync("}"); // } else if (obj is IList<Object>) { } else if (GenericUtil.IsList(obj)) { // ??? // IList<Object> list = null; dynamic list = null; try { // list = (IList<Object>) obj; list = obj; } catch(Exception e) { System.Diagnostics.Debug.WriteLine("Invalid list type.", e); } await writer.WriteAsync("["); if(list != null && list.Count > 0) { IEnumerator<Object> it = list.GetEnumerator(); var next = it.MoveNext(); while (next) { object o = it.Current; await _BuildAsync(writer, o, depth - 1); //// ???? //// How to do this??? next = it.MoveNext(); if (next) { await writer.WriteAsync(","); await writer.WriteAsync(WS); } //// ???? } } await writer.WriteAsync("]"); } else if(obj.GetType().IsArray) { // ??? // type safe casting to array???? // if obj.GetType().GetElementType() ... // object[] array = (object[]) obj; // ???? // temporary dynamic array = obj; // ???? await writer.WriteAsync("["); if(array!= null && array.Length > 0) { int arrLen = array.Length; // System.Diagnostics.Debug.WriteLine(">>>>>>>>>>>>>>>>>>>>>>>>>>>>> arrLen = " + arrLen); for(int i=0; i<arrLen; i++) { object o = array[i]; // System.Diagnostics.Debug.WriteLine(">>>>>>>>>>>>>>>>>>>>>>>>>>>>> o = " + o + "; " + o.Type); await _BuildAsync(writer, o, depth - 1); // System.Diagnostics.Debug.WriteLine(">>>>>>>>>>>>>>>>>>>>>>>>>>>>> jsonVal = " + jsonVal + "; " + o.Type); if(i < arrLen - 1) { await writer.WriteAsync(","); await writer.WriteAsync(WS); } } } await writer.WriteAsync("]"); // // ??? // // This adds weird repeated brackets ([[[[[[[ ...]]]]]]]]). // _Build(writer, Arrays.asList(array), depth); } else if(obj is Collection<Object>) { // ??????? Not implemented yet. Collection<Object> coll = null; try { coll = (Collection<Object>) obj; } catch(Exception ex) { System.Diagnostics.Debug.WriteLine("Invalid collection type.", ex); } await writer.WriteAsync("["); if(coll != null && coll.Count > 0) { IEnumerator<Object> it = coll.GetEnumerator(); var next = it.MoveNext(); while (next) { object o = it.Current; await _BuildAsync(writer, o, depth - 1); //// TBD: //// ???? next = it.MoveNext(); if (next) { await writer.WriteAsync(","); await writer.WriteAsync(WS); } //// ???? } } await writer.WriteAsync("]"); } else { // primitive types... ??? // ... string primStr = null; if(obj is bool) { if(((bool) obj) == true) { primStr = Literals.TRUE; } else { primStr = Literals.FALSE; } await writer.WriteAsync(primStr); } else if (obj is char) { // ??? char strChar = (char) obj; await writer.WriteAsync("\""); await writer.WriteAsync(strChar); await writer.WriteAsync("\""); } else if (Number.IsNumber(obj)) { primStr = obj.ToString(); // ???? await writer.WriteAsync(primStr); } else if (obj is String) { // ???? // Is there a better/faster way to do this? // ??? primStr = (String) obj; // await writer.WriteAsync("\"").Append(primStr).Append("\""); // ??? await writer.WriteAsync("\""); _AppendEscapedString(writer, primStr); await writer.WriteAsync("\""); // ??? } else { // TBD: // java.util.Date ??? // and other JDK built-in class support??? // .. if(obj is DateTime || obj is DateTimeOffset) { // TBD: // Create a struct ??? primStr = obj.ToString(); // ... } else if(obj is String) { primStr = (String) obj; } else { // ???? primStr = obj.ToString(); } await writer.WriteAsync("\""); _AppendEscapedString(writer, primStr); await writer.WriteAsync("\""); } } } } } // private static readonly int escapeForwardSlash = -1; private async void _AppendEscapedString(TextWriter writer, string primStr) { if(primStr != null && primStr.Length > 0) { char[] primChars = primStr.ToCharArray(); // char prevEc = 0; foreach(char ec in primChars) { if(Symbols.IsEscapedChar(ec)) { // if(prevEc == '<' && ec == '/') { // // if(escapeForwardSlash >= 0) { // // await writer.WriteAsync("\\/"); // // } else { // await writer.WriteAsync("/"); // // } // } else { // string str = Symbols.GetEscapedCharString(ec, escapeForwardSlash > 0 ? true : false); string str = Symbols.GetEscapedCharString(ec, false); if(str != null) { await writer.WriteAsync(str); } else { // ??? await writer.WriteAsync(ec); } // } } else if(CharUtil.IsISOControl(ec)) { char[] uc = UnicodeUtil.GetUnicodeHexCodeFromChar(ec); await writer.WriteAsync(uc); } else { await writer.WriteAsync(ec); } // prevEc = ec; } } } } }
// Copyright (c) Microsoft. All rights reserved. using Microsoft.Iot.IotCoreAppProjectExtensibility; using Microsoft.Win32; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using System.ComponentModel; using System.Globalization; using System.Collections.ObjectModel; using System.Linq; using System.Net.Sockets; using System.Reflection; namespace Microsoft.Iot.IotCoreAppDeployment { public class DeploymentWorker { private static Microsoft.ApplicationInsights.TelemetryClient TelemetryClient; private CommandLineParser argsHandler = null; private string outputFolder = null; private string source = ""; private string targetName = ""; private string makeAppxPath = null; private string signToolPath = null; private string powershellPath = null; private string copyOutputToFolder = null; private bool keepTempFolder = false; private TargetPlatform targetType = TargetPlatform.ARM; private SdkVersion sdk = SdkVersion.SDK_10_0_10586_0; private DependencyConfiguration configuration = DependencyConfiguration.Debug; private StreamWriter outputWriter; private const string packageFullNameFormat = "{0}_1.0.0.0_{1}__1w720vyc4ccym"; private const string universalSdkRootKey = @"HKEY_LOCAL_MACHINE\Software\Microsoft\Windows Kits\Installed Roots"; private const string universalSdkRootValue = @"KitsRoot10"; private const string powershellRootKey = @"HKEY_LOCAL_MACHINE\Software\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell"; private const string powershellRootValue = @"Path"; private const string defaultSdkVersion = "10.0.10586.0"; private const string defaultTargetUserName = "Administrator"; private const string defaultTargetPassword = "p@ssw0rd"; private UserInfo credentials = new UserInfo() { UserName = defaultTargetUserName, Password = defaultTargetPassword }; private const int QueryInterval = 3000; private void CreateCommandLineParser() { argsHandler = new CommandLineParser(this); // Required args argsHandler.AddRequiredArgumentWithInput("s", Resource.DeploymentWorker_SourceArgMsg, (worker, value) => { worker.source = new FileInfo(value).FullName; }); argsHandler.AddRequiredArgumentWithInput("n", Resource.DeploymentWorker_TargetArgMsg, (worker, value) => { worker.targetName = value; }); // Optional args argsHandler.AddOptionalArgumentWithInput("x", string.Format(CultureInfo.InvariantCulture, Resource.DeploymentWorker_SdkArgMsg, defaultSdkVersion), (worker, value) => { worker.HandleSdkVersionFromCommandLine(value); }); argsHandler.AddOptionalArgumentWithInput("t", Resource.DeploymentWorker_TempDirArgMsg, (worker, value) => { worker.outputFolder = value; }); argsHandler.AddOptionalArgumentWithInput("f", Resource.DeploymentWorker_ConfigArgMsg, (worker, value) => { if (!Enum.TryParse<DependencyConfiguration>(value, true, out worker.configuration)) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resource.DeploymentWorker_argumentHelper_0_is_not_a_supported_configuration, value)); } }); argsHandler.AddOptionalArgumentWithInput("a", Resource.DeploymentWorker_ArchArgMsg, (worker, value) => { if (!Enum.TryParse<TargetPlatform>(value, true, out worker.targetType)) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resource.DeploymentWorker_argumentHelper_0_is_not_a_supported_target_architecture, value)); } }); argsHandler.AddOptionalArgumentWithInput("w", string.Format(CultureInfo.InvariantCulture, Resource.DeploymentWorker_TargetUserNameArgMsg, defaultTargetUserName), (worker, value) => { worker.credentials.UserName = value; }); argsHandler.AddOptionalArgumentWithInput("p", string.Format(CultureInfo.InvariantCulture, Resource.DeploymentWorker_TargetPasswordArgMsg, defaultTargetPassword), (worker, value) => { worker.credentials.Password = value; }); argsHandler.AddOptionalArgumentWithInput("o", Resource.DeploymentWorker_SaveAppxArgMsg, (worker, value) => { worker.copyOutputToFolder = value; }); argsHandler.AddOptionalArgumentWithInput("x", Resource.DeploymentWorker_MakeAppxArgMsg, (worker, value) => { worker.makeAppxPath = value; }); argsHandler.AddOptionalArgumentWithInput("g", Resource.DeploymentWorker_SignToolArgMsg, (worker, value) => { worker.signToolPath = value; }); argsHandler.AddOptionalArgumentWithInput("w", Resource.DeploymentWorker_PowershellArgMsg, (worker, value) => { worker.powershellPath = value; }); argsHandler.AddOptionalArgumentWithoutInput("d", Resource.DeploymentWorker_KeepTempArgMsg, (worker, value) => { worker.keepTempFolder = true; }); argsHandler.AddHelpArgument(new string[] { "h", "help", "?" }, Resource.DeploymentWorker_HelpArgMsg); } private void HandleSdkVersionFromCommandLine(string value) { sdk = GetSdkVersionFromString(value); if (sdk != SdkVersion.Unknown) { return; } var sb = new StringBuilder(); var sdkVersionMembers = typeof(SdkVersion).GetEnumValues(); for (var i = 0; i < sdkVersionMembers.Length; i++) { var sdkVersionMember = (SdkVersion)sdkVersionMembers.GetValue(i); if (SdkVersion.Unknown == sdkVersionMember) continue; var field = typeof(SdkVersion).GetField(sdkVersionMember.ToString()); var customAttributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false); for (var j = 0; j < customAttributes.Length; j++) { var descriptionAttribute = customAttributes[j] as DescriptionAttribute; if (descriptionAttribute != null) { if (sb.Length != 0) sb.Append(", "); sb.Append(descriptionAttribute.Description); } } } throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resource.DeploymentWorker_SupportedSdksErrorMsg, sb.ToString())); } private static SdkVersion GetSdkVersionFromString(string sdk) { var sdkVersionMembers = typeof(SdkVersion).GetEnumValues(); for (var i = 0; i < sdkVersionMembers.Length; i++) { var enumValue = (SdkVersion)sdkVersionMembers.GetValue(i); var field = typeof(SdkVersion).GetField(enumValue.ToString()); var customAttributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false); for (var j = 0; j < customAttributes.Length; j++) { var descriptionAttribute = customAttributes[j] as DescriptionAttribute; if (null != descriptionAttribute && descriptionAttribute.Description.Equals(sdk, StringComparison.OrdinalIgnoreCase)) { return enumValue; } } } return SdkVersion.Unknown; } public void OutputMessage(string message) { outputWriter.WriteLine(message); } private static void ExecuteExternalProcess(string executableFileName, string arguments, string logFileName) { using (var process = new Process()) { process.StartInfo.FileName = executableFileName; process.StartInfo.Arguments = arguments; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.Start(); var output = new StringBuilder(); // Using WaitForExit would be cleaner, but for some reason, it // hangs when using MakeAppx. In the process of debugging that, // I found that this never hangs. while (!process.HasExited) { output.Append(process.StandardOutput.ReadToEnd()); Thread.Sleep(100); } using (var logStream = new StreamWriter(logFileName)) { var errors = process.StandardError.ReadToEnd(); if (!string.IsNullOrEmpty(errors)) { logStream.WriteLine("\n\n\n\nErrors:"); logStream.Write(errors); } logStream.WriteLine("\n\n\n\nFull Output:"); logStream.Write(output.ToString()); } } } private void NotifyThatMakeAppxOrSignToolNotFound() { OutputMessage(Resource.DeploymentWorker_ToolNotFound1); OutputMessage(Resource.DeploymentWorker_ToolNotFound2); OutputMessage(Resource.DeploymentWorker_ToolNotFound3); OutputMessage(Resource.DeploymentWorker_ToolNotFound4); OutputMessage(Resource.DeploymentWorker_ToolNotFound5); } private bool CopyBaseTemplateContents(ITemplate template) { var templateContents = template.GetTemplateContents(); foreach (var content in templateContents) { if (!content.Apply(outputFolder)) { Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, Resource.DeploymentWorker_FailedToCopyFromResourcesMsg, content.AppxRelativePath)); return false; } } OutputMessage(string.Format(CultureInfo.InvariantCulture, Resource.DeploymentWorker_CopiedBaseFromResourcesMsg, outputFolder)); return true; } private bool CopyProjectFiles(IProject project) { var appxContents = project.GetAppxContents(); foreach (var content in appxContents) { if (!content.Apply(outputFolder)) { Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, Resource.DeploymentWorker_FailedToCopyFromResourcesMsg, content.AppxRelativePath)); return false; } } OutputMessage(string.Format(CultureInfo.InvariantCulture, Resource.DeploymentWorker_CopiedFromResourcesMsg, outputFolder)); return true; } private bool SpecializeAppxManifest(IProject project) { var appxManifestChangess = project.GetAppxContentChanges(); foreach (var change in appxManifestChangess) { if (!change.ApplyToContent(outputFolder)) { Debug.WriteLine(Resource.DeploymentWorker_FailedToChangeAppxManifest); return false; } } OutputMessage(Resource.DeploymentWorker_ChangedAppxManifest); return true; } private Task<bool> BuildProjectAsync(IProjectWithCustomBuild project) { OutputMessage(Resource.DeploymentWorker_BuildStarted); var buildTask = project.BuildAsync(outputFolder, outputWriter); if (!buildTask.Result) { OutputMessage(Resource.DeploymentWorker_BuildFailed); return Task.FromResult(false); } OutputMessage(Resource.DeploymentWorker_BuildSucceeded); return Task.FromResult(true); } private bool AddCapabilitiesToAppxManifest(IProject project) { var capabilityAdditions = project.GetCapabilities(); foreach (var capability in capabilityAdditions) { if (!capability.ApplyToContent(outputFolder)) { Debug.WriteLine(Resource.DeploymentWorker_FailedToAddCapability); return false; } } return true; } private bool CreateAppxMapFile(ITemplate template, IProject project, string mapFile) { var resourceMetadata = new Collection<string>(); var appxFiles = new Collection<string>(); if (!template.GetAppxMapContents(resourceMetadata, appxFiles, outputFolder)) { Debug.WriteLine(Resource.DeploymentWorker_FailedToGetTemplateContents); return false; } if (!project.GetAppxMapContents(resourceMetadata, appxFiles, outputFolder)) { Debug.WriteLine(Resource.DeploymentWorker_FailedToGetProjectContents); return false; } using (var mapFileStream = File.Create(mapFile)) { using (var mapFileWriter = new StreamWriter(mapFileStream)) { mapFileWriter.WriteLine("[ResourceMetadata]"); foreach (var md in resourceMetadata) { mapFileWriter.WriteLine(md); } mapFileWriter.WriteLine(""); mapFileWriter.WriteLine("[Files]"); foreach (var appxFile in appxFiles) { mapFileWriter.WriteLine(appxFile); } } } OutputMessage(string.Format(CultureInfo.InvariantCulture, Resource.DeploymentWorker_AppxMapCreated, mapFile)); return true; } private bool CallMakeAppx(string makeAppxCmd, string mapFile, string outputAppx) { const string makeAppxArgsFormat = "pack /l /h sha256 /m \"{0}\" /f \"{1}\" /o /p \"{2}\""; var makeAppxArgs = string.Format(CultureInfo.InvariantCulture, makeAppxArgsFormat, outputFolder + @"\AppxManifest.xml", mapFile, outputAppx); var makeAppxLogfile = outputFolder + @"\makeappx.log"; ExecuteExternalProcess(makeAppxCmd, makeAppxArgs, makeAppxLogfile); if (!File.Exists(outputAppx)) { return false; } OutputMessage(Resource.DeploymentWorker_AppxCreated); OutputMessage(string.Format(CultureInfo.InvariantCulture, " {0}", outputAppx)); OutputMessage(string.Format(CultureInfo.InvariantCulture, Resource.DeploymentWorker_CreatedLogfile, makeAppxLogfile)); return true; } private bool SignAppx(string signToolCmd, string outputAppx, string pfxFile) { const string signToolArgsFormat = "sign /fd sha256 /f \"{0}\" \"{1}\""; var signToolArgs = string.Format(CultureInfo.InvariantCulture, signToolArgsFormat, pfxFile, outputAppx); var signToolLogfile = outputFolder + @"\signtool.log"; ExecuteExternalProcess(signToolCmd, signToolArgs, signToolLogfile); // TODO: how to validate this? OutputMessage(string.Format(CultureInfo.InvariantCulture, Resource.DeploymentWorker_AppxSignedWithPfx, signToolLogfile)); OutputMessage(string.Format(CultureInfo.InvariantCulture, Resource.DeploymentWorker_CreatedLogfile, signToolLogfile)); return true; } private bool CreateCertFromPfx(string powershellCmd, string pfxFile, string outputCer) { const string getCertArgsFormat = "\"Get-PfxCertificate -FilePath \'{0}\' | Export-Certificate -FilePath \'{1}\' -Type CERT\""; var getCertArgs = string.Format(CultureInfo.InvariantCulture, getCertArgsFormat, pfxFile, outputCer); var powershellLogfile = outputFolder + @"\powershell.log"; ExecuteExternalProcess(powershellCmd, getCertArgs, powershellLogfile); OutputMessage(Resource.DeploymentWorker_CreatedCertFromPfx); OutputMessage(string.Format(CultureInfo.InvariantCulture, " {0}", outputCer)); OutputMessage(string.Format(CultureInfo.InvariantCulture, Resource.DeploymentWorker_CreatedLogfile, powershellLogfile)); return true; } private bool CopyDependencyAppxFiles(ReadOnlyCollection<FileStreamInfo> dependencies, string artifactsFolder) { foreach (var dependency in dependencies) { if (!dependency.Apply(artifactsFolder)) { return false; } } OutputMessage(Resource.DeploymentWorker_CopiedDependencyAppxFiles); return true; } private static bool CopyFileAndValidate(string from, string to) { File.Copy(from, to, true); if (!File.Exists(to)) { Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, Resource.DeploymentWorker_FailedToCopy0to1, from, to)); return false; } return true; } private bool CopyArtifacts(string outputAppx, string appxFilename, string outputCer, string cerFilename, ReadOnlyCollection<FileStreamInfo> dependencies) { // If copy is not requested, skip if (null == copyOutputToFolder) { return true; } if (!Directory.Exists(copyOutputToFolder)) { Directory.CreateDirectory(copyOutputToFolder); } // Copy APPX if (!CopyFileAndValidate(outputAppx, copyOutputToFolder + @"\" + appxFilename)) { return false; } // Copy .cer if (!CopyFileAndValidate(outputCer, copyOutputToFolder + @"\" + cerFilename)) { return false; } // Copy dependencies foreach (var dependency in dependencies) { if (!dependency.Apply(copyOutputToFolder)) { Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, Resource.DeploymentWorker_FailedToSaveAppx, copyOutputToFolder + "\\" + dependency.AppxRelativePath)); return false; } } return true; } private bool HandleUnauthenticatedDeployAppx(string outputAppx, string outputCer, ReadOnlyCollection<FileStreamInfo> dependencies, string dependencyFolder, string identityName) { var deployResult = DeployAppx(outputAppx, outputCer, dependencies, dependencyFolder, identityName); if (deployResult == HttpStatusCode.Unauthorized) { OutputMessage(string.Format(CultureInfo.InvariantCulture, Resource.DeploymentWorker_UnauthorizedDeployment, credentials.UserName, credentials.Password)); CustomCredentialsForm customCredentialsForm = new CustomCredentialsForm(credentials.UserName, credentials.Password); var result = customCredentialsForm.ShowDialog(); if (result == System.Windows.Forms.DialogResult.OK) { credentials.UserName = customCredentialsForm.Username; credentials.Password = customCredentialsForm.Password; } else { return false; } deployResult = DeployAppx(outputAppx, outputCer, dependencies, dependencyFolder, identityName); if (deployResult == HttpStatusCode.Unauthorized) { OutputMessage(string.Format(CultureInfo.InvariantCulture, Resource.DeploymentWorker_UnauthorizedDeployment, credentials.UserName, credentials.Password)); } } return deployResult == HttpStatusCode.OK || deployResult == HttpStatusCode.Accepted; } private HttpStatusCode DeployAppx(string outputAppx, string outputCer, ReadOnlyCollection<FileStreamInfo> dependencies, string dependencyFolder, string identityName) { OutputMessage(string.Format(CultureInfo.InvariantCulture, Resource.DeploymentWorker_StartDeploy, targetName)); // Create list of all APPX and CER files for deployment var files = new List<FileInfo>() { new FileInfo(outputAppx), new FileInfo(outputCer), }; foreach (var dependency in dependencies) { files.Add(new FileInfo(dependencyFolder + @"\" + dependency.AppxRelativePath)); } // Call WEBB Rest APIs to deploy var packageFullName = string.Format(CultureInfo.InvariantCulture, packageFullNameFormat, identityName, targetType.ToString()); using (var webbHelper = new WebbHelper()) { OutputMessage(Resource.DeploymentWorker_DeployAppx_starting_to_deploy_certificate_APPX_and_dependencies); // Attempt to uninstall existing package if found var uninstallTask = webbHelper.UninstallAppAsync(packageFullName, targetName, credentials); if (uninstallTask.Result == HttpStatusCode.OK) { // result == OK means the package was uninstalled. OutputMessage(string.Format(CultureInfo.InvariantCulture, Resource.DeploymentWorker_PreviousDeployUninstalled, packageFullName)); } else if (uninstallTask.Result == HttpStatusCode.Unauthorized) { // result == Unauthorized means the credentials were not accepted. return uninstallTask.Result; } else { // result != OK could mean that the package wasn't already installed // or it could mean that there was a problem with the uninstall // request. OutputMessage(string.Format(CultureInfo.InvariantCulture, Resource.DeploymentWorker_PreviousDeployNotUninstalled, packageFullName)); } // Deploy new APPX, cert, and dependency files var deployTask = webbHelper.DeployAppAsync(files, targetName, credentials); if (deployTask.Result == HttpStatusCode.Accepted) { var result = webbHelper.PollInstallStateAsync(targetName, credentials).Result; OutputMessage(string.Format(CultureInfo.InvariantCulture, Resource.DeploymentWorker_DeployFinished, packageFullName)); OutputMessage("\r\n\r\n***"); OutputMessage(string.Format(CultureInfo.InvariantCulture, "*** PackageFullName = {0}", packageFullName)); OutputMessage("***\r\n\r\n"); if (!result) { return HttpStatusCode.BadRequest; } } else { OutputMessage(string.Format(CultureInfo.InvariantCulture, Resource.DeploymentWorker_DeployFailed, packageFullName)); } return deployTask.Result; } } private bool CreateAppx(ITemplate template, IProject project, string makeAppxCmd, string outputAppx) { // Copy generic base template files if (!CopyBaseTemplateContents(template)) { return false; } // Copy IProject-specific (but still generic) files if (!CopyProjectFiles(project)) { return false; } // Make changes to the files to tailor them to the specific user input if (!SpecializeAppxManifest(project)) { return false; } var projectWithCustomBuild = project as IProjectWithCustomBuild; // Do build step if needed (compiling/generation/etc) if (projectWithCustomBuild != null && !BuildProjectAsync(projectWithCustomBuild).Result) { return false; } // Add IProject-specific capabilities if (!AddCapabilitiesToAppxManifest(project)) { return false; } // Create mapping file used to build APPX var mapFile = outputFolder + @"\main.map.txt"; if (!CreateAppxMapFile(template, project, mapFile)) { return false; } // Create APPX file var makeAppxResult = CallMakeAppx(makeAppxCmd, mapFile, outputAppx); return makeAppxResult; } private bool GuardTargetName() { if (string.IsNullOrEmpty(targetName) || targetName.Equals("?")) { if (targetName.Equals("?")) { TelemetryClient.TrackEvent("DeployFromArduinoIde", new Dictionary<string, string>() { }); } // Use last successful deployment target as default string initialTargetValue = ""; using (var key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\IotCoreAppDeployment")) { if (key != null) { initialTargetValue = key.GetValue("Target") as string; } } // Let user specify target TargetNameForm targetNameForm = new TargetNameForm(initialTargetValue); var result = targetNameForm.ShowDialog(); if (result == System.Windows.Forms.DialogResult.OK) { targetName = targetNameForm.TargetName; } if (string.IsNullOrEmpty(targetName)) { Console.Write(Resource.DeploymentWorker_TargetMissing); return false; } } return true; } private bool ConvertTargetNameToIp() { // Is targetName set correctly? if (!GuardTargetName()) { return false; } try { // Assume an IP address was provided IPAddress.Parse(targetName); } catch (FormatException) { // If an IP address was not provided, assume device name was provided try { // Host Name resolution to IP var host = Dns.GetHostEntry(targetName); var ipaddr = host.AddressList.First(ip => ip.AddressFamily == AddressFamily.InterNetwork); if (ipaddr != null) { targetName = ipaddr.ToString(); } } catch (Exception e) when (e is ArgumentNullException || e is ArgumentOutOfRangeException || e is SocketException || e is ArgumentException) { Console.Write(string.Format(CultureInfo.InvariantCulture, Resource.DeploymentWorker_DeviceNotFound, targetName, e.Message)); return false; } } return true; } private bool CreateAndDeployApp() { #region Find Template and Project from available providers // Ensure that the target name is converted to IP address as needed if (!ConvertTargetNameToIp()) { return false; } // Ensure that the required Tools (MakeAppx and SignTool) can be found var universalSdkRoot = Registry.GetValue(universalSdkRootKey, universalSdkRootValue, null) as string; if (universalSdkRoot == null && (makeAppxPath == null || signToolPath == null)) { NotifyThatMakeAppxOrSignToolNotFound(); return false; } const string sdkToolCmdFormat = "{0}\\bin\\{1}\\{2}"; var is64 = Environment.Is64BitOperatingSystem; var makeAppxCmd = makeAppxPath ?? string.Format(CultureInfo.InvariantCulture, sdkToolCmdFormat, universalSdkRoot, is64 ? "x64" : "x86", "MakeAppx.exe"); var signToolCmd = signToolPath ?? string.Format(CultureInfo.InvariantCulture, sdkToolCmdFormat, universalSdkRoot, is64 ? "x64" : "x86", "SignTool.exe"); if (!File.Exists(makeAppxCmd) || !File.Exists(signToolCmd)) { NotifyThatMakeAppxOrSignToolNotFound(); return false; } // Ensure that PowerShell.exe can be found var powershellCmd = powershellPath ?? Registry.GetValue(powershellRootKey, powershellRootValue, null) as string; if (powershellCmd == null || !File.Exists(powershellCmd)) { OutputMessage(Resource.DeploymentWorker_PowershellNotFound1); OutputMessage(Resource.DeploymentWorker_PowershellNotFound2); return false; } // Surround tool cmd paths with quotes in case there are spaces in the paths makeAppxCmd = "\"" + makeAppxCmd + "\""; signToolCmd = "\"" + signToolCmd + "\""; powershellCmd = "\"" + powershellCmd + "\""; // Find an appropriate path for the input source IProject project = SupportedProjects.FindProject(source); if (null == project) { OutputMessage(string.Format(CultureInfo.InvariantCulture, Resource.DeploymentWorker_NoProjectForSource, source)); return false; } OutputMessage(string.Format(CultureInfo.InvariantCulture, Resource.DeploymentWorker_FoundProjectForSource, project.Name)); TelemetryClient.TrackEvent("DeployProjectType", new Dictionary<string, string>() { { "ProjectType", project.Name }, { "ProjectTargetArchitecture", targetType.ToString() }, }); // Configure IProject with user input project.SourceInput = source; project.ProcessorArchitecture = targetType; project.SdkVersion = sdk; project.DependencyConfiguration = configuration; // Find base project type ... typically, this is C++ for non-standard UWP // project types like Python and Node.js var baseProjectType = project.GetBaseProjectType(); if (IBaseProjectTypes.Other == baseProjectType) { OutputMessage(string.Format(CultureInfo.InvariantCulture, Resource.DeploymentWorker_NoBaseProjectType, baseProjectType.ToString())); return false; } // Get ITemplate to retrieve shared APPX content var template = SupportedProjects.FindTemplate(baseProjectType); if (null == template) { OutputMessage(string.Format(CultureInfo.InvariantCulture, Resource.DeploymentWorker_NoBaseProjectType, baseProjectType.ToString())); return false; } OutputMessage(string.Format(CultureInfo.InvariantCulture, Resource.DeploymentWorker_FoundBaseProjectType, template.Name)); #endregion if (outputFolder == null) { outputFolder = Path.GetTempPath() + Path.GetRandomFileName(); } var artifactsFolder = outputFolder + @"\output"; var filename = project.IdentityName + "_" + targetType + "_" + configuration; var appxFilename = filename + ".appx"; var cerFilename = filename + ".cer"; var outputAppx = artifactsFolder + @"\" + appxFilename; var outputCer = artifactsFolder + @"\" + cerFilename; if (!Directory.Exists(artifactsFolder)) { Directory.CreateDirectory(artifactsFolder); } var createResult = CreateAppx(template, project, makeAppxCmd, outputAppx); if (!createResult) { TelemetryClient.TrackEvent("CreateAppxFailure", new Dictionary<string, string>() { }); return false; } var pfxFile = outputFolder + @"\TemporaryKey.pfx"; if (!SignAppx(signToolCmd, outputAppx, pfxFile)) { TelemetryClient.TrackEvent("SignAppxFailure", new Dictionary<string, string>() { }); return false; } if (!CreateCertFromPfx(powershellCmd, pfxFile, outputCer)) { TelemetryClient.TrackEvent("CreateCertFailure", new Dictionary<string, string>() { }); return false; } var dependencies = project.GetDependencies(SupportedProjects.DependencyProviders); if (!CopyDependencyAppxFiles(dependencies, artifactsFolder)) { return false; } var deployResult = HandleUnauthenticatedDeployAppx(outputAppx, outputCer, dependencies, artifactsFolder, project.IdentityName); if (!deployResult) { TelemetryClient.TrackEvent("WebbDeployFailure", new Dictionary<string, string>() { }); return deployResult; } // If app was successfully deployed, cache target in registry using (var key = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\IotCoreAppDeployment")) { key.SetValue("Target", targetName); } return CopyArtifacts(outputAppx, appxFilename, outputCer, cerFilename, dependencies); } private DeploymentWorker(Stream outputStream) { this.outputWriter = new StreamWriter(outputStream) { AutoFlush = true }; CreateCommandLineParser(); } ~DeploymentWorker() { #region Cleanup if (!keepTempFolder && Directory.Exists(outputFolder)) { Directory.Delete(outputFolder, true); } #endregion } private static string getMachineId() { string id = null; try { // Try querying 64-bit registry for key var localRegKey = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry64); if (localRegKey != null) { id = (string)localRegKey.OpenSubKey(@"SOFTWARE\Microsoft\SQMClient").GetValue("MachineId"); // If can't find key in 64-bit registry, query 32-bit registry if (id == null) { localRegKey = RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, RegistryView.Registry32); if (localRegKey != null) { id = (string)localRegKey.OpenSubKey(@"SOFTWARE\Microsoft\SQMClient").GetValue("MachineId"); } } } } catch (Exception) { // ignored } if (id != null) { return id.Replace("{", "").Replace("}", ""); } return null; } public static bool Execute(string[] args, Stream outputStream) { var sessionId = Guid.NewGuid().ToString(); var machineId = getMachineId(); // Create AppInsights telemetry client to track app usage TelemetryClient = new Microsoft.ApplicationInsights.TelemetryClient(); TelemetryClient.Context.User.Id = machineId; TelemetryClient.Context.Session.Id = sessionId; Assembly assembly = Assembly.GetAssembly(typeof(DeploymentWorker)); FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(assembly.Location); var version = fileVersionInfo.ProductVersion; TelemetryClient.TrackEvent("DeployStart", new Dictionary<string, string>() { { "AppVersion", version } }); var worker = new DeploymentWorker(outputStream); if (!worker.argsHandler.HandleCommandLineArgs(args)) { TelemetryClient.TrackEvent("DeployFailed_IncorrectArgs", new Dictionary<string, string>() { }); TelemetryClient.Flush(); return false; } worker.OutputMessage(Resource.DeploymentWorker_Starting); var taskResult = worker.CreateAndDeployApp(); if (taskResult) { TelemetryClient.TrackEvent("DeploySucceeded", new Dictionary<string, string>() { }); } else { TelemetryClient.TrackEvent("DeployFailed", new Dictionary<string, string>() { }); } TelemetryClient.Flush(); return taskResult; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; #if DEBUG using System.Diagnostics; #endif using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Tagging { /// <summary> /// Base type of all asynchronous tagger providers (<see cref="ITaggerProvider"/> and <see cref="IViewTaggerProvider"/>). /// </summary> internal abstract partial class AbstractAsynchronousTaggerProvider<TTag> : ForegroundThreadAffinitizedObject where TTag : ITag { private readonly object _uniqueKey = new object(); private readonly IAsynchronousOperationListener _asyncListener; private readonly IForegroundNotificationService _notificationService; /// <summary> /// The behavior the tagger engine will have when text changes happen to the subject buffer /// it is attached to. Most taggers can simply use <see cref="TaggerTextChangeBehavior.None"/>. /// However, advanced taggers that want to perform specialized behavior depending on what has /// actually changed in the file can specify <see cref="TaggerTextChangeBehavior.TrackTextChanges"/>. /// /// If this is specified the tagger engine will track text changes and pass them along as /// <see cref="TaggerContext{TTag}.TextChangeRange"/> when calling /// <see cref="ProduceTagsAsync(TaggerContext{TTag})"/>. /// </summary> protected virtual TaggerTextChangeBehavior TextChangeBehavior => TaggerTextChangeBehavior.None; /// <summary> /// The behavior the tagger will have when changes happen to the caret. /// </summary> protected virtual TaggerCaretChangeBehavior CaretChangeBehavior => TaggerCaretChangeBehavior.None; /// <summary> /// The behavior of tags that are created by the async tagger. This will matter for tags /// created for a previous version of a document that are mapped forward by the async /// tagging architecture. This value cannot be <see cref="SpanTrackingMode.Custom"/>. /// </summary> protected virtual SpanTrackingMode SpanTrackingMode => SpanTrackingMode.EdgeExclusive; /// <summary> /// Comparer used to determine if two <see cref="ITag"/>s are the same. This is used by /// the <see cref="AbstractAsynchronousTaggerProvider{TTag}"/> to determine if a previous set of /// computed tags and a current set of computed tags should be considered the same or not. /// If they are the same, then the UI will not be updated. If they are different then /// the UI will be updated for sets of tags that have been removed or added. /// </summary> protected virtual IEqualityComparer<TTag> TagComparer => EqualityComparer<TTag>.Default; /// <summary> /// Options controlling this tagger. The tagger infrastructure will check this option /// against the buffer it is associated with to see if it should tag or not. /// /// An empty enumerable, or null, can be returned to indicate that this tagger should /// run unconditionally. /// </summary> protected virtual IEnumerable<Option<bool>> Options => SpecializedCollections.EmptyEnumerable<Option<bool>>(); protected virtual IEnumerable<PerLanguageOption<bool>> PerLanguageOptions => SpecializedCollections.EmptyEnumerable<PerLanguageOption<bool>>(); /// <summary> /// This controls what delay tagger will use to let editor know about newly inserted tags /// </summary> protected virtual TaggerDelay AddedTagNotificationDelay => TaggerDelay.NearImmediate; /// <summary> /// This controls what delay tagger will use to let editor know about just deleted tags. /// </summary> protected virtual TaggerDelay RemovedTagNotificationDelay => TaggerDelay.NearImmediate; #if DEBUG public readonly string StackTrace; #endif protected AbstractAsynchronousTaggerProvider( IAsynchronousOperationListener asyncListener, IForegroundNotificationService notificationService) { _asyncListener = asyncListener; _notificationService = notificationService; #if DEBUG StackTrace = new StackTrace().ToString(); #endif } private TagSource CreateTagSource(ITextView textViewOpt, ITextBuffer subjectBuffer) { return new TagSource(textViewOpt, subjectBuffer, this, _asyncListener, _notificationService); } internal IAccurateTagger<T> GetOrCreateTagger<T>(ITextView textViewOpt, ITextBuffer subjectBuffer) where T : ITag { if (!subjectBuffer.GetOption(EditorComponentOnOffOptions.Tagger)) { return null; } var tagSource = GetOrCreateTagSource(textViewOpt, subjectBuffer); return tagSource == null ? null : new Tagger(_asyncListener, _notificationService, tagSource, subjectBuffer) as IAccurateTagger<T>; } private TagSource GetOrCreateTagSource(ITextView textViewOpt, ITextBuffer subjectBuffer) { TagSource tagSource; if (!this.TryRetrieveTagSource(textViewOpt, subjectBuffer, out tagSource)) { tagSource = this.CreateTagSource(textViewOpt, subjectBuffer); if (tagSource == null) { return null; } this.StoreTagSource(textViewOpt, subjectBuffer, tagSource); tagSource.Disposed += (s, e) => this.RemoveTagSource(textViewOpt, subjectBuffer); } return tagSource; } private bool TryRetrieveTagSource(ITextView textViewOpt, ITextBuffer subjectBuffer, out TagSource tagSource) { return textViewOpt != null ? textViewOpt.TryGetPerSubjectBufferProperty(subjectBuffer, _uniqueKey, out tagSource) : subjectBuffer.Properties.TryGetProperty(_uniqueKey, out tagSource); } private void RemoveTagSource(ITextView textViewOpt, ITextBuffer subjectBuffer) { if (textViewOpt != null) { textViewOpt.RemovePerSubjectBufferProperty<TagSource, ITextView>(subjectBuffer, _uniqueKey); } else { subjectBuffer.Properties.RemoveProperty(_uniqueKey); } } private void StoreTagSource(ITextView textViewOpt, ITextBuffer subjectBuffer, TagSource tagSource) { if (textViewOpt != null) { textViewOpt.AddPerSubjectBufferProperty(subjectBuffer, _uniqueKey, tagSource); } else { subjectBuffer.Properties.AddProperty(_uniqueKey, tagSource); } } /// <summary> /// Called by the <see cref="AbstractAsynchronousTaggerProvider{TTag}"/> infrastructure to /// determine the caret position. This value will be passed in as the value to /// <see cref="TaggerContext{TTag}.CaretPosition"/> in the call to /// <see cref="ProduceTagsAsync(TaggerContext{TTag})"/>. /// </summary> protected virtual SnapshotPoint? GetCaretPoint(ITextView textViewOpt, ITextBuffer subjectBuffer) { return textViewOpt?.GetCaretPoint(subjectBuffer); } /// <summary> /// Called by the <see cref="AbstractAsynchronousTaggerProvider{TTag}"/> infrastructure to determine /// the set of spans that it should asynchronously tag. This will be called in response to /// notifications from the <see cref="ITaggerEventSource"/> that something has changed, and /// will only be called from the UI thread. The tagger infrastructure will then determine /// the <see cref="DocumentSnapshotSpan"/>s associated with these <see cref="SnapshotSpan"/>s /// and will asynchronously call into <see cref="ProduceTagsAsync(TaggerContext{TTag})"/> at some point in /// the future to produce tags for these spans. /// </summary> protected virtual IEnumerable<SnapshotSpan> GetSpansToTag(ITextView textViewOpt, ITextBuffer subjectBuffer) { // For a standard tagger, the spans to tag is the span of the entire snapshot. return new[] { subjectBuffer.CurrentSnapshot.GetFullSpan() }; } /// <summary> /// Creates the <see cref="ITaggerEventSource"/> that notifies the <see cref="AbstractAsynchronousTaggerProvider{TTag}"/> /// that it should recompute tags for the text buffer after an appropriate <see cref="TaggerDelay"/>. /// </summary> protected abstract ITaggerEventSource CreateEventSource(ITextView textViewOpt, ITextBuffer subjectBuffer); internal Task ProduceTagsAsync_ForTestingPurposesOnly(TaggerContext<TTag> context) { return ProduceTagsAsync(context); } /// <summary> /// Produce tags for the given context. /// Keep in sync with <see cref="ProduceTagsSynchronously(TaggerContext{TTag})"/> /// </summary> protected virtual async Task ProduceTagsAsync(TaggerContext<TTag> context) { foreach (var spanToTag in context.SpansToTag) { context.CancellationToken.ThrowIfCancellationRequested(); await ProduceTagsAsync( context, spanToTag, GetCaretPosition(context.CaretPosition, spanToTag.SnapshotSpan)).ConfigureAwait(false); } } /// <summary> /// Produce tags for the given context. /// Keep in sync with <see cref="ProduceTagsAsync(TaggerContext{TTag})"/> /// </summary> protected void ProduceTagsSynchronously(TaggerContext<TTag> context) { foreach (var spanToTag in context.SpansToTag) { context.CancellationToken.ThrowIfCancellationRequested(); ProduceTagsSynchronously( context, spanToTag, GetCaretPosition(context.CaretPosition, spanToTag.SnapshotSpan)); } } private static int? GetCaretPosition(SnapshotPoint? caretPosition, SnapshotSpan snapshotSpan) { return caretPosition.HasValue && caretPosition.Value.Snapshot == snapshotSpan.Snapshot ? caretPosition.Value.Position : (int?)null; } protected virtual Task ProduceTagsAsync(TaggerContext<TTag> context, DocumentSnapshotSpan spanToTag, int? caretPosition) { return SpecializedTasks.EmptyTask; } protected virtual void ProduceTagsSynchronously(TaggerContext<TTag> context, DocumentSnapshotSpan spanToTag, int? caretPosition) { // By default we implement the sync version of this by blocking on the async version. // // The benefit of this is that all taggers can implicitly be used as IAccurateTaggers // without any code changes. // // However, the drawback is that it means the UI thread might be blocked waiting for // tasks to be scheduled and run on the threadpool. // // Taggers that need to be called accurately should override this method to produce // results quickly if possible. ProduceTagsAsync(context, spanToTag, caretPosition).Wait(context.CancellationToken); } private struct DiffResult { public NormalizedSnapshotSpanCollection Added { get; } public NormalizedSnapshotSpanCollection Removed { get; } public DiffResult(List<SnapshotSpan> added, List<SnapshotSpan> removed) : this(added?.Count == 0 ? null : (IEnumerable<SnapshotSpan>)added, removed?.Count == 0 ? null : (IEnumerable<SnapshotSpan>)removed) { } public DiffResult(IEnumerable<SnapshotSpan> added, IEnumerable<SnapshotSpan> removed) { Added = added != null ? new NormalizedSnapshotSpanCollection(added) : NormalizedSnapshotSpanCollection.Empty; Removed = removed != null ? new NormalizedSnapshotSpanCollection(removed) : NormalizedSnapshotSpanCollection.Empty; } public int Count => Added.Count + Removed.Count; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void CompareEqualScalarSingle() { var test = new SimpleBinaryOpTest__CompareEqualScalarSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareEqualScalarSingle { private const int VectorSize = 16; private const int ElementCount = VectorSize / sizeof(Single); private static Single[] _data1 = new Single[ElementCount]; private static Single[] _data2 = new Single[ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private SimpleBinaryOpTest__DataTable<Single> _dataTable; static SimpleBinaryOpTest__CompareEqualScalarSingle() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__CompareEqualScalarSingle() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); } _dataTable = new SimpleBinaryOpTest__DataTable<Single>(_data1, _data2, new Single[ElementCount], VectorSize); } public bool IsSupported => Sse.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse.CompareEqualScalar( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse.CompareEqualScalar( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse.CompareEqualScalar( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse).GetMethod(nameof(Sse.CompareEqualScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse).GetMethod(nameof(Sse.CompareEqualScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse).GetMethod(nameof(Sse.CompareEqualScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse.CompareEqualScalar( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse.CompareEqualScalar(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.CompareEqualScalar(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.CompareEqualScalar(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__CompareEqualScalarSingle(); var result = Sse.CompareEqualScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse.CompareEqualScalar(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[ElementCount]; Single[] inArray2 = new Single[ElementCount]; Single[] outArray = new Single[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[ElementCount]; Single[] inArray2 = new Single[ElementCount]; Single[] outArray = new Single[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { if (BitConverter.SingleToInt32Bits(result[0]) != ((left[0] == right[0]) ? -1 : 0)) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if (BitConverter.SingleToInt32Bits(left[i]) != BitConverter.SingleToInt32Bits(result[i])) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse)}.{nameof(Sse.CompareEqualScalar)}<Single>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if !W8CORE using System; namespace SharpDX.Direct3D11 { public partial class FastFourierTransform { private FastFourierTransformBufferRequirements _bufferRequirements; /// <summary> /// Initializes a new instance of the <see cref="T:SharpDX.Direct3D11.FastFourierTransform" /> class. /// </summary> /// <param name="context">The device context used to create the FFT.</param> /// <param name="description">Information that describes the shape of the FFT data as well as the scaling factors that should be used for forward and inverse transforms.</param> public FastFourierTransform(DeviceContext context, FastFourierTransformDescription description) : this(context, description, FastFourierTransformCreationFlags.None) { } /// <summary> /// Initializes a new instance of the <see cref="T:SharpDX.Direct3D11.FastFourierTransform" /> class. /// </summary> /// <param name="context">The device context used to create the FFT.</param> /// <param name="description">Information that describes the shape of the FFT data as well as the scaling factors that should be used for forward and inverse transforms.</param> /// <param name="flags">Flag affecting the behavior of the FFT.</param> public FastFourierTransform(DeviceContext context, FastFourierTransformDescription description, FastFourierTransformCreationFlags flags) : base(IntPtr.Zero) { D3DCSX.CreateFFT(context, ref description, (int)flags, out _bufferRequirements, this); } /// <summary> /// Attaches buffers to an FFT context and performs any required precomputations. /// </summary> /// <remarks> /// The buffers must be no smaller than the corresponding buffer sizes returned by D3DX11CreateFFT*(). Temporary buffers can be shared between multiple contexts, though care should be taken not to concurrently execute multiple FFTs which share temp buffers. /// </remarks> /// <param name="temporaryBuffers">Temporary buffers to attach. </param> /// <param name="precomputeBuffers">Buffers to hold precomputed data. </param> /// <returns>Returns one of the return codes described in the topic {{Direct3D 11 Return Codes}}. </returns> /// <unmanaged>HRESULT ID3DX11FFT::AttachBuffersAndPrecompute([In] int NumTempBuffers,[In, Buffer] const ID3D11UnorderedAccessView** ppTempBuffers,[In] int NumPrecomputeBuffers,[In, Buffer] const ID3D11UnorderedAccessView** ppPrecomputeBufferSizes)</unmanaged> public void AttachBuffersAndPrecompute(UnorderedAccessView[] temporaryBuffers, UnorderedAccessView[] precomputeBuffers) { AttachBuffersAndPrecompute(temporaryBuffers.Length, temporaryBuffers, precomputeBuffers.Length, precomputeBuffers); } /// <summary> /// Creates a new one-dimensional complex FFT. /// </summary> /// <param name="context">Pointer to the <see cref="SharpDX.Direct3D11.DeviceContext"/> interface to use for the FFT. </param> /// <param name="x">Length of the first dimension of the FFT. </param> /// <returns>an <see cref="SharpDX.Direct3D11.FastFourierTransform"/> interface reference.</returns> /// <unmanaged>HRESULT D3DX11CreateFFT1DComplex([None] ID3D11DeviceContext* pDeviceContext,[None] int X,[None] int Flags,[Out] D3DX11_FFT_BUFFER_INFO* pBufferInfo,[Out] ID3DX11FFT** ppFFT)</unmanaged> public static FastFourierTransform Create1DComplex(DeviceContext context, int x) { return Create1DComplex(context, x, FastFourierTransformCreationFlags.None); } /// <summary> /// Creates a new one-dimensional complex FFT. /// </summary> /// <param name="context">Pointer to the <see cref="SharpDX.Direct3D11.DeviceContext"/> interface to use for the FFT. </param> /// <param name="x">Length of the first dimension of the FFT. </param> /// <param name="flags">Flag affecting the behavior of the FFT, can be 0 or a combination of flags from <see cref="SharpDX.Direct3D11.FastFourierTransformCreationFlags"/>. </param> /// <returns>an <see cref="SharpDX.Direct3D11.FastFourierTransform"/> interface reference.</returns> /// <unmanaged>HRESULT D3DX11CreateFFT1DComplex([None] ID3D11DeviceContext* pDeviceContext,[None] int X,[None] int Flags,[Out] D3DX11_FFT_BUFFER_INFO* pBufferInfo,[Out] ID3DX11FFT** ppFFT)</unmanaged> public static FastFourierTransform Create1DComplex(DeviceContext context, int x, FastFourierTransformCreationFlags flags) { FastFourierTransformBufferRequirements info; FastFourierTransform temp; D3DCSX.CreateFFT1DComplex(context, x, (int)flags, out info, out temp); temp.BufferRequirements = info; return temp; } /// <summary> /// Creates a new one-dimensional real FFT. /// </summary> /// <param name="context">Pointer to the <see cref="SharpDX.Direct3D11.DeviceContext"/> interface to use for the FFT. </param> /// <param name="x">Length of the first dimension of the FFT. </param> /// <returns>an <see cref="SharpDX.Direct3D11.FastFourierTransform"/> interface reference.</returns> /// <unmanaged>HRESULT D3DX11CreateFFT1DReal([None] ID3D11DeviceContext* pDeviceContext,[None] int X,[None] int Flags,[Out] D3DX11_FFT_BUFFER_INFO* pBufferInfo,[Out] ID3DX11FFT** ppFFT)</unmanaged> public static FastFourierTransform Create1DReal(DeviceContext context, int x) { return Create1DReal(context, x, FastFourierTransformCreationFlags.None); } /// <summary> /// Creates a new one-dimensional real FFT. /// </summary> /// <param name="context">Pointer to the <see cref="SharpDX.Direct3D11.DeviceContext"/> interface to use for the FFT. </param> /// <param name="x">Length of the first dimension of the FFT. </param> /// <param name="flags">Flag affecting the behavior of the FFT, can be 0 or a combination of flags from <see cref="SharpDX.Direct3D11.FastFourierTransformCreationFlags"/>. </param> /// <returns>an <see cref="SharpDX.Direct3D11.FastFourierTransform"/> interface reference.</returns> /// <unmanaged>HRESULT D3DX11CreateFFT1DReal([None] ID3D11DeviceContext* pDeviceContext,[None] int X,[None] int Flags,[Out] D3DX11_FFT_BUFFER_INFO* pBufferInfo,[Out] ID3DX11FFT** ppFFT)</unmanaged> public static FastFourierTransform Create1DReal(DeviceContext context, int x, FastFourierTransformCreationFlags flags) { FastFourierTransformBufferRequirements info; FastFourierTransform temp; D3DCSX.CreateFFT1DReal(context, x, (int)flags, out info, out temp); temp.BufferRequirements = info; return temp; } /// <summary> /// Creates a new two-dimensional complex FFT. /// </summary> /// <param name="context">Pointer to the <see cref="SharpDX.Direct3D11.DeviceContext"/> interface to use for the FFT. </param> /// <param name="x">Length of the first dimension of the FFT.</param> /// <param name="y">Length of the second dimension of the FFT.</param> /// <returns>an <see cref="SharpDX.Direct3D11.FastFourierTransform"/> interface reference.</returns> /// <unmanaged>HRESULT D3DX11CreateFFT1DReal([None] ID3D11DeviceContext* pDeviceContext,[None] int X,[None] int Flags,[Out] D3DX11_FFT_BUFFER_INFO* pBufferInfo,[Out] ID3DX11FFT** ppFFT)</unmanaged> public static FastFourierTransform Create2DComplex(DeviceContext context, int x, int y) { return Create2DComplex(context, x, y, FastFourierTransformCreationFlags.None); } /// <summary> /// Creates a new two-dimensional complex FFT. /// </summary> /// <param name="context">Pointer to the <see cref="SharpDX.Direct3D11.DeviceContext"/> interface to use for the FFT. </param> /// <param name="x">Length of the first dimension of the FFT.</param> /// <param name="y">Length of the second dimension of the FFT.</param> /// <param name="flags">Flag affecting the behavior of the FFT, can be 0 or a combination of flags from <see cref="SharpDX.Direct3D11.FastFourierTransformCreationFlags"/>. </param> /// <returns>an <see cref="SharpDX.Direct3D11.FastFourierTransform"/> interface reference.</returns> /// <unmanaged>HRESULT D3DX11CreateFFT1DReal([None] ID3D11DeviceContext* pDeviceContext,[None] int X,[None] int Flags,[Out] D3DX11_FFT_BUFFER_INFO* pBufferInfo,[Out] ID3DX11FFT** ppFFT)</unmanaged> public static FastFourierTransform Create2DComplex(DeviceContext context, int x, int y, FastFourierTransformCreationFlags flags) { FastFourierTransformBufferRequirements info; FastFourierTransform temp; D3DCSX.CreateFFT2DComplex(context, x, y, (int)flags, out info, out temp); temp.BufferRequirements = info; return temp; } /// <summary> /// Creates a new two-dimensional real FFT. /// </summary> /// <param name="context">Pointer to the <see cref="SharpDX.Direct3D11.DeviceContext"/> interface to use for the FFT. </param> /// <param name="x">Length of the first dimension of the FFT.</param> /// <param name="y">Length of the second dimension of the FFT.</param> /// <returns>an <see cref="SharpDX.Direct3D11.FastFourierTransform"/> interface reference.</returns> /// <unmanaged>HRESULT D3DX11CreateFFT1DReal([None] ID3D11DeviceContext* pDeviceContext,[None] int X,[None] int Flags,[Out] D3DX11_FFT_BUFFER_INFO* pBufferInfo,[Out] ID3DX11FFT** ppFFT)</unmanaged> public static FastFourierTransform Create2DReal(DeviceContext context, int x, int y) { return Create2DReal(context, x, y, FastFourierTransformCreationFlags.None); } /// <summary> /// Creates a new two-dimensional real FFT. /// </summary> /// <param name="context">Pointer to the <see cref="SharpDX.Direct3D11.DeviceContext"/> interface to use for the FFT. </param> /// <param name="x">Length of the first dimension of the FFT.</param> /// <param name="y">Length of the second dimension of the FFT.</param> /// <param name="flags">Flag affecting the behavior of the FFT, can be 0 or a combination of flags from <see cref="SharpDX.Direct3D11.FastFourierTransformCreationFlags"/>. </param> /// <returns>an <see cref="SharpDX.Direct3D11.FastFourierTransform"/> interface reference.</returns> /// <unmanaged>HRESULT D3DX11CreateFFT1DReal([None] ID3D11DeviceContext* pDeviceContext,[None] int X,[None] int Flags,[Out] D3DX11_FFT_BUFFER_INFO* pBufferInfo,[Out] ID3DX11FFT** ppFFT)</unmanaged> public static FastFourierTransform Create2DReal(DeviceContext context, int x, int y, FastFourierTransformCreationFlags flags) { FastFourierTransformBufferRequirements info; FastFourierTransform temp; D3DCSX.CreateFFT2DReal(context, x, y, (int)flags, out info, out temp); temp.BufferRequirements = info; return temp; } /// <summary> /// Creates a new three-dimensional complex FFT. /// </summary> /// <param name="context">Pointer to the <see cref="SharpDX.Direct3D11.DeviceContext"/> interface to use for the FFT. </param> /// <param name="x">Length of the first dimension of the FFT.</param> /// <param name="y">Length of the second dimension of the FFT.</param> /// <param name="z">Length of the third dimension of the FFT.</param> /// <returns>an <see cref="SharpDX.Direct3D11.FastFourierTransform"/> interface reference.</returns> /// <unmanaged>HRESULT D3DX11CreateFFT1DReal([None] ID3D11DeviceContext* pDeviceContext,[None] int X,[None] int Flags,[Out] D3DX11_FFT_BUFFER_INFO* pBufferInfo,[Out] ID3DX11FFT** ppFFT)</unmanaged> public static FastFourierTransform Create3DComplex(DeviceContext context, int x, int y, int z) { return Create3DComplex(context, x, y, z, FastFourierTransformCreationFlags.None); } /// <summary> /// Creates a new three-dimensional complex FFT. /// </summary> /// <param name="context">Pointer to the <see cref="SharpDX.Direct3D11.DeviceContext"/> interface to use for the FFT. </param> /// <param name="x">Length of the first dimension of the FFT.</param> /// <param name="y">Length of the second dimension of the FFT.</param> /// <param name="z">Length of the third dimension of the FFT.</param> /// <param name="flags">Flag affecting the behavior of the FFT, can be 0 or a combination of flags from <see cref="SharpDX.Direct3D11.FastFourierTransformCreationFlags"/>. </param> /// <returns>an <see cref="SharpDX.Direct3D11.FastFourierTransform"/> interface reference.</returns> /// <unmanaged>HRESULT D3DX11CreateFFT1DReal([None] ID3D11DeviceContext* pDeviceContext,[None] int X,[None] int Flags,[Out] D3DX11_FFT_BUFFER_INFO* pBufferInfo,[Out] ID3DX11FFT** ppFFT)</unmanaged> public static FastFourierTransform Create3DComplex(DeviceContext context, int x, int y, int z, FastFourierTransformCreationFlags flags) { FastFourierTransformBufferRequirements info; FastFourierTransform temp; D3DCSX.CreateFFT3DComplex(context, x, y, z, (int)flags, out info, out temp); temp.BufferRequirements = info; return temp; } /// <summary> /// Creates a new three-dimensional real FFT. /// </summary> /// <param name="context">Pointer to the <see cref="SharpDX.Direct3D11.DeviceContext"/> interface to use for the FFT. </param> /// <param name="x">Length of the first dimension of the FFT.</param> /// <param name="y">Length of the second dimension of the FFT.</param> /// <param name="z">Length of the third dimension of the FFT.</param> /// <returns>an <see cref="SharpDX.Direct3D11.FastFourierTransform"/> interface reference.</returns> /// <unmanaged>HRESULT D3DX11CreateFFT1DReal([None] ID3D11DeviceContext* pDeviceContext,[None] int X,[None] int Flags,[Out] D3DX11_FFT_BUFFER_INFO* pBufferInfo,[Out] ID3DX11FFT** ppFFT)</unmanaged> public static FastFourierTransform Create3DReal(DeviceContext context, int x, int y, int z) { return Create3DReal(context, x, y, z, FastFourierTransformCreationFlags.None); } /// <summary> /// Creates a new three-dimensional real FFT. /// </summary> /// <param name="context">Pointer to the <see cref="SharpDX.Direct3D11.DeviceContext"/> interface to use for the FFT. </param> /// <param name="x">Length of the first dimension of the FFT.</param> /// <param name="y">Length of the second dimension of the FFT.</param> /// <param name="z">Length of the third dimension of the FFT.</param> /// <param name="flags">Flag affecting the behavior of the FFT, can be 0 or a combination of flags from <see cref="SharpDX.Direct3D11.FastFourierTransformCreationFlags"/>. </param> /// <returns>an <see cref="SharpDX.Direct3D11.FastFourierTransform"/> interface reference.</returns> /// <unmanaged>HRESULT D3DX11CreateFFT1DReal([None] ID3D11DeviceContext* pDeviceContext,[None] int X,[None] int Flags,[Out] D3DX11_FFT_BUFFER_INFO* pBufferInfo,[Out] ID3DX11FFT** ppFFT)</unmanaged> public static FastFourierTransform Create3DReal(DeviceContext context, int x, int y, int z, FastFourierTransformCreationFlags flags) { FastFourierTransformBufferRequirements info; FastFourierTransform temp; D3DCSX.CreateFFT3DReal(context, x, y, z, (int)flags, out info, out temp); temp.BufferRequirements = info; return temp; } /// <summary> /// Performs a forward FFT. /// </summary> /// <param name="inputBufferRef">Pointer to <see cref="SharpDX.Direct3D11.UnorderedAccessView"/> onto the input buffer.</param> /// <returns> /// Returns the computation in a temp buffers; in addition, the last buffer written to is returned. /// </returns> /// <unmanaged>HRESULT ID3DX11FFT::ForwardTransform([In] const ID3D11UnorderedAccessView* pInputBuffer,[InOut] void** ppOutputBuffer)</unmanaged> /// <remarks> /// ForwardTransform can be called after buffers have been attached to the context using <see cref="SharpDX.Direct3D11.FastFourierTransform.AttachBuffersAndPrecompute"/>. The combination of pInputBuffer and *ppOuputBuffer can be one of the temp buffers.The format of complex data is interleaved components (for example, (Real0, Imag0), (Real1, Imag1) ... , and so on). Data is stored in row major order. /// </remarks> public SharpDX.Direct3D11.UnorderedAccessView ForwardTransform(SharpDX.Direct3D11.UnorderedAccessView inputBufferRef) { IntPtr returnView = IntPtr.Zero; ForwardTransform(inputBufferRef, ref returnView); return new UnorderedAccessView(returnView); } /// <summary> /// Performs an inverse FFT. /// </summary> /// <param name="inputBufferRef"><para>Pointer to <see cref="SharpDX.Direct3D11.UnorderedAccessView"/> onto the input buffer.</para></param> /// <returns> /// Returns the computation in a temp buffers; in addition, the last buffer written to is returned. /// </returns> /// <unmanaged>HRESULT ID3DX11FFT::InverseTransform([In] const ID3D11UnorderedAccessView* pInputBuffer,[InOut] void** ppOutputBuffer)</unmanaged> public SharpDX.Direct3D11.UnorderedAccessView InverseTransform(SharpDX.Direct3D11.UnorderedAccessView inputBufferRef) { IntPtr returnView = IntPtr.Zero; InverseTransform(inputBufferRef, ref returnView); return new UnorderedAccessView(returnView); } /// <summary> /// Performs a forward FFT. /// </summary> /// <param name="inputBufferRef">Pointer to <see cref="SharpDX.Direct3D11.UnorderedAccessView"/> onto the input buffer.</param> /// <param name="outputBufferView"><para>Buffer <see cref="SharpDX.Direct3D11.UnorderedAccessView"/> reference used as the output buffer.</para></param> /// <returns>Returns one of the return codes described in the topic Direct3D 11 Return Codes.</returns> /// <unmanaged>HRESULT ID3DX11FFT::ForwardTransform([In] const ID3D11UnorderedAccessView* pInputBuffer,[InOut] void** ppOutputBuffer)</unmanaged> /// <remarks> /// ForwardTransform can be called after buffers have been attached to the context using <see cref="SharpDX.Direct3D11.FastFourierTransform.AttachBuffersAndPrecompute"/>. The combination of pInputBuffer and *ppOuputBuffer can be one of the temp buffers.The format of complex data is interleaved components (for example, (Real0, Imag0), (Real1, Imag1) ... , and so on). Data is stored in row major order. /// </remarks> public void ForwardTransform(SharpDX.Direct3D11.UnorderedAccessView inputBufferRef, SharpDX.Direct3D11.UnorderedAccessView outputBufferView) { IntPtr outputView = outputBufferView.NativePointer; ForwardTransform(inputBufferRef, ref outputView); } /// <summary> /// Performs an inverse FFT. /// </summary> /// <param name="inputBufferRef"><para>Pointer to <see cref="SharpDX.Direct3D11.UnorderedAccessView"/> onto the input buffer.</para></param> /// <param name="outputBufferView"><para>Buffer <see cref="SharpDX.Direct3D11.UnorderedAccessView"/> reference used as the output buffer.</para></param> /// <returns>Returns one of the return codes described in the topic Direct3D 11 Return Codes.</returns> /// <unmanaged>HRESULT ID3DX11FFT::InverseTransform([In] const ID3D11UnorderedAccessView* pInputBuffer,[InOut] void** ppOutputBuffer)</unmanaged> public void InverseTransform(SharpDX.Direct3D11.UnorderedAccessView inputBufferRef, SharpDX.Direct3D11.UnorderedAccessView outputBufferView) { IntPtr outputView = outputBufferView.NativePointer; InverseTransform(inputBufferRef, ref outputView); } /// <summary> /// Gets the buffer requirements. /// </summary> /// <value>The buffer requirements.</value> public FastFourierTransformBufferRequirements BufferRequirements { get { return _bufferRequirements; } private set { _bufferRequirements = value; } } } } #endif
// Copyright (c) 2015 Alachisoft // // 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. using System; using System.Text; using System.Reflection; /// <summary> /// The namespace provides the CompactReader and CompactWriter that are required /// while implementing the Serialize and Deserialize methods of ICompactSerializable interface. /// </summary> namespace Alachisoft.NCache.Runtime.Serialization.IO { /// <summary> /// CompactReader is the base class for CompactBinaryReader. /// </summary> /// <remark> /// This Feature is Not Available in Express /// </remark> public abstract class CompactReader { /// <summary> /// Reads an object of type <see cref="object"/> from the current stream /// and advances the stream position. /// </summary> /// <returns>object read from the stream</returns> public abstract object ReadObject(); public abstract T ReadObjectAs<T>(); /// <summary> /// Skips an object of type <see cref="object"/> from the current stream /// and advances the stream position. /// </summary> public abstract void SkipObject(); public abstract void SkipObjectAs<T>(); #region / CompactBinaryReader.ReadXXX / /// <summary> /// Reads an object of type <see cref="bool"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public abstract bool ReadBoolean(); /// <summary> /// Reads an object of type <see cref="byte"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public abstract byte ReadByte(); /// <summary> /// Reads an object of type <see cref="byte[]"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <param name="count">number of bytes read</param> /// <returns>object read from the stream</returns> public abstract byte[] ReadBytes(int count); /// <summary> /// Reads an object of type <see cref="char"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public abstract char ReadChar(); /// <summary> /// Reads an object of type <see cref="char[]"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public abstract char[] ReadChars(int count); /// <summary> /// Reads an object of type <see cref="decimal"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public abstract decimal ReadDecimal(); /// <summary> /// Reads an object of type <see cref="float"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public abstract float ReadSingle(); /// <summary> /// Reads an object of type <see cref="double"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public abstract double ReadDouble(); /// <summary> /// Reads an object of type <see cref="short"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public abstract short ReadInt16(); /// <summary> /// Reads an object of type <see cref="int"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public abstract int ReadInt32(); /// <summary> /// Reads an object of type <see cref="long"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public abstract long ReadInt64(); /// <summary> /// Reads an object of type <see cref="string"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public abstract string ReadString(); /// <summary> /// Reads an object of type <see cref="DateTime"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public abstract DateTime ReadDateTime(); /// <summary> /// Reads an object of type <see cref="Guid"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> public abstract Guid ReadGuid(); /// <summary> /// Reads the specifies number of bytes into <paramref name="buffer"/>. /// This method reads directly from the underlying stream. /// </summary> /// <param name="buffer">buffer to read into</param> /// <param name="index">starting position in the buffer</param> /// <param name="count">number of bytes to write</param> /// <returns>number of buffer read</returns> public abstract int Read(byte[] buffer, int index, int count); /// <summary> /// Reads the specifies number of bytes into <paramref name="buffer"/>. /// This method reads directly from the underlying stream. /// </summary> /// <param name="buffer">buffer to read into</param> /// <param name="index">starting position in the buffer</param> /// <param name="count">number of bytes to write</param> /// <returns>number of chars read</returns> public abstract int Read(char[] buffer, int index, int count); /// <summary> /// Reads an object of type <see cref="sbyte"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> [CLSCompliant(false)] public virtual sbyte ReadSByte() { return 0; } /// <summary> /// Reads an object of type <see cref="ushort"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> [CLSCompliant(false)] public virtual ushort ReadUInt16() { return 0; } /// <summary> /// Reads an object of type <see cref="uint"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> [CLSCompliant(false)] public virtual uint ReadUInt32() { return 0; } /// <summary> /// Reads an object of type <see cref="ulong"/> from the current stream /// and advances the stream position. /// This method reads directly from the underlying stream. /// </summary> /// <returns>object read from the stream</returns> [CLSCompliant(false)] public virtual ulong ReadUInt64() { return 0; } #endregion #region / CompactBinaryReader.SkipXXX / /// <summary> /// Skips an object of type <see cref="bool"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public abstract void SkipBoolean(); /// <summary> /// Skips an object of type <see cref="byte"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public abstract void SkipByte(); /// <summary> /// Skips an object of type <see cref="byte[]"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> /// <param name="count">number of bytes read</param> public abstract void SkipBytes(int count); /// <summary> /// Skips an object of type <see cref="char"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public abstract void SkipChar(); /// <summary> /// Skips an object of type <see cref="char[]"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public abstract void SkipChars(int count); /// <summary> /// Skips an object of type <see cref="decimal"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public abstract void SkipDecimal(); /// <summary> /// Skips an object of type <see cref="float"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public abstract void SkipSingle(); /// <summary> /// Skips an object of type <see cref="double"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public abstract void SkipDouble(); /// <summary> /// Skips an object of type <see cref="short"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public abstract void SkipInt16(); /// <summary> /// Skips an object of type <see cref="int"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public abstract void SkipInt32(); /// <summary> /// Skips an object of type <see cref="long"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public abstract void SkipInt64(); /// <summary> /// Skips an object of type <see cref="string"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public abstract void SkipString(); /// <summary> /// Skips an object of type <see cref="DateTime"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public abstract void SkipDateTime(); /// <summary> /// Skips an object of type <see cref="Guid"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> public abstract void SkipGuid(); /// <summary> /// Skips an object of type <see cref="sbyte"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> [CLSCompliant(false)] public virtual void SkipSByte() { } /// <summary> /// Skips an object of type <see cref="ushort"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> [CLSCompliant(false)] public virtual void SkipUInt16() { } /// <summary> /// Skips an object of type <see cref="uint"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> [CLSCompliant(false)] public virtual void SkipUInt32() { } /// <summary> /// Skips an object of type <see cref="ulong"/> from the current stream /// and advances the stream position. /// This method Skips directly from the underlying stream. /// </summary> [CLSCompliant(false)] public virtual void SkipUInt64() { } #endregion } }
using CA; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using UnityEngine; namespace CA { public static class MemberInfoExtensions { public static bool CanWrite(this MemberInfo info) { switch (info.MemberType) { case MemberTypes.Field: return true; case MemberTypes.Property: var p = (info as PropertyInfo); return p.CanWrite; case MemberTypes.Constructor: case MemberTypes.Method: case MemberTypes.Event: case MemberTypes.TypeInfo: case MemberTypes.Custom: case MemberTypes.NestedType: case MemberTypes.All: default: return false; } } public static Type GetMemberType(this MemberInfo info) { switch (info.MemberType) { case MemberTypes.Event: var e = info as EventInfo; return e.EventHandlerType; case MemberTypes.Field: var f = info as FieldInfo; return f.FieldType; case MemberTypes.Method: var m = info as MethodInfo; return m.ReturnType; case MemberTypes.Property: var p = info as PropertyInfo; return p.PropertyType; case MemberTypes.Constructor: case MemberTypes.TypeInfo: case MemberTypes.Custom: case MemberTypes.NestedType: case MemberTypes.All: default: return null; } } public static void SetValue(this MemberInfo info, object obj, object value) { switch (info.MemberType) { case MemberTypes.Field: var f = (info as FieldInfo); f.SetValue(obj, value); break; case MemberTypes.Property: var p = (info as PropertyInfo); p.SetValue(obj, value, null); break; case MemberTypes.Constructor: case MemberTypes.Method: case MemberTypes.Event: case MemberTypes.TypeInfo: case MemberTypes.Custom: case MemberTypes.NestedType: case MemberTypes.All: default: break; } } } } public static class CAExtensions { private static Dictionary<Type, List<MemberInfo>> TypeMembers = new Dictionary<Type, List<MemberInfo>>(); private const string MISSING = "Component Loader: Unable to load {0} on {1}"; private const string MISSING_ADD = "Component Loader: Adding {0} on {1}"; private const string MISSING_ERROR = "Component Loader: Unable to load {0}, disabling {1} on {2}"; private const string MISSING_OBJECT = "Component Loader: Unable to find a GameObject named {0}"; private const string MISSING_OBJECT_COMPONENT = "Component Loader: Unable to load {0} on {1} for {2}"; private const string MISSING_OBJECT_ADD = "Component Loader: Adding {0} on {1} for {2}"; private const string MISSING_OBJECT_ERROR = "Component Loader: Unable to find a GameObject named {0}, disabling {1} on {2}"; private const string MISSING_OBJECT_CERROR = "Component Loader: Unable to load {0} on {1}, disabling {2} on {3}"; private const string NO_WRITE = "Component Loader: Unable to write {0} on {1}"; private const string NO_WRITE_ERROR = "Component Loader: Unable to write {0} on {1}, disabling it on {2}"; public static void LoadComponents(this MonoBehaviour behaviour) { var bGameObject = behaviour.gameObject; var bType = behaviour.GetType(); var cType = typeof(ComponentAttribute); var mType = typeof(Component); List<MemberInfo> members; if (TypeMembers.ContainsKey(bType)) { members = TypeMembers[bType]; } else { members = bType.GetMembers(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) .Where(m => (m.MemberType == MemberTypes.Field || m.MemberType == MemberTypes.Property) && m.GetMemberType().IsSubclassOf(mType) && m.GetCustomAttributes(cType, true).Length == 1).ToList(); members.OrderBy(m => m.MemberType).ThenBy(m => m.Name); TypeMembers.Add(bType, members); } foreach (var item in members) { var attribute = item.GetCustomAttributes(cType, true)[0] as ComponentAttribute; var memberType = item.GetMemberType(); Component component = null; if (string.IsNullOrEmpty(attribute.GameObject)) { component = behaviour.GetComponent(memberType); } else { var gObj = GameObject.Find(attribute.GameObject); if (gObj != null) { component = gObj.GetComponent(memberType); } else { if (attribute.DisableComponentOnError) { Debug.LogErrorFormat(bGameObject, MISSING_OBJECT_ERROR, attribute.GameObject, bType.Name, behaviour.name); return; } else { Debug.LogWarningFormat(bGameObject, MISSING_OBJECT, attribute.GameObject); continue; } } if (component == null) { if (attribute.AddComponentIfMissing) { Debug.LogWarningFormat(bGameObject, MISSING_OBJECT_ADD, memberType.Name, gObj.name, behaviour.name); component = gObj.AddComponent(memberType); } else if (attribute.DisableComponentOnError) { Debug.LogErrorFormat(bGameObject, MISSING_OBJECT_CERROR, memberType.Name, gObj.name, bType.Name, behaviour.name); behaviour.enabled = false; return; } else { Debug.LogWarningFormat(bGameObject, MISSING_OBJECT_COMPONENT, memberType.Name, gObj.name, bType.Name); continue; } } } if (component == null) { if (attribute.AddComponentIfMissing) { Debug.LogWarningFormat(bGameObject, MISSING_ADD, memberType.Name, behaviour.name); component = behaviour.gameObject.AddComponent(memberType); } else if (attribute.DisableComponentOnError) { Debug.LogErrorFormat(bGameObject, MISSING_ERROR, memberType.Name, bType.Name, behaviour.name); behaviour.enabled = false; return; } else { Debug.LogWarningFormat(bGameObject, MISSING, memberType.Name, behaviour.name); } if (component != null) { if (item.CanWrite()) { item.SetValue(behaviour, component); } else { if (attribute.DisableComponentOnError) { Debug.LogErrorFormat(bGameObject, NO_WRITE_ERROR, item.Name, behaviour.name); behaviour.enabled = false; } else { Debug.LogErrorFormat(bGameObject, NO_WRITE, item.Name, behaviour.name); } } } } else { if (item.CanWrite()) { item.SetValue(behaviour, component); } else { if (attribute.DisableComponentOnError) { Debug.LogErrorFormat(bGameObject, NO_WRITE_ERROR, item.Name, behaviour.name); behaviour.enabled = false; } else { Debug.LogErrorFormat(bGameObject, NO_WRITE, item.Name, behaviour.name); } } } } } } [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, Inherited = false, AllowMultiple = false)] internal sealed class ComponentAttribute : Attribute { public readonly bool AddComponentIfMissing; public readonly bool DisableComponentOnError; public readonly string GameObject; public ComponentAttribute() { AddComponentIfMissing = false; DisableComponentOnError = false; GameObject = ""; } public ComponentAttribute(bool addComponentIfMissing) { AddComponentIfMissing = addComponentIfMissing; DisableComponentOnError = false; GameObject = ""; } public ComponentAttribute(bool addComponentIfMissing, bool disableComponentOnError) { AddComponentIfMissing = addComponentIfMissing; DisableComponentOnError = disableComponentOnError; GameObject = ""; } public ComponentAttribute(string gameObject) { AddComponentIfMissing = false; DisableComponentOnError = false; GameObject = gameObject; } public ComponentAttribute(string gameObject, bool addComponentIfMissing, bool disableComponentOnError) { AddComponentIfMissing = addComponentIfMissing; DisableComponentOnError = disableComponentOnError; GameObject = gameObject; } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace MemoryGame.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copysecond (c) 2017 Atif Aziz. All seconds reserved. // // 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. #endregion namespace MoreLinq { using System; using System.Collections.Generic; static partial class MoreEnumerable { /// <summary> /// Performs a right outer join on two homogeneous sequences. /// Additional arguments specify key selection functions and result /// projection functions. /// </summary> /// <typeparam name="TSource"> /// The type of elements in the source sequence.</typeparam> /// <typeparam name="TKey"> /// The type of the key returned by the key selector function.</typeparam> /// <typeparam name="TResult"> /// The type of the result elements.</typeparam> /// <param name="first"> /// The first sequence of the join operation.</param> /// <param name="second"> /// The second sequence of the join operation.</param> /// <param name="keySelector"> /// Function that projects the key given an element of one of the /// sequences to join.</param> /// <param name="secondSelector"> /// Function that projects the result given just an element from /// <paramref name="second"/> where there is no corresponding element /// in <paramref name="first"/>.</param> /// <param name="bothSelector"> /// Function that projects the result given an element from /// <paramref name="first"/> and an element from <paramref name="second"/> /// that match on a common key.</param> /// <returns>A sequence containing results projected from a right /// outer join of the two input sequences.</returns> public static IEnumerable<TResult> RightJoin<TSource, TKey, TResult>( this IEnumerable<TSource> first, IEnumerable<TSource> second, Func<TSource, TKey> keySelector, Func<TSource, TResult> secondSelector, Func<TSource, TSource, TResult> bothSelector) { if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); return first.RightJoin(second, keySelector, secondSelector, bothSelector, null); } /// <summary> /// Performs a right outer join on two homogeneous sequences. /// Additional arguments specify key selection functions, result /// projection functions and a key comparer. /// </summary> /// <typeparam name="TSource"> /// The type of elements in the source sequence.</typeparam> /// <typeparam name="TKey"> /// The type of the key returned by the key selector function.</typeparam> /// <typeparam name="TResult"> /// The type of the result elements.</typeparam> /// <param name="first"> /// The first sequence of the join operation.</param> /// <param name="second"> /// The second sequence of the join operation.</param> /// <param name="keySelector"> /// Function that projects the key given an element of one of the /// sequences to join.</param> /// <param name="secondSelector"> /// Function that projects the result given just an element from /// <paramref name="second"/> where there is no corresponding element /// in <paramref name="first"/>.</param> /// <param name="bothSelector"> /// Function that projects the result given an element from /// <paramref name="first"/> and an element from <paramref name="second"/> /// that match on a common key.</param> /// <param name="comparer"> /// The <see cref="IEqualityComparer{T}"/> instance used to compare /// keys for equality.</param> /// <returns>A sequence containing results projected from a right /// outer join of the two input sequences.</returns> public static IEnumerable<TResult> RightJoin<TSource, TKey, TResult>( this IEnumerable<TSource> first, IEnumerable<TSource> second, Func<TSource, TKey> keySelector, Func<TSource, TResult> secondSelector, Func<TSource, TSource, TResult> bothSelector, IEqualityComparer<TKey> comparer) { if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); return first.RightJoin(second, keySelector, keySelector, secondSelector, bothSelector, comparer); } /// <summary> /// Performs a right outer join on two heterogeneous sequences. /// Additional arguments specify key selection functions and result /// projection functions. /// </summary> /// <typeparam name="TFirst"> /// The type of elements in the first sequence.</typeparam> /// <typeparam name="TSecond"> /// The type of elements in the second sequence.</typeparam> /// <typeparam name="TKey"> /// The type of the key returned by the key selector functions.</typeparam> /// <typeparam name="TResult"> /// The type of the result elements.</typeparam> /// <param name="first"> /// The first sequence of the join operation.</param> /// <param name="second"> /// The second sequence of the join operation.</param> /// <param name="firstKeySelector"> /// Function that projects the key given an element from <paramref name="first"/>.</param> /// <param name="secondKeySelector"> /// Function that projects the key given an element from <paramref name="second"/>.</param> /// <param name="secondSelector"> /// Function that projects the result given just an element from /// <paramref name="second"/> where there is no corresponding element /// in <paramref name="first"/>.</param> /// <param name="bothSelector"> /// Function that projects the result given an element from /// <paramref name="first"/> and an element from <paramref name="second"/> /// that match on a common key.</param> /// <returns>A sequence containing results projected from a right /// outer join of the two input sequences.</returns> public static IEnumerable<TResult> RightJoin<TFirst, TSecond, TKey, TResult>( this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TKey> firstKeySelector, Func<TSecond, TKey> secondKeySelector, Func<TSecond, TResult> secondSelector, Func<TFirst, TSecond, TResult> bothSelector) => first.RightJoin(second, firstKeySelector, secondKeySelector, secondSelector, bothSelector, null); /// <summary> /// Performs a right outer join on two heterogeneous sequences. /// Additional arguments specify key selection functions, result /// projection functions and a key comparer. /// </summary> /// <typeparam name="TFirst"> /// The type of elements in the first sequence.</typeparam> /// <typeparam name="TSecond"> /// The type of elements in the second sequence.</typeparam> /// <typeparam name="TKey"> /// The type of the key returned by the key selector functions.</typeparam> /// <typeparam name="TResult"> /// The type of the result elements.</typeparam> /// <param name="first"> /// The first sequence of the join operation.</param> /// <param name="second"> /// The second sequence of the join operation.</param> /// <param name="firstKeySelector"> /// Function that projects the key given an element from <paramref name="first"/>.</param> /// <param name="secondKeySelector"> /// Function that projects the key given an element from <paramref name="second"/>.</param> /// <param name="secondSelector"> /// Function that projects the result given just an element from /// <paramref name="second"/> where there is no corresponding element /// in <paramref name="first"/>.</param> /// <param name="bothSelector"> /// Function that projects the result given an element from /// <paramref name="first"/> and an element from <paramref name="second"/> /// that match on a common key.</param> /// <param name="comparer"> /// The <see cref="IEqualityComparer{T}"/> instance used to compare /// keys for equality.</param> /// <returns>A sequence containing results projected from a right /// outer join of the two input sequences.</returns> public static IEnumerable<TResult> RightJoin<TFirst, TSecond, TKey, TResult>( this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TKey> firstKeySelector, Func<TSecond, TKey> secondKeySelector, Func<TSecond, TResult> secondSelector, Func<TFirst, TSecond, TResult> bothSelector, IEqualityComparer<TKey> comparer) { if (first == null) throw new ArgumentNullException(nameof(first)); if (second == null) throw new ArgumentNullException(nameof(second)); if (firstKeySelector == null) throw new ArgumentNullException(nameof(firstKeySelector)); if (secondKeySelector == null) throw new ArgumentNullException(nameof(secondKeySelector)); if (secondSelector == null) throw new ArgumentNullException(nameof(secondSelector)); if (bothSelector == null) throw new ArgumentNullException(nameof(bothSelector)); return second.LeftJoin(first, secondKeySelector, firstKeySelector, secondSelector, (x, y) => bothSelector(y, x), comparer); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Data.Common; using System.Runtime.InteropServices; namespace System.Data.Odbc { internal struct SQLLEN { private IntPtr _value; internal SQLLEN(int value) { _value = new IntPtr(value); } internal SQLLEN(long value) { #if WIN32 _value = new IntPtr(checked((int)value)); #else _value = new IntPtr(value); #endif } internal SQLLEN(IntPtr value) { _value = value; } public static implicit operator SQLLEN(int value) { // return new SQLLEN(value); } public static explicit operator SQLLEN(long value) { return new SQLLEN(value); } public static unsafe implicit operator int (SQLLEN value) { // #if WIN32 return (int)value._value.ToInt32(); #else long l = (long)value._value.ToInt64(); return checked((int)l); #endif } public static unsafe explicit operator long (SQLLEN value) { return value._value.ToInt64(); } public unsafe long ToInt64() { return _value.ToInt64(); } } internal sealed class OdbcStatementHandle : OdbcHandle { internal OdbcStatementHandle(OdbcConnectionHandle connectionHandle) : base(ODBC32.SQL_HANDLE.STMT, connectionHandle) { } internal ODBC32.RetCode BindColumn2(int columnNumber, ODBC32.SQL_C targetType, HandleRef buffer, IntPtr length, IntPtr srLen_or_Ind) { ODBC32.RetCode retcode = Interop.Odbc.SQLBindCol(this, checked((ushort)columnNumber), targetType, buffer, length, srLen_or_Ind); ODBC.TraceODBC(3, "SQLBindCol", retcode); return retcode; } internal ODBC32.RetCode BindColumn3(int columnNumber, ODBC32.SQL_C targetType, IntPtr srLen_or_Ind) { ODBC32.RetCode retcode = Interop.Odbc.SQLBindCol(this, checked((ushort)columnNumber), targetType, ADP.PtrZero, ADP.PtrZero, srLen_or_Ind); ODBC.TraceODBC(3, "SQLBindCol", retcode); return retcode; } internal ODBC32.RetCode BindParameter(short ordinal, short parameterDirection, ODBC32.SQL_C sqlctype, ODBC32.SQL_TYPE sqltype, IntPtr cchSize, IntPtr scale, HandleRef buffer, IntPtr bufferLength, HandleRef intbuffer) { ODBC32.RetCode retcode = Interop.Odbc.SQLBindParameter(this, checked((ushort)ordinal), // Parameter Number parameterDirection, // InputOutputType sqlctype, // ValueType checked((short)sqltype), // ParameterType cchSize, // ColumnSize scale, // DecimalDigits buffer, // ParameterValuePtr bufferLength, // BufferLength intbuffer); // StrLen_or_IndPtr ODBC.TraceODBC(3, "SQLBindParameter", retcode); return retcode; } internal ODBC32.RetCode Cancel() { // In ODBC3.0 ... a call to SQLCancel when no processing is done has no effect at all // (ODBC Programmer's Reference ...) ODBC32.RetCode retcode = Interop.Odbc.SQLCancel(this); ODBC.TraceODBC(3, "SQLCancel", retcode); return retcode; } internal ODBC32.RetCode CloseCursor() { ODBC32.RetCode retcode = Interop.Odbc.SQLCloseCursor(this); ODBC.TraceODBC(3, "SQLCloseCursor", retcode); return retcode; } internal ODBC32.RetCode ColumnAttribute(int columnNumber, short fieldIdentifier, CNativeBuffer characterAttribute, out short stringLength, out SQLLEN numericAttribute) { IntPtr result; ODBC32.RetCode retcode = Interop.Odbc.SQLColAttributeW(this, checked((short)columnNumber), fieldIdentifier, characterAttribute, characterAttribute.ShortLength, out stringLength, out result); numericAttribute = new SQLLEN(result); ODBC.TraceODBC(3, "SQLColAttributeW", retcode); return retcode; } internal ODBC32.RetCode Columns(string tableCatalog, string tableSchema, string tableName, string columnName) { ODBC32.RetCode retcode = Interop.Odbc.SQLColumnsW(this, tableCatalog, ODBC.ShortStringLength(tableCatalog), tableSchema, ODBC.ShortStringLength(tableSchema), tableName, ODBC.ShortStringLength(tableName), columnName, ODBC.ShortStringLength(columnName)); ODBC.TraceODBC(3, "SQLColumnsW", retcode); return retcode; } internal ODBC32.RetCode Execute() { ODBC32.RetCode retcode = Interop.Odbc.SQLExecute(this); ODBC.TraceODBC(3, "SQLExecute", retcode); return retcode; } internal ODBC32.RetCode ExecuteDirect(string commandText) { ODBC32.RetCode retcode = Interop.Odbc.SQLExecDirectW(this, commandText, ODBC32.SQL_NTS); ODBC.TraceODBC(3, "SQLExecDirectW", retcode); return retcode; } internal ODBC32.RetCode Fetch() { ODBC32.RetCode retcode = Interop.Odbc.SQLFetch(this); ODBC.TraceODBC(3, "SQLFetch", retcode); return retcode; } internal ODBC32.RetCode FreeStatement(ODBC32.STMT stmt) { ODBC32.RetCode retcode = Interop.Odbc.SQLFreeStmt(this, stmt); ODBC.TraceODBC(3, "SQLFreeStmt", retcode); return retcode; } internal ODBC32.RetCode GetData(int index, ODBC32.SQL_C sqlctype, CNativeBuffer buffer, int cb, out IntPtr cbActual) { ODBC32.RetCode retcode = Interop.Odbc.SQLGetData(this, checked((ushort)index), sqlctype, buffer, new IntPtr(cb), out cbActual); ODBC.TraceODBC(3, "SQLGetData", retcode); return retcode; } internal ODBC32.RetCode GetStatementAttribute(ODBC32.SQL_ATTR attribute, out IntPtr value, out int stringLength) { ODBC32.RetCode retcode = Interop.Odbc.SQLGetStmtAttrW(this, attribute, out value, ADP.PtrSize, out stringLength); ODBC.TraceODBC(3, "SQLGetStmtAttrW", retcode); return retcode; } internal ODBC32.RetCode GetTypeInfo(Int16 fSqlType) { ODBC32.RetCode retcode = Interop.Odbc.SQLGetTypeInfo(this, fSqlType); ODBC.TraceODBC(3, "SQLGetTypeInfo", retcode); return retcode; } internal ODBC32.RetCode MoreResults() { ODBC32.RetCode retcode = Interop.Odbc.SQLMoreResults(this); ODBC.TraceODBC(3, "SQLMoreResults", retcode); return retcode; } internal ODBC32.RetCode NumberOfResultColumns(out short columnsAffected) { ODBC32.RetCode retcode = Interop.Odbc.SQLNumResultCols(this, out columnsAffected); ODBC.TraceODBC(3, "SQLNumResultCols", retcode); return retcode; } internal ODBC32.RetCode Prepare(string commandText) { ODBC32.RetCode retcode = Interop.Odbc.SQLPrepareW(this, commandText, ODBC32.SQL_NTS); ODBC.TraceODBC(3, "SQLPrepareW", retcode); return retcode; } internal ODBC32.RetCode PrimaryKeys(string catalogName, string schemaName, string tableName) { ODBC32.RetCode retcode = Interop.Odbc.SQLPrimaryKeysW(this, catalogName, ODBC.ShortStringLength(catalogName), // CatalogName schemaName, ODBC.ShortStringLength(schemaName), // SchemaName tableName, ODBC.ShortStringLength(tableName) // TableName ); ODBC.TraceODBC(3, "SQLPrimaryKeysW", retcode); return retcode; } internal ODBC32.RetCode Procedures(string procedureCatalog, string procedureSchema, string procedureName) { ODBC32.RetCode retcode = Interop.Odbc.SQLProceduresW(this, procedureCatalog, ODBC.ShortStringLength(procedureCatalog), procedureSchema, ODBC.ShortStringLength(procedureSchema), procedureName, ODBC.ShortStringLength(procedureName)); ODBC.TraceODBC(3, "SQLProceduresW", retcode); return retcode; } internal ODBC32.RetCode ProcedureColumns(string procedureCatalog, string procedureSchema, string procedureName, string columnName) { ODBC32.RetCode retcode = Interop.Odbc.SQLProcedureColumnsW(this, procedureCatalog, ODBC.ShortStringLength(procedureCatalog), procedureSchema, ODBC.ShortStringLength(procedureSchema), procedureName, ODBC.ShortStringLength(procedureName), columnName, ODBC.ShortStringLength(columnName)); ODBC.TraceODBC(3, "SQLProcedureColumnsW", retcode); return retcode; } internal ODBC32.RetCode RowCount(out SQLLEN rowCount) { IntPtr result; ODBC32.RetCode retcode = Interop.Odbc.SQLRowCount(this, out result); rowCount = new SQLLEN(result); ODBC.TraceODBC(3, "SQLRowCount", retcode); return retcode; } internal ODBC32.RetCode SetStatementAttribute(ODBC32.SQL_ATTR attribute, IntPtr value, ODBC32.SQL_IS stringLength) { ODBC32.RetCode retcode = Interop.Odbc.SQLSetStmtAttrW(this, (int)attribute, value, (int)stringLength); ODBC.TraceODBC(3, "SQLSetStmtAttrW", retcode); return retcode; } internal ODBC32.RetCode SpecialColumns(string quotedTable) { ODBC32.RetCode retcode = Interop.Odbc.SQLSpecialColumnsW(this, ODBC32.SQL_SPECIALCOLS.ROWVER, null, 0, null, 0, quotedTable, ODBC.ShortStringLength(quotedTable), ODBC32.SQL_SCOPE.SESSION, ODBC32.SQL_NULLABILITY.NO_NULLS); ODBC.TraceODBC(3, "SQLSpecialColumnsW", retcode); return retcode; } internal ODBC32.RetCode Statistics(string tableCatalog, string tableSchema, string tableName, Int16 unique, Int16 accuracy) { ODBC32.RetCode retcode = Interop.Odbc.SQLStatisticsW(this, tableCatalog, ODBC.ShortStringLength(tableCatalog), tableSchema, ODBC.ShortStringLength(tableSchema), tableName, ODBC.ShortStringLength(tableName), unique, accuracy); ODBC.TraceODBC(3, "SQLStatisticsW", retcode); return retcode; } internal ODBC32.RetCode Statistics(string tableName) { ODBC32.RetCode retcode = Interop.Odbc.SQLStatisticsW(this, null, 0, null, 0, tableName, ODBC.ShortStringLength(tableName), (Int16)ODBC32.SQL_INDEX.UNIQUE, (Int16)ODBC32.SQL_STATISTICS_RESERVED.ENSURE); ODBC.TraceODBC(3, "SQLStatisticsW", retcode); return retcode; } internal ODBC32.RetCode Tables(string tableCatalog, string tableSchema, string tableName, string tableType) { ODBC32.RetCode retcode = Interop.Odbc.SQLTablesW(this, tableCatalog, ODBC.ShortStringLength(tableCatalog), tableSchema, ODBC.ShortStringLength(tableSchema), tableName, ODBC.ShortStringLength(tableName), tableType, ODBC.ShortStringLength(tableType)); ODBC.TraceODBC(3, "SQLTablesW", retcode); return retcode; } } }
// ZipEntryFactory.cs // // Copyright 2006 John Reilly // // Copyright (C) 2001 Free Software Foundation, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; using System.IO; using ICSharpCode.SharpZipLib.Core; namespace ICSharpCode.SharpZipLib.Zip { /// <summary> /// Basic implementation of <see cref="IEntryFactory"></see> /// </summary> public class ZipEntryFactory : IEntryFactory { #region Enumerations /// <summary> /// Defines the possible values to be used for the <see cref="ZipEntry.DateTime"/>. /// </summary> public enum TimeSetting { /// <summary> /// Use the recorded LastWriteTime value for the file. /// </summary> LastWriteTime, /// <summary> /// Use the recorded LastWriteTimeUtc value for the file /// </summary> LastWriteTimeUtc, /// <summary> /// Use the recorded CreateTime value for the file. /// </summary> CreateTime, /// <summary> /// Use the recorded CreateTimeUtc value for the file. /// </summary> CreateTimeUtc, /// <summary> /// Use the recorded LastAccessTime value for the file. /// </summary> LastAccessTime, /// <summary> /// Use the recorded LastAccessTimeUtc value for the file. /// </summary> LastAccessTimeUtc, /// <summary> /// Use a fixed value. /// </summary> /// <remarks>The actual <see cref="DateTime"/> value used can be /// specified via the <see cref="ZipEntryFactory(DateTime)"/> constructor or /// using the <see cref="ZipEntryFactory(TimeSetting)"/> with the setting set /// to <see cref="TimeSetting.Fixed"/> which will use the <see cref="DateTime"/> when this class was constructed. /// The <see cref="FixedDateTime"/> property can also be used to set this value.</remarks> Fixed, } #endregion #region Constructors /// <summary> /// Initialise a new instance of the <see cref="ZipEntryFactory"/> class. /// </summary> /// <remarks>A default <see cref="INameTransform"/>, and the LastWriteTime for files is used.</remarks> public ZipEntryFactory() { nameTransform_ = new ZipNameTransform(); } /// <summary> /// Initialise a new instance of <see cref="ZipEntryFactory"/> using the specified <see cref="TimeSetting"/> /// </summary> /// <param name="timeSetting">The <see cref="TimeSetting">time setting</see> to use when creating <see cref="ZipEntry">Zip entries</see>.</param> public ZipEntryFactory(TimeSetting timeSetting) { timeSetting_ = timeSetting; nameTransform_ = new ZipNameTransform(); } /// <summary> /// Initialise a new instance of <see cref="ZipEntryFactory"/> using the specified <see cref="DateTime"/> /// </summary> /// <param name="time">The time to set all <see cref="ZipEntry.DateTime"/> values to.</param> public ZipEntryFactory(DateTime time) { timeSetting_ = TimeSetting.Fixed; FixedDateTime = time; nameTransform_ = new ZipNameTransform(); } #endregion #region Properties /// <summary> /// Get / set the <see cref="INameTransform"/> to be used when creating new <see cref="ZipEntry"/> values. /// </summary> /// <remarks> /// Setting this property to null will cause a default <see cref="ZipNameTransform">name transform</see> to be used. /// </remarks> public INameTransform NameTransform { get { return nameTransform_; } set { if (value == null) { nameTransform_ = new ZipNameTransform(); } else { nameTransform_ = value; } } } /// <summary> /// Get / set the <see cref="TimeSetting"/> in use. /// </summary> public TimeSetting Setting { get { return timeSetting_; } set { timeSetting_ = value; } } /// <summary> /// Get / set the <see cref="DateTime"/> value to use when <see cref="Setting"/> is set to <see cref="TimeSetting.Fixed"/> /// </summary> public DateTime FixedDateTime { get { return fixedDateTime_; } set { if (value.Year < 1970) { throw new ArgumentException("Value is too old to be valid", "value"); } fixedDateTime_ = value; } } /// <summary> /// A bitmask defining the attributes to be retrieved from the actual file. /// </summary> /// <remarks>The default is to get all possible attributes from the actual file.</remarks> public int GetAttributes { get { return getAttributes_; } set { getAttributes_ = value; } } /// <summary> /// A bitmask defining which attributes are to be set on. /// </summary> /// <remarks>By default no attributes are set on.</remarks> public int SetAttributes { get { return setAttributes_; } set { setAttributes_ = value; } } /// <summary> /// Get set a value indicating wether unidoce text should be set on. /// </summary> public bool IsUnicodeText { get { return isUnicodeText_; } set { isUnicodeText_ = value; } } #endregion #region IEntryFactory Members /// <summary> /// Make a new <see cref="ZipEntry"/> for a file. /// </summary> /// <param name="fileName">The name of the file to create a new entry for.</param> /// <returns>Returns a new <see cref="ZipEntry"/> based on the <paramref name="fileName"/>.</returns> public ZipEntry MakeFileEntry(string fileName) { return MakeFileEntry(fileName, true); } /// <summary> /// Make a new <see cref="ZipEntry"/> from a name. /// </summary> /// <param name="fileName">The name of the file to create a new entry for.</param> /// <param name="useFileSystem">If true entry detail is retrieved from the file system if the file exists.</param> /// <returns>Returns a new <see cref="ZipEntry"/> based on the <paramref name="fileName"/>.</returns> public ZipEntry MakeFileEntry(string fileName, bool useFileSystem) { ZipEntry result = new ZipEntry(nameTransform_.TransformFile(fileName)); result.IsUnicodeText = isUnicodeText_; int externalAttributes = 0; bool useAttributes = (setAttributes_ != 0); FileInfo fi = null; if (useFileSystem) { fi = new FileInfo(fileName); } if ((fi != null) && fi.Exists) { switch (timeSetting_) { case TimeSetting.CreateTime: result.DateTime = fi.CreationTime; break; case TimeSetting.CreateTimeUtc: #if NETCF_1_0 || NETCF_2_0 || XBOX result.DateTime = fi.CreationTime.ToUniversalTime(); #else result.DateTime = fi.CreationTimeUtc; #endif break; case TimeSetting.LastAccessTime: result.DateTime = fi.LastAccessTime; break; case TimeSetting.LastAccessTimeUtc: #if NETCF_1_0 || NETCF_2_0 || XBOX result.DateTime = fi.LastAccessTime.ToUniversalTime(); #else result.DateTime = fi.LastAccessTimeUtc; #endif break; case TimeSetting.LastWriteTime: result.DateTime = fi.LastWriteTime; break; case TimeSetting.LastWriteTimeUtc: #if NETCF_1_0 || NETCF_2_0 || XBOX result.DateTime = fi.LastWriteTime.ToUniversalTime(); #else result.DateTime = fi.LastWriteTimeUtc; #endif break; case TimeSetting.Fixed: result.DateTime = fixedDateTime_; break; default: throw new ZipException("Unhandled time setting in MakeFileEntry"); } result.Size = fi.Length; useAttributes = true; externalAttributes = ((int)fi.Attributes & getAttributes_); } else { if (timeSetting_ == TimeSetting.Fixed) { result.DateTime = fixedDateTime_; } } if (useAttributes) { externalAttributes |= setAttributes_; result.ExternalFileAttributes = externalAttributes; } return result; } /// <summary> /// Make a new <see cref="ZipEntry"></see> for a directory. /// </summary> /// <param name="directoryName">The raw untransformed name for the new directory</param> /// <returns>Returns a new <see cref="ZipEntry"></see> representing a directory.</returns> public ZipEntry MakeDirectoryEntry(string directoryName) { return MakeDirectoryEntry(directoryName, true); } /// <summary> /// Make a new <see cref="ZipEntry"></see> for a directory. /// </summary> /// <param name="directoryName">The raw untransformed name for the new directory</param> /// <param name="useFileSystem">If true entry detail is retrieved from the file system if the file exists.</param> /// <returns>Returns a new <see cref="ZipEntry"></see> representing a directory.</returns> public ZipEntry MakeDirectoryEntry(string directoryName, bool useFileSystem) { ZipEntry result = new ZipEntry(nameTransform_.TransformDirectory(directoryName)); result.IsUnicodeText = isUnicodeText_; result.Size = 0; int externalAttributes = 0; DirectoryInfo di = null; if (useFileSystem) { di = new DirectoryInfo(directoryName); } if ((di != null) && di.Exists) { switch (timeSetting_) { case TimeSetting.CreateTime: result.DateTime = di.CreationTime; break; case TimeSetting.CreateTimeUtc: #if NETCF_1_0 || NETCF_2_0 || XBOX result.DateTime = di.CreationTime.ToUniversalTime(); #else result.DateTime = di.CreationTimeUtc; #endif break; case TimeSetting.LastAccessTime: result.DateTime = di.LastAccessTime; break; case TimeSetting.LastAccessTimeUtc: #if NETCF_1_0 || NETCF_2_0 || XBOX result.DateTime = di.LastAccessTime.ToUniversalTime(); #else result.DateTime = di.LastAccessTimeUtc; #endif break; case TimeSetting.LastWriteTime: result.DateTime = di.LastWriteTime; break; case TimeSetting.LastWriteTimeUtc: #if NETCF_1_0 || NETCF_2_0 || XBOX result.DateTime = di.LastWriteTime.ToUniversalTime(); #else result.DateTime = di.LastWriteTimeUtc; #endif break; case TimeSetting.Fixed: result.DateTime = fixedDateTime_; break; default: throw new ZipException("Unhandled time setting in MakeDirectoryEntry"); } externalAttributes = ((int)di.Attributes & getAttributes_); } else { if (timeSetting_ == TimeSetting.Fixed) { result.DateTime = fixedDateTime_; } } // Always set directory attribute on. externalAttributes |= (setAttributes_ | 16); result.ExternalFileAttributes = externalAttributes; return result; } #endregion #region Instance Fields INameTransform nameTransform_; DateTime fixedDateTime_ = DateTime.Now; TimeSetting timeSetting_; bool isUnicodeText_; int getAttributes_ = -1; int setAttributes_; #endregion } }
#if !UNITY_WINRT || UNITY_EDITOR || (UNITY_WP8 && !UNITY_WP_8_1) #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using PlayFab.Json.Utilities; using System.Diagnostics; using System.Globalization; namespace PlayFab.Json.Linq { /// <summary> /// Represents a JSON property. /// </summary> public class JProperty : JContainer { private readonly List<JToken> _content = new List<JToken>(); private readonly string _name; /// <summary> /// Gets the container's children tokens. /// </summary> /// <value>The container's children tokens.</value> protected override IList<JToken> ChildrenTokens { get { return _content; } } /// <summary> /// Gets the property name. /// </summary> /// <value>The property name.</value> public string Name { [DebuggerStepThrough] get { return _name; } } #pragma warning disable 108 /// <summary> /// Gets or sets the property value. /// </summary> /// <value>The property value.</value> public JToken Value { [DebuggerStepThrough] get { return (ChildrenTokens.Count > 0) ? ChildrenTokens[0] : null; } set { CheckReentrancy(); JToken newValue = value ?? new JValue((object) null); if (ChildrenTokens.Count == 0) { InsertItem(0, newValue); } else { SetItem(0, newValue); } } } #pragma warning restore 108 /// <summary> /// Initializes a new instance of the <see cref="JProperty"/> class from another <see cref="JProperty"/> object. /// </summary> /// <param name="other">A <see cref="JProperty"/> object to copy from.</param> public JProperty(JProperty other) : base(other) { _name = other.Name; } internal override JToken GetItem(int index) { if (index != 0) throw new ArgumentOutOfRangeException(); return Value; } internal override void SetItem(int index, JToken item) { if (index != 0) throw new ArgumentOutOfRangeException(); if (IsTokenUnchanged(Value, item)) return; if (Parent != null) ((JObject)Parent).InternalPropertyChanging(this); base.SetItem(0, item); if (Parent != null) ((JObject)Parent).InternalPropertyChanged(this); } internal override bool RemoveItem(JToken item) { throw new Exception("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); } internal override void RemoveItemAt(int index) { throw new Exception("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); } internal override void InsertItem(int index, JToken item) { if (Value != null) throw new Exception("{0} cannot have multiple values.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); base.InsertItem(0, item); } internal override bool ContainsItem(JToken item) { return (Value == item); } internal override void ClearItems() { throw new Exception("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); } internal override bool DeepEquals(JToken node) { JProperty t = node as JProperty; return (t != null && _name == t.Name && ContentsEqual(t)); } internal override JToken CloneToken() { return new JProperty(this); } /// <summary> /// Gets the node type for this <see cref="JToken"/>. /// </summary> /// <value>The type.</value> public override JTokenType Type { [DebuggerStepThrough] get { return JTokenType.Property; } } internal JProperty(string name) { // called from JTokenWriter ValidationUtils.ArgumentNotNull(name, "name"); _name = name; } /// <summary> /// Initializes a new instance of the <see cref="JProperty"/> class. /// </summary> /// <param name="name">The property name.</param> /// <param name="content">The property content.</param> public JProperty(string name, params object[] content) : this(name, (object)content) { } /// <summary> /// Initializes a new instance of the <see cref="JProperty"/> class. /// </summary> /// <param name="name">The property name.</param> /// <param name="content">The property content.</param> public JProperty(string name, object content) { ValidationUtils.ArgumentNotNull(name, "name"); _name = name; Value = IsMultiContent(content) ? new JArray(content) : CreateFromContent(content); } /// <summary> /// Writes this token to a <see cref="JsonWriter"/>. /// </summary> /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param> public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) { writer.WritePropertyName(_name); Value.WriteTo(writer, converters); } internal override int GetDeepHashCode() { return _name.GetHashCode() ^ ((Value != null) ? Value.GetDeepHashCode() : 0); } /// <summary> /// Loads an <see cref="JProperty"/> from a <see cref="JsonReader"/>. /// </summary> /// <param name="reader">A <see cref="JsonReader"/> that will be read for the content of the <see cref="JProperty"/>.</param> /// <returns>A <see cref="JProperty"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns> public static new JProperty Load(JsonReader reader) { if (reader.TokenType == JsonToken.None) { if (!reader.Read()) throw new Exception("Error reading JProperty from JsonReader."); } if (reader.TokenType != JsonToken.PropertyName) throw new Exception( "Error reading JProperty from JsonReader. Current JsonReader item is not a property: {0}".FormatWith( CultureInfo.InvariantCulture, reader.TokenType)); JProperty p = new JProperty((string)reader.Value); p.SetLineInfo(reader as IJsonLineInfo); p.ReadTokenFrom(reader); return p; } } } #endif
/* * Deed API * * Land Registry Deed API * * OpenAPI spec version: 2.3.1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace IO.Swagger.Model { /// <summary> /// Unique deed, consisting of property, borrower and charge information as well as clauses for the deed. /// </summary> [DataContract] public partial class OperativeDeedDeed : IEquatable<OperativeDeedDeed>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="OperativeDeedDeed" /> class. /// </summary> /// <param name="TitleNumber">Unique Land Registry identifier for the registered estate..</param> /// <param name="MdRef">Land Registry assigned number for a Mortgage Deed (MD). If you wish to use an existing MD reference please prefix it with e- to comply with our system (eg e-MD12345).</param> /// <param name="Borrowers">Borrowers.</param> /// <param name="ChargeClause">ChargeClause.</param> /// <param name="AdditionalProvisions">AdditionalProvisions.</param> /// <param name="Lender">Lender.</param> /// <param name="EffectiveClause">Text to display the make effective clause.</param> /// <param name="PropertyAddress">The address of property that the deed relates. This should be supplied in a comma separated format e.g. 30 wakefield rd, plymouth, PL6 3WA.</param> /// <param name="Reference">A conveyancer reference. Can be displayed on the deed if the mortgage document template permits..</param> /// <param name="DateOfMortgageOffer">Date that the mortgage offer was made. Can be displayed on the deed if the mortgage document template permits..</param> /// <param name="DeedStatus">Current state of the deed.</param> /// <param name="EffectiveDate">An effective date is shown if the deed is made effective.</param> public OperativeDeedDeed(string TitleNumber = default(string), string MdRef = default(string), OpBorrowers Borrowers = default(OpBorrowers), ChargeClause ChargeClause = default(ChargeClause), AdditionalProvisions AdditionalProvisions = default(AdditionalProvisions), Lender Lender = default(Lender), string EffectiveClause = default(string), string PropertyAddress = default(string), string Reference = default(string), string DateOfMortgageOffer = default(string), string DeedStatus = default(string), string EffectiveDate = default(string)) { this.TitleNumber = TitleNumber; this.MdRef = MdRef; this.Borrowers = Borrowers; this.ChargeClause = ChargeClause; this.AdditionalProvisions = AdditionalProvisions; this.Lender = Lender; this.EffectiveClause = EffectiveClause; this.PropertyAddress = PropertyAddress; this.Reference = Reference; this.DateOfMortgageOffer = DateOfMortgageOffer; this.DeedStatus = DeedStatus; this.EffectiveDate = EffectiveDate; } /// <summary> /// Unique Land Registry identifier for the registered estate. /// </summary> /// <value>Unique Land Registry identifier for the registered estate.</value> [DataMember(Name="title_number", EmitDefaultValue=false)] public string TitleNumber { get; set; } /// <summary> /// Land Registry assigned number for a Mortgage Deed (MD). If you wish to use an existing MD reference please prefix it with e- to comply with our system (eg e-MD12345) /// </summary> /// <value>Land Registry assigned number for a Mortgage Deed (MD). If you wish to use an existing MD reference please prefix it with e- to comply with our system (eg e-MD12345)</value> [DataMember(Name="md_ref", EmitDefaultValue=false)] public string MdRef { get; set; } /// <summary> /// Gets or Sets Borrowers /// </summary> [DataMember(Name="borrowers", EmitDefaultValue=false)] public OpBorrowers Borrowers { get; set; } /// <summary> /// Gets or Sets ChargeClause /// </summary> [DataMember(Name="charge_clause", EmitDefaultValue=false)] public ChargeClause ChargeClause { get; set; } /// <summary> /// Gets or Sets AdditionalProvisions /// </summary> [DataMember(Name="additional_provisions", EmitDefaultValue=false)] public AdditionalProvisions AdditionalProvisions { get; set; } /// <summary> /// Gets or Sets Lender /// </summary> [DataMember(Name="lender", EmitDefaultValue=false)] public Lender Lender { get; set; } /// <summary> /// Text to display the make effective clause /// </summary> /// <value>Text to display the make effective clause</value> [DataMember(Name="effective_clause", EmitDefaultValue=false)] public string EffectiveClause { get; set; } /// <summary> /// The address of property that the deed relates. This should be supplied in a comma separated format e.g. 30 wakefield rd, plymouth, PL6 3WA /// </summary> /// <value>The address of property that the deed relates. This should be supplied in a comma separated format e.g. 30 wakefield rd, plymouth, PL6 3WA</value> [DataMember(Name="property_address", EmitDefaultValue=false)] public string PropertyAddress { get; set; } /// <summary> /// A conveyancer reference. Can be displayed on the deed if the mortgage document template permits. /// </summary> /// <value>A conveyancer reference. Can be displayed on the deed if the mortgage document template permits.</value> [DataMember(Name="reference", EmitDefaultValue=false)] public string Reference { get; set; } /// <summary> /// Date that the mortgage offer was made. Can be displayed on the deed if the mortgage document template permits. /// </summary> /// <value>Date that the mortgage offer was made. Can be displayed on the deed if the mortgage document template permits.</value> [DataMember(Name="date_of_mortgage_offer", EmitDefaultValue=false)] public string DateOfMortgageOffer { get; set; } /// <summary> /// Values unsuited to other keys. Can be displayed on the deed if the mortgage document template permits. /// </summary> /// <value>Values unsuited to other keys. Can be displayed on the deed if the mortgage document template permits.</value> [DataMember(Name="deed_status", EmitDefaultValue=false)] public string DeedStatus { get; set; } /// <summary> /// An effective date is shown if the deed is made effective /// </summary> /// <value>An effective date is shown if the deed is made effective</value> [DataMember(Name="effective_date", EmitDefaultValue=false)] public string EffectiveDate { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class OperativeDeedDeed {\n"); sb.Append(" TitleNumber: ").Append(TitleNumber).Append("\n"); sb.Append(" MdRef: ").Append(MdRef).Append("\n"); sb.Append(" Borrowers: ").Append(Borrowers).Append("\n"); sb.Append(" ChargeClause: ").Append(ChargeClause).Append("\n"); sb.Append(" AdditionalProvisions: ").Append(AdditionalProvisions).Append("\n"); sb.Append(" Lender: ").Append(Lender).Append("\n"); sb.Append(" EffectiveClause: ").Append(EffectiveClause).Append("\n"); sb.Append(" PropertyAddress: ").Append(PropertyAddress).Append("\n"); sb.Append(" Reference: ").Append(Reference).Append("\n"); sb.Append(" DateOfMortgageOffer: ").Append(DateOfMortgageOffer).Append("\n"); sb.Append(" DeedStatus: ").Append(DeedStatus).Append("\n"); sb.Append(" EffectiveDate: ").Append(EffectiveDate).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as OperativeDeedDeed); } /// <summary> /// Returns true if OperativeDeedDeed instances are equal /// </summary> /// <param name="other">Instance of OperativeDeedDeed to be compared</param> /// <returns>Boolean</returns> public bool Equals(OperativeDeedDeed other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.TitleNumber == other.TitleNumber || this.TitleNumber != null && this.TitleNumber.Equals(other.TitleNumber) ) && ( this.MdRef == other.MdRef || this.MdRef != null && this.MdRef.Equals(other.MdRef) ) && ( this.Borrowers == other.Borrowers || this.Borrowers != null && this.Borrowers.Equals(other.Borrowers) ) && ( this.ChargeClause == other.ChargeClause || this.ChargeClause != null && this.ChargeClause.Equals(other.ChargeClause) ) && ( this.AdditionalProvisions == other.AdditionalProvisions || this.AdditionalProvisions != null && this.AdditionalProvisions.Equals(other.AdditionalProvisions) ) && ( this.Lender == other.Lender || this.Lender != null && this.Lender.Equals(other.Lender) ) && ( this.EffectiveClause == other.EffectiveClause || this.EffectiveClause != null && this.EffectiveClause.Equals(other.EffectiveClause) ) && ( this.PropertyAddress == other.PropertyAddress || this.PropertyAddress != null && this.PropertyAddress.Equals(other.PropertyAddress) ) && ( this.Reference == other.Reference || this.Reference != null && this.Reference.Equals(other.Reference) ) && ( this.DateOfMortgageOffer == other.DateOfMortgageOffer || this.DateOfMortgageOffer != null && this.DateOfMortgageOffer.Equals(other.DateOfMortgageOffer) ) && ( this.DeedStatus == other.DeedStatus || this.DeedStatus != null && this.DeedStatus.Equals(other.DeedStatus) ) && ( this.EffectiveDate == other.EffectiveDate || this.EffectiveDate != null && this.EffectiveDate.Equals(other.EffectiveDate) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.TitleNumber != null) hash = hash * 59 + this.TitleNumber.GetHashCode(); if (this.MdRef != null) hash = hash * 59 + this.MdRef.GetHashCode(); if (this.Borrowers != null) hash = hash * 59 + this.Borrowers.GetHashCode(); if (this.ChargeClause != null) hash = hash * 59 + this.ChargeClause.GetHashCode(); if (this.AdditionalProvisions != null) hash = hash * 59 + this.AdditionalProvisions.GetHashCode(); if (this.Lender != null) hash = hash * 59 + this.Lender.GetHashCode(); if (this.EffectiveClause != null) hash = hash * 59 + this.EffectiveClause.GetHashCode(); if (this.PropertyAddress != null) hash = hash * 59 + this.PropertyAddress.GetHashCode(); if (this.Reference != null) hash = hash * 59 + this.Reference.GetHashCode(); if (this.DateOfMortgageOffer != null) hash = hash * 59 + this.DateOfMortgageOffer.GetHashCode(); if (this.DeedStatus != null) hash = hash * 59 + this.DeedStatus.GetHashCode(); if (this.EffectiveDate != null) hash = hash * 59 + this.EffectiveDate.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { // Reference (string) maxLength if(this.Reference != null && this.Reference.Length > 50) { yield return new ValidationResult("Invalid value for Reference, length must be less than 50.", new [] { "Reference" }); } // Reference (string) pattern Regex regexReference = new Regex(@"^(?!\\s*$).+", RegexOptions.CultureInvariant); if (false == regexReference.Match(this.Reference).Success) { yield return new ValidationResult("Invalid value for Reference, must match a pattern of /^(?!\\s*$).+/.", new [] { "Reference" }); } // DateOfMortgageOffer (string) maxLength if(this.DateOfMortgageOffer != null && this.DateOfMortgageOffer.Length > 50) { yield return new ValidationResult("Invalid value for DateOfMortgageOffer, length must be less than 50.", new [] { "DateOfMortgageOffer" }); } // DateOfMortgageOffer (string) pattern Regex regexDateOfMortgageOffer = new Regex(@"^(?!\\s*$).+", RegexOptions.CultureInvariant); if (false == regexDateOfMortgageOffer.Match(this.DateOfMortgageOffer).Success) { yield return new ValidationResult("Invalid value for DateOfMortgageOffer, must match a pattern of /^(?!\\s*$).+/.", new[] { "DateOfMortgageOffer" }); } yield break; } } }
// This file was generated by the Gtk# code generator. // Any changes made will be lost if regenerated. namespace GLib { using System; using System.Runtime.InteropServices; #region Autogenerated code public class MountAdapter : GLib.GInterfaceAdapter, GLib.Mount { public MountAdapter (IntPtr handle) { this.handle = handle; } [DllImport("libgio-2.0-0.dll")] static extern IntPtr g_mount_get_type(); private static GLib.GType _gtype = new GLib.GType (g_mount_get_type ()); public override GLib.GType GType { get { return _gtype; } } IntPtr handle; public override IntPtr Handle { get { return handle; } } public static Mount GetObject (IntPtr handle, bool owned) { GLib.Object obj = GLib.Object.GetObject (handle, owned); return GetObject (obj); } public static Mount GetObject (GLib.Object obj) { if (obj == null) return null; else if (obj as Mount == null) return new MountAdapter (obj.Handle); else return obj as Mount; } [GLib.Signal("pre-unmount")] public event System.EventHandler PreUnmount { add { GLib.Signal sig = GLib.Signal.Lookup (GLib.Object.GetObject (Handle), "pre-unmount"); sig.AddDelegate (value); } remove { GLib.Signal sig = GLib.Signal.Lookup (GLib.Object.GetObject (Handle), "pre-unmount"); sig.RemoveDelegate (value); } } [GLib.Signal("changed")] public event System.EventHandler Changed { add { GLib.Signal sig = GLib.Signal.Lookup (GLib.Object.GetObject (Handle), "changed"); sig.AddDelegate (value); } remove { GLib.Signal sig = GLib.Signal.Lookup (GLib.Object.GetObject (Handle), "changed"); sig.RemoveDelegate (value); } } [GLib.Signal("unmounted")] public event System.EventHandler Unmounted { add { GLib.Signal sig = GLib.Signal.Lookup (GLib.Object.GetObject (Handle), "unmounted"); sig.AddDelegate (value); } remove { GLib.Signal sig = GLib.Signal.Lookup (GLib.Object.GetObject (Handle), "unmounted"); sig.RemoveDelegate (value); } } [DllImport("libgio-2.0-0.dll")] static extern IntPtr g_mount_guess_content_type_sync(IntPtr raw, bool force_rescan, IntPtr cancellable, out IntPtr error); public string[] GuessContentTypeSync(bool force_rescan, GLib.Cancellable cancellable) { IntPtr error = IntPtr.Zero; IntPtr raw_ret = g_mount_guess_content_type_sync(Handle, force_rescan, cancellable == null ? IntPtr.Zero : cancellable.Handle, out error); string[] ret = GLib.Marshaller.NullTermPtrToStringArray (raw_ret, false); if (error != IntPtr.Zero) throw new GLib.GException (error); return ret; } [DllImport("libgio-2.0-0.dll")] static extern bool g_mount_unmount_finish(IntPtr raw, IntPtr result, out IntPtr error); [Obsolete] public bool UnmountFinish(GLib.AsyncResult result) { IntPtr error = IntPtr.Zero; bool raw_ret = g_mount_unmount_finish(Handle, result == null ? IntPtr.Zero : result.Handle, out error); bool ret = raw_ret; if (error != IntPtr.Zero) throw new GLib.GException (error); return ret; } [DllImport("libgio-2.0-0.dll")] static extern IntPtr g_mount_get_volume(IntPtr raw); public GLib.Volume Volume { get { IntPtr raw_ret = g_mount_get_volume(Handle); GLib.Volume ret = GLib.VolumeAdapter.GetObject (raw_ret, false); return ret; } } [DllImport("libgio-2.0-0.dll")] static extern IntPtr g_mount_get_root(IntPtr raw); public GLib.File Root { get { IntPtr raw_ret = g_mount_get_root(Handle); GLib.File ret = GLib.FileAdapter.GetObject (raw_ret, false); return ret; } } [DllImport("libgio-2.0-0.dll")] static extern bool g_mount_can_unmount(IntPtr raw); public bool CanUnmount { get { bool raw_ret = g_mount_can_unmount(Handle); bool ret = raw_ret; return ret; } } [DllImport("libgio-2.0-0.dll")] static extern IntPtr g_mount_get_icon(IntPtr raw); public GLib.Icon Icon { get { IntPtr raw_ret = g_mount_get_icon(Handle); GLib.Icon ret = GLib.IconAdapter.GetObject (raw_ret, false); return ret; } } [DllImport("libgio-2.0-0.dll")] static extern bool g_mount_can_eject(IntPtr raw); public bool CanEject() { bool raw_ret = g_mount_can_eject(Handle); bool ret = raw_ret; return ret; } [DllImport("libgio-2.0-0.dll")] static extern void g_mount_shadow(IntPtr raw); public void Shadow() { g_mount_shadow(Handle); } [DllImport("libgio-2.0-0.dll")] static extern bool g_mount_unmount_with_operation_finish(IntPtr raw, IntPtr result, out IntPtr error); public bool UnmountWithOperationFinish(GLib.AsyncResult result) { IntPtr error = IntPtr.Zero; bool raw_ret = g_mount_unmount_with_operation_finish(Handle, result == null ? IntPtr.Zero : result.Handle, out error); bool ret = raw_ret; if (error != IntPtr.Zero) throw new GLib.GException (error); return ret; } [DllImport("libgio-2.0-0.dll")] static extern void g_mount_eject_with_operation(IntPtr raw, int flags, IntPtr mount_operation, IntPtr cancellable, GLibSharp.AsyncReadyCallbackNative cb, IntPtr user_data); public void EjectWithOperation(GLib.MountUnmountFlags flags, GLib.MountOperation mount_operation, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb) { GLibSharp.AsyncReadyCallbackWrapper cb_wrapper = new GLibSharp.AsyncReadyCallbackWrapper (cb); cb_wrapper.PersistUntilCalled (); g_mount_eject_with_operation(Handle, (int) flags, mount_operation == null ? IntPtr.Zero : mount_operation.Handle, cancellable == null ? IntPtr.Zero : cancellable.Handle, cb_wrapper.NativeDelegate, IntPtr.Zero); } [DllImport("libgio-2.0-0.dll")] static extern void g_mount_guess_content_type(IntPtr raw, bool force_rescan, IntPtr cancellable, GLibSharp.AsyncReadyCallbackNative cb, IntPtr user_data); public void GuessContentType(bool force_rescan, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb) { GLibSharp.AsyncReadyCallbackWrapper cb_wrapper = new GLibSharp.AsyncReadyCallbackWrapper (cb); cb_wrapper.PersistUntilCalled (); g_mount_guess_content_type(Handle, force_rescan, cancellable == null ? IntPtr.Zero : cancellable.Handle, cb_wrapper.NativeDelegate, IntPtr.Zero); } [DllImport("libgio-2.0-0.dll")] static extern void g_mount_remount(IntPtr raw, int flags, IntPtr mount_operation, IntPtr cancellable, GLibSharp.AsyncReadyCallbackNative cb, IntPtr user_data); public void Remount(GLib.MountMountFlags flags, GLib.MountOperation mount_operation, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb) { GLibSharp.AsyncReadyCallbackWrapper cb_wrapper = new GLibSharp.AsyncReadyCallbackWrapper (cb); cb_wrapper.PersistUntilCalled (); g_mount_remount(Handle, (int) flags, mount_operation == null ? IntPtr.Zero : mount_operation.Handle, cancellable == null ? IntPtr.Zero : cancellable.Handle, cb_wrapper.NativeDelegate, IntPtr.Zero); } [DllImport("libgio-2.0-0.dll")] static extern IntPtr g_mount_guess_content_type_finish(IntPtr raw, IntPtr result, out IntPtr error); public string[] GuessContentTypeFinish(GLib.AsyncResult result) { IntPtr error = IntPtr.Zero; IntPtr raw_ret = g_mount_guess_content_type_finish(Handle, result == null ? IntPtr.Zero : result.Handle, out error); string[] ret = GLib.Marshaller.NullTermPtrToStringArray (raw_ret, false); if (error != IntPtr.Zero) throw new GLib.GException (error); return ret; } [DllImport("libgio-2.0-0.dll")] static extern bool g_mount_remount_finish(IntPtr raw, IntPtr result, out IntPtr error); public bool RemountFinish(GLib.AsyncResult result) { IntPtr error = IntPtr.Zero; bool raw_ret = g_mount_remount_finish(Handle, result == null ? IntPtr.Zero : result.Handle, out error); bool ret = raw_ret; if (error != IntPtr.Zero) throw new GLib.GException (error); return ret; } [DllImport("libgio-2.0-0.dll")] static extern void g_mount_eject(IntPtr raw, int flags, IntPtr cancellable, GLibSharp.AsyncReadyCallbackNative cb, IntPtr user_data); [Obsolete] public void Eject(GLib.MountUnmountFlags flags, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb) { GLibSharp.AsyncReadyCallbackWrapper cb_wrapper = new GLibSharp.AsyncReadyCallbackWrapper (cb); cb_wrapper.PersistUntilCalled (); g_mount_eject(Handle, (int) flags, cancellable == null ? IntPtr.Zero : cancellable.Handle, cb_wrapper.NativeDelegate, IntPtr.Zero); } [DllImport("libgio-2.0-0.dll")] static extern IntPtr g_mount_get_name(IntPtr raw); public string Name { get { IntPtr raw_ret = g_mount_get_name(Handle); string ret = GLib.Marshaller.PtrToStringGFree(raw_ret); return ret; } } [DllImport("libgio-2.0-0.dll")] static extern IntPtr g_mount_get_drive(IntPtr raw); public GLib.Drive Drive { get { IntPtr raw_ret = g_mount_get_drive(Handle); GLib.Drive ret = GLib.DriveAdapter.GetObject (raw_ret, false); return ret; } } [DllImport("libgio-2.0-0.dll")] static extern void g_mount_unmount_with_operation(IntPtr raw, int flags, IntPtr mount_operation, IntPtr cancellable, GLibSharp.AsyncReadyCallbackNative cb, IntPtr user_data); public void UnmountWithOperation(GLib.MountUnmountFlags flags, GLib.MountOperation mount_operation, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb) { GLibSharp.AsyncReadyCallbackWrapper cb_wrapper = new GLibSharp.AsyncReadyCallbackWrapper (cb); cb_wrapper.PersistUntilCalled (); g_mount_unmount_with_operation(Handle, (int) flags, mount_operation == null ? IntPtr.Zero : mount_operation.Handle, cancellable == null ? IntPtr.Zero : cancellable.Handle, cb_wrapper.NativeDelegate, IntPtr.Zero); } [DllImport("libgio-2.0-0.dll")] static extern void g_mount_unmount(IntPtr raw, int flags, IntPtr cancellable, GLibSharp.AsyncReadyCallbackNative cb, IntPtr user_data); [Obsolete] public void Unmount(GLib.MountUnmountFlags flags, GLib.Cancellable cancellable, GLib.AsyncReadyCallback cb) { GLibSharp.AsyncReadyCallbackWrapper cb_wrapper = new GLibSharp.AsyncReadyCallbackWrapper (cb); cb_wrapper.PersistUntilCalled (); g_mount_unmount(Handle, (int) flags, cancellable == null ? IntPtr.Zero : cancellable.Handle, cb_wrapper.NativeDelegate, IntPtr.Zero); } [DllImport("libgio-2.0-0.dll")] static extern IntPtr g_mount_get_uuid(IntPtr raw); public string Uuid { get { IntPtr raw_ret = g_mount_get_uuid(Handle); string ret = GLib.Marshaller.PtrToStringGFree(raw_ret); return ret; } } [DllImport("libgio-2.0-0.dll")] static extern void g_mount_unshadow(IntPtr raw); public void Unshadow() { g_mount_unshadow(Handle); } [DllImport("libgio-2.0-0.dll")] static extern bool g_mount_eject_with_operation_finish(IntPtr raw, IntPtr result, out IntPtr error); public bool EjectWithOperationFinish(GLib.AsyncResult result) { IntPtr error = IntPtr.Zero; bool raw_ret = g_mount_eject_with_operation_finish(Handle, result == null ? IntPtr.Zero : result.Handle, out error); bool ret = raw_ret; if (error != IntPtr.Zero) throw new GLib.GException (error); return ret; } [DllImport("libgio-2.0-0.dll")] static extern bool g_mount_is_shadowed(IntPtr raw); public bool IsShadowed { get { bool raw_ret = g_mount_is_shadowed(Handle); bool ret = raw_ret; return ret; } } [DllImport("libgio-2.0-0.dll")] static extern bool g_mount_eject_finish(IntPtr raw, IntPtr result, out IntPtr error); [Obsolete] public bool EjectFinish(GLib.AsyncResult result) { IntPtr error = IntPtr.Zero; bool raw_ret = g_mount_eject_finish(Handle, result == null ? IntPtr.Zero : result.Handle, out error); bool ret = raw_ret; if (error != IntPtr.Zero) throw new GLib.GException (error); return ret; } #endregion } }
// *********************************************************************** // Copyright (c) 2007 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections.Generic; using NUnit.Framework; namespace NUnit.TestData.OneTimeSetUpTearDownData { [TestFixture] public class SetUpAndTearDownFixture { public int setUpCount = 0; public int tearDownCount = 0; public bool throwInBaseSetUp = false; [OneTimeSetUp] public virtual void Init() { setUpCount++; if (throwInBaseSetUp) throw new Exception("Error in base OneTimeSetUp"); } [OneTimeTearDown] public virtual void Destroy() { tearDownCount++; } [Test] public void Success() { } [Test] public void EvenMoreSuccess() { } } [TestFixture] public class SetUpAndTearDownFixtureWithTestCases { public int setUpCount = 0; public int tearDownCount = 0; [OneTimeSetUp] public virtual void Init() { setUpCount++; } [OneTimeTearDown] public virtual void Destroy() { tearDownCount++; } [TestCase(1)] [TestCase(2)] [TestCase(3)] [TestCase(4)] public void Success(int i) { Assert.Pass("Passed with test case {0}", i); } } [TestFixture] public class SetUpAndTearDownFixtureWithTheories { public int setUpCount = 0; public int tearDownCount = 0; [OneTimeSetUp] public virtual void Init() { setUpCount++; } [OneTimeTearDown] public virtual void Destroy() { tearDownCount++; } public struct Data { public int Id { get; set; } } [DatapointSource] public IEnumerable<Data> fetchAllRows() { yield return new Data { Id = 1 }; yield return new Data { Id = 2 }; yield return new Data { Id = 3 }; yield return new Data { Id = 4 }; } [Theory] public void TheoryTest(Data entry) { Assert.Pass("Passed with theory id {0}", entry.Id); } } [TestFixture, Explicit] public class ExplicitSetUpAndTearDownFixture { public int setUpCount = 0; public int tearDownCount = 0; [OneTimeSetUp] public virtual void Init() { setUpCount++; } [OneTimeTearDown] public virtual void Destroy() { tearDownCount++; } [Test] public void Success() { } [Test] public void EvenMoreSuccess() { } } [TestFixture] public class InheritSetUpAndTearDown : SetUpAndTearDownFixture { [Test] public void AnotherTest() { } [Test] public void YetAnotherTest() { } } [TestFixture] public class OverrideSetUpAndTearDown : SetUpAndTearDownFixture { public int derivedSetUpCount; public int derivedTearDownCount; [OneTimeSetUp] public override void Init() { derivedSetUpCount++; } [OneTimeTearDown] public override void Destroy() { derivedTearDownCount++; } [Test] public void AnotherTest() { } [Test] public void YetAnotherTest() { } } [TestFixture] public class DerivedSetUpAndTearDownFixture : SetUpAndTearDownFixture { public int derivedSetUpCount; public int derivedTearDownCount; public bool baseSetUpCalledFirst; public bool baseTearDownCalledLast; [OneTimeSetUp] public void Init2() { derivedSetUpCount++; baseSetUpCalledFirst = this.setUpCount > 0; } [OneTimeTearDown] public void Destroy2() { derivedTearDownCount++; baseTearDownCalledLast = this.tearDownCount == 0; } [Test] public void AnotherTest() { } [Test] public void YetAnotherTest() { } } [TestFixture] public class StaticSetUpAndTearDownFixture { public static int setUpCount = 0; public static int tearDownCount = 0; [OneTimeSetUp] public static void Init() { setUpCount++; } [OneTimeTearDown] public static void Destroy() { tearDownCount++; } [Test] public static void MyTest() { } } [TestFixture] public class DerivedStaticSetUpAndTearDownFixture : StaticSetUpAndTearDownFixture { public static int derivedSetUpCount; public static int derivedTearDownCount; public static bool baseSetUpCalledFirst; public static bool baseTearDownCalledLast; [OneTimeSetUp] public static void Init2() { derivedSetUpCount++; baseSetUpCalledFirst = setUpCount > 0; } [OneTimeTearDown] public static void Destroy2() { derivedTearDownCount++; baseTearDownCalledLast = tearDownCount == 0; } [Test] public static void SomeTest() { } } [TestFixture] public static class StaticClassSetUpAndTearDownFixture { public static int setUpCount = 0; public static int tearDownCount = 0; [OneTimeSetUp] public static void Init() { setUpCount++; } [OneTimeTearDown] public static void Destroy() { tearDownCount++; } [Test] public static void MyTest() { } } [TestFixture] public class FixtureWithParallelizableOnOneTimeSetUp { [OneTimeSetUp] [Parallelizable] public void BadOneTimeSetup() { } [Test] public void Test() { } } [TestFixture] public class MisbehavingFixture { public bool blowUpInSetUp = false; public bool blowUpInTest = false; public bool blowUpInTearDown = false; public int setUpCount = 0; public int tearDownCount = 0; public void Reinitialize() { setUpCount = 0; tearDownCount = 0; blowUpInSetUp = false; blowUpInTearDown = false; } [OneTimeSetUp] public void BlowUpInSetUp() { setUpCount++; if (blowUpInSetUp) throw new Exception("This was thrown from fixture setup"); } [OneTimeTearDown] public void BlowUpInTearDown() { tearDownCount++; if ( blowUpInTearDown ) throw new Exception("This was thrown from fixture teardown"); } [Test] public void BlowUpInTest() { if (blowUpInTest) throw new Exception("This was thrown from a test"); } } [TestFixture] public class ExceptionInConstructor { public ExceptionInConstructor() { throw new Exception( "This was thrown in constructor" ); } [Test] public void nothingToTest() { } } [TestFixture] public class IgnoreInFixtureSetUp { [OneTimeSetUp] public void SetUpCallsIgnore() { Assert.Ignore("OneTimeSetUp called Ignore"); } [Test] public void nothingToTest() { } } [TestFixture] public class SetUpAndTearDownWithTestInName { public int setUpCount = 0; public int tearDownCount = 0; [OneTimeSetUp] public virtual void OneTimeSetUp() { setUpCount++; } [OneTimeTearDown] public virtual void OneTimeTearDown() { tearDownCount++; } [Test] public void Success(){} [Test] public void EvenMoreSuccess(){} } [TestFixture, Ignore( "Do Not Run This" )] public class IgnoredFixture { public bool setupCalled = false; public bool teardownCalled = false; [OneTimeSetUp] public virtual void ShouldNotRun() { setupCalled = true; } [OneTimeTearDown] public virtual void NeitherShouldThis() { teardownCalled = true; } [Test] public void Success(){} [Test] public void EvenMoreSuccess(){} } [TestFixture] public class FixtureWithNoTests { public bool setupCalled = false; public bool teardownCalled = false; [OneTimeSetUp] public virtual void Init() { setupCalled = true; } [OneTimeTearDown] public virtual void Destroy() { teardownCalled = true; } } [TestFixture] public class DisposableFixture : IDisposable { public int disposeCalled = 0; public List<String> Actions = new List<String>(); [OneTimeSetUp] public void OneTimeSetUp() { Actions.Add("OneTimeSetUp"); } [OneTimeTearDown] public void OneTimeTearDown() { Actions.Add("OneTimeTearDown"); } [Test] public void OneTest() { } public void Dispose() { Actions.Add("Dispose"); disposeCalled++; } } [TestFixture] public class DisposableFixtureWithTestCases : IDisposable { public int disposeCalled = 0; [TestCase(1)] [TestCase(2)] [TestCase(3)] [TestCase(4)] public void TestCaseTest(int data) { } public void Dispose() { disposeCalled++; } } }
using System; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Text; using UnityEngine; namespace FMODUnity { [AddComponentMenu("")] public class RuntimeManager : MonoBehaviour { static SystemNotInitializedException initException = null; static RuntimeManager instance; static bool isQuitting = false; [SerializeField] FMODPlatform fmodPlatform; static RuntimeManager Instance { get { if (initException != null) { throw initException; } if (isQuitting) { throw new Exception("FMOD Studio attempted access by script to RuntimeManager while application is quitting"); } if (instance == null) { var existing = FindObjectOfType(typeof(RuntimeManager)) as RuntimeManager; if (existing != null) { // Older versions of the integration may have leaked the runtime manager game object into the scene, // which was then serialized. It won't have valid pointers so don't use it. if (existing.cachedPointers[0] != 0) { instance = existing; instance.studioSystem = new FMOD.Studio.System((IntPtr)instance.cachedPointers[0]); instance.lowlevelSystem = new FMOD.System((IntPtr)instance.cachedPointers[1]); instance.mixerHead = new FMOD.DSP((IntPtr)instance.cachedPointers[2]); return instance; } } var gameObject = new GameObject("FMOD.UnityItegration.RuntimeManager"); instance = gameObject.AddComponent<RuntimeManager>(); DontDestroyOnLoad(gameObject); gameObject.hideFlags = HideFlags.HideInHierarchy; try { #if UNITY_ANDROID && !UNITY_EDITOR // First, obtain the current activity context AndroidJavaObject activity = null; using (var activityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) { activity = activityClass.GetStatic<AndroidJavaObject>("currentActivity"); } using (var fmodJava = new AndroidJavaClass("org.fmod.FMOD")) { if (fmodJava != null) { fmodJava.CallStatic("init", activity); } else { UnityEngine.Debug.LogWarning("FMOD Studio: Cannot initialiaze Java wrapper"); } } #endif RuntimeUtils.EnforceLibraryOrder(); instance.Initialiase(false); } catch (Exception e) { initException = e as SystemNotInitializedException; if (initException == null) { initException = new SystemNotInitializedException(e); } throw initException; } } return instance; } } public static FMOD.Studio.System StudioSystem { get { return Instance.studioSystem; } } public static FMOD.System LowlevelSystem { get { return Instance.lowlevelSystem; } } FMOD.Studio.System studioSystem; FMOD.System lowlevelSystem; FMOD.DSP mixerHead; [SerializeField] private long[] cachedPointers = new long[3]; struct LoadedBank { public FMOD.Studio.Bank Bank; public int RefCount; } Dictionary<string, LoadedBank> loadedBanks = new Dictionary<string, LoadedBank>(); Dictionary<string, uint> loadedPlugins = new Dictionary<string, uint>(); // Explicit comparer to avoid issues on platforms that don't support JIT compilation class GuidComparer : IEqualityComparer<Guid> { bool IEqualityComparer<Guid>.Equals(Guid x, Guid y) { return x.Equals(y); } int IEqualityComparer<Guid>.GetHashCode(Guid obj) { return obj.GetHashCode(); } } Dictionary<Guid, FMOD.Studio.EventDescription> cachedDescriptions = new Dictionary<Guid, FMOD.Studio.EventDescription>(new GuidComparer()); void CheckInitResult(FMOD.RESULT result, string cause) { if (result != FMOD.RESULT.OK) { if (studioSystem != null) { studioSystem.release(); studioSystem = null; } throw new SystemNotInitializedException(result, cause); } } void Initialiase(bool forceNoNetwork) { UnityEngine.Debug.Log("FMOD Studio: Creating runtime system instance"); FMOD.RESULT result; result = FMOD.Studio.System.create(out studioSystem); CheckInitResult(result, "Creating System Object"); studioSystem.getLowLevelSystem(out lowlevelSystem); Settings fmodSettings = Settings.Instance; fmodPlatform = RuntimeUtils.GetCurrentPlatform(); #if UNITY_EDITOR || ((UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX) && DEVELOPMENT_BUILD) result = FMOD.Debug.Initialize(FMOD.DEBUG_FLAGS.LOG, FMOD.DEBUG_MODE.FILE, null, RuntimeUtils.LogFileName); if (result == FMOD.RESULT.ERR_FILE_NOTFOUND) { UnityEngine.Debug.LogWarningFormat("FMOD Studio: Cannot open FMOD debug log file '{0}', logs will be missing for this session.", System.IO.Path.Combine(Application.dataPath, RuntimeUtils.LogFileName)); } else { CheckInitResult(result, "Applying debug settings"); } #endif int realChannels = fmodSettings.GetRealChannels(fmodPlatform); result = lowlevelSystem.setSoftwareChannels(realChannels); CheckInitResult(result, "Set software channels"); result = lowlevelSystem.setSoftwareFormat( fmodSettings.GetSampleRate(fmodPlatform), (FMOD.SPEAKERMODE)fmodSettings.GetSpeakerMode(fmodPlatform), 0 // raw not supported ); CheckInitResult(result, "Set software format"); // Setup up the platforms recommended codec to match the real channel count FMOD.ADVANCEDSETTINGS advancedsettings = new FMOD.ADVANCEDSETTINGS(); #if UNITY_EDITOR || UNITY_STANDALONE advancedsettings.maxVorbisCodecs = realChannels; #elif UNITY_IOS || UNITY_ANDROID || UNITY_WP8_1 || UNITY_PSP2 || UNITY_WII advancedsettings.maxFADPCMCodecs = realChannels; #elif UNITY_XBOXONE advancedsettings.maxXMACodecs = realChannels; #elif UNITY_PS4 advancedsettings.maxAT9Codecs = realChannels; #endif #if UNITY_5_0 || UNITY_5_1 if (fmodSettings.IsLiveUpdateEnabled(fmodPlatform) && !forceNoNetwork) { UnityEngine.Debug.LogWarning("FMOD Studio: Detected Unity 5, running on port 9265"); advancedsettings.profilePort = 9265; } #endif advancedsettings.randomSeed = (uint) DateTime.Now.Ticks; result = lowlevelSystem.setAdvancedSettings(ref advancedsettings); CheckInitResult(result, "Set advanced settings"); FMOD.INITFLAGS lowlevelInitFlags = FMOD.INITFLAGS.NORMAL; FMOD.Studio.INITFLAGS studioInitFlags = FMOD.Studio.INITFLAGS.NORMAL | FMOD.Studio.INITFLAGS.DEFERRED_CALLBACKS; if (fmodSettings.IsLiveUpdateEnabled(fmodPlatform) && !forceNoNetwork) { studioInitFlags |= FMOD.Studio.INITFLAGS.LIVEUPDATE; } FMOD.RESULT initResult = studioSystem.initialize( fmodSettings.GetVirtualChannels(fmodPlatform), studioInitFlags, lowlevelInitFlags, IntPtr.Zero ); CheckInitResult(initResult, "Calling initialize"); // Dummy flush and update to get network state studioSystem.flushCommands(); FMOD.RESULT updateResult = studioSystem.update(); // Restart without liveupdate if there was a socket error if (updateResult == FMOD.RESULT.ERR_NET_SOCKET_ERROR) { studioSystem.release(); UnityEngine.Debug.LogWarning("FMOD Studio: Cannot open network port for Live Update, restarting with Live Update disabled. Check for other applications that are running FMOD Studio"); Initialiase(true); } else { // Load plugins (before banks) #if (UNITY_IOS || UNITY_TVOS) && !UNITY_EDITOR FmodUnityNativePluginInit(lowlevelSystem.getRaw()); #else foreach (var pluginName in fmodSettings.Plugins) { string pluginPath = RuntimeUtils.GetPluginPath(pluginName); uint handle; result = lowlevelSystem.loadPlugin(pluginPath, out handle); #if UNITY_64 || UNITY_EDITOR_64 // Add a "64" suffix and try again if (result == FMOD.RESULT.ERR_FILE_BAD || result == FMOD.RESULT.ERR_FILE_NOTFOUND) { pluginPath = RuntimeUtils.GetPluginPath(pluginName + "64"); result = lowlevelSystem.loadPlugin(pluginPath, out handle); } #endif CheckInitResult(result, String.Format("Loading plugin '{0}' from '{1}'", pluginName, pluginPath)); loadedPlugins.Add(pluginName, handle); } #endif if (fmodSettings.ImportType == ImportType.StreamingAssets) { // Always load strings bank try { LoadBank(fmodSettings.MasterBank + ".strings", fmodSettings.AutomaticSampleLoading); } catch (BankLoadException e) { UnityEngine.Debug.LogException(e); } if (fmodSettings.AutomaticEventLoading) { try { LoadBank(fmodSettings.MasterBank, fmodSettings.AutomaticSampleLoading); } catch (BankLoadException e) { UnityEngine.Debug.LogException(e); } foreach (var bank in fmodSettings.Banks) { try { LoadBank(bank, fmodSettings.AutomaticSampleLoading); } catch (BankLoadException e) { UnityEngine.Debug.LogException(e); } } WaitForAllLoads(); } } }; FMOD.ChannelGroup master; lowlevelSystem.getMasterChannelGroup(out master); master.getDSP(0, out mixerHead); mixerHead.setMeteringEnabled(false, true); } class AttachedInstance { public FMOD.Studio.EventInstance instance; public Transform transform; public Rigidbody rigidBody; } List<AttachedInstance> attachedInstances = new List<AttachedInstance>(128); bool listenerWarningIssued = false; void Update() { if (studioSystem != null) { studioSystem.update(); if (!hasListener && !listenerWarningIssued) { listenerWarningIssued = true; UnityEngine.Debug.LogWarning("FMOD Studio Integration: Please add an 'FMOD Studio Listener' component to your a camera in the scene for correct 3D positioning of sounds"); } for (int i = 0; i < attachedInstances.Count; i++) { FMOD.Studio.PLAYBACK_STATE playbackState = FMOD.Studio.PLAYBACK_STATE.STOPPED; attachedInstances[i].instance.getPlaybackState(out playbackState); if (!attachedInstances[i].instance.isValid() || playbackState == FMOD.Studio.PLAYBACK_STATE.STOPPED || attachedInstances[i].transform == null // destroyed game object ) { attachedInstances.RemoveAt(i); i--; continue; } attachedInstances[i].instance.set3DAttributes(RuntimeUtils.To3DAttributes(attachedInstances[i].transform, attachedInstances[i].rigidBody)); } } } public static void AttachInstanceToGameObject(FMOD.Studio.EventInstance instance, Transform transform, Rigidbody rigidBody) { var attachedInstance = new AttachedInstance(); attachedInstance.transform = transform; attachedInstance.instance = instance; attachedInstance.rigidBody = rigidBody; Instance.attachedInstances.Add(attachedInstance); } public static void DetachInstanceFromGameObject(FMOD.Studio.EventInstance instance) { var manager = Instance; for (int i = 0; i < manager.attachedInstances.Count; i++) { if (manager.attachedInstances[i].instance == instance) { manager.attachedInstances.RemoveAt(i); return; } } } Rect windowRect = new Rect(10, 10, 300, 100); void OnGUI() { if (studioSystem != null && Settings.Instance.IsOverlayEnabled(fmodPlatform)) { windowRect = GUI.Window(0, windowRect, DrawDebugOverlay, "FMOD Studio Debug"); } } string lastDebugText; float lastDebugUpdate = 0; void DrawDebugOverlay(int windowID) { if (lastDebugUpdate + 0.25f < Time.unscaledTime) { if (initException != null) { lastDebugText = initException.Message; } else { StringBuilder debug = new StringBuilder(); FMOD.Studio.CPU_USAGE cpuUsage; studioSystem.getCPUUsage(out cpuUsage); debug.AppendFormat("CPU: dsp = {0:F1}%, studio = {1:F1}%\n", cpuUsage.dspUsage, cpuUsage.studioUsage); int currentAlloc, maxAlloc; FMOD.Memory.GetStats(out currentAlloc, out maxAlloc); debug.AppendFormat("MEMORY: cur = {0}MB, max = {1}MB\n", currentAlloc >> 20, maxAlloc >> 20); int realchannels, channels; lowlevelSystem.getChannelsPlaying(out channels, out realchannels); debug.AppendFormat("CHANNELS: real = {0}, total = {1}\n", realchannels, channels); FMOD.DSP_METERING_INFO metering = new FMOD.DSP_METERING_INFO(); mixerHead.getMeteringInfo(null, metering); float rms = 0; for (int i = 0; i < metering.numchannels; i++) { rms += metering.rmslevel[i] * metering.rmslevel[i]; } rms = Mathf.Sqrt(rms / (float)metering.numchannels); float db = rms > 0 ? 20.0f * Mathf.Log10(rms * Mathf.Sqrt(2.0f)) : -80.0f; if (db > 10.0f) db = 10.0f; debug.AppendFormat("VOLUME: RMS = {0:f2}db\n", db); lastDebugText = debug.ToString(); lastDebugUpdate = Time.unscaledTime; } } GUI.Label(new Rect(10, 20, 290, 100), lastDebugText); GUI.DragWindow(); } void OnDisable() { // If we're being torn down for a script reload - cache the native pointers in something unity can serialize cachedPointers[0] = (long)studioSystem.getRaw(); cachedPointers[1] = (long)lowlevelSystem.getRaw(); cachedPointers[2] = (long)mixerHead.getRaw(); } void OnDestroy() { if (studioSystem != null) { UnityEngine.Debug.Log("FMOD Studio: Destroying runtime system instance"); studioSystem.release(); studioSystem = null; } initException = null; instance = null; isQuitting = true; } void OnApplicationPause(bool pauseStatus) { if (studioSystem != null && studioSystem.isValid()) { if (pauseStatus) { lowlevelSystem.mixerSuspend(); } else { lowlevelSystem.mixerResume(); } } } public static void LoadBank(string bankName, bool loadSamples = false) { if (Instance.loadedBanks.ContainsKey(bankName)) { LoadedBank loadedBank = Instance.loadedBanks[bankName]; loadedBank.RefCount++; if (loadSamples) { loadedBank.Bank.loadSampleData(); } } else { LoadedBank loadedBank = new LoadedBank(); string bankPath = RuntimeUtils.GetBankPath(bankName); FMOD.RESULT loadResult; #if UNITY_ANDROID && !UNITY_EDITOR if (!bankPath.StartsWith("file:///android_asset")) { using (var www = new WWW(bankPath)) { while (!www.isDone) { } if (!String.IsNullOrEmpty(www.error)) { throw new BankLoadException(bankPath, www.error); } else { loadResult = Instance.studioSystem.loadBankMemory(www.bytes, FMOD.Studio.LOAD_BANK_FLAGS.NORMAL, out loadedBank.Bank); } } } else #endif { loadResult = Instance.studioSystem.loadBankFile(bankPath, FMOD.Studio.LOAD_BANK_FLAGS.NORMAL, out loadedBank.Bank); } if (loadResult == FMOD.RESULT.OK) { loadedBank.RefCount = 1; Instance.loadedBanks.Add(bankName, loadedBank); if (loadSamples) { loadedBank.Bank.loadSampleData(); } } else if (loadResult == FMOD.RESULT.ERR_EVENT_ALREADY_LOADED) { // someone loaded this bank directly using the studio API // TODO: will the null bank handle be an issue loadedBank.RefCount = 2; Instance.loadedBanks.Add(bankName, loadedBank); } else { throw new BankLoadException(bankPath, loadResult); } } } public static void LoadBank(TextAsset asset, bool loadSamples = false) { string bankName = asset.name; if (Instance.loadedBanks.ContainsKey(bankName)) { LoadedBank loadedBank = Instance.loadedBanks[bankName]; loadedBank.RefCount++; if (loadSamples) { loadedBank.Bank.loadSampleData(); } } else { LoadedBank loadedBank = new LoadedBank(); FMOD.RESULT loadResult = Instance.studioSystem.loadBankMemory(asset.bytes, FMOD.Studio.LOAD_BANK_FLAGS.NORMAL, out loadedBank.Bank); if (loadResult == FMOD.RESULT.OK) { loadedBank.RefCount = 1; Instance.loadedBanks.Add(bankName, loadedBank); if (loadSamples) { loadedBank.Bank.loadSampleData(); } } else if (loadResult == FMOD.RESULT.ERR_EVENT_ALREADY_LOADED) { // someone loaded this bank directly using the studio API // TODO: will the null bank handle be an issue loadedBank.RefCount = 2; Instance.loadedBanks.Add(bankName, loadedBank); } else { throw new BankLoadException(bankName, loadResult); } } } public static void UnloadBank(string bankName) { LoadedBank loadedBank; if (Instance.loadedBanks.TryGetValue(bankName, out loadedBank)) { loadedBank.RefCount--; if (loadedBank.RefCount == 0) { loadedBank.Bank.unload(); Instance.loadedBanks.Remove(bankName); } } } public static bool AnyBankLoading() { bool loading = false; foreach (LoadedBank bank in Instance.loadedBanks.Values) { FMOD.Studio.LOADING_STATE loadingState; bank.Bank.getSampleLoadingState(out loadingState); loading |= (loadingState == FMOD.Studio.LOADING_STATE.LOADING); } return loading; } public static void WaitForAllLoads() { Instance.studioSystem.flushSampleLoading(); } public static Guid PathToGUID(string path) { Guid guid = Guid.Empty; if (path.StartsWith("{")) { FMOD.Studio.Util.ParseID(path, out guid); } else { var result = Instance.studioSystem.lookupID(path, out guid); if (result == FMOD.RESULT.ERR_EVENT_NOTFOUND) { throw new EventNotFoundException(path); } } return guid; } public static FMOD.Studio.EventInstance CreateInstance(string path) { try { return CreateInstance(PathToGUID(path)); } catch(EventNotFoundException) { // Switch from exception with GUID to exception with path throw new EventNotFoundException(path); } } public static FMOD.Studio.EventInstance CreateInstance(Guid guid) { FMOD.Studio.EventDescription eventDesc = GetEventDescription(guid); FMOD.Studio.EventInstance newInstance; eventDesc.createInstance(out newInstance); return newInstance; } public static void PlayOneShot(string path, Vector3 position = new Vector3()) { try { PlayOneShot(PathToGUID(path), position); } catch (EventNotFoundException) { // Switch from exception with GUID to exception with path throw new EventNotFoundException(path); } } public static void PlayOneShot(Guid guid, Vector3 position = new Vector3()) { var instance = CreateInstance(guid); instance.set3DAttributes(RuntimeUtils.To3DAttributes(position)); instance.start(); instance.release(); } public static void PlayOneShotAttached(string path, GameObject gameObject) { try { PlayOneShotAttached(PathToGUID(path), gameObject); } catch (EventNotFoundException) { // Switch from exception with GUID to exception with path throw new EventNotFoundException(path); } } public static void PlayOneShotAttached(Guid guid, GameObject gameObject) { var instance = CreateInstance(guid); AttachInstanceToGameObject(instance, gameObject.transform, gameObject.GetComponent<Rigidbody>()); instance.start(); } public static FMOD.Studio.EventDescription GetEventDescription(string path) { try { return GetEventDescription(PathToGUID(path)); } catch (EventNotFoundException) { throw new EventNotFoundException(path); } } public static FMOD.Studio.EventDescription GetEventDescription(Guid guid) { FMOD.Studio.EventDescription eventDesc = null; if (Instance.cachedDescriptions.ContainsKey(guid) && Instance.cachedDescriptions[guid].isValid()) { eventDesc = Instance.cachedDescriptions[guid]; } else { var result = Instance.studioSystem.getEventByID(guid, out eventDesc); if (result != FMOD.RESULT.OK) { throw new EventNotFoundException(guid); } if (eventDesc != null && eventDesc.isValid()) { Instance.cachedDescriptions[guid] = eventDesc; } } return eventDesc; } static bool hasListener; public static bool HasListener { set { hasListener = value; } get { return hasListener; } } public static void SetListenerLocation(GameObject gameObject, Rigidbody rigidBody = null) { Instance.studioSystem.setListenerAttributes(0, RuntimeUtils.To3DAttributes(gameObject, rigidBody)); } public static void SetListenerLocation(Transform transform) { Instance.studioSystem.setListenerAttributes(0, transform.To3DAttributes()); } public static FMOD.Studio.Bus GetBus(String path) { FMOD.RESULT result; FMOD.Studio.Bus bus; result = StudioSystem.getBus(path, out bus); if (result != FMOD.RESULT.OK) { } return bus; } public static FMOD.Studio.VCA GetVCA(String path) { FMOD.RESULT result; FMOD.Studio.VCA vca; result = StudioSystem.getVCA(path, out vca); if (result != FMOD.RESULT.OK) { } return vca; } #if (UNITY_IOS || UNITY_TVOS) && !UNITY_EDITOR [DllImport("__Internal")] private static extern FMOD.RESULT FmodUnityNativePluginInit(IntPtr system); #endif } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.InlineDeclaration; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseImplicitType; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.InlineDeclaration { public partial class CSharpInlineDeclarationTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpInlineDeclarationDiagnosticAnalyzer(), new CSharpInlineDeclarationCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariable1() { await TestInRegularAndScriptAsync( @"class C { void M() { [|int|] i; if (int.TryParse(v, out i)) { } } }", @"class C { void M() { if (int.TryParse(v, out int i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineInNestedCall() { await TestInRegularAndScriptAsync( @"class C { void M() { [|int|] i; if (Foo(int.TryParse(v, out i))) { } } }", @"class C { void M() { if (Foo(int.TryParse(v, out int i))) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariableWithConstructor1() { await TestInRegularAndScriptAsync( @"class C { void M() { [|int|] i; if (new C1(v, out i)) { } } }", @"class C { void M() { if (new C1(v, out int i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariableMissingWithIndexer1() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|int|] i; if (this[out i]) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariableIntoFirstOut1() { await TestInRegularAndScriptAsync( @"class C { void M() { [|int|] i; if (int.TryParse(v, out i, out i)) { } } }", @"class C { void M() { if (int.TryParse(v, out int i, out i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariableIntoFirstOut2() { await TestInRegularAndScriptAsync( @"class C { void M() { [|int|] i; if (int.TryParse(v, out i)) { } if (int.TryParse(v, out i)) { } } }", @"class C { void M() { if (int.TryParse(v, out int i)) { } if (int.TryParse(v, out i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInCSharp6() { await TestMissingAsync( @"class C { void M() { [|int|] i; if (int.TryParse(v, out i)) { } } }", new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariablePreferVar1() { await TestInRegularAndScriptAsync( @"class C { void M(string v) { [|int|] i; if (int.TryParse(v, out i)) { } } }", @"class C { void M(string v) { if (int.TryParse(v, out var i)) { } } }", options: new UseImplicitTypeTests().ImplicitTypeEverywhere()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariablePreferVarExceptForPredefinedTypes1() { await TestInRegularAndScriptAsync( @"class C { void M(string v) { [|int|] i; if (int.TryParse(v, out i)) { } } }", @"class C { void M(string v) { if (int.TryParse(v, out int i)) { } } }", options: new UseImplicitTypeTests().ImplicitTypeButKeepIntrinsics()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestAvailableWhenWrittenAfter1() { await TestInRegularAndScriptAsync( @"class C { void M() { [|int|] i; if (int.TryParse(v, out i)) { } i = 0; } }", @"class C { void M() { if (int.TryParse(v, out int i)) { } i = 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingWhenWrittenBetween1() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|int|] i; i = 0; if (int.TryParse(v, out i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingWhenReadBetween1() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|int|] i = 0; M1(i); if (int.TryParse(v, out i)) { } } void M1(int i) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingWithComplexInitializer() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|int|] i = M1(); if (int.TryParse(v, out i)) { } } int M1() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestAvailableInOuterScopeIfNotWrittenOutside() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|int|] i = 0; { if (int.TryParse(v, out i)) { } i = 1; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingIfWrittenAfterInOuterScope() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|int|] i = 0; { if (int.TryParse(v, out i)) { } } i = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingIfWrittenBetweenInOuterScope() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|int|] i = 0; { i = 1; if (int.TryParse(v, out i)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInNonOut() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|int|] i; if (int.TryParse(v, i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInField() { await TestMissingInRegularAndScriptAsync( @"class C { [|int|] i; void M() { if (int.TryParse(v, out this.i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInField2() { await TestMissingInRegularAndScriptAsync( @"class C { [|int|] i; void M() { if (int.TryParse(v, out i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInNonLocalStatement() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { foreach ([|int|] i in e) { if (int.TryParse(v, out i)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInEmbeddedStatementWithWriteAfterwards() { await TestMissingInRegularAndScriptAsync( @"class C { void M() { [|int|] i; while (true) if (int.TryParse(v, out i)) { } i = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInEmbeddedStatement() { await TestInRegularAndScriptAsync( @"class C { void M() { [|int|] i; while (true) if (int.TryParse(v, out i)) { i = 1; } } }", @"class C { void M() { while (true) if (int.TryParse(v, out int i)) { i = 1; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestAvailableInNestedBlock() { await TestInRegularAndScriptAsync( @"class C { void M() { [|int|] i; while (true) { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { while (true) { if (int.TryParse(v, out int i)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestOverloadResolutionDoNotUseVar1() { await TestInRegularAndScriptAsync( @"class C { void M() { [|int|] i; if (M2(out i)) { } } void M2(out int i) { } void M2(out string s) { } }", @"class C { void M() { if (M2(out int i)) { } } void M2(out int i) { } void M2(out string s) { } }", options: new UseImplicitTypeTests().ImplicitTypeEverywhere()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestOverloadResolutionDoNotUseVar2() { await TestInRegularAndScriptAsync( @"class C { void M() { [|var|] i = 0; if (M2(out i)) { } } void M2(out int i) { } void M2(out string s) { } }", @"class C { void M() { if (M2(out int i)) { } } void M2(out int i) { } void M2(out string s) { } }", options: new UseImplicitTypeTests().ImplicitTypeEverywhere()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestGenericInferenceDoNotUseVar3() { await TestInRegularAndScriptAsync( @"class C { void M() { [|int|] i; if (M2(out i)) { } } void M2<T>(out T i) { } }", @"class C { void M() { if (M2(out int i)) { } } void M2<T>(out T i) { } }", options: new UseImplicitTypeTests().ImplicitTypeEverywhere()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments1() { await TestInRegularAndScriptAsync( @"class C { void M() { // prefix comment [|int|] i; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { // prefix comment { if (int.TryParse(v, out int i)) { } } } }", ignoreTrivia: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments2() { await TestInRegularAndScriptAsync( @"class C { void M() { [|int|] i; // suffix comment { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { // suffix comment { if (int.TryParse(v, out int i)) { } } } }", ignoreTrivia: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments3() { await TestInRegularAndScriptAsync( @"class C { void M() { // prefix comment [|int|] i; // suffix comment { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { // prefix comment // suffix comment { if (int.TryParse(v, out int i)) { } } } }", ignoreTrivia: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments4() { await TestInRegularAndScriptAsync( @"class C { void M() { int [|i|] /*suffix*/, j; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { int j; { if (int.TryParse(v, out int i /*suffix*/)) { } } } }", ignoreTrivia: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments5() { await TestInRegularAndScriptAsync( @"class C { void M() { int /*prefix*/ [|i|], j; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { int j; { if (int.TryParse(v, out int /*prefix*/ i)) { } } } }", ignoreTrivia: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments6() { await TestInRegularAndScriptAsync( @"class C { void M() { int /*prefix*/ [|i|] /*suffix*/, j; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { int j; { if (int.TryParse(v, out int /*prefix*/ i /*suffix*/)) { } } } }", ignoreTrivia: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments7() { await TestInRegularAndScriptAsync( @"class C { void M() { int j, /*prefix*/ [|i|] /*suffix*/; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { int j; { if (int.TryParse(v, out int /*prefix*/ i /*suffix*/)) { } } } }", ignoreTrivia: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments8() { await TestInRegularAndScriptAsync( @"class C { void M() { // prefix int j, [|i|]; // suffix { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { // prefix int j; // suffix { if (int.TryParse(v, out int i)) { } } } }", ignoreTrivia: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments9() { await TestInRegularAndScriptAsync( @"class C { void M() { int /*int comment*/ /*prefix*/ [|i|] /*suffix*/, j; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { int /*int comment*/ j; { if (int.TryParse(v, out int /*prefix*/ i /*suffix*/)) { } } } }", ignoreTrivia: false); } [WorkItem(15994, "https://github.com/dotnet/roslyn/issues/15994")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestCommentsTrivia1() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { Console.WriteLine(""Foo""); int [|result|]; if (int.TryParse(""12"", out result)) { } } }", @"using System; class Program { static void Main(string[] args) { Console.WriteLine(""Foo""); if (int.TryParse(""12"", out int result)) { } } }", ignoreTrivia: false); } [WorkItem(15994, "https://github.com/dotnet/roslyn/issues/15994")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestCommentsTrivia2() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { Console.WriteLine(""Foo""); // Foo int [|result|]; if (int.TryParse(""12"", out result)) { } } }", @"using System; class Program { static void Main(string[] args) { Console.WriteLine(""Foo""); // Foo if (int.TryParse(""12"", out int result)) { } } }", ignoreTrivia: false); } [WorkItem(15336, "https://github.com/dotnet/roslyn/issues/15336")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestNotMissingIfCapturedInLambdaAndNotUsedAfterwards() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { string [|s|]; Bar(() => Baz(out s)); } void Baz(out string s) { } void Bar(Action a) { } }", @" using System; class C { void M() { Bar(() => Baz(out string s)); } void Baz(out string s) { } void Bar(Action a) { } }"); } [WorkItem(15336, "https://github.com/dotnet/roslyn/issues/15336")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingIfCapturedInLambdaAndUsedAfterwards() { await TestMissingInRegularAndScriptAsync( @" using System; class C { void M() { string [|s|]; Bar(() => Baz(out s)); Console.WriteLine(s); } void Baz(out string s) { } void Bar(Action a) { } }"); } [WorkItem(15408, "https://github.com/dotnet/roslyn/issues/15408")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestDataFlow1() { await TestMissingInRegularAndScriptAsync( @" using System; class C { void Foo(string x) { object [|s|] = null; if (x != null || TryBaz(out s)) { Console.WriteLine(s); } } private bool TryBaz(out object s) { throw new NotImplementedException(); } }"); } [WorkItem(15408, "https://github.com/dotnet/roslyn/issues/15408")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestDataFlow2() { await TestInRegularAndScriptAsync( @" using System; class C { void Foo(string x) { object [|s|] = null; if (x != null && TryBaz(out s)) { Console.WriteLine(s); } } private bool TryBaz(out object s) { throw new NotImplementedException(); } }", @" using System; class C { void Foo(string x) { if (x != null && TryBaz(out object s)) { Console.WriteLine(s); } } private bool TryBaz(out object s) { throw new NotImplementedException(); } }"); } [WorkItem(16028, "https://github.com/dotnet/roslyn/issues/16028")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestExpressionTree1() { await TestMissingInRegularAndScriptAsync( @" using System; using System.Linq.Expressions; class Program { static void Main(string[] args) { int [|result|]; Method(() => GetValue(out result)); } public static void GetValue(out int result) { result = 0; } public static void Method(Expression<Action> expression) { } }"); } [WorkItem(16198, "https://github.com/dotnet/roslyn/issues/16198")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestIndentation1() { await TestInRegularAndScriptAsync( @" using System; class C { private int Bar() { IProjectRuleSnapshot [|unresolvedReferenceSnapshot|] = null; var itemType = GetUnresolvedReferenceItemType(originalItemSpec, updatedUnresolvedSnapshots, catalogs, out unresolvedReferenceSnapshot); } }", @" using System; class C { private int Bar() { var itemType = GetUnresolvedReferenceItemType(originalItemSpec, updatedUnresolvedSnapshots, catalogs, out IProjectRuleSnapshot unresolvedReferenceSnapshot); } }"); } [WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestNotInLoops1() { await TestMissingAsync( @" using System; class C { static void Main(string[] args) { string [|token|]; do { } while (!TryExtractTokenFromEmail(out token)); Console.WriteLine(token == ""Test""); } private static bool TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestNotInLoops2() { await TestMissingAsync( @" using System; class C { static void Main(string[] args) { string [|token|]; while (!TryExtractTokenFromEmail(out token)) { } Console.WriteLine(token == ""Test""); } private static bool TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestNotInLoops3() { await TestMissingAsync( @" using System; using System.Collections.Generic; class C { static void Main(string[] args) { string [|token|]; foreach (var v in TryExtractTokenFromEmail(out token)) { } Console.WriteLine(token == ""Test""); } private static IEnumerable<bool> TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestNotInLoops4() { await TestMissingAsync( @" using System; using System.Collections.Generic; class C { static void Main(string[] args) { string [|token|]; for ( ; TryExtractTokenFromEmail(out token); ) { } Console.WriteLine(token == ""Test""); } private static bool TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInLoops1() { await TestInRegularAndScript1Async( @" using System; class C { static void Main(string[] args) { string [|token|]; do { } while (!TryExtractTokenFromEmail(out token)); } private static bool TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }", @" using System; class C { static void Main(string[] args) { do { } while (!TryExtractTokenFromEmail(out string token)); } private static bool TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInLoops2() { await TestInRegularAndScript1Async( @" using System; class C { static void Main(string[] args) { string [|token|]; while (!TryExtractTokenFromEmail(out token)) { } } private static bool TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }", @" using System; class C { static void Main(string[] args) { while (!TryExtractTokenFromEmail(out string token)) { } } private static bool TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/17635"), Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInLoops3() { await TestInRegularAndScript1Async( @" using System; using System.Collections.Generic; class C { static void Main(string[] args) { string [|token|]; foreach (var v in TryExtractTokenFromEmail(out token)) { } } private static IEnumerable<bool> TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }", @" using System; using System.Collections.Generic; class C { static void Main(string[] args) { foreach (var v in TryExtractTokenFromEmail(out string token)) { } } private static IEnumerable<bool> TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(17624, "https://github.com/dotnet/roslyn/issues/17624")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInLoops4() { await TestInRegularAndScript1Async( @" using System; using System.Collections.Generic; class C { static void Main(string[] args) { string [|token|]; for ( ; TryExtractTokenFromEmail(out token); ) { } } private static bool TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }", @" using System; using System.Collections.Generic; class C { static void Main(string[] args) { for ( ; TryExtractTokenFromEmail(out string token); ) { } } private static bool TryExtractTokenFromEmail(out string token) { throw new NotImplementedException(); } }"); } [WorkItem(17743, "https://github.com/dotnet/roslyn/issues/17743")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInLocalFunction() { // Note: this currently works, but it should be missing. // This test validates that we don't crash in this case though. await TestInRegularAndScript1Async( @" using System; using System.Collections.Generic; class Demo { static void Main() { F(); void F() { Action f = () => { Dictionary<int, int> dict = null; int [|x|] = 0; dict?.TryGetValue(0, out x); Console.WriteLine(x); }; } } }", @" using System; using System.Collections.Generic; class Demo { static void Main() { F(); void F() { Action f = () => { Dictionary<int, int> dict = null; dict?.TryGetValue(0, out int x); Console.WriteLine(x); }; } } }"); } [WorkItem(16676, "https://github.com/dotnet/roslyn/issues/16676")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMultipleDeclarationStatementsOnSameLine1() { await TestInRegularAndScript1Async( @" class C { void Foo() { string a; string [|b|]; Method(out a, out b); } }", @" class C { void Foo() { string a; Method(out a, out string b); } }", ignoreTrivia: false); } [WorkItem(16676, "https://github.com/dotnet/roslyn/issues/16676")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMultipleDeclarationStatementsOnSameLine2() { await TestInRegularAndScript1Async( @" class C { void Foo() { string a; /*leading*/ string [|b|]; // trailing Method(out a, out b); } }", @" class C { void Foo() { string a; /*leading*/ // trailing Method(out a, out string b); } }", ignoreTrivia: false); } [WorkItem(16676, "https://github.com/dotnet/roslyn/issues/16676")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMultipleDeclarationStatementsOnSameLine3() { await TestInRegularAndScript1Async( @" class C { void Foo() { string a; /*leading*/ string [|b|]; // trailing Method(out a, out b); } }", @" class C { void Foo() { string a; /*leading*/ // trailing Method(out a, out string b); } }", ignoreTrivia: false); } } }
namespace System.Workflow.ComponentModel.Serialization { using System; using System.Reflection; using System.CodeDom; using System.CodeDom.Compiler; using System.Xml; using System.Collections.Generic; using System.Globalization; using System.ComponentModel.Design.Serialization; using System.Text; using System.Workflow.ComponentModel.Design; using System.Workflow.ComponentModel.Compiler; using System.Collections; using System.IO; using System.Diagnostics; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; #region Class ActivityMarkupSerializer [DefaultSerializationProvider(typeof(ActivityMarkupSerializationProvider))] [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public class ActivityMarkupSerializer : WorkflowMarkupSerializer { private const int minusOne = -1; // some user data keys need to be visible to the user, see #15400 "We should convert the UserDataKeys.DynamicEvents to DependencyProperty." public static readonly DependencyProperty StartLineProperty = DependencyProperty.RegisterAttached("StartLine", typeof(int), typeof(ActivityMarkupSerializer), new PropertyMetadata(minusOne, new Attribute[] { new DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden) })); public static readonly DependencyProperty StartColumnProperty = DependencyProperty.RegisterAttached("StartColumn", typeof(int), typeof(ActivityMarkupSerializer), new PropertyMetadata(minusOne, new Attribute[] { new DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden) })); public static readonly DependencyProperty EndLineProperty = DependencyProperty.RegisterAttached("EndLine", typeof(int), typeof(ActivityMarkupSerializer), new PropertyMetadata(minusOne, new Attribute[] { new DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden) })); public static readonly DependencyProperty EndColumnProperty = DependencyProperty.RegisterAttached("EndColumn", typeof(int), typeof(ActivityMarkupSerializer), new PropertyMetadata(minusOne, new Attribute[] { new DesignerSerializationVisibilityAttribute(DesignerSerializationVisibility.Hidden) })); [SuppressMessage("Microsoft.Globalization", "CA1307:SpecifyStringComparison", MessageId = "System.String.IndexOf(System.String,System.Int32)", Justification = "This is not a security threat since it is called in design time (compile) scenarios")] protected override void OnBeforeSerialize(WorkflowMarkupSerializationManager serializationManager, object obj) { if (serializationManager == null) throw new ArgumentNullException("serializationManager"); if (obj == null) throw new ArgumentNullException("obj"); Activity activity = obj as Activity; if (activity == null) throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(Activity).FullName), "obj"); XmlWriter writer = serializationManager.WorkflowMarkupStack[typeof(XmlWriter)] as XmlWriter; if (writer == null) { //We should not throw an exception here as both of the above properties are internal and //our serializer makes sure that they are always set. Note that OnBeforeSerialize can be //only called by WorkflowMarkupSerializer. Debug.Assert(false); return; } StringWriter stringWriter = serializationManager.WorkflowMarkupStack[typeof(StringWriter)] as StringWriter; if (stringWriter != null) { // we capture the start and end line of the activity getting serialized to xoml writer.Flush(); string currentXoml = stringWriter.ToString(); int startLine = 0; int currentIndex = 0; string newLine = stringWriter.NewLine; int newLineLength = newLine.Length; // Get to the starting line of this activity. while (true) { int nextNewLineIndex = currentXoml.IndexOf(newLine, currentIndex, StringComparison.Ordinal); if (nextNewLineIndex == -1) break; currentIndex = nextNewLineIndex + newLineLength; startLine++; } // We always serialize an element start tag onto exactly 1 line. activity.SetValue(ActivityMarkupSerializer.StartLineProperty, startLine); activity.SetValue(ActivityMarkupSerializer.EndLineProperty, startLine); // Cache the index of the beginning of the line. activity.SetValue(ActivityMarkupSerializer.EndColumnProperty, currentIndex); activity.SetValue(ActivityMarkupSerializer.StartColumnProperty, (currentXoml.IndexOf('<', currentIndex) - currentIndex + 1)); } // write x:Class attribute string className = activity.GetValue(WorkflowMarkupSerializer.XClassProperty) as string; if (className != null) writer.WriteAttributeString(StandardXomlKeys.Definitions_XmlNs_Prefix, StandardXomlKeys.Definitions_Class_LocalName, StandardXomlKeys.Definitions_XmlNs, className); } protected override object CreateInstance(WorkflowMarkupSerializationManager serializationManager, Type type) { XmlReader reader = serializationManager.WorkflowMarkupStack[typeof(XmlReader)] as XmlReader; if (reader == null) { Debug.Assert(false); return null; } object instance = base.CreateInstance(serializationManager, type); if (instance is Activity && (serializationManager.Context[typeof(Activity)] == null && serializationManager.Context[typeof(WorkflowCompilerParameters)] != null)) (instance as Activity).UserData[UserDataKeys.CustomActivity] = false; WorkflowMarkupSourceAttribute[] sourceAttrs = (WorkflowMarkupSourceAttribute[])type.GetCustomAttributes(typeof(WorkflowMarkupSourceAttribute), false); if (instance is CompositeActivity && sourceAttrs.Length > 0 && type.Assembly == serializationManager.LocalAssembly) { object instance2 = null; using (XmlReader reader2 = XmlReader.Create(sourceAttrs[0].FileName)) instance2 = Deserialize(serializationManager, reader2); ReplaceChildActivities(instance as CompositeActivity, instance2 as CompositeActivity); } if (instance is Activity) { int lineNumber = (reader is IXmlLineInfo) ? ((IXmlLineInfo)reader).LineNumber : 1; int linePosition = (reader is IXmlLineInfo) ? ((IXmlLineInfo)reader).LinePosition : 1; int startLine = lineNumber - 1; int startColumn = linePosition - 1; bool fAttributeExists = false; while (reader.MoveToNextAttribute()) fAttributeExists = true; int endLine = lineNumber - 1; int endColumn; if (fAttributeExists) { reader.ReadAttributeValue(); endColumn = linePosition + reader.Value.Length; } else endColumn = linePosition + reader.Name.Length - 1; reader.MoveToElement(); System.Diagnostics.Debug.Assert(startLine + 1 == lineNumber && startColumn + 1 == linePosition, "Error getting (line, column)!"); Activity activity = (Activity)instance; activity.SetValue(ActivityMarkupSerializer.StartLineProperty, startLine); activity.SetValue(ActivityMarkupSerializer.StartColumnProperty, startColumn); activity.SetValue(ActivityMarkupSerializer.EndLineProperty, endLine); activity.SetValue(ActivityMarkupSerializer.EndColumnProperty, endColumn); } return instance; } [SuppressMessage("Microsoft.Globalization", "CA1307:SpecifyStringComparison", MessageId = "System.String.IndexOf(System.String,System.Int32)", Justification = "This is not a security threat since it is called in design time (compile) scenarios")] protected override void OnAfterSerialize(WorkflowMarkupSerializationManager serializationManager, object obj) { if (serializationManager == null) throw new ArgumentNullException("serializationManager"); if (obj == null) throw new ArgumentNullException("obj"); Activity activity = obj as Activity; if (activity == null) throw new ArgumentException(SR.GetString(SR.Error_UnexpectedArgumentType, typeof(Activity).FullName), "obj"); XmlWriter writer = serializationManager.WorkflowMarkupStack[typeof(XmlWriter)] as XmlWriter; if (writer == null) { Debug.Assert(false); return; } StringWriter stringWriter = serializationManager.WorkflowMarkupStack[typeof(StringWriter)] as StringWriter; if (stringWriter != null) { string currentXoml = stringWriter.ToString(); int lineStartIndex = (int)activity.GetValue(ActivityMarkupSerializer.EndColumnProperty); int lastNewLine = currentXoml.IndexOf(stringWriter.NewLine, (int)lineStartIndex, StringComparison.Ordinal); if (lastNewLine == -1) activity.SetValue(ActivityMarkupSerializer.EndColumnProperty, (currentXoml.Length - lineStartIndex - 1)); else activity.SetValue(ActivityMarkupSerializer.EndColumnProperty, lastNewLine - lineStartIndex); } CodeTypeMemberCollection codeSegments = activity.GetValue(WorkflowMarkupSerializer.XCodeProperty) as CodeTypeMemberCollection; if (codeSegments != null) { foreach (CodeSnippetTypeMember cs in codeSegments) { if (cs.Text == null) continue; writer.WriteStartElement(StandardXomlKeys.Definitions_XmlNs_Prefix, StandardXomlKeys.Definitions_Code_LocalName, StandardXomlKeys.Definitions_XmlNs); int depth = serializationManager.WriterDepth; StringBuilder prettySegment = new StringBuilder(); if (cs.UserData.Contains(UserDataKeys.CodeSegment_New)) { prettySegment.AppendLine(); string[] lines = cs.Text.Trim().Split(new string[] { "\r\n" }, StringSplitOptions.None); foreach (string line in lines) { prettySegment.Append(writer.Settings.IndentChars); prettySegment.Append(line); prettySegment.AppendLine(); } prettySegment.Append(writer.Settings.IndentChars); } else { prettySegment.Append(cs.Text); } writer.WriteCData(prettySegment.ToString()); writer.WriteEndElement(); } } } internal static void ReplaceChildActivities(CompositeActivity instanceActivity, CompositeActivity xomlActivity) { ArrayList activities = new ArrayList(); foreach (Activity activity1 in (xomlActivity as CompositeActivity).Activities) { activities.Add(activity1); } try { // Clear the activities instanceActivity.CanModifyActivities = true; xomlActivity.CanModifyActivities = true; instanceActivity.Activities.Clear(); xomlActivity.Activities.Clear(); foreach (Activity activity in activities) { instanceActivity.Activities.Add(activity); } } finally { instanceActivity.CanModifyActivities = false; xomlActivity.CanModifyActivities = false; } if (!instanceActivity.UserData.Contains(UserDataKeys.CustomActivity)) instanceActivity.UserData[UserDataKeys.CustomActivity] = (instanceActivity.Activities.Count > 0); } } #endregion }
#region Foreign-License /* Copyright (c) 2001 Bruce A. Johnson Copyright (c) 1997 Sun Microsystems, Inc. Copyright (c) 2012 Sky Morey See the file "license.terms" for information on usage and redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES. */ #endregion using System; using System.Text; namespace Tcl.Lang { /// <summary> This class implements the built-in "fconfigure" command in Tcl.</summary> class FconfigureCmd : ICommand { private static readonly string[] validCmds = new string[] { "-blocking", "-buffering", "-buffersize", "-encoding", "-eofchar", "-translation" }; internal const int OPT_BLOCKING = 0; internal const int OPT_BUFFERING = 1; internal const int OPT_BUFFERSIZE = 2; internal const int OPT_ENCODING = 3; internal const int OPT_EOFCHAR = 4; internal const int OPT_TRANSLATION = 5; /// <summary> This procedure is invoked to process the "fconfigure" Tcl command. /// See the user documentation for details on what it does. /// /// </summary> /// <param name="interp">the current interpreter. /// </param> /// <param name="argv">command arguments. /// </param> public TCL.CompletionCode CmdProc(Interp interp, TclObject[] argv) { Channel chan; // The channel being operated on this method if ((argv.Length < 2) || (((argv.Length % 2) == 1) && (argv.Length != 3))) { throw new TclNumArgsException(interp, 1, argv, "channelId ?optionName? ?value? ?optionName value?..."); } chan = TclIO.getChannel(interp, argv[1].ToString()); if (chan == null) { throw new TclException(interp, "can not find channel named \"" + argv[1].ToString() + "\""); } if (argv.Length == 2) { // return list of all name/value pairs for this channelId TclObject list = TclList.NewInstance(); TclList.Append(interp, list, TclString.NewInstance("-blocking")); TclList.Append(interp, list, TclBoolean.newInstance(chan.Blocking)); TclList.Append(interp, list, TclString.NewInstance("-buffering")); TclList.Append(interp, list, TclString.NewInstance(TclIO.getBufferingString(chan.Buffering))); TclList.Append(interp, list, TclString.NewInstance("-buffersize")); TclList.Append(interp, list, TclInteger.NewInstance(chan.BufferSize)); // -encoding TclList.Append(interp, list, TclString.NewInstance("-encoding")); System.Text.Encoding javaEncoding = chan.Encoding; string tclEncoding; if ((System.Object)javaEncoding == null) { tclEncoding = "binary"; } else { tclEncoding = EncodingCmd.getTclName(javaEncoding); } TclList.Append(interp, list, TclString.NewInstance(tclEncoding)); // -eofchar TclList.Append(interp, list, TclString.NewInstance("-eofchar")); if (chan.ReadOnly) { char eofChar = chan.InputEofChar; TclList.Append(interp, list, (eofChar == 0) ? TclString.NewInstance("") : TclString.NewInstance(eofChar)); } else if (chan.WriteOnly) { char eofChar = chan.OutputEofChar; TclList.Append(interp, list, (eofChar == 0) ? TclString.NewInstance("") : TclString.NewInstance(eofChar)); } else if (chan.ReadWrite) { char inEofChar = chan.InputEofChar; char outEofChar = chan.OutputEofChar; TclObject eofchar_pair = TclList.NewInstance(); TclList.Append(interp, eofchar_pair, (inEofChar == 0) ? TclString.NewInstance("") : TclString.NewInstance(inEofChar)); TclList.Append(interp, eofchar_pair, (outEofChar == 0) ? TclString.NewInstance("") : TclString.NewInstance(outEofChar)); TclList.Append(interp, list, eofchar_pair); } else { // Not readable or writeable, do nothing } // -translation TclList.Append(interp, list, TclString.NewInstance("-translation")); if (chan.ReadOnly) { TclList.Append(interp, list, TclString.NewInstance(TclIO.getTranslationString(chan.InputTranslation))); } else if (chan.WriteOnly) { TclList.Append(interp, list, TclString.NewInstance(TclIO.getTranslationString(chan.OutputTranslation))); } else if (chan.ReadWrite) { TclObject translation_pair = TclList.NewInstance(); TclList.Append(interp, translation_pair, TclString.NewInstance(TclIO.getTranslationString(chan.InputTranslation))); TclList.Append(interp, translation_pair, TclString.NewInstance(TclIO.getTranslationString(chan.OutputTranslation))); TclList.Append(interp, list, translation_pair); } else { // Not readable or writeable, do nothing } interp.SetResult(list); } if (argv.Length == 3) { // return value for supplied name int index = TclIndex.Get(interp, argv[2], validCmds, "option", 0); switch (index) { case OPT_BLOCKING: { // -blocking interp.SetResult(chan.Blocking); break; } case OPT_BUFFERING: { // -buffering interp.SetResult(TclIO.getBufferingString(chan.Buffering)); break; } case OPT_BUFFERSIZE: { // -buffersize interp.SetResult(chan.BufferSize); break; } case OPT_ENCODING: { // -encoding System.Text.Encoding javaEncoding = chan.Encoding; if ((System.Object)javaEncoding == null) { interp.SetResult("binary"); } else { interp.SetResult(EncodingCmd.getTclName(javaEncoding)); } break; } case OPT_EOFCHAR: { // -eofchar if (chan.ReadOnly) { char eofChar = chan.InputEofChar; interp.SetResult((eofChar == 0) ? TclString.NewInstance("") : TclString.NewInstance(eofChar)); } else if (chan.WriteOnly) { char eofChar = chan.OutputEofChar; interp.SetResult((eofChar == 0) ? TclString.NewInstance("") : TclString.NewInstance(eofChar)); } else if (chan.ReadWrite) { char inEofChar = chan.InputEofChar; char outEofChar = chan.OutputEofChar; TclObject eofchar_pair = TclList.NewInstance(); TclList.Append(interp, eofchar_pair, (inEofChar == 0) ? TclString.NewInstance("") : TclString.NewInstance(inEofChar)); TclList.Append(interp, eofchar_pair, (outEofChar == 0) ? TclString.NewInstance("") : TclString.NewInstance(outEofChar)); interp.SetResult(eofchar_pair); } else { // Not readable or writeable, do nothing } break; } case OPT_TRANSLATION: { // -translation if (chan.ReadOnly) { interp.SetResult(TclIO.getTranslationString(chan.InputTranslation)); } else if (chan.WriteOnly) { interp.SetResult(TclIO.getTranslationString(chan.OutputTranslation)); } else if (chan.ReadWrite) { TclObject translation_pair = TclList.NewInstance(); TclList.Append(interp, translation_pair, TclString.NewInstance(TclIO.getTranslationString(chan.InputTranslation))); TclList.Append(interp, translation_pair, TclString.NewInstance(TclIO.getTranslationString(chan.OutputTranslation))); interp.SetResult(translation_pair); } else { // Not readable or writeable, do nothing } break; } default: { throw new TclRuntimeError("Fconfigure.cmdProc() error: " + "incorrect index returned from TclIndex.get()"); } } } for (int i = 3; i < argv.Length; i += 2) { // Iterate through the list setting the name with the // corresponding value. int index = TclIndex.Get(interp, argv[i - 1], validCmds, "option", 0); switch (index) { case OPT_BLOCKING: { // -blocking chan.Blocking = TclBoolean.get(interp, argv[i]); break; } case OPT_BUFFERING: { // -buffering int id = TclIO.getBufferingID(argv[i].ToString()); if (id == -1) { throw new TclException(interp, "bad value for -buffering: must be " + "one of full, line, or none"); } chan.Buffering = id; break; } case OPT_BUFFERSIZE: { // -buffersize chan.BufferSize = TclInteger.Get(interp, argv[i]); break; } case OPT_ENCODING: { // -encoding string tclEncoding = argv[i].ToString(); if (tclEncoding.Equals("") || tclEncoding.Equals("binary")) { chan.Encoding = null; } else { System.Text.Encoding javaEncoding = EncodingCmd.getJavaName(tclEncoding); if ((System.Object)javaEncoding == null) { throw new TclException(interp, "unknown encoding \"" + tclEncoding + "\""); } chan.Encoding = javaEncoding; } break; } case OPT_EOFCHAR: { // -eofchar TclList.setListFromAny(interp, argv[i]); int length = TclList.getLength(interp, argv[i]); if (length > 2) { throw new TclException(interp, "bad value for -eofchar: " + "should be a list of zero, one, or two elements"); } char inputEofChar, outputEofChar; string s; if (length == 0) { inputEofChar = outputEofChar = (char)(0); } else if (length == 1) { s = TclList.index(interp, argv[i], 0).ToString(); inputEofChar = outputEofChar = s[0]; } else { s = TclList.index(interp, argv[i], 0).ToString(); inputEofChar = s[0]; s = TclList.index(interp, argv[i], 1).ToString(); outputEofChar = s[0]; } chan.InputEofChar = inputEofChar; chan.OutputEofChar = outputEofChar; break; } case OPT_TRANSLATION: { // -translation TclList.setListFromAny(interp, argv[i]); int length = TclList.getLength(interp, argv[i]); if (length < 1 || length > 2) { throw new TclException(interp, "bad value for -translation: " + "must be a one or two element list"); } string inputTranslationArg, outputTranslationArg; int inputTranslation, outputTranslation; if (length == 2) { inputTranslationArg = TclList.index(interp, argv[i], 0).ToString(); inputTranslation = TclIO.getTranslationID(inputTranslationArg); outputTranslationArg = TclList.index(interp, argv[i], 1).ToString(); outputTranslation = TclIO.getTranslationID(outputTranslationArg); } else { outputTranslationArg = inputTranslationArg = argv[i].ToString(); outputTranslation = inputTranslation = TclIO.getTranslationID(outputTranslationArg); } if ((inputTranslation == -1) || (outputTranslation == -1)) { throw new TclException(interp, "bad value for -translation: " + "must be one of auto, binary, cr, lf, " + "crlf, or platform"); } if (outputTranslation == TclIO.TRANS_AUTO) outputTranslation = TclIO.TRANS_PLATFORM; if (chan.ReadOnly) { chan.InputTranslation = inputTranslation; if (inputTranslationArg.Equals("binary")) { chan.Encoding = null; } } else if (chan.WriteOnly) { chan.OutputTranslation = outputTranslation; if (outputTranslationArg.Equals("binary")) { chan.Encoding = null; } } else if (chan.ReadWrite) { chan.InputTranslation = inputTranslation; chan.OutputTranslation = outputTranslation; if (inputTranslationArg.Equals("binary") || outputTranslationArg.Equals("binary")) { chan.Encoding = null; } } else { // Not readable or writeable, do nothing } break; } default: { throw new TclRuntimeError("Fconfigure.cmdProc() error: " + "incorrect index returned from TclIndex.get()"); } } } return TCL.CompletionCode.RETURN; } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You 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. ==================================================================== */ namespace TestCases.OpenXml4Net.OPC { using System; using System.IO; using System.Xml; using NPOI; using NPOI.Openxml4Net.Exceptions; using NPOI.OpenXml4Net.OPC; using NPOI.SS.UserModel; using NPOI.Util; using NPOI.XSSF; using NPOI.XWPF.UserModel; using NUnit.Framework; using TestCases; using TestCases.OpenXml4Net; [TestFixture] public class TestZipPackage { [Test] public void TestBug56479() { Stream is1 = OpenXml4NetTestDataSamples.OpenSampleStream("dcterms_bug_56479.zip"); OPCPackage p = OPCPackage.Open(is1); // Check we found the contents of it bool foundCoreProps = false, foundDocument = false, foundTheme1 = false; foreach (PackagePart part in p.GetParts()) { if (part.PartName.ToString().Equals("/docProps/core.xml")) { Assert.AreEqual(ContentTypes.CORE_PROPERTIES_PART, part.ContentType); foundCoreProps = true; } if (part.PartName.ToString().Equals("/word/document.xml")) { Assert.AreEqual(XWPFRelation.DOCUMENT.ContentType, part.ContentType); foundDocument = true; } if (part.PartName.ToString().Equals("/word/theme/theme1.xml")) { Assert.AreEqual(XWPFRelation.THEME.ContentType, part.ContentType); foundTheme1 = true; } } Assert.IsTrue(foundCoreProps, "Core not found in " + p.GetParts()); Assert.IsFalse(foundDocument, "Document should not be found in " + p.GetParts()); Assert.IsFalse(foundTheme1, "Theme1 should not found in " + p.GetParts()); p.Close(); is1.Close(); } [Test] [Ignore("Need ZipSecureFile")] public void TestZipEntityExpansionTerminates() { try { IWorkbook wb = XSSFTestDataSamples.OpenSampleWorkbook("poc-xmlbomb.xlsx"); wb.Close(); Assert.Fail("Should catch exception due to entity expansion limitations"); } catch (POIXMLException e) { assertEntityLimitReached(e); } } private void assertEntityLimitReached(Exception e) { //ByteArrayOutputStream str = new ByteArrayOutputStream(); //PrintWriter writer = new PrintWriter(new OutputStreamWriter(str, "UTF-8")); try { //e.printStackTrace(writer); } finally { //writer.close(); } //String string1 = new String(str.toByteArray(), "UTF-8"); String string1 = e.Message; Assert.IsTrue(string1.Contains("The parser has encountered more than"), "Had: " + string1); } [Test] [Ignore("not implement class ExtractorFactory")] public void TestZipEntityExpansionExceedsMemory() { try { IWorkbook wb = WorkbookFactory.Create(XSSFTestDataSamples.OpenSamplePackage("poc-xmlbomb.xlsx")); wb.Close(); Assert.Fail("Should catch exception due to entity expansion limitations"); } catch (POIXMLException e) { assertEntityLimitReached(e); } try { //POITextExtractor extractor = ExtractorFactory.CreateExtractor(HSSFTestDataSamples.GetSampleFile("poc-xmlbomb.xlsx")); //try //{ // Assert.IsNotNull(extractor); // try // { // string tmp = extractor.Text; // } // catch (InvalidOperationException e) // { // // expected due to shared strings expansion // } //} //finally //{ // extractor.Close(); //} } catch (POIXMLException e) { assertEntityLimitReached(e); } } [Test] [Ignore("not implement class ExtractorFactory")] public void TestZipEntityExpansionSharedStringTable() { IWorkbook wb = WorkbookFactory.Create(XSSFTestDataSamples.OpenSamplePackage("poc-shared-strings.xlsx")); wb.Close(); //POITextExtractor extractor = ExtractorFactory.CreateExtractor(HSSFTestDataSamples.GetSampleFile("poc-shared-strings.xlsx")); //try //{ // Assert.IsNotNull(extractor); // try // { // string tmp = extractor.Text; // } // catch (InvalidOperationException e) // { // // expected due to shared strings expansion // } //} //finally //{ // extractor.Close(); //} } [Test] [Ignore("not implement class ExtractorFactory")] public void TestZipEntityExpansionSharedStringTableEvents() { //bool before = ExtractorFactory.ThreadPrefersEventExtractors; //ExtractorFactory.setThreadPrefersEventExtractors(true); try { //POITextExtractor extractor = ExtractorFactory.CreateExtractor(HSSFTestDataSamples.GetSampleFile("poc-shared-strings.xlsx")); //try //{ // Assert.IsNotNull(extractor); // try // { // string tmp = extractor.Text; // } // catch (InvalidOperationException e) // { // // expected due to shared strings expansion // } //} //finally //{ // extractor.Close(); //} } catch (XmlException e) { assertEntityLimitReached(e); } finally { //ExtractorFactory.setThreadPrefersEventExtractors(before); } } [Test, Ignore("SlideShow not implemented")] public void UnparseableCentralDirectory() { FileInfo f = OpenXml4NetTestDataSamples.GetSampleFile("at.pzp.www_uploads_media_PP_Scheinecker-jdk6error.pptx"); //SlideShow<?,?> ppt = SlideShowFactory.create(f, null, true); //ppt.close(); } [Test] public void TestClosingStreamOnException() { Stream is1 = OpenXml4NetTestDataSamples.OpenSampleStream("dcterms_bug_56479.zip"); FileInfo tmp = TempFile.CreateTempFile("poi-test-truncated-zip", ""); // create a corrupted zip file by truncating a valid zip file to the first 100 bytes Stream os = new FileStream(tmp.FullName, FileMode.OpenOrCreate, FileAccess.ReadWrite); for (int i = 0; i < 100; i++) { os.WriteByte((byte)is1.ReadByte()); } os.Flush(); os.Close(); is1.Close(); // feed the corrupted zip file to OPCPackage try { OPCPackage.Open(tmp, PackageAccess.READ); } catch (Exception) { // expected: the zip file is invalid // this test does not care if open() throws an exception or not. } tmp.Delete(); tmp.Refresh(); // If the stream is not closed on exception, it will keep a file descriptor to tmp, // and requests to the OS to delete the file will fail. Assert.IsFalse(tmp.Exists, "Can't delete tmp file"); } /** * If ZipPackage is passed an invalid file, a call to close * (eg from the OPCPackage open method) should tidy up the * stream / file the broken file is being read from. * See bug #60128 for more */ [Test] [Ignore("Need ZipSecureFile")] public void TestTidyStreamOnInvalidFile() { // Spreadsheet has a good mix of alternate file types POIDataSamples files = POIDataSamples.GetSpreadSheetInstance(); FileInfo[] notValidF = new FileInfo[] { files.GetFileInfo("SampleSS.ods"), files.GetFileInfo("SampleSS.txt") }; Stream[] notValidS = new Stream[] { files.OpenResourceAsStream("SampleSS.ods"), files.OpenResourceAsStream("SampleSS.txt") }; foreach (FileInfo notValid in notValidF) { ZipPackage pkg = new ZipPackage(notValid, PackageAccess.READ); Assert.IsNotNull(pkg.ZipArchive); Assert.IsFalse(pkg.ZipArchive.IsClosed); try { pkg.GetParts(); Assert.Fail("Shouldn't work"); } catch (ODFNotOfficeXmlFileException e) { } catch (NotOfficeXmlFileException ne) { } pkg.Close(); Assert.IsNotNull(pkg.ZipArchive); Assert.IsTrue(pkg.ZipArchive.IsClosed); } foreach (InputStream notValid in notValidS) { ZipPackage pkg = new ZipPackage(notValid, PackageAccess.READ); Assert.IsNotNull(pkg.ZipArchive); Assert.IsFalse(pkg.ZipArchive.IsClosed); try { pkg.GetParts(); Assert.Fail("Shouldn't work"); } catch (ODFNotOfficeXmlFileException e) { } catch (NotOfficeXmlFileException ne) { } pkg.Close(); Assert.IsNotNull(pkg.ZipArchive); Assert.IsTrue(pkg.ZipArchive.IsClosed); } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenMetaverse.Imaging; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Reflection; namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "DynamicTextureModule")] public class DynamicTextureModule : ISharedRegionModule, IDynamicTextureManager { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private const int ALL_SIDES = -1; public const int DISP_EXPIRE = 1; public const int DISP_TEMP = 2; /// <summary> /// If true then where possible dynamic textures are reused. /// </summary> public bool ReuseTextures { get; set; } /// <summary> /// If false, then textures which have a low data size are not reused when ReuseTextures = true. /// </summary> /// <remarks> /// LL viewers 3.3.4 and before appear to not fully render textures pulled from the viewer cache if those /// textures have a relatively high pixel surface but a small data size. Typically, this appears to happen /// if the data size is smaller than the viewer's discard level 2 size estimate. So if this is setting is /// false, textures smaller than the calculation in IsSizeReuseable are always regenerated rather than reused /// to work around this problem.</remarks> public bool ReuseLowDataTextures { get; set; } private ThreadedClasses.RwLockedDictionary<UUID, Scene> RegisteredScenes = new ThreadedClasses.RwLockedDictionary<UUID, Scene>(); private ThreadedClasses.RwLockedDictionary<string, IDynamicTextureRender> RenderPlugins = new ThreadedClasses.RwLockedDictionary<string, IDynamicTextureRender>(); private ThreadedClasses.RwLockedDictionary<UUID, DynamicTextureUpdater> Updaters = new ThreadedClasses.RwLockedDictionary<UUID, DynamicTextureUpdater>(); /// <summary> /// Record dynamic textures that we can reuse for a given data and parameter combination rather than /// regenerate. /// </summary> /// <remarks> /// Key is string.Format("{0}{1}", data /// </remarks> private ThreadedClasses.ExpiringCache<string, UUID> m_reuseableDynamicTextures; /// <summary> /// This constructor is only here because of the Unit Tests... /// Don't use it. /// </summary> public DynamicTextureModule() { m_reuseableDynamicTextures = new ThreadedClasses.ExpiringCache<string, UUID>(new TimeSpan(24, 0, 0)); } #region IDynamicTextureManager Members public void RegisterRender(string handleType, IDynamicTextureRender render) { try { RenderPlugins.Add(handleType, render); } catch { } } /// <summary> /// Called by code which actually renders the dynamic texture to supply texture data. /// </summary> /// <param name="updaterId"></param> /// <param name="texture"></param> public void ReturnData(UUID updaterId, IDynamicTexture texture) { DynamicTextureUpdater updater = null; if(Updaters.TryGetValue(updaterId, out updater)) { Scene scene; if (RegisteredScenes.TryGetValue(updater.SimUUID, out scene)) { UUID newTextureID = updater.DataReceived(texture.Data, scene); if (ReuseTextures && !updater.BlendWithOldTexture && texture.IsReuseable && (ReuseLowDataTextures || IsDataSizeReuseable(texture))) { m_reuseableDynamicTextures[GenerateReusableTextureKey(texture.InputCommands, texture.InputParams)] = newTextureID; } } } if (updater.UpdateTimer == 0) { Updaters.Remove(updater.UpdaterID); } } /// <summary> /// Determines whether the texture is reuseable based on its data size. /// </summary> /// <remarks> /// This is a workaround for a viewer bug where very small data size textures relative to their pixel size /// are not redisplayed properly when pulled from cache. The calculation here is based on the typical discard /// level of 2, a 'rate' of 0.125 and 4 components (which makes for a factor of 0.5). /// </remarks> /// <returns></returns> private bool IsDataSizeReuseable(IDynamicTexture texture) { // Console.WriteLine("{0} {1}", texture.Size.Width, texture.Size.Height); int discardLevel2DataThreshold = (int)Math.Ceiling((texture.Size.Width >> 2) * (texture.Size.Height >> 2) * 0.5); // m_log.DebugFormat( // "[DYNAMIC TEXTURE MODULE]: Discard level 2 threshold {0}, texture data length {1}", // discardLevel2DataThreshold, texture.Data.Length); return discardLevel2DataThreshold < texture.Data.Length; } public UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url, string extraParams, int updateTimer) { return AddDynamicTextureURL(simID, primID, contentType, url, extraParams, updateTimer, false, 255); } public UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url, string extraParams, int updateTimer, bool SetBlending, byte AlphaValue) { return AddDynamicTextureURL(simID, primID, contentType, url, extraParams, updateTimer, SetBlending, (int)(DISP_TEMP|DISP_EXPIRE), AlphaValue, ALL_SIDES); } public UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url, string extraParams, int updateTimer, bool SetBlending, int disp, byte AlphaValue, int face) { if (RenderPlugins.ContainsKey(contentType)) { DynamicTextureUpdater updater = new DynamicTextureUpdater(); updater.SimUUID = simID; updater.PrimID = primID; updater.ContentType = contentType; updater.Url = url; updater.UpdateTimer = updateTimer; updater.UpdaterID = UUID.Random(); updater.Params = extraParams; updater.BlendWithOldTexture = SetBlending; updater.FrontAlpha = AlphaValue; updater.Face = face; updater.Disp = disp; try { Updaters.Add(updater.UpdaterID, updater); } catch { } RenderPlugins[contentType].AsyncConvertUrl(updater.UpdaterID, url, extraParams); return updater.UpdaterID; } return UUID.Zero; } public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data, string extraParams, int updateTimer) { return AddDynamicTextureData(simID, primID, contentType, data, extraParams, updateTimer, false, 255); } public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data, string extraParams, int updateTimer, bool SetBlending, byte AlphaValue) { return AddDynamicTextureData(simID, primID, contentType, data, extraParams, updateTimer, SetBlending, (int) (DISP_TEMP|DISP_EXPIRE), AlphaValue, ALL_SIDES); } public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data, string extraParams, int updateTimer, bool SetBlending, int disp, byte AlphaValue, int face) { if (!RenderPlugins.ContainsKey(contentType)) return UUID.Zero; Scene scene; RegisteredScenes.TryGetValue(simID, out scene); if (scene == null) return UUID.Zero; SceneObjectPart part = scene.GetSceneObjectPart(primID); if (part == null) return UUID.Zero; // If we want to reuse dynamic textures then we have to ignore any request from the caller to expire // them. if (ReuseTextures) disp = disp & ~DISP_EXPIRE; DynamicTextureUpdater updater = new DynamicTextureUpdater(); updater.SimUUID = simID; updater.PrimID = primID; updater.ContentType = contentType; updater.BodyData = data; updater.UpdateTimer = updateTimer; updater.UpdaterID = UUID.Random(); updater.Params = extraParams; updater.BlendWithOldTexture = SetBlending; updater.FrontAlpha = AlphaValue; updater.Face = face; updater.Url = "Local image"; updater.Disp = disp; UUID objReusableTextureUUID = UUID.Zero; if (ReuseTextures && !updater.BlendWithOldTexture) { string reuseableTextureKey = GenerateReusableTextureKey(data, extraParams); if (m_reuseableDynamicTextures.TryGetValue(reuseableTextureKey, out objReusableTextureUUID)) { // If something else has removed this temporary asset from the cache, detect and invalidate // our cached uuid. if (scene.AssetService.GetMetadata(objReusableTextureUUID.ToString()) == null) { m_reuseableDynamicTextures.Remove(reuseableTextureKey); objReusableTextureUUID = UUID.Zero; } } } // We cannot reuse a dynamic texture if the data is going to be blended with something already there. if (objReusableTextureUUID == UUID.Zero) { Updaters.AddIfNotExists(updater.UpdaterID, delegate() { return updater; }); // m_log.DebugFormat( // "[DYNAMIC TEXTURE MODULE]: Requesting generation of new dynamic texture for {0} in {1}", // part.Name, part.ParentGroup.Scene.Name); RenderPlugins[contentType].AsyncConvertData(updater.UpdaterID, data, extraParams); } else { // m_log.DebugFormat( // "[DYNAMIC TEXTURE MODULE]: Reusing cached texture {0} for {1} in {2}", // objReusableTextureUUID, part.Name, part.ParentGroup.Scene.Name); // No need to add to updaters as the texture is always the same. Not that this functionality // apppears to be implemented anyway. updater.UpdatePart(part, (UUID)objReusableTextureUUID); } return updater.UpdaterID; } private string GenerateReusableTextureKey(string data, string extraParams) { return string.Format("{0}{1}", data, extraParams); } public void GetDrawStringSize(string contentType, string text, string fontName, int fontSize, out double xSize, out double ySize) { xSize = 0; ySize = 0; if (RenderPlugins.ContainsKey(contentType)) { RenderPlugins[contentType].GetDrawStringSize(text, fontName, fontSize, out xSize, out ySize); } } #endregion #region ISharedRegionModule Members public void Initialise(IConfigSource config) { IConfig texturesConfig = config.Configs["Textures"]; if (texturesConfig != null) { ReuseTextures = texturesConfig.GetBoolean("ReuseDynamicTextures", false); ReuseLowDataTextures = texturesConfig.GetBoolean("ReuseDynamicLowDataTextures", false); if (ReuseTextures) { m_reuseableDynamicTextures = new ThreadedClasses.ExpiringCache<string, UUID>(new TimeSpan(24, 0, 0)); } } } public void PostInitialise() { } public void AddRegion(Scene scene) { RegisteredScenes.Add(scene.RegionInfo.RegionID, scene); scene.RegisterModuleInterface<IDynamicTextureManager>(this); } public void RegionLoaded(Scene scene) { } public void RemoveRegion(Scene scene) { RegisteredScenes.Remove(scene.RegionInfo.RegionID); } public void Close() { } public string Name { get { return "DynamicTextureModule"; } } public Type ReplaceableInterface { get { return null; } } #endregion #region Nested type: DynamicTextureUpdater public class DynamicTextureUpdater { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public bool BlendWithOldTexture = false; public string BodyData; public string ContentType; public byte FrontAlpha = 255; public string Params; public UUID PrimID; public bool SetNewFrontAlpha = false; public UUID SimUUID; public UUID UpdaterID; public int UpdateTimer; public int Face; public int Disp; public string Url; public DynamicTextureUpdater() { UpdateTimer = 0; BodyData = null; } /// <summary> /// Update the given part with the new texture. /// </summary> /// <returns> /// The old texture UUID. /// </returns> public UUID UpdatePart(SceneObjectPart part, UUID textureID) { UUID oldID; lock (part) { // mostly keep the values from before Primitive.TextureEntry tmptex = part.Shape.Textures; // FIXME: Need to return the appropriate ID if only a single face is replaced. oldID = tmptex.DefaultTexture.TextureID; if (Face == ALL_SIDES) { oldID = tmptex.DefaultTexture.TextureID; tmptex.DefaultTexture.TextureID = textureID; } else { try { Primitive.TextureEntryFace texface = tmptex.CreateFace((uint)Face); texface.TextureID = textureID; tmptex.FaceTextures[Face] = texface; } catch (Exception) { tmptex.DefaultTexture.TextureID = textureID; } } // I'm pretty sure we always want to force this to true // I'm pretty sure noone whats to set fullbright true if it wasn't true before. // tmptex.DefaultTexture.Fullbright = true; part.UpdateTextureEntry(tmptex.GetBytes()); } return oldID; } /// <summary> /// Called once new texture data has been received for this updater. /// </summary> /// <param name="data"></param> /// <param name="scene"></param> /// <param name="isReuseable">True if the data given is reuseable.</param> /// <returns>The asset UUID given to the incoming data.</returns> public UUID DataReceived(byte[] data, Scene scene) { SceneObjectPart part = scene.GetSceneObjectPart(PrimID); if (part == null || data == null || data.Length <= 1) { string msg = String.Format("DynamicTextureModule: Error preparing image using URL {0}", Url); scene.SimChat(Utils.StringToBytes(msg), ChatTypeEnum.Say, 0, part.ParentGroup.RootPart.AbsolutePosition, part.Name, part.UUID, false); return UUID.Zero; } byte[] assetData = null; AssetBase oldAsset = null; if (BlendWithOldTexture) { Primitive.TextureEntryFace defaultFace = part.Shape.Textures.DefaultTexture; if (defaultFace != null) { oldAsset = scene.AssetService.Get(defaultFace.TextureID.ToString()); if (oldAsset != null) assetData = BlendTextures(data, oldAsset.Data, SetNewFrontAlpha, FrontAlpha); } } if (assetData == null) { assetData = new byte[data.Length]; Array.Copy(data, assetData, data.Length); } // Create a new asset for user AssetBase asset = new AssetBase( UUID.Random(), "DynamicImage" + Util.RandomClass.Next(1, 10000), (sbyte)AssetType.Texture, scene.RegionInfo.RegionID.ToString()); asset.Data = assetData; asset.Description = String.Format("URL image : {0}", Url); if (asset.Description.Length > 128) asset.Description = asset.Description.Substring(0, 128); asset.Local = true; // dynamic images aren't saved in the assets server asset.Temporary = ((Disp & DISP_TEMP) != 0); scene.AssetService.Store(asset); // this will only save the asset in the local asset cache IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface<IJ2KDecoder>(); if (cacheLayerDecode != null) { if (!cacheLayerDecode.Decode(asset.FullID, asset.Data)) m_log.WarnFormat( "[DYNAMIC TEXTURE MODULE]: Decoding of dynamically generated asset {0} for {1} in {2} failed", asset.ID, part.Name, part.ParentGroup.Scene.Name); } UUID oldID = UpdatePart(part, asset.FullID); if (oldID != UUID.Zero && ((Disp & DISP_EXPIRE) != 0)) { if (oldAsset == null) oldAsset = scene.AssetService.Get(oldID.ToString()); if (oldAsset != null) { if (oldAsset.Temporary) { scene.AssetService.Delete(oldID.ToString()); } } } return asset.FullID; } private byte[] BlendTextures(byte[] frontImage, byte[] backImage, bool setNewAlpha, byte newAlpha) { ManagedImage managedImage; Image image; if (OpenJPEG.DecodeToImage(frontImage, out managedImage, out image)) { Bitmap image1 = new Bitmap(image); if (OpenJPEG.DecodeToImage(backImage, out managedImage, out image)) { Bitmap image2 = new Bitmap(image); if (setNewAlpha) SetAlpha(ref image1, newAlpha); Bitmap joint = MergeBitMaps(image1, image2); byte[] result = new byte[0]; try { result = OpenJPEG.EncodeFromImage(joint, true); } catch (Exception e) { m_log.ErrorFormat( "[DYNAMICTEXTUREMODULE]: OpenJpeg Encode Failed. Exception {0}{1}", e.Message, e.StackTrace); } return result; } } return null; } public Bitmap MergeBitMaps(Bitmap front, Bitmap back) { Bitmap joint; Graphics jG; joint = new Bitmap(back.Width, back.Height, PixelFormat.Format32bppArgb); jG = Graphics.FromImage(joint); jG.DrawImage(back, 0, 0, back.Width, back.Height); jG.DrawImage(front, 0, 0, back.Width, back.Height); return joint; } private void SetAlpha(ref Bitmap b, byte alpha) { for (int w = 0; w < b.Width; w++) { for (int h = 0; h < b.Height; h++) { b.SetPixel(w, h, Color.FromArgb(alpha, b.GetPixel(w, h))); } } } } #endregion } }
using Microsoft.Research.Joins; using Microsoft.Research.Joins.Patterns; using Microsoft.Research.Joins.ArgCounts; using System; using System.Threading; namespace Microsoft.Research.Joins { public static class ChordExtensions { /// <summary> /// Completes this join pattern with body <paramref name="continuation"/> and registers it with the current <c>Join</c> instance. /// </summary> /// <param name="chord"> the join pattern to complete.</param> /// <param name="continuation"> the code to execute when the join pattern is enabled.</param> /// <exception cref="JoinException"> thrown if <paramref name="continuation"/> is null, the pattern repeats an /// asynchronous channel, /// an (a)synchronous channel is foreign to this pattern's join instance, the join pattern is redundant, /// or the join pattern is empty. /// </exception> public static void Do(this ActionChord<Z, Unit> chord, Action continuation) { if (continuation == null) JoinException.NullContinuationException(); var copy = new Chord<Unit,Unit>(chord.mJoin, chord.mPattern, continuation, delegate (Unit a) { continuation(); return Unit.Null; } ); chord.mJoin.Register(copy); } /// <summary> /// Completes this join pattern with body <paramref name="continuation"/> and registers it with the current <c>Join</c> instance. /// </summary> /// <param name="chord"> the join pattern to complete.</param> /// <param name="continuation"> the code to execute when the join pattern is enabled.</param> /// <exception cref="JoinException"> thrown if <paramref name="continuation"/> is null, the pattern repeats an /// asynchronous channel, /// an (a)synchronous channel is foreign to this pattern's join instance, the join pattern is redundant, /// or the join pattern is empty. /// </exception> public static void Do<P0>(this ActionChord<S<Z>, P0> chord, Action<P0> continuation) { if (continuation == null) JoinException.NullContinuationException(); var copy = new Chord<P0,Unit>(chord.mJoin, chord.mPattern, continuation, delegate (P0 a) { continuation(a); return Unit.Null; } ); chord.mJoin.Register(copy); } /// <summary> /// Completes this join pattern with body <paramref name="continuation"/> and registers it with the current <c>Join</c> instance. /// </summary> /// <param name="chord"> the join pattern to complete.</param> /// <param name="continuation"> the code to execute when the join pattern is enabled.</param> /// <exception cref="JoinException"> thrown if <paramref name="continuation"/> is null, the pattern repeats an /// asynchronous channel, /// an (a)synchronous channel is foreign to this pattern's join instance, the join pattern is redundant, /// or the join pattern is empty. /// </exception> public static void Do<P0, P1>(this ActionChord<S<S<Z>>, Pair<P0, P1>> chord, Action<P0, P1> continuation) { if (continuation == null) JoinException.NullContinuationException(); var copy = new Chord<Pair<P0, P1>,Unit>(chord.mJoin, chord.mPattern, continuation, delegate (Pair<P0, P1> a) { continuation(a.Fst,a.Snd); return Unit.Null; } ); chord.mJoin.Register(copy); } /// <summary> /// Completes this join pattern with body <paramref name="continuation"/> and registers it with the current <c>Join</c> instance. /// </summary> /// <param name="chord"> the join pattern to complete.</param> /// <param name="continuation"> the code to execute when the join pattern is enabled.</param> /// <exception cref="JoinException"> thrown if <paramref name="continuation"/> is null, the pattern repeats an /// asynchronous channel, /// an (a)synchronous channel is foreign to this pattern's join instance, the join pattern is redundant, /// or the join pattern is empty. /// </exception> public static void Do<P0, P1, P2>(this ActionChord<S<S<S<Z>>>, Pair<Pair<P0, P1>, P2>> chord, Action<P0, P1, P2> continuation) { if (continuation == null) JoinException.NullContinuationException(); var copy = new Chord<Pair<Pair<P0, P1>, P2>,Unit>(chord.mJoin, chord.mPattern, continuation, delegate (Pair<Pair<P0, P1>, P2> a) { continuation(a.Fst.Fst,a.Fst.Snd,a.Snd); return Unit.Null; } ); chord.mJoin.Register(copy); } /// <summary> /// Completes this join pattern with body <paramref name="continuation"/> and registers it with the current <c>Join</c> instance. /// </summary> /// <param name="chord"> the join pattern to complete.</param> /// <param name="continuation"> the code to execute when the join pattern is enabled.</param> /// <exception cref="JoinException"> thrown if <paramref name="continuation"/> is null, the pattern repeats an /// asynchronous channel, /// an (a)synchronous channel is foreign to this pattern's join instance, the join pattern is redundant, /// or the join pattern is empty. /// </exception> public static void Do<R>(this FuncChord<Z, Unit,R> chord, Func<R> continuation) { if (continuation == null) JoinException.NullContinuationException(); var copy = new Chord<Unit,R>(chord.mJoin, chord.mPattern, continuation, delegate (Unit a) { return continuation(); } ); chord.mJoin.Register(copy); } /// <summary> /// Completes this join pattern with body <paramref name="continuation"/> and registers it with the current <c>Join</c> instance. /// </summary> /// <param name="chord"> the join pattern to complete.</param> /// <param name="continuation"> the code to execute when the join pattern is enabled.</param> /// <exception cref="JoinException"> thrown if <paramref name="continuation"/> is null, the pattern repeats an /// asynchronous channel, /// an (a)synchronous channel is foreign to this pattern's join instance, the join pattern is redundant, /// or the join pattern is empty. /// </exception> public static void Do<P0, R>(this FuncChord<S<Z>, P0,R> chord, Func<P0, R> continuation) { if (continuation == null) JoinException.NullContinuationException(); var copy = new Chord<P0,R>(chord.mJoin, chord.mPattern, continuation, delegate (P0 a) { return continuation(a); } ); chord.mJoin.Register(copy); } /// <summary> /// Completes this join pattern with body <paramref name="continuation"/> and registers it with the current <c>Join</c> instance. /// </summary> /// <param name="chord"> the join pattern to complete.</param> /// <param name="continuation"> the code to execute when the join pattern is enabled.</param> /// <exception cref="JoinException"> thrown if <paramref name="continuation"/> is null, the pattern repeats an /// asynchronous channel, /// an (a)synchronous channel is foreign to this pattern's join instance, the join pattern is redundant, /// or the join pattern is empty. /// </exception> public static void Do<P0, P1, R>(this FuncChord<S<S<Z>>, Pair<P0, P1>,R> chord, Func<P0, P1, R> continuation) { if (continuation == null) JoinException.NullContinuationException(); var copy = new Chord<Pair<P0, P1>,R>(chord.mJoin, chord.mPattern, continuation, delegate (Pair<P0, P1> a) { return continuation(a.Fst,a.Snd); } ); chord.mJoin.Register(copy); } /// <summary> /// Completes this join pattern with body <paramref name="continuation"/> and registers it with the current <c>Join</c> instance. /// </summary> /// <param name="chord"> the join pattern to complete.</param> /// <param name="continuation"> the code to execute when the join pattern is enabled.</param> /// <exception cref="JoinException"> thrown if <paramref name="continuation"/> is null, the pattern repeats an /// asynchronous channel, /// an (a)synchronous channel is foreign to this pattern's join instance, the join pattern is redundant, /// or the join pattern is empty. /// </exception> public static void Do<P0, P1, P2, R>(this FuncChord<S<S<S<Z>>>, Pair<Pair<P0, P1>, P2>,R> chord, Func<P0, P1, P2, R> continuation) { if (continuation == null) JoinException.NullContinuationException(); var copy = new Chord<Pair<Pair<P0, P1>, P2>,R>(chord.mJoin, chord.mPattern, continuation, delegate (Pair<Pair<P0, P1>, P2> a) { return continuation(a.Fst.Fst,a.Fst.Snd,a.Snd); } ); chord.mJoin.Register(copy); } } // class ChordExtensions } // namespace Microsoft.Research.Joins #if false #define CONTINUATIONATTRIBUTES using Microsoft.Research.Joins; using Microsoft.Research.Joins.BitMasks; using Microsoft.Research.Joins.Patterns; using Microsoft.Research.Joins.ArgCounts; using System; using System.Threading; namespace Microsoft.Research.Joins { public static class ChordExtensions { /// <summary> /// Completes this join pattern with body <paramref name="continuation"/> and registers it with the current <c>Join</c> instance. /// </summary> /// <param name="chord"> the join pattern to complete.</param> /// <param name="continuation"> the code to execute when the join pattern is enabled.</param> /// <exception cref="JoinException"> thrown if <paramref name="continuation"/> is null, the pattern repeats an /// asynchronous channel, /// an (a)synchronous channel is foreign to this pattern's join instance, the join pattern is redundant, /// or the join pattern is empty. /// </exception> public static void Do(this ActionChord<Z,Unit> chord, Action continuation) { if (continuation == null) JoinException.NullContinuationException(); chord.mJoin.Register(chord, continuation); } /// <summary> /// Completes this join pattern with body <paramref name="continuation"/> and registers it with the current <c>Join</c> instance. /// </summary> /// <param name="chord"> the join pattern to complete.</param> /// <param name="continuation"> the code to execute when the join pattern is enabled.</param> /// <exception cref="JoinException"> thrown if <paramref name="continuation"/> is null, the pattern repeats an /// asynchronous channel, /// an (a)synchronous channel is foreign to this pattern's join instance, the join pattern is redundant, /// or the join pattern is empty. /// </exception> public static void Do<P0>(this ActionChord<S<Z>, P0> chord, Action<P0> continuation) { if (continuation == null) JoinException.NullContinuationException(); chord.mJoin.Register(chord, continuation); } /// <summary> /// Completes this join pattern with body <paramref name="continuation"/> and registers it with the current <c>Join</c> instance. /// </summary> /// <param name="chord"> the join pattern to complete.</param> /// <param name="continuation"> the code to execute when the join pattern is enabled.</param> /// <exception cref="JoinException"> thrown if <paramref name="continuation"/> is null, the pattern repeats an /// asynchronous channel, /// an (a)synchronous channel is foreign to this pattern's join instance, the join pattern is redundant, /// or the join pattern is empty. /// </exception> public static void Do<P0, P1>(this ActionChord<S<S<Z>>, Pair<P0, P1>> chord, Action<P0, P1> continuation) { if (continuation == null) JoinException.NullContinuationException(); chord.mJoin.Register(chord, continuation); } /// <summary> /// Completes this join pattern with body <paramref name="continuation"/> and registers it with the current <c>Join</c> instance. /// </summary> /// <param name="chord"> the join pattern to complete.</param> /// <param name="continuation"> the code to execute when the join pattern is enabled.</param> /// <exception cref="JoinException"> thrown if <paramref name="continuation"/> is null, the pattern repeats an /// asynchronous channel, /// an (a)synchronous channel is foreign to this pattern's join instance, the join pattern is redundant, /// or the join pattern is empty. /// </exception> public static void Do<P0, P1, P2>(this ActionChord<S<S<S<Z>>>, Pair<Pair<P0, P1>, P2>> chord, Action<P0, P1, P2> continuation) { if (continuation == null) JoinException.NullContinuationException(); chord.mJoin.Register(chord, continuation); } /// <summary> /// Completes this join pattern with body <paramref name="continuation"/> and registers it with the current <c>Join</c> instance. /// </summary> /// <param name="chord"> the join pattern to complete.</param> /// <param name="continuation"> the code to execute when the join pattern is enabled.</param> /// <exception cref="JoinException"> thrown if <paramref name="continuation"/> is null, the pattern repeats an /// asynchronous channel, /// an (a)synchronous channel is foreign to this pattern's join instance, the join pattern is redundant, /// or the join pattern is empty. /// </exception> public static void Do<P0, P1, P2, P3>(this ActionChord<S<S<S<S<Z>>>>, Pair<Pair<Pair<P0, P1>, P2>, P3>> chord, Action<P0, P1, P2, P3> continuation) { if (continuation == null) JoinException.NullContinuationException(); chord.mJoin.Register(chord, continuation); } /// <summary> /// Completes this join pattern with body <paramref name="continuation"/> and registers it with the current <c>Join</c> instance. /// </summary> /// <param name="chord"> the join pattern to complete.</param> /// <param name="continuation"> the code to execute when the join pattern is enabled.</param> /// <exception cref="JoinException"> thrown if <paramref name="continuation"/> is null, the pattern repeats an /// asynchronous channel, /// an (a)synchronous channel is foreign to this pattern's join instance, the join pattern is redundant, /// or the join pattern is empty. /// </exception> public static void Do<P0, P1, P2, P3, P4>(this ActionChord<S<S<S<S<S<Z>>>>>, Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>> chord, Action<P0, P1, P2, P3, P4> continuation) { if (continuation == null) JoinException.NullContinuationException(); chord.mJoin.Register(chord, continuation); } /// <summary> /// Completes this join pattern with body <paramref name="continuation"/> and registers it with the current <c>Join</c> instance. /// </summary> /// <param name="chord"> the join pattern to complete.</param> /// <param name="continuation"> the code to execute when the join pattern is enabled.</param> /// <exception cref="JoinException"> thrown if <paramref name="continuation"/> is null, the pattern repeats an /// asynchronous channel, /// an (a)synchronous channel is foreign to this pattern's join instance, the join pattern is redundant, /// or the join pattern is empty. /// </exception> public static void Do<P0, P1, P2, P3, P4, P5>(this ActionChord<S<S<S<S<S<S<Z>>>>>>, Pair<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, P5>> chord, Action<P0, P1, P2, P3, P4, P5> continuation) { if (continuation == null) JoinException.NullContinuationException(); chord.mJoin.Register(chord, continuation); } /// <summary> /// Completes this join pattern with body <paramref name="continuation"/> and registers it with the current <c>Join</c> instance. /// </summary> /// <param name="chord"> the join pattern to complete.</param> /// <param name="continuation"> the code to execute when the join pattern is enabled.</param> /// <exception cref="JoinException"> thrown if <paramref name="continuation"/> is null, the pattern repeats an /// asynchronous channel, /// an (a)synchronous channel is foreign to this pattern's join instance, the join pattern is redundant, /// or the join pattern is empty. /// </exception> public static void Do<P0, P1, P2, P3, P4, P5, P6>(this ActionChord<S<S<S<S<S<S<S<Z>>>>>>>, Pair<Pair<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, P5>, P6>> chord, Action<P0, P1, P2, P3, P4, P5, P6> continuation) { if (continuation == null) JoinException.NullContinuationException(); chord.mJoin.Register(chord, continuation); } /// <summary> /// Completes this join pattern with body <paramref name="continuation"/> and registers it with the current <c>Join</c> instance. /// </summary> /// <param name="chord"> the join pattern to complete.</param> /// <param name="continuation"> the code to execute when the join pattern is enabled.</param> /// <exception cref="JoinException"> thrown if <paramref name="continuation"/> is null, the pattern repeats an /// asynchronous channel, /// an (a)synchronous channel is foreign to this pattern's join instance, the join pattern is redundant, /// or the join pattern is empty. /// </exception> public static void Do<R>(this FuncChord<Z,Unit,R> chord, Func<R> continuation) { if (continuation == null) JoinException.NullContinuationException(); chord.mJoin.Register(chord, continuation); } /// <summary> /// Completes this join pattern with body <paramref name="continuation"/> and registers it with the current <c>Join</c> instance. /// </summary> /// <param name="chord"> the join pattern to complete.</param> /// <param name="continuation"> the code to execute when the join pattern is enabled.</param> /// <exception cref="JoinException"> thrown if <paramref name="continuation"/> is null, the pattern repeats an /// asynchronous channel, /// an (a)synchronous channel is foreign to this pattern's join instance, the join pattern is redundant, /// or the join pattern is empty. /// </exception> public static void Do<P0, R>(this FuncChord<S<Z>, P0,R> chord, Func<P0, R> continuation) { if (continuation == null) JoinException.NullContinuationException(); chord.mJoin.Register(chord, continuation); } /// <summary> /// Completes this join pattern with body <paramref name="continuation"/> and registers it with the current <c>Join</c> instance. /// </summary> /// <param name="chord"> the join pattern to complete.</param> /// <param name="continuation"> the code to execute when the join pattern is enabled.</param> /// <exception cref="JoinException"> thrown if <paramref name="continuation"/> is null, the pattern repeats an /// asynchronous channel, /// an (a)synchronous channel is foreign to this pattern's join instance, the join pattern is redundant, /// or the join pattern is empty. /// </exception> public static void Do<P0, P1, R>(this FuncChord<S<S<Z>>, Pair<P0, P1>,R> chord, Func<P0, P1, R> continuation) { if (continuation == null) JoinException.NullContinuationException(); chord.mJoin.Register(chord, continuation); } /// <summary> /// Completes this join pattern with body <paramref name="continuation"/> and registers it with the current <c>Join</c> instance. /// </summary> /// <param name="chord"> the join pattern to complete.</param> /// <param name="continuation"> the code to execute when the join pattern is enabled.</param> /// <exception cref="JoinException"> thrown if <paramref name="continuation"/> is null, the pattern repeats an /// asynchronous channel, /// an (a)synchronous channel is foreign to this pattern's join instance, the join pattern is redundant, /// or the join pattern is empty. /// </exception> public static void Do<P0, P1, P2, R>(this FuncChord<S<S<S<Z>>>, Pair<Pair<P0, P1>, P2>,R> chord, Func<P0, P1, P2, R> continuation) { if (continuation == null) JoinException.NullContinuationException(); chord.mJoin.Register(chord, continuation); } /// <summary> /// Completes this join pattern with body <paramref name="continuation"/> and registers it with the current <c>Join</c> instance. /// </summary> /// <param name="chord"> the join pattern to complete.</param> /// <param name="continuation"> the code to execute when the join pattern is enabled.</param> /// <exception cref="JoinException"> thrown if <paramref name="continuation"/> is null, the pattern repeats an /// asynchronous channel, /// an (a)synchronous channel is foreign to this pattern's join instance, the join pattern is redundant, /// or the join pattern is empty. /// </exception> public static void Do<P0, P1, P2, P3, R>(this FuncChord<S<S<S<S<Z>>>>, Pair<Pair<Pair<P0, P1>, P2>, P3>,R> chord, Func<P0, P1, P2, P3, R> continuation) { if (continuation == null) JoinException.NullContinuationException(); chord.mJoin.Register(chord, continuation); } /// <summary> /// Completes this join pattern with body <paramref name="continuation"/> and registers it with the current <c>Join</c> instance. /// </summary> /// <param name="chord"> the join pattern to complete.</param> /// <param name="continuation"> the code to execute when the join pattern is enabled.</param> /// <exception cref="JoinException"> thrown if <paramref name="continuation"/> is null, the pattern repeats an /// asynchronous channel, /// an (a)synchronous channel is foreign to this pattern's join instance, the join pattern is redundant, /// or the join pattern is empty. /// </exception> public static void Do<P0, P1, P2, P3, P4, R>(this FuncChord<S<S<S<S<S<Z>>>>>, Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>,R> chord, Func<P0, P1, P2, P3, P4, R> continuation) { if (continuation == null) JoinException.NullContinuationException(); chord.mJoin.Register(chord, continuation); } /// <summary> /// Completes this join pattern with body <paramref name="continuation"/> and registers it with the current <c>Join</c> instance. /// </summary> /// <param name="chord"> the join pattern to complete.</param> /// <param name="continuation"> the code to execute when the join pattern is enabled.</param> /// <exception cref="JoinException"> thrown if <paramref name="continuation"/> is null, the pattern repeats an /// asynchronous channel, /// an (a)synchronous channel is foreign to this pattern's join instance, the join pattern is redundant, /// or the join pattern is empty. /// </exception> public static void Do<P0, P1, P2, P3, P4, P5, R>(this FuncChord<S<S<S<S<S<S<Z>>>>>>, Pair<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, P5>,R> chord, Func<P0, P1, P2, P3, P4, P5, R> continuation) { if (continuation == null) JoinException.NullContinuationException(); chord.mJoin.Register(chord, continuation); } /// <summary> /// Completes this join pattern with body <paramref name="continuation"/> and registers it with the current <c>Join</c> instance. /// </summary> /// <param name="chord"> the join pattern to complete.</param> /// <param name="continuation"> the code to execute when the join pattern is enabled.</param> /// <exception cref="JoinException"> thrown if <paramref name="continuation"/> is null, the pattern repeats an /// asynchronous channel, /// an (a)synchronous channel is foreign to this pattern's join instance, the join pattern is redundant, /// or the join pattern is empty. /// </exception> public static void Do<P0, P1, P2, P3, P4, P5, P6, R>(this FuncChord<S<S<S<S<S<S<S<Z>>>>>>>, Pair<Pair<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, P5>, P6>,R> chord, Func<P0, P1, P2, P3, P4, P5, P6, R> continuation) { if (continuation == null) JoinException.NullContinuationException(); chord.mJoin.Register(chord, continuation); } } // class ChordExtensions public abstract partial class Join { internal virtual void Register(ActionChord<Z,Unit> chord, Action continuation) { var copy = new Chord<Unit, Unit>(chord.mJoin, chord.mPattern); copy.mContinuation = delegate (Unit a) { continuation(); return Unit.Null; }; copy.SetContinuationAttribute(continuation); Register(copy); } internal virtual void Register<P0>(ActionChord<S<Z>, P0> chord, Action<P0> continuation) { var copy = new Chord<P0, Unit>(chord.mJoin, chord.mPattern); copy.mContinuation = delegate (P0 a) { continuation(a); return Unit.Null; }; copy.SetContinuationAttribute(continuation); Register(copy); } internal virtual void Register<P0, P1>(ActionChord<S<S<Z>>, Pair<P0, P1>> chord, Action<P0, P1> continuation) { var copy = new Chord<Pair<P0, P1>, Unit>(chord.mJoin, chord.mPattern); copy.mContinuation = delegate (Pair<P0, P1> a) { continuation(a.Fst,a.Snd); return Unit.Null; }; copy.SetContinuationAttribute(continuation); Register(copy); } internal virtual void Register<P0, P1, P2>(ActionChord<S<S<S<Z>>>, Pair<Pair<P0, P1>, P2>> chord, Action<P0, P1, P2> continuation) { var copy = new Chord<Pair<Pair<P0, P1>, P2>, Unit>(chord.mJoin, chord.mPattern); copy.mContinuation = delegate (Pair<Pair<P0, P1>, P2> a) { continuation(a.Fst.Fst,a.Fst.Snd,a.Snd); return Unit.Null; }; copy.SetContinuationAttribute(continuation); Register(copy); } internal virtual void Register<P0, P1, P2, P3>(ActionChord<S<S<S<S<Z>>>>, Pair<Pair<Pair<P0, P1>, P2>, P3>> chord, Action<P0, P1, P2, P3> continuation) { var copy = new Chord<Pair<Pair<Pair<P0, P1>, P2>, P3>, Unit>(chord.mJoin, chord.mPattern); copy.mContinuation = delegate (Pair<Pair<Pair<P0, P1>, P2>, P3> a) { continuation(a.Fst.Fst.Fst,a.Fst.Fst.Snd,a.Fst.Snd,a.Snd); return Unit.Null; }; copy.SetContinuationAttribute(continuation); Register(copy); } internal virtual void Register<P0, P1, P2, P3, P4>(ActionChord<S<S<S<S<S<Z>>>>>, Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>> chord, Action<P0, P1, P2, P3, P4> continuation) { var copy = new Chord<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, Unit>(chord.mJoin, chord.mPattern); copy.mContinuation = delegate (Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4> a) { continuation(a.Fst.Fst.Fst.Fst,a.Fst.Fst.Fst.Snd,a.Fst.Fst.Snd,a.Fst.Snd,a.Snd); return Unit.Null; }; copy.SetContinuationAttribute(continuation); Register(copy); } internal virtual void Register<P0, P1, P2, P3, P4, P5>(ActionChord<S<S<S<S<S<S<Z>>>>>>, Pair<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, P5>> chord, Action<P0, P1, P2, P3, P4, P5> continuation) { var copy = new Chord<Pair<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, P5>, Unit>(chord.mJoin, chord.mPattern); copy.mContinuation = delegate (Pair<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, P5> a) { continuation(a.Fst.Fst.Fst.Fst.Fst,a.Fst.Fst.Fst.Fst.Snd,a.Fst.Fst.Fst.Snd,a.Fst.Fst.Snd,a.Fst.Snd,a.Snd); return Unit.Null; }; copy.SetContinuationAttribute(continuation); Register(copy); } internal virtual void Register<P0, P1, P2, P3, P4, P5, P6>(ActionChord<S<S<S<S<S<S<S<Z>>>>>>>, Pair<Pair<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, P5>, P6>> chord, Action<P0, P1, P2, P3, P4, P5, P6> continuation) { var copy = new Chord<Pair<Pair<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, P5>, P6>, Unit>(chord.mJoin, chord.mPattern); copy.mContinuation = delegate (Pair<Pair<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, P5>, P6> a) { continuation(a.Fst.Fst.Fst.Fst.Fst.Fst,a.Fst.Fst.Fst.Fst.Fst.Snd,a.Fst.Fst.Fst.Fst.Snd,a.Fst.Fst.Fst.Snd,a.Fst.Fst.Snd,a.Fst.Snd,a.Snd); return Unit.Null; }; copy.SetContinuationAttribute(continuation); Register(copy); } internal virtual void Register<R>(FuncChord<Z,Unit,R> chord, Func<R> continuation) { var copy = new Chord<Unit, R>(chord.mJoin, chord.mPattern); copy.mContinuation = delegate (Unit a) { return continuation(); }; copy.SetContinuationAttribute(continuation); Register(copy); } internal virtual void Register<P0, R>(FuncChord<S<Z>, P0,R> chord, Func<P0, R> continuation) { var copy = new Chord<P0, R>(chord.mJoin, chord.mPattern); copy.mContinuation = delegate (P0 a) { return continuation(a); }; copy.SetContinuationAttribute(continuation); Register(copy); } internal virtual void Register<P0, P1, R>(FuncChord<S<S<Z>>, Pair<P0, P1>,R> chord, Func<P0, P1, R> continuation) { var copy = new Chord<Pair<P0, P1>, R>(chord.mJoin, chord.mPattern); copy.mContinuation = delegate (Pair<P0, P1> a) { return continuation(a.Fst,a.Snd); }; copy.SetContinuationAttribute(continuation); Register(copy); } internal virtual void Register<P0, P1, P2, R>(FuncChord<S<S<S<Z>>>, Pair<Pair<P0, P1>, P2>,R> chord, Func<P0, P1, P2, R> continuation) { var copy = new Chord<Pair<Pair<P0, P1>, P2>, R>(chord.mJoin, chord.mPattern); copy.mContinuation = delegate (Pair<Pair<P0, P1>, P2> a) { return continuation(a.Fst.Fst,a.Fst.Snd,a.Snd); }; copy.SetContinuationAttribute(continuation); Register(copy); } internal virtual void Register<P0, P1, P2, P3, R>(FuncChord<S<S<S<S<Z>>>>, Pair<Pair<Pair<P0, P1>, P2>, P3>,R> chord, Func<P0, P1, P2, P3, R> continuation) { var copy = new Chord<Pair<Pair<Pair<P0, P1>, P2>, P3>, R>(chord.mJoin, chord.mPattern); copy.mContinuation = delegate (Pair<Pair<Pair<P0, P1>, P2>, P3> a) { return continuation(a.Fst.Fst.Fst,a.Fst.Fst.Snd,a.Fst.Snd,a.Snd); }; copy.SetContinuationAttribute(continuation); Register(copy); } internal virtual void Register<P0, P1, P2, P3, P4, R>(FuncChord<S<S<S<S<S<Z>>>>>, Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>,R> chord, Func<P0, P1, P2, P3, P4, R> continuation) { var copy = new Chord<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, R>(chord.mJoin, chord.mPattern); copy.mContinuation = delegate (Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4> a) { return continuation(a.Fst.Fst.Fst.Fst,a.Fst.Fst.Fst.Snd,a.Fst.Fst.Snd,a.Fst.Snd,a.Snd); }; copy.SetContinuationAttribute(continuation); Register(copy); } internal virtual void Register<P0, P1, P2, P3, P4, P5, R>(FuncChord<S<S<S<S<S<S<Z>>>>>>, Pair<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, P5>,R> chord, Func<P0, P1, P2, P3, P4, P5, R> continuation) { var copy = new Chord<Pair<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, P5>, R>(chord.mJoin, chord.mPattern); copy.mContinuation = delegate (Pair<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, P5> a) { return continuation(a.Fst.Fst.Fst.Fst.Fst,a.Fst.Fst.Fst.Fst.Snd,a.Fst.Fst.Fst.Snd,a.Fst.Fst.Snd,a.Fst.Snd,a.Snd); }; copy.SetContinuationAttribute(continuation); Register(copy); } internal virtual void Register<P0, P1, P2, P3, P4, P5, P6, R>(FuncChord<S<S<S<S<S<S<S<Z>>>>>>>, Pair<Pair<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, P5>, P6>,R> chord, Func<P0, P1, P2, P3, P4, P5, P6, R> continuation) { var copy = new Chord<Pair<Pair<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, P5>, P6>, R>(chord.mJoin, chord.mPattern); copy.mContinuation = delegate (Pair<Pair<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, P5>, P6> a) { return continuation(a.Fst.Fst.Fst.Fst.Fst.Fst,a.Fst.Fst.Fst.Fst.Fst.Snd,a.Fst.Fst.Fst.Fst.Snd,a.Fst.Fst.Fst.Snd,a.Fst.Fst.Snd,a.Fst.Snd,a.Snd); }; copy.SetContinuationAttribute(continuation); Register(copy); } } // class Join } // namespace Microsoft.Research.Joins #if false namespace Microsoft.Research.Joins.Paper { internal partial class Join<IntSet,MsgArray> : Join<IntSet> { internal override void Register(ActionChord<Z,Unit> chord, Action continuation) { var copy = new Chord<Unit, Unit>(chord.mJoin, chord.mPattern, chord.mAsyncChans, chord.mSyncChans, chord.mArgChans); copy.mContinuation = delegate(Unit a) { continuation(); return Unit.Null; }; copy.SetContinuationAttribute(continuation); Register(copy); } internal override void Register<P0>(VoidRetChord<O, P0> chord, Action<P0> continuation) { var copy = new Chord<P0, Unit>(chord.mJoin, chord.mPattern, chord.mAsyncChans, chord.mSyncChans, chord.mArgChans); copy.mContinuation = delegate(P0 a) { continuation(a); return Unit.Null; }; copy.SetContinuationAttribute(continuation); Register(copy); } internal override void Register<P0, P1>(VoidRetChord<S<O>, Pair<P0, P1>> chord, Action<P0, P1> continuation) { var copy = new Chord<Pair<P0, P1>, Unit>(chord.mJoin, chord.mPattern, chord.mAsyncChans, chord.mSyncChans, chord.mArgChans); copy.mContinuation = delegate(Pair<P0, P1> a) { continuation(a.Fst, a.Snd); return Unit.Null; }; copy.SetContinuationAttribute(continuation); Register(copy); } internal override void Register<P0, P1, P2>(VoidRetChord<S<S<O>>, Pair<Pair<P0, P1>, P2>> chord, Action<P0, P1, P2> continuation) { var copy = new Chord<Pair<Pair<P0, P1>, P2>, Unit>(chord.mJoin, chord.mPattern, chord.mAsyncChans, chord.mSyncChans, chord.mArgChans); copy.mContinuation = delegate(Pair<Pair<P0, P1>, P2> a) { continuation(a.Fst.Fst, a.Fst.Snd, a.Snd); return Unit.Null; }; copy.SetContinuationAttribute(continuation); Register(copy); } internal override void Register<P0, P1, P2, P3>(VoidRetChord<S<S<S<O>>>, Pair<Pair<Pair<P0, P1>, P2>, P3>> chord, Action<P0, P1, P2, P3> continuation) { var copy = new Chord<Pair<Pair<Pair<P0, P1>, P2>, P3>, Unit>(chord.mJoin, chord.mPattern, chord.mAsyncChans, chord.mSyncChans, chord.mArgChans); copy.mContinuation = delegate(Pair<Pair<Pair<P0, P1>, P2>, P3> a) { continuation(a.Fst.Fst.Fst, a.Fst.Fst.Snd, a.Fst.Snd, a.Snd); return Unit.Null; }; copy.SetContinuationAttribute(continuation); Register(copy); } internal override void Register<P0, P1, P2, P3, P4>(VoidRetChord<S<S<S<S<O>>>>, Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>> chord, Action<P0, P1, P2, P3, P4> continuation) { var copy = new Chord<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, Unit>(chord.mJoin, chord.mPattern, chord.mAsyncChans, chord.mSyncChans, chord.mArgChans); copy.mContinuation = delegate(Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4> a) { continuation(a.Fst.Fst.Fst.Fst, a.Fst.Fst.Fst.Snd, a.Fst.Fst.Snd, a.Fst.Snd, a.Snd); return Unit.Null; }; copy.SetContinuationAttribute(continuation); Register(copy); } internal override void Register<P0, P1, P2, P3, P4, P5>(VoidRetChord<S<S<S<S<S<O>>>>>, Pair<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, P5>> chord, Action<P0, P1, P2, P3, P4, P5> continuation) { var copy = new Chord<Pair<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, P5>, Unit>(chord.mJoin, chord.mPattern, chord.mAsyncChans, chord.mSyncChans, chord.mArgChans); copy.mContinuation = delegate(Pair<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, P5> a) { continuation(a.Fst.Fst.Fst.Fst.Fst, a.Fst.Fst.Fst.Fst.Snd, a.Fst.Fst.Fst.Snd, a.Fst.Fst.Snd, a.Fst.Snd, a.Snd); return Unit.Null; }; copy.SetContinuationAttribute(continuation); Register(copy); } internal override void Register<P0, P1, P2, P3, P4, P5, P6>(VoidRetChord<S<S<S<S<S<S<O>>>>>>, Pair<Pair<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, P5>, P6>> chord, Action<P0, P1, P2, P3, P4, P5, P6> continuation) { var copy = new Chord<Pair<Pair<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, P5>, P6>, Unit>(chord.mJoin, chord.mPattern, chord.mAsyncChans, chord.mSyncChans, chord.mArgChans); copy.mContinuation = delegate(Pair<Pair<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, P5>, P6> a) { continuation(a.Fst.Fst.Fst.Fst.Fst.Fst, a.Fst.Fst.Fst.Fst.Fst.Snd, a.Fst.Fst.Fst.Fst.Snd, a.Fst.Fst.Fst.Snd, a.Fst.Fst.Snd, a.Fst.Snd, a.Snd); return Unit.Null; }; copy.SetContinuationAttribute(continuation); Register(copy); } internal override void Register<R>(FuncChord<Z,Unit,R> chord, Func<R> continuation) { var copy = new Chord<Unit, R>(chord.mJoin, chord.mPattern, chord.mAsyncChans, chord.mSyncChans, chord.mArgChans); copy.mContinuation = delegate(Unit a) { return continuation(); }; copy.SetContinuationAttribute(continuation); Register(copy); } internal override void Register<P0, R>(NonVoidChord<O, P0, R> chord, Func<P0, R> continuation) { var copy = new Chord<P0, R>(chord.mJoin, chord.mPattern, chord.mAsyncChans, chord.mSyncChans, chord.mArgChans); copy.mContinuation = delegate(P0 a) { return continuation(a); }; copy.SetContinuationAttribute(continuation); Register(copy); } internal override void Register<P0, P1, R>(NonVoidChord<S<O>, Pair<P0, P1>, R> chord, Func<P0, P1, R> continuation) { var copy = new Chord<Pair<P0, P1>, R>(chord.mJoin, chord.mPattern, chord.mAsyncChans, chord.mSyncChans, chord.mArgChans); copy.mContinuation = delegate(Pair<P0, P1> a) { return continuation(a.Fst, a.Snd); }; copy.SetContinuationAttribute(continuation); Register(copy); } internal override void Register<P0, P1, P2, R>(NonVoidChord<S<S<O>>, Pair<Pair<P0, P1>, P2>, R> chord, Func<P0, P1, P2, R> continuation) { var copy = new Chord<Pair<Pair<P0, P1>, P2>, R>(chord.mJoin, chord.mPattern, chord.mAsyncChans, chord.mSyncChans, chord.mArgChans); copy.mContinuation = delegate(Pair<Pair<P0, P1>, P2> a) { return continuation(a.Fst.Fst, a.Fst.Snd, a.Snd); }; copy.SetContinuationAttribute(continuation); Register(copy); } internal override void Register<P0, P1, P2, P3, R>(NonVoidChord<S<S<S<O>>>, Pair<Pair<Pair<P0, P1>, P2>, P3>, R> chord, Func<P0, P1, P2, P3, R> continuation) { var copy = new Chord<Pair<Pair<Pair<P0, P1>, P2>, P3>, R>(chord.mJoin, chord.mPattern, chord.mAsyncChans, chord.mSyncChans, chord.mArgChans); copy.mContinuation = delegate(Pair<Pair<Pair<P0, P1>, P2>, P3> a) { return continuation(a.Fst.Fst.Fst, a.Fst.Fst.Snd, a.Fst.Snd, a.Snd); }; copy.SetContinuationAttribute(continuation); Register(copy); } internal override void Register<P0, P1, P2, P3, P4, R>(NonVoidChord<S<S<S<S<O>>>>, Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, R> chord, Func<P0, P1, P2, P3, P4, R> continuation) { var copy = new Chord<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, R>(chord.mJoin, chord.mPattern, chord.mAsyncChans, chord.mSyncChans, chord.mArgChans); copy.mContinuation = delegate(Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4> a) { return continuation(a.Fst.Fst.Fst.Fst, a.Fst.Fst.Fst.Snd, a.Fst.Fst.Snd, a.Fst.Snd, a.Snd); }; copy.SetContinuationAttribute(continuation); Register(copy); } internal override void Register<P0, P1, P2, P3, P4, P5, R>(NonVoidChord<S<S<S<S<S<O>>>>>, Pair<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, P5>, R> chord, Func<P0, P1, P2, P3, P4, P5, R> continuation) { var copy = new Chord<Pair<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, P5>, R>(chord.mJoin, chord.mPattern, chord.mAsyncChans, chord.mSyncChans, chord.mArgChans); copy.mContinuation = delegate(Pair<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, P5> a) { return continuation(a.Fst.Fst.Fst.Fst.Fst, a.Fst.Fst.Fst.Fst.Snd, a.Fst.Fst.Fst.Snd, a.Fst.Fst.Snd, a.Fst.Snd, a.Snd); }; copy.SetContinuationAttribute(continuation); Register(copy); } internal override void Register<P0, P1, P2, P3, P4, P5, P6, R>(NonVoidChord<S<S<S<S<S<S<O>>>>>>, Pair<Pair<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, P5>, P6>, R> chord, Func<P0, P1, P2, P3, P4, P5, P6, R> continuation) { var copy = new Chord<Pair<Pair<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, P5>, P6>, R>(chord.mJoin, chord.mPattern, chord.mAsyncChans, chord.mSyncChans, chord.mArgChans); copy.mContinuation = delegate(Pair<Pair<Pair<Pair<Pair<Pair<P0, P1>, P2>, P3>, P4>, P5>, P6> a) { return continuation(a.Fst.Fst.Fst.Fst.Fst.Fst, a.Fst.Fst.Fst.Fst.Fst.Snd, a.Fst.Fst.Fst.Fst.Snd, a.Fst.Fst.Fst.Snd, a.Fst.Fst.Snd, a.Fst.Snd, a.Snd); }; copy.SetContinuationAttribute(continuation); Register(copy); } } // class SJoin } // namespace Microsoft.Research.Joins.Paper #endif #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace System.Collections.Immutable { /// <content> /// Contains the inner <see cref="ImmutableDictionary{TKey, TValue}.Builder"/> class. /// </content> [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] public sealed partial class ImmutableDictionary<TKey, TValue> { /// <summary> /// A dictionary that mutates with little or no memory allocations, /// can produce and/or build on immutable dictionary instances very efficiently. /// </summary> /// <remarks> /// <para> /// While <see cref="ImmutableDictionary{TKey, TValue}.AddRange(IEnumerable{KeyValuePair{TKey, TValue}})"/> /// and other bulk change methods already provide fast bulk change operations on the collection, this class allows /// multiple combinations of changes to be made to a set with equal efficiency. /// </para> /// <para> /// Instance members of this class are <em>not</em> thread-safe. /// </para> /// </remarks> [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Ignored")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(ImmutableDictionaryBuilderDebuggerProxy<,>))] public sealed class Builder : IDictionary<TKey, TValue>, IReadOnlyDictionary<TKey, TValue>, IDictionary { /// <summary> /// The root of the binary tree that stores the collection. Contents are typically not entirely frozen. /// </summary> private SortedInt32KeyNode<HashBucket> _root = SortedInt32KeyNode<HashBucket>.EmptyNode; /// <summary> /// The comparers. /// </summary> private Comparers _comparers; /// <summary> /// The number of elements in this collection. /// </summary> private int _count; /// <summary> /// Caches an immutable instance that represents the current state of the collection. /// </summary> /// <value>Null if no immutable view has been created for the current version.</value> private ImmutableDictionary<TKey, TValue> _immutable; /// <summary> /// A number that increments every time the builder changes its contents. /// </summary> private int _version; /// <summary> /// The object callers may use to synchronize access to this collection. /// </summary> private object _syncRoot; /// <summary> /// Initializes a new instance of the <see cref="ImmutableDictionary{TKey, TValue}.Builder"/> class. /// </summary> /// <param name="map">The map that serves as the basis for this Builder.</param> internal Builder(ImmutableDictionary<TKey, TValue> map) { Requires.NotNull(map, nameof(map)); _root = map._root; _count = map._count; _comparers = map._comparers; _immutable = map; } /// <summary> /// Gets or sets the key comparer. /// </summary> /// <value> /// The key comparer. /// </value> public IEqualityComparer<TKey> KeyComparer { get { return _comparers.KeyComparer; } set { Requires.NotNull(value, nameof(value)); if (value != this.KeyComparer) { var comparers = Comparers.Get(value, this.ValueComparer); var input = new MutationInput(SortedInt32KeyNode<HashBucket>.EmptyNode, comparers, 0); var result = ImmutableDictionary<TKey, TValue>.AddRange(this, input); _immutable = null; _comparers = comparers; _count = result.CountAdjustment; // offset from 0 this.Root = result.Root; } } } /// <summary> /// Gets or sets the value comparer. /// </summary> /// <value> /// The value comparer. /// </value> public IEqualityComparer<TValue> ValueComparer { get { return _comparers.ValueComparer; } set { Requires.NotNull(value, nameof(value)); if (value != this.ValueComparer) { // When the key comparer is the same but the value comparer is different, we don't need a whole new tree // because the structure of the tree does not depend on the value comparer. // We just need a new root node to store the new value comparer. _comparers = _comparers.WithValueComparer(value); _immutable = null; // invalidate cached immutable } } } #region IDictionary<TKey, TValue> Properties /// <summary> /// Gets the number of elements contained in the <see cref="ICollection{T}"/>. /// </summary> /// <returns>The number of elements contained in the <see cref="ICollection{T}"/>.</returns> public int Count { get { return _count; } } /// <summary> /// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only. /// </summary> /// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false.</returns> bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return false; } } /// <summary> /// See <see cref="IReadOnlyDictionary{TKey, TValue}"/> /// </summary> public IEnumerable<TKey> Keys { get { foreach (KeyValuePair<TKey, TValue> item in this) { yield return item.Key; } } } /// <summary> /// Gets an <see cref="ICollection{T}"/> containing the keys of the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <returns>An <see cref="ICollection{T}"/> containing the keys of the object that implements <see cref="IDictionary{TKey, TValue}"/>.</returns> ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { return this.Keys.ToArray(this.Count); } } /// <summary> /// See <see cref="IReadOnlyDictionary{TKey, TValue}"/> /// </summary> public IEnumerable<TValue> Values { get { foreach (KeyValuePair<TKey, TValue> item in this) { yield return item.Value; } } } /// <summary> /// Gets an <see cref="ICollection{T}"/> containing the values in the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <returns>An <see cref="ICollection{T}"/> containing the values in the object that implements <see cref="IDictionary{TKey, TValue}"/>.</returns> ICollection<TValue> IDictionary<TKey, TValue>.Values { get { return this.Values.ToArray(this.Count); } } #endregion #region IDictionary Properties /// <summary> /// Gets a value indicating whether the <see cref="IDictionary"/> object has a fixed size. /// </summary> /// <returns>true if the <see cref="IDictionary"/> object has a fixed size; otherwise, false.</returns> bool IDictionary.IsFixedSize { get { return false; } } /// <summary> /// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only. /// </summary> /// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false. /// </returns> bool IDictionary.IsReadOnly { get { return false; } } /// <summary> /// Gets an <see cref="ICollection{T}"/> containing the keys of the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <returns> /// An <see cref="ICollection{T}"/> containing the keys of the object that implements <see cref="IDictionary{TKey, TValue}"/>. /// </returns> ICollection IDictionary.Keys { get { return this.Keys.ToArray(this.Count); } } /// <summary> /// Gets an <see cref="ICollection{T}"/> containing the values in the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <returns> /// An <see cref="ICollection{T}"/> containing the values in the object that implements <see cref="IDictionary{TKey, TValue}"/>. /// </returns> ICollection IDictionary.Values { get { return this.Values.ToArray(this.Count); } } #endregion #region ICollection Properties /// <summary> /// Gets an object that can be used to synchronize access to the <see cref="ICollection"/>. /// </summary> /// <returns>An object that can be used to synchronize access to the <see cref="ICollection"/>.</returns> [DebuggerBrowsable(DebuggerBrowsableState.Never)] object ICollection.SyncRoot { get { if (_syncRoot == null) { Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } return _syncRoot; } } /// <summary> /// Gets a value indicating whether access to the <see cref="ICollection"/> is synchronized (thread safe). /// </summary> /// <returns>true if access to the <see cref="ICollection"/> is synchronized (thread safe); otherwise, false.</returns> [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool ICollection.IsSynchronized { get { return false; } } #endregion #region IDictionary Methods /// <summary> /// Adds an element with the provided key and value to the <see cref="IDictionary"/> object. /// </summary> /// <param name="key">The <see cref="object"/> to use as the key of the element to add.</param> /// <param name="value">The <see cref="object"/> to use as the value of the element to add.</param> void IDictionary.Add(object key, object value) { this.Add((TKey)key, (TValue)value); } /// <summary> /// Determines whether the <see cref="IDictionary"/> object contains an element with the specified key. /// </summary> /// <param name="key">The key to locate in the <see cref="IDictionary"/> object.</param> /// <returns> /// true if the <see cref="IDictionary"/> contains an element with the key; otherwise, false. /// </returns> bool IDictionary.Contains(object key) { return this.ContainsKey((TKey)key); } /// <summary> /// Returns an <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object. /// </summary> /// <returns> /// An <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object. /// </returns> IDictionaryEnumerator IDictionary.GetEnumerator() { return new DictionaryEnumerator<TKey, TValue>(this.GetEnumerator()); } /// <summary> /// Removes the element with the specified key from the <see cref="IDictionary"/> object. /// </summary> /// <param name="key">The key of the element to remove.</param> void IDictionary.Remove(object key) { this.Remove((TKey)key); } /// <summary> /// Gets or sets the element with the specified key. /// </summary> /// <param name="key">The key.</param> /// <returns></returns> object IDictionary.this[object key] { get { return this[(TKey)key]; } set { this[(TKey)key] = (TValue)value; } } #endregion #region ICollection methods /// <summary> /// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ICollection"/>. The <see cref="Array"/> must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param> void ICollection.CopyTo(Array array, int arrayIndex) { Requires.NotNull(array, nameof(array)); Requires.Range(arrayIndex >= 0, nameof(arrayIndex)); Requires.Range(array.Length >= arrayIndex + this.Count, nameof(arrayIndex)); foreach (var item in this) { array.SetValue(new DictionaryEntry(item.Key, item.Value), arrayIndex++); } } #endregion /// <summary> /// Gets the current version of the contents of this builder. /// </summary> internal int Version { get { return _version; } } /// <summary> /// Gets the initial data to pass to a query or mutation method. /// </summary> private MutationInput Origin { get { return new MutationInput(this.Root, _comparers, _count); } } /// <summary> /// Gets or sets the root of this data structure. /// </summary> private SortedInt32KeyNode<HashBucket> Root { get { return _root; } set { // We *always* increment the version number because some mutations // may not create a new value of root, although the existing root // instance may have mutated. _version++; if (_root != value) { _root = value; // Clear any cached value for the immutable view since it is now invalidated. _immutable = null; } } } /// <summary> /// Gets or sets the element with the specified key. /// </summary> /// <returns>The element with the specified key.</returns> /// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception> /// <exception cref="KeyNotFoundException">The property is retrieved and <paramref name="key"/> is not found.</exception> /// <exception cref="NotSupportedException">The property is set and the <see cref="IDictionary{TKey, TValue}"/> is read-only.</exception> public TValue this[TKey key] { get { TValue value; if (this.TryGetValue(key, out value)) { return value; } throw new KeyNotFoundException(); } set { var result = ImmutableDictionary<TKey, TValue>.Add(key, value, KeyCollisionBehavior.SetValue, this.Origin); this.Apply(result); } } #region Public Methods /// <summary> /// Adds a sequence of values to this collection. /// </summary> /// <param name="items">The items.</param> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public void AddRange(IEnumerable<KeyValuePair<TKey, TValue>> items) { var result = ImmutableDictionary<TKey, TValue>.AddRange(items, this.Origin); this.Apply(result); } /// <summary> /// Removes any entries from the dictionaries with keys that match those found in the specified sequence. /// </summary> /// <param name="keys">The keys for entries to remove from the dictionary.</param> public void RemoveRange(IEnumerable<TKey> keys) { Requires.NotNull(keys, nameof(keys)); foreach (var key in keys) { this.Remove(key); } } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> public Enumerator GetEnumerator() { return new Enumerator(_root, this); } /// <summary> /// Gets the value for a given key if a matching key exists in the dictionary. /// </summary> /// <param name="key">The key to search for.</param> /// <returns>The value for the key, or the default value of type <typeparamref name="TValue"/> if no matching key was found.</returns> [Pure] public TValue GetValueOrDefault(TKey key) { return this.GetValueOrDefault(key, default(TValue)); } /// <summary> /// Gets the value for a given key if a matching key exists in the dictionary. /// </summary> /// <param name="key">The key to search for.</param> /// <param name="defaultValue">The default value to return if no matching key is found in the dictionary.</param> /// <returns> /// The value for the key, or <paramref name="defaultValue"/> if no matching key was found. /// </returns> [Pure] public TValue GetValueOrDefault(TKey key, TValue defaultValue) { Requires.NotNullAllowStructs(key, nameof(key)); TValue value; if (this.TryGetValue(key, out value)) { return value; } return defaultValue; } /// <summary> /// Creates an immutable dictionary based on the contents of this instance. /// </summary> /// <returns>An immutable map.</returns> /// <remarks> /// This method is an O(n) operation, and approaches O(1) time as the number of /// actual mutations to the set since the last call to this method approaches 0. /// </remarks> public ImmutableDictionary<TKey, TValue> ToImmutable() { // Creating an instance of ImmutableSortedMap<T> with our root node automatically freezes our tree, // ensuring that the returned instance is immutable. Any further mutations made to this builder // will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked. if (_immutable == null) { _immutable = ImmutableDictionary<TKey, TValue>.Wrap(_root, _comparers, _count); } return _immutable; } #endregion #region IDictionary<TKey, TValue> Members /// <summary> /// Adds an element with the provided key and value to the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <param name="key">The object to use as the key of the element to add.</param> /// <param name="value">The object to use as the value of the element to add.</param> /// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception> /// <exception cref="ArgumentException">An element with the same key already exists in the <see cref="IDictionary{TKey, TValue}"/>.</exception> /// <exception cref="NotSupportedException">The <see cref="IDictionary{TKey, TValue}"/> is read-only.</exception> public void Add(TKey key, TValue value) { var result = ImmutableDictionary<TKey, TValue>.Add(key, value, KeyCollisionBehavior.ThrowIfValueDifferent, this.Origin); this.Apply(result); } /// <summary> /// Determines whether the <see cref="IDictionary{TKey, TValue}"/> contains an element with the specified key. /// </summary> /// <param name="key">The key to locate in the <see cref="IDictionary{TKey, TValue}"/>.</param> /// <returns> /// true if the <see cref="IDictionary{TKey, TValue}"/> contains an element with the key; otherwise, false. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception> public bool ContainsKey(TKey key) { return ImmutableDictionary<TKey, TValue>.ContainsKey(key, this.Origin); } /// <summary> /// Determines whether the <see cref="ImmutableDictionary{TKey, TValue}"/> /// contains an element with the specified value. /// </summary> /// <param name="value"> /// The value to locate in the <see cref="ImmutableDictionary{TKey, TValue}"/>. /// The value can be null for reference types. /// </param> /// <returns> /// true if the <see cref="ImmutableDictionary{TKey, TValue}"/> contains /// an element with the specified value; otherwise, false. /// </returns> [Pure] public bool ContainsValue(TValue value) { foreach (KeyValuePair<TKey, TValue> item in this) { if (this.ValueComparer.Equals(value, item.Value)) { return true; } } return false; } /// <summary> /// Removes the element with the specified key from the <see cref="IDictionary{TKey, TValue}"/>. /// </summary> /// <param name="key">The key of the element to remove.</param> /// <returns> /// true if the element is successfully removed; otherwise, false. This method also returns false if <paramref name="key"/> was not found in the original <see cref="IDictionary{TKey, TValue}"/>. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception> /// /// <exception cref="NotSupportedException">The <see cref="IDictionary{TKey, TValue}"/> is read-only.</exception> public bool Remove(TKey key) { var result = ImmutableDictionary<TKey, TValue>.Remove(key, this.Origin); return this.Apply(result); } /// <summary> /// Gets the value associated with the specified key. /// </summary> /// <param name="key">The key whose value to get.</param> /// <param name="value">When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value of the type <typeparamref name="TValue"/>. This parameter is passed uninitialized.</param> /// <returns> /// true if the object that implements <see cref="IDictionary{TKey, TValue}"/> contains an element with the specified key; otherwise, false. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="key"/> is null.</exception> public bool TryGetValue(TKey key, out TValue value) { return ImmutableDictionary<TKey, TValue>.TryGetValue(key, this.Origin, out value); } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface. /// </summary> public bool TryGetKey(TKey equalKey, out TKey actualKey) { return ImmutableDictionary<TKey, TValue>.TryGetKey(equalKey, this.Origin, out actualKey); } /// <summary> /// Adds an item to the <see cref="ICollection{T}"/>. /// </summary> /// <param name="item">The object to add to the <see cref="ICollection{T}"/>.</param> /// <exception cref="NotSupportedException">The <see cref="ICollection{T}"/> is read-only.</exception> public void Add(KeyValuePair<TKey, TValue> item) { this.Add(item.Key, item.Value); } /// <summary> /// Removes all items from the <see cref="ICollection{T}"/>. /// </summary> /// <exception cref="NotSupportedException">The <see cref="ICollection{T}"/> is read-only. </exception> public void Clear() { this.Root = SortedInt32KeyNode<HashBucket>.EmptyNode; _count = 0; } /// <summary> /// Determines whether the <see cref="ICollection{T}"/> contains a specific value. /// </summary> /// <param name="item">The object to locate in the <see cref="ICollection{T}"/>.</param> /// <returns> /// true if <paramref name="item"/> is found in the <see cref="ICollection{T}"/>; otherwise, false. /// </returns> public bool Contains(KeyValuePair<TKey, TValue> item) { return ImmutableDictionary<TKey, TValue>.Contains(item, this.Origin); } /// <summary> /// See the <see cref="ICollection{T}"/> interface. /// </summary> void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { Requires.NotNull(array, nameof(array)); foreach (var item in this) { array[arrayIndex++] = item; } } #endregion #region ICollection<KeyValuePair<TKey, TValue>> Members /// <summary> /// Removes the first occurrence of a specific object from the <see cref="ICollection{T}"/>. /// </summary> /// <param name="item">The object to remove from the <see cref="ICollection{T}"/>.</param> /// <returns> /// true if <paramref name="item"/> was successfully removed from the <see cref="ICollection{T}"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="ICollection{T}"/>. /// </returns> /// <exception cref="NotSupportedException">The <see cref="ICollection{T}"/> is read-only.</exception> public bool Remove(KeyValuePair<TKey, TValue> item) { // Before removing based on the key, check that the key (if it exists) has the value given in the parameter as well. if (this.Contains(item)) { return this.Remove(item.Key); } return false; } #endregion #region IEnumerator<T> methods /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="IEnumerator"/> object that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion /// <summary> /// Applies the result of some mutation operation to this instance. /// </summary> /// <param name="result">The result.</param> private bool Apply(MutationResult result) { this.Root = result.Root; _count += result.CountAdjustment; return result.CountAdjustment != 0; } } } /// <summary> /// A simple view of the immutable collection that the debugger can show to the developer. /// </summary> internal class ImmutableDictionaryBuilderDebuggerProxy<TKey, TValue> { /// <summary> /// The collection to be enumerated. /// </summary> private readonly ImmutableDictionary<TKey, TValue>.Builder _map; /// <summary> /// The simple view of the collection. /// </summary> private KeyValuePair<TKey, TValue>[] _contents; /// <summary> /// Initializes a new instance of the <see cref="ImmutableDictionaryBuilderDebuggerProxy{TKey, TValue}"/> class. /// </summary> /// <param name="map">The collection to display in the debugger</param> public ImmutableDictionaryBuilderDebuggerProxy(ImmutableDictionary<TKey, TValue>.Builder map) { Requires.NotNull(map, nameof(map)); _map = map; } /// <summary> /// Gets a simple debugger-viewable collection. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public KeyValuePair<TKey, TValue>[] Contents { get { if (_contents == null) { _contents = _map.ToArray(_map.Count); } return _contents; } } } }
// // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using System.Threading; using Zenject.ReflectionBaking.Mono.Collections.Generic; namespace Zenject.ReflectionBaking.Mono.Cecil.Cil { public sealed class MethodBody : IVariableDefinitionProvider { readonly internal MethodDefinition method; internal ParameterDefinition this_parameter; internal int max_stack_size; internal int code_size; internal bool init_locals; internal MetadataToken local_var_token; internal Collection<Instruction> instructions; internal Collection<ExceptionHandler> exceptions; internal Collection<VariableDefinition> variables; Scope scope; public MethodDefinition Method { get { return method; } } public int MaxStackSize { get { return max_stack_size; } set { max_stack_size = value; } } public int CodeSize { get { return code_size; } } public bool InitLocals { get { return init_locals; } set { init_locals = value; } } public MetadataToken LocalVarToken { get { return local_var_token; } set { local_var_token = value; } } public Collection<Instruction> Instructions { get { return instructions ?? (instructions = new InstructionCollection ()); } } public bool HasExceptionHandlers { get { return !exceptions.IsNullOrEmpty (); } } public Collection<ExceptionHandler> ExceptionHandlers { get { return exceptions ?? (exceptions = new Collection<ExceptionHandler> ()); } } public bool HasVariables { get { return !variables.IsNullOrEmpty (); } } public Collection<VariableDefinition> Variables { get { return variables ?? (variables = new VariableDefinitionCollection ()); } } public Scope Scope { get { return scope; } set { scope = value; } } public ParameterDefinition ThisParameter { get { if (method == null || method.DeclaringType == null) throw new NotSupportedException (); if (!method.HasThis) return null; if (this_parameter == null) Interlocked.CompareExchange (ref this_parameter, CreateThisParameter (method), null); return this_parameter; } } static ParameterDefinition CreateThisParameter (MethodDefinition method) { var declaring_type = method.DeclaringType; var type = declaring_type.IsValueType || declaring_type.IsPrimitive ? new PointerType (declaring_type) : declaring_type as TypeReference; return new ParameterDefinition (type, method); } public MethodBody (MethodDefinition method) { this.method = method; } public ILProcessor GetILProcessor () { return new ILProcessor (this); } } public interface IVariableDefinitionProvider { bool HasVariables { get; } Collection<VariableDefinition> Variables { get; } } class VariableDefinitionCollection : Collection<VariableDefinition> { internal VariableDefinitionCollection () { } internal VariableDefinitionCollection (int capacity) : base (capacity) { } protected override void OnAdd (VariableDefinition item, int index) { item.index = index; } protected override void OnInsert (VariableDefinition item, int index) { item.index = index; for (int i = index; i < size; i++) items [i].index = i + 1; } protected override void OnSet (VariableDefinition item, int index) { item.index = index; } protected override void OnRemove (VariableDefinition item, int index) { item.index = -1; for (int i = index + 1; i < size; i++) items [i].index = i - 1; } } class InstructionCollection : Collection<Instruction> { internal InstructionCollection () { } internal InstructionCollection (int capacity) : base (capacity) { } protected override void OnAdd (Instruction item, int index) { if (index == 0) return; var previous = items [index - 1]; previous.next = item; item.previous = previous; } protected override void OnInsert (Instruction item, int index) { if (size == 0) return; var current = items [index]; if (current == null) { var last = items [index - 1]; last.next = item; item.previous = last; return; } var previous = current.previous; if (previous != null) { previous.next = item; item.previous = previous; } current.previous = item; item.next = current; } protected override void OnSet (Instruction item, int index) { var current = items [index]; item.previous = current.previous; item.next = current.next; current.previous = null; current.next = null; } protected override void OnRemove (Instruction item, int index) { var previous = item.previous; if (previous != null) previous.next = item.next; var next = item.next; if (next != null) next.previous = item.previous; item.previous = null; item.next = null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Authentication; using System.Threading.Tasks; using System.Web; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace RedditSharp.Things { public class Post : VotableThing { private const string CommentUrl = "/api/comment"; private const string RemoveUrl = "/api/remove"; private const string DelUrl = "/api/del"; private const string GetCommentsUrl = "/comments/{0}.json"; private const string ApproveUrl = "/api/approve"; private const string EditUserTextUrl = "/api/editusertext"; private const string HideUrl = "/api/hide"; private const string UnhideUrl = "/api/unhide"; private const string SetFlairUrl = "/api/flair"; private const string MarkNSFWUrl = "/api/marknsfw"; private const string UnmarkNSFWUrl = "/api/unmarknsfw"; private const string ContestModeUrl = "/api/set_contest_mode"; [JsonIgnore] private Reddit Reddit { get; set; } [JsonIgnore] private IWebAgent WebAgent { get; set; } public Post Init(Reddit reddit, JToken post, IWebAgent webAgent) { CommonInit(reddit, post, webAgent); JsonConvert.PopulateObject(post["data"].ToString(), this, reddit.JsonSerializerSettings); return this; } public async Task<Post> InitAsync(Reddit reddit, JToken post, IWebAgent webAgent) { CommonInit(reddit, post, webAgent); await Task.Factory.StartNew(() => JsonConvert.PopulateObject(post["data"].ToString(), this, reddit.JsonSerializerSettings)); return this; } private void CommonInit(Reddit reddit, JToken post, IWebAgent webAgent) { base.Init(reddit, webAgent, post); Reddit = reddit; WebAgent = webAgent; } [JsonProperty("author")] public string AuthorName { get; set; } [JsonIgnore] public RedditUser Author { get { return Reddit.GetUser(AuthorName); } } public Comment[] Comments { get { return ListComments().ToArray(); } } [JsonProperty("approved_by")] public string ApprovedBy { get; set; } [JsonProperty("author_flair_css_class")] public string AuthorFlairCssClass { get; set; } [JsonProperty("author_flair_text")] public string AuthorFlairText { get; set; } [JsonProperty("banned_by")] public string BannedBy { get; set; } [JsonProperty("domain")] public string Domain { get; set; } [JsonProperty("edited")] public bool Edited { get; set; } [JsonProperty("is_self")] public bool IsSelfPost { get; set; } [JsonProperty("link_flair_css_class")] public string LinkFlairCssClass { get; set; } [JsonProperty("link_flair_text")] public string LinkFlairText { get; set; } [JsonProperty("num_comments")] public int CommentCount { get; set; } [JsonProperty("over_18")] public bool NSFW { get; set; } [JsonProperty("permalink")] [JsonConverter(typeof(UrlParser))] public Uri Permalink { get; set; } [JsonProperty("score")] public int Score { get; set; } [JsonProperty("selftext")] public string SelfText { get; set; } [JsonProperty("selftext_html")] public string SelfTextHtml { get; set; } [JsonProperty("thumbnail")] [JsonConverter(typeof(UrlParser))] public Uri Thumbnail { get; set; } [JsonProperty("title")] public string Title { get; set; } [JsonProperty("subreddit")] public string SubredditName { get; set; } [JsonIgnore] public Subreddit Subreddit { get { return Reddit.GetSubreddit("/r/" + SubredditName); } } [JsonProperty("url")] [JsonConverter(typeof(UrlParser))] public Uri Url { get; set; } [JsonProperty("num_reports")] public int? Reports { get; set; } public Comment Comment(string message) { if (Reddit.User == null) throw new AuthenticationException("No user logged in."); var request = WebAgent.CreatePost(CommentUrl); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { text = message, thing_id = FullName, uh = Reddit.User.Modhash, api_type = "json" }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); var json = JObject.Parse(data); if (json["json"]["ratelimit"] != null) throw new RateLimitException(TimeSpan.FromSeconds(json["json"]["ratelimit"].ValueOrDefault<double>())); return new Comment().Init(Reddit, json["json"]["data"]["things"][0], WebAgent, this); } private string SimpleAction(string endpoint) { if (Reddit.User == null) throw new AuthenticationException("No user logged in."); var request = WebAgent.CreatePost(endpoint); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { id = FullName, uh = Reddit.User.Modhash }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); return data; } private string SimpleActionToggle(string endpoint, bool value) { if (Reddit.User == null) throw new AuthenticationException("No user logged in."); var request = WebAgent.CreatePost(endpoint); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { id = FullName, state = value, uh = Reddit.User.Modhash }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); return data; } public void Approve() { var data = SimpleAction(ApproveUrl); } public void Remove() { RemoveImpl(false); } public void RemoveSpam() { RemoveImpl(true); } private void RemoveImpl(bool spam) { var request = WebAgent.CreatePost(RemoveUrl); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { id = FullName, spam = spam, uh = Reddit.User.Modhash }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); } public void Del() { var data = SimpleAction(DelUrl); } public void Hide() { var data = SimpleAction(HideUrl); } public void Unhide() { var data = SimpleAction(UnhideUrl); } public void MarkNSFW() { var data = SimpleAction(MarkNSFWUrl); } public void UnmarkNSFW() { var data = SimpleAction(UnmarkNSFWUrl); } public void ContestMode(bool state) { var data = SimpleActionToggle(ContestModeUrl, state); } #region Obsolete Getter Methods [Obsolete("Use Comments property instead")] public Comment[] GetComments() { return Comments; } #endregion Obsolete Getter Methods /// <summary> /// Replaces the text in this post with the input text. /// </summary> /// <param name="newText">The text to replace the post's contents</param> public void EditText(string newText) { if (Reddit.User == null) throw new Exception("No user logged in."); if (!IsSelfPost) throw new Exception("Submission to edit is not a self-post."); var request = WebAgent.CreatePost(EditUserTextUrl); WebAgent.WritePostBody(request.GetRequestStream(), new { api_type = "json", text = newText, thing_id = FullName, uh = Reddit.User.Modhash }); var response = request.GetResponse(); var result = WebAgent.GetResponseString(response.GetResponseStream()); JToken json = JToken.Parse(result); if (json["json"].ToString().Contains("\"errors\": []")) SelfText = newText; else throw new Exception("Error editing text."); } public void Update() { JToken post = Reddit.GetToken(this.Url); JsonConvert.PopulateObject(post["data"].ToString(), this, Reddit.JsonSerializerSettings); } public void SetFlair(string flairText, string flairClass) { if (Reddit.User == null) throw new Exception("No user logged in."); var request = WebAgent.CreatePost(SetFlairUrl); WebAgent.WritePostBody(request.GetRequestStream(), new { api_type = "json", css_class = flairClass, link = FullName, name = Reddit.User.Name, text = flairText, uh = Reddit.User.Modhash }); var response = request.GetResponse(); var result = WebAgent.GetResponseString(response.GetResponseStream()); var json = JToken.Parse(result); LinkFlairText = flairText; } public List<Comment> ListComments(int? limit = null) { var url = string.Format(GetCommentsUrl, Id); if (limit.HasValue) { var query = HttpUtility.ParseQueryString(string.Empty); query.Add("limit", limit.Value.ToString()); url = string.Format("{0}?{1}", url, query); } var request = WebAgent.CreateGet(url); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); var json = JArray.Parse(data); var postJson = json.Last()["data"]["children"]; var comments = new List<Comment>(); foreach (var comment in postJson) { comments.Add(new Comment().Init(Reddit, comment, WebAgent, this)); } return comments; } } }
using System; using System.IO; using BigMath; using NUnit.Framework; using Raksha.Asn1; using Raksha.Math; using Raksha.Utilities; using Raksha.Utilities.Encoders; using Raksha.Tests.Utilities; namespace Raksha.Tests.Asn1 { [TestFixture] public class Asn1SequenceParserTest { private static readonly byte[] seqData = Hex.Decode("3006020100060129"); private static readonly byte[] nestedSeqData = Hex.Decode("300b0201000601293003020101"); private static readonly byte[] expTagSeqData = Hex.Decode("a1083006020100060129"); private static readonly byte[] implTagSeqData = Hex.Decode("a106020100060129"); private static readonly byte[] nestedSeqExpTagData = Hex.Decode("300d020100060129a1053003020101"); private static readonly byte[] nestedSeqImpTagData = Hex.Decode("300b020100060129a103020101"); private static readonly byte[] berSeqData = Hex.Decode("30800201000601290000"); private static readonly byte[] berDerNestedSeqData = Hex.Decode("308002010006012930030201010000"); private static readonly byte[] berNestedSeqData = Hex.Decode("3080020100060129308002010100000000"); private static readonly byte[] berExpTagSeqData = Hex.Decode("a180308002010006012900000000"); private static readonly byte[] berSeqWithDERNullData = Hex.Decode("308005000201000601290000"); [Test] public void TestDerWriting() { MemoryStream bOut = new MemoryStream(); DerSequenceGenerator seqGen = new DerSequenceGenerator(bOut); seqGen.AddObject(new DerInteger(BigInteger.Zero)); seqGen.AddObject(new DerObjectIdentifier("1.1")); seqGen.Close(); Assert.IsTrue(Arrays.AreEqual(seqData, bOut.ToArray()), "basic DER writing test failed."); } [Test] public void TestNestedDerWriting() { MemoryStream bOut = new MemoryStream(); DerSequenceGenerator seqGen1 = new DerSequenceGenerator(bOut); seqGen1.AddObject(new DerInteger(BigInteger.Zero)); seqGen1.AddObject(new DerObjectIdentifier("1.1")); DerSequenceGenerator seqGen2 = new DerSequenceGenerator(seqGen1.GetRawOutputStream()); seqGen2.AddObject(new DerInteger(BigInteger.One)); seqGen2.Close(); seqGen1.Close(); Assert.IsTrue(Arrays.AreEqual(nestedSeqData, bOut.ToArray()), "nested DER writing test failed."); } [Test] public void TestDerExplicitTaggedSequenceWriting() { MemoryStream bOut = new MemoryStream(); DerSequenceGenerator seqGen = new DerSequenceGenerator(bOut, 1, true); seqGen.AddObject(new DerInteger(BigInteger.Zero)); seqGen.AddObject(new DerObjectIdentifier("1.1")); seqGen.Close(); Assert.IsTrue(Arrays.AreEqual(expTagSeqData, bOut.ToArray()), "explicit tag writing test failed."); } [Test] public void TestDerImplicitTaggedSequenceWriting() { MemoryStream bOut = new MemoryStream(); DerSequenceGenerator seqGen = new DerSequenceGenerator(bOut, 1, false); seqGen.AddObject(new DerInteger(BigInteger.Zero)); seqGen.AddObject(new DerObjectIdentifier("1.1")); seqGen.Close(); Assert.IsTrue(Arrays.AreEqual(implTagSeqData, bOut.ToArray()), "implicit tag writing test failed."); } [Test] public void TestNestedExplicitTagDerWriting() { MemoryStream bOut = new MemoryStream(); DerSequenceGenerator seqGen1 = new DerSequenceGenerator(bOut); seqGen1.AddObject(new DerInteger(BigInteger.Zero)); seqGen1.AddObject(new DerObjectIdentifier("1.1")); DerSequenceGenerator seqGen2 = new DerSequenceGenerator(seqGen1.GetRawOutputStream(), 1, true); seqGen2.AddObject(new DerInteger(BigInteger.ValueOf(1))); seqGen2.Close(); seqGen1.Close(); Assert.IsTrue(Arrays.AreEqual(nestedSeqExpTagData, bOut.ToArray()), "nested explicit tagged DER writing test failed."); } [Test] public void TestNestedImplicitTagDerWriting() { MemoryStream bOut = new MemoryStream(); DerSequenceGenerator seqGen1 = new DerSequenceGenerator(bOut); seqGen1.AddObject(new DerInteger(BigInteger.Zero)); seqGen1.AddObject(new DerObjectIdentifier("1.1")); DerSequenceGenerator seqGen2 = new DerSequenceGenerator(seqGen1.GetRawOutputStream(), 1, false); seqGen2.AddObject(new DerInteger(BigInteger.ValueOf(1))); seqGen2.Close(); seqGen1.Close(); Assert.IsTrue(Arrays.AreEqual(nestedSeqImpTagData, bOut.ToArray()), "nested implicit tagged DER writing test failed."); } [Test] public void TestBerWriting() { MemoryStream bOut = new MemoryStream(); BerSequenceGenerator seqGen = new BerSequenceGenerator(bOut); seqGen.AddObject(new DerInteger(BigInteger.Zero)); seqGen.AddObject(new DerObjectIdentifier("1.1")); seqGen.Close(); Assert.IsTrue(Arrays.AreEqual(berSeqData, bOut.ToArray()), "basic BER writing test failed."); } [Test] public void TestNestedBerDerWriting() { MemoryStream bOut = new MemoryStream(); BerSequenceGenerator seqGen1 = new BerSequenceGenerator(bOut); seqGen1.AddObject(new DerInteger(BigInteger.Zero)); seqGen1.AddObject(new DerObjectIdentifier("1.1")); DerSequenceGenerator seqGen2 = new DerSequenceGenerator(seqGen1.GetRawOutputStream()); seqGen2.AddObject(new DerInteger(BigInteger.ValueOf(1))); seqGen2.Close(); seqGen1.Close(); Assert.IsTrue(Arrays.AreEqual(berDerNestedSeqData, bOut.ToArray()), "nested BER/DER writing test failed."); } [Test] public void TestNestedBerWriting() { MemoryStream bOut = new MemoryStream(); BerSequenceGenerator seqGen1 = new BerSequenceGenerator(bOut); seqGen1.AddObject(new DerInteger(BigInteger.Zero)); seqGen1.AddObject(new DerObjectIdentifier("1.1")); BerSequenceGenerator seqGen2 = new BerSequenceGenerator(seqGen1.GetRawOutputStream()); seqGen2.AddObject(new DerInteger(BigInteger.ValueOf(1))); seqGen2.Close(); seqGen1.Close(); Assert.IsTrue(Arrays.AreEqual(berNestedSeqData, bOut.ToArray()), "nested BER writing test failed."); } [Test] public void TestDerReading() { Asn1StreamParser aIn = new Asn1StreamParser(seqData); Asn1SequenceParser seq = (Asn1SequenceParser)aIn.ReadObject(); int count = 0; Assert.IsNotNull(seq, "null sequence returned"); object o; while ((o = seq.ReadObject()) != null) { switch (count) { case 0: Assert.IsTrue(o is DerInteger); break; case 1: Assert.IsTrue(o is DerObjectIdentifier); break; } count++; } Assert.AreEqual(2, count, "wrong number of objects in sequence"); } private void doTestNestedReading( byte[] data) { Asn1StreamParser aIn = new Asn1StreamParser(data); Asn1SequenceParser seq = (Asn1SequenceParser) aIn.ReadObject(); object o = null; int count = 0; Assert.IsNotNull(seq, "null sequence returned"); while ((o = seq.ReadObject()) != null) { switch (count) { case 0: Assert.IsTrue(o is DerInteger); break; case 1: Assert.IsTrue(o is DerObjectIdentifier); break; case 2: Assert.IsTrue(o is Asn1SequenceParser); Asn1SequenceParser s = (Asn1SequenceParser)o; // NB: Must exhaust the nested parser while (s.ReadObject() != null) { // Ignore } break; } count++; } Assert.AreEqual(3, count, "wrong number of objects in sequence"); } [Test] public void TestNestedDerReading() { doTestNestedReading(nestedSeqData); } [Test] public void TestBerReading() { Asn1StreamParser aIn = new Asn1StreamParser(berSeqData); Asn1SequenceParser seq = (Asn1SequenceParser) aIn.ReadObject(); object o = null; int count = 0; Assert.IsNotNull(seq, "null sequence returned"); while ((o = seq.ReadObject()) != null) { switch (count) { case 0: Assert.IsTrue(o is DerInteger); break; case 1: Assert.IsTrue(o is DerObjectIdentifier); break; } count++; } Assert.AreEqual(2, count, "wrong number of objects in sequence"); } [Test] public void TestNestedBerDerReading() { doTestNestedReading(berDerNestedSeqData); } [Test] public void TestNestedBerReading() { doTestNestedReading(berNestedSeqData); } [Test] public void TestBerExplicitTaggedSequenceWriting() { MemoryStream bOut = new MemoryStream(); BerSequenceGenerator seqGen = new BerSequenceGenerator(bOut, 1, true); seqGen.AddObject(new DerInteger(BigInteger.Zero)); seqGen.AddObject(new DerObjectIdentifier("1.1")); seqGen.Close(); Assert.IsTrue(Arrays.AreEqual(berExpTagSeqData, bOut.ToArray()), "explicit BER tag writing test failed."); } [Test] public void TestSequenceWithDerNullReading() { doTestParseWithNull(berSeqWithDERNullData); } private void doTestParseWithNull( byte[] data) { Asn1StreamParser aIn = new Asn1StreamParser(data); Asn1SequenceParser seq = (Asn1SequenceParser) aIn.ReadObject(); object o; int count = 0; Assert.IsNotNull(seq, "null sequence returned"); while ((o = seq.ReadObject()) != null) { switch (count) { case 0: Assert.IsTrue(o is Asn1Null); break; case 1: Assert.IsTrue(o is DerInteger); break; case 2: Assert.IsTrue(o is DerObjectIdentifier); break; } count++; } Assert.AreEqual(3, count, "wrong number of objects in sequence"); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Net; using System.IO; using System.Timers; using System.Drawing; using System.Drawing.Imaging; using log4net; using Mono.Addins; using Nini.Config; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using OpenSim.Server.Base; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.MapImage { /// <summary> /// </summary> /// <remarks> /// </remarks> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "MapImageServiceModule")] public class MapImageServiceModule : IMapImageUploadModule, ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static string LogHeader = "[MAP IMAGE SERVICE MODULE]:"; private bool m_enabled = false; private IMapImageService m_MapService; private Dictionary<UUID, Scene> m_scenes = new Dictionary<UUID, Scene>(); private int m_refreshtime = 0; private int m_lastrefresh = 0; private System.Timers.Timer m_refreshTimer; #region ISharedRegionModule public Type ReplaceableInterface { get { return null; } } public string Name { get { return "MapImageServiceModule"; } } public void RegionLoaded(Scene scene) { } public void Close() { } public void PostInitialise() { } ///<summary> /// ///</summary> public void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("MapImageService", ""); if (name != Name) return; } IConfig config = source.Configs["MapImageService"]; if (config == null) return; int refreshminutes = Convert.ToInt32(config.GetString("RefreshTime", "60")); if (refreshminutes < 0) { m_log.WarnFormat("[MAP IMAGE SERVICE MODULE]: Negative refresh time given in config. Module disabled."); return; } string service = config.GetString("LocalServiceModule", string.Empty); if (service == string.Empty) { m_log.WarnFormat("[MAP IMAGE SERVICE MODULE]: No service dll given in config. Unable to proceed."); return; } Object[] args = new Object[] { source }; m_MapService = ServerUtils.LoadPlugin<IMapImageService>(service, args); if (m_MapService == null) { m_log.WarnFormat("[MAP IMAGE SERVICE MODULE]: Unable to load LocalServiceModule from {0}. MapService module disabled. Please fix the configuration.", service); return; } // we don't want the timer if the interval is zero, but we still want this module enables if(refreshminutes > 0) { m_refreshtime = refreshminutes * 60 * 1000; // convert from minutes to ms m_refreshTimer = new System.Timers.Timer(); m_refreshTimer.Enabled = true; m_refreshTimer.AutoReset = true; m_refreshTimer.Interval = m_refreshtime; m_refreshTimer.Elapsed += new ElapsedEventHandler(HandleMaptileRefresh); m_log.InfoFormat("[MAP IMAGE SERVICE MODULE]: enabled with refresh time {0} min and service object {1}", refreshminutes, service); } else { m_log.InfoFormat("[MAP IMAGE SERVICE MODULE]: enabled with no refresh and service object {0}", service); } m_enabled = true; } ///<summary> /// ///</summary> public void AddRegion(Scene scene) { if (!m_enabled) return; // Every shared region module has to maintain an indepedent list of // currently running regions lock (m_scenes) m_scenes[scene.RegionInfo.RegionID] = scene; // v2 Map generation on startup is now handled by scene to allow bmp to be shared with // v1 service and not generate map tiles twice as was previous behavior //scene.EventManager.OnRegionReadyStatusChange += s => { if (s.Ready) UploadMapTile(s); }; scene.RegisterModuleInterface<IMapImageUploadModule>(this); } ///<summary> /// ///</summary> public void RemoveRegion(Scene scene) { if (! m_enabled) return; lock (m_scenes) m_scenes.Remove(scene.RegionInfo.RegionID); } #endregion ISharedRegionModule ///<summary> /// ///</summary> private void HandleMaptileRefresh(object sender, EventArgs ea) { // this approach is a bit convoluted becase we want to wait for the // first upload to happen on startup but after all the objects are // loaded and initialized if (m_lastrefresh > 0 && Util.EnvironmentTickCountSubtract(m_lastrefresh) < m_refreshtime) return; m_log.DebugFormat("[MAP IMAGE SERVICE MODULE]: map refresh!"); lock (m_scenes) { foreach (IScene scene in m_scenes.Values) { try { UploadMapTile(scene); } catch (Exception ex) { m_log.WarnFormat("[MAP IMAGE SERVICE MODULE]: something bad happened {0}", ex.Message); } } } m_lastrefresh = Util.EnvironmentTickCount(); } public void UploadMapTile(IScene scene, Bitmap mapTile) { if (mapTile == null) { m_log.WarnFormat("{0} Cannot upload null image", LogHeader); return; } m_log.DebugFormat("{0} Upload maptile for {1}", LogHeader, scene.Name); // mapTile.Save( // DEBUG DEBUG // String.Format("maptiles/raw-{0}-{1}-{2}.jpg", regionName, scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY), // ImageFormat.Jpeg); // If the region/maptile is legacy sized, just upload the one tile like it has always been done if (mapTile.Width == Constants.RegionSize && mapTile.Height == Constants.RegionSize) { ConvertAndUploadMaptile(scene, mapTile, scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY, scene.RegionInfo.RegionName); } else { // For larger regions (varregion) we must cut the region image into legacy sized // pieces since that is how the maptile system works. // Note the assumption that varregions are always a multiple of legacy size. for (uint xx = 0; xx < mapTile.Width; xx += Constants.RegionSize) { for (uint yy = 0; yy < mapTile.Height; yy += Constants.RegionSize) { // Images are addressed from the upper left corner so have to do funny // math to pick out the sub-tile since regions are numbered from // the lower left. Rectangle rect = new Rectangle( (int)xx, mapTile.Height - (int)yy - (int)Constants.RegionSize, (int)Constants.RegionSize, (int)Constants.RegionSize); using (Bitmap subMapTile = mapTile.Clone(rect, mapTile.PixelFormat)) { ConvertAndUploadMaptile(scene, subMapTile, scene.RegionInfo.RegionLocX + (xx / Constants.RegionSize), scene.RegionInfo.RegionLocY + (yy / Constants.RegionSize), scene.Name); } } } } } ///<summary> /// ///</summary> public void UploadMapTile(IScene scene) { m_log.DebugFormat("{0}: upload maptile for {1}", LogHeader, scene.RegionInfo.RegionName); // Create a JPG map tile and upload it to the AddMapTile API IMapImageGenerator tileGenerator = scene.RequestModuleInterface<IMapImageGenerator>(); if (tileGenerator == null) { m_log.WarnFormat("{0} Cannot upload map tile without an ImageGenerator", LogHeader); return; } using (Bitmap mapTile = tileGenerator.CreateMapTile()) { // XXX: The MapImageModule will return a null if the user has chosen not to create map tiles and there // is no static map tile. if (mapTile == null) return; UploadMapTile(scene, mapTile); } } private void ConvertAndUploadMaptile(IScene scene, Image tileImage, uint locX, uint locY, string regionName) { byte[] jpgData = Utils.EmptyBytes; using (MemoryStream stream = new MemoryStream()) { tileImage.Save(stream, ImageFormat.Jpeg); jpgData = stream.ToArray(); } if (jpgData != Utils.EmptyBytes) { string reason = string.Empty; if (!m_MapService.AddMapTile((int)locX, (int)locY, jpgData, scene.RegionInfo.ScopeID, out reason)) { m_log.DebugFormat("{0} Unable to upload tile image for {1} at {2}-{3}: {4}", LogHeader, regionName, locX, locY, reason); } } else { m_log.WarnFormat("{0} Tile image generation failed for region {1}", LogHeader, regionName); } } } }
#nullable disable using System; using System.Drawing; using System.Drawing.Imaging; namespace WWT.Imaging { public struct PixelData { public byte blue; public byte green; public byte red; public byte alpha; public PixelData(int r, int g, int b, int a) // values between 0 and 255 { blue = (byte)(b >= 255 ? 255 : (b < 0 ? 0 : b)); red = (byte)(r >= 255 ? 255 : (r < 0 ? 0 : r)); green = (byte)(g >= 255 ? 255 : (g < 0 ? 0 : g)); alpha = (byte)(a >= 255 ? 255 : (a < 0 ? 0 : a)); } } public unsafe class FastBitmapEnumerator : IDisposable { int x; int y; FastBitmap fastBitmap; PixelData* pCurrentPixel; bool locked; public FastBitmapEnumerator(FastBitmap fastBitmap) { fastBitmap.LockBitmap(); locked = true; this.fastBitmap = fastBitmap; x = -1; y = 0; pCurrentPixel = fastBitmap[x, y]; } public void Dispose() { if (locked) { fastBitmap.UnlockBitmap(); } } public bool MoveNext() { x++; pCurrentPixel++; if (x == fastBitmap.Size.X) { y++; if (y == fastBitmap.Size.Y) { return false; } else { x = 0; pCurrentPixel = fastBitmap[0, y]; //Debug.WriteLine(String.Format("{0}", pCurrentPixel - fastBitmap[0, 0])); } } return true; } public PixelData* Current { get { return pCurrentPixel; } } } /// <summary> /// A bitmap class that allows fast x, y access /// </summary> public unsafe class FastBitmap : IDisposable { Bitmap bitmap; // three elements used for MakeGreyUnsafe int width; BitmapData bitmapData = null; Byte* pBase = null; PixelData* pCurrentPixel = null; int xLocation; int yLocation; Point size; internal bool locked = false; /// <summary> /// Create an instance from an existing bitmap /// </summary> /// <param name="bitmap">The bitmap</param> public FastBitmap(Bitmap bitmap) { this.bitmap = bitmap; GraphicsUnit unit = GraphicsUnit.Pixel; RectangleF bounds = bitmap.GetBounds(ref unit); size = new Point((int)bounds.Width, (int)bounds.Height); } /// <summary> /// Save the bitmap to a file /// </summary> /// <param name="filename">Filename to save the bitmap to</param> public void Save(string filename) { bitmap.Save(filename, ImageFormat.Jpeg); } public void Dispose() { bitmap.Dispose(); } /// <summary> /// Size of the bitmap in pixels /// </summary> public Point Size { get { return size; } } /// <summary> /// The Bitmap object wrapped by this instance /// </summary> public Bitmap Bitmap { get { return (bitmap); } } /// <summary> /// Start at the beginning of the bitmap /// </summary> public void InitCurrentPixel() { LockBitmap(); //if (pBase == null) //{ // throw new InvalidOperationException("Bitmap must be locked before calling InitCurrentPixel()"); // } pCurrentPixel = (PixelData*)pBase; } /// <summary> /// Return the next pixel /// </summary> /// <returns>The next pixel, or null if done</returns> public PixelData* GetNextPixel() { PixelData* pReturnPixel = pCurrentPixel; if (xLocation == size.X) { xLocation = 0; yLocation++; if (yLocation == size.Y) { UnlockBitmap(); return null; } else { pCurrentPixel = this[0, yLocation]; } } else { xLocation++; pCurrentPixel++; } return pReturnPixel; } /// <summary> /// Get the pixel data at a specific x and y location /// </summary> public PixelData* this[int x, int y] { get { return (PixelData*)(pBase + y * width + x * sizeof(PixelData)); } } public FastBitmapEnumerator GetEnumerator() { return new FastBitmapEnumerator(this); } /// <summary> /// Lock the bitmap. /// </summary> public void LockBitmap() { GraphicsUnit unit = GraphicsUnit.Pixel; RectangleF boundsF = bitmap.GetBounds(ref unit); Rectangle bounds = new Rectangle((int)boundsF.X, (int)boundsF.Y, (int)boundsF.Width, (int)boundsF.Height); // Figure out the number of bytes in a row // This is rounded up to be a multiple of 4 // bytes, since a scan line in an image must always be a multiple of 4 bytes // in length. width = (int)boundsF.Width * sizeof(PixelData); if (width % 4 != 0) { width = 4 * (width / 4 + 1); } bitmapData = bitmap.LockBits(bounds, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); pBase = (Byte*)bitmapData.Scan0.ToPointer(); locked = true; } /// <summary> /// Unlock the bitmap /// </summary> public void UnlockBitmap() { bitmap.UnlockBits(bitmapData); bitmapData = null; pBase = null; locked = false; } public PixelData GetFilteredPixel(double xd, double yd) { int x = (int)(xd); double xr = xd - (double)x; int y = (int)(yd); double yr = yd - (double)y; if (x < 0 || x > (bitmap.Width - 1) || y < 0 || y > (bitmap.Height - 1)) { return new PixelData(); } int stepX = 1; int stepY = 1; if (x == bitmap.Width - 1) { stepX = 0; } if (y == bitmap.Height - 1) { stepY = 0; } PixelData* tl = this[x, y]; PixelData* tr = this[x + stepX, y]; PixelData* bl = this[x, y + stepY]; PixelData* br = this[x + stepX, y + stepY]; PixelData result; result.alpha = (byte)((((((double)tl->alpha * (1.0 - xr)) + ((double)tr->alpha * xr))) * (1.0 - yr)) + (((((double)bl->alpha * (1.0 - xr)) + ((double)br->alpha * xr))) * yr)); result.red = (byte)((((((double)tl->red * (1.0 - xr)) + ((double)tr->red * xr))) * (1.0 - yr)) + (((((double)bl->red * (1.0 - xr)) + ((double)br->red * xr))) * yr)); result.green = (byte)((((((double)tl->green * (1.0 - xr)) + ((double)tr->green * xr))) * (1.0 - yr)) + (((((double)bl->green * (1.0 - xr)) + ((double)br->green * xr))) * yr)); result.blue = (byte)((((((double)tl->blue * (1.0 - xr)) + ((double)tr->blue * xr))) * (1.0 - yr)) + (((((double)bl->blue * (1.0 - xr)) + ((double)br->blue * xr))) * yr)); return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Xunit; namespace ShopifySharp.Tests { [Trait("Category", "Product")] public class Product_Tests : IClassFixture<Product_Tests_Fixture> { private Product_Tests_Fixture Fixture { get; } public Product_Tests(Product_Tests_Fixture fixture) { this.Fixture = fixture; } [Fact] public async Task Counts_Products() { var count = await Fixture.Service.CountAsync(); Assert.True(count > 0); } [Fact] public async Task Lists_Products() { var list = await Fixture.Service.ListAsync(); Assert.True(list.Count() > 0); } [Fact] public async Task Deletes_Products() { var created = await Fixture.Create(true); bool threw = false; try { await Fixture.Service.DeleteAsync(created.Id.Value); } catch (ShopifyException ex) { Console.WriteLine($"{nameof(Deletes_Products)} failed. {ex.Message}"); threw = true; } Assert.False(threw); } [Fact] public async Task Gets_Products() { var obj = await Fixture.Service.GetAsync(Fixture.Created.First().Id.Value); Assert.NotNull(obj); Assert.True(obj.Id.HasValue); Assert.Equal(Fixture.Title, obj.Title); Assert.Equal(Fixture.BodyHtml, obj.BodyHtml); Assert.Equal(Fixture.ProductType, obj.ProductType); Assert.Equal(Fixture.Vendor, obj.Vendor); } [Fact] public async Task Creates_Products() { var obj = await Fixture.Create(); Assert.NotNull(obj); Assert.True(obj.Id.HasValue); Assert.Equal(Fixture.Title, obj.Title); Assert.Equal(Fixture.BodyHtml, obj.BodyHtml); Assert.Equal(Fixture.ProductType, obj.ProductType); Assert.Equal(Fixture.Vendor, obj.Vendor); } [Fact] public async Task Creates_Unpublished_Products() { var created = await Fixture.Create(options: new ProductCreateOptions() { Published = false }); Assert.False(created.PublishedAt.HasValue); } [Fact] public async Task Updates_Products() { string title = "ShopifySharp Updated Test Product"; var created = await Fixture.Create(); long id = created.Id.Value; created.Title = title; created.Id = null; var updated = await Fixture.Service.UpdateAsync(id, created); // Reset the id so the Fixture can properly delete this object. created.Id = id; Assert.Equal(title, updated.Title); } [Fact] public async Task Publishes_Products() { var created = await Fixture.Create(options: new ProductCreateOptions() { Published = false }); var published = await Fixture.Service.PublishAsync(created.Id.Value); Assert.True(published.PublishedAt.HasValue); } [Fact] public async Task Unpublishes_Products() { var created = await Fixture.Create(options: new ProductCreateOptions() { Published = true }); var unpublished = await Fixture.Service.UnpublishAsync(created.Id.Value); Assert.False(unpublished.PublishedAt.HasValue); } } public class Product_Tests_Fixture : IAsyncLifetime { public ProductService Service { get; } = new ProductService(Utils.MyShopifyUrl, Utils.AccessToken); public List<Product> Created { get; } = new List<Product>(); public string Title => "ShopifySharp Test Product"; public string Vendor = "Auntie Dot"; public string BodyHtml => "<strong>This product was created while testing ShopifySharp!</strong>"; public string ProductType => "Foobars"; public async Task InitializeAsync() { // Create one for count, list, get, etc. orders. await Create(); } public async Task DisposeAsync() { foreach (var obj in Created) { try { await Service.DeleteAsync(obj.Id.Value); } catch (ShopifyException ex) { if (ex.HttpStatusCode != HttpStatusCode.NotFound) { Console.WriteLine($"Failed to delete created Product with id {obj.Id.Value}. {ex.Message}"); } } } } /// <summary> /// Convenience function for running tests. Creates an object and automatically adds it to the queue for deleting after tests finish. /// </summary> public async Task<Product> Create(bool skipAddToCreateList = false, ProductCreateOptions options = null) { var obj = await Service.CreateAsync(new Product() { Title = Title, Vendor = Vendor, BodyHtml = BodyHtml, ProductType = ProductType, Handle = Guid.NewGuid().ToString(), Images = new List<ProductImage> { new ProductImage { Attachment = "R0lGODlhAQABAIAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" } }, }, options); if (! skipAddToCreateList) { Created.Add(obj); } return obj; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; #if !netcoreapp using System.Linq; #endif using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using System.IO; namespace System.Data.SqlClient.SNI { /// <summary> /// Managed SNI proxy implementation. Contains many SNI entry points used by SqlClient. /// </summary> internal class SNIProxy { private const int DefaultSqlServerPort = 1433; private const int DefaultSqlServerDacPort = 1434; private const string SqlServerSpnHeader = "MSSQLSvc"; public static readonly SNIProxy Singleton = new SNIProxy(); /// <summary> /// Terminate SNI /// </summary> public void Terminate() { } /// <summary> /// Enable SSL on a connection /// </summary> /// <param name="handle">Connection handle</param> /// <returns>SNI error code</returns> public uint EnableSsl(SNIHandle handle, uint options) { try { return handle.EnableSsl(options); } catch (Exception e) { return SNICommon.ReportSNIError(SNIProviders.SSL_PROV, SNICommon.HandshakeFailureError, e); } } /// <summary> /// Disable SSL on a connection /// </summary> /// <param name="handle">Connection handle</param> /// <returns>SNI error code</returns> public uint DisableSsl(SNIHandle handle) { handle.DisableSsl(); return TdsEnums.SNI_SUCCESS; } /// <summary> /// Generate SSPI context /// </summary> /// <param name="sspiClientContextStatus">SSPI client context status</param> /// <param name="receivedBuff">Receive buffer</param> /// <param name="sendBuff">Send buffer</param> /// <param name="serverName">Service Principal Name buffer</param> /// <returns>SNI error code</returns> public void GenSspiClientContext(SspiClientContextStatus sspiClientContextStatus, byte[] receivedBuff, ref byte[] sendBuff, byte[] serverName) { SafeDeleteContext securityContext = sspiClientContextStatus.SecurityContext; ContextFlagsPal contextFlags = sspiClientContextStatus.ContextFlags; SafeFreeCredentials credentialsHandle = sspiClientContextStatus.CredentialsHandle; string securityPackage = NegotiationInfoClass.Negotiate; if (securityContext == null) { credentialsHandle = NegotiateStreamPal.AcquireDefaultCredential(securityPackage, false); } int tokenSize = NegotiateStreamPal.QueryMaxTokenSize(securityPackage); byte[] resultToken = new byte[tokenSize]; ContextFlagsPal requestedContextFlags = ContextFlagsPal.Connection | ContextFlagsPal.Confidentiality | ContextFlagsPal.Delegate | ContextFlagsPal.MutualAuth; string serverSPN = System.Text.Encoding.UTF8.GetString(serverName); SecurityStatusPal statusCode = NegotiateStreamPal.InitializeSecurityContext( ref credentialsHandle, ref securityContext, serverSPN, requestedContextFlags, receivedBuff, null, ref resultToken, ref contextFlags); if (statusCode.ErrorCode == SecurityStatusPalErrorCode.CompleteNeeded || statusCode.ErrorCode == SecurityStatusPalErrorCode.CompAndContinue) { statusCode = NegotiateStreamPal.CompleteAuthToken(ref securityContext, resultToken); resultToken = null; } sendBuff = resultToken; if (sendBuff == null) { sendBuff = Array.Empty<byte>(); } sspiClientContextStatus.SecurityContext = securityContext; sspiClientContextStatus.ContextFlags = contextFlags; sspiClientContextStatus.CredentialsHandle = credentialsHandle; if (IsErrorStatus(statusCode.ErrorCode)) { // Could not access Kerberos Ticket. // // SecurityStatusPalErrorCode.InternalError only occurs in Unix and always comes with a GssApiException, // so we don't need to check for a GssApiException here. if (statusCode.ErrorCode == SecurityStatusPalErrorCode.InternalError) { throw new InvalidOperationException(SQLMessage.KerberosTicketMissingError() + "\n" + statusCode); } else { throw new InvalidOperationException(SQLMessage.SSPIGenerateError() + "\n" + statusCode); } } } private static bool IsErrorStatus(SecurityStatusPalErrorCode errorCode) { return errorCode != SecurityStatusPalErrorCode.NotSet && errorCode != SecurityStatusPalErrorCode.OK && errorCode != SecurityStatusPalErrorCode.ContinueNeeded && errorCode != SecurityStatusPalErrorCode.CompleteNeeded && errorCode != SecurityStatusPalErrorCode.CompAndContinue && errorCode != SecurityStatusPalErrorCode.ContextExpired && errorCode != SecurityStatusPalErrorCode.CredentialsNeeded && errorCode != SecurityStatusPalErrorCode.Renegotiate; } /// <summary> /// Initialize SSPI /// </summary> /// <param name="maxLength">Max length of SSPI packet</param> /// <returns>SNI error code</returns> public uint InitializeSspiPackage(ref uint maxLength) { throw new PlatformNotSupportedException(); } /// <summary> /// Set connection buffer size /// </summary> /// <param name="handle">SNI handle</param> /// <param name="bufferSize">Buffer size</param> /// <returns>SNI error code</returns> public uint SetConnectionBufferSize(SNIHandle handle, uint bufferSize) { handle.SetBufferSize((int)bufferSize); return TdsEnums.SNI_SUCCESS; } /// <summary> /// Copies data in SNIPacket to given byte array parameter /// </summary> /// <param name="packet">SNIPacket object containing data packets</param> /// <param name="inBuff">Destination byte array where data packets are copied to</param> /// <param name="dataSize">Length of data packets</param> /// <returns>SNI error status</returns> public uint PacketGetData(SNIPacket packet, byte[] inBuff, ref uint dataSize) { int dataSizeInt = 0; packet.GetData(inBuff, ref dataSizeInt); dataSize = (uint)dataSizeInt; return TdsEnums.SNI_SUCCESS; } /// <summary> /// Read synchronously /// </summary> /// <param name="handle">SNI handle</param> /// <param name="packet">SNI packet</param> /// <param name="timeout">Timeout</param> /// <returns>SNI error status</returns> public uint ReadSyncOverAsync(SNIHandle handle, out SNIPacket packet, int timeout) { return handle.Receive(out packet, timeout); } /// <summary> /// Get SNI connection ID /// </summary> /// <param name="handle">SNI handle</param> /// <param name="clientConnectionId">Client connection ID</param> /// <returns>SNI error status</returns> public uint GetConnectionId(SNIHandle handle, ref Guid clientConnectionId) { clientConnectionId = handle.ConnectionId; return TdsEnums.SNI_SUCCESS; } /// <summary> /// Send a packet /// </summary> /// <param name="handle">SNI handle</param> /// <param name="packet">SNI packet</param> /// <param name="sync">true if synchronous, false if asynchronous</param> /// <returns>SNI error status</returns> public uint WritePacket(SNIHandle handle, SNIPacket packet, bool sync) { SNIPacket clonedPacket = packet.Clone(); uint result; if (sync) { result = handle.Send(clonedPacket); clonedPacket.Dispose(); } else { result = handle.SendAsync(clonedPacket, true); } return result; } /// <summary> /// Create a SNI connection handle /// </summary> /// <param name="callbackObject">Asynchronous I/O callback object</param> /// <param name="fullServerName">Full server name from connection string</param> /// <param name="ignoreSniOpenTimeout">Ignore open timeout</param> /// <param name="timerExpire">Timer expiration</param> /// <param name="instanceName">Instance name</param> /// <param name="spnBuffer">SPN</param> /// <param name="flushCache">Flush packet cache</param> /// <param name="async">Asynchronous connection</param> /// <param name="parallel">Attempt parallel connects</param> /// <returns>SNI handle</returns> public SNIHandle CreateConnectionHandle(object callbackObject, string fullServerName, bool ignoreSniOpenTimeout, long timerExpire, out byte[] instanceName, ref byte[] spnBuffer, bool flushCache, bool async, bool parallel, bool isIntegratedSecurity) { instanceName = new byte[1]; bool errorWithLocalDBProcessing; string localDBDataSource = GetLocalDBDataSource(fullServerName, out errorWithLocalDBProcessing); if (errorWithLocalDBProcessing) { return null; } // If a localDB Data source is available, we need to use it. fullServerName = localDBDataSource ?? fullServerName; DataSource details = DataSource.ParseServerName(fullServerName); if (details == null) { return null; } SNIHandle sniHandle = null; switch (details.ConnectionProtocol) { case DataSource.Protocol.Admin: case DataSource.Protocol.None: // default to using tcp if no protocol is provided case DataSource.Protocol.TCP: sniHandle = CreateTcpHandle(details, timerExpire, callbackObject, parallel); break; case DataSource.Protocol.NP: sniHandle = CreateNpHandle(details, timerExpire, callbackObject, parallel); break; default: Debug.Fail($"Unexpected connection protocol: {details.ConnectionProtocol}"); break; } if (isIntegratedSecurity) { try { spnBuffer = GetSqlServerSPN(details); } catch (Exception e) { SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, SNICommon.ErrorSpnLookup, e); } } return sniHandle; } private static byte[] GetSqlServerSPN(DataSource dataSource) { Debug.Assert(!string.IsNullOrWhiteSpace(dataSource.ServerName)); string hostName = dataSource.ServerName; string postfix = null; if (dataSource.Port != -1) { postfix = dataSource.Port.ToString(); } else if (!string.IsNullOrWhiteSpace(dataSource.InstanceName)) { postfix = dataSource.InstanceName; } // For handling tcp:<hostname> format else if (dataSource.ConnectionProtocol == DataSource.Protocol.TCP) { postfix = DefaultSqlServerPort.ToString(); } return GetSqlServerSPN(hostName, postfix); } private static byte[] GetSqlServerSPN(string hostNameOrAddress, string portOrInstanceName) { Debug.Assert(!string.IsNullOrWhiteSpace(hostNameOrAddress)); IPHostEntry hostEntry = null; string fullyQualifiedDomainName; try { hostEntry = Dns.GetHostEntry(hostNameOrAddress); } catch (SocketException) { // A SocketException can occur while resolving the hostname. // We will fallback on using hostname from the connection string in the finally block } finally { // If the DNS lookup failed, then resort to using the user provided hostname to construct the SPN. fullyQualifiedDomainName = hostEntry?.HostName ?? hostNameOrAddress; } string serverSpn = SqlServerSpnHeader + "/" + fullyQualifiedDomainName; if (!string.IsNullOrWhiteSpace(portOrInstanceName)) { serverSpn += ":" + portOrInstanceName; } return Encoding.UTF8.GetBytes(serverSpn); } /// <summary> /// Creates an SNITCPHandle object /// </summary> /// <param name="details">Data source</param> /// <param name="timerExpire">Timer expiration</param> /// <param name="callbackObject">Asynchronous I/O callback object</param> /// <param name="parallel">Should MultiSubnetFailover be used</param> /// <returns>SNITCPHandle</returns> private SNITCPHandle CreateTcpHandle(DataSource details, long timerExpire, object callbackObject, bool parallel) { // TCP Format: // tcp:<host name>\<instance name> // tcp:<host name>,<TCP/IP port number> string hostName = details.ServerName; if (string.IsNullOrWhiteSpace(hostName)) { SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.TCP_PROV, 0, SNICommon.InvalidConnStringError, string.Empty); return null; } int port = -1; bool isAdminConnection = details.ConnectionProtocol == DataSource.Protocol.Admin; if (details.IsSsrpRequired) { try { port = isAdminConnection ? SSRP.GetDacPortByInstanceName(hostName, details.InstanceName) : SSRP.GetPortByInstanceName(hostName, details.InstanceName); } catch (SocketException se) { SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.TCP_PROV, SNICommon.InvalidConnStringError, se); return null; } } else if (details.Port != -1) { port = details.Port; } else { port = isAdminConnection ? DefaultSqlServerDacPort : DefaultSqlServerPort; } return new SNITCPHandle(hostName, port, timerExpire, callbackObject, parallel); } /// <summary> /// Creates an SNINpHandle object /// </summary> /// <param name="details">Data source</param> /// <param name="timerExpire">Timer expiration</param> /// <param name="callbackObject">Asynchronous I/O callback object</param> /// <param name="parallel">Should MultiSubnetFailover be used. Only returns an error for named pipes.</param> /// <returns>SNINpHandle</returns> private SNINpHandle CreateNpHandle(DataSource details, long timerExpire, object callbackObject, bool parallel) { if (parallel) { SNICommon.ReportSNIError(SNIProviders.NP_PROV, 0, SNICommon.MultiSubnetFailoverWithNonTcpProtocol, string.Empty); return null; } return new SNINpHandle(details.PipeHostName, details.PipeName, timerExpire, callbackObject); } /// <summary> /// Read packet asynchronously /// </summary> /// <param name="handle">SNI handle</param> /// <param name="packet">Packet</param> /// <returns>SNI error status</returns> public uint ReadAsync(SNIHandle handle, out SNIPacket packet) { packet = null; return handle.ReceiveAsync(ref packet); } /// <summary> /// Set packet data /// </summary> /// <param name="packet">SNI packet</param> /// <param name="data">Data</param> /// <param name="length">Length</param> public void PacketSetData(SNIPacket packet, byte[] data, int length) { packet.SetData(data, length); } /// <summary> /// Release packet /// </summary> /// <param name="packet">SNI packet</param> public void PacketRelease(SNIPacket packet) { packet.Release(); } /// <summary> /// Check SNI handle connection /// </summary> /// <param name="handle"></param> /// <returns>SNI error status</returns> public uint CheckConnection(SNIHandle handle) { return handle.CheckConnection(); } /// <summary> /// Get last SNI error on this thread /// </summary> /// <returns></returns> public SNIError GetLastError() { return SNILoadHandle.SingletonInstance.LastError; } /// <summary> /// Gets the Local db Named pipe data source if the input is a localDB server. /// </summary> /// <param name="fullServerName">The data source</param> /// <param name="error">Set true when an error occurred while getting LocalDB up</param> /// <returns></returns> private string GetLocalDBDataSource(string fullServerName, out bool error) { string localDBConnectionString = null; bool isBadLocalDBDataSource; string localDBInstance = DataSource.GetLocalDBInstance(fullServerName, out isBadLocalDBDataSource); if (isBadLocalDBDataSource) { error = true; return null; } else if (!string.IsNullOrEmpty(localDBInstance)) { // We have successfully received a localDBInstance which is valid. Debug.Assert(!string.IsNullOrWhiteSpace(localDBInstance), "Local DB Instance name cannot be empty."); localDBConnectionString = LocalDB.GetLocalDBConnectionString(localDBInstance); if (fullServerName == null) { // The Last error is set in LocalDB.GetLocalDBConnectionString. We don't need to set Last here. error = true; return null; } } error = false; return localDBConnectionString; } } internal class DataSource { private const char CommaSeparator = ','; private const char BackSlashSeparator = '\\'; private const string DefaultHostName = "localhost"; private const string DefaultSqlServerInstanceName = "mssqlserver"; private const string PipeBeginning = @"\\"; private const string PipeToken = "pipe"; private const string LocalDbHost = "(localdb)"; private const string NamedPipeInstanceNameHeader = "mssql$"; private const string DefaultPipeName = "sql\\query"; internal enum Protocol { TCP, NP, None, Admin }; internal Protocol ConnectionProtocol = Protocol.None; /// <summary> /// Provides the HostName of the server to connect to for TCP protocol. /// This information is also used for finding the SPN of SqlServer /// </summary> internal string ServerName { get; private set; } /// <summary> /// Provides the port on which the TCP connection should be made if one was specified in Data Source /// </summary> internal int Port { get; private set; } = -1; /// <summary> /// Provides the inferred Instance Name from Server Data Source /// </summary> public string InstanceName { get; internal set; } /// <summary> /// Provides the pipe name in case of Named Pipes /// </summary> public string PipeName { get; internal set; } /// <summary> /// Provides the HostName to connect to in case of Named pipes Data Source /// </summary> public string PipeHostName { get; internal set; } private string _workingDataSource; private string _dataSourceAfterTrimmingProtocol; internal bool IsBadDataSource { get; private set; } = false; internal bool IsSsrpRequired { get; private set; } = false; private DataSource(string dataSource) { // Remove all whitespaces from the datasource and all operations will happen on lower case. _workingDataSource = dataSource.Trim().ToLowerInvariant(); int firstIndexOfColon = _workingDataSource.IndexOf(':'); PopulateProtocol(); _dataSourceAfterTrimmingProtocol = (firstIndexOfColon > -1) && ConnectionProtocol != DataSource.Protocol.None ? _workingDataSource.Substring(firstIndexOfColon + 1).Trim() : _workingDataSource; // Pipe paths only allow back slashes #if netcoreapp if (_dataSourceAfterTrimmingProtocol.Contains('/')) // string.Contains(char) is .NetCore2.1+ specific #else if (_dataSourceAfterTrimmingProtocol.Contains("/")) #endif { if (ConnectionProtocol == DataSource.Protocol.None) ReportSNIError(SNIProviders.INVALID_PROV); else if (ConnectionProtocol == DataSource.Protocol.NP) ReportSNIError(SNIProviders.NP_PROV); else if (ConnectionProtocol == DataSource.Protocol.TCP) ReportSNIError(SNIProviders.TCP_PROV); } } private void PopulateProtocol() { string[] splitByColon = _workingDataSource.Split(':'); if (splitByColon.Length <= 1) { ConnectionProtocol = DataSource.Protocol.None; } else { // We trim before switching because " tcp : server , 1433 " is a valid data source switch (splitByColon[0].Trim()) { case TdsEnums.TCP: ConnectionProtocol = DataSource.Protocol.TCP; break; case TdsEnums.NP: ConnectionProtocol = DataSource.Protocol.NP; break; case TdsEnums.ADMIN: ConnectionProtocol = DataSource.Protocol.Admin; break; default: // None of the supported protocols were found. This may be a IPv6 address ConnectionProtocol = DataSource.Protocol.None; break; } } } public static string GetLocalDBInstance(string dataSource, out bool error) { string instanceName = null; string workingDataSource = dataSource.ToLowerInvariant(); string[] tokensByBackSlash = workingDataSource.Split(BackSlashSeparator); error = false; // All LocalDb endpoints are of the format host\instancename where host is always (LocalDb) (case-insensitive) if (tokensByBackSlash.Length == 2 && LocalDbHost.Equals(tokensByBackSlash[0].TrimStart())) { if (!string.IsNullOrWhiteSpace(tokensByBackSlash[1])) { instanceName = tokensByBackSlash[1].Trim(); } else { SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, SNICommon.LocalDBNoInstanceName, string.Empty); error = true; return null; } } return instanceName; } public static DataSource ParseServerName(string dataSource) { DataSource details = new DataSource(dataSource); if (details.IsBadDataSource) { return null; } if (details.InferNamedPipesInformation()) { return details; } if (details.IsBadDataSource) { return null; } if (details.InferConnectionDetails()) { return details; } return null; } private void InferLocalServerName() { // If Server name is empty or localhost, then use "localhost" if (string.IsNullOrEmpty(ServerName) || IsLocalHost(ServerName)) { ServerName = ConnectionProtocol == DataSource.Protocol.Admin ? Environment.MachineName : DefaultHostName; } } private bool InferConnectionDetails() { string[] tokensByCommaAndSlash = _dataSourceAfterTrimmingProtocol.Split(BackSlashSeparator, ','); ServerName = tokensByCommaAndSlash[0].Trim(); int commaIndex = _dataSourceAfterTrimmingProtocol.IndexOf(','); int backSlashIndex = _dataSourceAfterTrimmingProtocol.IndexOf(BackSlashSeparator); // Check the parameters. The parameters are Comma separated in the Data Source. The parameter we really care about is the port // If Comma exists, the try to get the port number if (commaIndex > -1) { string parameter = backSlashIndex > -1 ? ((commaIndex > backSlashIndex) ? tokensByCommaAndSlash[2].Trim() : tokensByCommaAndSlash[1].Trim()) : tokensByCommaAndSlash[1].Trim(); // Bad Data Source like "server, " if (string.IsNullOrEmpty(parameter)) { ReportSNIError(SNIProviders.INVALID_PROV); return false; } // For Tcp and Only Tcp are parameters allowed. if (ConnectionProtocol == DataSource.Protocol.None) { ConnectionProtocol = DataSource.Protocol.TCP; } else if (ConnectionProtocol != DataSource.Protocol.TCP) { // Parameter has been specified for non-TCP protocol. This is not allowed. ReportSNIError(SNIProviders.INVALID_PROV); return false; } int port; if (!int.TryParse(parameter, out port)) { ReportSNIError(SNIProviders.TCP_PROV); return false; } // If the user explicitly specified a invalid port in the connection string. if (port < 1) { ReportSNIError(SNIProviders.TCP_PROV); return false; } Port = port; } // Instance Name Handling. Only if we found a '\' and we did not find a port in the Data Source else if (backSlashIndex > -1) { // This means that there will not be any part separated by comma. InstanceName = tokensByCommaAndSlash[1].Trim(); if (string.IsNullOrWhiteSpace(InstanceName)) { ReportSNIError(SNIProviders.INVALID_PROV); return false; } if (DefaultSqlServerInstanceName.Equals(InstanceName)) { ReportSNIError(SNIProviders.INVALID_PROV); return false; } IsSsrpRequired = true; } InferLocalServerName(); return true; } private void ReportSNIError(SNIProviders provider) { SNILoadHandle.SingletonInstance.LastError = new SNIError(provider, 0, SNICommon.InvalidConnStringError, string.Empty); IsBadDataSource = true; } private bool InferNamedPipesInformation() { // If we have a datasource beginning with a pipe or we have already determined that the protocol is Named Pipe if (_dataSourceAfterTrimmingProtocol.StartsWith(PipeBeginning) || ConnectionProtocol == Protocol.NP) { // If the data source is "np:servername" if (!_dataSourceAfterTrimmingProtocol.Contains(BackSlashSeparator)) // string.Contains(char) is .NetCore2.1+ specific. Else uses Linq (perf warning) { PipeHostName = ServerName = _dataSourceAfterTrimmingProtocol; InferLocalServerName(); PipeName = SNINpHandle.DefaultPipePath; return true; } try { string[] tokensByBackSlash = _dataSourceAfterTrimmingProtocol.Split(BackSlashSeparator); // The datasource is of the format \\host\pipe\sql\query [0]\[1]\[2]\[3]\[4]\[5] // It would at least have 6 parts. // Another valid Sql named pipe for an named instance is \\.\pipe\MSSQL$MYINSTANCE\sql\query if (tokensByBackSlash.Length < 6) { ReportSNIError(SNIProviders.NP_PROV); return false; } string host = tokensByBackSlash[2]; if (string.IsNullOrEmpty(host)) { ReportSNIError(SNIProviders.NP_PROV); return false; } //Check if the "pipe" keyword is the first part of path if (!PipeToken.Equals(tokensByBackSlash[3])) { ReportSNIError(SNIProviders.NP_PROV); return false; } if (tokensByBackSlash[4].StartsWith(NamedPipeInstanceNameHeader)) { InstanceName = tokensByBackSlash[4].Substring(NamedPipeInstanceNameHeader.Length); } StringBuilder pipeNameBuilder = new StringBuilder(); for (int i = 4; i < tokensByBackSlash.Length - 1; i++) { pipeNameBuilder.Append(tokensByBackSlash[i]); pipeNameBuilder.Append(Path.DirectorySeparatorChar); } // Append the last part without a "/" pipeNameBuilder.Append(tokensByBackSlash[tokensByBackSlash.Length - 1]); PipeName = pipeNameBuilder.ToString(); if (string.IsNullOrWhiteSpace(InstanceName) && !DefaultPipeName.Equals(PipeName)) { InstanceName = PipeToken + PipeName; } ServerName = IsLocalHost(host) ? Environment.MachineName : host; // Pipe hostname is the hostname after leading \\ which should be passed down as is to open Named Pipe. // For Named Pipes the ServerName makes sense for SPN creation only. PipeHostName = host; } catch (UriFormatException) { ReportSNIError(SNIProviders.NP_PROV); return false; } // DataSource is something like "\\pipename" if (ConnectionProtocol == DataSource.Protocol.None) { ConnectionProtocol = DataSource.Protocol.NP; } else if (ConnectionProtocol != DataSource.Protocol.NP) { // In case the path began with a "\\" and protocol was not Named Pipes ReportSNIError(SNIProviders.NP_PROV); return false; } return true; } return false; } private static bool IsLocalHost(string serverName) => ".".Equals(serverName) || "(local)".Equals(serverName) || "localhost".Equals(serverName); } }
using System; using System.Linq; using System.Runtime.InteropServices; using Torque6.Engine.SimObjects; using Torque6.Engine.SimObjects.Scene; using Torque6.Engine.Namespaces; using Torque6.Utility; namespace Torque6.Engine.SimObjects.GuiControls { public unsafe class GuiEditCtrl : GuiControl { public GuiEditCtrl() { ObjectPtr = Sim.WrapObject(InternalUnsafeMethods.GuiEditCtrlCreateInstance()); } public GuiEditCtrl(uint pId) : base(pId) { } public GuiEditCtrl(string pName) : base(pName) { } public GuiEditCtrl(IntPtr pObjPtr) : base(pObjPtr) { } public GuiEditCtrl(Sim.SimObjectPtr* pObjPtr) : base(pObjPtr) { } public GuiEditCtrl(SimObject pObj) : base(pObj) { } #region UnsafeNativeMethods new internal struct InternalUnsafeMethods { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _GuiEditCtrlCreateInstance(); private static _GuiEditCtrlCreateInstance _GuiEditCtrlCreateInstanceFunc; internal static IntPtr GuiEditCtrlCreateInstance() { if (_GuiEditCtrlCreateInstanceFunc == null) { _GuiEditCtrlCreateInstanceFunc = (_GuiEditCtrlCreateInstance)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiEditCtrlCreateInstance"), typeof(_GuiEditCtrlCreateInstance)); } return _GuiEditCtrlCreateInstanceFunc(); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiEditCtrlSetRoot(IntPtr ctrl, IntPtr root); private static _GuiEditCtrlSetRoot _GuiEditCtrlSetRootFunc; internal static void GuiEditCtrlSetRoot(IntPtr ctrl, IntPtr root) { if (_GuiEditCtrlSetRootFunc == null) { _GuiEditCtrlSetRootFunc = (_GuiEditCtrlSetRoot)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiEditCtrlSetRoot"), typeof(_GuiEditCtrlSetRoot)); } _GuiEditCtrlSetRootFunc(ctrl, root); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiEditCtrlAddNewCtrl(IntPtr ctrl, IntPtr root); private static _GuiEditCtrlAddNewCtrl _GuiEditCtrlAddNewCtrlFunc; internal static void GuiEditCtrlAddNewCtrl(IntPtr ctrl, IntPtr root) { if (_GuiEditCtrlAddNewCtrlFunc == null) { _GuiEditCtrlAddNewCtrlFunc = (_GuiEditCtrlAddNewCtrl)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiEditCtrlAddNewCtrl"), typeof(_GuiEditCtrlAddNewCtrl)); } _GuiEditCtrlAddNewCtrlFunc(ctrl, root); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiEditCtrlAddSelection(IntPtr ctrl, int ctrlID); private static _GuiEditCtrlAddSelection _GuiEditCtrlAddSelectionFunc; internal static void GuiEditCtrlAddSelection(IntPtr ctrl, int ctrlID) { if (_GuiEditCtrlAddSelectionFunc == null) { _GuiEditCtrlAddSelectionFunc = (_GuiEditCtrlAddSelection)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiEditCtrlAddSelection"), typeof(_GuiEditCtrlAddSelection)); } _GuiEditCtrlAddSelectionFunc(ctrl, ctrlID); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiEditCtrlRemoveSelection(IntPtr ctrl, int ctrlID); private static _GuiEditCtrlRemoveSelection _GuiEditCtrlRemoveSelectionFunc; internal static void GuiEditCtrlRemoveSelection(IntPtr ctrl, int ctrlID) { if (_GuiEditCtrlRemoveSelectionFunc == null) { _GuiEditCtrlRemoveSelectionFunc = (_GuiEditCtrlRemoveSelection)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiEditCtrlRemoveSelection"), typeof(_GuiEditCtrlRemoveSelection)); } _GuiEditCtrlRemoveSelectionFunc(ctrl, ctrlID); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiEditCtrlClearSelection(IntPtr ctrl); private static _GuiEditCtrlClearSelection _GuiEditCtrlClearSelectionFunc; internal static void GuiEditCtrlClearSelection(IntPtr ctrl) { if (_GuiEditCtrlClearSelectionFunc == null) { _GuiEditCtrlClearSelectionFunc = (_GuiEditCtrlClearSelection)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiEditCtrlClearSelection"), typeof(_GuiEditCtrlClearSelection)); } _GuiEditCtrlClearSelectionFunc(ctrl); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiEditCtrlSelect(IntPtr ctrl, IntPtr selCtrl); private static _GuiEditCtrlSelect _GuiEditCtrlSelectFunc; internal static void GuiEditCtrlSelect(IntPtr ctrl, IntPtr selCtrl) { if (_GuiEditCtrlSelectFunc == null) { _GuiEditCtrlSelectFunc = (_GuiEditCtrlSelect)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiEditCtrlSelect"), typeof(_GuiEditCtrlSelect)); } _GuiEditCtrlSelectFunc(ctrl, selCtrl); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiEditCtrlSetCurrentAddSet(IntPtr ctrl, IntPtr selCtrl); private static _GuiEditCtrlSetCurrentAddSet _GuiEditCtrlSetCurrentAddSetFunc; internal static void GuiEditCtrlSetCurrentAddSet(IntPtr ctrl, IntPtr selCtrl) { if (_GuiEditCtrlSetCurrentAddSetFunc == null) { _GuiEditCtrlSetCurrentAddSetFunc = (_GuiEditCtrlSetCurrentAddSet)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiEditCtrlSetCurrentAddSet"), typeof(_GuiEditCtrlSetCurrentAddSet)); } _GuiEditCtrlSetCurrentAddSetFunc(ctrl, selCtrl); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _GuiEditCtrlGetCurrentAddSet(IntPtr ctrl); private static _GuiEditCtrlGetCurrentAddSet _GuiEditCtrlGetCurrentAddSetFunc; internal static IntPtr GuiEditCtrlGetCurrentAddSet(IntPtr ctrl) { if (_GuiEditCtrlGetCurrentAddSetFunc == null) { _GuiEditCtrlGetCurrentAddSetFunc = (_GuiEditCtrlGetCurrentAddSet)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiEditCtrlGetCurrentAddSet"), typeof(_GuiEditCtrlGetCurrentAddSet)); } return _GuiEditCtrlGetCurrentAddSetFunc(ctrl); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiEditCtrlToggle(IntPtr ctrl); private static _GuiEditCtrlToggle _GuiEditCtrlToggleFunc; internal static void GuiEditCtrlToggle(IntPtr ctrl) { if (_GuiEditCtrlToggleFunc == null) { _GuiEditCtrlToggleFunc = (_GuiEditCtrlToggle)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiEditCtrlToggle"), typeof(_GuiEditCtrlToggle)); } _GuiEditCtrlToggleFunc(ctrl); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiEditCtrlJustify(IntPtr ctrl, int mode); private static _GuiEditCtrlJustify _GuiEditCtrlJustifyFunc; internal static void GuiEditCtrlJustify(IntPtr ctrl, int mode) { if (_GuiEditCtrlJustifyFunc == null) { _GuiEditCtrlJustifyFunc = (_GuiEditCtrlJustify)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiEditCtrlJustify"), typeof(_GuiEditCtrlJustify)); } _GuiEditCtrlJustifyFunc(ctrl, mode); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiEditCtrlBringToFront(IntPtr ctrl); private static _GuiEditCtrlBringToFront _GuiEditCtrlBringToFrontFunc; internal static void GuiEditCtrlBringToFront(IntPtr ctrl) { if (_GuiEditCtrlBringToFrontFunc == null) { _GuiEditCtrlBringToFrontFunc = (_GuiEditCtrlBringToFront)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiEditCtrlBringToFront"), typeof(_GuiEditCtrlBringToFront)); } _GuiEditCtrlBringToFrontFunc(ctrl); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiEditCtrlPushToBack(IntPtr ctrl); private static _GuiEditCtrlPushToBack _GuiEditCtrlPushToBackFunc; internal static void GuiEditCtrlPushToBack(IntPtr ctrl) { if (_GuiEditCtrlPushToBackFunc == null) { _GuiEditCtrlPushToBackFunc = (_GuiEditCtrlPushToBack)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiEditCtrlPushToBack"), typeof(_GuiEditCtrlPushToBack)); } _GuiEditCtrlPushToBackFunc(ctrl); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiEditCtrlDeleteSelection(IntPtr ctrl); private static _GuiEditCtrlDeleteSelection _GuiEditCtrlDeleteSelectionFunc; internal static void GuiEditCtrlDeleteSelection(IntPtr ctrl) { if (_GuiEditCtrlDeleteSelectionFunc == null) { _GuiEditCtrlDeleteSelectionFunc = (_GuiEditCtrlDeleteSelection)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiEditCtrlDeleteSelection"), typeof(_GuiEditCtrlDeleteSelection)); } _GuiEditCtrlDeleteSelectionFunc(ctrl); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiEditCtrlMoveSelection(IntPtr ctrl, int deltaX, int deltaY); private static _GuiEditCtrlMoveSelection _GuiEditCtrlMoveSelectionFunc; internal static void GuiEditCtrlMoveSelection(IntPtr ctrl, int deltaX, int deltaY) { if (_GuiEditCtrlMoveSelectionFunc == null) { _GuiEditCtrlMoveSelectionFunc = (_GuiEditCtrlMoveSelection)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiEditCtrlMoveSelection"), typeof(_GuiEditCtrlMoveSelection)); } _GuiEditCtrlMoveSelectionFunc(ctrl, deltaX, deltaY); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiEditCtrlSaveSelection(IntPtr ctrl, string fileName); private static _GuiEditCtrlSaveSelection _GuiEditCtrlSaveSelectionFunc; internal static void GuiEditCtrlSaveSelection(IntPtr ctrl, string fileName) { if (_GuiEditCtrlSaveSelectionFunc == null) { _GuiEditCtrlSaveSelectionFunc = (_GuiEditCtrlSaveSelection)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiEditCtrlSaveSelection"), typeof(_GuiEditCtrlSaveSelection)); } _GuiEditCtrlSaveSelectionFunc(ctrl, fileName); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiEditCtrlLoadSelection(IntPtr ctrl, string fileName); private static _GuiEditCtrlLoadSelection _GuiEditCtrlLoadSelectionFunc; internal static void GuiEditCtrlLoadSelection(IntPtr ctrl, string fileName) { if (_GuiEditCtrlLoadSelectionFunc == null) { _GuiEditCtrlLoadSelectionFunc = (_GuiEditCtrlLoadSelection)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiEditCtrlLoadSelection"), typeof(_GuiEditCtrlLoadSelection)); } _GuiEditCtrlLoadSelectionFunc(ctrl, fileName); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiEditCtrlSelectAll(IntPtr ctrl); private static _GuiEditCtrlSelectAll _GuiEditCtrlSelectAllFunc; internal static void GuiEditCtrlSelectAll(IntPtr ctrl) { if (_GuiEditCtrlSelectAllFunc == null) { _GuiEditCtrlSelectAllFunc = (_GuiEditCtrlSelectAll)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiEditCtrlSelectAll"), typeof(_GuiEditCtrlSelectAll)); } _GuiEditCtrlSelectAllFunc(ctrl); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _GuiEditCtrlGetSelected(IntPtr ctrl); private static _GuiEditCtrlGetSelected _GuiEditCtrlGetSelectedFunc; internal static IntPtr GuiEditCtrlGetSelected(IntPtr ctrl) { if (_GuiEditCtrlGetSelectedFunc == null) { _GuiEditCtrlGetSelectedFunc = (_GuiEditCtrlGetSelected)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiEditCtrlGetSelected"), typeof(_GuiEditCtrlGetSelected)); } return _GuiEditCtrlGetSelectedFunc(ctrl); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _GuiEditCtrlGetTrash(IntPtr ctrl); private static _GuiEditCtrlGetTrash _GuiEditCtrlGetTrashFunc; internal static IntPtr GuiEditCtrlGetTrash(IntPtr ctrl) { if (_GuiEditCtrlGetTrashFunc == null) { _GuiEditCtrlGetTrashFunc = (_GuiEditCtrlGetTrash)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiEditCtrlGetTrash"), typeof(_GuiEditCtrlGetTrash)); } return _GuiEditCtrlGetTrashFunc(ctrl); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _GuiEditCtrlGetUndoManager(IntPtr ctrl); private static _GuiEditCtrlGetUndoManager _GuiEditCtrlGetUndoManagerFunc; internal static IntPtr GuiEditCtrlGetUndoManager(IntPtr ctrl) { if (_GuiEditCtrlGetUndoManagerFunc == null) { _GuiEditCtrlGetUndoManagerFunc = (_GuiEditCtrlGetUndoManager)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiEditCtrlGetUndoManager"), typeof(_GuiEditCtrlGetUndoManager)); } return _GuiEditCtrlGetUndoManagerFunc(ctrl); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiEditCtrlSetSnapToGrid(IntPtr ctrl, uint gridSize); private static _GuiEditCtrlSetSnapToGrid _GuiEditCtrlSetSnapToGridFunc; internal static void GuiEditCtrlSetSnapToGrid(IntPtr ctrl, uint gridSize) { if (_GuiEditCtrlSetSnapToGridFunc == null) { _GuiEditCtrlSetSnapToGridFunc = (_GuiEditCtrlSetSnapToGrid)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiEditCtrlSetSnapToGrid"), typeof(_GuiEditCtrlSetSnapToGrid)); } _GuiEditCtrlSetSnapToGridFunc(ctrl, gridSize); } } #endregion #region Properties #endregion #region Methods public void SetRoot(GuiControl root) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiEditCtrlSetRoot(ObjectPtr->ObjPtr, root.ObjectPtr->ObjPtr); } public void AddNewCtrl(GuiControl root) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiEditCtrlAddNewCtrl(ObjectPtr->ObjPtr, root.ObjectPtr->ObjPtr); } public void AddSelection(int ctrlID) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiEditCtrlAddSelection(ObjectPtr->ObjPtr, ctrlID); } public void RemoveSelection(int ctrlID) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiEditCtrlRemoveSelection(ObjectPtr->ObjPtr, ctrlID); } public void ClearSelection() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiEditCtrlClearSelection(ObjectPtr->ObjPtr); } public void Select(GuiControl selCtrl) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiEditCtrlSelect(ObjectPtr->ObjPtr, selCtrl.ObjectPtr->ObjPtr); } public void SetCurrentAddSet(GuiControl selCtrl) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiEditCtrlSetCurrentAddSet(ObjectPtr->ObjPtr, selCtrl.ObjectPtr->ObjPtr); } public GuiControl GetCurrentAddSet() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return new GuiControl(InternalUnsafeMethods.GuiEditCtrlGetCurrentAddSet(ObjectPtr->ObjPtr)); } public void Toggle() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiEditCtrlToggle(ObjectPtr->ObjPtr); } public void Justify(int mode) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiEditCtrlJustify(ObjectPtr->ObjPtr, mode); } public void BringToFront() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiEditCtrlBringToFront(ObjectPtr->ObjPtr); } public void PushToBack() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiEditCtrlPushToBack(ObjectPtr->ObjPtr); } public void DeleteSelection() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiEditCtrlDeleteSelection(ObjectPtr->ObjPtr); } public void MoveSelection(int deltaX, int deltaY) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiEditCtrlMoveSelection(ObjectPtr->ObjPtr, deltaX, deltaY); } public void SaveSelection(string fileName) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiEditCtrlSaveSelection(ObjectPtr->ObjPtr, fileName); } public void LoadSelection(string fileName) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiEditCtrlLoadSelection(ObjectPtr->ObjPtr, fileName); } public void SelectAll() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiEditCtrlSelectAll(ObjectPtr->ObjPtr); } public SimSet GetSelected() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return new SimSet(InternalUnsafeMethods.GuiEditCtrlGetSelected(ObjectPtr->ObjPtr)); } public SimGroup GetTrash() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return new SimGroup(InternalUnsafeMethods.GuiEditCtrlGetTrash(ObjectPtr->ObjPtr)); } public UndoManager GetUndoManager() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return new UndoManager(InternalUnsafeMethods.GuiEditCtrlGetUndoManager(ObjectPtr->ObjPtr)); } public void SetSnapToGrid(uint gridSize) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiEditCtrlSetSnapToGrid(ObjectPtr->ObjPtr, gridSize); } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace EverlastingStudent.Web.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// Copyright (c) 2007-2014 Joe White // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Text; using DGrok.Framework; using NUnit.Framework; namespace DGrok.Tests { [TestFixture] public class SimpleStatementTests : ParserTestCase { protected override RuleType RuleType { get { return RuleType.SimpleStatement; } } [Test] public void BareInherited() { Assert.That("inherited", ParsesAs("InheritedKeyword |inherited|")); } [Test] public void InheritedExpression() { Assert.That("inherited Foo", ParsesAs( "UnaryOperationNode", " OperatorNode: InheritedKeyword |inherited|", " OperandNode: Identifier |Foo|")); } [Test] public void Assignment() { Assert.That("Foo := 42", ParsesAs( "BinaryOperationNode", " LeftNode: Identifier |Foo|", " OperatorNode: ColonEquals |:=|", " RightNode: Number |42|")); } [Test] public void Goto() { Assert.That("goto 42", ParsesAs( "GotoStatementNode", " GotoKeywordNode: GotoKeyword |goto|", " LabelIdNode: Number |42|")); } [Test] public void Block() { Assert.That("begin end", ParsesAs( "BlockNode", " BeginKeywordNode: BeginKeyword |begin|", " StatementListNode: ListNode", " EndKeywordNode: EndKeyword |end|")); } [Test] public void IfStatement() { Assert.That("if Foo then Bar", ParsesAs( "IfStatementNode", " IfKeywordNode: IfKeyword |if|", " ConditionNode: Identifier |Foo|", " ThenKeywordNode: ThenKeyword |then|", " ThenStatementNode: Identifier |Bar|", " ElseKeywordNode: (none)", " ElseStatementNode: (none)")); } [Test] public void Case() { Assert.That("case Foo of 1: end", ParsesAs( "CaseStatementNode", " CaseKeywordNode: CaseKeyword |case|", " ExpressionNode: Identifier |Foo|", " OfKeywordNode: OfKeyword |of|", " SelectorListNode: ListNode", " Items[0]: CaseSelectorNode", " ValueListNode: ListNode", " Items[0]: DelimitedItemNode", " ItemNode: Number |1|", " DelimiterNode: (none)", " ColonNode: Colon |:|", " StatementNode: (none)", " SemicolonNode: (none)", " ElseKeywordNode: (none)", " ElseStatementListNode: ListNode", " EndKeywordNode: EndKeyword |end|")); } [Test] public void Repeat() { Assert.That("repeat until Doomsday", ParsesAs( "RepeatStatementNode", " RepeatKeywordNode: RepeatKeyword |repeat|", " StatementListNode: ListNode", " UntilKeywordNode: UntilKeyword |until|", " ConditionNode: Identifier |Doomsday|")); } [Test] public void While() { Assert.That("while Foo do Bar", ParsesAs( "WhileStatementNode", " WhileKeywordNode: WhileKeyword |while|", " ConditionNode: Identifier |Foo|", " DoKeywordNode: DoKeyword |do|", " StatementNode: Identifier |Bar|")); } [Test] public void For() { Assert.That("for I := 1 to 42 do", ParsesAs( "ForStatementNode", " ForKeywordNode: ForKeyword |for|", " LoopVariableNode: Identifier |I|", " ColonEqualsNode: ColonEquals |:=|", " StartingValueNode: Number |1|", " DirectionNode: ToKeyword |to|", " EndingValueNode: Number |42|", " DoKeywordNode: DoKeyword |do|", " StatementNode: (none)")); } [Test] public void With() { Assert.That("with Foo do", ParsesAs( "WithStatementNode", " WithKeywordNode: WithKeyword |with|", " ExpressionListNode: ListNode", " Items[0]: DelimitedItemNode", " ItemNode: Identifier |Foo|", " DelimiterNode: (none)", " DoKeywordNode: DoKeyword |do|", " StatementNode: (none)")); } [Test] public void ForIn() { Assert.That("for Obj in List do", ParsesAs( "ForInStatementNode", " ForKeywordNode: ForKeyword |for|", " LoopVariableNode: Identifier |Obj|", " InKeywordNode: InKeyword |in|", " ExpressionNode: Identifier |List|", " DoKeywordNode: DoKeyword |do|", " StatementNode: (none)")); } [Test] public void TryExcept() { Assert.That("try except end", ParsesAs( "TryExceptNode", " TryKeywordNode: TryKeyword |try|", " TryStatementListNode: ListNode", " ExceptKeywordNode: ExceptKeyword |except|", " ExceptionItemListNode: ListNode", " ElseKeywordNode: (none)", " ElseStatementListNode: ListNode", " EndKeywordNode: EndKeyword |end|")); } [Test] public void TryFinally() { Assert.That("try finally end", ParsesAs( "TryFinallyNode", " TryKeywordNode: TryKeyword |try|", " TryStatementListNode: ListNode", " FinallyKeywordNode: FinallyKeyword |finally|", " FinallyStatementListNode: ListNode", " EndKeywordNode: EndKeyword |end|")); } [Test] public void Raise() { Assert.That("raise E", ParsesAs( "RaiseStatementNode", " RaiseKeywordNode: RaiseKeyword |raise|", " ExceptionNode: Identifier |E|", " AtSemikeywordNode: (none)", " AddressNode: (none)")); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; using Azure; using Azure.Storage.Blobs; using Azure.Storage.Blobs.Models; using Microsoft.AspNetCore.DataProtection.Repositories; #pragma warning disable AZC0001 // namespace Azure.Extensions.AspNetCore.DataProtection.Blobs #pragma warning restore { /// <summary> /// An <see cref="IXmlRepository"/> which is backed by Azure Blob Storage. /// </summary> /// <remarks> /// Instances of this type are thread-safe. /// </remarks> internal sealed class AzureBlobXmlRepository : IXmlRepository { private const int ConflictMaxRetries = 5; private static readonly TimeSpan ConflictBackoffPeriod = TimeSpan.FromMilliseconds(200); private static readonly XName RepositoryElementName = "repository"; private static BlobHttpHeaders _blobHttpHeaders = new BlobHttpHeaders() { ContentType = "application/xml; charset=utf-8" }; private readonly Random _random; private BlobData _cachedBlobData; private readonly BlobClient _blobClient; /// <summary> /// Creates a new instance of the <see cref="AzureBlobXmlRepository"/>. /// </summary> /// <param name="blobClient">A <see cref="BlobClient"/> that is connected to the blob we are reading from and writing to.</param> public AzureBlobXmlRepository(BlobClient blobClient) { _random = new Random(); _blobClient = blobClient; } /// <inheritdoc /> public IReadOnlyCollection<XElement> GetAllElements() { // Shunt the work onto a ThreadPool thread so that it's independent of any // existing sync context or other potentially deadlock-causing items. var elements = Task.Run(() => GetAllElementsAsync()).GetAwaiter().GetResult(); return new ReadOnlyCollection<XElement>(elements); } /// <inheritdoc /> public void StoreElement(XElement element, string friendlyName) { if (element == null) { throw new ArgumentNullException(nameof(element)); } // Shunt the work onto a ThreadPool thread so that it's independent of any // existing sync context or other potentially deadlock-causing items. Task.Run(() => StoreElementAsync(element)).GetAwaiter().GetResult(); } private static XDocument CreateDocumentFromBlobData(BlobData blobData) { if (blobData == null || blobData.BlobContents.Length == 0) { return new XDocument(new XElement(RepositoryElementName)); } using var memoryStream = new MemoryStream(blobData.BlobContents); var xmlReaderSettings = new XmlReaderSettings() { DtdProcessing = DtdProcessing.Prohibit, IgnoreProcessingInstructions = true, }; using (var xmlReader = XmlReader.Create(memoryStream, xmlReaderSettings)) { return XDocument.Load(xmlReader); } } private async Task<IList<XElement>> GetAllElementsAsync() { var data = await GetLatestDataAsync().ConfigureAwait(false); // The document will look like this: // // <root> // <child /> // <child /> // ... // </root> // // We want to return the first-level child elements to our caller. var doc = CreateDocumentFromBlobData(data); return doc.Root.Elements().ToList(); } private async Task<BlobData> GetLatestDataAsync() { // Set the appropriate AccessCondition based on what we believe the latest // file contents to be, then make the request. var latestCachedData = Volatile.Read(ref _cachedBlobData); // local ref so field isn't mutated under our feet var requestCondition = (latestCachedData != null) ? new BlobRequestConditions() { IfNoneMatch = latestCachedData.ETag } : null; try { using (var memoryStream = new MemoryStream()) { var response = await _blobClient.DownloadToAsync( destination: memoryStream, conditions: requestCondition).ConfigureAwait(false); if (response.Status == 304) { // 304 Not Modified // Thrown when we already have the latest cached data. // This isn't an error; we'll return our cached copy of the data. return latestCachedData; } // At this point, our original cache either didn't exist or was outdated. // We'll update it now and return the updated value latestCachedData = new BlobData() { BlobContents = memoryStream.ToArray(), ETag = response.Headers.ETag }; } Volatile.Write(ref _cachedBlobData, latestCachedData); } catch (RequestFailedException ex) when (ex.Status == 404) { // 404 Not Found // Thrown when no file exists in storage. // This isn't an error; we'll delete our cached copy of data. latestCachedData = null; Volatile.Write(ref _cachedBlobData, latestCachedData); } return latestCachedData; } private int GetRandomizedBackoffPeriod() { // returns a TimeSpan in the range [0.8, 1.0) * ConflictBackoffPeriod // not used for crypto purposes var multiplier = 0.8 + (_random.NextDouble() * 0.2); return (int) (multiplier * ConflictBackoffPeriod.Ticks); } private async Task StoreElementAsync(XElement element) { // holds the last error in case we need to rethrow it ExceptionDispatchInfo lastError = null; for (var i = 0; i < ConflictMaxRetries; i++) { if (i > 1) { // If multiple conflicts occurred, wait a small period of time before retrying // the operation so that other writers can make forward progress. await Task.Delay(GetRandomizedBackoffPeriod()).ConfigureAwait(false); } if (i > 0) { // If at least one conflict occurred, make sure we have an up-to-date // view of the blob contents. await GetLatestDataAsync().ConfigureAwait(false); } // Merge the new element into the document. If no document exists, // create a new default document and inject this element into it. var latestData = Volatile.Read(ref _cachedBlobData); var doc = CreateDocumentFromBlobData(latestData); doc.Root.Add(element); // Turn this document back into a byte[]. var serializedDoc = new MemoryStream(); doc.Save(serializedDoc, SaveOptions.DisableFormatting); serializedDoc.Position = 0; // Generate the appropriate precondition header based on whether or not // we believe data already exists in storage. BlobRequestConditions requestConditions; if (latestData != null) { requestConditions = new BlobRequestConditions() { IfMatch = latestData.ETag }; } else { requestConditions = new BlobRequestConditions() { IfNoneMatch = ETag.All }; } try { // Send the request up to the server. var response = await _blobClient.UploadAsync( serializedDoc, httpHeaders: _blobHttpHeaders, conditions: requestConditions).ConfigureAwait(false); // If we got this far, success! // We can update the cached view of the remote contents. Volatile.Write(ref _cachedBlobData, new BlobData() { BlobContents = serializedDoc.ToArray(), ETag = response.Value.ETag // was updated by Upload routine }); return; } catch (RequestFailedException ex) when (ex.Status == 409 || ex.Status == 412) { // 409 Conflict // This error is rare but can be thrown in very special circumstances, // such as if the blob in the process of being created. We treat it // as equivalent to 412 for the purposes of retry logic. // 412 Precondition Failed // We'll get this error if another writer updated the repository and we // have an outdated view of its contents. If this occurs, we'll just // refresh our view of the remote contents and try again up to the max // retry limit. lastError = ExceptionDispatchInfo.Capture(ex); } } // if we got this far, something went awry lastError.Throw(); } private sealed class BlobData { internal byte[] BlobContents; internal ETag? ETag; } } }
--- /dev/null 2016-03-07 13:22:00.000000000 -0500 +++ src/System.IO.FileSystem/src/SR.cs 2016-03-07 13:21:49.221160000 -0500 @@ -0,0 +1,558 @@ +using System; +using System.Resources; + +namespace FxResources.System.IO.FileSystem +{ + internal static class SR + { + + } +} + +namespace System +{ + internal static class SR + { + private static ResourceManager s_resourceManager; + + private const String s_resourcesName = "FxResources.System.IO.FileSystem.SR"; + + internal static String Arg_DevicesNotSupported + { + get + { + return SR.GetResourceString("Arg_DevicesNotSupported", null); + } + } + + internal static String Arg_FileIsDirectory_Name + { + get + { + return SR.GetResourceString("Arg_FileIsDirectory_Name", null); + } + } + + internal static String Arg_HandleNotAsync + { + get + { + return SR.GetResourceString("Arg_HandleNotAsync", null); + } + } + + internal static String Arg_HandleNotSync + { + get + { + return SR.GetResourceString("Arg_HandleNotSync", null); + } + } + + internal static String Arg_InvalidFileAttrs + { + get + { + return SR.GetResourceString("Arg_InvalidFileAttrs", null); + } + } + + internal static String Arg_InvalidHandle + { + get + { + return SR.GetResourceString("Arg_InvalidHandle", null); + } + } + + internal static String Arg_InvalidSearchPattern + { + get + { + return SR.GetResourceString("Arg_InvalidSearchPattern", null); + } + } + + internal static String Arg_Path2IsRooted + { + get + { + return SR.GetResourceString("Arg_Path2IsRooted", null); + } + } + + internal static String Arg_PathIsVolume + { + get + { + return SR.GetResourceString("Arg_PathIsVolume", null); + } + } + + internal static String Argument_EmptyFileName + { + get + { + return SR.GetResourceString("Argument_EmptyFileName", null); + } + } + + internal static String Argument_EmptyPath + { + get + { + return SR.GetResourceString("Argument_EmptyPath", null); + } + } + + internal static String Argument_InvalidAppendMode + { + get + { + return SR.GetResourceString("Argument_InvalidAppendMode", null); + } + } + + internal static String Argument_InvalidFileModeAndAccessCombo + { + get + { + return SR.GetResourceString("Argument_InvalidFileModeAndAccessCombo", null); + } + } + + internal static String Argument_InvalidOffLen + { + get + { + return SR.GetResourceString("Argument_InvalidOffLen", null); + } + } + + internal static String Argument_InvalidPathChars + { + get + { + return SR.GetResourceString("Argument_InvalidPathChars", null); + } + } + + internal static String Argument_InvalidSeekOrigin + { + get + { + return SR.GetResourceString("Argument_InvalidSeekOrigin", null); + } + } + + internal static String Argument_InvalidSubPath + { + get + { + return SR.GetResourceString("Argument_InvalidSubPath", null); + } + } + + internal static String Argument_PathEmpty + { + get + { + return SR.GetResourceString("Argument_PathEmpty", null); + } + } + + internal static String Argument_PathFormatNotSupported + { + get + { + return SR.GetResourceString("Argument_PathFormatNotSupported", null); + } + } + + internal static String ArgumentNull_Buffer + { + get + { + return SR.GetResourceString("ArgumentNull_Buffer", null); + } + } + + internal static String ArgumentNull_FileName + { + get + { + return SR.GetResourceString("ArgumentNull_FileName", null); + } + } + + internal static String ArgumentNull_Path + { + get + { + return SR.GetResourceString("ArgumentNull_Path", null); + } + } + + internal static String ArgumentOutOfRange_Enum + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_Enum", null); + } + } + + internal static String ArgumentOutOfRange_FileLengthTooBig + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_FileLengthTooBig", null); + } + } + + internal static String ArgumentOutOfRange_NeedNonNegInt32Range + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_NeedNonNegInt32Range", null); + } + } + + internal static String ArgumentOutOfRange_NeedNonNegNum + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_NeedNonNegNum", null); + } + } + + internal static String ArgumentOutOfRange_NeedPosNum + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_NeedPosNum", null); + } + } + + internal static String IndexOutOfRange_IORaceCondition + { + get + { + return SR.GetResourceString("IndexOutOfRange_IORaceCondition", null); + } + } + + internal static String IO_AlreadyExists_Name + { + get + { + return SR.GetResourceString("IO_AlreadyExists_Name", null); + } + } + + internal static String IO_BindHandleFailed + { + get + { + return SR.GetResourceString("IO_BindHandleFailed", null); + } + } + + internal static String IO_CannotCreateDirectory + { + get + { + return SR.GetResourceString("IO_CannotCreateDirectory", null); + } + } + + internal static String IO_EOF_ReadBeyondEOF + { + get + { + return SR.GetResourceString("IO_EOF_ReadBeyondEOF", null); + } + } + + internal static String IO_FileExists_Name + { + get + { + return SR.GetResourceString("IO_FileExists_Name", null); + } + } + + internal static String IO_FileNotFound + { + get + { + return SR.GetResourceString("IO_FileNotFound", null); + } + } + + internal static String IO_FileNotFound_FileName + { + get + { + return SR.GetResourceString("IO_FileNotFound_FileName", null); + } + } + + internal static String IO_FileStreamHandlePosition + { + get + { + return SR.GetResourceString("IO_FileStreamHandlePosition", null); + } + } + + internal static String IO_FileTooLong2GB + { + get + { + return SR.GetResourceString("IO_FileTooLong2GB", null); + } + } + + internal static String IO_FileTooLongOrHandleNotSync + { + get + { + return SR.GetResourceString("IO_FileTooLongOrHandleNotSync", null); + } + } + + internal static String IO_PathNotFound_NoPathName + { + get + { + return SR.GetResourceString("IO_PathNotFound_NoPathName", null); + } + } + + internal static String IO_PathNotFound_Path + { + get + { + return SR.GetResourceString("IO_PathNotFound_Path", null); + } + } + + internal static String IO_PathTooLong + { + get + { + return SR.GetResourceString("IO_PathTooLong", null); + } + } + + internal static String IO_SeekAppendOverwrite + { + get + { + return SR.GetResourceString("IO_SeekAppendOverwrite", null); + } + } + + internal static String IO_SetLengthAppendTruncate + { + get + { + return SR.GetResourceString("IO_SetLengthAppendTruncate", null); + } + } + + internal static String IO_SharingViolation_File + { + get + { + return SR.GetResourceString("IO_SharingViolation_File", null); + } + } + + internal static String IO_SharingViolation_NoFileName + { + get + { + return SR.GetResourceString("IO_SharingViolation_NoFileName", null); + } + } + + internal static String IO_SourceDestMustBeDifferent + { + get + { + return SR.GetResourceString("IO_SourceDestMustBeDifferent", null); + } + } + + internal static String IO_SourceDestMustHaveSameRoot + { + get + { + return SR.GetResourceString("IO_SourceDestMustHaveSameRoot", null); + } + } + + internal static String IO_SyncOpOnUIThread + { + get + { + return SR.GetResourceString("IO_SyncOpOnUIThread", null); + } + } + + internal static String IO_UnknownFileName + { + get + { + return SR.GetResourceString("IO_UnknownFileName", null); + } + } + + internal static String NotSupported_FileStreamOnNonFiles + { + get + { + return SR.GetResourceString("NotSupported_FileStreamOnNonFiles", null); + } + } + + internal static String NotSupported_UnreadableStream + { + get + { + return SR.GetResourceString("NotSupported_UnreadableStream", null); + } + } + + internal static String NotSupported_UnseekableStream + { + get + { + return SR.GetResourceString("NotSupported_UnseekableStream", null); + } + } + + internal static String NotSupported_UnwritableStream + { + get + { + return SR.GetResourceString("NotSupported_UnwritableStream", null); + } + } + + internal static String ObjectDisposed_FileClosed + { + get + { + return SR.GetResourceString("ObjectDisposed_FileClosed", null); + } + } + + private static ResourceManager ResourceManager + { + get + { + if (SR.s_resourceManager == null) + { + SR.s_resourceManager = new ResourceManager(SR.ResourceType); + } + return SR.s_resourceManager; + } + } + + internal static Type ResourceType + { + get + { + return typeof(FxResources.System.IO.FileSystem.SR); + } + } + + internal static String UnauthorizedAccess_IODenied_NoPathName + { + get + { + return SR.GetResourceString("UnauthorizedAccess_IODenied_NoPathName", null); + } + } + + internal static String UnauthorizedAccess_IODenied_Path + { + get + { + return SR.GetResourceString("UnauthorizedAccess_IODenied_Path", null); + } + } + + internal static String UnknownError_Num + { + get + { + return SR.GetResourceString("UnknownError_Num", null); + } + } + + internal static String Format(String resourceFormat, params Object[] args) + { + if (args == null) + { + return resourceFormat; + } + if (!SR.UsingResourceKeys()) + { + return String.Format(resourceFormat, args); + } + return String.Concat(resourceFormat, String.Join(", ", args)); + } + + internal static String Format(String resourceFormat, Object p1) + { + if (!SR.UsingResourceKeys()) + { + return String.Format(resourceFormat, p1); + } + return String.Join(", ", new Object[] { resourceFormat, p1 }); + } + + internal static String Format(String resourceFormat, Object p1, Object p2) + { + if (!SR.UsingResourceKeys()) + { + return String.Format(resourceFormat, p1, p2); + } + return String.Join(", ", new Object[] { resourceFormat, p1, p2 }); + } + + internal static String Format(String resourceFormat, Object p1, Object p2, Object p3) + { + if (!SR.UsingResourceKeys()) + { + return String.Format(resourceFormat, p1, p2, p3); + } + return String.Join(", ", new Object[] { resourceFormat, p1, p2, p3 }); + } + + internal static String GetResourceString(String resourceKey, String defaultString) + { + String str = null; + try + { + str = SR.ResourceManager.GetString(resourceKey); + } + catch (MissingManifestResourceException missingManifestResourceException) + { + } + if (defaultString != null && resourceKey.Equals(str)) + { + return defaultString; + } + return str; + } + + private static Boolean UsingResourceKeys() + { + return false; + } + } +}
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.txt file at the root of this distribution. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using System; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; using VSPackage = Microsoft.VisualStudio.Project; namespace Microsoft.VisualStudio.Project { /// <summary> /// All public properties on Nodeproperties or derived classes are assumed to be used by Automation by default. /// Set this attribute to false on Properties that should not be visible for Automation. /// </summary> [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class AutomationBrowsableAttribute : System.Attribute { public AutomationBrowsableAttribute(bool browsable) { this.browsable = browsable; } public bool Browsable { get { return this.browsable; } } private bool browsable; } /// <summary> /// Encapsulates BuildAction enumeration /// </summary> public sealed class BuildAction { private readonly string actionName; // BuildAction is immutable, so suppress these messages [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly BuildAction None = new BuildAction("None"); [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly BuildAction Compile = new BuildAction("Compile"); [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly BuildAction Content = new BuildAction("Content"); [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly BuildAction EmbeddedResource = new BuildAction("EmbeddedResource"); [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly BuildAction ApplicationDefinition = new BuildAction("ApplicationDefinition"); [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly BuildAction Page = new BuildAction("Page"); [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly BuildAction Resource = new BuildAction("Resource"); public BuildAction(string actionName) { this.actionName = actionName; } public string Name { get { return this.actionName; } } public override bool Equals(object other) { BuildAction action = other as BuildAction; return action != null && this.actionName == action.actionName; } public override int GetHashCode() { return this.actionName.GetHashCode(); } public BuildActionEnum ToBuildActionEnum() { switch (this.actionName) { case "Compile": return BuildActionEnum.Compile; case "Content": return BuildActionEnum.Content; case "EmbeddedResource": return BuildActionEnum.EmbeddedResource; case "ApplicationDefinition": return BuildActionEnum.ApplicationDefinition; case "Page": return BuildActionEnum.Page; case "Resource": return BuildActionEnum.Resource; case "None": return BuildActionEnum.None; default: throw new ArgumentException("Unknown BuildAction " + this.actionName); } } public override string ToString() { return String.Format("BuildAction={0}", this.actionName); } public static bool operator ==(BuildAction b1, BuildAction b2) { return Equals(b1, b2); } public static bool operator !=(BuildAction b1, BuildAction b2) { return !(b1 == b2); } public static BuildAction Parse(string value) { switch(value) { case "Compile": return BuildAction.Compile; case "Content": return BuildAction.Content; case "EmbeddedResource": return BuildAction.EmbeddedResource; case "ApplicationDefinition": return BuildAction.ApplicationDefinition; case "Page": return BuildAction.Page; case "Resource": return BuildAction.Resource; case "None": return BuildAction.None; default: throw new ArgumentException("Unknown BuildAction " + value); } } } /// <summary> /// Encapsulates BuildAction enumeration /// </summary> public enum BuildActionEnum { None, Compile, Content, EmbeddedResource, ApplicationDefinition, Page, Resource } /// <summary> /// To create your own localizable node properties, subclass this and add public properties /// decorated with your own localized display name, category and description attributes. /// </summary> [CLSCompliant(false), ComVisible(true)] public class NodeProperties : VSPackage.LocalizableProperties, ISpecifyPropertyPages, IVsGetCfgProvider, IVsSpecifyProjectDesignerPages, EnvDTE80.IInternalExtenderProvider, IVsBrowseObject, IVsBuildMacroInfo { #region fields private HierarchyNode node; #endregion #region properties [Browsable(false)] [AutomationBrowsable(false)] public HierarchyNode Node { get { return this.node; } } /// <summary> /// Used by Property Pages Frame to set it's title bar. The Caption of the Hierarchy Node is returned. /// </summary> [Browsable(false)] [AutomationBrowsable(false)] public virtual string Name { get { return this.node.Caption; } } #endregion #region ctors public NodeProperties(HierarchyNode node) { if (node == null) { throw new ArgumentNullException("node"); } this.node = node; } #endregion #region ISpecifyPropertyPages methods public virtual void GetPages(CAUUID[] pages) { ThreadHelper.ThrowIfNotOnUIThread(); this.GetCommonPropertyPages(pages); } #endregion #region IVsBuildMacroInfo methods /// <summary> /// We support this interface so the build event command dialog can display a list /// of tokens for the user to select from. /// </summary> public int GetBuildMacroValue(string buildMacroName, out string buildMacroValue) { buildMacroValue = string.Empty; if (String.IsNullOrEmpty(buildMacroName) == true) return NativeMethods.S_OK; if (buildMacroName.Equals("SolutionDir", StringComparison.OrdinalIgnoreCase) || buildMacroName.Equals("SolutionPath", StringComparison.OrdinalIgnoreCase) || buildMacroName.Equals("SolutionName", StringComparison.OrdinalIgnoreCase) || buildMacroName.Equals("SolutionFileName", StringComparison.OrdinalIgnoreCase) || buildMacroName.Equals("SolutionExt", StringComparison.OrdinalIgnoreCase)) { string solutionPath = Environment.GetEnvironmentVariable("SolutionPath"); if (buildMacroName.Equals("SolutionDir", StringComparison.OrdinalIgnoreCase)) { buildMacroValue = Path.GetDirectoryName(solutionPath); return NativeMethods.S_OK; } else if (buildMacroName.Equals("SolutionPath", StringComparison.OrdinalIgnoreCase)) { buildMacroValue = solutionPath; return NativeMethods.S_OK; } else if (buildMacroName.Equals("SolutionName", StringComparison.OrdinalIgnoreCase)) { buildMacroValue = Path.GetFileNameWithoutExtension((string)solutionPath); return NativeMethods.S_OK; } else if (buildMacroName.Equals("SolutionFileName", StringComparison.OrdinalIgnoreCase)) { buildMacroValue = Path.GetFileName((string)solutionPath); return NativeMethods.S_OK; } else if (buildMacroName.Equals("SolutionExt", StringComparison.OrdinalIgnoreCase)) { buildMacroValue = Path.GetExtension((string)solutionPath); return NativeMethods.S_OK; } } ThreadHelper.ThrowIfNotOnUIThread(); buildMacroValue = this.Node.ProjectMgr.GetBuildMacroValue(buildMacroName); return NativeMethods.S_OK; } #endregion #region IVsSpecifyProjectDesignerPages /// <summary> /// Implementation of the IVsSpecifyProjectDesignerPages. It will retun the pages that are configuration independent. /// </summary> /// <param name="pages">The pages to return.</param> /// <returns></returns> public virtual int GetProjectDesignerPages(CAUUID[] pages) { ThreadHelper.ThrowIfNotOnUIThread(); this.GetCommonPropertyPages(pages); return VSConstants.S_OK; } #endregion #region IVsGetCfgProvider methods public virtual int GetCfgProvider(out IVsCfgProvider p) { p = null; return VSConstants.E_NOTIMPL; } #endregion #region IVsBrowseObject methods /// <summary> /// Maps back to the hierarchy or project item object corresponding to the browse object. /// </summary> /// <param name="hier">Reference to the hierarchy object.</param> /// <param name="itemid">Reference to the project item.</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code. </returns> public virtual int GetProjectItem(out IVsHierarchy hier, out uint itemid) { if (this.node == null) { throw new InvalidOperationException(); } ThreadHelper.ThrowIfNotOnUIThread(); hier = HierarchyNode.GetOuterHierarchy(this.node.ProjectMgr); itemid = this.node.ID; return VSConstants.S_OK; } #endregion #region overridden methods /// <summary> /// Get the Caption of the Hierarchy Node instance. If Caption is null or empty we delegate to base /// </summary> /// <returns>Caption of Hierarchy node instance</returns> public override string GetComponentName() { string caption = this.Node.Caption; if (String.IsNullOrEmpty(caption)) { return base.GetComponentName(); } else { return caption; } } #endregion #region helper methods protected string GetProperty(string name, string def) { string a = this.Node.ItemNode.GetMetadata(name); return (a == null) ? def : a; } protected void SetProperty(string name, string value) { ThreadHelper.ThrowIfNotOnUIThread(); this.Node.ItemNode.SetMetadata(name, value); } /// <summary> /// Retrieves the common property pages. The NodeProperties is the BrowseObject and that will be called to support /// configuration independent properties. /// </summary> /// <param name="pages">The pages to return.</param> private void GetCommonPropertyPages(CAUUID[] pages) { // We do not check whether the supportsProjectDesigner is set to false on the ProjectNode. // We rely that the caller knows what to call on us. if (pages == null) { throw new ArgumentNullException("pages"); } if(pages.Length == 0) { throw new ArgumentException(SR.GetString(SR.InvalidParameter, CultureInfo.CurrentUICulture), "pages"); } ThreadHelper.ThrowIfNotOnUIThread(); // Only the project should show the property page the rest should show the project properties. if (this.node != null && (this.node is ProjectNode)) { // Retrieve the list of guids from hierarchy properties. // Because a flavor could modify that list we must make sure we are calling the outer most implementation of IVsHierarchy string guidsList = String.Empty; IVsHierarchy hierarchy = HierarchyNode.GetOuterHierarchy(this.Node.ProjectMgr); object variant = null; ErrorHandler.ThrowOnFailure(hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID2.VSHPROPID_PropertyPagesCLSIDList, out variant)); guidsList = (string)variant; Guid[] guids = Utilities.GuidsArrayFromSemicolonDelimitedStringOfGuids(guidsList); if(guids == null || guids.Length == 0) { pages[0] = new CAUUID(); pages[0].cElems = 0; } else { pages[0] = PackageUtilities.CreateCAUUIDFromGuidArray(guids); } } else { pages[0] = new CAUUID(); pages[0].cElems = 0; } } #endregion #region IInternalExtenderProvider Members bool EnvDTE80.IInternalExtenderProvider.CanExtend(string extenderCATID, string extenderName, object extendeeObject) { ThreadHelper.ThrowIfNotOnUIThread(); IVsHierarchy outerHierarchy = HierarchyNode.GetOuterHierarchy(this.Node); if (outerHierarchy is EnvDTE80.IInternalExtenderProvider) { return ((EnvDTE80.IInternalExtenderProvider)outerHierarchy).CanExtend(extenderCATID, extenderName, extendeeObject); } return false; } object EnvDTE80.IInternalExtenderProvider.GetExtender(string extenderCATID, string extenderName, object extendeeObject, EnvDTE.IExtenderSite extenderSite, int cookie) { ThreadHelper.ThrowIfNotOnUIThread(); IVsHierarchy outerHierarchy = HierarchyNode.GetOuterHierarchy(this.Node); if (outerHierarchy is EnvDTE80.IInternalExtenderProvider) { return ((EnvDTE80.IInternalExtenderProvider)outerHierarchy).GetExtender(extenderCATID, extenderName, extendeeObject, extenderSite, cookie); } return null; } object EnvDTE80.IInternalExtenderProvider.GetExtenderNames(string extenderCATID, object extendeeObject) { ThreadHelper.ThrowIfNotOnUIThread(); IVsHierarchy outerHierarchy = HierarchyNode.GetOuterHierarchy(this.Node); if (outerHierarchy is EnvDTE80.IInternalExtenderProvider) { return ((EnvDTE80.IInternalExtenderProvider)outerHierarchy).GetExtenderNames(extenderCATID, extendeeObject); } return null; } #endregion #region ExtenderSupport [Browsable(false)] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "CATID")] public virtual string ExtenderCATID { get { Guid catid = this.Node.ProjectMgr.GetCATIDForType(this.GetType()); if(Guid.Empty.CompareTo(catid) == 0) { return null; } return catid.ToString("B"); } } [Browsable(false)] public object ExtenderNames() { ThreadHelper.ThrowIfNotOnUIThread(); EnvDTE.ObjectExtenders extenderService = (EnvDTE.ObjectExtenders)this.Node.GetService(typeof(EnvDTE.ObjectExtenders)); Debug.Assert(extenderService != null, "Could not get the ObjectExtenders object from the services exposed by this property object"); if (extenderService == null) { throw new InvalidOperationException(); } return extenderService.GetExtenderNames(this.ExtenderCATID, this); } public object Extender(string extenderName) { ThreadHelper.ThrowIfNotOnUIThread(); EnvDTE.ObjectExtenders extenderService = (EnvDTE.ObjectExtenders)this.Node.GetService(typeof(EnvDTE.ObjectExtenders)); Debug.Assert(extenderService != null, "Could not get the ObjectExtenders object from the services exposed by this property object"); if (extenderService == null) { throw new InvalidOperationException(); } return extenderService.GetExtender(this.ExtenderCATID, extenderName, this); } #endregion } [CLSCompliant(false), ComVisible(true)] public abstract class BaseFileNodeProperties : NodeProperties, VSLangProj.FileProperties { #region properties [SRCategoryAttribute(SR.Advanced)] [LocDisplayName(SR.BuildAction)] [SRDescriptionAttribute(SR.BuildActionDescription)] public virtual VSPackage.BuildActionEnum BuildAction { get { string value = this.Node.ItemNode.ItemName; if(value == null || value.Length == 0) { return VSPackage.BuildActionEnum.None; } return VSPackage.BuildAction.Parse(value).ToBuildActionEnum(); } set { ThreadHelper.ThrowIfNotOnUIThread(); this.Node.ItemNode.ItemName = value.ToString(); } } [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.FullPath)] [SRDescriptionAttribute(SR.FullPathDescription)] public string FullPath { get { return this.Node.Url; } } #region non-browsable properties - used for automation only [Browsable(false)] public string Extension { get { return Path.GetExtension(this.Node.Caption); } } [Browsable(false)] public virtual bool IsLink { get { return false; } } [Browsable(false)] public string URL { get { return this.Node.Url; } } #endregion #endregion #region ctors public BaseFileNodeProperties(HierarchyNode node) : base(node) { } #endregion #region overridden methods public override string GetClassName() { return SR.GetString(SR.FileProperties, CultureInfo.CurrentUICulture); } #endregion #region VSLangProj.FileProperties Members string VSLangProj.FileProperties.Author { get { return String.Empty; } } VSLangProj.prjBuildAction VSLangProj.FileProperties.BuildAction { get { ThreadHelper.ThrowIfNotOnUIThread(); return (VSLangProj.prjBuildAction)Enum.Parse(typeof(VSPackage.BuildAction), BuildAction.ToString()); } set { ThreadHelper.ThrowIfNotOnUIThread(); this.BuildAction = new BuildAction(Enum.GetName(typeof(VSPackage.BuildAction), value)).ToBuildActionEnum(); } } string VSLangProj.FileProperties.CustomTool { get { return String.Empty; } set { } } string VSLangProj.FileProperties.CustomToolNamespace { get { return String.Empty; } set { } } string VSLangProj.FileProperties.CustomToolOutput { get { return String.Empty; } } string VSLangProj.FileProperties.DateCreated { get { return String.Empty; } } string VSLangProj.FileProperties.DateModified { get { return String.Empty; } } string VSLangProj.FileProperties.ExtenderCATID { get { return String.Empty; } } object VSLangProj.FileProperties.ExtenderNames { get { return String.Empty; } } string VSLangProj.FileProperties.FileName { get { return this.Node.Caption; } set { this.SetFileName(value); } } internal virtual void SetFileName(string value) { } uint VSLangProj.FileProperties.Filesize { get { FileInfo fileInfo = new FileInfo(this.FullPath); return fileInfo.Exists ? (uint)fileInfo.Length : 0; } } string VSLangProj.FileProperties.HTMLTitle { get { return String.Empty; } } bool VSLangProj.FileProperties.IsCustomToolOutput { get { return false; } } bool VSLangProj.FileProperties.IsDependentFile { get { return false; } } bool VSLangProj.FileProperties.IsDesignTimeBuildInput { get { return false; } } string VSLangProj.FileProperties.LocalPath { get { return this.FullPath; } } string VSLangProj.FileProperties.ModifiedBy { get { return String.Empty; } } string VSLangProj.FileProperties.SubType { get { return String.Empty; } set { } } string VSLangProj.FileProperties.__id { get { return String.Empty; } } object VSLangProj.FileProperties.get_Extender(string ExtenderName) { return null; } #endregion } [CLSCompliant(false), ComVisible(true)] public class FileNodeProperties : BaseFileNodeProperties { #region properties [SRCategoryAttribute(SR.Advanced)] [LocDisplayName(SR.CopyToOutputDirectory)] [SRDescriptionAttribute(SR.CopyToOutputDirectoryDescription)] public virtual VSPackage.CopyToOutputDirectory CopyToOutputDirectory { get { string value = this.Node.ItemNode.GetEvaluatedMetadata(ProjectFileConstants.CopyToOutputDirectory); ThreadHelper.ThrowIfNotOnUIThread(); VSPackage.CopyToOutputDirectory result; if (! Enum.TryParse(value, true, out result)) { result = VSPackage.CopyToOutputDirectory.DoNotCopy; } return result; } set { ThreadHelper.ThrowIfNotOnUIThread(); if (value == CopyToOutputDirectory.DoNotCopy) this.Node.ItemNode.SetMetadata(ProjectFileConstants.CopyToOutputDirectory, null); else this.Node.ItemNode.SetMetadata(ProjectFileConstants.CopyToOutputDirectory, value.ToString()); } } [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.FileName)] [SRDescriptionAttribute(SR.FileNameDescription)] public string FileName { get { return this.Node.Caption; } set { this.Node.SetEditLabel(value); } } #endregion #region ctors public FileNodeProperties(HierarchyNode node) : base(node) { } #endregion #region overridden methods internal override void SetFileName(string value) { this.FileName = value; } #endregion } [CLSCompliant(false), ComVisible(true)] public class LinkedFileNodeProperties : BaseFileNodeProperties { #region properties [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.FileName)] [SRDescriptionAttribute(SR.FileNameDescription)] public string FileName { get { return this.Node.Caption; } } [Browsable(false)] public override bool IsLink { get { return true; } } #endregion #region ctors public LinkedFileNodeProperties(HierarchyNode node) : base(node) { } #endregion } [CLSCompliant(false), ComVisible(true)] public class DependentFileNodeProperties : BaseFileNodeProperties { #region properties [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.FileName)] [SRDescriptionAttribute(SR.FileNameDescription)] public virtual string FileName { get { return this.Node.Caption; } } #endregion #region ctors public DependentFileNodeProperties(HierarchyNode node) : base(node) { } #endregion #region overridden methods public override string GetClassName() { return SR.GetString(SR.FileProperties, CultureInfo.CurrentUICulture); } #endregion } [CLSCompliant(false), ComVisible(true)] public class SingleFileGeneratorNodeProperties : FileNodeProperties { #region fields private EventHandler<HierarchyNodeEventArgs> onCustomToolChanged; private EventHandler<HierarchyNodeEventArgs> onCustomToolNameSpaceChanged; protected string _customTool = ""; protected string _customToolNamespace = ""; #endregion #region custom tool events public event EventHandler<HierarchyNodeEventArgs> OnCustomToolChanged { add { onCustomToolChanged += value; } remove { onCustomToolChanged -= value; } } public event EventHandler<HierarchyNodeEventArgs> OnCustomToolNameSpaceChanged { add { onCustomToolNameSpaceChanged += value; } remove { onCustomToolNameSpaceChanged -= value; } } #endregion #region properties [SRCategoryAttribute(SR.Advanced)] [LocDisplayName(SR.CustomTool)] [SRDescriptionAttribute(SR.CustomToolDescription)] public virtual string CustomTool { get { ThreadHelper.ThrowIfNotOnUIThread(); _customTool = this.Node.ItemNode.GetMetadata(ProjectFileConstants.Generator); return _customTool; } set { _customTool = value; ThreadHelper.ThrowIfNotOnUIThread(); if (!String.IsNullOrEmpty(_customTool)) { this.Node.ItemNode.SetMetadata(ProjectFileConstants.Generator, _customTool); HierarchyNodeEventArgs args = new HierarchyNodeEventArgs(this.Node); if (onCustomToolChanged != null) { onCustomToolChanged(this.Node, args); } } } } [SRCategoryAttribute(VisualStudio.Project.SR.Advanced)] [LocDisplayName(SR.CustomToolNamespace)] [SRDescriptionAttribute(SR.CustomToolNamespaceDescription)] public virtual string CustomToolNamespace { get { ThreadHelper.ThrowIfNotOnUIThread(); _customToolNamespace = this.Node.ItemNode.GetMetadata(ProjectFileConstants.CustomToolNamespace); return _customToolNamespace; } set { _customToolNamespace = value; ThreadHelper.ThrowIfNotOnUIThread(); if (!String.IsNullOrEmpty(_customToolNamespace)) { this.Node.ItemNode.SetMetadata(ProjectFileConstants.CustomToolNamespace, _customToolNamespace); HierarchyNodeEventArgs args = new HierarchyNodeEventArgs(this.Node); if (onCustomToolNameSpaceChanged != null) { onCustomToolNameSpaceChanged(this.Node, args); } } } } #endregion #region ctors public SingleFileGeneratorNodeProperties(HierarchyNode node) : base(node) { } #endregion } [CLSCompliant(false), ComVisible(true)] public class ProjectNodeProperties : NodeProperties { #region properties [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.ProjectFolder)] [SRDescriptionAttribute(SR.ProjectFolderDescription)] [AutomationBrowsable(false)] public string ProjectFolder { get { return this.Node.ProjectMgr.ProjectFolder; } } [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.ProjectFile)] [SRDescriptionAttribute(SR.ProjectFileDescription)] [AutomationBrowsable(false)] public string ProjectFile { get { return this.Node.ProjectMgr.ProjectFile; } set { ThreadHelper.ThrowIfNotOnUIThread(); this.Node.ProjectMgr.ProjectFile = value; } } #region non-browsable properties - used for automation only [Browsable(false)] public string FileName { get { return this.Node.ProjectMgr.ProjectFile; } set { ThreadHelper.ThrowIfNotOnUIThread(); this.Node.ProjectMgr.ProjectFile = value; } } [Browsable(false)] public string ReferencePath { get { ThreadHelper.ThrowIfNotOnUIThread(); return this.Node.ProjectMgr.GetProjectProperty(ProjectFileConstants.ReferencePath, true); } set { ThreadHelper.ThrowIfNotOnUIThread(); this.Node.ProjectMgr.SetProjectProperty(ProjectFileConstants.ReferencePath, value); } } [Browsable(false)] public IReferenceContainer DesignTimeReferences { get { return this.Node.ProjectMgr.GetReferenceContainer(); } } [Browsable(false)] public string FullPath { get { string fullPath = this.Node.ProjectMgr.ProjectFolder; if(!fullPath.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal)) { return fullPath + Path.DirectorySeparatorChar; } else { return fullPath; } } } #endregion #endregion #region ctors public ProjectNodeProperties(ProjectNode node) : base(node) { } #endregion #region overridden methods public override string GetClassName() { return SR.GetString(SR.ProjectProperties, CultureInfo.CurrentUICulture); } /// <summary> /// ICustomTypeDescriptor.GetEditor /// To enable the "Property Pages" button on the properties browser /// the browse object (project properties) need to be unmanaged /// or it needs to provide an editor of type ComponentEditor. /// </summary> /// <param name="editorBaseType">Type of the editor</param> /// <returns>Editor</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification="The service provider is used by the PropertiesEditorLauncher")] public override object GetEditor(Type editorBaseType) { // Override the scenario where we are asked for a ComponentEditor // as this is how the Properties Browser calls us ThreadHelper.ThrowIfNotOnUIThread(); if (editorBaseType.IsEquivalentTo(typeof(ComponentEditor))) { IOleServiceProvider sp; ErrorHandler.ThrowOnFailure(this.Node.GetSite(out sp)); return new PropertiesEditorLauncher(new ServiceProvider(sp)); } return base.GetEditor(editorBaseType); } public override int GetCfgProvider(out IVsCfgProvider p) { ThreadHelper.ThrowIfNotOnUIThread(); if (this.Node != null && this.Node.ProjectMgr != null) { return this.Node.ProjectMgr.GetCfgProvider(out p); } return base.GetCfgProvider(out p); } #endregion } [CLSCompliant(false), ComVisible(true)] public class FolderNodeProperties : NodeProperties { #region properties [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.FolderName)] [SRDescriptionAttribute(SR.FolderNameDescription)] [AutomationBrowsable(false)] public string FolderName { get { return this.Node.Caption; } set { ThreadHelper.JoinableTaskFactory.Run(async delegate { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); this.Node.SetEditLabel(value); this.Node.ReDraw(UIHierarchyElement.Caption); }); } } #region properties - used for automation only [Browsable(false)] [AutomationBrowsable(true)] public string FileName { get { return this.Node.Caption; } set { ThreadHelper.JoinableTaskFactory.Run(async delegate { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); this.Node.SetEditLabel(value); this.Node.ReDraw(UIHierarchyElement.Caption); }); } } [Browsable(false)] [AutomationBrowsable(true)] public string DefaultNamespace { get { ThreadHelper.ThrowIfNotOnUIThread(); var project = this.Node.ProjectMgr as ProjectNode; string parentName = (string)project.GetProperty((int)__VSHPROPID.VSHPROPID_DefaultNamespace); string relativePath = project.GetRelativePath(this.Node.Url); if (relativePath.EndsWith("\\")) relativePath = relativePath.Substring(0, relativePath.Length - 1); var result = parentName + "." + relativePath.Replace('\\', '.'); if (!project.WizardIsRunning) { result = "global::" + result; } return result; } } [Browsable(false)] [AutomationBrowsable(true)] public string FullPath { get { string fullPath = this.Node.GetMkDocument(); if(!fullPath.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal)) { return fullPath + Path.DirectorySeparatorChar; } else { return fullPath; } } } #endregion #endregion #region ctors public FolderNodeProperties(HierarchyNode node) : base(node) { } #endregion #region overridden methods public override string GetClassName() { return SR.GetString(SR.FolderProperties, CultureInfo.CurrentUICulture); } #endregion } [CLSCompliant(false), ComVisible(true)] public class ReferenceNodeProperties : NodeProperties { #region properties [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.RefName)] [SRDescriptionAttribute(SR.RefNameDescription)] [Browsable(true)] [AutomationBrowsable(true)] public override string Name { get { return this.Node.Caption; } } [Browsable(false)] public string DefaultNamespace { get { ThreadHelper.ThrowIfNotOnUIThread(); return (string)this.Node.ProjectMgr.GetProperty((int)__VSHPROPID.VSHPROPID_DefaultNamespace); } } [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.CopyToLocal)] [SRDescriptionAttribute(SR.CopyToLocalDescription)] public virtual bool CopyToLocal { get { ThreadHelper.ThrowIfNotOnUIThread(); string copyLocal = this.GetProperty(ProjectFileConstants.Private, "False"); if(copyLocal == null || copyLocal.Length == 0) return true; return bool.Parse(copyLocal); } set { ThreadHelper.ThrowIfNotOnUIThread(); if (value) { this.SetProperty(ProjectFileConstants.Private, null); } else { this.SetProperty(ProjectFileConstants.Private, value.ToString()); } } } [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.FullPath)] [SRDescriptionAttribute(SR.FullPathDescription)] public virtual string FullPath { get { return this.Node.Url; } } #endregion #region ctors public ReferenceNodeProperties(HierarchyNode node) : base(node) { } #endregion #region overridden methods public override string GetClassName() { return SR.GetString(SR.ReferenceProperties, CultureInfo.CurrentUICulture); } #endregion } [CLSCompliant(false), ComVisible(true)] public class ProjectReferencesProperties : ReferenceNodeProperties { #region ctors public ProjectReferencesProperties(ProjectReferenceNode node) : base(node) { } #endregion #region properties /// <summary> /// Overrides Name to not be displayed. ReferenceName is to be used /// instead. /// </summary> [Browsable(false)] public override string Name { get { return this.ReferenceName; } } [SRCategoryAttribute(SR.Misc)] [LocDisplayName(SR.RefName)] [SRDescriptionAttribute(SR.RefNameDescription)] [Browsable(true)] [AutomationBrowsable(true)] public string ReferenceName { get { return this.Node.Caption; } set { this.Node.SetEditLabel(value); } } #endregion #region overriden methods public override string FullPath { get { ThreadHelper.ThrowIfNotOnUIThread(); return ((ProjectReferenceNode)Node).ReferencedProjectOutputPath; } } #endregion } [ComVisible(true)] public class ComReferenceProperties : ReferenceNodeProperties { public ComReferenceProperties(ComReferenceNode node) : base(node) { } [SRCategory(SR.Misc)] [LocDisplayName(SR.EmbedInteropTypes)] [SRDescription(SR.EmbedInteropTypesDescription)] public virtual bool EmbedInteropTypes { get { ThreadHelper.ThrowIfNotOnUIThread(); return ((ComReferenceNode)this.Node).EmbedInteropTypes; } set { ThreadHelper.ThrowIfNotOnUIThread(); ((ComReferenceNode)this.Node).EmbedInteropTypes = value; } } } }
using System; using System.Linq; using Jasper.Configuration; using Jasper.Runtime.Routing; using Jasper.Transports; using Jasper.Transports.Local; using Jasper.Transports.Stub; using Jasper.Util; using LamarCodeGeneration.Util; using Microsoft.Extensions.Hosting; using Shouldly; using Xunit; namespace Jasper.Testing.Configuration { public class configuring_endpoints : IDisposable { private IHost _host; private JasperOptions theOptions; public configuring_endpoints() { _host = Host.CreateDefaultBuilder().UseJasper(x => { x.Endpoints.ListenForMessagesFrom("local://one").Sequential().Named("one"); x.Endpoints.ListenForMessagesFrom("local://two").MaximumThreads(11); x.Endpoints.ListenForMessagesFrom("local://three").DurablyPersistedLocally(); x.Endpoints.ListenForMessagesFrom("local://four").DurablyPersistedLocally().BufferedInMemory(); x.Endpoints.ListenForMessagesFrom("local://five").ProcessInline(); }).Build(); theOptions = _host.Get<JasperOptions>(); } private LocalQueueSettings localQueue(string queueName) { return theOptions.Endpoints.As<TransportCollection>().Get<LocalTransport>() .QueueFor(queueName); } private Endpoint findEndpoint(string uri) { return theOptions.Endpoints.As<TransportCollection>() .TryGetEndpoint(uri.ToUri()); } private StubTransport theStubTransport => theOptions.Endpoints.As<TransportCollection>().Get<StubTransport>(); public void Dispose() { _host.Dispose(); } [Fact] public void can_set_the_endpoint_name() { localQueue("one").Name.ShouldBe("one"); } [Fact] public void publish_all_adds_an_all_subscription_to_the_endpoint() { theOptions.Endpoints.PublishAllMessages() .To("stub://5555"); findEndpoint("stub://5555") .Subscriptions.Single() .Scope.ShouldBe(RoutingScope.All); } [Fact] public void configure_default_queue() { theOptions.Endpoints.DefaultLocalQueue .MaximumThreads(13); localQueue(TransportConstants.Default) .ExecutionOptions.MaxDegreeOfParallelism .ShouldBe(13); } [Fact] public void configure_durable_queue() { theOptions.Endpoints.DurableScheduledMessagesLocalQueue .MaximumThreads(22); localQueue(TransportConstants.Durable) .ExecutionOptions.MaxDegreeOfParallelism .ShouldBe(22); } [Fact] public void mark_durable() { theOptions.Endpoints.ListenForMessagesFrom("stub://1111") .DurablyPersistedLocally(); var endpoint = findEndpoint("stub://1111"); endpoint.ShouldNotBeNull(); endpoint.Mode.ShouldBe(EndpointMode.Durable); endpoint.IsListener.ShouldBeTrue(); } [Fact] public void prefer_listener() { theOptions.Endpoints.ListenForMessagesFrom("stub://1111"); theOptions.Endpoints.ListenForMessagesFrom("stub://2222"); theOptions.Endpoints.ListenForMessagesFrom("stub://3333").UseForReplies(); findEndpoint("stub://1111").IsUsedForReplies.ShouldBeFalse(); findEndpoint("stub://2222").IsUsedForReplies.ShouldBeFalse(); findEndpoint("stub://3333").IsUsedForReplies.ShouldBeTrue(); } [Fact] public void configure_sequential() { localQueue("one") .ExecutionOptions .MaxDegreeOfParallelism .ShouldBe(1); } [Fact] public void configure_max_parallelization() { localQueue("two") .ExecutionOptions .MaxDegreeOfParallelism .ShouldBe(11); } [Fact] public void configure_process_inline() { theOptions .Endpoints .ListenForMessagesFrom("local://three") .ProcessInline(); localQueue("three") .Mode .ShouldBe(EndpointMode.Inline); } [Fact] public void configure_durable() { theOptions .Endpoints .ListenForMessagesFrom("local://three") .DurablyPersistedLocally(); localQueue("three") .Mode .ShouldBe(EndpointMode.Durable); } [Fact] public void configure_not_durable() { theOptions.Endpoints.ListenForMessagesFrom("local://four"); localQueue("four") .Mode .ShouldBe(EndpointMode.BufferedInMemory); } [Fact] public void configure_execution() { theOptions.Endpoints.LocalQueue("foo") .ConfigureExecution(x => x.BoundedCapacity = 111); localQueue("foo") .ExecutionOptions.BoundedCapacity.ShouldBe(111); } [Fact] public void sets_is_listener() { var uriString = "stub://1111"; theOptions.Endpoints.ListenForMessagesFrom(uriString); findEndpoint(uriString) .IsListener.ShouldBeTrue(); } [Fact] public void select_reply_endpoint_with_one_listener() { theOptions.Endpoints.ListenForMessagesFrom("stub://2222"); theOptions.Endpoints.PublishAllMessages().To("stub://3333"); theStubTransport.ReplyEndpoint() .Uri.ShouldBe("stub://2222".ToUri()); } [Fact] public void select_reply_endpoint_with_multiple_listeners_and_one_designated_reply_endpoint() { theOptions.Endpoints.ListenForMessagesFrom("stub://2222"); theOptions.Endpoints.ListenForMessagesFrom("stub://4444").UseForReplies(); theOptions.Endpoints.ListenForMessagesFrom("stub://5555"); theOptions.Endpoints.PublishAllMessages().To("stub://3333"); theStubTransport.ReplyEndpoint() .Uri.ShouldBe("stub://4444".ToUri()); } [Fact] public void select_reply_endpoint_with_no_listeners() { theOptions.Endpoints.PublishAllMessages().To("stub://3333"); theStubTransport.ReplyEndpoint().ShouldBeNull(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace Security.Api.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Net.IPAddress.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Net { public partial class IPAddress { #region Methods and constructors public override bool Equals(Object comparand) { return default(bool); } public byte[] GetAddressBytes() { Contract.Ensures(Contract.Result<byte[]>() != null); return default(byte[]); } public override int GetHashCode() { return default(int); } public static short HostToNetworkOrder(short host) { Contract.Ensures(Contract.Result<short>() <= 32767); Contract.Ensures(Contract.Result<short>() == (short)((((host & 255) << 8) | ((host >> 8) & 255)))); return default(short); } public static int HostToNetworkOrder(int host) { Contract.Ensures(0 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() <= 2147450879); Contract.Ensures(Contract.Result<int>() == ((((((short)(((((short)(host) & 255) << 8) | (((short)(host) >> 8) & 255))) & 65535)) != 0 << 16) | (((short)(((((short)((host >> 16)) & 255) << 8) | (((short)((host >> 16)) >> 8) & 255))) & 65535)) != 0))); return default(int); } public static long HostToNetworkOrder(long host) { return default(long); } public IPAddress(long newAddress) { } public IPAddress(byte[] address) { } public IPAddress(byte[] address, long scopeid) { } public static bool IsLoopback(System.Net.IPAddress address) { Contract.Requires(address != null); return default(bool); } public static int NetworkToHostOrder(int network) { Contract.Ensures(0 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() <= 2147450879); return default(int); } public static long NetworkToHostOrder(long network) { return default(long); } public static short NetworkToHostOrder(short network) { Contract.Ensures(Contract.Result<short>() == (short)((((network & 255) << 8) | ((network >> 8) & 255)))); return default(short); } public static System.Net.IPAddress Parse(string ipString) { return default(System.Net.IPAddress); } public override string ToString() { return default(string); } public static bool TryParse(string ipString, out System.Net.IPAddress address) { Contract.Ensures(Contract.Result<bool>() == ((Contract.ValueAtReturn(out address) == null) == false)); address = default(System.Net.IPAddress); return default(bool); } #endregion #region Properties and indexers public long Address { get { return default(long); } set { } } public System.Net.Sockets.AddressFamily AddressFamily { get { return default(System.Net.Sockets.AddressFamily); } } public bool IsIPv6LinkLocal { get { return default(bool); } } public bool IsIPv6Multicast { get { return default(bool); } } public bool IsIPv6SiteLocal { get { return default(bool); } } public bool IsIPv6Teredo { get { return default(bool); } } public long ScopeId { get { return default(long); } set { } } #endregion #region Fields public readonly static System.Net.IPAddress Any; public readonly static System.Net.IPAddress Broadcast; public readonly static System.Net.IPAddress IPv6Any; public readonly static System.Net.IPAddress IPv6Loopback; public readonly static System.Net.IPAddress IPv6None; public readonly static System.Net.IPAddress Loopback; public readonly static System.Net.IPAddress None; #endregion } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: supply/snapshot/group_booking_quantity_snapshot.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace HOLMS.Types.Supply.Snapshot { /// <summary>Holder for reflection information generated from supply/snapshot/group_booking_quantity_snapshot.proto</summary> public static partial class GroupBookingQuantitySnapshotReflection { #region Descriptor /// <summary>File descriptor for supply/snapshot/group_booking_quantity_snapshot.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static GroupBookingQuantitySnapshotReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjVzdXBwbHkvc25hcHNob3QvZ3JvdXBfYm9va2luZ19xdWFudGl0eV9zbmFw", "c2hvdC5wcm90bxIbaG9sbXMudHlwZXMuc3VwcGx5LnNuYXBzaG90GjBib29r", "aW5nL2luZGljYXRvcnMvZ3JvdXBfYm9va2luZ19pbmRpY2F0b3IucHJvdG8i", "mwEKHEdyb3VwQm9va2luZ1F1YW50aXR5U25hcHNob3QSRgoHYm9va2luZxgB", "IAEoCzI1LmhvbG1zLnR5cGVzLmJvb2tpbmcuaW5kaWNhdG9ycy5Hcm91cEJv", "b2tpbmdJbmRpY2F0b3ISGQoRdG90YWxfaG9sZF9uaWdodHMYAiABKAUSGAoQ", "dXNlZF9ob2xkX25pZ2h0cxgDIAEoBUIeqgIbSE9MTVMuVHlwZXMuU3VwcGx5", "LlNuYXBzaG90YgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HOLMS.Types.Booking.Indicators.GroupBookingIndicatorReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Supply.Snapshot.GroupBookingQuantitySnapshot), global::HOLMS.Types.Supply.Snapshot.GroupBookingQuantitySnapshot.Parser, new[]{ "Booking", "TotalHoldNights", "UsedHoldNights" }, null, null, null) })); } #endregion } #region Messages public sealed partial class GroupBookingQuantitySnapshot : pb::IMessage<GroupBookingQuantitySnapshot> { private static readonly pb::MessageParser<GroupBookingQuantitySnapshot> _parser = new pb::MessageParser<GroupBookingQuantitySnapshot>(() => new GroupBookingQuantitySnapshot()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<GroupBookingQuantitySnapshot> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Supply.Snapshot.GroupBookingQuantitySnapshotReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GroupBookingQuantitySnapshot() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GroupBookingQuantitySnapshot(GroupBookingQuantitySnapshot other) : this() { Booking = other.booking_ != null ? other.Booking.Clone() : null; totalHoldNights_ = other.totalHoldNights_; usedHoldNights_ = other.usedHoldNights_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GroupBookingQuantitySnapshot Clone() { return new GroupBookingQuantitySnapshot(this); } /// <summary>Field number for the "booking" field.</summary> public const int BookingFieldNumber = 1; private global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator booking_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator Booking { get { return booking_; } set { booking_ = value; } } /// <summary>Field number for the "total_hold_nights" field.</summary> public const int TotalHoldNightsFieldNumber = 2; private int totalHoldNights_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int TotalHoldNights { get { return totalHoldNights_; } set { totalHoldNights_ = value; } } /// <summary>Field number for the "used_hold_nights" field.</summary> public const int UsedHoldNightsFieldNumber = 3; private int usedHoldNights_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int UsedHoldNights { get { return usedHoldNights_; } set { usedHoldNights_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as GroupBookingQuantitySnapshot); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(GroupBookingQuantitySnapshot other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Booking, other.Booking)) return false; if (TotalHoldNights != other.TotalHoldNights) return false; if (UsedHoldNights != other.UsedHoldNights) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (booking_ != null) hash ^= Booking.GetHashCode(); if (TotalHoldNights != 0) hash ^= TotalHoldNights.GetHashCode(); if (UsedHoldNights != 0) hash ^= UsedHoldNights.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (booking_ != null) { output.WriteRawTag(10); output.WriteMessage(Booking); } if (TotalHoldNights != 0) { output.WriteRawTag(16); output.WriteInt32(TotalHoldNights); } if (UsedHoldNights != 0) { output.WriteRawTag(24); output.WriteInt32(UsedHoldNights); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (booking_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Booking); } if (TotalHoldNights != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(TotalHoldNights); } if (UsedHoldNights != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(UsedHoldNights); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(GroupBookingQuantitySnapshot other) { if (other == null) { return; } if (other.booking_ != null) { if (booking_ == null) { booking_ = new global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator(); } Booking.MergeFrom(other.Booking); } if (other.TotalHoldNights != 0) { TotalHoldNights = other.TotalHoldNights; } if (other.UsedHoldNights != 0) { UsedHoldNights = other.UsedHoldNights; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (booking_ == null) { booking_ = new global::HOLMS.Types.Booking.Indicators.GroupBookingIndicator(); } input.ReadMessage(booking_); break; } case 16: { TotalHoldNights = input.ReadInt32(); break; } case 24: { UsedHoldNights = input.ReadInt32(); break; } } } } } #endregion } #endregion Designer generated code
// Copyright (c) "Neo4j" // Neo4j Sweden AB [http://neo4j.com] // // This file is part of Neo4j. // // 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. using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Neo4j.Driver.Internal.Connector; using Neo4j.Driver; using Neo4j.Driver.Internal.Protocol; using Neo4j.Driver.Internal.Util; using static Neo4j.Driver.Internal.Throw.ObjectDisposedException; using static Neo4j.Driver.Internal.Util.ConnectionContext; namespace Neo4j.Driver.Internal.Routing { internal class LoadBalancer : IConnectionProvider, IErrorHandler, IClusterConnectionPoolManager { private readonly IRoutingTableManager _routingTableManager; private readonly ILoadBalancingStrategy _loadBalancingStrategy; private readonly IClusterConnectionPool _clusterConnectionPool; private readonly ILogger _logger; private int _closedMarker = 0; private IInitialServerAddressProvider _initialServerAddressProvider; public RoutingSettings RoutingSetting { get; set; } public IDictionary<string, string> RoutingContext { get; set; } public LoadBalancer( IPooledConnectionFactory connectionFactory, RoutingSettings routingSettings, ConnectionPoolSettings poolSettings, ILogger logger) { RoutingSetting = routingSettings; RoutingContext = RoutingSetting.RoutingContext; _logger = logger; _clusterConnectionPool = new ClusterConnectionPool(Enumerable.Empty<Uri>(), connectionFactory, RoutingSetting, poolSettings, logger); _routingTableManager = new RoutingTableManager(routingSettings, this, logger); _loadBalancingStrategy = CreateLoadBalancingStrategy(_clusterConnectionPool, _logger); _initialServerAddressProvider = routingSettings.InitialServerAddressProvider; } // for test only internal LoadBalancer( IClusterConnectionPool clusterConnPool, IRoutingTableManager routingTableManager) { var config = Config.Default; _logger = config.Logger; _clusterConnectionPool = clusterConnPool; _routingTableManager = routingTableManager; _loadBalancingStrategy = CreateLoadBalancingStrategy(clusterConnPool, _logger); } private bool IsClosed => _closedMarker > 0; public async Task<IConnection> AcquireAsync(AccessMode mode, string database, string impersonatedUser, Bookmark bookmark) { if (IsClosed) throw GetDriverDisposedException(nameof(LoadBalancer)); var conn = await AcquireConnectionAsync(mode, database, impersonatedUser, bookmark).ConfigureAwait(false); if (IsClosed) throw GetDriverDisposedException(nameof(LoadBalancer)); return conn; } public Task OnConnectionErrorAsync(Uri uri, string database, Exception e) { _logger?.Info($"Server at {uri} is no longer available due to error: {e.Message}."); _routingTableManager.ForgetServer(uri, database); return _clusterConnectionPool.DeactivateAsync(uri); } public void OnWriteError(Uri uri, string database) { _routingTableManager.ForgetWriter(uri, database); } public Task AddConnectionPoolAsync(IEnumerable<Uri> uris) { return _clusterConnectionPool.AddAsync(uris); } public Task UpdateConnectionPoolAsync(IEnumerable<Uri> added, IEnumerable<Uri> removed) { return _clusterConnectionPool.UpdateAsync(added, removed); } public Task<IConnection> CreateClusterConnectionAsync(Uri uri) { return CreateClusterConnectionAsync(uri, AccessMode.Write, null, null, Bookmark.Empty); } public Task CloseAsync() { if (Interlocked.CompareExchange(ref _closedMarker, 1, 0) == 0) { _routingTableManager.Clear(); return _clusterConnectionPool.CloseAsync(); } return Task.CompletedTask; } public async Task VerifyConnectivityAsync() { // As long as there is a fresh routing table, we consider we can route to these servers. try { var database = await SupportsMultiDbAsync().ConfigureAwait(false) ? "system" : null; await _routingTableManager.EnsureRoutingTableForModeAsync(Simple.Mode, database, null, Simple.Bookmark).ConfigureAwait(false); } catch (ServiceUnavailableException e) { throw new ServiceUnavailableException( "Unable to connect to database, " + "ensure the database is running and that there is a working network connection to it.", e); } } public async Task<bool> SupportsMultiDbAsync() { var uris = _initialServerAddressProvider.Get(); await AddConnectionPoolAsync(uris).ConfigureAwait(false); var exceptions = new List<Exception>(); foreach (var uri in uris) { try { var connection = await CreateClusterConnectionAsync(uri, Simple.Mode, Simple.Database, null, Simple.Bookmark).ConfigureAwait(false); var multiDb = connection.SupportsMultidatabase(); await connection.CloseAsync().ConfigureAwait(false); return multiDb; } catch (SecurityException) { throw; // immediately stop } catch (Exception e) { exceptions.Add(e); // save and continue with the next server } } throw new ServiceUnavailableException( $"Failed to perform multi-databases feature detection with the following servers: {uris.ToContentString()} ", new AggregateException(exceptions)); } public IRoutingTable GetRoutingTable(string database) { return _routingTableManager.RoutingTableFor(database); } private async Task<IConnection> AcquireConnectionAsync(AccessMode mode, string database, string impersonatedUser, Bookmark bookmark) { var routingTable = await _routingTableManager.EnsureRoutingTableForModeAsync(mode, database, impersonatedUser, bookmark) .ConfigureAwait(false); while (true) { Uri uri; switch (mode) { case AccessMode.Read: uri = _loadBalancingStrategy.SelectReader(routingTable.Readers, database); break; case AccessMode.Write: uri = _loadBalancingStrategy.SelectWriter(routingTable.Writers, database); break; default: throw new InvalidOperationException($"Unknown access mode {mode}"); } if (uri == null) { // no server known to routingTable break; } var conn = await CreateClusterConnectionAsync(uri, mode, routingTable.Database, impersonatedUser, bookmark).ConfigureAwait(false); if (conn != null) { return conn; } //else connection already removed by clusterConnection onError method } throw new SessionExpiredException($"Failed to connect to any {mode.ToString().ToLower()} server."); } private async Task<IConnection> CreateClusterConnectionAsync(Uri uri, AccessMode mode, string database, string impersonatedUser, Bookmark bookmark) { try { var conn = await _clusterConnectionPool.AcquireAsync(uri, mode, database, impersonatedUser, bookmark) .ConfigureAwait(false); if (conn != null) { return new ClusterConnection(conn, uri, this); } await OnConnectionErrorAsync(uri, database, new ArgumentException( $"Routing table {_routingTableManager.RoutingTableFor(database)} contains a server {uri} " + $"that is not known to cluster connection pool {_clusterConnectionPool}.")).ConfigureAwait(false); } catch (ServiceUnavailableException e) { await OnConnectionErrorAsync(uri, database, e).ConfigureAwait(false); } return null; } public override string ToString() { return new StringBuilder(128) .Append("LoadBalancer{") .AppendFormat("routingTableManager={0}, ", _routingTableManager) .AppendFormat("clusterConnectionPool={0}, ", _clusterConnectionPool) .AppendFormat("closed={0}", IsClosed) .Append("}") .ToString(); } private static ILoadBalancingStrategy CreateLoadBalancingStrategy(IClusterConnectionPool pool, ILogger logger) { return new LeastConnectedLoadBalancingStrategy(pool, logger); } } }
using System; using System.IO; using System.Net; using System.Text; using System.Threading; using ServiceStack.Logging; using ServiceStack.ServiceHost; using ServiceStack.Text; using ServiceStack.Common.Web; namespace ServiceStack.ServiceClient.Web { /** * Need to provide async request options * http://msdn.microsoft.com/en-us/library/86wf6409(VS.71).aspx */ public class AsyncServiceClient { private static readonly ILog Log = LogManager.GetLogger(typeof(AsyncServiceClient)); private static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(60); private HttpWebRequest _webRequest = null; /// <summary> /// The request filter is called before any request. /// This request filter is executed globally. /// </summary> public static Action<HttpWebRequest> HttpWebRequestFilter { get; set; } /// <summary> /// The response action is called once the server response is available. /// It will allow you to access raw response information. /// This response action is executed globally. /// Note that you should NOT consume the response stream as this is handled by ServiceStack /// </summary> public static Action<HttpWebResponse> HttpWebResponseFilter { get; set; } /// <summary> /// Called before request resend, when the initial request required authentication /// </summary> public Action<WebRequest> OnAuthenticationRequired { get; set; } const int BufferSize = 4096; public ICredentials Credentials { get; set; } public bool StoreCookies { get; set; } public CookieContainer CookieContainer { get; set; } /// <summary> /// The request filter is called before any request. /// This request filter only works with the instance where it was set (not global). /// </summary> public Action<HttpWebRequest> LocalHttpWebRequestFilter { get; set; } /// <summary> /// The response action is called once the server response is available. /// It will allow you to access raw response information. /// Note that you should NOT consume the response stream as this is handled by ServiceStack /// </summary> public Action<HttpWebResponse> LocalHttpWebResponseFilter { get; set; } public string BaseUri { get; set; } internal class RequestState<TResponse> : IDisposable { private bool _timedOut; // Pass the correct error back even on Async Calls public RequestState() { BufferRead = new byte[BufferSize]; TextData = new StringBuilder(); BytesData = new MemoryStream(BufferSize); WebRequest = null; ResponseStream = null; } public string HttpMethod; public string Url; public StringBuilder TextData; public MemoryStream BytesData; public byte[] BufferRead; public object Request; public HttpWebRequest WebRequest; public HttpWebResponse WebResponse; public Stream ResponseStream; public int Completed; public int RequestCount; public Timer Timer; public Action<TResponse> OnSuccess; public Action<TResponse, Exception> OnError; #if SILVERLIGHT public bool HandleCallbackOnUIThread { get; set; } #endif public void HandleSuccess(TResponse response) { if (this.OnSuccess == null) return; #if SILVERLIGHT if (this.HandleCallbackOnUIThread) System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => this.OnSuccess(response)); else this.OnSuccess(response); #else this.OnSuccess(response); #endif } public void HandleError(TResponse response, Exception ex) { if (this.OnError == null) return; Exception toReturn = ex; if (_timedOut) { #if SILVERLIGHT WebException we = new WebException("The request timed out", ex, WebExceptionStatus.RequestCanceled, null); #else WebException we = new WebException("The request timed out", ex, WebExceptionStatus.Timeout, null); #endif toReturn = we; } #if SILVERLIGHT if (this.HandleCallbackOnUIThread) System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => this.OnError(response, toReturn)); else this.OnError(response, toReturn); #else OnError(response, toReturn); #endif } public void StartTimer(TimeSpan timeOut) { this.Timer = new Timer(this.TimedOut, this, (int)timeOut.TotalMilliseconds, System.Threading.Timeout.Infinite); } public void TimedOut(object state) { if (Interlocked.Increment(ref Completed) == 1) { if (this.WebRequest != null) { _timedOut = true; this.WebRequest.Abort(); } } this.Timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite); this.Timer.Dispose(); this.Dispose(); } public void Dispose() { if (this.BytesData == null) return; this.BytesData.Dispose(); this.BytesData = null; } } public bool DisableAutoCompression { get; set; } public string UserName { get; set; } public string Password { get; set; } public void SetCredentials(string userName, string password) { this.UserName = userName; this.Password = password; } public TimeSpan? Timeout { get; set; } public string ContentType { get; set; } public StreamSerializerDelegate StreamSerializer { get; set; } public StreamDeserializerDelegate StreamDeserializer { get; set; } #if SILVERLIGHT public bool HandleCallbackOnUIThread { get; set; } public bool UseBrowserHttpHandling { get; set; } public bool ShareCookiesWithBrowser { get; set; } #endif public void SendAsync<TResponse>(string httpMethod, string absoluteUrl, object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { SendWebRequest(httpMethod, absoluteUrl, request, onSuccess, onError); } public void CancelAsync() { if (_webRequest != null) { // Request will be nulled after it throws an exception on its async methods // See - http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.abort _webRequest.Abort(); } } #if !SILVERLIGHT internal static void AllowAutoCompression(HttpWebRequest webRequest) { webRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate"); webRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; } #endif private RequestState<TResponse> SendWebRequest<TResponse>(string httpMethod, string absoluteUrl, object request, Action<TResponse> onSuccess, Action<TResponse, Exception> onError) { if (httpMethod == null) throw new ArgumentNullException("httpMethod"); var requestUri = absoluteUrl; var httpGetOrDelete = (httpMethod == "GET" || httpMethod == "DELETE"); var hasQueryString = request != null && httpGetOrDelete; if (hasQueryString) { var queryString = QueryStringSerializer.SerializeToString(request); if (!string.IsNullOrEmpty(queryString)) { requestUri += "?" + queryString; } } #if SILVERLIGHT var creator = this.UseBrowserHttpHandling ? System.Net.Browser.WebRequestCreator.BrowserHttp : System.Net.Browser.WebRequestCreator.ClientHttp; var webRequest = (HttpWebRequest) creator.Create(new Uri(requestUri)); if (StoreCookies && !UseBrowserHttpHandling) { if (ShareCookiesWithBrowser) { if (CookieContainer == null) CookieContainer = new CookieContainer(); CookieContainer.SetCookies(new Uri(BaseUri), System.Windows.Browser.HtmlPage.Document.Cookies); } webRequest.CookieContainer = CookieContainer; } #else _webRequest = (HttpWebRequest)WebRequest.Create(requestUri); if (StoreCookies) { _webRequest.CookieContainer = CookieContainer; } #endif #if !SILVERLIGHT if (!DisableAutoCompression) { _webRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate"); _webRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; } #endif var requestState = new RequestState<TResponse> { HttpMethod = httpMethod, Url = requestUri, #if SILVERLIGHT WebRequest = webRequest, #else WebRequest = _webRequest, #endif Request = request, OnSuccess = onSuccess, OnError = onError, #if SILVERLIGHT HandleCallbackOnUIThread = HandleCallbackOnUIThread, #endif }; requestState.StartTimer(this.Timeout.GetValueOrDefault(DefaultTimeout)); #if SILVERLIGHT SendWebRequestAsync(httpMethod, request, requestState, webRequest); #else SendWebRequestAsync(httpMethod, request, requestState, _webRequest); #endif return requestState; } private void SendWebRequestAsync<TResponse>(string httpMethod, object request, RequestState<TResponse> requestState, HttpWebRequest webRequest) { var httpGetOrDelete = (httpMethod == "GET" || httpMethod == "DELETE"); webRequest.Accept = string.Format("{0}, */*", ContentType); #if !SILVERLIGHT webRequest.Method = httpMethod; #else //Methods others than GET and POST are only supported by Client request creator, see //http://msdn.microsoft.com/en-us/library/cc838250(v=vs.95).aspx if (this.UseBrowserHttpHandling && httpMethod != "GET" && httpMethod != "POST") { webRequest.Method = "POST"; webRequest.Headers[HttpHeaders.XHttpMethodOverride] = httpMethod; } else { webRequest.Method = httpMethod; } #endif if (this.Credentials != null) { webRequest.Credentials = this.Credentials; } ApplyWebRequestFilters(webRequest); try { if (!httpGetOrDelete && request != null) { webRequest.ContentType = ContentType; webRequest.BeginGetRequestStream(RequestCallback<TResponse>, requestState); } else { requestState.WebRequest.BeginGetResponse(ResponseCallback<TResponse>, requestState); } } catch (Exception ex) { // BeginGetRequestStream can throw if request was aborted HandleResponseError(ex, requestState); } } private void RequestCallback<T>(IAsyncResult asyncResult) { var requestState = (RequestState<T>)asyncResult.AsyncState; try { var req = requestState.WebRequest; var postStream = req.EndGetRequestStream(asyncResult); StreamSerializer(null, requestState.Request, postStream); postStream.Close(); requestState.WebRequest.BeginGetResponse(ResponseCallback<T>, requestState); } catch (Exception ex) { HandleResponseError(ex, requestState); } } private void ResponseCallback<T>(IAsyncResult asyncResult) { var requestState = (RequestState<T>)asyncResult.AsyncState; try { var webRequest = requestState.WebRequest; requestState.WebResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult); ApplyWebResponseFilters(requestState.WebResponse); // Read the response into a Stream object. var responseStream = requestState.WebResponse.GetResponseStream(); requestState.ResponseStream = responseStream; responseStream.BeginRead(requestState.BufferRead, 0, BufferSize, ReadCallBack<T>, requestState); return; } catch (Exception ex) { var firstCall = Interlocked.Increment(ref requestState.RequestCount) == 1; if (firstCall && WebRequestUtils.ShouldAuthenticate(ex, this.UserName, this.Password)) { try { requestState.WebRequest = (HttpWebRequest)WebRequest.Create(requestState.Url); requestState.WebRequest.AddBasicAuth(this.UserName, this.Password); if (OnAuthenticationRequired != null) { OnAuthenticationRequired(requestState.WebRequest); } SendWebRequestAsync( requestState.HttpMethod, requestState.Request, requestState, requestState.WebRequest); } catch (Exception /*subEx*/) { HandleResponseError(ex, requestState); } return; } HandleResponseError(ex, requestState); } } private void ReadCallBack<T>(IAsyncResult asyncResult) { var requestState = (RequestState<T>)asyncResult.AsyncState; try { var responseStream = requestState.ResponseStream; int read = responseStream.EndRead(asyncResult); if (read > 0) { requestState.BytesData.Write(requestState.BufferRead, 0, read); responseStream.BeginRead( requestState.BufferRead, 0, BufferSize, ReadCallBack<T>, requestState); return; } Interlocked.Increment(ref requestState.Completed); var response = default(T); try { requestState.BytesData.Position = 0; using (var reader = requestState.BytesData) { response = (T)this.StreamDeserializer(typeof(T), reader); } #if SILVERLIGHT if (this.StoreCookies && this.ShareCookiesWithBrowser && !this.UseBrowserHttpHandling) { // browser cookies must be set on the ui thread System.Windows.Deployment.Current.Dispatcher.BeginInvoke( () => { var cookieHeader = this.CookieContainer.GetCookieHeader(new Uri(BaseUri)); System.Windows.Browser.HtmlPage.Document.Cookies = cookieHeader; }); } #endif requestState.HandleSuccess(response); } catch (Exception ex) { Log.Debug(string.Format("Error Reading Response Error: {0}", ex.Message), ex); requestState.HandleError(default(T), ex); } finally { responseStream.Close(); _webRequest = null; } } catch (Exception ex) { HandleResponseError(ex, requestState); } } private void HandleResponseError<TResponse>(Exception exception, RequestState<TResponse> requestState) { var webEx = exception as WebException; if (webEx != null #if !SILVERLIGHT && webEx.Status == WebExceptionStatus.ProtocolError #endif ) { var errorResponse = ((HttpWebResponse)webEx.Response); Log.Error(webEx); Log.DebugFormat("Status Code : {0}", errorResponse.StatusCode); Log.DebugFormat("Status Description : {0}", errorResponse.StatusDescription); var serviceEx = new WebServiceException(errorResponse.StatusDescription) { StatusCode = (int)errorResponse.StatusCode, }; try { using (var stream = errorResponse.GetResponseStream()) { //Uncomment to Debug exceptions: //var strResponse = new StreamReader(stream).ReadToEnd(); //Console.WriteLine("Response: " + strResponse); //stream.Position = 0; serviceEx.ResponseDto = this.StreamDeserializer(typeof(TResponse), stream); requestState.HandleError((TResponse)serviceEx.ResponseDto, serviceEx); } } catch (Exception innerEx) { // Oh, well, we tried Log.Debug(string.Format("WebException Reading Response Error: {0}", innerEx.Message), innerEx); requestState.HandleError(default(TResponse), new WebServiceException(errorResponse.StatusDescription, innerEx) { StatusCode = (int)errorResponse.StatusCode, }); } return; } var authEx = exception as AuthenticationException; if (authEx != null) { var customEx = WebRequestUtils.CreateCustomException(requestState.Url, authEx); Log.Debug(string.Format("AuthenticationException: {0}", customEx.Message), customEx); requestState.HandleError(default(TResponse), authEx); } Log.Debug(string.Format("Exception Reading Response Error: {0}", exception.Message), exception); requestState.HandleError(default(TResponse), exception); _webRequest = null; } private void ApplyWebResponseFilters(WebResponse webResponse) { if (!(webResponse is HttpWebResponse)) return; if (HttpWebResponseFilter != null) HttpWebResponseFilter((HttpWebResponse)webResponse); if (LocalHttpWebResponseFilter != null) LocalHttpWebResponseFilter((HttpWebResponse)webResponse); } private void ApplyWebRequestFilters(HttpWebRequest client) { if (LocalHttpWebRequestFilter != null) LocalHttpWebRequestFilter(client); if (HttpWebRequestFilter != null) HttpWebRequestFilter(client); } public void Dispose() { } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using NFCoreEx; public class NFObjectElement { public NFIDENTID xTargetIdent = new NFIDENTID(); private string strTableName = ""; private string strInfo = ""; private string strCommand = ""; private Vector2 scrollPositionFirst = Vector2.zero; private Vector2 scrollPositionSecond = Vector2.zero; private Vector2 scrollPositionThird = Vector2.zero; GUIStyle buttonLeft; public void OnGUI(NFIKernel kernel, int nHeight, int nWidth) { if (buttonLeft == null) { buttonLeft = GUI.skin.button; buttonLeft.alignment = TextAnchor.MiddleLeft; } int nElementWidth = 150; int nElementHeight = 20; GUI.color = Color.red; strInfo = GUI.TextField(new Rect(0, nHeight - 20, nElementWidth * 3f + 120, 20), strInfo); strCommand = GUI.TextField(new Rect(nElementWidth * 3f + 120, nHeight - 20, 350, 20), strCommand); if (GUI.Button(new Rect(nWidth - 100, nHeight - 20, 100, 20), "cmd")) { } GUI.color = Color.white; NFIDataList objectList = kernel.GetObjectList(); scrollPositionFirst = GUI.BeginScrollView(new Rect(0, nElementHeight, nElementWidth / 2 + 20, nHeight), scrollPositionFirst, new Rect(0, 0, nElementWidth, objectList.Count() * (nElementHeight))); //all object for (int i = 0; i < objectList.Count(); i++) { NFIDENTID ident = objectList.ObjectVal(i); if (GUI.Button(new Rect(0, i * nElementHeight, nElementWidth, nElementHeight), ident.nHead64.ToString() + "_" + ident.nData64.ToString())) { xTargetIdent = ident; strTableName = ""; } } GUI.EndScrollView(); //////////////// if(!xTargetIdent.IsNull()) { NFIObject go = kernel.GetObject(xTargetIdent); NFIDataList recordLlist = go.GetRecordManager().GetRecordList(); NFIDataList propertyList = go.GetPropertyManager().GetPropertyList(); int nAllElement = 1; for(int j = 0; j < recordLlist.Count(); j++) { string strRecordName = recordLlist.StringVal(j); if(strRecordName.Length > 0) { nAllElement++; } } for(int j = 0; j < propertyList.Count(); j++) { string strPropertyName = propertyList.StringVal(j); if(strPropertyName.Length > 0) { nAllElement++; } } ////////////////// scrollPositionSecond = GUI.BeginScrollView(new Rect(nElementWidth / 2 + 20, nElementHeight, nElementWidth+20, nHeight/2), scrollPositionSecond, new Rect(0, 0, nElementWidth, (nAllElement+1) * (nElementHeight) + 1)); int nElementIndex = 0; GUI.Button(new Rect(0, nElementIndex*nElementHeight, nElementWidth, nElementHeight), xTargetIdent.nData64.ToString()); nElementIndex++; //all record for(int j = 0; j < recordLlist.Count(); j++) { string strRecordName = recordLlist.StringVal(j); if(strRecordName.Length > 0) { if(GUI.Button(new Rect(0, nElementIndex*nElementHeight, nElementWidth, nElementHeight), "++" + strRecordName)) { strTableName = strRecordName; } nElementIndex++; } } /////////////////////////////// //all property for (int k = 0; k < propertyList.Count(); k++) { string strPropertyValue = null; string strPropertyName = propertyList.StringVal(k); NFIProperty property = go.GetPropertyManager().GetProperty(strPropertyName); NFIDataList.VARIANT_TYPE eType = property.GetType(); switch (eType) { case NFIDataList.VARIANT_TYPE.VTYPE_DOUBLE: strPropertyValue = property.QueryDouble().ToString(); break; case NFIDataList.VARIANT_TYPE.VTYPE_FLOAT: strPropertyValue = property.QueryFloat().ToString(); break; case NFIDataList.VARIANT_TYPE.VTYPE_INT: strPropertyValue = property.QueryInt().ToString(); break; case NFIDataList.VARIANT_TYPE.VTYPE_OBJECT: strPropertyValue = property.QueryObject().nData64.ToString(); break; case NFIDataList.VARIANT_TYPE.VTYPE_STRING: strPropertyValue = property.QueryString(); break; default: strPropertyValue = "?"; break; } if (strPropertyName.Length > 0) { if (GUI.Button(new Rect(0, nElementIndex * nElementHeight, nElementWidth, nElementHeight), strPropertyName + ":" + strPropertyValue)) { strTableName = ""; strInfo = strPropertyName + ":" + strPropertyValue; } nElementIndex++; } } GUI.EndScrollView(); //////////////////////// if(strTableName.Length > 0) { NFIRecord record = go.GetRecordManager().GetRecord(strTableName); if(null != record) { int nRow = record.GetRows(); int nCol = record.GetCols(); int nOffest = 30; scrollPositionThird = GUI.BeginScrollView(new Rect(nElementWidth * 1.5f + 40, nElementHeight, nElementWidth * 2, nHeight/2), scrollPositionThird, new Rect(0, 0, nElementWidth * nCol + nOffest, nRow * nElementHeight + nOffest)); string selString = null; for(int row = 0; row < nRow; row++) { GUI.Button(new Rect(0, row*nElementHeight+nOffest, nOffest, nElementHeight), row.ToString());//row for(int col = 0; col < nCol; col++) { if(0 == row) { GUI.Button(new Rect(col * nElementWidth + nOffest, 0, nElementWidth, nElementHeight), col.ToString() + " [" + record.GetColType(col) + "]"); } if(record.IsUsed(row)) { NFIDataList.VARIANT_TYPE eType = record.GetColType(col); switch(eType) { case NFIDataList.VARIANT_TYPE.VTYPE_INT: selString = record.QueryInt(row, col).ToString(); break; case NFIDataList.VARIANT_TYPE.VTYPE_FLOAT: selString = record.QueryFloat(row, col).ToString(); break; case NFIDataList.VARIANT_TYPE.VTYPE_DOUBLE: selString = record.QueryDouble(row, col).ToString(); break; case NFIDataList.VARIANT_TYPE.VTYPE_STRING: selString = record.QueryString(row, col).ToString(); break; case NFIDataList.VARIANT_TYPE.VTYPE_OBJECT: selString = record.QueryObject(row, col).nData64.ToString(); break; default: selString = "UnKnowType"; break; } } else { selString = "NoUse"; } if(GUI.Button(new Rect(col*nElementWidth+nOffest, row*nElementHeight+nOffest, nElementWidth, nElementHeight), selString)) { strInfo = "Row:" + row.ToString() + " Col:" + col.ToString() + " " + selString; } } } GUI.EndScrollView(); } } } } }
/* ### # # ######### _______ _ _ ______ _ _ ## ######## @ ## |______ | | | ____ | | ################## | |_____| |_____| |_____| ## ############# f r a m e w o r k # # ######### ### (c) 2015 - 2017 FUGU framework project 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. */ using System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; using System.Threading; namespace Fugu.Linq { internal class ClassFactory { public static readonly ClassFactory Instance = new ClassFactory(); private readonly Dictionary<Signature, Type> _classes; private readonly ModuleBuilder _module; private readonly ReaderWriterLockSlim _rwLock; private int _classCount; static ClassFactory() { } private ClassFactory() { #if ENABLE_LINQ_PARTIAL_TRUST new ReflectionPermission(PermissionState.Unrestricted).Assert(); #endif try { _module = AssemblyBuilder .DefineDynamicAssembly(new AssemblyName("DynamicClasses"), AssemblyBuilderAccess.Run) .DefineDynamicModule("DynamicClasses"); } finally { #if ENABLE_LINQ_PARTIAL_TRUST PermissionSet.RevertAssert(); #endif } _classes = new Dictionary<Signature, Type>(); _rwLock = new ReaderWriterLockSlim(); } public Type GetDynamicClass(IEnumerable<DynamicProperty> properties) { _rwLock.EnterReadLock(); try { var signature = new Signature(properties); if (!_classes.TryGetValue(signature, out Type type)) { type = CreateDynamicClass(signature.properties); _classes.Add(signature, type); } return type; } finally { _rwLock.ExitReadLock(); } } private Type CreateDynamicClass(DynamicProperty[] properties) { _rwLock.EnterWriteLock(); try { var typeName = "DynamicClass" + (_classCount + 1); #if ENABLE_LINQ_PARTIAL_TRUST new ReflectionPermission(PermissionState.Unrestricted).Assert(); #endif try { var tb = _module.DefineType(typeName, TypeAttributes.Class | TypeAttributes.Public, typeof(DynamicClass)); var fields = GenerateProperties(tb, properties); GenerateEquals(tb, fields); GenerateGetHashCode(tb, fields); var result = tb.AsType(); _classCount++; return result; } finally { #if ENABLE_LINQ_PARTIAL_TRUST PermissionSet.RevertAssert(); #endif } } finally { _rwLock.ExitWriteLock(); } } private FieldInfo[] GenerateProperties(TypeBuilder tb, DynamicProperty[] properties) { FieldInfo[] fields = new FieldBuilder[properties.Length]; for (var i = 0; i < properties.Length; i++) { var dp = properties[i]; var fb = tb.DefineField("_" + dp.Name, dp.Type, FieldAttributes.Private); var pb = tb.DefineProperty(dp.Name, PropertyAttributes.HasDefault, dp.Type, null); var mbGet = tb.DefineMethod("get_" + dp.Name, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, dp.Type, Type.EmptyTypes); var genGet = mbGet.GetILGenerator(); genGet.Emit(OpCodes.Ldarg_0); genGet.Emit(OpCodes.Ldfld, fb); genGet.Emit(OpCodes.Ret); var mbSet = tb.DefineMethod("set_" + dp.Name, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, null, new[] { dp.Type }); var genSet = mbSet.GetILGenerator(); genSet.Emit(OpCodes.Ldarg_0); genSet.Emit(OpCodes.Ldarg_1); genSet.Emit(OpCodes.Stfld, fb); genSet.Emit(OpCodes.Ret); pb.SetGetMethod(mbGet); pb.SetSetMethod(mbSet); fields[i] = fb; } return fields; } private void GenerateEquals(TypeBuilder tb, FieldInfo[] fields) { var mb = tb.DefineMethod("Equals", MethodAttributes.Public | MethodAttributes.ReuseSlot | MethodAttributes.Virtual | MethodAttributes.HideBySig, typeof(bool), new[] { typeof(object) }); var gen = mb.GetILGenerator(); var other = gen.DeclareLocal(tb.GetType()); var next = gen.DefineLabel(); gen.Emit(OpCodes.Ldarg_1); gen.Emit(OpCodes.Isinst, tb.GetType()); gen.Emit(OpCodes.Stloc, other); gen.Emit(OpCodes.Ldloc, other); gen.Emit(OpCodes.Brtrue_S, next); gen.Emit(OpCodes.Ldc_I4_0); gen.Emit(OpCodes.Ret); gen.MarkLabel(next); foreach (var field in fields) { var ft = field.FieldType; var ct = typeof(EqualityComparer<>).MakeGenericType(ft); next = gen.DefineLabel(); gen.EmitCall(OpCodes.Call, ct.GetMethod("get_Default"), null); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldfld, field); gen.Emit(OpCodes.Ldloc, other); gen.Emit(OpCodes.Ldfld, field); gen.EmitCall(OpCodes.Callvirt, ct.GetMethod("Equals", new[] { ft, ft }), null); gen.Emit(OpCodes.Brtrue_S, next); gen.Emit(OpCodes.Ldc_I4_0); gen.Emit(OpCodes.Ret); gen.MarkLabel(next); } gen.Emit(OpCodes.Ldc_I4_1); gen.Emit(OpCodes.Ret); } private void GenerateGetHashCode(TypeBuilder tb, FieldInfo[] fields) { var mb = tb.DefineMethod("GetHashCode", MethodAttributes.Public | MethodAttributes.ReuseSlot | MethodAttributes.Virtual | MethodAttributes.HideBySig, typeof(int), Type.EmptyTypes); var gen = mb.GetILGenerator(); gen.Emit(OpCodes.Ldc_I4_0); foreach (var field in fields) { var ft = field.FieldType; var ct = typeof(EqualityComparer<>).MakeGenericType(ft); gen.EmitCall(OpCodes.Call, ct.GetMethod("get_Default"), null); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldfld, field); gen.EmitCall(OpCodes.Callvirt, ct.GetMethod("GetHashCode", new[] { ft }), null); gen.Emit(OpCodes.Xor); } gen.Emit(OpCodes.Ret); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** ** ** Purpose: Wraps a stream and provides convenient read functionality ** for strings and primitive types. ** ** ============================================================*/ using System.Buffers.Binary; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; namespace System.IO { public class BinaryReader : IDisposable { private const int MaxCharBytesSize = 128; private Stream _stream; private byte[] _buffer; private Decoder _decoder; private byte[] _charBytes; private char[] _singleChar; private char[] _charBuffer; private int _maxCharsSize; // From MaxCharBytesSize & Encoding // Performance optimization for Read() w/ Unicode. Speeds us up by ~40% private bool _2BytesPerChar; private bool _isMemoryStream; // "do we sit on MemoryStream?" for Read/ReadInt32 perf private bool _leaveOpen; public BinaryReader(Stream input) : this(input, Encoding.UTF8, false) { } public BinaryReader(Stream input, Encoding encoding) : this(input, encoding, false) { } public BinaryReader(Stream input, Encoding encoding, bool leaveOpen) { if (input == null) { throw new ArgumentNullException(nameof(input)); } if (encoding == null) { throw new ArgumentNullException(nameof(encoding)); } if (!input.CanRead) { throw new ArgumentException(SR.Argument_StreamNotReadable); } _stream = input; _decoder = encoding.GetDecoder(); _maxCharsSize = encoding.GetMaxCharCount(MaxCharBytesSize); int minBufferSize = encoding.GetMaxByteCount(1); // max bytes per one char if (minBufferSize < 16) { minBufferSize = 16; } _buffer = new byte[minBufferSize]; // _charBuffer and _charBytes will be left null. // For Encodings that always use 2 bytes per char (or more), // special case them here to make Read() & Peek() faster. _2BytesPerChar = encoding is UnicodeEncoding; // check if BinaryReader is based on MemoryStream, and keep this for it's life // we cannot use "as" operator, since derived classes are not allowed _isMemoryStream = (_stream.GetType() == typeof(MemoryStream)); _leaveOpen = leaveOpen; Debug.Assert(_decoder != null, "[BinaryReader.ctor]_decoder!=null"); } public virtual Stream BaseStream { get { return _stream; } } protected virtual void Dispose(bool disposing) { if (disposing) { Stream copyOfStream = _stream; _stream = null; if (copyOfStream != null && !_leaveOpen) { copyOfStream.Close(); } } _isMemoryStream = false; _stream = null; _buffer = null; _decoder = null; _charBytes = null; _singleChar = null; _charBuffer = null; } public void Dispose() { Dispose(true); } /// <remarks> /// Override Dispose(bool) instead of Close(). This API exists for compatibility purposes. /// </remarks> public virtual void Close() { Dispose(true); } public virtual int PeekChar() { if (_stream == null) { throw Error.GetFileNotOpen(); } if (!_stream.CanSeek) { return -1; } long origPos = _stream.Position; int ch = Read(); _stream.Position = origPos; return ch; } public virtual int Read() { if (_stream == null) { throw Error.GetFileNotOpen(); } int charsRead = 0; int numBytes = 0; long posSav = 0; if (_stream.CanSeek) { posSav = _stream.Position; } if (_charBytes == null) { _charBytes = new byte[MaxCharBytesSize]; //REVIEW: We need at most 2 bytes/char here? } if (_singleChar == null) { _singleChar = new char[1]; } while (charsRead == 0) { // We really want to know what the minimum number of bytes per char // is for our encoding. Otherwise for UnicodeEncoding we'd have to // do ~1+log(n) reads to read n characters. // Assume 1 byte can be 1 char unless _2BytesPerChar is true. numBytes = _2BytesPerChar ? 2 : 1; int r = _stream.ReadByte(); _charBytes[0] = (byte)r; if (r == -1) { numBytes = 0; } if (numBytes == 2) { r = _stream.ReadByte(); _charBytes[1] = (byte)r; if (r == -1) { numBytes = 1; } } if (numBytes == 0) { return -1; } Debug.Assert(numBytes == 1 || numBytes == 2, "BinaryReader::ReadOneChar assumes it's reading one or 2 bytes only."); try { charsRead = _decoder.GetChars(_charBytes, 0, numBytes, _singleChar, 0); } catch { // Handle surrogate char if (_stream.CanSeek) { _stream.Seek((posSav - _stream.Position), SeekOrigin.Current); } // else - we can't do much here throw; } Debug.Assert(charsRead < 2, "BinaryReader::ReadOneChar - assuming we only got 0 or 1 char, not 2!"); } Debug.Assert(charsRead > 0); return _singleChar[0]; } public virtual byte ReadByte() => InternalReadByte(); [MethodImpl(MethodImplOptions.AggressiveInlining)] private byte InternalReadByte() { // Inlined to avoid some method call overhead with InternalRead. if (_stream == null) { throw Error.GetFileNotOpen(); } int b = _stream.ReadByte(); if (b == -1) { throw Error.GetEndOfFile(); } return (byte)b; } [CLSCompliant(false)] public virtual sbyte ReadSByte() => (sbyte)InternalReadByte(); public virtual bool ReadBoolean() => InternalReadByte() != 0; public virtual char ReadChar() { int value = Read(); if (value == -1) { throw Error.GetEndOfFile(); } return (char)value; } public virtual short ReadInt16() => BinaryPrimitives.ReadInt16LittleEndian(InternalRead(2)); [CLSCompliant(false)] public virtual ushort ReadUInt16() => BinaryPrimitives.ReadUInt16LittleEndian(InternalRead(2)); public virtual int ReadInt32() => BinaryPrimitives.ReadInt32LittleEndian(InternalRead(4)); [CLSCompliant(false)] public virtual uint ReadUInt32() => BinaryPrimitives.ReadUInt32LittleEndian(InternalRead(4)); public virtual long ReadInt64() => BinaryPrimitives.ReadInt64LittleEndian(InternalRead(8)); [CLSCompliant(false)] public virtual ulong ReadUInt64() => BinaryPrimitives.ReadUInt64LittleEndian(InternalRead(8)); public virtual unsafe float ReadSingle() => BitConverter.Int32BitsToSingle(BinaryPrimitives.ReadInt32LittleEndian(InternalRead(4))); public virtual unsafe double ReadDouble() => BitConverter.Int64BitsToDouble(BinaryPrimitives.ReadInt64LittleEndian(InternalRead(8))); public virtual decimal ReadDecimal() { ReadOnlySpan<byte> span = InternalRead(16); try { return decimal.ToDecimal(span); } catch (ArgumentException e) { // ReadDecimal cannot leak out ArgumentException throw new IOException(SR.Arg_DecBitCtor, e); } } public virtual string ReadString() { if (_stream == null) { throw Error.GetFileNotOpen(); } int currPos = 0; int n; int stringLength; int readLength; int charsRead; // Length of the string in bytes, not chars stringLength = Read7BitEncodedInt(); if (stringLength < 0) { throw new IOException(SR.Format(SR.IO_InvalidStringLen_Len, stringLength)); } if (stringLength == 0) { return string.Empty; } if (_charBytes == null) { _charBytes = new byte[MaxCharBytesSize]; } if (_charBuffer == null) { _charBuffer = new char[_maxCharsSize]; } StringBuilder sb = null; do { readLength = ((stringLength - currPos) > MaxCharBytesSize) ? MaxCharBytesSize : (stringLength - currPos); n = _stream.Read(_charBytes, 0, readLength); if (n == 0) { throw Error.GetEndOfFile(); } charsRead = _decoder.GetChars(_charBytes, 0, n, _charBuffer, 0); if (currPos == 0 && n == stringLength) { return new string(_charBuffer, 0, charsRead); } if (sb == null) { sb = StringBuilderCache.Acquire(stringLength); // Actual string length in chars may be smaller. } sb.Append(_charBuffer, 0, charsRead); currPos += n; } while (currPos < stringLength); return StringBuilderCache.GetStringAndRelease(sb); } public virtual int Read(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } if (_stream == null) { throw Error.GetFileNotOpen(); } // SafeCritical: index and count have already been verified to be a valid range for the buffer return InternalReadChars(new Span<char>(buffer, index, count)); } public virtual int Read(Span<char> buffer) { if (_stream == null) { throw Error.GetFileNotOpen(); } return InternalReadChars(buffer); } private int InternalReadChars(Span<char> buffer) { Debug.Assert(_stream != null); int numBytes = 0; int index = 0; int charsRemaining = buffer.Length; if (_charBytes == null) { _charBytes = new byte[MaxCharBytesSize]; } while (charsRemaining > 0) { int charsRead = 0; // We really want to know what the minimum number of bytes per char // is for our encoding. Otherwise for UnicodeEncoding we'd have to // do ~1+log(n) reads to read n characters. numBytes = charsRemaining; if (_2BytesPerChar) { numBytes <<= 1; } if (numBytes > MaxCharBytesSize) { numBytes = MaxCharBytesSize; } int position = 0; byte[] byteBuffer = null; if (_isMemoryStream) { Debug.Assert(_stream is MemoryStream); MemoryStream mStream = (MemoryStream)_stream; position = mStream.InternalGetPosition(); numBytes = mStream.InternalEmulateRead(numBytes); byteBuffer = mStream.InternalGetBuffer(); } else { numBytes = _stream.Read(_charBytes, 0, numBytes); byteBuffer = _charBytes; } if (numBytes == 0) { return (buffer.Length - charsRemaining); } Debug.Assert(byteBuffer != null, "expected byteBuffer to be non-null"); checked { if (position < 0 || numBytes < 0 || position > byteBuffer.Length - numBytes) { throw new ArgumentOutOfRangeException(nameof(numBytes)); } if (index < 0 || charsRemaining < 0 || index > buffer.Length - charsRemaining) { throw new ArgumentOutOfRangeException(nameof(charsRemaining)); } unsafe { fixed (byte* pBytes = byteBuffer) fixed (char* pChars = &MemoryMarshal.GetReference(buffer)) { charsRead = _decoder.GetChars(pBytes + position, numBytes, pChars + index, charsRemaining, flush: false); } } } charsRemaining -= charsRead; index += charsRead; } // this should never fail Debug.Assert(charsRemaining >= 0, "We read too many characters."); // we may have read fewer than the number of characters requested if end of stream reached // or if the encoding makes the char count too big for the buffer (e.g. fallback sequence) return (buffer.Length - charsRemaining); } public virtual char[] ReadChars(int count) { if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (_stream == null) { throw Error.GetFileNotOpen(); } if (count == 0) { return Array.Empty<char>(); } // SafeCritical: we own the chars buffer, and therefore can guarantee that the index and count are valid char[] chars = new char[count]; int n = InternalReadChars(new Span<char>(chars)); if (n != count) { char[] copy = new char[n]; Buffer.BlockCopy(chars, 0, copy, 0, 2 * n); // sizeof(char) chars = copy; } return chars; } public virtual int Read(byte[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } if (_stream == null) { throw Error.GetFileNotOpen(); } return _stream.Read(buffer, index, count); } public virtual int Read(Span<byte> buffer) { if (_stream == null) { throw Error.GetFileNotOpen(); } return _stream.Read(buffer); } public virtual byte[] ReadBytes(int count) { if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed); } if (count == 0) { return Array.Empty<byte>(); } byte[] result = new byte[count]; int numRead = 0; do { int n = _stream.Read(result, numRead, count); if (n == 0) { break; } numRead += n; count -= n; } while (count > 0); if (numRead != result.Length) { // Trim array. This should happen on EOF & possibly net streams. byte[] copy = new byte[numRead]; Buffer.BlockCopy(result, 0, copy, 0, numRead); result = copy; } return result; } private ReadOnlySpan<byte> InternalRead(int numBytes) { Debug.Assert(numBytes >= 2 && numBytes <= 16, "value of 1 should use ReadByte. value > 16 requires to change the minimal _buffer size"); if (_isMemoryStream) { // no need to check if _stream == null as we will never have null _stream when _isMemoryStream = true // read directly from MemoryStream buffer Debug.Assert(_stream is MemoryStream); return ((MemoryStream)_stream).InternalReadSpan(numBytes); } else { if (_stream == null) { throw Error.GetFileNotOpen(); } int bytesRead = 0; int n = 0; do { n = _stream.Read(_buffer, bytesRead, numBytes - bytesRead); if (n == 0) { throw Error.GetEndOfFile(); } bytesRead += n; } while (bytesRead < numBytes); return _buffer; } } // FillBuffer is not performing well when reading from MemoryStreams as it is using the public Stream interface. // We introduced new function InternalRead which can work directly on the MemoryStream internal buffer or using the public Stream // interface when working with all other streams. This function is not needed anymore but we decided not to delete it for compatibility // reasons. More about the subject in: https://github.com/dotnet/coreclr/pull/22102 protected virtual void FillBuffer(int numBytes) { if (_buffer != null && (numBytes < 0 || numBytes > _buffer.Length)) { throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_BinaryReaderFillBuffer); } int bytesRead = 0; int n = 0; if (_stream == null) { throw Error.GetFileNotOpen(); } // Need to find a good threshold for calling ReadByte() repeatedly // vs. calling Read(byte[], int, int) for both buffered & unbuffered // streams. if (numBytes == 1) { n = _stream.ReadByte(); if (n == -1) { throw Error.GetEndOfFile(); } _buffer[0] = (byte)n; return; } do { n = _stream.Read(_buffer, bytesRead, numBytes - bytesRead); if (n == 0) { throw Error.GetEndOfFile(); } bytesRead += n; } while (bytesRead < numBytes); } protected internal int Read7BitEncodedInt() { // Read out an Int32 7 bits at a time. The high bit // of the byte when on means to continue reading more bytes. int count = 0; int shift = 0; byte b; do { // Check for a corrupted stream. Read a max of 5 bytes. // In a future version, add a DataFormatException. if (shift == 5 * 7) // 5 bytes max per Int32, shift += 7 { throw new FormatException(SR.Format_Bad7BitInt32); } // ReadByte handles end of stream cases for us. b = ReadByte(); count |= (b & 0x7F) << shift; shift += 7; } while ((b & 0x80) != 0); return count; } } }
/* * Copyright 2012 ZXing authors * * 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. */ namespace ZXing.PDF417.Internal.EC { /// <summary> /// <p>PDF417 error correction implementation.</p> /// <p>This <a href="http://en.wikipedia.org/wiki/Reed%E2%80%93Solomon_error_correction#Example">example</a> /// is quite useful in understanding the algorithm.</p> /// <author>Sean Owen</author> /// <see cref="ZXing.Common.ReedSolomon.ReedSolomonDecoder" /> /// </summary> public sealed class ErrorCorrection { private readonly ModulusGF field; /// <summary> /// Initializes a new instance of the <see cref="ErrorCorrection"/> class. /// </summary> public ErrorCorrection() { this.field = ModulusGF.PDF417_GF; } /// <summary> /// Decodes the specified received. /// </summary> /// <param name="received">The received.</param> /// <param name="numECCodewords">The num EC codewords.</param> /// <param name="erasures">The erasures.</param> /// <returns></returns> public bool decode(int[] received, int numECCodewords, int[] erasures) { ModulusPoly poly = new ModulusPoly(field, received); int[] S = new int[numECCodewords]; bool error = false; for (int i = numECCodewords; i > 0; i--) { int eval = poly.evaluateAt(field.exp(i)); S[numECCodewords - i] = eval; if (eval != 0) { error = true; } } if (error) { ModulusPoly knownErrors = field.getOne(); foreach (int erasure in erasures) { int b = field.exp(received.Length - 1 - erasure); // Add (1 - bx) term: ModulusPoly term = new ModulusPoly(field, new int[] { field.subtract(0, b), 1 }); knownErrors = knownErrors.multiply(term); } ModulusPoly syndrome = new ModulusPoly(field, S); //syndrome = syndrome.multiply(knownErrors); ModulusPoly[] sigmaOmega = runEuclideanAlgorithm(field.buildMonomial(numECCodewords, 1), syndrome, numECCodewords); if (sigmaOmega == null) return false; ModulusPoly sigma = sigmaOmega[0]; ModulusPoly omega = sigmaOmega[1]; //sigma = sigma.multiply(knownErrors); int[] errorLocations = findErrorLocations(sigma); if (errorLocations == null) return false; int[] errorMagnitudes = findErrorMagnitudes(omega, sigma, errorLocations); if (errorMagnitudes == null) return false; for (int i = 0; i < errorLocations.Length; i++) { int position = received.Length - 1 - field.log(errorLocations[i]); if (position < 0) { return false; } received[position] = field.subtract(received[position], errorMagnitudes[i]); } } return true; } private ModulusPoly[] runEuclideanAlgorithm(ModulusPoly a, ModulusPoly b, int R) { // Assume a's degree is >= b's if (a.Degree < b.Degree) { ModulusPoly temp = a; a = b; b = temp; } ModulusPoly rLast = a; ModulusPoly r = b; ModulusPoly tLast = field.getZero(); ModulusPoly t = field.getOne(); // Run Euclidean algorithm until r's degree is less than R/2 while (r.Degree >= R / 2) { ModulusPoly rLastLast = rLast; ModulusPoly tLastLast = tLast; rLast = r; tLast = t; // Divide rLastLast by rLast, with quotient in q and remainder in r if (rLast.isZero) { // Oops, Euclidean algorithm already terminated? return null; } r = rLastLast; ModulusPoly q = field.getZero(); int denominatorLeadingTerm = rLast.getCoefficient(rLast.Degree); int dltInverse = field.inverse(denominatorLeadingTerm); while (r.Degree >= rLast.Degree && !r.isZero) { int degreeDiff = r.Degree - rLast.Degree; int scale = field.multiply(r.getCoefficient(r.Degree), dltInverse); q = q.add(field.buildMonomial(degreeDiff, scale)); r = r.subtract(rLast.multiplyByMonomial(degreeDiff, scale)); } t = q.multiply(tLast).subtract(tLastLast).negative(); } int sigmaTildeAtZero = t.getCoefficient(0); if (sigmaTildeAtZero == 0) { return null; } int inverse = field.inverse(sigmaTildeAtZero); ModulusPoly sigma = t.multiply(inverse); ModulusPoly omega = r.multiply(inverse); return new ModulusPoly[] { sigma, omega }; } private int[] findErrorLocations(ModulusPoly errorLocator) { // This is a direct application of Chien's search int numErrors = errorLocator.Degree; int[] result = new int[numErrors]; int e = 0; for (int i = 1; i < field.Size && e < numErrors; i++) { if (errorLocator.evaluateAt(i) == 0) { result[e] = field.inverse(i); e++; } } if (e != numErrors) { return null; } return result; } private int[] findErrorMagnitudes(ModulusPoly errorEvaluator, ModulusPoly errorLocator, int[] errorLocations) { int errorLocatorDegree = errorLocator.Degree; int[] formalDerivativeCoefficients = new int[errorLocatorDegree]; for (int i = 1; i <= errorLocatorDegree; i++) { formalDerivativeCoefficients[errorLocatorDegree - i] = field.multiply(i, errorLocator.getCoefficient(i)); } ModulusPoly formalDerivative = new ModulusPoly(field, formalDerivativeCoefficients); // This is directly applying Forney's Formula int s = errorLocations.Length; int[] result = new int[s]; for (int i = 0; i < s; i++) { int xiInverse = field.inverse(errorLocations[i]); int numerator = field.subtract(0, errorEvaluator.evaluateAt(xiInverse)); int denominator = field.inverse(formalDerivative.evaluateAt(xiInverse)); result[i] = field.multiply(numerator, denominator); } return result; } } }
using Xunit; namespace Jint.Tests.Ecma { public class Test_11_9_1 : EcmaTest { [Fact] [Trait("Category", "11.9.1")] public void WhiteSpaceAndLineTerminatorBetweenEqualityexpressionAndOrBetweenAndRelationalexpressionAreAllowed() { RunTest(@"TestCases/ch11/11.9/11.9.1/S11.9.1_A1.js", false); } [Fact] [Trait("Category", "11.9.1")] public void OperatorXYUsesGetvalue() { RunTest(@"TestCases/ch11/11.9/11.9.1/S11.9.1_A2.1_T1.js", false); } [Fact] [Trait("Category", "11.9.1")] public void OperatorXYUsesGetvalue2() { RunTest(@"TestCases/ch11/11.9/11.9.1/S11.9.1_A2.1_T2.js", false); } [Fact] [Trait("Category", "11.9.1")] public void OperatorXYUsesGetvalue3() { RunTest(@"TestCases/ch11/11.9/11.9.1/S11.9.1_A2.1_T3.js", false); } [Fact] [Trait("Category", "11.9.1")] public void FirstExpressionIsEvaluatedFirstAndThenSecondExpression() { RunTest(@"TestCases/ch11/11.9/11.9.1/S11.9.1_A2.4_T1.js", false); } [Fact] [Trait("Category", "11.9.1")] public void FirstExpressionIsEvaluatedFirstAndThenSecondExpression2() { RunTest(@"TestCases/ch11/11.9/11.9.1/S11.9.1_A2.4_T2.js", false); } [Fact] [Trait("Category", "11.9.1")] public void FirstExpressionIsEvaluatedFirstAndThenSecondExpression3() { RunTest(@"TestCases/ch11/11.9/11.9.1/S11.9.1_A2.4_T3.js", false); } [Fact] [Trait("Category", "11.9.1")] public void ReturnTrueIfXAndYAreBothTrueOrBothFalseOtherwiseReturnFalse() { RunTest(@"TestCases/ch11/11.9/11.9.1/S11.9.1_A3.1.js", false); } [Fact] [Trait("Category", "11.9.1")] public void IfTypeXIsBooleanAndTypeYIsNumberReturnTheResultOfComparisonTonumberXY() { RunTest(@"TestCases/ch11/11.9/11.9.1/S11.9.1_A3.2.js", false); } [Fact] [Trait("Category", "11.9.1")] public void IfTypeYIsNumberAndTypeYIsBooleanReturnTheResultOfComparisonXTonumberY() { RunTest(@"TestCases/ch11/11.9/11.9.1/S11.9.1_A3.3.js", false); } [Fact] [Trait("Category", "11.9.1")] public void IfXOrYIsNanReturnFalse() { RunTest(@"TestCases/ch11/11.9/11.9.1/S11.9.1_A4.1_T1.js", false); } [Fact] [Trait("Category", "11.9.1")] public void IfXOrYIsNanReturnFalse2() { RunTest(@"TestCases/ch11/11.9/11.9.1/S11.9.1_A4.1_T2.js", false); } [Fact] [Trait("Category", "11.9.1")] public void IfXIs00AndYIs00ReturnTrue() { RunTest(@"TestCases/ch11/11.9/11.9.1/S11.9.1_A4.2.js", false); } [Fact] [Trait("Category", "11.9.1")] public void TypeXAndTypeYAreNumberSMinusNan00ReturnTrueIfXIsTheSameNumberValueAsYOtherwiseReturnFalse() { RunTest(@"TestCases/ch11/11.9/11.9.1/S11.9.1_A4.3.js", false); } [Fact] [Trait("Category", "11.9.1")] public void TypeXAndTypeYAreStringSReturnTrueIfXAndYAreExactlyTheSameSequenceOfCharactersOtherwiseReturnFalse() { RunTest(@"TestCases/ch11/11.9/11.9.1/S11.9.1_A5.1.js", false); } [Fact] [Trait("Category", "11.9.1")] public void IfTypeXIsNumberAndTypeYIsStringReturnTheResultOfComparisonXTonumberY() { RunTest(@"TestCases/ch11/11.9/11.9.1/S11.9.1_A5.2.js", false); } [Fact] [Trait("Category", "11.9.1")] public void IfTypeXIsStringAndTypeYIsNumberReturnTheResultOfComparisonTonumberXY() { RunTest(@"TestCases/ch11/11.9/11.9.1/S11.9.1_A5.3.js", false); } [Fact] [Trait("Category", "11.9.1")] public void IfTypeXAsWellAsTypeYIsUndefinedOrNullReturnTrue() { RunTest(@"TestCases/ch11/11.9/11.9.1/S11.9.1_A6.1.js", false); } [Fact] [Trait("Category", "11.9.1")] public void IfOneExpressionIsUndefinedOrNullAndAnotherIsNotReturnFalse() { RunTest(@"TestCases/ch11/11.9/11.9.1/S11.9.1_A6.2_T1.js", false); } [Fact] [Trait("Category", "11.9.1")] public void IfOneExpressionIsUndefinedOrNullAndAnotherIsNotReturnFalse2() { RunTest(@"TestCases/ch11/11.9/11.9.1/S11.9.1_A6.2_T2.js", false); } [Fact] [Trait("Category", "11.9.1")] public void TypeXAndTypeYAreObjectSReturnTrueIfXAndYAreReferencesToTheSameObjectOtherwiseReturnFalse() { RunTest(@"TestCases/ch11/11.9/11.9.1/S11.9.1_A7.1.js", false); } [Fact] [Trait("Category", "11.9.1")] public void IfTypeXIsObjectAndTypeYIsBooleanReturnToprimitiveXY() { RunTest(@"TestCases/ch11/11.9/11.9.1/S11.9.1_A7.2.js", false); } [Fact] [Trait("Category", "11.9.1")] public void IfTypeXIsBooleanAndTypeYIsObjectReturnXToprimitiveY() { RunTest(@"TestCases/ch11/11.9/11.9.1/S11.9.1_A7.3.js", false); } [Fact] [Trait("Category", "11.9.1")] public void IfTypeXIsObjectAndTypeYIsNumberReturnToprimitiveXY() { RunTest(@"TestCases/ch11/11.9/11.9.1/S11.9.1_A7.4.js", false); } [Fact] [Trait("Category", "11.9.1")] public void IfTypeXIsNumberAndTypeYIsObjectReturnXToprimitiveY() { RunTest(@"TestCases/ch11/11.9/11.9.1/S11.9.1_A7.5.js", false); } [Fact] [Trait("Category", "11.9.1")] public void IfTypeXIsObjectAndTypeYIsStringReturnToprimitiveXY() { RunTest(@"TestCases/ch11/11.9/11.9.1/S11.9.1_A7.6.js", false); } [Fact] [Trait("Category", "11.9.1")] public void IfTypeXIsStringAndTypeYIsObjectReturnXToprimitiveY() { RunTest(@"TestCases/ch11/11.9/11.9.1/S11.9.1_A7.7.js", false); } [Fact] [Trait("Category", "11.9.1")] public void IfTypeXIsObjectAndTypeYIsPrimitiveTypeReturnToprimitiveXY() { RunTest(@"TestCases/ch11/11.9/11.9.1/S11.9.1_A7.8.js", false); } [Fact] [Trait("Category", "11.9.1")] public void IfTypeXIsPrimitiveTypeAndTypeYIsObjectReturnXToprimitiveY() { RunTest(@"TestCases/ch11/11.9/11.9.1/S11.9.1_A7.9.js", false); } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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. * */ using System; using System.Collections.Generic; using System.Linq; using ASC.Mail.Core.Engine; using ASC.Mail.Core.Entities; using ASC.Mail.Data.Contracts; using ASC.Mail.Enums; using ASC.Web.Studio.Utility; using ContactInfo = ASC.Mail.Data.Contracts.ContactInfo; namespace ASC.Mail.Extensions { public static class DataContractsExtensions { public static List<MailAccountData> ToAccountData(this AccountInfo account) { var fromEmailList = new List<MailAccountData>(); var mailBoxAccountSettings = MailBoxAccountSettings.LoadForCurrentUser(); var emailData = new MailAccountData { MailboxId = account.Id, Email = account.Email, Name = account.Name, Enabled = account.Enabled, OAuthConnection = account.OAuthConnection, AuthError = account.AuthError, QuotaError = account.QuotaError, Signature = account.Signature, Autoreply = account.Autoreply, EMailInFolder = account.EMailInFolder, IsAlias = false, IsGroup = false, IsTeamlabMailbox = account.IsTeamlabMailbox, IsDefault = mailBoxAccountSettings.DefaultEmail == account.Email, IsSharedDomainMailbox = account.IsSharedDomainMailbox }; fromEmailList.Add(emailData); foreach (var alias in account.Aliases) { emailData = new MailAccountData { MailboxId = account.Id, Email = alias.Email, Name = account.Name, Enabled = account.Enabled, OAuthConnection = false, AuthError = account.AuthError, QuotaError = account.QuotaError, Signature = account.Signature, Autoreply = account.Autoreply, EMailInFolder = account.EMailInFolder, IsAlias = true, IsGroup = false, IsTeamlabMailbox = account.IsTeamlabMailbox, IsDefault = mailBoxAccountSettings.DefaultEmail == alias.Email }; fromEmailList.Add(emailData); } foreach ( var @group in account.Groups.Where(@group => fromEmailList.FindIndex(e => e.Email.Equals(@group.Email)) == -1)) { emailData = new MailAccountData { MailboxId = account.Id, Email = @group.Email, Name = "", Enabled = true, OAuthConnection = false, AuthError = false, QuotaError = false, Signature = new MailSignatureData(-1, account.Signature.Tenant, "", false), Autoreply = new MailAutoreplyData(-1, account.Signature.Tenant, false, false, false, DateTime.MinValue, DateTime.MinValue, String.Empty, String.Empty), EMailInFolder = "", IsAlias = false, IsGroup = true, IsTeamlabMailbox = true }; fromEmailList.Add(emailData); } return fromEmailList; } public static List<MailAccountData> ToAccountData(this List<AccountInfo> accounts) { var fromEmailList = new List<MailAccountData>(); fromEmailList = accounts.Aggregate(fromEmailList, (current, account) => current.Concat(account.ToAccountData()).ToList()); return fromEmailList.DistinctBy(a => a.Email).ToList(); } private const string BASE_VIRTUAL_PATH = "~/addons/mail/"; public static MailContactData ToMailContactData(this ContactCard contactCard) { var baseAbsolutePath = CommonLinkUtility.ToAbsolute(BASE_VIRTUAL_PATH).ToLower(); var emails = new MailContactData.EmailsList<ContactInfo>(); var phones = new MailContactData.PhoneNumgersList<ContactInfo>(); foreach (var contact in contactCard.ContactItems) { if (contact.Type == (int)ContactInfoType.Email) { if (contact.IsPrimary) emails.Insert(0, new ContactInfo { Id = contact.Id, Value = contact.Data, IsPrimary = contact.IsPrimary }); else emails.Add(new ContactInfo { Id = contact.Id, Value = contact.Data, IsPrimary = contact.IsPrimary }); } else if (contact.Type == (int)ContactInfoType.Phone) { if (contact.IsPrimary) phones.Insert(0, new ContactInfo { Id = contact.Id, Value = contact.Data, IsPrimary = contact.IsPrimary }); else phones.Add(new ContactInfo { Id = contact.Id, Value = contact.Data, IsPrimary = contact.IsPrimary }); } } var contactData = new MailContactData { ContactId = contactCard.ContactInfo.Id, Name = contactCard.ContactInfo.ContactName, Description = contactCard.ContactInfo.Description, Emails = emails, PhoneNumbers = phones, Type = (int)contactCard.ContactInfo.Type, SmallFotoUrl = string.Format("{0}HttpHandlers/contactphoto.ashx?cid={1}&ps=1", baseAbsolutePath, contactCard.ContactInfo.Id) .ToLower(), MediumFotoUrl = string.Format("{0}HttpHandlers/contactphoto.ashx?cid={1}&ps=2", baseAbsolutePath, contactCard.ContactInfo.Id) .ToLower() }; return contactData; } public static List<MailContactData> ToMailContactDataList(this List<ContactCard> contacts) { var contactsList = contacts.Select(contact => contact.ToMailContactData()).ToList(); return contactsList; } public static void GetNeededAccounts(this List<MailAccountData> accounts, out MailAccountData defaultAccount, out List<MailAccountData> commonAccounts, out List<MailAccountData> serverAccounts, out List<MailAccountData> aliases, out List<MailAccountData> groups) { defaultAccount = null; commonAccounts = new List<MailAccountData>(); serverAccounts = new List<MailAccountData>(); aliases = new List<MailAccountData>(); groups = new List<MailAccountData>(); if (accounts == null) { return; } foreach (var account in accounts) { if (account.IsDefault) { defaultAccount = account; } else if (account.IsGroup) { groups.Add(account); } else if (account.IsAlias) { aliases.Add(account); } else if (account.IsTeamlabMailbox) { serverAccounts.Add(account); } else { commonAccounts.Add(account); } } } public static List<MailFolderData> ToFolderData(this List<FolderEngine.MailFolderInfo> folders) { return folders.Select(ToFolderData).ToList(); } public static MailFolderData ToFolderData(this FolderEngine.MailFolderInfo folder) { return new MailFolderData { Id = folder.id, UnreadCount = folder.unread, UnreadMessagesCount = folder.unreadMessages, TotalCount = folder.total, TotalMessgesCount = folder.totalMessages, TimeModified = folder.timeModified }; } public static MailTagData ToTagData(this Tag tag) { return new MailTagData { Id = tag.Id, Name = tag.TagName, Style = tag.Style, Addresses = new MailTagData.AddressesList<string>(tag.Addresses.Split(';')), LettersCount = tag.Count }; } public static List<MailTagData> ToTagData(this List<Tag> tags) { return tags .Select(t => new MailTagData { Id = t.Id, Name = t.TagName, Style = t.Style, Addresses = new MailTagData.AddressesList<string>(t.Addresses.Split(';')), LettersCount = t.Count }) .ToList(); } public static Attachment ToAttachmnet(this MailAttachmentData a, int mailId, bool isRemoved = false) { var attachment = new Attachment { Id = a.fileId, MailId = mailId, Name = a.fileName, StoredName = a.storedName, Type = a.contentType, Size = a.size, FileNumber = a.fileNumber, IsRemoved = isRemoved, ContentId = a.contentId, Tenant = a.tenant, MailboxId = a.mailboxId }; return attachment; } } }
using System; using System.Collections; using System.Collections.Generic; /// <summary> /// System.Collections.IDictionary.get_Item(System.Object) /// </summary> public class DictionaryIDictionaryItem { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; // // TODO: Add your negative test cases here // // TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest1: Verify property IDictionaryItem(get) ."); try { IDictionary dictionary = new Dictionary<string, string>(); dictionary.Add("txt", "notepad.exe"); dictionary.Add("bmp", "paint.exe"); dictionary.Add("dib", "paint.exe"); dictionary.Add("rtf", "wordpad.exe"); bool testVerify = dictionary["txt"].Equals("notepad.exe") && dictionary["bmp"].Equals("paint.exe") && dictionary["dib"].Equals("paint.exe") && dictionary["rtf"].Equals("wordpad.exe"); if (testVerify != true) { TestLibrary.TestFramework.LogError("001.1", "Property IDictionaryItem(get) Err ."); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; // Add your scenario description here TestLibrary.TestFramework.BeginScenario("PosTest2: Verify property IDictionaryItem(set) ."); try { IDictionary dictionary = new Dictionary<string, string>(); dictionary.Add("txt", "notepad.exe"); dictionary.Add("bmp", "paint.exe"); dictionary.Add("dib", "paint.exe"); dictionary.Add("rtf", "wordpad.exe"); dictionary["txt"] = "updated"; if (!dictionary["txt"].Equals("updated")) { TestLibrary.TestFramework.LogError("002.1", "Property IDictionaryItem(set) Err ."); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentNullException is not thrown ."); try { IDictionary dictionary = new Dictionary<string, string>(); dictionary.Add("txt", "notepad.exe"); dictionary.Add("bmp", "paint.exe"); dictionary.Add("dib", "paint.exe"); dictionary.Add("rtf", "wordpad.exe"); string key = null; dictionary[key] = "updated"; TestLibrary.TestFramework.LogError("101.1", "ArgumentNullException is not thrown."); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: ArgumentException is not thrown ."); try { IDictionary dictionary = new Dictionary<string, string>(); dictionary.Add("txt", "notepad.exe"); dictionary.Add("bmp", "paint.exe"); dictionary.Add("dib", "paint.exe"); dictionary.Add("rtf", "wordpad.exe"); object key = new object(); dictionary[key] = "updated"; TestLibrary.TestFramework.LogError("102.1", "ArgumentNullException is not thrown."); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3: ArgumentException is not thrown ."); try { IDictionary dictionary = new Dictionary<string, string>(); dictionary.Add("txt", "notepad.exe"); dictionary.Add("bmp", "paint.exe"); dictionary.Add("dib", "paint.exe"); dictionary.Add("rtf", "wordpad.exe"); object updated = new object(); dictionary["txt"] = updated; TestLibrary.TestFramework.LogError("102.1", "ArgumentNullException is not thrown."); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { DictionaryIDictionaryItem test = new DictionaryIDictionaryItem(); TestLibrary.TestFramework.BeginTestCase("DictionaryIDictionaryItem"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } }
using System; namespace ICSharpCode.SharpZipLib.Core { #region EventArgs /// <summary> /// Event arguments for scanning. /// </summary> public class ScanEventArgs : EventArgs { #region Constructors /// <summary> /// Initialise a new instance of <see cref="ScanEventArgs"/> /// </summary> /// <param name="name">The file or directory name.</param> public ScanEventArgs(string name) { name_ = name; } #endregion /// <summary> /// The file or directory name for this event. /// </summary> public string Name { get { return name_; } } /// <summary> /// Get set a value indicating if scanning should continue or not. /// </summary> public bool ContinueRunning { get { return continueRunning_; } set { continueRunning_ = value; } } #region Instance Fields string name_; bool continueRunning_ = true; #endregion } /// <summary> /// Event arguments during processing of a single file or directory. /// </summary> public class ProgressEventArgs : EventArgs { #region Constructors /// <summary> /// Initialise a new instance of <see cref="ScanEventArgs"/> /// </summary> /// <param name="name">The file or directory name if known.</param> /// <param name="processed">The number of bytes processed so far</param> /// <param name="target">The total number of bytes to process, 0 if not known</param> public ProgressEventArgs(string name, long processed, long target) { name_ = name; processed_ = processed; target_ = target; } #endregion /// <summary> /// The name for this event if known. /// </summary> public string Name { get { return name_; } } /// <summary> /// Get set a value indicating wether scanning should continue or not. /// </summary> public bool ContinueRunning { get { return continueRunning_; } set { continueRunning_ = value; } } /// <summary> /// Get a percentage representing how much of the <see cref="Target"></see> has been processed /// </summary> /// <value>0.0 to 100.0 percent; 0 if target is not known.</value> public float PercentComplete { get { float result; if (target_ <= 0) { result = 0; } else { result = ((float)processed_ / (float)target_) * 100.0f; } return result; } } /// <summary> /// The number of bytes processed so far /// </summary> public long Processed { get { return processed_; } } /// <summary> /// The number of bytes to process. /// </summary> /// <remarks>Target may be 0 or negative if the value isnt known.</remarks> public long Target { get { return target_; } } #region Instance Fields string name_; long processed_; long target_; bool continueRunning_ = true; #endregion } /// <summary> /// Event arguments for directories. /// </summary> public class DirectoryEventArgs : ScanEventArgs { #region Constructors /// <summary> /// Initialize an instance of <see cref="DirectoryEventArgs"></see>. /// </summary> /// <param name="name">The name for this directory.</param> /// <param name="hasMatchingFiles">Flag value indicating if any matching files are contained in this directory.</param> public DirectoryEventArgs(string name, bool hasMatchingFiles) : base(name) { hasMatchingFiles_ = hasMatchingFiles; } #endregion /// <summary> /// Get a value indicating if the directory contains any matching files or not. /// </summary> public bool HasMatchingFiles { get { return hasMatchingFiles_; } } readonly #region Instance Fields bool hasMatchingFiles_; #endregion } /// <summary> /// Arguments passed when scan failures are detected. /// </summary> public class ScanFailureEventArgs : EventArgs { #region Constructors /// <summary> /// Initialise a new instance of <see cref="ScanFailureEventArgs"></see> /// </summary> /// <param name="name">The name to apply.</param> /// <param name="e">The exception to use.</param> public ScanFailureEventArgs(string name, Exception e) { name_ = name; exception_ = e; continueRunning_ = true; } #endregion /// <summary> /// The applicable name. /// </summary> public string Name { get { return name_; } } /// <summary> /// The applicable exception. /// </summary> public Exception Exception { get { return exception_; } } /// <summary> /// Get / set a value indicating wether scanning should continue. /// </summary> public bool ContinueRunning { get { return continueRunning_; } set { continueRunning_ = value; } } #region Instance Fields string name_; Exception exception_; bool continueRunning_; #endregion } #endregion #region Delegates /// <summary> /// Delegate invoked before starting to process a file. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> public delegate void ProcessFileHandler(object sender, ScanEventArgs e); /// <summary> /// Delegate invoked during processing of a file or directory /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> public delegate void ProgressHandler(object sender, ProgressEventArgs e); /// <summary> /// Delegate invoked when a file has been completely processed. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> public delegate void CompletedFileHandler(object sender, ScanEventArgs e); /// <summary> /// Delegate invoked when a directory failure is detected. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> public delegate void DirectoryFailureHandler(object sender, ScanFailureEventArgs e); /// <summary> /// Delegate invoked when a file failure is detected. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> public delegate void FileFailureHandler(object sender, ScanFailureEventArgs e); #endregion /// <summary> /// FileSystemScanner provides facilities scanning of files and directories. /// </summary> public class FileSystemScanner { #region Constructors /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="filter">The <see cref="PathFilter">file filter</see> to apply when scanning.</param> public FileSystemScanner(string filter) { fileFilter_ = new PathFilter(filter); } /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="fileFilter">The <see cref="PathFilter">file filter</see> to apply.</param> /// <param name="directoryFilter">The <see cref="PathFilter"> directory filter</see> to apply.</param> public FileSystemScanner(string fileFilter, string directoryFilter) { fileFilter_ = new PathFilter(fileFilter); directoryFilter_ = new PathFilter(directoryFilter); } /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="fileFilter">The file <see cref="IScanFilter">filter</see> to apply.</param> public FileSystemScanner(IScanFilter fileFilter) { fileFilter_ = fileFilter; } /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="fileFilter">The file <see cref="IScanFilter">filter</see> to apply.</param> /// <param name="directoryFilter">The directory <see cref="IScanFilter">filter</see> to apply.</param> public FileSystemScanner(IScanFilter fileFilter, IScanFilter directoryFilter) { fileFilter_ = fileFilter; directoryFilter_ = directoryFilter; } #endregion #region Delegates /// <summary> /// Delegate to invoke when a directory is processed. /// </summary> public event EventHandler<DirectoryEventArgs> ProcessDirectory; /// <summary> /// Delegate to invoke when a file is processed. /// </summary> public ProcessFileHandler ProcessFile; /// <summary> /// Delegate to invoke when processing for a file has finished. /// </summary> public CompletedFileHandler CompletedFile; /// <summary> /// Delegate to invoke when a directory failure is detected. /// </summary> public DirectoryFailureHandler DirectoryFailure; /// <summary> /// Delegate to invoke when a file failure is detected. /// </summary> public FileFailureHandler FileFailure; #endregion /// <summary> /// Raise the DirectoryFailure event. /// </summary> /// <param name="directory">The directory name.</param> /// <param name="e">The exception detected.</param> bool OnDirectoryFailure(string directory, Exception e) { DirectoryFailureHandler handler = DirectoryFailure; bool result = (handler != null); if (result) { var args = new ScanFailureEventArgs(directory, e); handler(this, args); alive_ = args.ContinueRunning; } return result; } /// <summary> /// Raise the FileFailure event. /// </summary> /// <param name="file">The file name.</param> /// <param name="e">The exception detected.</param> bool OnFileFailure(string file, Exception e) { FileFailureHandler handler = FileFailure; bool result = (handler != null); if (result) { var args = new ScanFailureEventArgs(file, e); FileFailure(this, args); alive_ = args.ContinueRunning; } return result; } /// <summary> /// Raise the ProcessFile event. /// </summary> /// <param name="file">The file name.</param> void OnProcessFile(string file) { ProcessFileHandler handler = ProcessFile; if (handler != null) { var args = new ScanEventArgs(file); handler(this, args); alive_ = args.ContinueRunning; } } /// <summary> /// Raise the complete file event /// </summary> /// <param name="file">The file name</param> void OnCompleteFile(string file) { CompletedFileHandler handler = CompletedFile; if (handler != null) { var args = new ScanEventArgs(file); handler(this, args); alive_ = args.ContinueRunning; } } /// <summary> /// Raise the ProcessDirectory event. /// </summary> /// <param name="directory">The directory name.</param> /// <param name="hasMatchingFiles">Flag indicating if the directory has matching files.</param> void OnProcessDirectory(string directory, bool hasMatchingFiles) { EventHandler<DirectoryEventArgs> handler = ProcessDirectory; if (handler != null) { var args = new DirectoryEventArgs(directory, hasMatchingFiles); handler(this, args); alive_ = args.ContinueRunning; } } /// <summary> /// Scan a directory. /// </summary> /// <param name="directory">The base directory to scan.</param> /// <param name="recurse">True to recurse subdirectories, false to scan a single directory.</param> public void Scan(string directory, bool recurse) { alive_ = true; ScanDir(directory, recurse); } void ScanDir(string directory, bool recurse) { try { string[] names = System.IO.Directory.GetFiles(directory); bool hasMatch = false; for (int fileIndex = 0; fileIndex < names.Length; ++fileIndex) { if (!fileFilter_.IsMatch(names[fileIndex])) { names[fileIndex] = null; } else { hasMatch = true; } } OnProcessDirectory(directory, hasMatch); if (alive_ && hasMatch) { foreach (string fileName in names) { try { if (fileName != null) { OnProcessFile(fileName); if (!alive_) { break; } } } catch (Exception e) { if (!OnFileFailure(fileName, e)) { throw; } } } } } catch (Exception e) { if (!OnDirectoryFailure(directory, e)) { throw; } } if (alive_ && recurse) { try { string[] names = System.IO.Directory.GetDirectories(directory); foreach (string fulldir in names) { if ((directoryFilter_ == null) || (directoryFilter_.IsMatch(fulldir))) { ScanDir(fulldir, true); if (!alive_) { break; } } } } catch (Exception e) { if (!OnDirectoryFailure(directory, e)) { throw; } } } } #region Instance Fields /// <summary> /// The file filter currently in use. /// </summary> IScanFilter fileFilter_; /// <summary> /// The directory filter currently in use. /// </summary> IScanFilter directoryFilter_; /// <summary> /// Flag indicating if scanning should continue running. /// </summary> bool alive_; #endregion } }
#define STEAMNETWORKINGSOCKETS_ENABLE_SDR // This file is provided under The MIT License as part of Steamworks.NET. // Copyright (c) 2013-2021 Riley Labrecque // Please see the included LICENSE.txt for additional information. // This file is automatically generated. // Changes to this file will be reverted when you update Steamworks.NET #if !(UNITY_STANDALONE_WIN || UNITY_STANDALONE_LINUX || UNITY_STANDALONE_OSX || STEAMWORKS_WIN || STEAMWORKS_LIN_OSX) #define DISABLESTEAMWORKS #endif #if !DISABLESTEAMWORKS using System.Runtime.InteropServices; using IntPtr = System.IntPtr; namespace Steamworks { public static class SteamNetworkingUtils { /// <summary> /// <para> Efficient message sending</para> /// <para>/ Allocate and initialize a message object. Usually the reason</para> /// <para>/ you call this is to pass it to ISteamNetworkingSockets::SendMessages.</para> /// <para>/ The returned object will have all of the relevant fields cleared to zero.</para> /// <para>/</para> /// <para>/ Optionally you can also request that this system allocate space to</para> /// <para>/ hold the payload itself. If cbAllocateBuffer is nonzero, the system</para> /// <para>/ will allocate memory to hold a payload of at least cbAllocateBuffer bytes.</para> /// <para>/ m_pData will point to the allocated buffer, m_cbSize will be set to the</para> /// <para>/ size, and m_pfnFreeData will be set to the proper function to free up</para> /// <para>/ the buffer.</para> /// <para>/</para> /// <para>/ If cbAllocateBuffer=0, then no buffer is allocated. m_pData will be NULL,</para> /// <para>/ m_cbSize will be zero, and m_pfnFreeData will be NULL. You will need to</para> /// <para>/ set each of these.</para> /// </summary> public static IntPtr AllocateMessage(int cbAllocateBuffer) { InteropHelp.TestIfAvailableClient(); return NativeMethods.ISteamNetworkingUtils_AllocateMessage(CSteamAPIContext.GetSteamNetworkingUtils(), cbAllocateBuffer); } /// <summary> /// <para> Access to Steam Datagram Relay (SDR) network</para> /// <para> Initialization and status check</para> /// <para>/ If you know that you are going to be using the relay network (for example,</para> /// <para>/ because you anticipate making P2P connections), call this to initialize the</para> /// <para>/ relay network. If you do not call this, the initialization will</para> /// <para>/ be delayed until the first time you use a feature that requires access</para> /// <para>/ to the relay network, which will delay that first access.</para> /// <para>/</para> /// <para>/ You can also call this to force a retry if the previous attempt has failed.</para> /// <para>/ Performing any action that requires access to the relay network will also</para> /// <para>/ trigger a retry, and so calling this function is never strictly necessary,</para> /// <para>/ but it can be useful to call it a program launch time, if access to the</para> /// <para>/ relay network is anticipated.</para> /// <para>/</para> /// <para>/ Use GetRelayNetworkStatus or listen for SteamRelayNetworkStatus_t</para> /// <para>/ callbacks to know when initialization has completed.</para> /// <para>/ Typically initialization completes in a few seconds.</para> /// <para>/</para> /// <para>/ Note: dedicated servers hosted in known data centers do *not* need</para> /// <para>/ to call this, since they do not make routing decisions. However, if</para> /// <para>/ the dedicated server will be using P2P functionality, it will act as</para> /// <para>/ a "client" and this should be called.</para> /// </summary> public static void InitRelayNetworkAccess() { InteropHelp.TestIfAvailableClient(); NativeMethods.ISteamNetworkingUtils_InitRelayNetworkAccess(CSteamAPIContext.GetSteamNetworkingUtils()); } /// <summary> /// <para>/ Fetch current status of the relay network.</para> /// <para>/</para> /// <para>/ SteamRelayNetworkStatus_t is also a callback. It will be triggered on</para> /// <para>/ both the user and gameserver interfaces any time the status changes, or</para> /// <para>/ ping measurement starts or stops.</para> /// <para>/</para> /// <para>/ SteamRelayNetworkStatus_t::m_eAvail is returned. If you want</para> /// <para>/ more details, you can pass a non-NULL value.</para> /// </summary> public static ESteamNetworkingAvailability GetRelayNetworkStatus(out SteamRelayNetworkStatus_t pDetails) { InteropHelp.TestIfAvailableClient(); return NativeMethods.ISteamNetworkingUtils_GetRelayNetworkStatus(CSteamAPIContext.GetSteamNetworkingUtils(), out pDetails); } /// <summary> /// <para> "Ping location" functions</para> /// <para> We use the ping times to the valve relays deployed worldwide to</para> /// <para> generate a "marker" that describes the location of an Internet host.</para> /// <para> Given two such markers, we can estimate the network latency between</para> /// <para> two hosts, without sending any packets. The estimate is based on the</para> /// <para> optimal route that is found through the Valve network. If you are</para> /// <para> using the Valve network to carry the traffic, then this is precisely</para> /// <para> the ping you want. If you are not, then the ping time will probably</para> /// <para> still be a reasonable estimate.</para> /// <para> This is extremely useful to select peers for matchmaking!</para> /// <para> The markers can also be converted to a string, so they can be transmitted.</para> /// <para> We have a separate library you can use on your app's matchmaking/coordinating</para> /// <para> server to manipulate these objects. (See steamdatagram_gamecoordinator.h)</para> /// <para>/ Return location info for the current host. Returns the approximate</para> /// <para>/ age of the data, in seconds, or -1 if no data is available.</para> /// <para>/</para> /// <para>/ It takes a few seconds to initialize access to the relay network. If</para> /// <para>/ you call this very soon after calling InitRelayNetworkAccess,</para> /// <para>/ the data may not be available yet.</para> /// <para>/</para> /// <para>/ This always return the most up-to-date information we have available</para> /// <para>/ right now, even if we are in the middle of re-calculating ping times.</para> /// </summary> public static float GetLocalPingLocation(out SteamNetworkPingLocation_t result) { InteropHelp.TestIfAvailableClient(); return NativeMethods.ISteamNetworkingUtils_GetLocalPingLocation(CSteamAPIContext.GetSteamNetworkingUtils(), out result); } /// <summary> /// <para>/ Estimate the round-trip latency between two arbitrary locations, in</para> /// <para>/ milliseconds. This is a conservative estimate, based on routing through</para> /// <para>/ the relay network. For most basic relayed connections, this ping time</para> /// <para>/ will be pretty accurate, since it will be based on the route likely to</para> /// <para>/ be actually used.</para> /// <para>/</para> /// <para>/ If a direct IP route is used (perhaps via NAT traversal), then the route</para> /// <para>/ will be different, and the ping time might be better. Or it might actually</para> /// <para>/ be a bit worse! Standard IP routing is frequently suboptimal!</para> /// <para>/</para> /// <para>/ But even in this case, the estimate obtained using this method is a</para> /// <para>/ reasonable upper bound on the ping time. (Also it has the advantage</para> /// <para>/ of returning immediately and not sending any packets.)</para> /// <para>/</para> /// <para>/ In a few cases we might not able to estimate the route. In this case</para> /// <para>/ a negative value is returned. k_nSteamNetworkingPing_Failed means</para> /// <para>/ the reason was because of some networking difficulty. (Failure to</para> /// <para>/ ping, etc) k_nSteamNetworkingPing_Unknown is returned if we cannot</para> /// <para>/ currently answer the question for some other reason.</para> /// <para>/</para> /// <para>/ Do you need to be able to do this from a backend/matchmaking server?</para> /// <para>/ You are looking for the "game coordinator" library.</para> /// </summary> public static int EstimatePingTimeBetweenTwoLocations(ref SteamNetworkPingLocation_t location1, ref SteamNetworkPingLocation_t location2) { InteropHelp.TestIfAvailableClient(); return NativeMethods.ISteamNetworkingUtils_EstimatePingTimeBetweenTwoLocations(CSteamAPIContext.GetSteamNetworkingUtils(), ref location1, ref location2); } /// <summary> /// <para>/ Same as EstimatePingTime, but assumes that one location is the local host.</para> /// <para>/ This is a bit faster, especially if you need to calculate a bunch of</para> /// <para>/ these in a loop to find the fastest one.</para> /// <para>/</para> /// <para>/ In rare cases this might return a slightly different estimate than combining</para> /// <para>/ GetLocalPingLocation with EstimatePingTimeBetweenTwoLocations. That's because</para> /// <para>/ this function uses a slightly more complete set of information about what</para> /// <para>/ route would be taken.</para> /// </summary> public static int EstimatePingTimeFromLocalHost(ref SteamNetworkPingLocation_t remoteLocation) { InteropHelp.TestIfAvailableClient(); return NativeMethods.ISteamNetworkingUtils_EstimatePingTimeFromLocalHost(CSteamAPIContext.GetSteamNetworkingUtils(), ref remoteLocation); } /// <summary> /// <para>/ Convert a ping location into a text format suitable for sending over the wire.</para> /// <para>/ The format is a compact and human readable. However, it is subject to change</para> /// <para>/ so please do not parse it yourself. Your buffer must be at least</para> /// <para>/ k_cchMaxSteamNetworkingPingLocationString bytes.</para> /// </summary> public static void ConvertPingLocationToString(ref SteamNetworkPingLocation_t location, out string pszBuf, int cchBufSize) { InteropHelp.TestIfAvailableClient(); IntPtr pszBuf2 = Marshal.AllocHGlobal(cchBufSize); NativeMethods.ISteamNetworkingUtils_ConvertPingLocationToString(CSteamAPIContext.GetSteamNetworkingUtils(), ref location, pszBuf2, cchBufSize); pszBuf = InteropHelp.PtrToStringUTF8(pszBuf2); Marshal.FreeHGlobal(pszBuf2); } /// <summary> /// <para>/ Parse back SteamNetworkPingLocation_t string. Returns false if we couldn't understand</para> /// <para>/ the string.</para> /// </summary> public static bool ParsePingLocationString(string pszString, out SteamNetworkPingLocation_t result) { InteropHelp.TestIfAvailableClient(); using (var pszString2 = new InteropHelp.UTF8StringHandle(pszString)) { return NativeMethods.ISteamNetworkingUtils_ParsePingLocationString(CSteamAPIContext.GetSteamNetworkingUtils(), pszString2, out result); } } /// <summary> /// <para>/ Check if the ping data of sufficient recency is available, and if</para> /// <para>/ it's too old, start refreshing it.</para> /// <para>/</para> /// <para>/ Please only call this function when you *really* do need to force an</para> /// <para>/ immediate refresh of the data. (For example, in response to a specific</para> /// <para>/ user input to refresh this information.) Don't call it "just in case",</para> /// <para>/ before every connection, etc. That will cause extra traffic to be sent</para> /// <para>/ for no benefit. The library will automatically refresh the information</para> /// <para>/ as needed.</para> /// <para>/</para> /// <para>/ Returns true if sufficiently recent data is already available.</para> /// <para>/</para> /// <para>/ Returns false if sufficiently recent data is not available. In this</para> /// <para>/ case, ping measurement is initiated, if it is not already active.</para> /// <para>/ (You cannot restart a measurement already in progress.)</para> /// <para>/</para> /// <para>/ You can use GetRelayNetworkStatus or listen for SteamRelayNetworkStatus_t</para> /// <para>/ to know when ping measurement completes.</para> /// </summary> public static bool CheckPingDataUpToDate(float flMaxAgeSeconds) { InteropHelp.TestIfAvailableClient(); return NativeMethods.ISteamNetworkingUtils_CheckPingDataUpToDate(CSteamAPIContext.GetSteamNetworkingUtils(), flMaxAgeSeconds); } /// <summary> /// <para> List of Valve data centers, and ping times to them. This might</para> /// <para> be useful to you if you are use our hosting, or just need to measure</para> /// <para> latency to a cloud data center where we are running relays.</para> /// <para>/ Fetch ping time of best available relayed route from this host to</para> /// <para>/ the specified data center.</para> /// </summary> public static int GetPingToDataCenter(SteamNetworkingPOPID popID, out SteamNetworkingPOPID pViaRelayPoP) { InteropHelp.TestIfAvailableClient(); return NativeMethods.ISteamNetworkingUtils_GetPingToDataCenter(CSteamAPIContext.GetSteamNetworkingUtils(), popID, out pViaRelayPoP); } /// <summary> /// <para>/ Get *direct* ping time to the relays at the data center.</para> /// </summary> public static int GetDirectPingToPOP(SteamNetworkingPOPID popID) { InteropHelp.TestIfAvailableClient(); return NativeMethods.ISteamNetworkingUtils_GetDirectPingToPOP(CSteamAPIContext.GetSteamNetworkingUtils(), popID); } /// <summary> /// <para>/ Get number of network points of presence in the config</para> /// </summary> public static int GetPOPCount() { InteropHelp.TestIfAvailableClient(); return NativeMethods.ISteamNetworkingUtils_GetPOPCount(CSteamAPIContext.GetSteamNetworkingUtils()); } /// <summary> /// <para>/ Get list of all POP IDs. Returns the number of entries that were filled into</para> /// <para>/ your list.</para> /// </summary> public static int GetPOPList(out SteamNetworkingPOPID list, int nListSz) { InteropHelp.TestIfAvailableClient(); return NativeMethods.ISteamNetworkingUtils_GetPOPList(CSteamAPIContext.GetSteamNetworkingUtils(), out list, nListSz); } /// <summary> /// <para> Misc</para> /// <para>/ Fetch current timestamp. This timer has the following properties:</para> /// <para>/</para> /// <para>/ - Monotonicity is guaranteed.</para> /// <para>/ - The initial value will be at least 24*3600*30*1e6, i.e. about</para> /// <para>/ 30 days worth of microseconds. In this way, the timestamp value of</para> /// <para>/ 0 will always be at least "30 days ago". Also, negative numbers</para> /// <para>/ will never be returned.</para> /// <para>/ - Wraparound / overflow is not a practical concern.</para> /// <para>/</para> /// <para>/ If you are running under the debugger and stop the process, the clock</para> /// <para>/ might not advance the full wall clock time that has elapsed between</para> /// <para>/ calls. If the process is not blocked from normal operation, the</para> /// <para>/ timestamp values will track wall clock time, even if you don't call</para> /// <para>/ the function frequently.</para> /// <para>/</para> /// <para>/ The value is only meaningful for this run of the process. Don't compare</para> /// <para>/ it to values obtained on another computer, or other runs of the same process.</para> /// </summary> public static SteamNetworkingMicroseconds GetLocalTimestamp() { InteropHelp.TestIfAvailableClient(); return (SteamNetworkingMicroseconds)NativeMethods.ISteamNetworkingUtils_GetLocalTimestamp(CSteamAPIContext.GetSteamNetworkingUtils()); } /// <summary> /// <para>/ Set a function to receive network-related information that is useful for debugging.</para> /// <para>/ This can be very useful during development, but it can also be useful for troubleshooting</para> /// <para>/ problems with tech savvy end users. If you have a console or other log that customers</para> /// <para>/ can examine, these log messages can often be helpful to troubleshoot network issues.</para> /// <para>/ (Especially any warning/error messages.)</para> /// <para>/</para> /// <para>/ The detail level indicates what message to invoke your callback on. Lower numeric</para> /// <para>/ value means more important, and the value you pass is the lowest priority (highest</para> /// <para>/ numeric value) you wish to receive callbacks for.</para> /// <para>/</para> /// <para>/ The value here controls the detail level for most messages. You can control the</para> /// <para>/ detail level for various subsystems (perhaps only for certain connections) by</para> /// <para>/ adjusting the configuration values k_ESteamNetworkingConfig_LogLevel_Xxxxx.</para> /// <para>/</para> /// <para>/ Except when debugging, you should only use k_ESteamNetworkingSocketsDebugOutputType_Msg</para> /// <para>/ or k_ESteamNetworkingSocketsDebugOutputType_Warning. For best performance, do NOT</para> /// <para>/ request a high detail level and then filter out messages in your callback. This incurs</para> /// <para>/ all of the expense of formatting the messages, which are then discarded. Setting a high</para> /// <para>/ priority value (low numeric value) here allows the library to avoid doing this work.</para> /// <para>/</para> /// <para>/ IMPORTANT: This may be called from a service thread, while we own a mutex, etc.</para> /// <para>/ Your output function must be threadsafe and fast! Do not make any other</para> /// <para>/ Steamworks calls from within the handler.</para> /// </summary> public static void SetDebugOutputFunction(ESteamNetworkingSocketsDebugOutputType eDetailLevel, FSteamNetworkingSocketsDebugOutput pfnFunc) { InteropHelp.TestIfAvailableClient(); NativeMethods.ISteamNetworkingUtils_SetDebugOutputFunction(CSteamAPIContext.GetSteamNetworkingUtils(), eDetailLevel, pfnFunc); } /// <summary> /// <para> Fake IP</para> /// <para> Useful for interfacing with code that assumes peers are identified using an IPv4 address</para> /// <para>/ Return true if an IPv4 address is one that might be used as a "fake" one.</para> /// <para>/ This function is fast; it just does some logical tests on the IP and does</para> /// <para>/ not need to do any lookup operations.</para> /// </summary> public static bool IsFakeIPv4(uint nIPv4) { InteropHelp.TestIfAvailableClient(); return NativeMethods.ISteamNetworkingUtils_IsFakeIPv4(CSteamAPIContext.GetSteamNetworkingUtils(), nIPv4); } public static ESteamNetworkingFakeIPType GetIPv4FakeIPType(uint nIPv4) { InteropHelp.TestIfAvailableClient(); return NativeMethods.ISteamNetworkingUtils_GetIPv4FakeIPType(CSteamAPIContext.GetSteamNetworkingUtils(), nIPv4); } /// <summary> /// <para>/ Get the real identity associated with a given FakeIP.</para> /// <para>/</para> /// <para>/ On failure, returns:</para> /// <para>/ - k_EResultInvalidParam: the IP is not a FakeIP.</para> /// <para>/ - k_EResultNoMatch: we don't recognize that FakeIP and don't know the corresponding identity.</para> /// <para>/</para> /// <para>/ FakeIP's used by active connections, or the FakeIPs assigned to local identities,</para> /// <para>/ will always work. FakeIPs for recently destroyed connections will continue to</para> /// <para>/ return results for a little while, but not forever. At some point, we will forget</para> /// <para>/ FakeIPs to save space. It's reasonably safe to assume that you can read back the</para> /// <para>/ real identity of a connection very soon after it is destroyed. But do not wait</para> /// <para>/ indefinitely.</para> /// </summary> public static EResult GetRealIdentityForFakeIP(ref SteamNetworkingIPAddr fakeIP, out SteamNetworkingIdentity pOutRealIdentity) { InteropHelp.TestIfAvailableClient(); return NativeMethods.ISteamNetworkingUtils_GetRealIdentityForFakeIP(CSteamAPIContext.GetSteamNetworkingUtils(), ref fakeIP, out pOutRealIdentity); } /// <summary> /// <para> Set and get configuration values, see ESteamNetworkingConfigValue for individual descriptions.</para> /// <para> Shortcuts for common cases. (Implemented as inline functions below)</para> /// <para> Set global callbacks. If you do not want to use Steam's callback dispatch mechanism and you</para> /// <para> want to use the same callback on all (or most) listen sockets and connections, then</para> /// <para> simply install these callbacks first thing, and you are good to go.</para> /// <para> See ISteamNetworkingSockets::RunCallbacks</para> /// <para>/ Set a configuration value.</para> /// <para>/ - eValue: which value is being set</para> /// <para>/ - eScope: Onto what type of object are you applying the setting?</para> /// <para>/ - scopeArg: Which object you want to change? (Ignored for global scope). E.g. connection handle, listen socket handle, interface pointer, etc.</para> /// <para>/ - eDataType: What type of data is in the buffer at pValue? This must match the type of the variable exactly!</para> /// <para>/ - pArg: Value to set it to. You can pass NULL to remove a non-global setting at this scope,</para> /// <para>/ causing the value for that object to use global defaults. Or at global scope, passing NULL</para> /// <para>/ will reset any custom value and restore it to the system default.</para> /// <para>/ NOTE: When setting pointers (e.g. callback functions), do not pass the function pointer directly.</para> /// <para>/ Your argument should be a pointer to a function pointer.</para> /// </summary> public static bool SetConfigValue(ESteamNetworkingConfigValue eValue, ESteamNetworkingConfigScope eScopeType, IntPtr scopeObj, ESteamNetworkingConfigDataType eDataType, IntPtr pArg) { InteropHelp.TestIfAvailableClient(); return NativeMethods.ISteamNetworkingUtils_SetConfigValue(CSteamAPIContext.GetSteamNetworkingUtils(), eValue, eScopeType, scopeObj, eDataType, pArg); } /// <summary> /// <para>/ Set a configuration value, using a struct to pass the value.</para> /// <para>/ (This is just a convenience shortcut; see below for the implementation and</para> /// <para>/ a little insight into how SteamNetworkingConfigValue_t is used when</para> /// <para>/ setting config options during listen socket and connection creation.)</para> /// <para>/ Get a configuration value.</para> /// <para>/ - eValue: which value to fetch</para> /// <para>/ - eScopeType: query setting on what type of object</para> /// <para>/ - eScopeArg: the object to query the setting for</para> /// <para>/ - pOutDataType: If non-NULL, the data type of the value is returned.</para> /// <para>/ - pResult: Where to put the result. Pass NULL to query the required buffer size. (k_ESteamNetworkingGetConfigValue_BufferTooSmall will be returned.)</para> /// <para>/ - cbResult: IN: the size of your buffer. OUT: the number of bytes filled in or required.</para> /// </summary> public static ESteamNetworkingGetConfigValueResult GetConfigValue(ESteamNetworkingConfigValue eValue, ESteamNetworkingConfigScope eScopeType, IntPtr scopeObj, out ESteamNetworkingConfigDataType pOutDataType, IntPtr pResult, ref ulong cbResult) { InteropHelp.TestIfAvailableClient(); return NativeMethods.ISteamNetworkingUtils_GetConfigValue(CSteamAPIContext.GetSteamNetworkingUtils(), eValue, eScopeType, scopeObj, out pOutDataType, pResult, ref cbResult); } /// <summary> /// <para>/ Get info about a configuration value. Returns the name of the value,</para> /// <para>/ or NULL if the value doesn't exist. Other output parameters can be NULL</para> /// <para>/ if you do not need them.</para> /// </summary> public static string GetConfigValueInfo(ESteamNetworkingConfigValue eValue, out ESteamNetworkingConfigDataType pOutDataType, out ESteamNetworkingConfigScope pOutScope) { InteropHelp.TestIfAvailableClient(); return InteropHelp.PtrToStringUTF8(NativeMethods.ISteamNetworkingUtils_GetConfigValueInfo(CSteamAPIContext.GetSteamNetworkingUtils(), eValue, out pOutDataType, out pOutScope)); } /// <summary> /// <para>/ Iterate the list of all configuration values in the current environment that it might</para> /// <para>/ be possible to display or edit using a generic UI. To get the first iterable value,</para> /// <para>/ pass k_ESteamNetworkingConfig_Invalid. Returns k_ESteamNetworkingConfig_Invalid</para> /// <para>/ to signal end of list.</para> /// <para>/</para> /// <para>/ The bEnumerateDevVars argument can be used to include "dev" vars. These are vars that</para> /// <para>/ are recommended to only be editable in "debug" or "dev" mode and typically should not be</para> /// <para>/ shown in a retail environment where a malicious local user might use this to cheat.</para> /// </summary> public static ESteamNetworkingConfigValue IterateGenericEditableConfigValues(ESteamNetworkingConfigValue eCurrent, bool bEnumerateDevVars) { InteropHelp.TestIfAvailableClient(); return NativeMethods.ISteamNetworkingUtils_IterateGenericEditableConfigValues(CSteamAPIContext.GetSteamNetworkingUtils(), eCurrent, bEnumerateDevVars); } /// <summary> /// <para> String conversions. You'll usually access these using the respective</para> /// <para> inline methods.</para> /// </summary> public static void SteamNetworkingIPAddr_ToString(ref SteamNetworkingIPAddr addr, out string buf, uint cbBuf, bool bWithPort) { InteropHelp.TestIfAvailableClient(); IntPtr buf2 = Marshal.AllocHGlobal((int)cbBuf); NativeMethods.ISteamNetworkingUtils_SteamNetworkingIPAddr_ToString(CSteamAPIContext.GetSteamNetworkingUtils(), ref addr, buf2, cbBuf, bWithPort); buf = InteropHelp.PtrToStringUTF8(buf2); Marshal.FreeHGlobal(buf2); } public static bool SteamNetworkingIPAddr_ParseString(out SteamNetworkingIPAddr pAddr, string pszStr) { InteropHelp.TestIfAvailableClient(); using (var pszStr2 = new InteropHelp.UTF8StringHandle(pszStr)) { return NativeMethods.ISteamNetworkingUtils_SteamNetworkingIPAddr_ParseString(CSteamAPIContext.GetSteamNetworkingUtils(), out pAddr, pszStr2); } } public static ESteamNetworkingFakeIPType SteamNetworkingIPAddr_GetFakeIPType(ref SteamNetworkingIPAddr addr) { InteropHelp.TestIfAvailableClient(); return NativeMethods.ISteamNetworkingUtils_SteamNetworkingIPAddr_GetFakeIPType(CSteamAPIContext.GetSteamNetworkingUtils(), ref addr); } public static void SteamNetworkingIdentity_ToString(ref SteamNetworkingIdentity identity, out string buf, uint cbBuf) { InteropHelp.TestIfAvailableClient(); IntPtr buf2 = Marshal.AllocHGlobal((int)cbBuf); NativeMethods.ISteamNetworkingUtils_SteamNetworkingIdentity_ToString(CSteamAPIContext.GetSteamNetworkingUtils(), ref identity, buf2, cbBuf); buf = InteropHelp.PtrToStringUTF8(buf2); Marshal.FreeHGlobal(buf2); } public static bool SteamNetworkingIdentity_ParseString(out SteamNetworkingIdentity pIdentity, string pszStr) { InteropHelp.TestIfAvailableClient(); using (var pszStr2 = new InteropHelp.UTF8StringHandle(pszStr)) { return NativeMethods.ISteamNetworkingUtils_SteamNetworkingIdentity_ParseString(CSteamAPIContext.GetSteamNetworkingUtils(), out pIdentity, pszStr2); } } } } #endif // !DISABLESTEAMWORKS
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.Session { /// <summary> /// An <see cref="ISession"/> backed by an <see cref="IDistributedCache"/>. /// </summary> public class DistributedSession : ISession { private const int IdByteCount = 16; private const byte SerializationRevision = 2; private const int KeyLengthLimit = ushort.MaxValue; private readonly IDistributedCache _cache; private readonly string _sessionKey; private readonly TimeSpan _idleTimeout; private readonly TimeSpan _ioTimeout; private readonly Func<bool> _tryEstablishSession; private readonly ILogger _logger; private IDistributedSessionStore _store; private bool _isModified; private bool _loaded; private bool _isAvailable; private readonly bool _isNewSessionKey; private string? _sessionId; private byte[]? _sessionIdBytes; /// <summary> /// Initializes a new instance of <see cref="DistributedSession"/>. /// </summary> /// <param name="cache">The <see cref="IDistributedCache"/> used to store the session data.</param> /// <param name="sessionKey">A unique key used to lookup the session.</param> /// <param name="idleTimeout">How long the session can be inactive (e.g. not accessed) before it will expire.</param> /// <param name="ioTimeout"> /// The maximum amount of time <see cref="LoadAsync(CancellationToken)"/> and <see cref="CommitAsync(CancellationToken)"/> are allowed take. /// </param> /// <param name="tryEstablishSession"> /// A callback invoked during <see cref="Set(string, byte[])"/> to verify that modifying the session is currently valid. /// If the callback returns <see langword="false"/>, <see cref="Set(string, byte[])"/> throws an <see cref="InvalidOperationException"/>. /// <see cref="SessionMiddleware"/> provides a callback that returns <see langword="false"/> if the session was not established /// prior to sending the response. /// </param> /// <param name="loggerFactory">The <see cref="ILoggerFactory"/>.</param> /// <param name="isNewSessionKey"><see langword="true"/> if establishing a new session; <see langword="false"/> if resuming a session.</param> public DistributedSession( IDistributedCache cache, string sessionKey, TimeSpan idleTimeout, TimeSpan ioTimeout, Func<bool> tryEstablishSession, ILoggerFactory loggerFactory, bool isNewSessionKey) { if (cache == null) { throw new ArgumentNullException(nameof(cache)); } if (string.IsNullOrEmpty(sessionKey)) { throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(sessionKey)); } if (tryEstablishSession == null) { throw new ArgumentNullException(nameof(tryEstablishSession)); } if (loggerFactory == null) { throw new ArgumentNullException(nameof(loggerFactory)); } _cache = cache; _sessionKey = sessionKey; _idleTimeout = idleTimeout; _ioTimeout = ioTimeout; _tryEstablishSession = tryEstablishSession; // When using a NoOpSessionStore, using a dictionary as a backing store results in problematic API choices particularly with nullability. // We instead use a more limited contract - `IDistributedSessionStore` as the backing store that plays better. _store = new DefaultDistributedSessionStore(); _logger = loggerFactory.CreateLogger<DistributedSession>(); _isNewSessionKey = isNewSessionKey; } /// <inheritdoc /> public bool IsAvailable { get { Load(); return _isAvailable; } } /// <inheritdoc /> public string Id { get { Load(); if (_sessionId == null) { _sessionId = new Guid(IdBytes).ToString(); } return _sessionId; } } private byte[] IdBytes { get { Load(); if (_sessionIdBytes == null) { _sessionIdBytes = new byte[IdByteCount]; RandomNumberGenerator.Fill(_sessionIdBytes); } return _sessionIdBytes; } } /// <inheritdoc/> public IEnumerable<string> Keys { get { Load(); return _store.Keys.Select(key => key.KeyString); } } /// <inheritdoc /> public bool TryGetValue(string key, [NotNullWhen(true)] out byte[]? value) { Load(); return _store.TryGetValue(new EncodedKey(key), out value); } /// <inheritdoc /> public void Set(string key, byte[] value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (IsAvailable) { var encodedKey = new EncodedKey(key); if (encodedKey.KeyBytes.Length > KeyLengthLimit) { throw new ArgumentOutOfRangeException(nameof(key), Resources.FormatException_KeyLengthIsExceeded(KeyLengthLimit)); } if (!_tryEstablishSession()) { throw new InvalidOperationException(Resources.Exception_InvalidSessionEstablishment); } _isModified = true; var copy = new byte[value.Length]; Buffer.BlockCopy(src: value, srcOffset: 0, dst: copy, dstOffset: 0, count: value.Length); _store.SetValue(encodedKey, copy); } } /// <inheritdoc /> public void Remove(string key) { Load(); _isModified |= _store.Remove(new EncodedKey(key)); } /// <inheritdoc /> public void Clear() { Load(); _isModified |= _store.Count > 0; _store.Clear(); } private void Load() { if (!_loaded) { try { var data = _cache.Get(_sessionKey); if (data != null) { Deserialize(new MemoryStream(data)); } else if (!_isNewSessionKey) { _logger.AccessingExpiredSession(_sessionKey); } _isAvailable = true; } catch (Exception exception) { _logger.SessionCacheReadException(_sessionKey, exception); _isAvailable = false; _sessionId = string.Empty; _sessionIdBytes = null; _store = new NoOpSessionStore(); } finally { _loaded = true; } } } /// <inheritdoc /> public async Task LoadAsync(CancellationToken cancellationToken = default) { // This will throw if called directly and a failure occurs. The user is expected to handle the failures. if (!_loaded) { using (var timeout = new CancellationTokenSource(_ioTimeout)) { var cts = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, cancellationToken); try { cts.Token.ThrowIfCancellationRequested(); var data = await _cache.GetAsync(_sessionKey, cts.Token); if (data != null) { Deserialize(new MemoryStream(data)); } else if (!_isNewSessionKey) { _logger.AccessingExpiredSession(_sessionKey); } } catch (OperationCanceledException oex) { if (timeout.Token.IsCancellationRequested) { _logger.SessionLoadingTimeout(); throw new OperationCanceledException("Timed out loading the session.", oex, timeout.Token); } throw; } } _isAvailable = true; _loaded = true; } } /// <inheritdoc /> public async Task CommitAsync(CancellationToken cancellationToken = default) { if (!IsAvailable) { _logger.SessionNotAvailable(); return; } using (var timeout = new CancellationTokenSource(_ioTimeout)) { var cts = CancellationTokenSource.CreateLinkedTokenSource(timeout.Token, cancellationToken); if (_isModified) { if (_logger.IsEnabled(LogLevel.Information)) { // This operation is only so we can log if the session already existed. // Log and ignore failures. try { cts.Token.ThrowIfCancellationRequested(); var data = await _cache.GetAsync(_sessionKey, cts.Token); if (data == null) { _logger.SessionStarted(_sessionKey, Id); } } catch (OperationCanceledException) { } catch (Exception exception) { _logger.SessionCacheReadException(_sessionKey, exception); } } var stream = new MemoryStream(); Serialize(stream); try { cts.Token.ThrowIfCancellationRequested(); await _cache.SetAsync( _sessionKey, stream.ToArray(), new DistributedCacheEntryOptions().SetSlidingExpiration(_idleTimeout), cts.Token); _isModified = false; _logger.SessionStored(_sessionKey, Id, _store.Count); } catch (OperationCanceledException oex) { if (timeout.Token.IsCancellationRequested) { _logger.SessionCommitTimeout(); throw new OperationCanceledException("Timed out committing the session.", oex, timeout.Token); } throw; } } else { try { await _cache.RefreshAsync(_sessionKey, cts.Token); } catch (OperationCanceledException oex) { if (timeout.Token.IsCancellationRequested) { _logger.SessionRefreshTimeout(); throw new OperationCanceledException("Timed out refreshing the session.", oex, timeout.Token); } throw; } } } } // Format: // Serialization revision: 1 byte, range 0-255 // Entry count: 3 bytes, range 0-16,777,215 // SessionId: IdByteCount bytes (16) // foreach entry: // key name byte length: 2 bytes, range 0-65,535 // UTF-8 encoded key name byte[] // data byte length: 4 bytes, range 0-2,147,483,647 // data byte[] private void Serialize(Stream output) { output.WriteByte(SerializationRevision); SerializeNumAs3Bytes(output, _store.Count); output.Write(IdBytes, 0, IdByteCount); foreach (var entry in _store) { var keyBytes = entry.Key.KeyBytes; SerializeNumAs2Bytes(output, keyBytes.Length); output.Write(keyBytes, 0, keyBytes.Length); SerializeNumAs4Bytes(output, entry.Value.Length); output.Write(entry.Value, 0, entry.Value.Length); } } private void Deserialize(Stream content) { if (content == null || content.ReadByte() != SerializationRevision) { // Replace the un-readable format. _isModified = true; return; } var expectedEntries = DeserializeNumFrom3Bytes(content); _sessionIdBytes = ReadBytes(content, IdByteCount); for (var i = 0; i < expectedEntries; i++) { var keyLength = DeserializeNumFrom2Bytes(content); var key = new EncodedKey(ReadBytes(content, keyLength)); var dataLength = DeserializeNumFrom4Bytes(content); _store.SetValue(key, ReadBytes(content, dataLength)); } if (_logger.IsEnabled(LogLevel.Debug)) { _sessionId = new Guid(_sessionIdBytes).ToString(); _logger.SessionLoaded(_sessionKey, _sessionId, expectedEntries); } } private static void SerializeNumAs2Bytes(Stream output, int num) { if (num < 0 || ushort.MaxValue < num) { throw new ArgumentOutOfRangeException(nameof(num), Resources.Exception_InvalidToSerializeIn2Bytes); } output.WriteByte((byte)(num >> 8)); output.WriteByte((byte)(0xFF & num)); } private static int DeserializeNumFrom2Bytes(Stream content) { return content.ReadByte() << 8 | content.ReadByte(); } private static void SerializeNumAs3Bytes(Stream output, int num) { if (num < 0 || 0xFFFFFF < num) { throw new ArgumentOutOfRangeException(nameof(num), Resources.Exception_InvalidToSerializeIn3Bytes); } output.WriteByte((byte)(num >> 16)); output.WriteByte((byte)(0xFF & (num >> 8))); output.WriteByte((byte)(0xFF & num)); } private static int DeserializeNumFrom3Bytes(Stream content) { return content.ReadByte() << 16 | content.ReadByte() << 8 | content.ReadByte(); } private static void SerializeNumAs4Bytes(Stream output, int num) { if (num < 0) { throw new ArgumentOutOfRangeException(nameof(num), Resources.Exception_NumberShouldNotBeNegative); } output.WriteByte((byte)(num >> 24)); output.WriteByte((byte)(0xFF & (num >> 16))); output.WriteByte((byte)(0xFF & (num >> 8))); output.WriteByte((byte)(0xFF & num)); } private static int DeserializeNumFrom4Bytes(Stream content) { return content.ReadByte() << 24 | content.ReadByte() << 16 | content.ReadByte() << 8 | content.ReadByte(); } private static byte[] ReadBytes(Stream stream, int count) { var output = new byte[count]; var total = 0; while (total < count) { var read = stream.Read(output, total, count - total); if (read == 0) { throw new EndOfStreamException(); } total += read; } return output; } } }
// Copyright (C) 2015-2021 The Neo Project. // // The neo is free software distributed under the MIT software license, // see the accompanying file LICENSE in the main directory of the // project or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without // modifications are permitted. using Microsoft.Extensions.Configuration; using Neo.Cryptography.ECC; using Neo.Network.P2P.Payloads; using Neo.SmartContract.Native; using System; using System.Collections.Generic; using System.Linq; namespace Neo { /// <summary> /// Represents the protocol settings of the NEO system. /// </summary> public record ProtocolSettings { /// <summary> /// The magic number of the NEO network. /// </summary> public uint Network { get; init; } /// <summary> /// The address version of the NEO system. /// </summary> public byte AddressVersion { get; init; } /// <summary> /// The public keys of the standby committee members. /// </summary> public IReadOnlyList<ECPoint> StandbyCommittee { get; init; } /// <summary> /// The number of members of the committee in NEO system. /// </summary> public int CommitteeMembersCount => StandbyCommittee.Count; /// <summary> /// The number of the validators in NEO system. /// </summary> public int ValidatorsCount { get; init; } /// <summary> /// The default seed nodes list. /// </summary> public string[] SeedList { get; init; } /// <summary> /// Indicates the time in milliseconds between two blocks. /// </summary> public uint MillisecondsPerBlock { get; init; } /// <summary> /// Indicates the time between two blocks. /// </summary> public TimeSpan TimePerBlock => TimeSpan.FromMilliseconds(MillisecondsPerBlock); /// <summary> /// The maximum increment of the <see cref="Transaction.ValidUntilBlock"/> field. /// </summary> public uint MaxValidUntilBlockIncrement => 86400000 / MillisecondsPerBlock; /// <summary> /// Indicates the maximum number of transactions that can be contained in a block. /// </summary> public uint MaxTransactionsPerBlock { get; init; } /// <summary> /// Indicates the maximum number of transactions that can be contained in the memory pool. /// </summary> public int MemoryPoolMaxTransactions { get; init; } /// <summary> /// Indicates the maximum number of blocks that can be traced in the smart contract. /// </summary> public uint MaxTraceableBlocks { get; init; } /// <summary> /// Contains the update history of all native contracts. /// </summary> public IReadOnlyDictionary<string, uint[]> NativeUpdateHistory { get; init; } /// <summary> /// Indicates the amount of gas to distribute during initialization. /// </summary> public ulong InitialGasDistribution { get; init; } private IReadOnlyList<ECPoint> _standbyValidators; /// <summary> /// The public keys of the standby validators. /// </summary> public IReadOnlyList<ECPoint> StandbyValidators => _standbyValidators ??= StandbyCommittee.Take(ValidatorsCount).ToArray(); /// <summary> /// The default protocol settings for NEO MainNet. /// </summary> public static ProtocolSettings Default { get; } = new ProtocolSettings { Network = 0x334F454Eu, AddressVersion = 0x35, StandbyCommittee = new[] { //Validators ECPoint.Parse("03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c", ECCurve.Secp256r1), ECPoint.Parse("02df48f60e8f3e01c48ff40b9b7f1310d7a8b2a193188befe1c2e3df740e895093", ECCurve.Secp256r1), ECPoint.Parse("03b8d9d5771d8f513aa0869b9cc8d50986403b78c6da36890638c3d46a5adce04a", ECCurve.Secp256r1), ECPoint.Parse("02ca0e27697b9c248f6f16e085fd0061e26f44da85b58ee835c110caa5ec3ba554", ECCurve.Secp256r1), ECPoint.Parse("024c7b7fb6c310fccf1ba33b082519d82964ea93868d676662d4a59ad548df0e7d", ECCurve.Secp256r1), ECPoint.Parse("02aaec38470f6aad0042c6e877cfd8087d2676b0f516fddd362801b9bd3936399e", ECCurve.Secp256r1), ECPoint.Parse("02486fd15702c4490a26703112a5cc1d0923fd697a33406bd5a1c00e0013b09a70", ECCurve.Secp256r1), //Other Members ECPoint.Parse("023a36c72844610b4d34d1968662424011bf783ca9d984efa19a20babf5582f3fe", ECCurve.Secp256r1), ECPoint.Parse("03708b860c1de5d87f5b151a12c2a99feebd2e8b315ee8e7cf8aa19692a9e18379", ECCurve.Secp256r1), ECPoint.Parse("03c6aa6e12638b36e88adc1ccdceac4db9929575c3e03576c617c49cce7114a050", ECCurve.Secp256r1), ECPoint.Parse("03204223f8c86b8cd5c89ef12e4f0dbb314172e9241e30c9ef2293790793537cf0", ECCurve.Secp256r1), ECPoint.Parse("02a62c915cf19c7f19a50ec217e79fac2439bbaad658493de0c7d8ffa92ab0aa62", ECCurve.Secp256r1), ECPoint.Parse("03409f31f0d66bdc2f70a9730b66fe186658f84a8018204db01c106edc36553cd0", ECCurve.Secp256r1), ECPoint.Parse("0288342b141c30dc8ffcde0204929bb46aed5756b41ef4a56778d15ada8f0c6654", ECCurve.Secp256r1), ECPoint.Parse("020f2887f41474cfeb11fd262e982051c1541418137c02a0f4961af911045de639", ECCurve.Secp256r1), ECPoint.Parse("0222038884bbd1d8ff109ed3bdef3542e768eef76c1247aea8bc8171f532928c30", ECCurve.Secp256r1), ECPoint.Parse("03d281b42002647f0113f36c7b8efb30db66078dfaaa9ab3ff76d043a98d512fde", ECCurve.Secp256r1), ECPoint.Parse("02504acbc1f4b3bdad1d86d6e1a08603771db135a73e61c9d565ae06a1938cd2ad", ECCurve.Secp256r1), ECPoint.Parse("0226933336f1b75baa42d42b71d9091508b638046d19abd67f4e119bf64a7cfb4d", ECCurve.Secp256r1), ECPoint.Parse("03cdcea66032b82f5c30450e381e5295cae85c5e6943af716cc6b646352a6067dc", ECCurve.Secp256r1), ECPoint.Parse("02cd5a5547119e24feaa7c2a0f37b8c9366216bab7054de0065c9be42084003c8a", ECCurve.Secp256r1) }, ValidatorsCount = 7, SeedList = new[] { "seed1.neo.org:10333", "seed2.neo.org:10333", "seed3.neo.org:10333", "seed4.neo.org:10333", "seed5.neo.org:10333" }, MillisecondsPerBlock = 15000, MaxTransactionsPerBlock = 512, MemoryPoolMaxTransactions = 50_000, MaxTraceableBlocks = 2_102_400, InitialGasDistribution = 52_000_000_00000000, NativeUpdateHistory = new Dictionary<string, uint[]> { [nameof(ContractManagement)] = new[] { 0u }, [nameof(StdLib)] = new[] { 0u }, [nameof(CryptoLib)] = new[] { 0u }, [nameof(LedgerContract)] = new[] { 0u }, [nameof(NeoToken)] = new[] { 0u }, [nameof(GasToken)] = new[] { 0u }, [nameof(PolicyContract)] = new[] { 0u }, [nameof(RoleManagement)] = new[] { 0u }, [nameof(OracleContract)] = new[] { 0u } } }; /// <summary> /// Loads the <see cref="ProtocolSettings"/> at the specified path. /// </summary> /// <param name="path">The path of the settings file.</param> /// <param name="optional">Indicates whether the file is optional.</param> /// <returns>The loaded <see cref="ProtocolSettings"/>.</returns> public static ProtocolSettings Load(string path, bool optional = true) { IConfigurationRoot config = new ConfigurationBuilder().AddJsonFile(path, optional).Build(); IConfigurationSection section = config.GetSection("ProtocolConfiguration"); return Load(section); } /// <summary> /// Loads the <see cref="ProtocolSettings"/> with the specified <see cref="IConfigurationSection"/>. /// </summary> /// <param name="section">The <see cref="IConfigurationSection"/> to be loaded.</param> /// <returns>The loaded <see cref="ProtocolSettings"/>.</returns> public static ProtocolSettings Load(IConfigurationSection section) { return new ProtocolSettings { Network = section.GetValue("Network", Default.Network), AddressVersion = section.GetValue("AddressVersion", Default.AddressVersion), StandbyCommittee = section.GetSection("StandbyCommittee").Exists() ? section.GetSection("StandbyCommittee").GetChildren().Select(p => ECPoint.Parse(p.Get<string>(), ECCurve.Secp256r1)).ToArray() : Default.StandbyCommittee, ValidatorsCount = section.GetValue("ValidatorsCount", Default.ValidatorsCount), SeedList = section.GetSection("SeedList").Exists() ? section.GetSection("SeedList").GetChildren().Select(p => p.Get<string>()).ToArray() : Default.SeedList, MillisecondsPerBlock = section.GetValue("MillisecondsPerBlock", Default.MillisecondsPerBlock), MaxTransactionsPerBlock = section.GetValue("MaxTransactionsPerBlock", Default.MaxTransactionsPerBlock), MemoryPoolMaxTransactions = section.GetValue("MemoryPoolMaxTransactions", Default.MemoryPoolMaxTransactions), MaxTraceableBlocks = section.GetValue("MaxTraceableBlocks", Default.MaxTraceableBlocks), InitialGasDistribution = section.GetValue("InitialGasDistribution", Default.InitialGasDistribution), NativeUpdateHistory = section.GetSection("NativeUpdateHistory").Exists() ? section.GetSection("NativeUpdateHistory").GetChildren().ToDictionary(p => p.Key, p => p.GetChildren().Select(q => uint.Parse(q.Value)).ToArray()) : Default.NativeUpdateHistory }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //////////////////////////////////////////////////////////////////////////// // // // Purpose: This class implements a set of methods for retrieving // character type information. Character type information is // independent of culture and region. // // //////////////////////////////////////////////////////////////////////////// namespace System.Globalization { //This class has only static members and therefore doesn't need to be serialized. using System; using System.Threading; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Reflection; using System.Security; using System.Diagnostics.Contracts; public static class CharUnicodeInfo { //--------------------------------------------------------------------// // Internal Information // //--------------------------------------------------------------------// // // Native methods to access the Unicode category data tables in charinfo.nlp. // internal const char HIGH_SURROGATE_START = '\ud800'; internal const char HIGH_SURROGATE_END = '\udbff'; internal const char LOW_SURROGATE_START = '\udc00'; internal const char LOW_SURROGATE_END = '\udfff'; internal const int UNICODE_CATEGORY_OFFSET = 0; internal const int BIDI_CATEGORY_OFFSET = 1; static bool s_initialized = InitTable(); // The native pointer to the 12:4:4 index table of the Unicode cateogry data. [SecurityCritical] unsafe static ushort* s_pCategoryLevel1Index; [SecurityCritical] unsafe static byte* s_pCategoriesValue; // The native pointer to the 12:4:4 index table of the Unicode numeric data. // The value of this index table is an index into the real value table stored in s_pNumericValues. [SecurityCritical] unsafe static ushort* s_pNumericLevel1Index; // The numeric value table, which is indexed by s_pNumericLevel1Index. // Every item contains the value for numeric value. // unsafe static double* s_pNumericValues; // To get around the IA64 alignment issue. Our double data is aligned in 8-byte boundary, but loader loads the embeded table starting // at 4-byte boundary. This cause a alignment issue since double is 8-byte. [SecurityCritical] unsafe static byte* s_pNumericValues; // The digit value table, which is indexed by s_pNumericLevel1Index. It shares the same indice as s_pNumericValues. // Every item contains the value for decimal digit/digit value. [SecurityCritical] unsafe static DigitValues* s_pDigitValues; internal const String UNICODE_INFO_FILE_NAME = "charinfo.nlp"; // The starting codepoint for Unicode plane 1. Plane 1 contains 0x010000 ~ 0x01ffff. internal const int UNICODE_PLANE01_START = 0x10000; // // This is the header for the native data table that we load from UNICODE_INFO_FILE_NAME. // // Excplicit layout is used here since a syntax like char[16] can not be used in sequential layout. [StructLayout(LayoutKind.Explicit)] internal unsafe struct UnicodeDataHeader { [FieldOffset(0)] internal char TableName; // WCHAR[16] [FieldOffset(0x20)] internal ushort version; // WORD[4] [FieldOffset(0x28)] internal uint OffsetToCategoriesIndex; // DWORD [FieldOffset(0x2c)] internal uint OffsetToCategoriesValue; // DWORD [FieldOffset(0x30)] internal uint OffsetToNumbericIndex; // DWORD [FieldOffset(0x34)] internal uint OffsetToDigitValue; // DWORD [FieldOffset(0x38)] internal uint OffsetToNumbericValue; // DWORD } // NOTE: It's important to specify pack size here, since the size of the structure is 2 bytes. Otherwise, // the default pack size will be 4. [StructLayout(LayoutKind.Sequential, Pack=2)] internal struct DigitValues { internal sbyte decimalDigit; internal sbyte digit; } //We need to allocate the underlying table that provides us with the information that we //use. We allocate this once in the class initializer and then we don't need to worry //about it again. // [System.Security.SecuritySafeCritical] // auto-generated unsafe static bool InitTable() { // Go to native side and get pointer to the native table byte * pDataTable = GlobalizationAssembly.GetGlobalizationResourceBytePtr(typeof(CharUnicodeInfo).Assembly, UNICODE_INFO_FILE_NAME); UnicodeDataHeader* mainHeader = (UnicodeDataHeader*)pDataTable; // Set up the native pointer to different part of the tables. s_pCategoryLevel1Index = (ushort*) (pDataTable + mainHeader->OffsetToCategoriesIndex); s_pCategoriesValue = (byte*) (pDataTable + mainHeader->OffsetToCategoriesValue); s_pNumericLevel1Index = (ushort*) (pDataTable + mainHeader->OffsetToNumbericIndex); s_pNumericValues = (byte*) (pDataTable + mainHeader->OffsetToNumbericValue); s_pDigitValues = (DigitValues*) (pDataTable + mainHeader->OffsetToDigitValue); return true; } //////////////////////////////////////////////////////////////////////// // // Actions: // Convert the BMP character or surrogate pointed by index to a UTF32 value. // This is similar to Char.ConvertToUTF32, but the difference is that // it does not throw exceptions when invalid surrogate characters are passed in. // // WARNING: since it doesn't throw an exception it CAN return a value // in the surrogate range D800-DFFF, which are not legal unicode values. // //////////////////////////////////////////////////////////////////////// internal static int InternalConvertToUtf32(String s, int index) { Contract.Assert(s != null, "s != null"); Contract.Assert(index >= 0 && index < s.Length, "index < s.Length"); if (index < s.Length - 1) { int temp1 = (int)s[index] - HIGH_SURROGATE_START; if (temp1 >= 0 && temp1 <= 0x3ff) { int temp2 = (int)s[index+1] - LOW_SURROGATE_START; if (temp2 >= 0 && temp2 <= 0x3ff) { // Convert the surrogate to UTF32 and get the result. return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START); } } } return ((int)s[index]); } //////////////////////////////////////////////////////////////////////// // // Convert a character or a surrogate pair starting at index of string s // to UTF32 value. // // Parameters: // s The string // index The starting index. It can point to a BMP character or // a surrogate pair. // len The length of the string. // charLength [out] If the index points to a BMP char, charLength // will be 1. If the index points to a surrogate pair, // charLength will be 2. // // WARNING: since it doesn't throw an exception it CAN return a value // in the surrogate range D800-DFFF, which are not legal unicode values. // // Returns: // The UTF32 value // //////////////////////////////////////////////////////////////////////// internal static int InternalConvertToUtf32(String s, int index, out int charLength) { Contract.Assert(s != null, "s != null"); Contract.Assert(s.Length > 0, "s.Length > 0"); Contract.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length"); charLength = 1; if (index < s.Length - 1) { int temp1 = (int)s[index] - HIGH_SURROGATE_START; if (temp1 >= 0 && temp1 <= 0x3ff) { int temp2 = (int)s[index+1] - LOW_SURROGATE_START; if (temp2 >= 0 && temp2 <= 0x3ff) { // Convert the surrogate to UTF32 and get the result. charLength++; return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START); } } } return ((int)s[index]); } //////////////////////////////////////////////////////////////////////// // // IsWhiteSpace // // Determines if the given character is a white space character. // //////////////////////////////////////////////////////////////////////// internal static bool IsWhiteSpace(String s, int index) { Contract.Assert(s != null, "s!=null"); Contract.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length"); UnicodeCategory uc = GetUnicodeCategory(s, index); // In Unicode 3.0, U+2028 is the only character which is under the category "LineSeparator". // And U+2029 is th eonly character which is under the category "ParagraphSeparator". switch (uc) { case (UnicodeCategory.SpaceSeparator): case (UnicodeCategory.LineSeparator): case (UnicodeCategory.ParagraphSeparator): return (true); } return (false); } internal static bool IsWhiteSpace(char c) { UnicodeCategory uc = GetUnicodeCategory(c); // In Unicode 3.0, U+2028 is the only character which is under the category "LineSeparator". // And U+2029 is th eonly character which is under the category "ParagraphSeparator". switch (uc) { case (UnicodeCategory.SpaceSeparator): case (UnicodeCategory.LineSeparator): case (UnicodeCategory.ParagraphSeparator): return (true); } return (false); } // // This is called by the public char and string, index versions // // Note that for ch in the range D800-DFFF we just treat it as any other non-numeric character // [System.Security.SecuritySafeCritical] // auto-generated internal unsafe static double InternalGetNumericValue(int ch) { Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range."); // Get the level 2 item from the highest 12 bit (8 - 19) of ch. ushort index = s_pNumericLevel1Index[ch >> 8]; // Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table. // The offset is referred to an float item in m_pNumericFloatData. // Note that & has the lower precedence than addition, so don't forget the parathesis. index = s_pNumericLevel1Index[index + ((ch >> 4) & 0x000f)]; byte* pBytePtr = (byte*)&(s_pNumericLevel1Index[index]); // Get the result from the 0 -3 bit of ch. #if BIT64 // To get around the IA64 alignment issue. Our double data is aligned in 8-byte boundary, but loader loads the embeded table starting // at 4-byte boundary. This cause a alignment issue since double is 8-byte. byte* pSourcePtr = &(s_pNumericValues[pBytePtr[(ch & 0x000f)] * sizeof(double)]); if (((long)pSourcePtr % 8) != 0) { // We are not aligned in 8-byte boundary. Do a copy. double ret; byte* retPtr = (byte*)&ret; Buffer.Memcpy(retPtr, pSourcePtr, sizeof(double)); return (ret); } return (((double*)s_pNumericValues)[pBytePtr[(ch & 0x000f)]]); #else return (((double*)s_pNumericValues)[pBytePtr[(ch & 0x000f)]]); #endif } // // This is called by the public char and string, index versions // // Note that for ch in the range D800-DFFF we just treat it as any other non-numeric character // [System.Security.SecuritySafeCritical] // auto-generated internal unsafe static DigitValues* InternalGetDigitValues(int ch) { Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range."); // Get the level 2 item from the highest 12 bit (8 - 19) of ch. ushort index = s_pNumericLevel1Index[ch >> 8]; // Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table. // The offset is referred to an float item in m_pNumericFloatData. // Note that & has the lower precedence than addition, so don't forget the parathesis. index = s_pNumericLevel1Index[index + ((ch >> 4) & 0x000f)]; byte* pBytePtr = (byte*)&(s_pNumericLevel1Index[index]); // Get the result from the 0 -3 bit of ch. return &(s_pDigitValues[pBytePtr[(ch & 0x000f)]]); } [System.Security.SecuritySafeCritical] // auto-generated internal unsafe static sbyte InternalGetDecimalDigitValue(int ch) { return (InternalGetDigitValues(ch)->decimalDigit); } [System.Security.SecuritySafeCritical] // auto-generated internal unsafe static sbyte InternalGetDigitValue(int ch) { return (InternalGetDigitValues(ch)->digit); } //////////////////////////////////////////////////////////////////////// // //Returns the numeric value associated with the character c. If the character is a fraction, // the return value will not be an integer. If the character does not have a numeric value, the return value is -1. // //Returns: // the numeric value for the specified Unicode character. If the character does not have a numeric value, the return value is -1. //Arguments: // ch a Unicode character //Exceptions: // ArgumentNullException // ArgumentOutOfRangeException // //////////////////////////////////////////////////////////////////////// public static double GetNumericValue(char ch) { return (InternalGetNumericValue(ch)); } public static double GetNumericValue(String s, int index) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); } Contract.EndContractBlock(); return (InternalGetNumericValue(InternalConvertToUtf32(s, index))); } //////////////////////////////////////////////////////////////////////// // //Returns the decimal digit value associated with the character c. // // The value should be from 0 ~ 9. // If the character does not have a numeric value, the return value is -1. // From Unicode.org: Decimal Digits. Digits that can be used to form decimal-radix numbers. //Returns: // the decimal digit value for the specified Unicode character. If the character does not have a decimal digit value, the return value is -1. //Arguments: // ch a Unicode character //Exceptions: // ArgumentNullException // ArgumentOutOfRangeException // //////////////////////////////////////////////////////////////////////// public static int GetDecimalDigitValue(char ch) { return (InternalGetDecimalDigitValue(ch)); } public static int GetDecimalDigitValue(String s, int index) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); } Contract.EndContractBlock(); return (InternalGetDecimalDigitValue(InternalConvertToUtf32(s, index))); } //////////////////////////////////////////////////////////////////////// // //Action: Returns the digit value associated with the character c. // If the character does not have a numeric value, the return value is -1. // From Unicode.org: If the character represents a digit, not necessarily a decimal digit, // the value is here. This covers digits which do not form decimal radix forms, such as the compatibility superscript digits. // // An example is: U+2460 IRCLED DIGIT ONE. This character has digit value 1, but does not have associcated decimal digit value. // //Returns: // the digit value for the specified Unicode character. If the character does not have a digit value, the return value is -1. //Arguments: // ch a Unicode character //Exceptions: // ArgumentNullException // ArgumentOutOfRangeException // //////////////////////////////////////////////////////////////////////// public static int GetDigitValue(char ch) { return (InternalGetDigitValue(ch)); } public static int GetDigitValue(String s, int index) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); } Contract.EndContractBlock(); return (InternalGetDigitValue(InternalConvertToUtf32(s, index))); } public static UnicodeCategory GetUnicodeCategory(char ch) { return (InternalGetUnicodeCategory(ch)) ; } public static UnicodeCategory GetUnicodeCategory(String s, int index) { if (s==null) throw new ArgumentNullException(nameof(s)); if (((uint)index)>=((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); return InternalGetUnicodeCategory(s, index); } internal unsafe static UnicodeCategory InternalGetUnicodeCategory(int ch) { return ((UnicodeCategory)InternalGetCategoryValue(ch, UNICODE_CATEGORY_OFFSET)); } //////////////////////////////////////////////////////////////////////// // //Action: Returns the Unicode Category property for the character c. //Returns: // an value in UnicodeCategory enum //Arguments: // ch a Unicode character //Exceptions: // None // //Note that this API will return values for D800-DF00 surrogate halves. // //////////////////////////////////////////////////////////////////////// [System.Security.SecuritySafeCritical] // auto-generated internal unsafe static byte InternalGetCategoryValue(int ch, int offset) { Contract.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range."); // Get the level 2 item from the highest 12 bit (8 - 19) of ch. ushort index = s_pCategoryLevel1Index[ch >> 8]; // Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table. // Note that & has the lower precedence than addition, so don't forget the parathesis. index = s_pCategoryLevel1Index[index + ((ch >> 4) & 0x000f)]; byte* pBytePtr = (byte*)&(s_pCategoryLevel1Index[index]); // Get the result from the 0 -3 bit of ch. byte valueIndex = pBytePtr[(ch & 0x000f)]; byte uc = s_pCategoriesValue[valueIndex * 2 + offset]; // // Make sure that OtherNotAssigned is the last category in UnicodeCategory. // If that changes, change the following assertion as well. // //Contract.Assert(uc >= 0 && uc <= UnicodeCategory.OtherNotAssigned, "Table returns incorrect Unicode category"); return (uc); } // internal static BidiCategory GetBidiCategory(char ch) { // return ((BidiCategory)InternalGetCategoryValue(c, BIDI_CATEGORY_OFFSET)); // } internal static BidiCategory GetBidiCategory(String s, int index) { if (s==null) throw new ArgumentNullException(nameof(s)); if (((uint)index)>=((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } Contract.EndContractBlock(); return ((BidiCategory)InternalGetCategoryValue(InternalConvertToUtf32(s, index), BIDI_CATEGORY_OFFSET)); } //////////////////////////////////////////////////////////////////////// // //Action: Returns the Unicode Category property for the character c. //Returns: // an value in UnicodeCategory enum //Arguments: // value a Unicode String // index Index for the specified string. //Exceptions: // None // //////////////////////////////////////////////////////////////////////// internal static UnicodeCategory InternalGetUnicodeCategory(String value, int index) { Contract.Assert(value != null, "value can not be null"); Contract.Assert(index < value.Length, "index < value.Length"); return (InternalGetUnicodeCategory(InternalConvertToUtf32(value, index))); } //////////////////////////////////////////////////////////////////////// // // Get the Unicode category of the character starting at index. If the character is in BMP, charLength will return 1. // If the character is a valid surrogate pair, charLength will return 2. // //////////////////////////////////////////////////////////////////////// internal static UnicodeCategory InternalGetUnicodeCategory(String str, int index, out int charLength) { Contract.Assert(str != null, "str can not be null"); Contract.Assert(str.Length > 0, "str.Length > 0");; Contract.Assert(index >= 0 && index < str.Length, "index >= 0 && index < str.Length"); return (InternalGetUnicodeCategory(InternalConvertToUtf32(str, index, out charLength))); } internal static bool IsCombiningCategory(UnicodeCategory uc) { Contract.Assert(uc >= 0, "uc >= 0"); return ( uc == UnicodeCategory.NonSpacingMark || uc == UnicodeCategory.SpacingCombiningMark || uc == UnicodeCategory.EnclosingMark ); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Hydra.Framework.Extensions { /// <summary> /// Object Extension Methods /// </summary> public static class ObjectExtensions { #region Constants const int RecursionLimit = 10; #endregion #region Static Methods /// <summary> /// Musts the not be null. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="reference">The reference.</param> public static void MustNotBeNull<T>(this T reference) where T : class { if (reference == null) throw new ArgumentNullException(); } /// <summary> /// Musts the not be null. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="reference">The reference.</param> /// <param name="name">The name.</param> public static void MustNotBeNull<T>(this T reference, string name) where T : class { if (reference == null) throw new ArgumentNullException(name); } /// <summary> /// Musts the not be null. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="reference">The reference.</param> /// <param name="name">The name.</param> /// <param name="message">The message.</param> public static void MustNotBeNull<T>(this T reference, string name, string message) where T : class { if (reference == null) throw new ArgumentNullException(name, message); } /// <summary> /// Musts the not be empty. /// </summary> /// <param name="value">The value.</param> public static void MustNotBeEmpty(this string value) { if (value == null) throw new ArgumentNullException(); if (string.IsNullOrEmpty(value)) throw new ArgumentException(); } /// <summary> /// Musts the not be empty. /// </summary> /// <param name="value">The value.</param> /// <param name="name">The name.</param> public static void MustNotBeEmpty(this string value, string name) { if (value == null) throw new ArgumentNullException(name, "The argument must not be null"); if (string.IsNullOrEmpty(value)) throw new ArgumentException("The argument must not be empty", name); } /// <summary> /// Musts the not be empty. /// </summary> /// <param name="value">The value.</param> /// <param name="name">The name.</param> /// <param name="message">The message.</param> public static void MustNotBeEmpty(this string value, string name, string message) { if (string.IsNullOrEmpty(value)) throw new ArgumentException(message, name); } /// <summary> /// Musts the be in range. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value">The value.</param> /// <param name="rangeBuilder">The range builder.</param> public static void MustBeInRange<T>(this T value, RangeBuilder<T> rangeBuilder) { Range<T> range = rangeBuilder; value.MustBeInRange(range); } /// <summary> /// Musts the be in range. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value">The value.</param> /// <param name="range">The range.</param> public static void MustBeInRange<T>(this T value, Range<T> range) { if (!range.Contains(value)) throw new ArgumentException(); } /// <summary> /// Determines whether [is null or empty] [the specified value]. /// </summary> /// <param name="value">The value.</param> /// <returns> /// <c>true</c> if [is null or empty] [the specified value]; otherwise, <c>false</c>. /// </returns> public static bool IsNullOrEmpty(this string value) { return string.IsNullOrEmpty(value); } /// <summary> /// props to Jeremy Miller for these two nice helpers /// </summary> /// <typeparam name="T"></typeparam> /// <param name="provider">The provider.</param> /// <returns></returns> public static T GetAttribute<T>(this ICustomAttributeProvider provider) where T : Attribute { var attributes = provider.GetCustomAttributes(typeof(T), true); return attributes.Length > 0 ? attributes[0] as T : null; } /// <summary> /// Fors the attributes of. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="provider">The provider.</param> /// <param name="action">The action.</param> public static void ForAttributesOf<T>(this ICustomAttributeProvider provider, Action<T> action) where T : Attribute { foreach (T attribute in provider.GetCustomAttributes(typeof(T), true)) action(attribute); } public static string Stringify(this object value) { try { return StringifyInternal(value, RecursionLimit); } catch (InvalidOperationException ex) { return value.ToString(); } } static string StringifyInternal(object value, int recursionLevel) { if (value == null) return "null"; if (recursionLevel < 0) throw new InvalidOperationException(); if (value is string || value is char) return "\"" + value + "\""; var collection = value as IEnumerable; if (collection != null) return StringifyCollection(collection, recursionLevel); if (value.GetType().IsValueType) return value.ToString(); return StringifyObject(value, recursionLevel); } static string StringifyCollection(IEnumerable collection, int recursionLevel) { string[] elements = collection.Cast<object>() .Select(x => StringifyInternal(x, recursionLevel - 1)) .ToArray(); return "[" + String.Join(", ", elements) + "]"; } static string StringifyObject(object value, int recursionLevel) { string[] elements = value .GetType() .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) .Select(x => "{0} = {1}".FormatWith(x.Name, StringifyInternal(x.GetValue(value, null), recursionLevel - 1))) .ToArray(); return "{" + String.Join(", ", elements) + "}"; } public static T CastAs<T>(this object input) where T : class { if (input == null) throw new ArgumentNullException("input"); var result = input as T; if (result == null) throw new InvalidOperationException("Unable to convert from " + input.GetType().FullName + " to " + typeof(T).FullName); return result; } /// <summary> /// Returns the value of the instance member, or the default value if the instance is null /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TValue"></typeparam> /// <param name="instance"></param> /// <param name="accessor"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static TValue ValueOrDefault<T, TValue>(this T instance, Func<T, TValue> accessor, TValue defaultValue) where T : class { if (null == instance) return defaultValue; return accessor(instance); } #endregion } }