context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// <copyright file="Precision.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2015 Math.NET // // 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. // </copyright> using System; using System.Runtime; using System.Runtime.InteropServices; namespace MathNet.Numerics { /// <summary> /// Support Interface for Precision Operations (like AlmostEquals). /// </summary> /// <typeparam name="T">Type of the implementing class.</typeparam> public interface IPrecisionSupport<in T> { /// <summary> /// Returns a Norm of a value of this type, which is appropriate for measuring how /// close this value is to zero. /// </summary> /// <returns>A norm of this value.</returns> double Norm(); /// <summary> /// Returns a Norm of the difference of two values of this type, which is /// appropriate for measuring how close together these two values are. /// </summary> /// <param name="otherValue">The value to compare with.</param> /// <returns>A norm of the difference between this and the other value.</returns> double NormOfDifference(T otherValue); } /// <summary> /// Utilities for working with floating point numbers. /// </summary> /// <remarks> /// <para> /// Useful links: /// <list type="bullet"> /// <item> /// http://docs.sun.com/source/806-3568/ncg_goldberg.html#689 - What every computer scientist should know about floating-point arithmetic /// </item> /// <item> /// http://en.wikipedia.org/wiki/Machine_epsilon - Gives the definition of machine epsilon /// </item> /// </list> /// </para> /// </remarks> public static partial class Precision { /// <summary> /// The number of binary digits used to represent the binary number for a double precision floating /// point value. i.e. there are this many digits used to represent the /// actual number, where in a number as: 0.134556 * 10^5 the digits are 0.134556 and the exponent is 5. /// </summary> const int DoubleWidth = 53; /// <summary> /// The number of binary digits used to represent the binary number for a single precision floating /// point value. i.e. there are this many digits used to represent the /// actual number, where in a number as: 0.134556 * 10^5 the digits are 0.134556 and the exponent is 5. /// </summary> const int SingleWidth = 24; /// <summary> /// Standard epsilon, the maximum relative precision of IEEE 754 double-precision floating numbers (64 bit). /// According to the definition of Prof. Demmel and used in LAPACK and Scilab. /// </summary> public static readonly double DoublePrecision = Math.Pow(2, -DoubleWidth); /// <summary> /// Standard epsilon, the maximum relative precision of IEEE 754 double-precision floating numbers (64 bit). /// According to the definition of Prof. Higham and used in the ISO C standard and MATLAB. /// </summary> public static readonly double PositiveDoublePrecision = 2*DoublePrecision; /// <summary> /// Standard epsilon, the maximum relative precision of IEEE 754 single-precision floating numbers (32 bit). /// According to the definition of Prof. Demmel and used in LAPACK and Scilab. /// </summary> public static readonly double SinglePrecision = Math.Pow(2, -SingleWidth); /// <summary> /// Standard epsilon, the maximum relative precision of IEEE 754 single-precision floating numbers (32 bit). /// According to the definition of Prof. Higham and used in the ISO C standard and MATLAB. /// </summary> public static readonly double PositiveSinglePrecision = 2*SinglePrecision; /// <summary> /// Actual double precision machine epsilon, the smallest number that can be subtracted from 1, yielding a results different than 1. /// This is also known as unit roundoff error. According to the definition of Prof. Demmel. /// On a standard machine this is equivalent to `DoublePrecision`. /// </summary> public static readonly double MachineEpsilon = MeasureMachineEpsilon(); /// <summary> /// Actual double precision machine epsilon, the smallest number that can be added to 1, yielding a results different than 1. /// This is also known as unit roundoff error. According to the definition of Prof. Higham. /// On a standard machine this is equivalent to `PositiveDoublePrecision`. /// </summary> public static readonly double PositiveMachineEpsilon = MeasurePositiveMachineEpsilon(); /// <summary> /// The number of significant decimal places of double-precision floating numbers (64 bit). /// </summary> public static readonly int DoubleDecimalPlaces = (int) Math.Floor(Math.Abs(Math.Log10(DoublePrecision))); /// <summary> /// The number of significant decimal places of single-precision floating numbers (32 bit). /// </summary> public static readonly int SingleDecimalPlaces = (int) Math.Floor(Math.Abs(Math.Log10(SinglePrecision))); /// <summary> /// Value representing 10 * 2^(-53) = 1.11022302462516E-15 /// </summary> static readonly double DefaultDoubleAccuracy = DoublePrecision*10; /// <summary> /// Value representing 10 * 2^(-24) = 5.96046447753906E-07 /// </summary> static readonly float DefaultSingleAccuracy = (float) (SinglePrecision*10); /// <summary> /// Returns the magnitude of the number. /// </summary> /// <param name="value">The value.</param> /// <returns>The magnitude of the number.</returns> public static int Magnitude(this double value) { // Can't do this with zero because the 10-log of zero doesn't exist. if (value.Equals(0.0)) { return 0; } // Note that we need the absolute value of the input because Log10 doesn't // work for negative numbers (obviously). double magnitude = Math.Log10(Math.Abs(value)); var truncated = (int)Truncate(magnitude); // To get the right number we need to know if the value is negative or positive // truncating a positive number will always give use the correct magnitude // truncating a negative number will give us a magnitude that is off by 1 (unless integer) return magnitude < 0d && truncated != magnitude ? truncated - 1 : truncated; } /// <summary> /// Returns the magnitude of the number. /// </summary> /// <param name="value">The value.</param> /// <returns>The magnitude of the number.</returns> public static int Magnitude(this float value) { // Can't do this with zero because the 10-log of zero doesn't exist. if (value.Equals(0.0f)) { return 0; } // Note that we need the absolute value of the input because Log10 doesn't // work for negative numbers (obviously). var magnitude = Convert.ToSingle(Math.Log10(Math.Abs(value))); var truncated = (int)Truncate(magnitude); // To get the right number we need to know if the value is negative or positive // truncating a positive number will always give use the correct magnitude // truncating a negative number will give us a magnitude that is off by 1 (unless integer) return magnitude < 0f && truncated != magnitude ? truncated - 1 : truncated; } /// <summary> /// Returns the number divided by it's magnitude, effectively returning a number between -10 and 10. /// </summary> /// <param name="value">The value.</param> /// <returns>The value of the number.</returns> public static double ScaleUnitMagnitude(this double value) { if (value.Equals(0.0)) { return value; } int magnitude = Magnitude(value); return value*Math.Pow(10, -magnitude); } /// <summary> /// Returns a 'directional' long value. This is a long value which acts the same as a double, /// e.g. a negative double value will return a negative double value starting at 0 and going /// more negative as the double value gets more negative. /// </summary> /// <param name="value">The input double value.</param> /// <returns>A long value which is roughly the equivalent of the double value.</returns> static long AsDirectionalInt64(double value) { // Convert in the normal way. long result = BitConverter.DoubleToInt64Bits(value); // Now find out where we're at in the range // If the value is larger/equal to zero then we can just return the value // if the value is negative we subtract long.MinValue from it. return (result >= 0) ? result : (long.MinValue - result); } /// <summary> /// Returns a 'directional' int value. This is a int value which acts the same as a float, /// e.g. a negative float value will return a negative int value starting at 0 and going /// more negative as the float value gets more negative. /// </summary> /// <param name="value">The input float value.</param> /// <returns>An int value which is roughly the equivalent of the double value.</returns> static int AsDirectionalInt32(float value) { // Convert in the normal way. int result = SingleToInt32Bits(value); // Now find out where we're at in the range // If the value is larger/equal to zero then we can just return the value // if the value is negative we subtract int.MinValue from it. return (result >= 0) ? result : (int.MinValue - result); } /// <summary> /// Increments a floating point number to the next bigger number representable by the data type. /// </summary> /// <param name="value">The value which needs to be incremented.</param> /// <param name="count">How many times the number should be incremented.</param> /// <remarks> /// The incrementation step length depends on the provided value. /// Increment(double.MaxValue) will return positive infinity. /// </remarks> /// <returns>The next larger floating point value.</returns> public static double Increment(this double value, int count = 1) { if (double.IsInfinity(value) || double.IsNaN(value) || count == 0) { return value; } if (count < 0) { return Decrement(value, -count); } // Translate the bit pattern of the double to an integer. // Note that this leads to: // double > 0 --> long > 0, growing as the double value grows // double < 0 --> long < 0, increasing in absolute magnitude as the double // gets closer to zero! // i.e. 0 - double.epsilon will give the largest long value! long intValue = BitConverter.DoubleToInt64Bits(value); if (intValue < 0) { intValue -= count; } else { intValue += count; } // Note that long.MinValue has the same bit pattern as -0.0. if (intValue == long.MinValue) { return 0; } // Note that not all long values can be translated into double values. There's a whole bunch of them // which return weird values like infinity and NaN return BitConverter.Int64BitsToDouble(intValue); } /// <summary> /// Decrements a floating point number to the next smaller number representable by the data type. /// </summary> /// <param name="value">The value which should be decremented.</param> /// <param name="count">How many times the number should be decremented.</param> /// <remarks> /// The decrementation step length depends on the provided value. /// Decrement(double.MinValue) will return negative infinity. /// </remarks> /// <returns>The next smaller floating point value.</returns> public static double Decrement(this double value, int count = 1) { if (double.IsInfinity(value) || double.IsNaN(value) || count == 0) { return value; } if (count < 0) { return Decrement(value, -count); } // Translate the bit pattern of the double to an integer. // Note that this leads to: // double > 0 --> long > 0, growing as the double value grows // double < 0 --> long < 0, increasing in absolute magnitude as the double // gets closer to zero! // i.e. 0 - double.epsilon will give the largest long value! long intValue = BitConverter.DoubleToInt64Bits(value); // If the value is zero then we'd really like the value to be -0. So we'll make it -0 // and then everything else should work out. if (intValue == 0) { // Note that long.MinValue has the same bit pattern as -0.0. intValue = long.MinValue; } if (intValue < 0) { intValue += count; } else { intValue -= count; } // Note that not all long values can be translated into double values. There's a whole bunch of them // which return weird values like infinity and NaN return BitConverter.Int64BitsToDouble(intValue); } /// <summary> /// Forces small numbers near zero to zero, according to the specified absolute accuracy. /// </summary> /// <param name="a">The real number to coerce to zero, if it is almost zero.</param> /// <param name="maxNumbersBetween">The maximum count of numbers between the zero and the number <paramref name="a"/>.</param> /// <returns> /// Zero if |<paramref name="a"/>| is fewer than <paramref name="maxNumbersBetween"/> numbers from zero, <paramref name="a"/> otherwise. /// </returns> public static double CoerceZero(this double a, int maxNumbersBetween) { return CoerceZero(a, (long) maxNumbersBetween); } /// <summary> /// Forces small numbers near zero to zero, according to the specified absolute accuracy. /// </summary> /// <param name="a">The real number to coerce to zero, if it is almost zero.</param> /// <param name="maxNumbersBetween">The maximum count of numbers between the zero and the number <paramref name="a"/>.</param> /// <returns> /// Zero if |<paramref name="a"/>| is fewer than <paramref name="maxNumbersBetween"/> numbers from zero, <paramref name="a"/> otherwise. /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// Thrown if <paramref name="maxNumbersBetween"/> is smaller than zero. /// </exception> public static double CoerceZero(this double a, long maxNumbersBetween) { if (maxNumbersBetween < 0) { throw new ArgumentOutOfRangeException("maxNumbersBetween"); } if (double.IsInfinity(a) || double.IsNaN(a)) { return a; } // We allow maxNumbersBetween between 0 and the number so // we need to check if there a if (NumbersBetween(0.0, a) <= (ulong) maxNumbersBetween) { return 0.0; } return a; } /// <summary> /// Forces small numbers near zero to zero, according to the specified absolute accuracy. /// </summary> /// <param name="a">The real number to coerce to zero, if it is almost zero.</param> /// <param name="maximumAbsoluteError">The absolute threshold for <paramref name="a"/> to consider it as zero.</param> /// <returns>Zero if |<paramref name="a"/>| is smaller than <paramref name="maximumAbsoluteError"/>, <paramref name="a"/> otherwise.</returns> /// <exception cref="ArgumentOutOfRangeException"> /// Thrown if <paramref name="maximumAbsoluteError"/> is smaller than zero. /// </exception> public static double CoerceZero(this double a, double maximumAbsoluteError) { if (maximumAbsoluteError < 0) { throw new ArgumentOutOfRangeException("maximumAbsoluteError"); } if (double.IsInfinity(a) || double.IsNaN(a)) { return a; } if (Math.Abs(a) < maximumAbsoluteError) { return 0.0; } return a; } /// <summary> /// Forces small numbers near zero to zero. /// </summary> /// <param name="a">The real number to coerce to zero, if it is almost zero.</param> /// <returns>Zero if |<paramref name="a"/>| is smaller than 2^(-53) = 1.11e-16, <paramref name="a"/> otherwise.</returns> public static double CoerceZero(this double a) { return CoerceZero(a, DoublePrecision); } /// <summary> /// Determines the range of floating point numbers that will match the specified value with the given tolerance. /// </summary> /// <param name="value">The value.</param> /// <param name="maxNumbersBetween">The <c>ulps</c> difference.</param> /// <exception cref="ArgumentOutOfRangeException"> /// Thrown if <paramref name="maxNumbersBetween"/> is smaller than zero. /// </exception> /// <returns>Tuple of the bottom and top range ends.</returns> public static Tuple<double, double> RangeOfMatchingFloatingPointNumbers(this double value, long maxNumbersBetween) { // Make sure ulpDifference is non-negative if (maxNumbersBetween < 1) { throw new ArgumentOutOfRangeException("maxNumbersBetween"); } // If the value is infinity (positive or negative) just // return the same infinity for the range. if (double.IsInfinity(value)) { return new Tuple<double, double>(value, value); } // If the value is a NaN then the range is a NaN too. if (double.IsNaN(value)) { return new Tuple<double, double>(double.NaN, double.NaN); } // Translate the bit pattern of the double to an integer. // Note that this leads to: // double > 0 --> long > 0, growing as the double value grows // double < 0 --> long < 0, increasing in absolute magnitude as the double // gets closer to zero! // i.e. 0 - double.epsilon will give the largest long value! long intValue = BitConverter.DoubleToInt64Bits(value); // We need to protect against over- and under-flow of the intValue when // we start to add the ulpsDifference. if (intValue < 0) { // Note that long.MinValue has the same bit pattern as // -0.0. Therefore we're working in opposite direction (i.e. add if we want to // go more negative and subtract if we want to go less negative) var topRangeEnd = Math.Abs(long.MinValue - intValue) < maxNumbersBetween // Got underflow, which can be fixed by splitting the calculation into two bits // first get the remainder of the intValue after subtracting it from the long.MinValue // and add that to the ulpsDifference. That way we'll turn positive without underflow ? BitConverter.Int64BitsToDouble(maxNumbersBetween + (long.MinValue - intValue)) // No problems here, move along. : BitConverter.Int64BitsToDouble(intValue - maxNumbersBetween); var bottomRangeEnd = Math.Abs(intValue) < maxNumbersBetween // Underflow, which means we'd have to go further than a long would allow us. // Also we couldn't translate it back to a double, so we'll return -Double.MaxValue ? -double.MaxValue // intValue is negative. Adding the positive ulpsDifference means that it gets less negative. // However due to the conversion way this means that the actual double value gets more negative :-S : BitConverter.Int64BitsToDouble(intValue + maxNumbersBetween); return new Tuple<double, double>(bottomRangeEnd, topRangeEnd); } else { // IntValue is positive var topRangeEnd = long.MaxValue - intValue < maxNumbersBetween // Overflow, which means we'd have to go further than a long would allow us. // Also we couldn't translate it back to a double, so we'll return Double.MaxValue ? double.MaxValue // No troubles here : BitConverter.Int64BitsToDouble(intValue + maxNumbersBetween); // Check the bottom range end for underflows var bottomRangeEnd = intValue > maxNumbersBetween // No problems here. IntValue is larger than ulpsDifference so we'll end up with a // positive number. ? BitConverter.Int64BitsToDouble(intValue - maxNumbersBetween) // Int value is bigger than zero but smaller than the ulpsDifference. So we'll need to deal with // the reversal at the negative end : BitConverter.Int64BitsToDouble(long.MinValue + (maxNumbersBetween - intValue)); return new Tuple<double, double>(bottomRangeEnd, topRangeEnd); } } /// <summary> /// Returns the floating point number that will match the value with the tolerance on the maximum size (i.e. the result is /// always bigger than the value) /// </summary> /// <param name="value">The value.</param> /// <param name="maxNumbersBetween">The <c>ulps</c> difference.</param> /// <returns>The maximum floating point number which is <paramref name="maxNumbersBetween"/> larger than the given <paramref name="value"/>.</returns> public static double MaximumMatchingFloatingPointNumber(this double value, long maxNumbersBetween) { return RangeOfMatchingFloatingPointNumbers(value, maxNumbersBetween).Item2; } /// <summary> /// Returns the floating point number that will match the value with the tolerance on the minimum size (i.e. the result is /// always smaller than the value) /// </summary> /// <param name="value">The value.</param> /// <param name="maxNumbersBetween">The <c>ulps</c> difference.</param> /// <returns>The minimum floating point number which is <paramref name="maxNumbersBetween"/> smaller than the given <paramref name="value"/>.</returns> public static double MinimumMatchingFloatingPointNumber(this double value, long maxNumbersBetween) { return RangeOfMatchingFloatingPointNumbers(value, maxNumbersBetween).Item1; } /// <summary> /// Determines the range of <c>ulps</c> that will match the specified value with the given tolerance. /// </summary> /// <param name="value">The value.</param> /// <param name="relativeDifference">The relative difference.</param> /// <exception cref="ArgumentOutOfRangeException"> /// Thrown if <paramref name="relativeDifference"/> is smaller than zero. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// Thrown if <paramref name="value"/> is <c>double.PositiveInfinity</c> or <c>double.NegativeInfinity</c>. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// Thrown if <paramref name="value"/> is <c>double.NaN</c>. /// </exception> /// <returns> /// Tuple with the number of ULPS between the <c>value</c> and the <c>value - relativeDifference</c> as first, /// and the number of ULPS between the <c>value</c> and the <c>value + relativeDifference</c> as second value. /// </returns> public static Tuple<long, long> RangeOfMatchingNumbers(this double value, double relativeDifference) { // Make sure the relative is non-negative if (relativeDifference < 0) { throw new ArgumentOutOfRangeException("relativeDifference"); } // If the value is infinity (positive or negative) then // we can't determine the range. if (double.IsInfinity(value)) { throw new ArgumentOutOfRangeException("value"); } // If the value is a NaN then we can't determine the range. if (double.IsNaN(value)) { throw new ArgumentOutOfRangeException("value"); } // If the value is zero (0.0) then we can't calculate the relative difference // so return the ulps counts for the difference. if (value.Equals(0)) { var v = BitConverter.DoubleToInt64Bits(relativeDifference); return new Tuple<long, long>(v, v); } // Calculate the ulps for the maximum and minimum values // Note that these can overflow long max = AsDirectionalInt64(value + (relativeDifference*Math.Abs(value))); long min = AsDirectionalInt64(value - (relativeDifference*Math.Abs(value))); // Calculate the ulps from the value long intValue = AsDirectionalInt64(value); // Determine the ranges return new Tuple<long, long>(Math.Abs(intValue - min), Math.Abs(max - intValue)); } /// <summary> /// Evaluates the count of numbers between two double numbers /// </summary> /// <param name="a">The first parameter.</param> /// <param name="b">The second parameter.</param> /// <remarks>The second number is included in the number, thus two equal numbers evaluate to zero and two neighbor numbers evaluate to one. Therefore, what is returned is actually the count of numbers between plus 1.</remarks> /// <returns>The number of floating point values between <paramref name="a"/> and <paramref name="b"/>.</returns> /// <exception cref="ArgumentOutOfRangeException"> /// Thrown if <paramref name="a"/> is <c>double.PositiveInfinity</c> or <c>double.NegativeInfinity</c>. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// Thrown if <paramref name="a"/> is <c>double.NaN</c>. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// Thrown if <paramref name="b"/> is <c>double.PositiveInfinity</c> or <c>double.NegativeInfinity</c>. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// Thrown if <paramref name="b"/> is <c>double.NaN</c>. /// </exception> [CLSCompliant(false)] public static ulong NumbersBetween(this double a, double b) { if (double.IsNaN(a) || double.IsInfinity(a)) { throw new ArgumentOutOfRangeException("a"); } if (double.IsNaN(b) || double.IsInfinity(b)) { throw new ArgumentOutOfRangeException("b"); } // Calculate the ulps for the maximum and minimum values // Note that these can overflow long intA = AsDirectionalInt64(a); long intB = AsDirectionalInt64(b); // Now find the number of values between the two doubles. This should not overflow // given that there are more long values than there are double values return (a >= b) ? (ulong) (intA - intB) : (ulong) (intB - intA); } /// <summary> /// Evaluates the minimum distance to the next distinguishable number near the argument value. /// </summary> /// <param name="value">The value used to determine the minimum distance.</param> /// <returns> /// Relative Epsilon (positive double or NaN). /// </returns> /// <remarks>Evaluates the <b>negative</b> epsilon. The more common positive epsilon is equal to two times this negative epsilon.</remarks> /// <seealso cref="PositiveEpsilonOf(double)"/> public static double EpsilonOf(this double value) { if (double.IsInfinity(value) || double.IsNaN(value)) { return double.NaN; } long signed64 = BitConverter.DoubleToInt64Bits(value); if (signed64 == 0) { signed64++; return BitConverter.Int64BitsToDouble(signed64) - value; } if (signed64-- < 0) { return BitConverter.Int64BitsToDouble(signed64) - value; } return value - BitConverter.Int64BitsToDouble(signed64); } /// <summary> /// Evaluates the minimum distance to the next distinguishable number near the argument value. /// </summary> /// <param name="value">The value used to determine the minimum distance.</param> /// <returns> /// Relative Epsilon (positive float or NaN). /// </returns> /// <remarks>Evaluates the <b>negative</b> epsilon. The more common positive epsilon is equal to two times this negative epsilon.</remarks> /// <seealso cref="PositiveEpsilonOf(float)"/> public static float EpsilonOf(this float value) { if (float.IsInfinity(value) || float.IsNaN(value)) { return float.NaN; } int signed32 = SingleToInt32Bits(value); if (signed32 == 0) { signed32++; return Int32BitsToSingle(signed32) - value; } if (signed32-- < 0) { return Int32BitsToSingle(signed32) - value; } return value - Int32BitsToSingle(signed32); } /// <summary> /// Evaluates the minimum distance to the next distinguishable number near the argument value. /// </summary> /// <param name="value">The value used to determine the minimum distance.</param> /// <returns>Relative Epsilon (positive double or NaN)</returns> /// <remarks>Evaluates the <b>positive</b> epsilon. See also <see cref="EpsilonOf(double)"/></remarks> /// <seealso cref="EpsilonOf(double)"/> public static double PositiveEpsilonOf(this double value) { return 2*EpsilonOf(value); } /// <summary> /// Evaluates the minimum distance to the next distinguishable number near the argument value. /// </summary> /// <param name="value">The value used to determine the minimum distance.</param> /// <returns>Relative Epsilon (positive float or NaN)</returns> /// <remarks>Evaluates the <b>positive</b> epsilon. See also <see cref="EpsilonOf(float)"/></remarks> /// <seealso cref="EpsilonOf(float)"/> public static float PositiveEpsilonOf(this float value) { return 2 * EpsilonOf(value); } /// <summary> /// Calculates the actual (negative) double precision machine epsilon - the smallest number that can be subtracted from 1, yielding a results different than 1. /// This is also known as unit roundoff error. According to the definition of Prof. Demmel. /// </summary> /// <returns>Positive Machine epsilon</returns> static double MeasureMachineEpsilon() { double eps = 1.0d; while ((1.0d - (eps / 2.0d)) < 1.0d) eps /= 2.0d; return eps; } /// <summary> /// Calculates the actual positive double precision machine epsilon - the smallest number that can be added to 1, yielding a results different than 1. /// This is also known as unit roundoff error. According to the definition of Prof. Higham. /// </summary> /// <returns>Machine epsilon</returns> static double MeasurePositiveMachineEpsilon() { double eps = 1.0d; while ((1.0d + (eps / 2.0d)) > 1.0d) eps /= 2.0d; return eps; } [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] static double Truncate(double value) { #if PORTABLE return value >= 0.0 ? Math.Floor(value) : Math.Ceiling(value); #else return Math.Truncate(value); #endif } static int SingleToInt32Bits(float value) { var union = new SingleIntUnion { Single = value }; return union.Int32; } static float Int32BitsToSingle(int value) { var union = new SingleIntUnion { Int32 = value }; return union.Single; } [StructLayout(LayoutKind.Explicit)] struct SingleIntUnion { [FieldOffset(0)] public float Single; [FieldOffset(0)] public int Int32; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Console : IGameSystem { const int k_BufferSize = 80 * 25 * 1000; // arbitrarily set to 1000 scroll back lines at 80x25 const int k_InputBufferSize = 512; const int k_HistorySize = 1000; // lines of history int m_Width; int m_Height; int m_NumLines; int m_LastLine; int m_LastColumn; int m_LastVisibleLine; float m_ConsoleFoldout; float m_ConsoleFoldoutDest; bool m_ConsoleOpen; char[] m_InputFieldBuffer; int m_CursorPos = 0; int m_InputFieldLength = 0; string[] m_History = new string[k_HistorySize]; int m_HistoryDisplayIndex = 0; int m_HistoryNextIndex = 0; Color m_BackgroundColor = new Color(0, 0, 0, 0.9f); Vector4 m_TextColor = new Vector4(0.7f, 1.0f, 0.7f, 1.0f); Color m_CursorCol = new Color(0, 0.8f, 0.2f, 0.5f); System.UInt32[] m_ConsoleBuffer; public Console() { m_ConsoleBuffer = new System.UInt32[k_BufferSize]; m_InputFieldBuffer = new char[k_InputBufferSize]; AddCommand("help", CmdHelp, "Show available commands"); } void CmdHelp(string[] args) { foreach (var c in m_Commands) { Write(" {0,-15} {1}\n", c.Key, m_CommandDescriptions[c.Key]); } } public void Init() { Init(null); } public void Init(DebugOverlay debugOverlay) { m_DebugOverlay = debugOverlay != null ? debugOverlay : DebugOverlay.instance; Resize(m_DebugOverlay.width, m_DebugOverlay.height); Clear(); } public void Shutdown() { } public delegate void CommandDelegate(string[] args); Dictionary<string, CommandDelegate> m_Commands = new Dictionary<string, CommandDelegate>(); Dictionary<string, string> m_CommandDescriptions = new Dictionary<string, string>(); public void AddCommand(string name, CommandDelegate callback, string description) { if (m_Commands.ContainsKey(name)) { Write("Cannot add command {0} twice", name); return; } m_Commands.Add(name, callback); m_CommandDescriptions.Add(name, description); } public void Resize(int width, int height) { m_Width = width; m_Height = height; m_NumLines = m_ConsoleBuffer.Length / m_Width; m_LastLine = m_Height - 1; m_LastVisibleLine = m_Height - 1; m_LastColumn = 0; // TODO: copy old text to resized console } public void Clear() { for (int i = 0, c = m_ConsoleBuffer.Length; i < c; i++) m_ConsoleBuffer[i] = 0; m_LastColumn = 0; } public void Show(float shown) { m_ConsoleFoldoutDest = shown; } public void TickUpdate() { if (Input.GetKeyDown(KeyCode.F12)) { m_ConsoleOpen = !m_ConsoleOpen; m_ConsoleFoldoutDest = m_ConsoleOpen ? 1.0f : 0.0f; Show(m_ConsoleFoldoutDest); } if (!m_ConsoleOpen) return; Scroll((int)Input.mouseScrollDelta.y); if (Input.anyKey) { if (Input.GetKeyDown(KeyCode.LeftArrow) && m_CursorPos > 0) m_CursorPos--; else if (Input.GetKeyDown(KeyCode.RightArrow) && m_CursorPos < m_InputFieldLength) m_CursorPos++; else if (Input.GetKeyDown(KeyCode.Home) || (Input.GetKeyDown(KeyCode.A) && (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)))) m_CursorPos = 0; else if (Input.GetKeyDown(KeyCode.End) || (Input.GetKeyDown(KeyCode.E) && (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)))) m_CursorPos = m_InputFieldLength; else if (Input.GetKeyDown(KeyCode.Tab)) TabComplete(); else if (Input.GetKeyDown(KeyCode.UpArrow)) HistoryPrev(); else if (Input.GetKeyDown(KeyCode.DownArrow)) HistoryNext(); else { // TODO replace with garbage free alternative (perhaps impossible until new input system?) var inputString = Input.inputString; for (var i = 0; i < inputString.Length; i++) { var ch = inputString[i]; if (ch == '\b') Backspace(); else if (ch == '\n' || ch == '\r') { var s = new string(m_InputFieldBuffer, 0, m_InputFieldLength); HistoryStore(s); ExecuteCommand(s); m_InputFieldLength = 0; m_CursorPos = 0; } else Type(ch); } } } } void HistoryPrev() { if (m_HistoryDisplayIndex == 0 || m_HistoryNextIndex - m_HistoryDisplayIndex >= m_History.Length - 1) return; if (m_HistoryDisplayIndex == m_HistoryNextIndex) m_History[m_HistoryNextIndex % m_History.Length] = new string(m_InputFieldBuffer, 0, m_InputFieldLength); m_HistoryDisplayIndex--; var s = m_History[m_HistoryDisplayIndex % m_History.Length]; s.CopyTo(0, m_InputFieldBuffer, 0, s.Length); m_InputFieldLength = s.Length; m_CursorPos = s.Length; } void HistoryNext() { if (m_HistoryDisplayIndex == m_HistoryNextIndex) return; m_HistoryDisplayIndex++; var s = m_History[m_HistoryDisplayIndex % m_History.Length]; s.CopyTo(0, m_InputFieldBuffer, 0, s.Length); m_InputFieldLength = s.Length; m_CursorPos = s.Length; } void HistoryStore(string cmd) { m_History[m_HistoryNextIndex % m_History.Length] = cmd; m_HistoryNextIndex++; m_HistoryDisplayIndex = m_HistoryNextIndex; } void ExecuteCommand(string command) { var splitCommand = command.Split(null as char[], System.StringSplitOptions.RemoveEmptyEntries); if (splitCommand.Length < 1) return; Write('>' + string.Join(" ", splitCommand) + '\n'); var commandName = splitCommand[0].ToLower(); CommandDelegate commandDelegate; if (m_Commands.TryGetValue(commandName, out commandDelegate)) { var arguments = new string[splitCommand.Length - 1]; System.Array.Copy(splitCommand, 1, arguments, 0, splitCommand.Length - 1); commandDelegate(arguments); } else { Write("Unknown command: {0}\n", splitCommand[0]); } } public void TickLateUpdate() { if (m_ConsoleFoldout < m_ConsoleFoldoutDest) { m_ConsoleFoldout = Mathf.Min(m_ConsoleFoldoutDest, m_ConsoleFoldout + Time.deltaTime * 5.0f); } else if (m_ConsoleFoldout > m_ConsoleFoldoutDest) { m_ConsoleFoldout = Mathf.Max(m_ConsoleFoldoutDest, m_ConsoleFoldout - Time.deltaTime * 5.0f); } if (m_ConsoleFoldout <= 0.0f) return; var yoffset = -(float)m_Height * (1.0f - m_ConsoleFoldout); m_DebugOverlay._DrawRect(0, 0 + yoffset, m_Width, m_Height, m_BackgroundColor); var line = m_LastVisibleLine; if ((m_LastVisibleLine == m_LastLine) && (m_LastColumn == 0)) { line -= 1; } Vector4 col = m_TextColor; UInt32 icol = 0; for (var i = 0; i < m_Height - 1; i++, line--) { var idx = (line % m_NumLines) * m_Width; for (var j = 0; j < m_Width; j++) { UInt32 c = m_ConsoleBuffer[idx + j]; char ch = (char)(c & 0xff); if (icol != (c & 0xffffff00)) { icol = c & 0xffffff00; col.x = (float)((icol >> 24) & 0xff) / 255.0f; col.y = (float)((icol >> 16) & 0xff) / 255.0f; col.z = (float)((icol >> 8) & 0xff) / 255.0f; } if (c != '\0') m_DebugOverlay.AddQuad(j, m_Height - 2 - i + yoffset, 1, 1, ch, col); } } // Draw input line var horizontalScroll = m_CursorPos - m_Width + 1; horizontalScroll = Mathf.Max(0, horizontalScroll); for (var i = horizontalScroll; i < m_InputFieldLength; i++) { char c = m_InputFieldBuffer[i]; if (c != '\0') m_DebugOverlay.AddQuad(i - horizontalScroll, m_Height - 1 + yoffset, 1, 1, c, m_TextColor); } m_DebugOverlay.AddQuad(m_CursorPos - horizontalScroll, m_Height - 1 + yoffset, 1, 1, '\0', m_CursorCol); } void NewLine() { // Only scroll view if at bottom if (m_LastVisibleLine == m_LastLine) m_LastVisibleLine++; m_LastLine++; m_LastColumn = 0; } void Scroll(int amount) { m_LastVisibleLine += amount; // Prevent going past last line if (m_LastVisibleLine > m_LastLine) m_LastVisibleLine = m_LastLine; if (m_LastVisibleLine < m_Height - 1) m_LastVisibleLine = m_Height - 1; // Prevent wrapping around if (m_LastVisibleLine < m_LastLine - m_NumLines + m_Height) m_LastVisibleLine = m_LastLine - m_NumLines + m_Height; } public void _Write(char[] buf, int length) { const string hexes = "0123456789ABCDEF"; UInt32 col = 0xBBBBBB00; for (int i = 0; i < length; i++) { if (buf[i] == '\n') { NewLine(); continue; } // Parse color markup of the form ^AF7 -> color(0xAA, 0xFF, 0x77) if (buf[i] == '^' && i < length - 3) { UInt32 res = 0; for (var j = i + 1; j < i + 4; j++) { var v = (uint)hexes.IndexOf(buf[j]); res = res * 256 + v * 16 + v; } col = res << 8; i += 3; continue; } var idx = (m_LastLine % m_NumLines) * m_Width + m_LastColumn; m_ConsoleBuffer[idx] = col | (byte)buf[i]; m_LastColumn++; if (m_LastColumn >= m_Width) { NewLine(); } } } static char[] _buf = new char[1024]; public void Write(string format) { var l = StringFormatter.Write(ref _buf, 0, format); _Write(_buf, l); } public void Write<T>(string format, T arg) { var l = StringFormatter.Write(ref _buf, 0, format, arg); _Write(_buf, l); } public void Write<T0, T1>(string format, T0 arg0, T1 arg1) { var l = StringFormatter.Write(ref _buf, 0, format, arg0, arg1); _Write(_buf, l); } public void Write<T0, T1, T2>(string format, T0 arg0, T1 arg1, T2 arg2) { var l = StringFormatter.Write(ref _buf, 0, format, arg0, arg1, arg2); _Write(_buf, l); } void Type(char c) { if (m_InputFieldLength >= m_InputFieldBuffer.Length) return; System.Array.Copy(m_InputFieldBuffer, m_CursorPos, m_InputFieldBuffer, m_CursorPos + 1, m_InputFieldLength - m_CursorPos); m_InputFieldBuffer[m_CursorPos] = c; m_CursorPos++; m_InputFieldLength++; } void Backspace() { if (m_CursorPos == 0) return; System.Array.Copy(m_InputFieldBuffer, m_CursorPos, m_InputFieldBuffer, m_CursorPos - 1, m_InputFieldLength - m_CursorPos); m_CursorPos--; m_InputFieldLength--; } void TabComplete() { string prefix = new string(m_InputFieldBuffer, 0, m_CursorPos); // Look for possible tab completions List<string> matches = new List<string>(); foreach (var c in m_Commands) { var name = c.Key; if (!name.StartsWith(prefix, true, null)) continue; matches.Add(name); } if (matches.Count == 0) return; // Look for longest common prefix int lcp = matches[0].Length; for (var i = 0; i < matches.Count - 1; i++) { lcp = Mathf.Min(lcp, CommonPrefix(matches[i], matches[i + 1])); } var bestMatch = matches[0].Substring(prefix.Length, lcp - prefix.Length); foreach (var c in bestMatch) Type(c); if (matches.Count > 1) { // write list of possible completions for (var i = 0; i < matches.Count; i++) Write(" {0}\n", matches[i]); } if (matches.Count == 1) Type(' '); } // Returns length of largest common prefix of two strings static int CommonPrefix(string a, string b) { int minl = Mathf.Min(a.Length, b.Length); for (int i = 1; i <= minl; i++) { if (!a.StartsWith(b.Substring(0, i), true, null)) return i - 1; } return minl; } DebugOverlay m_DebugOverlay; }
using Magnesium; using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Text; namespace Magnesium.Vulkan { public class VkPhysicalDevice : IMgPhysicalDevice { internal IntPtr Handle { get; private set;} internal VkPhysicalDevice(IntPtr handle) { Handle = handle; } /// <summary> /// Allocator is optional /// </summary> /// <param name="allocator"></param> /// <returns></returns> static IntPtr GetAllocatorHandle(IMgAllocationCallbacks allocator) { var bAllocator = (MgVkAllocationCallbacks)allocator; return bAllocator != null ? bAllocator.Handle : IntPtr.Zero; } public void GetPhysicalDeviceProperties(out MgPhysicalDeviceProperties pProperties) { var pCreateInfo = default(VkPhysicalDeviceProperties); Interops.vkGetPhysicalDeviceProperties(Handle, ref pCreateInfo); pProperties = new MgPhysicalDeviceProperties { ApiVersion = pCreateInfo.apiVersion, DriverVersion = pCreateInfo.driverVersion, VendorID = pCreateInfo.vendorID, DeviceID = pCreateInfo.deviceID, DeviceType = (MgPhysicalDeviceType) pCreateInfo.deviceType, DeviceName = VkInteropsUtility.ByteArrayToTrimmedString(pCreateInfo.deviceName), PipelineCacheUUID = new Guid(pCreateInfo.pipelineCacheUUID), Limits = new MgPhysicalDeviceLimits { MaxImageDimension1D = pCreateInfo.limits.maxImageDimension1D, MaxImageDimension2D = pCreateInfo.limits.maxImageDimension2D, MaxImageDimension3D = pCreateInfo.limits.maxImageDimension3D, MaxImageDimensionCube = pCreateInfo.limits.maxImageDimensionCube, MaxImageArrayLayers = pCreateInfo.limits.maxImageArrayLayers, MaxTexelBufferElements = pCreateInfo.limits.maxTexelBufferElements, MaxUniformBufferRange = pCreateInfo.limits.maxUniformBufferRange, MaxStorageBufferRange = pCreateInfo.limits.maxStorageBufferRange, MaxPushConstantsSize = pCreateInfo.limits.maxPushConstantsSize, MaxMemoryAllocationCount = pCreateInfo.limits.maxMemoryAllocationCount, MaxSamplerAllocationCount = pCreateInfo.limits.maxSamplerAllocationCount, BufferImageGranularity = pCreateInfo.limits.bufferImageGranularity, SparseAddressSpaceSize = pCreateInfo.limits.sparseAddressSpaceSize, MaxBoundDescriptorSets = pCreateInfo.limits.maxBoundDescriptorSets, MaxPerStageDescriptorSamplers = pCreateInfo.limits.maxPerStageDescriptorSamplers, MaxPerStageDescriptorUniformBuffers = pCreateInfo.limits.maxPerStageDescriptorUniformBuffers, MaxPerStageDescriptorStorageBuffers = pCreateInfo.limits.maxPerStageDescriptorStorageBuffers, MaxPerStageDescriptorSampledImages = pCreateInfo.limits.maxPerStageDescriptorSampledImages, MaxPerStageDescriptorStorageImages = pCreateInfo.limits.maxPerStageDescriptorStorageImages, MaxPerStageDescriptorInputAttachments = pCreateInfo.limits.maxPerStageDescriptorInputAttachments, MaxPerStageResources = pCreateInfo.limits.maxPerStageResources, MaxDescriptorSetSamplers = pCreateInfo.limits.maxDescriptorSetSamplers, MaxDescriptorSetUniformBuffers = pCreateInfo.limits.maxDescriptorSetUniformBuffers, MaxDescriptorSetUniformBuffersDynamic = pCreateInfo.limits.maxDescriptorSetUniformBuffersDynamic, MaxDescriptorSetStorageBuffers = pCreateInfo.limits.maxDescriptorSetStorageBuffers, MaxDescriptorSetStorageBuffersDynamic = pCreateInfo.limits.maxDescriptorSetStorageBuffersDynamic, MaxDescriptorSetSampledImages = pCreateInfo.limits.maxDescriptorSetSampledImages, MaxDescriptorSetStorageImages = pCreateInfo.limits.maxDescriptorSetStorageImages, MaxDescriptorSetInputAttachments = pCreateInfo.limits.maxDescriptorSetInputAttachments, MaxVertexInputAttributes = pCreateInfo.limits.maxVertexInputAttributes, MaxVertexInputBindings = pCreateInfo.limits.maxVertexInputBindings, MaxVertexInputAttributeOffset = pCreateInfo.limits.maxVertexInputAttributeOffset, MaxVertexInputBindingStride = pCreateInfo.limits.maxVertexInputBindingStride, MaxVertexOutputComponents = pCreateInfo.limits.maxVertexOutputComponents, MaxTessellationGenerationLevel = pCreateInfo.limits.maxTessellationGenerationLevel, MaxTessellationPatchSize = pCreateInfo.limits.maxTessellationPatchSize, MaxTessellationControlPerVertexInputComponents = pCreateInfo.limits.maxTessellationControlPerVertexInputComponents, MaxTessellationControlPerVertexOutputComponents = pCreateInfo.limits.maxTessellationControlPerVertexOutputComponents, MaxTessellationControlPerPatchOutputComponents = pCreateInfo.limits.maxTessellationControlPerPatchOutputComponents, MaxTessellationControlTotalOutputComponents = pCreateInfo.limits.maxTessellationControlTotalOutputComponents, MaxTessellationEvaluationInputComponents = pCreateInfo.limits.maxTessellationEvaluationInputComponents, MaxTessellationEvaluationOutputComponents = pCreateInfo.limits.maxTessellationEvaluationOutputComponents, MaxGeometryShaderInvocations = pCreateInfo.limits.maxGeometryShaderInvocations, MaxGeometryInputComponents = pCreateInfo.limits.maxGeometryInputComponents, MaxGeometryOutputComponents = pCreateInfo.limits.maxGeometryOutputComponents, MaxGeometryOutputVertices = pCreateInfo.limits.maxGeometryOutputVertices, MaxGeometryTotalOutputComponents = pCreateInfo.limits.maxGeometryTotalOutputComponents, MaxFragmentInputComponents = pCreateInfo.limits.maxFragmentInputComponents, MaxFragmentOutputAttachments = pCreateInfo.limits.maxFragmentOutputAttachments, MaxFragmentDualSrcAttachments = pCreateInfo.limits.maxFragmentDualSrcAttachments, MaxFragmentCombinedOutputResources = pCreateInfo.limits.maxFragmentCombinedOutputResources, MaxComputeSharedMemorySize = pCreateInfo.limits.maxComputeSharedMemorySize, MaxComputeWorkGroupCount = pCreateInfo.limits.maxComputeWorkGroupCount, MaxComputeWorkGroupInvocations = pCreateInfo.limits.maxComputeWorkGroupInvocations, MaxComputeWorkGroupSize = pCreateInfo.limits.maxComputeWorkGroupSize, SubPixelPrecisionBits = pCreateInfo.limits.subPixelPrecisionBits, SubTexelPrecisionBits = pCreateInfo.limits.subTexelPrecisionBits, MipmapPrecisionBits = pCreateInfo.limits.mipmapPrecisionBits, MaxDrawIndexedIndexValue = pCreateInfo.limits.maxDrawIndexedIndexValue, MaxDrawIndirectCount = pCreateInfo.limits.maxDrawIndirectCount, MaxSamplerLodBias = pCreateInfo.limits.maxSamplerLodBias, MaxSamplerAnisotropy = pCreateInfo.limits.maxSamplerAnisotropy, MaxViewports = pCreateInfo.limits.maxViewports, MaxViewportDimensions = pCreateInfo.limits.maxViewportDimensions, ViewportBoundsRange = pCreateInfo.limits.viewportBoundsRange, ViewportSubPixelBits = pCreateInfo.limits.viewportSubPixelBits, MinMemoryMapAlignment = pCreateInfo.limits.minMemoryMapAlignment, MinTexelBufferOffsetAlignment = pCreateInfo.limits.minTexelBufferOffsetAlignment, MinUniformBufferOffsetAlignment = pCreateInfo.limits.minUniformBufferOffsetAlignment, MinStorageBufferOffsetAlignment = pCreateInfo.limits.minStorageBufferOffsetAlignment, MinTexelOffset = pCreateInfo.limits.minTexelOffset, MaxTexelOffset = pCreateInfo.limits.maxTexelOffset, MinTexelGatherOffset = pCreateInfo.limits.minTexelGatherOffset, MaxTexelGatherOffset = pCreateInfo.limits.maxTexelGatherOffset, MinInterpolationOffset = pCreateInfo.limits.minInterpolationOffset, MaxInterpolationOffset = pCreateInfo.limits.maxInterpolationOffset, SubPixelInterpolationOffsetBits = pCreateInfo.limits.subPixelInterpolationOffsetBits, MaxFramebufferWidth = pCreateInfo.limits.maxFramebufferWidth, MaxFramebufferHeight = pCreateInfo.limits.maxFramebufferHeight, MaxFramebufferLayers = pCreateInfo.limits.maxFramebufferLayers, FramebufferColorSampleCounts = (MgSampleCountFlagBits) pCreateInfo.limits.framebufferColorSampleCounts, FramebufferDepthSampleCounts = (MgSampleCountFlagBits)pCreateInfo.limits.framebufferDepthSampleCounts, FramebufferStencilSampleCounts = (MgSampleCountFlagBits) pCreateInfo.limits.framebufferStencilSampleCounts, FramebufferNoAttachmentsSampleCounts = (MgSampleCountFlagBits)pCreateInfo.limits.framebufferNoAttachmentsSampleCounts, MaxColorAttachments = pCreateInfo.limits.maxColorAttachments, SampledImageColorSampleCounts = (MgSampleCountFlagBits) pCreateInfo.limits.sampledImageColorSampleCounts, SampledImageIntegerSampleCounts = (MgSampleCountFlagBits) pCreateInfo.limits.sampledImageIntegerSampleCounts, SampledImageDepthSampleCounts = (MgSampleCountFlagBits) pCreateInfo.limits.sampledImageDepthSampleCounts, SampledImageStencilSampleCounts = (MgSampleCountFlagBits) pCreateInfo.limits.sampledImageStencilSampleCounts, StorageImageSampleCounts = (MgSampleCountFlagBits) pCreateInfo.limits.storageImageSampleCounts, MaxSampleMaskWords = pCreateInfo.limits.maxSampleMaskWords, TimestampComputeAndGraphics = VkBool32.ConvertFrom(pCreateInfo.limits.timestampComputeAndGraphics), TimestampPeriod = pCreateInfo.limits.timestampPeriod, MaxClipDistances = pCreateInfo.limits.maxClipDistances, MaxCullDistances = pCreateInfo.limits.maxCullDistances, MaxCombinedClipAndCullDistances = pCreateInfo.limits.maxCombinedClipAndCullDistances, DiscreteQueuePriorities = pCreateInfo.limits.discreteQueuePriorities, PointSizeRange = pCreateInfo.limits.pointSizeRange, LineWidthRange = pCreateInfo.limits.lineWidthRange, PointSizeGranularity = pCreateInfo.limits.pointSizeGranularity, LineWidthGranularity = pCreateInfo.limits.lineWidthGranularity, StrictLines = VkBool32.ConvertFrom(pCreateInfo.limits.strictLines), StandardSampleLocations = VkBool32.ConvertFrom(pCreateInfo.limits.standardSampleLocations), OptimalBufferCopyOffsetAlignment = pCreateInfo.limits.optimalBufferCopyOffsetAlignment, OptimalBufferCopyRowPitchAlignment = pCreateInfo.limits.optimalBufferCopyRowPitchAlignment, NonCoherentAtomSize = pCreateInfo.limits.nonCoherentAtomSize, }, SparseProperties = new MgPhysicalDeviceSparseProperties { ResidencyStandard2DBlockShape = VkBool32.ConvertFrom(pCreateInfo.sparseProperties.residencyStandard2DBlockShape), ResidencyStandard2DMultisampleBlockShape = VkBool32.ConvertFrom(pCreateInfo.sparseProperties.residencyStandard2DMultisampleBlockShape), ResidencyStandard3DBlockShape = VkBool32.ConvertFrom(pCreateInfo.sparseProperties.residencyStandard3DBlockShape), ResidencyAlignedMipSize = VkBool32.ConvertFrom(pCreateInfo.sparseProperties.residencyAlignedMipSize), ResidencyNonResidentStrict = VkBool32.ConvertFrom(pCreateInfo.sparseProperties.residencyNonResidentStrict), }, }; } public void GetPhysicalDeviceQueueFamilyProperties(out MgQueueFamilyProperties[] pQueueFamilyProperties) { unsafe { var count = stackalloc uint[1]; count[0] = 0; Interops.vkGetPhysicalDeviceQueueFamilyProperties(Handle, count, null); var queueFamilyCount = (int) count[0]; var familyProperties = stackalloc VkQueueFamilyProperties[queueFamilyCount]; Interops.vkGetPhysicalDeviceQueueFamilyProperties(Handle, count, familyProperties); pQueueFamilyProperties = new MgQueueFamilyProperties[queueFamilyCount]; for (var i = 0; i < queueFamilyCount; ++i) { pQueueFamilyProperties[i] = new MgQueueFamilyProperties { QueueFlags = (MgQueueFlagBits)familyProperties[i].queueFlags, QueueCount = familyProperties[i].queueCount, TimestampValidBits = familyProperties[i].timestampValidBits, MinImageTransferGranularity = familyProperties[i].minImageTransferGranularity, }; } } } public void GetPhysicalDeviceMemoryProperties(out MgPhysicalDeviceMemoryProperties pMemoryProperties) { var memoryProperties = default(VkPhysicalDeviceMemoryProperties); Interops.vkGetPhysicalDeviceMemoryProperties(Handle, ref memoryProperties); var memoryHeaps = new MgMemoryHeap[memoryProperties.memoryHeapCount]; for (var i = 0; i < memoryProperties.memoryHeapCount; ++i) { memoryHeaps[i] = new MgMemoryHeap { Size = memoryProperties.memoryHeaps[i].size, Flags = (MgMemoryHeapFlagBits)memoryProperties.memoryHeaps[i].flags, }; } var memoryTypes = new MgMemoryType[memoryProperties.memoryTypeCount]; for (var i = 0; i < memoryProperties.memoryTypeCount; ++i) { memoryTypes[i] = new MgMemoryType { PropertyFlags = (uint)memoryProperties.memoryTypes[i].propertyFlags, HeapIndex = memoryProperties.memoryTypes[i].heapIndex, }; } pMemoryProperties = new MgPhysicalDeviceMemoryProperties { MemoryHeaps = memoryHeaps, MemoryTypes = memoryTypes, }; } public void GetPhysicalDeviceFeatures(out MgPhysicalDeviceFeatures pFeatures) { var features = default(VkPhysicalDeviceFeatures); Interops.vkGetPhysicalDeviceFeatures(Handle, ref features); pFeatures = new MgPhysicalDeviceFeatures { RobustBufferAccess = VkBool32.ConvertFrom(features.robustBufferAccess), FullDrawIndexUint32 = VkBool32.ConvertFrom(features.fullDrawIndexUint32), ImageCubeArray = VkBool32.ConvertFrom(features.imageCubeArray), IndependentBlend = VkBool32.ConvertFrom(features.independentBlend), GeometryShader = VkBool32.ConvertFrom(features.geometryShader), TessellationShader = VkBool32.ConvertFrom(features.tessellationShader), SampleRateShading = VkBool32.ConvertFrom(features.sampleRateShading), DualSrcBlend = VkBool32.ConvertFrom(features.dualSrcBlend), LogicOp = VkBool32.ConvertFrom(features.logicOp), MultiDrawIndirect = VkBool32.ConvertFrom(features.multiDrawIndirect), DrawIndirectFirstInstance = VkBool32.ConvertFrom(features.drawIndirectFirstInstance), DepthClamp = VkBool32.ConvertFrom(features.depthClamp), DepthBiasClamp = VkBool32.ConvertFrom(features.depthBiasClamp), FillModeNonSolid = VkBool32.ConvertFrom(features.fillModeNonSolid), DepthBounds = VkBool32.ConvertFrom(features.depthBounds), WideLines = VkBool32.ConvertFrom(features.wideLines), LargePoints = VkBool32.ConvertFrom(features.largePoints), AlphaToOne = VkBool32.ConvertFrom(features.alphaToOne), MultiViewport = VkBool32.ConvertFrom(features.multiViewport), SamplerAnisotropy = VkBool32.ConvertFrom(features.samplerAnisotropy), TextureCompressionETC2 = VkBool32.ConvertFrom(features.textureCompressionETC2), TextureCompressionASTC_LDR = VkBool32.ConvertFrom(features.textureCompressionASTC_LDR), TextureCompressionBC = VkBool32.ConvertFrom(features.textureCompressionBC), OcclusionQueryPrecise = VkBool32.ConvertFrom(features.occlusionQueryPrecise), PipelineStatisticsQuery = VkBool32.ConvertFrom(features.pipelineStatisticsQuery), VertexPipelineStoresAndAtomics = VkBool32.ConvertFrom(features.vertexPipelineStoresAndAtomics), FragmentStoresAndAtomics = VkBool32.ConvertFrom(features.fragmentStoresAndAtomics), ShaderTessellationAndGeometryPointSize = VkBool32.ConvertFrom(features.shaderTessellationAndGeometryPointSize), ShaderImageGatherExtended = VkBool32.ConvertFrom(features.shaderImageGatherExtended), ShaderStorageImageExtendedFormats = VkBool32.ConvertFrom(features.shaderStorageImageExtendedFormats), ShaderStorageImageMultisample = VkBool32.ConvertFrom(features.shaderStorageImageMultisample), ShaderStorageImageReadWithoutFormat = VkBool32.ConvertFrom(features.shaderStorageImageReadWithoutFormat), ShaderStorageImageWriteWithoutFormat = VkBool32.ConvertFrom(features.shaderStorageImageWriteWithoutFormat), ShaderUniformBufferArrayDynamicIndexing = VkBool32.ConvertFrom(features.shaderUniformBufferArrayDynamicIndexing), ShaderSampledImageArrayDynamicIndexing = VkBool32.ConvertFrom(features.shaderSampledImageArrayDynamicIndexing), ShaderStorageBufferArrayDynamicIndexing = VkBool32.ConvertFrom(features.shaderStorageBufferArrayDynamicIndexing), ShaderStorageImageArrayDynamicIndexing = VkBool32.ConvertFrom(features.shaderStorageImageArrayDynamicIndexing), ShaderClipDistance = VkBool32.ConvertFrom(features.shaderClipDistance), ShaderCullDistance = VkBool32.ConvertFrom(features.shaderCullDistance), ShaderFloat64 = VkBool32.ConvertFrom(features.shaderFloat64), ShaderInt64 = VkBool32.ConvertFrom(features.shaderInt64), ShaderInt16 = VkBool32.ConvertFrom(features.shaderInt16), ShaderResourceResidency = VkBool32.ConvertFrom(features.shaderResourceResidency), ShaderResourceMinLod = VkBool32.ConvertFrom(features.shaderResourceMinLod), SparseBinding = VkBool32.ConvertFrom(features.sparseBinding), SparseResidencyBuffer = VkBool32.ConvertFrom(features.sparseResidencyBuffer), SparseResidencyImage2D = VkBool32.ConvertFrom(features.sparseResidencyImage2D), SparseResidencyImage3D = VkBool32.ConvertFrom(features.sparseResidencyImage3D), SparseResidency2Samples = VkBool32.ConvertFrom(features.sparseResidency2Samples), SparseResidency4Samples = VkBool32.ConvertFrom(features.sparseResidency4Samples), SparseResidency8Samples = VkBool32.ConvertFrom(features.sparseResidency8Samples), SparseResidency16Samples = VkBool32.ConvertFrom(features.sparseResidency16Samples), SparseResidencyAliased = VkBool32.ConvertFrom(features.sparseResidencyAliased), VariableMultisampleRate = VkBool32.ConvertFrom(features.variableMultisampleRate), InheritedQueries = VkBool32.ConvertFrom(features.inheritedQueries), }; } public void GetPhysicalDeviceFormatProperties(MgFormat format, out MgFormatProperties pFormatProperties) { var formatProperties = default(VkFormatProperties); Interops.vkGetPhysicalDeviceFormatProperties(Handle, (VkFormat)format, ref formatProperties); pFormatProperties = new MgFormatProperties { Format = format, LinearTilingFeatures = (MgFormatFeatureFlagBits)formatProperties.linearTilingFeatures, OptimalTilingFeatures = (MgFormatFeatureFlagBits)formatProperties.optimalTilingFeatures, BufferFeatures = (MgFormatFeatureFlagBits)formatProperties.bufferFeatures, }; } public Result GetPhysicalDeviceImageFormatProperties(MgFormat format, MgImageType type, MgImageTiling tiling, MgImageUsageFlagBits usage, MgImageCreateFlagBits flags, out MgImageFormatProperties pImageFormatProperties) { var bFormat = (VkFormat)format; var bType = (VkImageType)type; var bUsage = (VkImageUsageFlags)usage; var bTiling = (VkImageTiling)tiling; var bFlags = (VkImageCreateFlags)flags; var properties = default(VkImageFormatProperties); var result = Interops.vkGetPhysicalDeviceImageFormatProperties ( Handle, bFormat, bType, bTiling, bUsage, bFlags, ref properties ); pImageFormatProperties = new MgImageFormatProperties { MaxExtent = properties.maxExtent, MaxMipLevels = properties.maxMipLevels, MaxArrayLayers = properties.maxArrayLayers, SampleCounts = (MgSampleCountFlagBits)properties.sampleCounts, MaxResourceSize = properties.maxResourceSize, }; return result; } /// <summary> /// /// </summary> /// <param name="pCreateInfo"></param> /// <param name="allocator"></param> /// <param name="pDevice"></param> /// <returns></returns> public Result CreateDevice(MgDeviceCreateInfo pCreateInfo, IMgAllocationCallbacks allocator, out IMgDevice pDevice) { if (pCreateInfo == null) throw new ArgumentNullException(nameof(pCreateInfo)); var allocatorPtr = GetAllocatorHandle(allocator); var attachedItems = new List<IntPtr>(); try { var queueCreateInfoCount = 0U; var pQueueCreateInfos = IntPtr.Zero; if (pCreateInfo.QueueCreateInfos != null) { queueCreateInfoCount = (uint)pCreateInfo.QueueCreateInfos.Length; if (queueCreateInfoCount > 0) { pQueueCreateInfos = GenerateQueueCreateInfos(attachedItems, pCreateInfo.QueueCreateInfos); } } var enabledExtensionCount = 0U; var ppEnabledExtensionNames = VkInteropsUtility.CopyStringArrays(attachedItems, pCreateInfo.EnabledExtensionNames, out enabledExtensionCount); var pEnabledFeatures = GenerateEnabledFeatures(attachedItems, pCreateInfo.EnabledFeatures); var internalHandle = IntPtr.Zero; var createInfo = new VkDeviceCreateInfo { sType = VkStructureType.StructureTypeDeviceCreateInfo, pNext = IntPtr.Zero, flags = pCreateInfo.Flags, queueCreateInfoCount = queueCreateInfoCount, pQueueCreateInfos = pQueueCreateInfos, // https://www.khronos.org/registry/vulkan/specs/1.0-wsi_extensions/xhtml/vkspec.html#extended-functionality-device-layer-deprecation ppEnabledLayerNames = IntPtr.Zero, enabledLayerCount = 0U, enabledExtensionCount = enabledExtensionCount, ppEnabledExtensionNames = ppEnabledExtensionNames, pEnabledFeatures = pEnabledFeatures, }; var result = Interops.vkCreateDevice(Handle, ref createInfo, allocatorPtr, ref internalHandle); pDevice = new VkDevice(internalHandle); return result; } finally { foreach (var item in attachedItems) { Marshal.FreeHGlobal(item); } } } IntPtr GenerateEnabledFeatures(List<IntPtr> attachedItems, MgPhysicalDeviceFeatures enabledFeatures) { if (enabledFeatures == null) return IntPtr.Zero; var dataItem = new VkPhysicalDeviceFeatures { robustBufferAccess = VkBool32.ConvertTo(enabledFeatures.RobustBufferAccess), fullDrawIndexUint32 = VkBool32.ConvertTo(enabledFeatures.FullDrawIndexUint32), imageCubeArray = VkBool32.ConvertTo(enabledFeatures.ImageCubeArray), independentBlend = VkBool32.ConvertTo(enabledFeatures.IndependentBlend), geometryShader = VkBool32.ConvertTo(enabledFeatures.GeometryShader), tessellationShader = VkBool32.ConvertTo(enabledFeatures.TessellationShader), sampleRateShading = VkBool32.ConvertTo(enabledFeatures.SampleRateShading), dualSrcBlend = VkBool32.ConvertTo(enabledFeatures.DualSrcBlend), logicOp = VkBool32.ConvertTo(enabledFeatures.LogicOp), multiDrawIndirect = VkBool32.ConvertTo(enabledFeatures.MultiDrawIndirect), drawIndirectFirstInstance = VkBool32.ConvertTo(enabledFeatures.DrawIndirectFirstInstance), depthClamp = VkBool32.ConvertTo(enabledFeatures.DepthClamp), depthBiasClamp = VkBool32.ConvertTo(enabledFeatures.DepthBiasClamp), fillModeNonSolid = VkBool32.ConvertTo(enabledFeatures.FillModeNonSolid), depthBounds = VkBool32.ConvertTo(enabledFeatures.DepthBounds), wideLines = VkBool32.ConvertTo(enabledFeatures.WideLines), largePoints = VkBool32.ConvertTo(enabledFeatures.LargePoints), alphaToOne = VkBool32.ConvertTo(enabledFeatures.AlphaToOne), multiViewport = VkBool32.ConvertTo(enabledFeatures.MultiViewport), samplerAnisotropy = VkBool32.ConvertTo(enabledFeatures.SamplerAnisotropy), textureCompressionETC2 = VkBool32.ConvertTo(enabledFeatures.TextureCompressionETC2), textureCompressionASTC_LDR = VkBool32.ConvertTo(enabledFeatures.TextureCompressionASTC_LDR), textureCompressionBC = VkBool32.ConvertTo(enabledFeatures.TextureCompressionBC), occlusionQueryPrecise = VkBool32.ConvertTo(enabledFeatures.OcclusionQueryPrecise), pipelineStatisticsQuery = VkBool32.ConvertTo(enabledFeatures.PipelineStatisticsQuery), vertexPipelineStoresAndAtomics = VkBool32.ConvertTo(enabledFeatures.VertexPipelineStoresAndAtomics), fragmentStoresAndAtomics = VkBool32.ConvertTo(enabledFeatures.FragmentStoresAndAtomics), shaderTessellationAndGeometryPointSize = VkBool32.ConvertTo(enabledFeatures.ShaderTessellationAndGeometryPointSize), shaderImageGatherExtended = VkBool32.ConvertTo(enabledFeatures.ShaderImageGatherExtended), shaderStorageImageExtendedFormats = VkBool32.ConvertTo(enabledFeatures.ShaderStorageImageExtendedFormats), shaderStorageImageMultisample = VkBool32.ConvertTo(enabledFeatures.ShaderStorageImageMultisample), shaderStorageImageReadWithoutFormat = VkBool32.ConvertTo(enabledFeatures.ShaderStorageImageReadWithoutFormat), shaderStorageImageWriteWithoutFormat = VkBool32.ConvertTo(enabledFeatures.ShaderStorageImageWriteWithoutFormat), shaderUniformBufferArrayDynamicIndexing = VkBool32.ConvertTo(enabledFeatures.ShaderUniformBufferArrayDynamicIndexing), shaderSampledImageArrayDynamicIndexing = VkBool32.ConvertTo(enabledFeatures.ShaderSampledImageArrayDynamicIndexing), shaderStorageBufferArrayDynamicIndexing = VkBool32.ConvertTo(enabledFeatures.ShaderStorageBufferArrayDynamicIndexing), shaderStorageImageArrayDynamicIndexing = VkBool32.ConvertTo(enabledFeatures.ShaderStorageImageArrayDynamicIndexing), shaderClipDistance = VkBool32.ConvertTo(enabledFeatures.ShaderClipDistance), shaderCullDistance = VkBool32.ConvertTo(enabledFeatures.ShaderCullDistance), shaderFloat64 = VkBool32.ConvertTo(enabledFeatures.ShaderFloat64), shaderInt64 = VkBool32.ConvertTo(enabledFeatures.ShaderInt64), shaderInt16 = VkBool32.ConvertTo(enabledFeatures.ShaderInt16), shaderResourceResidency = VkBool32.ConvertTo(enabledFeatures.ShaderResourceResidency), shaderResourceMinLod = VkBool32.ConvertTo(enabledFeatures.ShaderResourceMinLod), sparseBinding = VkBool32.ConvertTo(enabledFeatures.SparseBinding), sparseResidencyBuffer = VkBool32.ConvertTo(enabledFeatures.SparseResidencyBuffer), sparseResidencyImage2D = VkBool32.ConvertTo(enabledFeatures.SparseResidencyImage2D), sparseResidencyImage3D = VkBool32.ConvertTo(enabledFeatures.SparseResidencyImage3D), sparseResidency2Samples = VkBool32.ConvertTo(enabledFeatures.SparseResidency2Samples), sparseResidency4Samples = VkBool32.ConvertTo(enabledFeatures.SparseResidency4Samples), sparseResidency8Samples = VkBool32.ConvertTo(enabledFeatures.SparseResidency8Samples), sparseResidency16Samples = VkBool32.ConvertTo(enabledFeatures.SparseResidency16Samples), sparseResidencyAliased = VkBool32.ConvertTo(enabledFeatures.SparseResidencyAliased), variableMultisampleRate = VkBool32.ConvertTo(enabledFeatures.VariableMultisampleRate), inheritedQueries = VkBool32.ConvertTo(enabledFeatures.InheritedQueries), }; { var structSize = Marshal.SizeOf(dataItem); var dest = Marshal.AllocHGlobal(structSize); attachedItems.Add(dest); Marshal.StructureToPtr(dataItem, dest, false); return dest; } } IntPtr GenerateQueueCreateInfos(List<IntPtr> attachedItems, MgDeviceQueueCreateInfo[] queueCreateInfos) { var pQueueCreateInfos = VkInteropsUtility.AllocateNestedHGlobalArray( attachedItems, queueCreateInfos, (items, qcr) => { var queueCount = qcr.QueueCount; Debug.Assert(qcr.QueuePriorities != null); int arrayLength = qcr.QueuePriorities.Length; Debug.Assert(qcr.QueueCount == arrayLength); var pQueuePriorities = Marshal.AllocHGlobal(sizeof(float) * arrayLength); items.Add(pQueuePriorities); Marshal.Copy(qcr.QueuePriorities, 0, pQueuePriorities, arrayLength); return new VkDeviceQueueCreateInfo { sType = VkStructureType.StructureTypeDeviceQueueCreateInfo, pNext = IntPtr.Zero, flags = qcr.Flags, queueFamilyIndex = qcr.QueueFamilyIndex, queueCount = qcr.QueueCount, pQueuePriorities = pQueuePriorities, }; }); attachedItems.Add(pQueueCreateInfos); return pQueueCreateInfos; } public Result EnumerateDeviceLayerProperties(out MgLayerProperties[] pProperties) { uint count = 0U; var first = Interops.vkEnumerateDeviceLayerProperties(Handle, ref count, null); if (first != Result.SUCCESS) { pProperties = null; return first; } var layers = new VkLayerProperties[count]; var final = Interops.vkEnumerateDeviceLayerProperties(Handle, ref count, layers); pProperties = new MgLayerProperties[count]; for (var i = 0; i < count; ++i) { pProperties[i] = new MgLayerProperties { LayerName = VkInteropsUtility.ByteArrayToTrimmedString(layers[i].layerName), SpecVersion = layers[i].specVersion, ImplementationVersion = layers[i].implementationVersion, Description = VkInteropsUtility.ByteArrayToTrimmedString(layers[i].description), }; } return final; } public Result EnumerateDeviceExtensionProperties(string layerName, out MgExtensionProperties[] pProperties) { var bLayerName = IntPtr.Zero; try { if (layerName != null) { bLayerName = VkInteropsUtility.NativeUtf8FromString(layerName); } uint count = 0; var first = Interops.vkEnumerateDeviceExtensionProperties(Handle, bLayerName, ref count, null); if (first != Result.SUCCESS) { pProperties = null; return first; } var extensions = new VkExtensionProperties[count]; var final = Interops.vkEnumerateDeviceExtensionProperties(Handle, bLayerName, ref count, extensions); pProperties = new MgExtensionProperties[count]; for (var i = 0; i < count; ++i) { pProperties[i] = new MgExtensionProperties { ExtensionName = VkInteropsUtility.ByteArrayToTrimmedString(extensions[i].extensionName), SpecVersion = extensions[i].specVersion, }; } return final; } finally { if (bLayerName != IntPtr.Zero) { Marshal.FreeHGlobal(bLayerName); } } } public void GetPhysicalDeviceSparseImageFormatProperties(MgFormat format, MgImageType type, MgSampleCountFlagBits samples, MgImageUsageFlagBits usage, MgImageTiling tiling, out MgSparseImageFormatProperties[] pProperties) { uint count = 0; var bFormat = (VkFormat) format; var bType = (VkImageType) type; var bSamples = (VkSampleCountFlags) samples; var bUsage = (VkImageUsageFlags) usage; var bTiling = (VkImageTiling) tiling; Interops.vkGetPhysicalDeviceSparseImageFormatProperties ( Handle, bFormat, bType, bSamples, bUsage, bTiling, ref count, null ); if (count == 0) { pProperties = new MgSparseImageFormatProperties[0]; return; } var formatProperties = new VkSparseImageFormatProperties[count]; Interops.vkGetPhysicalDeviceSparseImageFormatProperties ( Handle, bFormat, bType, bSamples, bUsage, bTiling, ref count, formatProperties ); pProperties = new MgSparseImageFormatProperties[count]; for (var i = 0; i < count; ++i) { pProperties[i] = new MgSparseImageFormatProperties { AspectMask = (MgImageAspectFlagBits)formatProperties[i].aspectMask, ImageGranularity = formatProperties[i].imageGranularity, Flags = (MgSparseImageFormatFlagBits)formatProperties[i].flags, }; } } public Result GetPhysicalDeviceDisplayPropertiesKHR(out MgDisplayPropertiesKHR[] pProperties) { uint count = 0; var first = Interops.vkGetPhysicalDeviceDisplayPropertiesKHR(Handle, ref count, null); if (first != Result.SUCCESS) { pProperties = null; return first; } var displayProperties = new VkDisplayPropertiesKHR[count]; var final = Interops.vkGetPhysicalDeviceDisplayPropertiesKHR(Handle, ref count, displayProperties); pProperties = new MgDisplayPropertiesKHR[count]; for (var i = 0; i < count; ++i) { var internalDisplay = new VkDisplayKHR(displayProperties[i].display); pProperties[i] = new MgDisplayPropertiesKHR { Display = internalDisplay, DisplayName = displayProperties[i].displayName, PhysicalDimensions = displayProperties[i].physicalDimensions, PhysicalResolution = displayProperties[i].physicalResolution, SupportedTransforms = (MgSurfaceTransformFlagBitsKHR)displayProperties[i].supportedTransforms, PlaneReorderPossible = VkBool32.ConvertFrom(displayProperties[i].planeReorderPossible), PersistentContent = VkBool32.ConvertFrom(displayProperties[i].persistentContent), }; } return final; } public Result GetPhysicalDeviceDisplayPlanePropertiesKHR(out MgDisplayPlanePropertiesKHR[] pProperties) { uint count = 0; var first = Interops.vkGetPhysicalDeviceDisplayPlanePropertiesKHR(Handle, ref count, null); if (first != Result.SUCCESS) { pProperties = null; return first; } var planeProperties = new VkDisplayPlanePropertiesKHR[count]; var final = Interops.vkGetPhysicalDeviceDisplayPlanePropertiesKHR(Handle, ref count, planeProperties); pProperties = new MgDisplayPlanePropertiesKHR[count]; for (var i = 0; i < count; ++i) { pProperties[i] = new MgDisplayPlanePropertiesKHR { CurrentDisplay = new VkDisplayKHR(planeProperties[i].currentDisplay), CurrentStackIndex = planeProperties[i].currentStackIndex, }; } return final; } public Result GetDisplayPlaneSupportedDisplaysKHR(UInt32 planeIndex, out IMgDisplayKHR[] pDisplays) { uint count = 0; var first = Interops.vkGetDisplayPlaneSupportedDisplaysKHR(Handle, planeIndex, ref count, null); if (first != Result.SUCCESS) { pDisplays = null; return first; } var supportedDisplays = new ulong[count]; var final = Interops.vkGetDisplayPlaneSupportedDisplaysKHR(Handle, planeIndex, ref count, supportedDisplays); pDisplays = new VkDisplayKHR[count]; for (var i = 0; i < count; ++i) { pDisplays[i] = new VkDisplayKHR(supportedDisplays[i]); } return final; } public Result GetDisplayModePropertiesKHR(IMgDisplayKHR display, out MgDisplayModePropertiesKHR[] pProperties) { if (display == null) throw new ArgumentNullException(nameof(display)); var bDisplay = (VkDisplayKHR)display; Debug.Assert(bDisplay != null); // MAYBE DUPLICATE CHECK uint count = 0; var first = Interops.vkGetDisplayModePropertiesKHR(Handle, bDisplay.Handle, ref count, null); if (first != Result.SUCCESS) { pProperties = null; return first; } var modeProperties = new VkDisplayModePropertiesKHR[count]; var final = Interops.vkGetDisplayModePropertiesKHR(Handle, bDisplay.Handle, ref count, modeProperties); pProperties = new MgDisplayModePropertiesKHR[count]; for (var i = 0; i < count; ++i) { pProperties[i] = new MgDisplayModePropertiesKHR { DisplayMode = new VkDisplayModeKHR(modeProperties[i].displayMode), Parameters = modeProperties[i].parameters, }; } return final; } public Result GetDisplayPlaneCapabilitiesKHR(IMgDisplayModeKHR mode, UInt32 planeIndex, out MgDisplayPlaneCapabilitiesKHR pCapabilities) { if (mode == null) throw new ArgumentNullException(nameof(mode)); var bMode = (VkDisplayModeKHR)mode; Debug.Assert(bMode != null); var capabilities = default(VkDisplayPlaneCapabilitiesKHR); var result = Interops.vkGetDisplayPlaneCapabilitiesKHR(Handle, bMode.Handle, planeIndex, ref capabilities); pCapabilities = new MgDisplayPlaneCapabilitiesKHR { SupportedAlpha = (MgDisplayPlaneAlphaFlagBitsKHR) capabilities.supportedAlpha, MinSrcPosition = capabilities.minSrcPosition, MaxSrcPosition = capabilities.maxSrcPosition, MinSrcExtent = capabilities.minSrcExtent, MaxSrcExtent = capabilities.maxSrcExtent, MinDstPosition = capabilities.minDstPosition, MaxDstPosition = capabilities.maxDstPosition, MinDstExtent = capabilities.minDstExtent, MaxDstExtent = capabilities.maxDstExtent, }; return result; } public Result GetPhysicalDeviceSurfaceSupportKHR(UInt32 queueFamilyIndex, IMgSurfaceKHR surface, ref bool pSupported) { if (surface == null) throw new ArgumentNullException(nameof(surface)); var bSurface = (VkSurfaceKHR)surface; Debug.Assert(bSurface != null); VkBool32 isSupported = default(VkBool32); var result = Interops.vkGetPhysicalDeviceSurfaceSupportKHR(Handle, queueFamilyIndex, bSurface.Handle, ref isSupported); pSupported = VkBool32.ConvertFrom(isSupported); return result; } public Result GetPhysicalDeviceSurfaceCapabilitiesKHR(IMgSurfaceKHR surface, out MgSurfaceCapabilitiesKHR pSurfaceCapabilities) { if (surface == null) throw new ArgumentNullException(nameof(surface)); var bSurface = (VkSurfaceKHR)surface; Debug.Assert(bSurface != null); var pCreateInfo = default(VkSurfaceCapabilitiesKHR); var result = Interops.vkGetPhysicalDeviceSurfaceCapabilitiesKHR(Handle, bSurface.Handle, ref pCreateInfo); pSurfaceCapabilities = new MgSurfaceCapabilitiesKHR { MinImageCount = pCreateInfo.minImageCount, MaxImageCount = pCreateInfo.maxImageCount, CurrentExtent = pCreateInfo.currentExtent, MinImageExtent = pCreateInfo.minImageExtent, MaxImageExtent = pCreateInfo.maxImageExtent, MaxImageArrayLayers = pCreateInfo.maxImageArrayLayers, SupportedTransforms = (MgSurfaceTransformFlagBitsKHR) pCreateInfo.supportedTransforms, CurrentTransform = (MgSurfaceTransformFlagBitsKHR) pCreateInfo.currentTransform, SupportedCompositeAlpha = (MgCompositeAlphaFlagBitsKHR) pCreateInfo.supportedCompositeAlpha, SupportedUsageFlags = (MgImageUsageFlagBits) pCreateInfo.supportedUsageFlags, }; return result; } public Result GetPhysicalDeviceSurfaceFormatsKHR(IMgSurfaceKHR surface, out MgSurfaceFormatKHR[] pSurfaceFormats) { if (surface == null) throw new ArgumentNullException(nameof(surface)); var bSurface = (VkSurfaceKHR)surface; Debug.Assert(bSurface != null); var count = 0U; var first = Interops.vkGetPhysicalDeviceSurfaceFormatsKHR(Handle, bSurface.Handle, ref count, null); if (first != Result.SUCCESS) { pSurfaceFormats = null; return first; } var surfaceFormats = new VkSurfaceFormatKHR[count]; var final = Interops.vkGetPhysicalDeviceSurfaceFormatsKHR(Handle, bSurface.Handle, ref count, surfaceFormats); pSurfaceFormats = new MgSurfaceFormatKHR[count]; for (var i = 0; i < count; ++i) { pSurfaceFormats[i] = new MgSurfaceFormatKHR { Format = (MgFormat)surfaceFormats[i].format, ColorSpace = (MgColorSpaceKHR)surfaceFormats[i].colorSpace, }; } return final; } public Result GetPhysicalDeviceSurfacePresentModesKHR(IMgSurfaceKHR surface, out MgPresentModeKHR[] pPresentModes) { if (surface == null) throw new ArgumentNullException(nameof(surface)); var bSurface = (VkSurfaceKHR)surface; Debug.Assert(bSurface != null); var count = 0U; var first = Interops.vkGetPhysicalDeviceSurfacePresentModesKHR(Handle, bSurface.Handle, ref count, null); if (first != Result.SUCCESS) { pPresentModes = null; return first; } var modes = new VkPresentModeKhr[count]; var final = Interops.vkGetPhysicalDeviceSurfacePresentModesKHR(Handle, bSurface.Handle, ref count, modes); pPresentModes = new MgPresentModeKHR[count]; for (var i = 0; i < count; ++i) { pPresentModes[i] = (MgPresentModeKHR)modes[i]; } return final; } public bool GetPhysicalDeviceWin32PresentationSupportKHR(UInt32 queueFamilyIndex) { var final = Interops.vkGetPhysicalDeviceWin32PresentationSupportKHR(Handle, queueFamilyIndex); return VkBool32.ConvertFrom(final); } public Result CreateDisplayModeKHR(IMgDisplayKHR display, MgDisplayModeCreateInfoKHR pCreateInfo, IMgAllocationCallbacks allocator, out IMgDisplayModeKHR pMode) { if (display == null) throw new ArgumentNullException(nameof(display)); if (pCreateInfo == null) throw new ArgumentNullException(nameof(pCreateInfo)); var bDisplay = (VkDisplayModeKHR)display; Debug.Assert(bDisplay != null); var allocatorPtr = GetAllocatorHandle(allocator); var createInfo = new VkDisplayModeCreateInfoKHR { sType = VkStructureType.StructureTypeDisplayModeCreateInfoKhr, pNext = IntPtr.Zero, flags = pCreateInfo.flags, parameters = pCreateInfo.parameters, }; var modeHandle = 0UL; var result = Interops.vkCreateDisplayModeKHR(this.Handle, bDisplay.Handle, ref createInfo, allocatorPtr, ref modeHandle); pMode = new VkDisplayModeKHR(modeHandle); return result; } } }
// 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; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO.Enumeration; using System.Threading; using System.Threading.Tasks; namespace System.IO { /// <devdoc> /// Listens to the system directory change notifications and /// raises events when a directory or file within a directory changes. /// </devdoc> public partial class FileSystemWatcher : Component, ISupportInitialize { // Filters collection private readonly NormalizedFilterCollection _filters = new NormalizedFilterCollection(); // Directory being monitored private string _directory; // The watch filter for the API call. private const NotifyFilters c_defaultNotifyFilters = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; private NotifyFilters _notifyFilters = c_defaultNotifyFilters; // Flag to watch subtree of this directory private bool _includeSubdirectories = false; // Flag to note whether we are attached to the thread pool and responding to changes private bool _enabled = false; // Are we in init? private bool _initializing = false; // Buffer size private uint _internalBufferSize = 8192; // Used for synchronization private bool _disposed; // Event handlers private FileSystemEventHandler _onChangedHandler = null; private FileSystemEventHandler _onCreatedHandler = null; private FileSystemEventHandler _onDeletedHandler = null; private RenamedEventHandler _onRenamedHandler = null; private ErrorEventHandler _onErrorHandler = null; private const int c_notifyFiltersValidMask = (int)(NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size); #if DEBUG static FileSystemWatcher() { int s_notifyFiltersValidMask = 0; foreach (int enumValue in Enum.GetValues(typeof(NotifyFilters))) s_notifyFiltersValidMask |= enumValue; Debug.Assert(c_notifyFiltersValidMask == s_notifyFiltersValidMask, "The NotifyFilters enum has changed. The c_notifyFiltersValidMask must be updated to reflect the values of the NotifyFilters enum."); } #endif /// <devdoc> /// Initializes a new instance of the <see cref='System.IO.FileSystemWatcher'/> class. /// </devdoc> public FileSystemWatcher() { _directory = string.Empty; } /// <devdoc> /// Initializes a new instance of the <see cref='System.IO.FileSystemWatcher'/> class, /// given the specified directory to monitor. /// </devdoc> public FileSystemWatcher(string path) { CheckPathValidity(path); _directory = path; } /// <devdoc> /// Initializes a new instance of the <see cref='System.IO.FileSystemWatcher'/> class, /// given the specified directory and type of files to monitor. /// </devdoc> public FileSystemWatcher(string path, string filter) { CheckPathValidity(path); _directory = path; Filter = filter ?? throw new ArgumentNullException(nameof(filter)); } /// <devdoc> /// Gets or sets the type of changes to watch for. /// </devdoc> public NotifyFilters NotifyFilter { get { return _notifyFilters; } set { if (((int)value & ~c_notifyFiltersValidMask) != 0) throw new ArgumentException(SR.Format(SR.InvalidEnumArgument, nameof(value), (int)value, nameof(NotifyFilters))); if (_notifyFilters != value) { _notifyFilters = value; Restart(); } } } public Collection<string> Filters => _filters; /// <devdoc> /// Gets or sets a value indicating whether the component is enabled. /// </devdoc> public bool EnableRaisingEvents { get { return _enabled; } set { if (_enabled == value) { return; } if (IsSuspended()) { _enabled = value; // Alert the Component to start watching for events when EndInit is called. } else { if (value) { StartRaisingEventsIfNotDisposed(); // will set _enabled to true once successfully started } else { StopRaisingEvents(); // will set _enabled to false } } } } /// <devdoc> /// Gets or sets the filter string, used to determine what files are monitored in a directory. /// </devdoc> public string Filter { get { return Filters.Count == 0 ? "*" : Filters[0]; } set { Filters.Clear(); Filters.Add(value); } } /// <devdoc> /// Gets or sets a value indicating whether subdirectories within the specified path should be monitored. /// </devdoc> public bool IncludeSubdirectories { get { return _includeSubdirectories; } set { if (_includeSubdirectories != value) { _includeSubdirectories = value; Restart(); } } } /// <devdoc> /// Gets or sets the size of the internal buffer. /// </devdoc> public int InternalBufferSize { get { return (int)_internalBufferSize; } set { if (_internalBufferSize != value) { if (value < 4096) { _internalBufferSize = 4096; } else { _internalBufferSize = (uint)value; } Restart(); } } } /// <summary>Allocates a buffer of the requested internal buffer size.</summary> /// <returns>The allocated buffer.</returns> private byte[] AllocateBuffer() { try { return new byte[_internalBufferSize]; } catch (OutOfMemoryException) { throw new OutOfMemoryException(SR.Format(SR.BufferSizeTooLarge, _internalBufferSize)); } } /// <devdoc> /// Gets or sets the path of the directory to watch. /// </devdoc> public string Path { get { return _directory; } set { value = (value == null) ? string.Empty : value; if (!string.Equals(_directory, value, PathInternal.StringComparison)) { if (value.Length == 0) throw new ArgumentException(SR.Format(SR.InvalidDirName, value), nameof(Path)); if (!Directory.Exists(value)) throw new ArgumentException(SR.Format(SR.InvalidDirName_NotExists, value), nameof(Path)); _directory = value; Restart(); } } } /// <devdoc> /// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> is changed. /// </devdoc> public event FileSystemEventHandler Changed { add { _onChangedHandler += value; } remove { _onChangedHandler -= value; } } /// <devdoc> /// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> is created. /// </devdoc> public event FileSystemEventHandler Created { add { _onCreatedHandler += value; } remove { _onCreatedHandler -= value; } } /// <devdoc> /// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> is deleted. /// </devdoc> public event FileSystemEventHandler Deleted { add { _onDeletedHandler += value; } remove { _onDeletedHandler -= value; } } /// <devdoc> /// Occurs when the internal buffer overflows. /// </devdoc> public event ErrorEventHandler Error { add { _onErrorHandler += value; } remove { _onErrorHandler -= value; } } /// <devdoc> /// Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> /// is renamed. /// </devdoc> public event RenamedEventHandler Renamed { add { _onRenamedHandler += value; } remove { _onRenamedHandler -= value; } } protected override void Dispose(bool disposing) { try { if (disposing) { //Stop raising events cleans up managed and //unmanaged resources. StopRaisingEvents(); // Clean up managed resources _onChangedHandler = null; _onCreatedHandler = null; _onDeletedHandler = null; _onRenamedHandler = null; _onErrorHandler = null; } else { FinalizeDispose(); } } finally { _disposed = true; base.Dispose(disposing); } } private static void CheckPathValidity(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); // Early check for directory parameter so that an exception can be thrown as early as possible. if (path.Length == 0) throw new ArgumentException(SR.Format(SR.InvalidDirName, path), nameof(path)); if (!Directory.Exists(path)) throw new ArgumentException(SR.Format(SR.InvalidDirName_NotExists, path), nameof(path)); } /// <summary> /// Sees if the name given matches the name filter we have. /// </summary> private bool MatchPattern(ReadOnlySpan<char> relativePath) { ReadOnlySpan<char> name = IO.Path.GetFileName(relativePath); if (name.Length == 0) return false; string[] filters = _filters.GetFilters(); if (filters.Length == 0) return true; foreach (string filter in filters) { if (FileSystemName.MatchesSimpleExpression(filter, name, ignoreCase: !PathInternal.IsCaseSensitive)) return true; } return false; } /// <summary> /// Raises the event to each handler in the list. /// </summary> private void NotifyInternalBufferOverflowEvent() { _onErrorHandler?.Invoke(this, new ErrorEventArgs( new InternalBufferOverflowException(SR.Format(SR.FSW_BufferOverflow, _directory)))); } /// <summary> /// Raises the event to each handler in the list. /// </summary> private void NotifyRenameEventArgs(WatcherChangeTypes action, ReadOnlySpan<char> name, ReadOnlySpan<char> oldName) { // filter if there's no handler or neither new name or old name match a specified pattern RenamedEventHandler handler = _onRenamedHandler; if (handler != null && (MatchPattern(name) || MatchPattern(oldName))) { handler(this, new RenamedEventArgs(action, _directory, name.IsEmpty ? null : name.ToString(), oldName.IsEmpty ? null : oldName.ToString())); } } private FileSystemEventHandler GetHandler(WatcherChangeTypes changeType) { switch (changeType) { case WatcherChangeTypes.Created: return _onCreatedHandler; case WatcherChangeTypes.Deleted: return _onDeletedHandler; case WatcherChangeTypes.Changed: return _onChangedHandler; } Debug.Fail("Unknown FileSystemEvent change type! Value: " + changeType); return null; } /// <summary> /// Raises the event to each handler in the list. /// </summary> private void NotifyFileSystemEventArgs(WatcherChangeTypes changeType, ReadOnlySpan<char> name) { FileSystemEventHandler handler = GetHandler(changeType); if (handler != null && MatchPattern(name.IsEmpty ? _directory : name)) { handler(this, new FileSystemEventArgs(changeType, _directory, name.IsEmpty ? null : name.ToString())); } } /// <summary> /// Raises the event to each handler in the list. /// </summary> private void NotifyFileSystemEventArgs(WatcherChangeTypes changeType, string name) { FileSystemEventHandler handler = GetHandler(changeType); if (handler != null && MatchPattern(string.IsNullOrEmpty(name) ? _directory : name)) { handler(this, new FileSystemEventArgs(changeType, _directory, name)); } } /// <devdoc> /// Raises the <see cref='System.IO.FileSystemWatcher.Changed'/> event. /// </devdoc> [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")] protected void OnChanged(FileSystemEventArgs e) { InvokeOn(e, _onChangedHandler); } /// <devdoc> /// Raises the <see cref='System.IO.FileSystemWatcher.Created'/> event. /// </devdoc> [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")] protected void OnCreated(FileSystemEventArgs e) { InvokeOn(e, _onCreatedHandler); } /// <devdoc> /// Raises the <see cref='System.IO.FileSystemWatcher.Deleted'/> event. /// </devdoc> [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")] protected void OnDeleted(FileSystemEventArgs e) { InvokeOn(e, _onDeletedHandler); } private void InvokeOn(FileSystemEventArgs e, FileSystemEventHandler handler) { if (handler != null) { ISynchronizeInvoke syncObj = SynchronizingObject; if (syncObj != null && syncObj.InvokeRequired) syncObj.BeginInvoke(handler, new object[] { this, e }); else handler(this, e); } } /// <devdoc> /// Raises the <see cref='System.IO.FileSystemWatcher.Error'/> event. /// </devdoc> [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")] protected void OnError(ErrorEventArgs e) { ErrorEventHandler handler = _onErrorHandler; if (handler != null) { ISynchronizeInvoke syncObj = SynchronizingObject; if (syncObj != null && syncObj.InvokeRequired) syncObj.BeginInvoke(handler, new object[] { this, e }); else handler(this, e); } } /// <devdoc> /// Raises the <see cref='System.IO.FileSystemWatcher.Renamed'/> event. /// </devdoc> [SuppressMessage("Microsoft.Security", "CA2109:ReviewVisibleEventHandlers", MessageId = "0#", Justification = "Changing from protected to private would be a breaking change")] protected void OnRenamed(RenamedEventArgs e) { RenamedEventHandler handler = _onRenamedHandler; if (handler != null) { ISynchronizeInvoke syncObj = SynchronizingObject; if (syncObj != null && syncObj.InvokeRequired) syncObj.BeginInvoke(handler, new object[] { this, e }); else handler(this, e); } } public WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType) => WaitForChanged(changeType, Timeout.Infinite); public WaitForChangedResult WaitForChanged(WatcherChangeTypes changeType, int timeout) { // The full framework implementation doesn't do any argument validation, so // none is done here, either. var tcs = new TaskCompletionSource<WaitForChangedResult>(); FileSystemEventHandler fseh = null; RenamedEventHandler reh = null; // Register the event handlers based on what events are desired. The full framework // doesn't register for the Error event, so this doesn't either. if ((changeType & (WatcherChangeTypes.Created | WatcherChangeTypes.Deleted | WatcherChangeTypes.Changed)) != 0) { fseh = (s, e) => { if ((e.ChangeType & changeType) != 0) { tcs.TrySetResult(new WaitForChangedResult(e.ChangeType, e.Name, oldName: null, timedOut: false)); } }; if ((changeType & WatcherChangeTypes.Created) != 0) Created += fseh; if ((changeType & WatcherChangeTypes.Deleted) != 0) Deleted += fseh; if ((changeType & WatcherChangeTypes.Changed) != 0) Changed += fseh; } if ((changeType & WatcherChangeTypes.Renamed) != 0) { reh = (s, e) => { if ((e.ChangeType & changeType) != 0) { tcs.TrySetResult(new WaitForChangedResult(e.ChangeType, e.Name, e.OldName, timedOut: false)); } }; Renamed += reh; } try { // Enable the FSW if it wasn't already. bool wasEnabled = EnableRaisingEvents; if (!wasEnabled) { EnableRaisingEvents = true; } // Block until an appropriate event arrives or until we timeout. Debug.Assert(EnableRaisingEvents, "Expected EnableRaisingEvents to be true"); tcs.Task.Wait(timeout); // Reset the enabled state to what it was. EnableRaisingEvents = wasEnabled; } finally { // Unregister the event handlers. if (reh != null) { Renamed -= reh; } if (fseh != null) { if ((changeType & WatcherChangeTypes.Changed) != 0) Changed -= fseh; if ((changeType & WatcherChangeTypes.Deleted) != 0) Deleted -= fseh; if ((changeType & WatcherChangeTypes.Created) != 0) Created -= fseh; } } // Return the results. return tcs.Task.IsCompletedSuccessfully ? tcs.Task.Result : WaitForChangedResult.TimedOutResult; } /// <devdoc> /// Stops and starts this object. /// </devdoc> /// <internalonly/> private void Restart() { if ((!IsSuspended()) && _enabled) { StopRaisingEvents(); StartRaisingEventsIfNotDisposed(); } } private void StartRaisingEventsIfNotDisposed() { //Cannot allocate the directoryHandle and the readBuffer if the object has been disposed; finalization has been suppressed. if (_disposed) throw new ObjectDisposedException(GetType().Name); StartRaisingEvents(); } public override ISite Site { get { return base.Site; } set { base.Site = value; // set EnableRaisingEvents to true at design time so the user // doesn't have to manually. if (Site != null && Site.DesignMode) EnableRaisingEvents = true; } } public ISynchronizeInvoke SynchronizingObject { get; set; } public void BeginInit() { bool oldEnabled = _enabled; StopRaisingEvents(); _enabled = oldEnabled; _initializing = true; } public void EndInit() { _initializing = false; // Start listening to events if _enabled was set to true at some point. if (_directory.Length != 0 && _enabled) StartRaisingEvents(); } private bool IsSuspended() { return _initializing || DesignMode; } private sealed class NormalizedFilterCollection : Collection<string> { internal NormalizedFilterCollection() : base(new ImmutableStringList()) { } protected override void InsertItem(int index, string item) { base.InsertItem(index, string.IsNullOrEmpty(item) || item == "*.*" ? "*" : item); } protected override void SetItem(int index, string item) { base.SetItem(index, string.IsNullOrEmpty(item) || item == "*.*" ? "*" : item); } internal string[] GetFilters() => ((ImmutableStringList)Items).Items; /// <summary> /// List that maintains its underlying data in an immutable array, such that the list /// will never modify an array returned from its Items property. This is to allow /// the array to be enumerated safely while another thread might be concurrently mutating /// the collection. /// </summary> private sealed class ImmutableStringList : IList<string> { public string[] Items = Array.Empty<string>(); public string this[int index] { get { string[] items = Items; if ((uint)index >= (uint)items.Length) { throw new ArgumentOutOfRangeException(nameof(index)); } return items[index]; } set { string[] clone = (string[])Items.Clone(); clone[index] = value; Items = clone; } } public int Count => Items.Length; public bool IsReadOnly => false; public void Add(string item) { // Collection<T> doesn't use this method. throw new NotSupportedException(); } public void Clear() => Items = Array.Empty<string>(); public bool Contains(string item) => Array.IndexOf(Items, item) != -1; public void CopyTo(string[] array, int arrayIndex) => Items.CopyTo(array, arrayIndex); public IEnumerator<string> GetEnumerator() => ((IEnumerable<string>)Items).GetEnumerator(); public int IndexOf(string item) => Array.IndexOf(Items, item); public void Insert(int index, string item) { string[] items = Items; string[] newItems = new string[items.Length + 1]; items.AsSpan(0, index).CopyTo(newItems); items.AsSpan(index).CopyTo(newItems.AsSpan(index + 1)); newItems[index] = item; Items = newItems; } public bool Remove(string item) { // Collection<T> doesn't use this method. throw new NotSupportedException(); } public void RemoveAt(int index) { string[] items = Items; string[] newItems = new string[items.Length - 1]; items.AsSpan(0, index).CopyTo(newItems); items.AsSpan(index + 1).CopyTo(newItems.AsSpan(index)); Items = newItems; } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.Data.Entity; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using PartsUnlimited.Areas.Admin; using PartsUnlimited.Models; using PartsUnlimited.Queries; using PartsUnlimited.Recommendations; using PartsUnlimited.Search; using PartsUnlimited.Security; using PartsUnlimited.Telemetry; using PartsUnlimited.WebsiteConfiguration; using System; namespace PartsUnlimited { public class Startup { public IConfiguration Configuration { get; private set; } public Startup(IHostingEnvironment env) { //Below code demonstrates usage of multiple configuration sources. For instance a setting say 'setting1' is found in both the registered sources, //then the later source will win. By this way a Local config can be overridden by a different setting while deployed remotely. var builder = new ConfigurationBuilder() .AddJsonFile("config.json") .AddEnvironmentVariables(); //All environment variables in the process's context flow in as configuration values. Configuration = builder.Build(); } public void ConfigureServices(IServiceCollection services) { //If this type is present - we're on mono var runningOnMono = Type.GetType("Mono.Runtime") != null; var sqlConnectionString = Configuration["Data:DefaultConnection:ConnectionString"]; var useInMemoryDatabase = string.IsNullOrWhiteSpace(sqlConnectionString); // Add EF services to the services container if (useInMemoryDatabase || runningOnMono) { services.AddEntityFramework() .AddInMemoryDatabase() .AddDbContext<PartsUnlimitedContext>(options => { options.UseInMemoryDatabase(); }); } else { services.AddEntityFramework() .AddSqlServer() .AddDbContext<PartsUnlimitedContext>(options => { options.UseSqlServer(sqlConnectionString); }); } // Add Identity services to the services container services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<PartsUnlimitedContext>() .AddDefaultTokenProviders(); // Configure admin policies services.AddAuthorization(auth => { auth.AddPolicy(AdminConstants.Role, authBuilder => { authBuilder.RequireClaim(AdminConstants.ManageStore.Name, AdminConstants.ManageStore.Allowed); }); }); // Add implementations services.AddSingleton<IMemoryCache, MemoryCache>(); services.AddScoped<IOrdersQuery, OrdersQuery>(); services.AddScoped<IRaincheckQuery, RaincheckQuery>(); services.AddSingleton<ITelemetryProvider, EmptyTelemetryProvider>(); services.AddScoped<IProductSearch, StringContainsProductSearch>(); services.AddSingleton<IProductsRepository, ProductsRepository>(s => { string databaseId = Configuration["Keys:DocumentDB:Database"]; string collectionId = Configuration["Keys:DocumentDB:Collection"]; string endpoint = Configuration["Keys:DocumentDB:Endpoint"]; string authKey = Configuration["Keys:DocumentDB:AuthKey"]; return new ProductsRepository(endpoint, authKey, databaseId, collectionId); }); SetupRecommendationService(services); services.AddScoped<IWebsiteOptions>(p => { var telemetry = p.GetRequiredService<ITelemetryProvider>(); return new ConfigurationWebsiteOptions(Configuration.GetSection("WebsiteOptions"), telemetry); }); services.AddScoped<IApplicationInsightsSettings>(p => { return new ConfigurationApplicationInsightsSettings(Configuration.GetSection("Keys:ApplicationInsights")); }); // Associate IPartsUnlimitedContext with context services.AddTransient<IPartsUnlimitedContext>(s => s.GetService<PartsUnlimitedContext>()); // We need access to these settings in a static extension method, so DI does not help us :( ContentDeliveryNetworkExtensions.Configuration = new ContentDeliveryNetworkConfiguration(Configuration.GetSection("CDN")); // Add MVC services to the services container services.AddMvc(); //Add all SignalR related services to IoC. services.AddSignalR(); //Add InMemoryCache services.AddSingleton<IMemoryCache, MemoryCache>(); // Add session related services. services.AddCaching(); services.AddSession(); } private void SetupRecommendationService(IServiceCollection services) { var azureMlConfig = new AzureMLFrequentlyBoughtTogetherConfig(Configuration.GetSection("Keys:AzureMLFrequentlyBoughtTogether")); // If keys are not available for Azure ML recommendation service, register an empty recommendation engine if (string.IsNullOrEmpty(azureMlConfig.AccountKey) || string.IsNullOrEmpty(azureMlConfig.ModelName)) { services.AddSingleton<IRecommendationEngine, EmptyRecommendationsEngine>(); } else { services.AddSingleton<IAzureMLAuthenticatedHttpClient, AzureMLAuthenticatedHttpClient>(); services.AddInstance<IAzureMLFrequentlyBoughtTogetherConfig>(azureMlConfig); services.AddScoped<IRecommendationEngine, AzureMLFrequentlyBoughtTogetherRecommendationEngine>(); } } //This method is invoked when KRE_ENV is 'Development' or is not defined //The allowed values are Development,Staging and Production public void ConfigureDevelopment(IApplicationBuilder app) { //Display custom error page in production when error occurs //During development use the ErrorPage middleware to display error information in the browser app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(DatabaseErrorPageExtensions.EnableAll); // Add the runtime information page that can be used by developers // to see what packages are used by the application // default path is: /runtimeinfo app.UseRuntimeInfoPage(); Configure(app); } //This method is invoked when KRE_ENV is 'Staging' //The allowed values are Development,Staging and Production public void ConfigureStaging(IApplicationBuilder app) { app.UseExceptionHandler("/Home/Error"); Configure(app); } //This method is invoked when KRE_ENV is 'Production' //The allowed values are Development,Staging and Production public void ConfigureProduction(IApplicationBuilder app) { app.UseExceptionHandler("/Home/Error"); Configure(app); } public void Configure(IApplicationBuilder app) { // Configure Session. app.UseSession(); //Configure SignalR app.UseSignalR(); // Add static files to the request pipeline app.UseStaticFiles(); // Add cookie-based authentication to the request pipeline app.UseIdentity(); // Add login providers (Microsoft/AzureAD/Google/etc). This must be done after `app.UseIdentity()` app.AddLoginProviders(new ConfigurationLoginProviders(Configuration.GetSection("Authentication"))); // Add MVC to the request pipeline app.UseMvc(routes => { routes.MapRoute( name: "areaRoute", template: "{area:exists}/{controller}/{action}", defaults: new { action = "Index" }); routes.MapRoute( name: "default", template: "{controller}/{action}/{id?}", defaults: new { controller = "Home", action = "Index" }); routes.MapRoute( name: "api", template: "{controller}/{id?}"); }); //Populates the PartsUnlimited sample data SampleData.InitializePartsUnlimitedDatabaseAsync(app.ApplicationServices).Wait(); } } }
using System; using System.Collections; using System.Drawing; using System.Drawing.Imaging; namespace DotNetNuke.Services.GeneratedImage.ImageQuantization { /// <summary> /// Quantize using an Octree /// </summary> public class OctreeQuantizer : Quantizer { /// <summary> /// Construct the octree quantizer /// </summary> /// <remarks> /// The Octree quantizer is a two pass algorithm. The initial pass sets up the octree, /// the second pass quantizes a color based on the nodes in the tree /// </remarks> /// <param name="maxColors">The maximum number of colors to return</param> /// <param name="maxColorBits">The number of significant bits</param> public OctreeQuantizer ( int maxColors , int maxColorBits ) : base ( false ) { if ( maxColors > 255 ) throw new ArgumentOutOfRangeException ( nameof(maxColors) , maxColors , "The number of colors should be less than 256" ) ; if ( ( maxColorBits < 1 ) | ( maxColorBits > 8 ) ) throw new ArgumentOutOfRangeException ( nameof(maxColorBits) , maxColorBits , "This should be between 1 and 8" ) ; // Construct the octree _octree = new Octree ( maxColorBits ) ; _maxColors = maxColors ; } /// <summary> /// Process the pixel in the first pass of the algorithm /// </summary> /// <param name="pixel">The pixel to quantize</param> /// <remarks> /// This function need only be overridden if your quantize algorithm needs two passes, /// such as an Octree quantizer. /// </remarks> protected override void InitialQuantizePixel ( Color32 pixel ) { // Add the color to the octree _octree.AddColor ( pixel ) ; } /// <summary> /// Override this to process the pixel in the second pass of the algorithm /// </summary> /// <param name="pixel">The pixel to quantize</param> /// <returns>The quantized value</returns> protected override byte QuantizePixel ( Color32 pixel ) { byte paletteIndex = (byte)_maxColors ; // The color at [_maxColors] is set to transparent // Get the palette index if this non-transparent if ( pixel.Alpha > 0 ) paletteIndex = (byte)_octree.GetPaletteIndex ( pixel ) ; return paletteIndex ; } /// <summary> /// Retrieve the palette for the quantized image /// </summary> /// <param name="original">Any old palette, this is overrwritten</param> /// <returns>The new color palette</returns> protected override ColorPalette GetPalette ( ColorPalette original ) { // First off convert the octree to _maxColors colors ArrayList palette = _octree.Palletize ( _maxColors - 1 ) ; // Then convert the palette based on those colors for ( int index = 0 ; index < palette.Count ; index++ ) original.Entries[index] = (Color)palette[index] ; // Add the transparent color original.Entries[_maxColors] = Color.FromArgb ( 0 , 0 , 0 , 0 ) ; return original ; } /// <summary> /// Stores the tree /// </summary> private Octree _octree ; /// <summary> /// Maximum allowed color depth /// </summary> private int _maxColors ; /// <summary> /// Class which does the actual quantization /// </summary> private class Octree { /// <summary> /// Construct the octree /// </summary> /// <param name="maxColorBits">The maximum number of significant bits in the image</param> public Octree ( int maxColorBits ) { _maxColorBits = maxColorBits ; _leafCount = 0 ; _reducibleNodes = new OctreeNode[9] ; _root = new OctreeNode ( 0 , _maxColorBits , this ) ; _previousColor = 0 ; _previousNode = null ; } /// <summary> /// Add a given color value to the octree /// </summary> /// <param name="pixel"></param> public void AddColor ( Color32 pixel ) { // Check if this request is for the same color as the last if ( _previousColor == pixel.ARGB ) { // If so, check if I have a previous node setup. This will only ocurr if the first color in the image // happens to be black, with an alpha component of zero. if ( null == _previousNode ) { _previousColor = pixel.ARGB ; _root.AddColor ( pixel , _maxColorBits , 0 , this ) ; } else // Just update the previous node _previousNode.Increment ( pixel ) ; } else { _previousColor = pixel.ARGB ; _root.AddColor ( pixel , _maxColorBits , 0 , this ) ; } } /// <summary> /// Reduce the depth of the tree /// </summary> public void Reduce() { int index; // Find the deepest level containing at least one reducible node for (index = _maxColorBits - 1; (index > 0) && (null == _reducibleNodes[index]); index--) ; // Reduce the node most recently added to the list at level 'index' OctreeNode node = _reducibleNodes[index]; _reducibleNodes[index] = node.NextReducible; // Decrement the leaf count after reducing the node _leafCount -= node.Reduce(); // And just in case I've reduced the last color to be added, and the next color to // be added is the same, invalidate the previousNode... _previousNode = null; } /// <summary> /// Get/Set the number of leaves in the tree /// </summary> public int Leaves { get { return _leafCount ; } set { _leafCount = value ; } } /// <summary> /// Return the array of reducible nodes /// </summary> protected OctreeNode[] ReducibleNodes { get { return _reducibleNodes ; } } /// <summary> /// Keep track of the previous node that was quantized /// </summary> /// <param name="node">The node last quantized</param> protected void TrackPrevious ( OctreeNode node ) { _previousNode = node ; } /// <summary> /// Convert the nodes in the octree to a palette with a maximum of colorCount colors /// </summary> /// <param name="colorCount">The maximum number of colors</param> /// <returns>An arraylist with the palettized colors</returns> public ArrayList Palletize ( int colorCount ) { while ( Leaves > colorCount ) Reduce ( ) ; // Now palettize the nodes ArrayList palette = new ArrayList ( Leaves ) ; int paletteIndex = 0 ; _root.ConstructPalette ( palette , ref paletteIndex ) ; // And return the palette return palette ; } /// <summary> /// Get the palette index for the passed color /// </summary> /// <param name="pixel"></param> /// <returns></returns> public int GetPaletteIndex ( Color32 pixel ) { return _root.GetPaletteIndex ( pixel , 0 ) ; } /// <summary> /// Mask used when getting the appropriate pixels for a given node /// </summary> private static readonly int[] mask = new int[8] { 0x80 , 0x40 , 0x20 , 0x10 , 0x08 , 0x04 , 0x02 , 0x01 } ; /// <summary> /// The root of the octree /// </summary> private OctreeNode _root ; /// <summary> /// Number of leaves in the tree /// </summary> private int _leafCount ; /// <summary> /// Array of reducible nodes /// </summary> private OctreeNode[] _reducibleNodes ; /// <summary> /// Maximum number of significant bits in the image /// </summary> private int _maxColorBits ; /// <summary> /// Store the last node quantized /// </summary> private OctreeNode _previousNode ; /// <summary> /// Cache the previous color quantized /// </summary> private int _previousColor ; /// <summary> /// Class which encapsulates each node in the tree /// </summary> protected class OctreeNode { /// <summary> /// Construct the node /// </summary> /// <param name="level">The level in the tree = 0 - 7</param> /// <param name="colorBits">The number of significant color bits in the image</param> /// <param name="octree">The tree to which this node belongs</param> public OctreeNode ( int level , int colorBits , Octree octree ) { // Construct the new node _leaf = ( level == colorBits ) ; _red = _green = _blue = 0 ; _pixelCount = 0 ; // If a leaf, increment the leaf count if ( _leaf ) { octree.Leaves++ ; _nextReducible = null ; _children = null ; } else { // Otherwise add this to the reducible nodes _nextReducible = octree.ReducibleNodes[level] ; octree.ReducibleNodes[level] = this ; _children = new OctreeNode[8] ; } } /// <summary> /// Add a color into the tree /// </summary> /// <param name="pixel">The color</param> /// <param name="colorBits">The number of significant color bits</param> /// <param name="level">The level in the tree</param> /// <param name="octree">The tree to which this node belongs</param> public void AddColor ( Color32 pixel , int colorBits , int level , Octree octree ) { // Update the color information if this is a leaf if ( _leaf ) { Increment ( pixel ) ; // Setup the previous node octree.TrackPrevious ( this ) ; } else { // Go to the next level down in the tree int shift = 7 - level ; int index = ( ( pixel.Red & mask[level] ) >> ( shift - 2 ) ) | ( ( pixel.Green & mask[level] ) >> ( shift - 1 ) ) | ( ( pixel.Blue & mask[level] ) >> ( shift ) ) ; OctreeNode child = _children[index] ; if ( null == child ) { // Create a new child node & store in the array child = new OctreeNode ( level + 1 , colorBits , octree ) ; _children[index] = child ; } // Add the color to the child node child.AddColor ( pixel , colorBits , level + 1 , octree ) ; } } /// <summary> /// Get/Set the next reducible node /// </summary> public OctreeNode NextReducible { get { return _nextReducible ; } set { _nextReducible = value ; } } /// <summary> /// Return the child nodes /// </summary> public OctreeNode[] Children { get { return _children ; } } /// <summary> /// Reduce this node by removing all of its children /// </summary> /// <returns>The number of leaves removed</returns> public int Reduce ( ) { _red = _green = _blue = 0 ; int children = 0 ; // Loop through all children and add their information to this node for ( int index = 0 ; index < 8 ; index++ ) { if ( null != _children[index] ) { _red += _children[index]._red ; _green += _children[index]._green ; _blue += _children[index]._blue ; _pixelCount += _children[index]._pixelCount ; ++children ; _children[index] = null ; } } // Now change this to a leaf node _leaf = true ; // Return the number of nodes to decrement the leaf count by return ( children - 1 ) ; } /// <summary> /// Traverse the tree, building up the color palette /// </summary> /// <param name="palette">The palette</param> /// <param name="paletteIndex">The current palette index</param> public void ConstructPalette ( ArrayList palette , ref int paletteIndex ) { if ( _leaf ) { // Consume the next palette index _paletteIndex = paletteIndex++ ; // And set the color of the palette entry palette.Add ( Color.FromArgb ( _red / _pixelCount , _green / _pixelCount , _blue / _pixelCount ) ) ; } else { // Loop through children looking for leaves for ( int index = 0 ; index < 8 ; index++ ) { if ( null != _children[index] ) _children[index].ConstructPalette ( palette , ref paletteIndex ) ; } } } /// <summary> /// Return the palette index for the passed color /// </summary> public int GetPaletteIndex ( Color32 pixel , int level ) { int paletteIndex = _paletteIndex ; if ( !_leaf ) { int shift = 7 - level ; int index = ( ( pixel.Red & mask[level] ) >> ( shift - 2 ) ) | ( ( pixel.Green & mask[level] ) >> ( shift - 1 ) ) | ( ( pixel.Blue & mask[level] ) >> ( shift ) ) ; if ( null != _children[index] ) paletteIndex = _children[index].GetPaletteIndex ( pixel , level + 1 ) ; else throw new Exception ( "Didn't expect this!" ) ; } return paletteIndex ; } /// <summary> /// Increment the pixel count and add to the color information /// </summary> public void Increment ( Color32 pixel ) { _pixelCount++ ; _red += pixel.Red ; _green += pixel.Green ; _blue += pixel.Blue ; } /// <summary> /// Flag indicating that this is a leaf node /// </summary> private bool _leaf ; /// <summary> /// Number of pixels in this node /// </summary> private int _pixelCount ; /// <summary> /// Red component /// </summary> private int _red ; /// <summary> /// Green Component /// </summary> private int _green ; /// <summary> /// Blue component /// </summary> private int _blue ; /// <summary> /// Pointers to any child nodes /// </summary> private OctreeNode[] _children ; /// <summary> /// Pointer to next reducible node /// </summary> private OctreeNode _nextReducible ; /// <summary> /// The index of this node in the palette /// </summary> private int _paletteIndex ; } } } }
// 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.Buffers; using System.IO; namespace System.Security.Cryptography { public abstract class HashAlgorithm : IDisposable, ICryptoTransform { private bool _disposed; protected int HashSizeValue; protected internal byte[] HashValue; protected int State = 0; protected HashAlgorithm() { } public static HashAlgorithm Create() => Create("System.Security.Cryptography.HashAlgorithm"); public static HashAlgorithm Create(string hashName) => throw new PlatformNotSupportedException(); public virtual int HashSize => HashSizeValue; public virtual byte[] Hash { get { if (_disposed) throw new ObjectDisposedException(null); if (State != 0) throw new CryptographicUnexpectedOperationException(SR.Cryptography_HashNotYetFinalized); return (byte[])HashValue?.Clone(); } } public byte[] ComputeHash(byte[] buffer) { if (_disposed) throw new ObjectDisposedException(null); if (buffer == null) throw new ArgumentNullException(nameof(buffer)); HashCore(buffer, 0, buffer.Length); return CaptureHashCodeAndReinitialize(); } public bool TryComputeHash(ReadOnlySpan<byte> source, Span<byte> destination, out int bytesWritten) { if (_disposed) { throw new ObjectDisposedException(null); } if (destination.Length < HashSizeValue/8) { bytesWritten = 0; return false; } HashCore(source); if (!TryHashFinal(destination, out bytesWritten)) { // The only reason for failure should be that the destination isn't long enough, // but we checked the size earlier. throw new InvalidOperationException(SR.InvalidOperation_IncorrectImplementation); } HashValue = null; Initialize(); return true; } public byte[] ComputeHash(byte[] buffer, int offset, int count) { if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0 || (count > buffer.Length)) throw new ArgumentException(SR.Argument_InvalidValue); if ((buffer.Length - count) < offset) throw new ArgumentException(SR.Argument_InvalidOffLen); if (_disposed) throw new ObjectDisposedException(null); HashCore(buffer, offset, count); return CaptureHashCodeAndReinitialize(); } public byte[] ComputeHash(Stream inputStream) { if (_disposed) throw new ObjectDisposedException(null); // Default the buffer size to 4K. byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0) { HashCore(buffer, 0, bytesRead); } return CaptureHashCodeAndReinitialize(); } private byte[] CaptureHashCodeAndReinitialize() { HashValue = HashFinal(); // Clone the hash value prior to invoking Initialize in case the user-defined Initialize // manipulates the array. byte[] tmp = (byte[])HashValue.Clone(); Initialize(); return tmp; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public void Clear() { (this as IDisposable).Dispose(); } protected virtual void Dispose(bool disposing) { if (disposing) { // Although we don't have any resources to dispose at this level, // we need to continue to throw ObjectDisposedExceptions from CalculateHash // for compatibility with the desktop framework. _disposed = true; } return; } // ICryptoTransform methods // We assume any HashAlgorithm can take input a byte at a time public virtual int InputBlockSize => 1; public virtual int OutputBlockSize => 1; public virtual bool CanTransformMultipleBlocks => true; public virtual bool CanReuseTransform => true; public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { ValidateTransformBlock(inputBuffer, inputOffset, inputCount); // Change the State value State = 1; HashCore(inputBuffer, inputOffset, inputCount); if ((outputBuffer != null) && ((inputBuffer != outputBuffer) || (inputOffset != outputOffset))) { // We let BlockCopy do the destination array validation Buffer.BlockCopy(inputBuffer, inputOffset, outputBuffer, outputOffset, inputCount); } return inputCount; } public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { ValidateTransformBlock(inputBuffer, inputOffset, inputCount); HashCore(inputBuffer, inputOffset, inputCount); HashValue = CaptureHashCodeAndReinitialize(); byte[] outputBytes; if (inputCount != 0) { outputBytes = new byte[inputCount]; Buffer.BlockCopy(inputBuffer, inputOffset, outputBytes, 0, inputCount); } else { outputBytes = Array.Empty<byte>(); } // Reset the State value State = 0; return outputBytes; } private void ValidateTransformBlock(byte[] inputBuffer, int inputOffset, int inputCount) { if (inputBuffer == null) throw new ArgumentNullException(nameof(inputBuffer)); if (inputOffset < 0) throw new ArgumentOutOfRangeException(nameof(inputOffset), SR.ArgumentOutOfRange_NeedNonNegNum); if (inputCount < 0 || inputCount > inputBuffer.Length) throw new ArgumentException(SR.Argument_InvalidValue); if ((inputBuffer.Length - inputCount) < inputOffset) throw new ArgumentException(SR.Argument_InvalidOffLen); if (_disposed) throw new ObjectDisposedException(null); } protected abstract void HashCore(byte[] array, int ibStart, int cbSize); protected abstract byte[] HashFinal(); public abstract void Initialize(); protected virtual void HashCore(ReadOnlySpan<byte> source) { byte[] array = ArrayPool<byte>.Shared.Rent(source.Length); try { source.CopyTo(array); HashCore(array, 0, source.Length); } finally { Array.Clear(array, 0, source.Length); ArrayPool<byte>.Shared.Return(array); } } protected virtual bool TryHashFinal(Span<byte> destination, out int bytesWritten) { int hashSizeInBytes = HashSizeValue / 8; if (destination.Length >= hashSizeInBytes) { byte[] final = HashFinal(); if (final.Length == hashSizeInBytes) { new ReadOnlySpan<byte>(final).CopyTo(destination); bytesWritten = final.Length; return true; } throw new InvalidOperationException(SR.InvalidOperation_IncorrectImplementation); } bytesWritten = 0; return false; } } }
namespace khovratovich_equihash_cs { using System; using System.Reflection; class pow_test { /* void TestEquihash(unsigned n, unsigned k, Seed seed) { Equihash equihash(n, k, seed); Proof p = equihash.FindProof(); p.Test(); } */ public static void TestEquihash(uint n, uint k, Seed seed) { Equihash equihash = new Equihash(n, k, seed); Proof p = equihash.FindProof(); p.Test(); } /* static void fatal(const char* error) { fprintf(stderr, "Error: %s\n", error); exit(1); } */ public static int fatal(string error) { Console.WriteLine($"Error: {error}"); return 1; } /* static void usage(const char* cmd) { printf("Usage: %s [-n N] [-k K] " "[-s S]\n", cmd); printf("Parameters:\n"); printf("\t-n N \t\tSets the tuple length of iterations to N\n"); printf("\t-k K\t\tSets the number of steps to K \n"); printf("\t-s S\t\tSets seed to S\n"); } */ public static void usage(string cmd) { Console.WriteLine($"Usage: {cmd} [-n N] [-k K] [-s S]"); Console.WriteLine("Parameters:\n"); Console.WriteLine("\t-n N \t\tSets the tuple length of iterations to N"); Console.WriteLine("\t-k K\t\tSets the number of steps to K"); Console.WriteLine("\t-s S\t\tSets seed to S"); } /* int main(int argc, char* argv[]) { uint32_t n = 0, k = 0; Seed seed; if (argc < 2) { usage(argv[0]); return 1; } / * parse options * / for (int i = 1; i < argc; i++) { const char* a = argv[i]; unsigned long input = 0; if (!strcmp(a, "-n")) { if (i < argc - 1) { i++; input = strtoul(argv[i], NULL, 10); if (input == 0 || input > 255) { fatal("bad numeric input for -n"); } n = input; continue; } else { fatal("missing -n argument"); } } else if (!strcmp(a, "-k")) { if (i < argc - 1) { i++; input = strtoul(argv[i], NULL, 10); if (input == 0 || input > 20) { fatal("bad numeric input for -k"); } k = input; continue; } else { fatal("missing -k argument"); } } if (!strcmp(a, "-s")) { if (i < argc - 1) { i++; input = strtoul(argv[i], NULL, 10); if (input == 0 || input > 0xFFFFFF) { fatal("bad numeric input for -s"); } seed = Seed(input); continue; } else { fatal("missing -s argument"); } } } printf("N:\t%" PRIu32 " \n", n); printf("K:\t%" PRIu32 " \n", k); printf("SEED: "); for (unsigned i = 0; i < SEED_LENGTH; ++i) { printf(" \t%" PRIu32 " ", seed[i]); } printf("\n"); printf("Memory:\t\t%" PRIu64 "KiB\n", ((((uint32_t)1) << (n / (k + 1))) * LIST_LENGTH * k * sizeof(uint32_t)) / (1 << 10)); TestEquihash(n, k, seed); return 0; } */ // try // equihash -n 120 -k 5 -s 3 static int Main(string[] argc) { uint n = 0, k = 0; Seed seed = new Seed(0); if (argc.Length < 6) { usage(Assembly.GetExecutingAssembly().GetName().Name); return 1; } /* parse options */ for (int i = 0; i < argc.Length; i++) { if (argc[i] == "-n") { if (i < argc.Length - 1) { i++; uint input; if (!uint.TryParse(argc[i], out input) || input == 0 || input > 255) { return fatal("bad numeric input for -n"); } n = input; continue; } else { return fatal("missing -n argument"); } } else if (argc[i] == "-k") { if (i < argc.Length - 1) { i++; uint input; if (!uint.TryParse(argc[i], out input) || input == 0 || input > 20) { fatal("bad numeric input for -k"); } k = input; continue; } else { fatal("missing -k argument"); } } if (argc[i] == "-s") { if (i < argc.Length - 1) { i++; uint input; if (!uint.TryParse(argc[i], out input) || input == 0 || input > 0xFFFFFF) { fatal("bad numeric input for -s"); } seed = new Seed(input); continue; } else { fatal("missing -s argument"); } } } Console.WriteLine($"N:\t{n}"); Console.WriteLine($"K:\t{k}"); Console.Write("SEED: "); for (int i = 0; i < Equihash.SEED_LENGTH; ++i) { Console.Write($" \t{seed[i]} "); } Console.WriteLine(); Console.WriteLine($"Memory:\t\t{((((uint)1) << (int)(n / (k + 1))) * Equihash.LIST_LENGTH * k * sizeof(uint)) / (1 << 10)}KiB"); TestEquihash(n, k, seed); return 0; } } }
namespace Nancy.Tests { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Bootstrapper; using FakeItEasy; using Hosting.Owin; using Hosting.Owin.Tests.Fakes; using Xunit; using BodyDelegate = System.Func<System.Func<System.ArraySegment<byte>, // data System.Action, // continuation bool>, // continuation will be invoked System.Action<System.Exception>, // onError System.Action, // on Complete System.Action>; // cancel using ResponseCallBack = System.Action<string, System.Collections.Generic.IDictionary<string, string>, System.Func<System.Func<System.ArraySegment<byte>, System.Action, bool>, System.Action<System.Exception>, System.Action, System.Action>>; public class NancyOwinHostFixture { private readonly NancyOwinHost host; private readonly ResponseCallBack fakeResponseCallback; private readonly Action<Exception> fakeErrorCallback; private readonly Dictionary<string, object> environment; private readonly INancyEngine fakeEngine; private readonly INancyBootstrapper fakeBootstrapper; public NancyOwinHostFixture() { this.fakeEngine = A.Fake<INancyEngine>(); this.fakeBootstrapper = A.Fake<INancyBootstrapper>(); A.CallTo(() => this.fakeBootstrapper.GetEngine()).Returns(this.fakeEngine); this.host = new NancyOwinHost(fakeBootstrapper); this.fakeResponseCallback = (status, headers, bodyDelegate) => { }; this.fakeErrorCallback = (ex) => { }; this.environment = new Dictionary<string, object>() { { "owin.RequestMethod", "GET" }, { "owin.RequestPath", "/test" }, { "owin.RequestPathBase", "/root" }, { "owin.RequestQueryString", "var=value" }, { "owin.RequestHeaders", new Dictionary<string, string> { { "Host", "testserver" } } }, { "owin.RequestBody", null }, { "owin.RequestScheme", "http" }, { "owin.Version", "1.0" } }; } [Fact] public void Should_throw_if_owin_version_is_incorrect() { this.environment["owin.Version"] = "1.2"; var result = Record.Exception( () => this.host.ProcessRequest(environment, fakeResponseCallback, fakeErrorCallback)); result.ShouldBeOfType(typeof(InvalidOperationException)); } [Fact] public void Should_immediately_invoke_nancy_if_no_request_body_delegate() { this.host.ProcessRequest(environment, fakeResponseCallback, fakeErrorCallback); A.CallTo(() => this.fakeEngine.HandleRequest(A<Request>.Ignored, A<Action<NancyContext>>.Ignored, A<Action<Exception>>.Ignored)).MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_invoke_request_body_delegate_if_one_exists() { var invoked = false; BodyDelegate bodyDelegate = (onNext, onError, onComplete) => { invoked = true; return () => { }; }; this.environment["owin.RequestBody"] = bodyDelegate; this.host.ProcessRequest(environment, fakeResponseCallback, fakeErrorCallback); invoked.ShouldBeTrue(); } [Fact] public void Should_invoke_nancy_on_request_body_delegate_oncomplete() { Action complete = null; BodyDelegate bodyDelegate = (onNext, onError, onComplete) => { complete = onComplete; return () => { }; }; this.environment["owin.RequestBody"] = bodyDelegate; this.host.ProcessRequest(environment, fakeResponseCallback, fakeErrorCallback); complete.Invoke(); A.CallTo(() => this.fakeEngine.HandleRequest(A<Request>.Ignored, A<Action<NancyContext>>.Ignored, A<Action<Exception>>.Ignored)).MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_invoke_error_callback_if_nancy_invoke_throws() { var called = false; A.CallTo(() => this.fakeEngine.HandleRequest(A<Request>.Ignored, A<Action<NancyContext>>.Ignored, A<Action<Exception>>.Ignored)).Throws(new NotSupportedException()); this.host.ProcessRequest(environment, fakeResponseCallback, (e) => called = true); called.ShouldBeTrue(); } [Fact] public void Should_invoke_response_delegate_when_nancy_returns() { var fakeResponse = new Response() { StatusCode = HttpStatusCode.OK }; var fakeContext = new NancyContext() { Response = fakeResponse }; this.SetupFakeNancyCompleteCallback(fakeContext); var called = false; ResponseCallBack callback = (status, headers, bodyDelegate) => called = true; this.host.ProcessRequest(environment, callback, fakeErrorCallback); called.ShouldBeTrue(); } [Fact] public void Should_invoke_view_delegate_to_get_response() { var called = false; var fakeResponse = new Response() { StatusCode = HttpStatusCode.OK, Contents = s => called = true }; var fakeContext = new NancyContext() { Response = fakeResponse }; this.SetupFakeNancyCompleteCallback(fakeContext); var fakeConsumer = new FakeConsumer(false); ResponseCallBack callback = (r, h, b) => fakeConsumer.InvokeBodyDelegate(b); this.host.ProcessRequest(environment, callback, fakeErrorCallback); called.ShouldBeTrue(); } [Fact] public void Should_set_return_code_in_response_callback() { var fakeResponse = new Response() { StatusCode = HttpStatusCode.OK, Contents = s => { } }; var fakeContext = new NancyContext() { Response = fakeResponse }; this.SetupFakeNancyCompleteCallback(fakeContext); string statusCode = ""; ResponseCallBack callback = (r, h, b) => statusCode = r; this.host.ProcessRequest(environment, callback, fakeErrorCallback); statusCode.ShouldEqual("200 OK"); } [Fact] public void Should_set_headers_in_response_callback() { var fakeResponse = new Response() { StatusCode = HttpStatusCode.OK, Headers = new Dictionary<string, string>() { { "TestHeader", "TestValue" } }, Contents = s => { } }; var fakeContext = new NancyContext() { Response = fakeResponse }; this.SetupFakeNancyCompleteCallback(fakeContext); IDictionary<string, string> headers = null; ResponseCallBack callback = (r, h, b) => headers = h; this.host.ProcessRequest(environment, callback, fakeErrorCallback); // 2 headers because the default content-type is text/html headers.Count.ShouldEqual(2); headers["Content-Type"].ShouldEqual("text/html"); headers["TestHeader"].ShouldEqual("TestValue"); } [Fact] public void Should_set_contenttype_in_response_callback() { var fakeResponse = new Response { StatusCode = HttpStatusCode.OK, ContentType = "text/html", Contents = s => { } }; var fakeContext = new NancyContext {Response = fakeResponse}; SetupFakeNancyCompleteCallback(fakeContext); IDictionary<string, string> headers = null; ResponseCallBack callback = (r, h, b) => headers = h; host.ProcessRequest(environment, callback, fakeErrorCallback); headers.Count.ShouldEqual(1); headers["Content-Type"].ShouldEqual("text/html"); } [Fact] public void Should_send_null_continuation() { var fakeResponse = new Response() { StatusCode = HttpStatusCode.OK, Contents = s => s.WriteByte(12) }; var fakeContext = new NancyContext() { Response = fakeResponse }; this.SetupFakeNancyCompleteCallback(fakeContext); var fakeConsumer = new FakeConsumer(false); ResponseCallBack callback = (r, h, b) => fakeConsumer.InvokeBodyDelegate(b); this.host.ProcessRequest(environment, callback, fakeErrorCallback); fakeConsumer.ContinuationSent.ShouldBeFalse(); } [Fact] public void Should_send_entire_body() { var data1 = Encoding.ASCII.GetBytes("Some content"); var data2 = Encoding.ASCII.GetBytes("Some more content"); var fakeResponse = new Response() { StatusCode = HttpStatusCode.OK, Contents = s => { s.Write(data1, 0, data1.Length); s.Write(data2, 0, data2.Length); } }; var fakeContext = new NancyContext() { Response = fakeResponse }; this.SetupFakeNancyCompleteCallback(fakeContext); var fakeConsumer = new FakeConsumer(false); ResponseCallBack callback = (r, h, b) => fakeConsumer.InvokeBodyDelegate(b); this.host.ProcessRequest(environment, callback, fakeErrorCallback); fakeConsumer.ConsumedData.SequenceEqual(data1.Concat(data2)).ShouldBeTrue(); } [Fact] public void Should_dispose_context_on_completion_of_body_delegate() { var data1 = Encoding.ASCII.GetBytes("Some content"); var fakeResponse = new Response() { StatusCode = HttpStatusCode.OK, Contents = s => s.Write(data1, 0, data1.Length) }; var fakeContext = new NancyContext() { Response = fakeResponse }; var mockDisposable = A.Fake<IDisposable>(); fakeContext.Items.Add("Test", mockDisposable); this.SetupFakeNancyCompleteCallback(fakeContext); var fakeConsumer = new FakeConsumer(false); ResponseCallBack callback = (r, h, b) => fakeConsumer.InvokeBodyDelegate(b); this.host.ProcessRequest(environment, callback, fakeErrorCallback); A.CallTo(() => mockDisposable.Dispose()).MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_dispose_context_if_body_delegate_throws() { var fakeResponse = new Response() { StatusCode = HttpStatusCode.OK, Contents = s => { throw new InvalidOperationException(); } }; var fakeContext = new NancyContext() { Response = fakeResponse }; var mockDisposable = A.Fake<IDisposable>(); fakeContext.Items.Add("Test", mockDisposable); this.SetupFakeNancyCompleteCallback(fakeContext); var fakeConsumer = new FakeConsumer(false); ResponseCallBack callback = (r, h, b) => fakeConsumer.InvokeBodyDelegate(b); this.host.ProcessRequest(environment, callback, fakeErrorCallback); A.CallTo(() => mockDisposable.Dispose()).MustHaveHappened(Repeated.Exactly.Once); } [Fact] public void Should_read_entire_request_body_when_theres_no_continuation() { var requestBody = Encoding.ASCII.GetBytes("This is some request body content"); var fakeRequestBodyDelegate = new FakeProducer(false, requestBody, 5, false); this.environment["owin.RequestBody"] = (BodyDelegate)fakeRequestBodyDelegate; Request request = null; A.CallTo(() => this.fakeEngine.HandleRequest(A<Request>.Ignored, A<Action<NancyContext>>.Ignored, A<Action<Exception>>.Ignored)) .Invokes(i => request = (Request)i.Arguments[0]); this.host.ProcessRequest(environment, fakeResponseCallback, fakeErrorCallback); fakeRequestBodyDelegate.SendAll(); var read = new StreamReader(request.Body); var output = read.ReadToEnd(); output.ShouldEqual("This is some request body content"); } [Fact] public void Should_read_entire_request_body_when_there_is_a_continuation() { var requestBody = Encoding.ASCII.GetBytes("This is some request body content"); var fakeRequestBodyDelegate = new FakeProducer(true, requestBody, 5, false); this.environment["owin.RequestBody"] = (BodyDelegate)fakeRequestBodyDelegate; Request request = null; A.CallTo(() => this.fakeEngine.HandleRequest(A<Request>.Ignored, A<Action<NancyContext>>.Ignored, A<Action<Exception>>.Ignored)) .Invokes(i => request = (Request)i.Arguments[0]); this.host.ProcessRequest(environment, fakeResponseCallback, fakeErrorCallback); fakeRequestBodyDelegate.SendAll(); var read = new StreamReader(request.Body); var output = read.ReadToEnd(); output.ShouldEqual("This is some request body content"); } [Fact] public void Should_set_cookie_with_valid_header() { var fakeResponse = new Response() { StatusCode = HttpStatusCode.OK }; fakeResponse.AddCookie("test", "testvalue"); fakeResponse.AddCookie("test1", "testvalue1"); var fakeContext = new NancyContext() { Response = fakeResponse }; this.SetupFakeNancyCompleteCallback(fakeContext); var respHeaders = new Dictionary<string, string>(); ResponseCallBack callback = (status, headers, bodyDelegate) =>respHeaders=(Dictionary<string,string>)headers; this.host.ProcessRequest(environment, callback, fakeErrorCallback); respHeaders.ContainsKey("Set-Cookie").ShouldBeTrue(); (respHeaders["Set-Cookie"] == "test=testvalue; path=/\r\ntest1=testvalue1; path=/").ShouldBeTrue(); } /// <summary> /// Sets the fake nancy engine to execute the complete callback with the given context /// </summary> /// <param name="context">Context to return</param> private void SetupFakeNancyCompleteCallback(NancyContext context) { A.CallTo(() => this.fakeEngine.HandleRequest(A<Request>.Ignored, A<Action<NancyContext>>.Ignored, A<Action<Exception>>.Ignored)) .Invokes((i => ((Action<NancyContext>)i.Arguments[1]).Invoke(context))); } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * 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 OpenSim 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; using System.Collections.Generic; using System.IO; using System.Net; using System.Reflection; using System.Timers; using System.Threading.Tasks; using log4net; using log4net.Config; using Nini.Config; using OpenMetaverse; using OpenSim.Data; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Framework.Communications.Cache; using OpenSim.Framework.Console; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Framework.Statistics; using OpenSim.Grid.Framework; using OpenSim.Grid.UserServer.Modules; namespace OpenSim.Grid.UserServer { /// <summary> /// Grid user server main class /// </summary> public class OpenUser_Main : BaseOpenSimServer, IGridServiceCore { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected UserConfig Cfg; protected UserDataBaseService m_userDataBaseService; public UserManager m_userManager; protected UserServerAvatarAppearanceModule m_avatarAppearanceModule; protected UserServerFriendsModule m_friendsModule; public UserLoginService m_loginService; public MessageServersConnector m_messagesService; protected GridInfoServiceModule m_gridInfoService; protected UserServerCommandModule m_consoleCommandModule; protected UserServerEventDispatchModule m_eventDispatcher; protected InWorldz.RemoteAdmin.RemoteAdmin m_radmin; public static void Main(string[] args) { ServicePointManager.DefaultConnectionLimit = 12; PIDFileManager pidFile = new PIDFileManager(); XmlConfigurator.Configure(); m_log.Info("Launching UserServer..."); OpenUser_Main userserver = new OpenUser_Main(); pidFile.SetStatus(PIDFileManager.Status.Starting); userserver.Startup(); pidFile.SetStatus(PIDFileManager.Status.Running); userserver.Work(); } public OpenUser_Main() { m_console = new LocalConsole("User"); MainConsole.Instance = m_console; } public void Work() { m_console.Notice("Enter help for a list of commands\n"); while (true) { m_console.Prompt(); } } protected override void StartupSpecific() { StartupCoreComponents(); m_stats = StatsManager.StartCollectingUserStats(); //setup services/modules StartupUserServerModules(); StartOtherComponents(); //PostInitialise the modules PostInitialiseModules(); //register http handlers and start http server m_log.Info("[STARTUP]: Starting HTTP process"); RegisterHttpHandlers(); m_httpServer.Start(); base.StartupSpecific(); } protected virtual void StartupCoreComponents() { Cfg = new UserConfig("USER SERVER", (Path.Combine(Util.configDir(), "UserServer_Config.xml"))); m_httpServer = new BaseHttpServer(Cfg.HttpPort, null); RegisterInterface<CommandConsole>(m_console); RegisterInterface<UserConfig>(Cfg); IConfigSource defaultConfig = new IniConfigSource("Halcyon.ini"); IConfig startupConfig = defaultConfig.Configs["Startup"]; IConfig inventoryConfig = defaultConfig.Configs["Inventory"]; OpenSim.Framework.ConfigSettings settings = new ConfigSettings(); settings.InventoryPlugin = inventoryConfig.GetString("inventory_plugin"); settings.InventoryCluster = inventoryConfig.GetString("inventory_cluster"); settings.LegacyInventorySource = inventoryConfig.GetString("legacy_inventory_source"); settings.InventoryMigrationActive = inventoryConfig.GetBoolean("migration_active"); settings.LegacyInventorySource = inventoryConfig.GetString("legacy_inventory_source"); settings.CoreConnectionString = startupConfig.GetString("core_connection_string"); PluginLoader<IInventoryStoragePlugin> loader = new PluginLoader<IInventoryStoragePlugin>(); loader.Add("/OpenSim/InventoryStorage", new PluginProviderFilter(settings.InventoryPlugin)); loader.Load(); if (loader.Plugin != null) loader.Plugin.Initialize(settings); } /// <summary> /// Start up the user manager /// </summary> /// <param name="inventoryService"></param> protected virtual void StartupUserServerModules() { m_log.Info("[STARTUP]: Establishing data connection"); //we only need core components so we can request them from here IInterServiceInventoryServices inventoryService; TryGet<IInterServiceInventoryServices>(out inventoryService); CommunicationsManager commsManager = new UserServerCommsManager(); //setup database access service, for now this has to be created before the other modules. m_userDataBaseService = new UserDataBaseService(commsManager); m_userDataBaseService.Initialise(this); //TODO: change these modules so they fetch the databaseService class in the PostInitialise method m_userManager = new UserManager(m_userDataBaseService); m_userManager.Initialise(this); m_avatarAppearanceModule = new UserServerAvatarAppearanceModule(m_userDataBaseService); m_avatarAppearanceModule.Initialise(this); m_friendsModule = new UserServerFriendsModule(m_userDataBaseService); m_friendsModule.Initialise(this); m_consoleCommandModule = new UserServerCommandModule(); m_consoleCommandModule.Initialise(this); m_messagesService = new MessageServersConnector(); m_messagesService.Initialise(this); m_gridInfoService = new GridInfoServiceModule(); m_gridInfoService.Initialise(this); } protected virtual void StartOtherComponents() { StartupLoginService(); // // Get the minimum defaultLevel to access to the grid // m_loginService.setloginlevel((int)Cfg.DefaultUserLevel); RegisterInterface<UserLoginService>(m_loginService); //TODO: should be done in the login service m_eventDispatcher = new UserServerEventDispatchModule(m_userManager, m_messagesService, m_loginService); m_eventDispatcher.Initialise(this); } /// <summary> /// Start up the login service /// </summary> /// <param name="inventoryService"></param> protected virtual void StartupLoginService() { m_loginService = new UserLoginService( m_userDataBaseService, new LibraryRootFolder(Cfg.LibraryXmlfile), Cfg.MapServerURI, Cfg, Cfg.DefaultStartupMsg, new RegionProfileServiceProxy()); //if (Cfg.EnableHGLogin) // m_loginAuthService = new UserLoginAuthService(m_userDataBaseService, inventoryService, new LibraryRootFolder(Cfg.LibraryXmlfile), // Cfg, Cfg.DefaultStartupMsg, new RegionProfileServiceProxy()); } protected virtual void PostInitialiseModules() { m_consoleCommandModule.PostInitialise(); //it will register its Console command handlers in here m_userDataBaseService.PostInitialise(); m_messagesService.PostInitialise(); m_eventDispatcher.PostInitialise(); //it will register event handlers in here m_gridInfoService.PostInitialise(); m_userManager.PostInitialise(); m_avatarAppearanceModule.PostInitialise(); m_friendsModule.PostInitialise(); } protected virtual void RegisterHttpHandlers() { m_loginService.RegisterHandlers(m_httpServer, true); m_userManager.RegisterHandlers(m_httpServer); m_friendsModule.RegisterHandlers(m_httpServer); m_avatarAppearanceModule.RegisterHandlers(m_httpServer); m_messagesService.RegisterHandlers(m_httpServer); m_gridInfoService.RegisterHandlers(m_httpServer); m_radmin = new InWorldz.RemoteAdmin.RemoteAdmin(); m_radmin.AddCommand("UserService", "Shutdown", UserServerShutdownHandler); m_radmin.AddHandler(m_httpServer); } public object UserServerShutdownHandler(IList args, IPEndPoint remoteClient) { m_radmin.CheckSessionValid(new UUID((string)args[0])); try { int delay = (int)args[1]; string message; if (delay > 0) message = "Server is going down in " + delay.ToString() + " second(s)."; else message = "Server is going down now."; m_log.DebugFormat("[RADMIN] Shutdown: {0}", message); // Perform shutdown if (delay > 0) System.Threading.Thread.Sleep(delay * 1000); // Do this on a new thread so the actual shutdown call returns successfully. Task.Factory.StartNew(() => Shutdown()); } catch (Exception e) { m_log.ErrorFormat("[RADMIN] Shutdown: failed: {0}", e.Message); m_log.DebugFormat("[RADMIN] Shutdown: failed: {0}", e.ToString()); throw e; } m_log.Info("[RADMIN]: Shutdown Administrator Request complete"); return true; } public override void ShutdownSpecific() { m_eventDispatcher.Close(); } #region IUGAIMCore protected Dictionary<Type, object> m_moduleInterfaces = new Dictionary<Type, object>(); /// <summary> /// Register an Module interface. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="iface"></param> public void RegisterInterface<T>(T iface) { lock (m_moduleInterfaces) { if (!m_moduleInterfaces.ContainsKey(typeof(T))) { m_moduleInterfaces.Add(typeof(T), iface); } } } public bool TryGet<T>(out T iface) { if (m_moduleInterfaces.ContainsKey(typeof(T))) { iface = (T)m_moduleInterfaces[typeof(T)]; return true; } iface = default(T); return false; } public T Get<T>() { return (T)m_moduleInterfaces[typeof(T)]; } public BaseHttpServer GetHttpServer() { return m_httpServer; } #endregion public void TestResponse(List<InventoryFolderBase> resp) { m_console.Notice("response got"); } } }
/* * MSR Tools - tools for mining software repositories * * Copyright (C) 2010 Semyon Kirnosenko */ using System; using System.Linq; using NUnit.Framework; using SharpTestsEx; using Rhino.Mocks; using MSR.Data.Entities.DSL.Mapping; namespace MSR.Data.Entities.DSL.Selection { [TestFixture] public class CodeBlockSelectionExpressionTest : BaseRepositoryTest { [Test] public void Should_select_codeblocks_for_modifications() { mappingDSL .AddCommit("1") .AddFile("file1").Modified() .Code(+100) .AddFile("file2").Modified() .Code(+50) .Submit() .AddCommit("2") .File("file1").Modified() .Code(+10) .Code(-5) .Submit(); selectionDSL .Files().PathIs("file1") .Modifications().InFiles() .CodeBlocks().InModifications() .Select(x => x.Size).ToArray() .Should().Have.SameSequenceAs(new double[] { 100, 10, -5 }); selectionDSL .Files().PathIs("file2") .Modifications().InFiles() .CodeBlocks().InModifications() .Select(x => x.Size).ToArray() .Should().Have.SameSequenceAs(new double[] { 50 }); } [Test] public void Should_select_codeblocks_modified_by_specified_codeblocks() { mappingDSL .AddCommit("1") .AddFile("file1").Modified() .Code(+100) .AddFile("file2").Modified() .Code(+50) .Submit() .AddCommit("2") .File("file1").Modified() .Code(+10) .Code(-5).ForCodeAddedInitiallyInRevision("1") .Submit() .AddCommit("3") .File("file1").Modified() .Code(+20) .Code(-2).ForCodeAddedInitiallyInRevision("1") .Code(-3).ForCodeAddedInitiallyInRevision("2") .File("file2").Modified() .Code(-4).ForCodeAddedInitiallyInRevision("1") .Submit(); selectionDSL .Commits().RevisionIs("3") .Files().PathIs("file1") .Modifications().InCommits().InFiles() .CodeBlocks().InModifications().Modify() .Select(x => x.Size).ToArray() .Should().Have.SameSequenceAs(new double[] { 100, 10 }); selectionDSL .Commits().RevisionIs("1") .Modifications().InCommits() .CodeBlocks().InModifications().ModifiedBy() .Select(x => x.Size).ToArray() .Should().Have.SameSequenceAs(new double[] { -5, -2, -4 }); } [Test] public void Should_select_code_in_bugfixes() { mappingDSL .AddCommit("1") .AddFile("file1").Modified() .Code(100) .Submit() .AddCommit("2").IsBugFix() .File("file1").Modified() .Code(-5).ForCodeAddedInitiallyInRevision("1") .Code(5) .Submit() .AddCommit("3") .File("file1").Modified() .Code(-10).ForCodeAddedInitiallyInRevision("1") .Code(20) .Submit() .AddCommit("4").IsBugFix() .File("file1").Modified() .Code(-3) .Code(3) .Submit(); selectionDSL .CodeBlocks().InBugFixes() .Select(x => x.Size).ToArray() .Should().Have.SameSequenceAs(new double[] { -5, 5, -3, 3 }); selectionDSL .Commits().BeforeRevision("4") .BugFixes().InCommits() .CodeBlocks().InBugFixes() .Select(x => x.Size).ToArray() .Should().Have.SameSequenceAs(new double[] { -5, 5}); } [Test] public void Should_select_code_added_initially_in_commit() { mappingDSL .AddCommit("1") .AddFile("file1").Modified() .Code(100) .Submit() .AddCommit("2") .AddFile("file2").CopiedFrom("file1", "1").Modified() .CopyCode() .Submit(); selectionDSL .Commits().RevisionIs("1") .CodeBlocks().AddedInitiallyInCommits() .Select(x => x.Size).ToArray() .Should().Have.SameSequenceAs(new double[] { 100, 100 }); } [Test] public void Should_select_unique_modifications_that_contain_codeblocks() { mappingDSL .AddCommit("1") .AddFile("file1").Modified() .Code(100) .Submit() .AddCommit("2") .File("file1").Modified() .Code(-10) .Code(15) .Submit(); selectionDSL .CodeBlocks().Added() .Modifications().ContainCodeBlocks().Count() .Should().Be(2); selectionDSL .CodeBlocks().Deleted() .Modifications().ContainCodeBlocks().Count() .Should().Be(1); selectionDSL .Modifications().ContainCodeBlocks().Count() .Should().Be(2); } [Test] public void Should_select_refactoring_commits() { mappingDSL .AddCommit("1") .AddFile("file1").Modified() .Code(100) .Submit() .AddCommit("2") .File("file1").Modified() .Code(-10).ForCodeAddedInitiallyInRevision("1") .Code(10) .Submit() .AddCommit("3").IsBugFix() .File("file1").Modified() .Code(-5).ForCodeAddedInitiallyInRevision("1") .Code(10) .Submit() .AddCommit("4") .File("file1").Modified() .Code(-5).ForCodeAddedInitiallyInRevision("1") .Code(15) .Submit(); selectionDSL .Commits().AreRefactorings() .Select(c => c.Revision).ToArray() .Should().Have.SameValuesAs(new string[] { "2" }); } } }
/* * Infoplus API * * Infoplus API. * * OpenAPI spec version: v1.0 * Contact: api@infopluscommerce.com * Generated by: https://github.com/swagger-api/swagger-codegen.git * * 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.Collections.ObjectModel; using System.Linq; using RestSharp; using Infoplus.Client; using Infoplus.Model; namespace Infoplus.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IWarehouseApi : IApiAccessor { #region Synchronous Operations /// <summary> /// Search warehouses by filter /// </summary> /// <remarks> /// Returns the list of warehouses that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>List&lt;Warehouse&gt;</returns> List<Warehouse> GetWarehouseByFilter (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Search warehouses by filter /// </summary> /// <remarks> /// Returns the list of warehouses that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>ApiResponse of List&lt;Warehouse&gt;</returns> ApiResponse<List<Warehouse>> GetWarehouseByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Get a warehouse by id /// </summary> /// <remarks> /// Returns the warehouse identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="warehouseId">Id of the warehouse to be returned.</param> /// <returns>Warehouse</returns> Warehouse GetWarehouseById (int? warehouseId); /// <summary> /// Get a warehouse by id /// </summary> /// <remarks> /// Returns the warehouse identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="warehouseId">Id of the warehouse to be returned.</param> /// <returns>ApiResponse of Warehouse</returns> ApiResponse<Warehouse> GetWarehouseByIdWithHttpInfo (int? warehouseId); /// <summary> /// Update a warehouse /// </summary> /// <remarks> /// Updates an existing warehouse using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">Warehouse to be updated.</param> /// <returns></returns> void UpdateWarehouse (Warehouse body); /// <summary> /// Update a warehouse /// </summary> /// <remarks> /// Updates an existing warehouse using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">Warehouse to be updated.</param> /// <returns>ApiResponse of Object(void)</returns> ApiResponse<Object> UpdateWarehouseWithHttpInfo (Warehouse body); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// Search warehouses by filter /// </summary> /// <remarks> /// Returns the list of warehouses that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of List&lt;Warehouse&gt;</returns> System.Threading.Tasks.Task<List<Warehouse>> GetWarehouseByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Search warehouses by filter /// </summary> /// <remarks> /// Returns the list of warehouses that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of ApiResponse (List&lt;Warehouse&gt;)</returns> System.Threading.Tasks.Task<ApiResponse<List<Warehouse>>> GetWarehouseByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Get a warehouse by id /// </summary> /// <remarks> /// Returns the warehouse identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="warehouseId">Id of the warehouse to be returned.</param> /// <returns>Task of Warehouse</returns> System.Threading.Tasks.Task<Warehouse> GetWarehouseByIdAsync (int? warehouseId); /// <summary> /// Get a warehouse by id /// </summary> /// <remarks> /// Returns the warehouse identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="warehouseId">Id of the warehouse to be returned.</param> /// <returns>Task of ApiResponse (Warehouse)</returns> System.Threading.Tasks.Task<ApiResponse<Warehouse>> GetWarehouseByIdAsyncWithHttpInfo (int? warehouseId); /// <summary> /// Update a warehouse /// </summary> /// <remarks> /// Updates an existing warehouse using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">Warehouse to be updated.</param> /// <returns>Task of void</returns> System.Threading.Tasks.Task UpdateWarehouseAsync (Warehouse body); /// <summary> /// Update a warehouse /// </summary> /// <remarks> /// Updates an existing warehouse using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">Warehouse to be updated.</param> /// <returns>Task of ApiResponse</returns> System.Threading.Tasks.Task<ApiResponse<Object>> UpdateWarehouseAsyncWithHttpInfo (Warehouse body); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class WarehouseApi : IWarehouseApi { private Infoplus.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="WarehouseApi"/> class. /// </summary> /// <returns></returns> public WarehouseApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Initializes a new instance of the <see cref="WarehouseApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public WarehouseApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Configuration Configuration {get; set;} /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public Infoplus.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public Dictionary<String, String> DefaultHeader() { return this.Configuration.DefaultHeader; } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// Search warehouses by filter Returns the list of warehouses that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>List&lt;Warehouse&gt;</returns> public List<Warehouse> GetWarehouseByFilter (string filter = null, int? page = null, int? limit = null, string sort = null) { ApiResponse<List<Warehouse>> localVarResponse = GetWarehouseByFilterWithHttpInfo(filter, page, limit, sort); return localVarResponse.Data; } /// <summary> /// Search warehouses by filter Returns the list of warehouses that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>ApiResponse of List&lt;Warehouse&gt;</returns> public ApiResponse< List<Warehouse> > GetWarehouseByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null) { var localVarPath = "/v1.0/warehouse/search"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter if (sort != null) localVarQueryParams.Add("sort", Configuration.ApiClient.ParameterToString(sort)); // query parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetWarehouseByFilter", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<Warehouse>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<Warehouse>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<Warehouse>))); } /// <summary> /// Search warehouses by filter Returns the list of warehouses that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of List&lt;Warehouse&gt;</returns> public async System.Threading.Tasks.Task<List<Warehouse>> GetWarehouseByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null) { ApiResponse<List<Warehouse>> localVarResponse = await GetWarehouseByFilterAsyncWithHttpInfo(filter, page, limit, sort); return localVarResponse.Data; } /// <summary> /// Search warehouses by filter Returns the list of warehouses that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of ApiResponse (List&lt;Warehouse&gt;)</returns> public async System.Threading.Tasks.Task<ApiResponse<List<Warehouse>>> GetWarehouseByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null) { var localVarPath = "/v1.0/warehouse/search"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter if (sort != null) localVarQueryParams.Add("sort", Configuration.ApiClient.ParameterToString(sort)); // query parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetWarehouseByFilter", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<Warehouse>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<Warehouse>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<Warehouse>))); } /// <summary> /// Get a warehouse by id Returns the warehouse identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="warehouseId">Id of the warehouse to be returned.</param> /// <returns>Warehouse</returns> public Warehouse GetWarehouseById (int? warehouseId) { ApiResponse<Warehouse> localVarResponse = GetWarehouseByIdWithHttpInfo(warehouseId); return localVarResponse.Data; } /// <summary> /// Get a warehouse by id Returns the warehouse identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="warehouseId">Id of the warehouse to be returned.</param> /// <returns>ApiResponse of Warehouse</returns> public ApiResponse< Warehouse > GetWarehouseByIdWithHttpInfo (int? warehouseId) { // verify the required parameter 'warehouseId' is set if (warehouseId == null) throw new ApiException(400, "Missing required parameter 'warehouseId' when calling WarehouseApi->GetWarehouseById"); var localVarPath = "/v1.0/warehouse/{warehouseId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (warehouseId != null) localVarPathParams.Add("warehouseId", Configuration.ApiClient.ParameterToString(warehouseId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetWarehouseById", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Warehouse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (Warehouse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Warehouse))); } /// <summary> /// Get a warehouse by id Returns the warehouse identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="warehouseId">Id of the warehouse to be returned.</param> /// <returns>Task of Warehouse</returns> public async System.Threading.Tasks.Task<Warehouse> GetWarehouseByIdAsync (int? warehouseId) { ApiResponse<Warehouse> localVarResponse = await GetWarehouseByIdAsyncWithHttpInfo(warehouseId); return localVarResponse.Data; } /// <summary> /// Get a warehouse by id Returns the warehouse identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="warehouseId">Id of the warehouse to be returned.</param> /// <returns>Task of ApiResponse (Warehouse)</returns> public async System.Threading.Tasks.Task<ApiResponse<Warehouse>> GetWarehouseByIdAsyncWithHttpInfo (int? warehouseId) { // verify the required parameter 'warehouseId' is set if (warehouseId == null) throw new ApiException(400, "Missing required parameter 'warehouseId' when calling WarehouseApi->GetWarehouseById"); var localVarPath = "/v1.0/warehouse/{warehouseId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (warehouseId != null) localVarPathParams.Add("warehouseId", Configuration.ApiClient.ParameterToString(warehouseId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetWarehouseById", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Warehouse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (Warehouse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Warehouse))); } /// <summary> /// Update a warehouse Updates an existing warehouse using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">Warehouse to be updated.</param> /// <returns></returns> public void UpdateWarehouse (Warehouse body) { UpdateWarehouseWithHttpInfo(body); } /// <summary> /// Update a warehouse Updates an existing warehouse using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">Warehouse to be updated.</param> /// <returns>ApiResponse of Object(void)</returns> public ApiResponse<Object> UpdateWarehouseWithHttpInfo (Warehouse body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling WarehouseApi->UpdateWarehouse"); var localVarPath = "/v1.0/warehouse"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("UpdateWarehouse", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } /// <summary> /// Update a warehouse Updates an existing warehouse using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">Warehouse to be updated.</param> /// <returns>Task of void</returns> public async System.Threading.Tasks.Task UpdateWarehouseAsync (Warehouse body) { await UpdateWarehouseAsyncWithHttpInfo(body); } /// <summary> /// Update a warehouse Updates an existing warehouse using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">Warehouse to be updated.</param> /// <returns>Task of ApiResponse</returns> public async System.Threading.Tasks.Task<ApiResponse<Object>> UpdateWarehouseAsyncWithHttpInfo (Warehouse body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling WarehouseApi->UpdateWarehouse"); var localVarPath = "/v1.0/warehouse"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("UpdateWarehouse", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } } }
using System; using System.Collections; using System.Windows.Forms; using ChartDirector; namespace CSharpChartExplorer { public partial class FrmFinanceDemo : Form { public FrmFinanceDemo() { InitializeComponent(); } /// <summary> /// A utility class for adding items to ComboBox /// </summary> private class ListItem { string m_key; string m_value; public ListItem(string key, string val) { m_key = key; m_value = val; } public string Key { get { return m_key; } } public override string ToString() { return m_value; } } // The ticker symbol, timeStamps, volume, high, low, open and close data string tickerKey = ""; private DateTime[] timeStamps; private double[] volData; private double[] highData; private double[] lowData; private double[] openData; private double[] closeData; // An extra data series to compare with the close data private string compareKey = ""; private double[] compareData = null; // The resolution of the data in seconds. 1 day = 86400 seconds. private int resolution = 86400; // Will set to true at the end of initialization - prevents events from firing before the // controls are properly initialized. private bool hasFinishedInitialization = false; /// <summary> /// Form Load event handler - initialize the form /// </summary> private void FrmFinanceDemo_Load(object sender, System.EventArgs e) { hasFinishedInitialization = false; timeRange.Items.Add(new ListItem("1", "1 day")); timeRange.Items.Add(new ListItem("2", "2 days")); timeRange.Items.Add(new ListItem("5", "5 days")); timeRange.Items.Add(new ListItem("10", "10 days")); timeRange.Items.Add(new ListItem("30", "1 month")); timeRange.Items.Add(new ListItem("60", "2 months")); timeRange.Items.Add(new ListItem("90", "3 months")); timeRange.SelectedIndex = timeRange.Items.Add(new ListItem("180", "6 months")); timeRange.Items.Add(new ListItem("360", "1 year")); timeRange.Items.Add(new ListItem("720", "2 years")); timeRange.Items.Add(new ListItem("1080", "3 years")); timeRange.Items.Add(new ListItem("1440", "4 years")); timeRange.Items.Add(new ListItem("1800", "5 years")); timeRange.Items.Add(new ListItem("3600", "10 years")); chartSize.Items.Add(new ListItem("S", "Small")); chartSize.Items.Add(new ListItem("M", "Medium")); chartSize.SelectedIndex = chartSize.Items.Add(new ListItem("L", "Large")); chartSize.Items.Add(new ListItem("H", "Huge")); chartType.Items.Add(new ListItem("None", "None")); chartType.SelectedIndex = chartType.Items.Add(new ListItem("CandleStick", "CandleStick")); chartType.Items.Add(new ListItem("Close", "Closing Price")); chartType.Items.Add(new ListItem("Median", "Median Price")); chartType.Items.Add(new ListItem("OHLC", "OHLC")); chartType.Items.Add(new ListItem("TP", "Typical Price")); chartType.Items.Add(new ListItem("WC", "Weighted Close")); priceBand.Items.Add(new ListItem("None", "None")); priceBand.SelectedIndex = priceBand.Items.Add(new ListItem("BB", "Bollinger Band")); priceBand.Items.Add(new ListItem("DC", "Donchain Channel")); priceBand.Items.Add(new ListItem("Envelop", "Envelop (SMA 20 +/- 10%)")); avgType1.Items.Add(new ListItem("None", "None")); avgType1.SelectedIndex = avgType1.Items.Add(new ListItem("SMA", "Simple")); avgType1.Items.Add(new ListItem("EMA", "Exponential")); avgType1.Items.Add(new ListItem("TMA", "Triangular")); avgType1.Items.Add(new ListItem("WMA", "Weighted")); avgType2.Items.Add(new ListItem("None", "None")); avgType2.SelectedIndex = avgType2.Items.Add(new ListItem("SMA", "Simple")); avgType2.Items.Add(new ListItem("EMA", "Exponential")); avgType2.Items.Add(new ListItem("TMA", "Triangular")); avgType2.Items.Add(new ListItem("WMA", "Weighted")); ListItem[] indicators = { new ListItem("None", "None"), new ListItem("AccDist", "Accumulation/Distribution"), new ListItem("AroonOsc", "Aroon Oscillator"), new ListItem("Aroon", "Aroon Up/Down"), new ListItem("ADX", "Avg Directional Index"), new ListItem("ATR", "Avg True Range"), new ListItem("BBW", "Bollinger Band Width"), new ListItem("CMF", "Chaikin Money Flow"), new ListItem("COscillator", "Chaikin Oscillator"), new ListItem("CVolatility", "Chaikin Volatility"), new ListItem("CLV", "Close Location Value"), new ListItem("CCI", "Commodity Channel Index"), new ListItem("DPO", "Detrended Price Osc"), new ListItem("DCW", "Donchian Channel Width"), new ListItem("EMV", "Ease of Movement"), new ListItem("FStoch", "Fast Stochastic"), new ListItem("MACD", "MACD"), new ListItem("MDX", "Mass Index"), new ListItem("Momentum", "Momentum"), new ListItem("MFI", "Money Flow Index"), new ListItem("NVI", "Neg Volume Index"), new ListItem("OBV", "On Balance Volume"), new ListItem("Performance", "Performance"), new ListItem("PPO", "% Price Oscillator"), new ListItem("PVO", "% Volume Oscillator"), new ListItem("PVI", "Pos Volume Index"), new ListItem("PVT", "Price Volume Trend"), new ListItem("ROC", "Rate of Change"), new ListItem("RSI", "RSI"), new ListItem("SStoch", "Slow Stochastic"), new ListItem("StochRSI", "StochRSI"), new ListItem("TRIX", "TRIX"), new ListItem("UO", "Ultimate Oscillator"), new ListItem("Vol", "Volume"), new ListItem("WilliamR", "William's %R") }; indicator1.Items.AddRange(indicators); indicator2.Items.AddRange(indicators); indicator3.Items.AddRange(indicators); indicator4.Items.AddRange(indicators); for (int i = 0; i < indicators.Length; ++i) { if (indicators[i].Key == "RSI") indicator1.SelectedIndex = i; else if (indicators[i].Key == "MACD") indicator2.SelectedIndex = i; } indicator3.SelectedIndex = 0; indicator4.SelectedIndex = 0; hasFinishedInitialization = true; drawChart(winChartViewer1); } /// <summary> /// Get the timeStamps, highData, lowData, openData, closeData and volData. /// </summary> /// <param name="ticker">The ticker symbol for the data series.</param> /// <param name="startDate">The starting date/time for the data series.</param> /// <param name="endDate">The ending date/time for the data series.</param> /// <param name="durationInDays">The number of trading days to get.</param> /// <param name="extraPoints">The extra leading data points needed in order to /// compute moving averages.</param> /// <returns>True if successfully obtain the data, otherwise false.</returns> protected bool getData(string ticker, DateTime startDate, DateTime endDate, int durationInDays, int extraPoints) { // This method should return false if the ticker symbol is invalid. In this // sample code, as we are using a random number generator for the data, all // ticker symbol is allowed, but we still assumed an empty symbol is invalid. if (ticker == "") return false; // In this demo, we can get 15 min, daily, weekly or monthly data depending on // the time range. resolution = 86400; if (durationInDays <= 10) { // 10 days or less, we assume 15 minute data points are available resolution = 900; // We need to adjust the startDate backwards for the extraPoints. We assume // 6.5 hours trading time per day, and 5 trading days per week. double dataPointsPerDay = 6.5 * 3600 / resolution; DateTime adjustedStartDate = startDate.AddDays(-Math.Ceiling(extraPoints / dataPointsPerDay * 7 / 5) - 2); // Get the required 15 min data get15MinData(ticker, adjustedStartDate, endDate); } else if (durationInDays >= 4.5 * 360) { // 4 years or more - use monthly data points. resolution = 30 * 86400; // Adjust startDate backwards to cater for extraPoints DateTime adjustedStartDate = startDate.Date.AddMonths(-extraPoints); // Get the required monthly data getMonthlyData(ticker, adjustedStartDate, endDate); } else if (durationInDays >= 1.5 * 360) { // 1 year or more - use weekly points. resolution = 7 * 86400; // Adjust startDate backwards to cater for extraPoints DateTime adjustedStartDate = startDate.Date.AddDays(-extraPoints * 7 - 6); // Get the required weekly data getWeeklyData(ticker, adjustedStartDate, endDate); } else { // Default - use daily points resolution = 86400; // Adjust startDate backwards to cater for extraPoints. We multiply the days // by 7/5 as we assume 1 week has 5 trading days. DateTime adjustedStartDate = startDate.Date.AddDays(-Math.Ceiling(extraPoints * 7.0 / 5) - 2); // Get the required daily data getDailyData(ticker, adjustedStartDate, endDate); } return true; } /// <summary> /// Get 15 minutes data series for timeStamps, highData, lowData, openData, closeData /// and volData. /// </summary> /// <param name="ticker">The ticker symbol for the data series.</param> /// <param name="startDate">The starting date/time for the data series.</param> /// <param name="endDate">The ending date/time for the data series.</param> private void get15MinData(string ticker, DateTime startDate, DateTime endDate) { // //In this demo, we use a random number generator to generate the data. In practice, //you may get the data from a database or by other means. If you do not have 15 //minute data, you may modify the "drawChart" method below to not using 15 minute //data. // generateRandomData(ticker, startDate, endDate, 900); } /// <summary> /// Get daily data series for timeStamps, highData, lowData, openData, closeData /// and volData. /// </summary> /// <param name="ticker">The ticker symbol for the data series.</param> /// <param name="startDate">The starting date/time for the data series.</param> /// <param name="endDate">The ending date/time for the data series.</param> private void getDailyData(string ticker, DateTime startDate, DateTime endDate) { // //In this demo, we use a random number generator to generate the data. In practice, //you may get the data from a database or by other means. A typical database code //example is like below. (This only shows a general idea. The exact details may differ //depending on your database brand and schema. The SQL, in particular the date format, //may be different depending on which brand of database you use.) // // //Open the database connection to MS SQL // System.Data.IDbConnection dbconn = new System.Data.SqlClient.SqlConnection( // "..... put your database connection string here ......."); // dbconn.Open(); // // //SQL statement to get the data // System.Data.IDbCommand sqlCmd = dbconn.CreateCommand(); // sqlCmd.CommandText = "Select recordDate, highData, lowData, openData, " + // "closeData, volData From dailyFinanceTable Where ticker = '" + ticker + // "' And recordDate >= '" + startDate.ToString("yyyyMMdd") + "' And " + // "recordDate <= '" + endDate.ToString("yyyyMMdd") + "' Order By recordDate"; // // //The most convenient way to read the SQL result into arrays is to use the // //ChartDirector DBTable utility. // DBTable table = new DBTable(sqlCmd.ExecuteReader()); // dbconn.Close(); // // //Now get the data into arrays // timeStamps = table.getColAsDateTime(0); // highData = table.getCol(1); // lowData = table.getCol(2); // openData = table.getCol(3); // closeData = table.getCol(4); // volData = table.getCol(5); // generateRandomData(ticker, startDate, endDate, 86400); } /// <summary> /// Get weekly data series for timeStamps, highData, lowData, openData, closeData /// and volData. /// </summary> /// <param name="ticker">The ticker symbol for the data series.</param> /// <param name="startDate">The starting date/time for the data series.</param> /// <param name="endDate">The ending date/time for the data series.</param> private void getWeeklyData(string ticker, DateTime startDate, DateTime endDate) { // //In this demo, we use a random number generator to generate the data. In practice, //you may get the data from a database or by other means. If you do not have weekly //data, you may call "getDailyData" to get daily data first, and then call //"convertDailyToWeeklyData" to convert it to weekly data, like: // // getDailyData(startDate, endDate); // convertDailyToWeeklyData(); // generateRandomData(ticker, startDate, endDate, 86400 * 7); } /// <summary> /// Get monthly data series for timeStamps, highData, lowData, openData, closeData /// and volData. /// </summary> /// <param name="ticker">The ticker symbol for the data series.</param> /// <param name="startDate">The starting date/time for the data series.</param> /// <param name="endDate">The ending date/time for the data series.</param> private void getMonthlyData(string ticker, DateTime startDate, DateTime endDate) { // //In this demo, we use a random number generator to generate the data. In practice, //you may get the data from a database or by other means. If you do not have monthly //data, you may call "getDailyData" to get daily data first, and then call //"convertDailyToMonthlyData" to convert it to monthly data, like: // // getDailyData(startDate, endDate); // convertDailyToMonthlyData(); // generateRandomData(ticker, startDate, endDate, 86400 * 30); } /// <summary> /// A random number generator designed to generate realistic financial data. /// </summary> /// <param name="ticker">The ticker symbol for the data series.</param> /// <param name="startDate">The starting date/time for the data series.</param> /// <param name="endDate">The ending date/time for the data series.</param> /// <param name="resolution">The period of the data series.</param> private void generateRandomData(string ticker, DateTime startDate, DateTime endDate, int resolution) { FinanceSimulator db = new FinanceSimulator(ticker, startDate, endDate, resolution); timeStamps = db.getTimeStamps(); highData = db.getHighData(); lowData = db.getLowData(); openData = db.getOpenData(); closeData = db.getCloseData(); volData = db.getVolData(); } /// <summary> /// A utility to convert daily to weekly data. /// </summary> private void convertDailyToWeeklyData() { aggregateData(new ArrayMath(timeStamps).selectStartOfWeek()); } /// <summary> /// A utility to convert daily to monthly data. /// </summary> private void convertDailyToMonthlyData() { aggregateData(new ArrayMath(timeStamps).selectStartOfMonth()); } /// <summary> /// An internal method used to aggregate daily data. /// </summary> private void aggregateData(ArrayMath aggregator) { timeStamps = Chart.NTime(aggregator.aggregate(Chart.CTime(timeStamps), Chart.AggregateFirst)); highData = aggregator.aggregate(highData, Chart.AggregateMax); lowData = aggregator.aggregate(lowData, Chart.AggregateMin); openData = aggregator.aggregate(openData, Chart.AggregateFirst); closeData = aggregator.aggregate(closeData, Chart.AggregateLast); volData = aggregator.aggregate(volData, Chart.AggregateSum); } /// <summary> /// In this sample code, the chart updates when the user selection changes. You may /// modify the code to update the data and chart periodically for real time charts. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void selectionChanged(object sender, System.EventArgs e) { if (hasFinishedInitialization) drawChart(winChartViewer1); } /// /// For the ticker symbols, the chart will update when the user enters a new symbol, /// and then press the enter button or leave the text box. /// private void tickerSymbol_Leave(object sender, System.EventArgs e) { // User leave ticker symbol text box - redraw chart if symbol has changed if (tickerSymbol.Text != tickerKey) drawChart(winChartViewer1); } private void tickerSymbol_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { // User press enter key - same action as leaving the text box. if (e.KeyChar == '\r') tickerSymbol_Leave(sender, e); } private void compareWith_Leave(object sender, System.EventArgs e) { // User leave compare symbol text box - redraw chart if symbol has changed if (compareWith.Text != compareKey) drawChart(winChartViewer1); } private void compareWith_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { // User press enter key - same action as leaving the text box. if (e.KeyChar == '\r') compareWith_Leave(sender, e); } /// <summary> /// Draw the chart according to user selection and display it in the WinChartViewer. /// </summary> /// <param name="viewer">The WinChartViewer object to display the chart.</param> private void drawChart(WinChartViewer viewer) { // Use InvariantCulture to draw the chart. This ensures the chart will look the // same on any computer. System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture; // In this demo, we just assume we plot up to the latest time. So endDate is now. DateTime endDate = DateTime.Now; // If the trading day has not yet started (before 9:30am), or if the end date is // on on Sat or Sun, we set the end date to 4:00pm of the last trading day while ((endDate.TimeOfDay.CompareTo(new TimeSpan(9, 30, 0)) < 0) || ( endDate.DayOfWeek == DayOfWeek.Sunday) || (endDate.DayOfWeek == DayOfWeek.Saturday)) { endDate = endDate.Date.AddDays(-1).Add(new TimeSpan(16, 0, 0)); } // The duration selected by the user int durationInDays = int.Parse(((ListItem)timeRange.SelectedItem).Key); // Compute the start date by subtracting the duration from the end date. DateTime startDate; if (durationInDays >= 30) { // More or equal to 30 days - so we use months as the unit startDate = new DateTime(endDate.Year, endDate.Month, 1).AddMonths( -durationInDays / 30); } else { // Less than 30 days - use day as the unit. Note that we use trading days // below. For less than 30 days, the starting point of the axis is always at // the start of the day. startDate = endDate.Date; for (int i = 1; i < durationInDays; ++i) startDate = startDate.AddDays( (startDate.DayOfWeek == DayOfWeek.Monday) ? -3 : -1); } // The first moving average period selected by the user. int avgPeriod1; try { avgPeriod1 = int.Parse(movAvg1.Text); } catch { avgPeriod1 = 0; } avgPeriod1 = Math.Max(0, Math.Min(300, avgPeriod1)); // The second moving average period selected by the user. int avgPeriod2; try { avgPeriod2 = int.Parse(movAvg2.Text); } catch { avgPeriod2 = 0; } avgPeriod2 = Math.Max(0, Math.Min(300, avgPeriod2)); // We need extra leading data points in order to compute moving averages. int extraPoints = Math.Max(20, Math.Max(avgPeriod1, avgPeriod2)); // Get the data series to compare with, if any. compareKey = compareWith.Text.Trim(); compareData = null; if (getData(compareKey, startDate, endDate, durationInDays, extraPoints)) compareData = closeData; // The data series we want to get. tickerKey = tickerSymbol.Text.Trim(); if (!getData(tickerKey, startDate, endDate, durationInDays, extraPoints)) { errMsg(viewer, "Please enter a valid ticker symbol"); return; } // We now confirm the actual number of extra points (data points that are before // the start date) as inferred using actual data from the database. extraPoints = timeStamps.Length; for (int i = 0; i < timeStamps.Length; ++i) { if (timeStamps[i] >= startDate) { extraPoints = i; break; } } // Check if there is any valid data if (extraPoints >= timeStamps.Length) { // No data - just display the no data message. errMsg(viewer, "No data available for the specified time period"); return; } // In some finance chart presentation style, even if the data for the latest day // is not fully available, the axis for the entire day will still be drawn, where // no data will appear near the end of the axis. if (resolution < 86400) { // Add extra points to the axis until it reaches the end of the day. The end // of day is assumed to be 4:00pm (it depends on the stock exchange). DateTime lastTime = timeStamps[timeStamps.Length - 1]; int extraTrailingPoints = (int)(new TimeSpan(16, 0, 0).Subtract( lastTime.TimeOfDay).TotalSeconds / resolution); if (extraTrailingPoints > 0) { DateTime[] extendedTimeStamps = new DateTime[timeStamps.Length + extraTrailingPoints]; Array.Copy(timeStamps, 0, extendedTimeStamps, 0, timeStamps.Length); for (int i = 0; i < extraTrailingPoints; ++i) extendedTimeStamps[i + timeStamps.Length] = lastTime.AddSeconds( resolution * i); timeStamps = extendedTimeStamps; } } // // At this stage, all data is available. We can draw the chart as according to // user input. // // // Determine the chart size. In this demo, user can select 4 different chart // sizes. Default is the large chart size. // int width = 780; int mainHeight = 255; int indicatorHeight = 80; string selectedSize = ((ListItem)chartSize.SelectedItem).Key; if (selectedSize == "S") { // Small chart size width = 450; mainHeight = 160; indicatorHeight = 60; } else if (selectedSize == "M") { // Medium chart size width = 620; mainHeight = 215; indicatorHeight = 70; } else if (selectedSize == "H") { // Huge chart size width = 1000; mainHeight = 320; indicatorHeight = 90; } // Create the chart object using the selected size FinanceChart m = new FinanceChart(width); // Set the data into the chart object m.setData(timeStamps, highData, lowData, openData, closeData, volData, extraPoints); // // We configure the title of the chart. In this demo chart design, we put the // company name as the top line of the title with left alignment. // m.addPlotAreaTitle(Chart.TopLeft, tickerKey); // We displays the current date as well as the data resolution on the next line. string resolutionText = ""; if (resolution == 30 * 86400) resolutionText = "Monthly"; else if (resolution == 7 * 86400) resolutionText = "Weekly"; else if (resolution == 86400) resolutionText = "Daily"; else if (resolution == 900) resolutionText = "15-min"; m.addPlotAreaTitle(Chart.BottomLeft, "<*font=Arial,size=8*>" + m.formatValue( DateTime.Now, "mmm dd, yyyy") + " - " + resolutionText + " chart"); // A copyright message at the bottom left corner the title area m.addPlotAreaTitle(Chart.BottomRight, "<*font=arial.ttf,size=8*>(c) Advanced Software Engineering"); // // Add the first techical indicator according. In this demo, we draw the first // indicator on top of the main chart. // addIndicator(m, ((ListItem)indicator1.SelectedItem).Key, indicatorHeight); // // Add the main chart // m.addMainChart(mainHeight); // // Set log or linear scale according to user preference // m.setLogScale(logScale.Checked); // // Set axis labels to show data values or percentage change to user preference // if (percentageScale.Checked) m.setPercentageAxis(); // // Draw any price line the user has selected // string mainType = ((ListItem)chartType.SelectedItem).Key; if (mainType == "Close") m.addCloseLine(0x000040); else if (mainType == "TP") m.addTypicalPrice(0x000040); else if (mainType == "WC") m.addWeightedClose(0x000040); else if (mainType == "Median") m.addMedianPrice(0x000040); // // Add comparison line if there is data for comparison // if ((compareData != null) && (compareData.Length > extraPoints)) m.addComparison(compareData, 0x0000ff, compareKey); // // Add moving average lines. // addMovingAvg(m, ((ListItem)avgType1.SelectedItem).Key, avgPeriod1, 0x663300); addMovingAvg(m, ((ListItem)avgType2.SelectedItem).Key, avgPeriod2, 0x9900ff); // // Draw candlesticks or OHLC symbols if the user has selected them. // if (mainType == "CandleStick") m.addCandleStick(0x33ff33, 0xff3333); else if (mainType == "OHLC") m.addHLOC(0x008800, 0xcc0000); // // Add parabolic SAR if necessary // if (parabolicSAR.Checked) m.addParabolicSAR(0.02, 0.02, 0.2, Chart.DiamondShape, 5, 0x008800, 0x000000); // // Add price band/channel/envelop to the chart according to user selection // string selectedBand = ((ListItem)priceBand.SelectedItem).Key; if (selectedBand == "BB") m.addBollingerBand(20, 2, 0x9999ff, unchecked((int)(0xc06666ff))); else if (selectedBand == "DC") m.addDonchianChannel(20, 0x9999ff, unchecked((int)(0xc06666ff))); else if (selectedBand == "Envelop") m.addEnvelop(20, 0.1, 0x9999ff, unchecked((int)(0xc06666ff))); // // Add volume bars to the main chart if necessary // if (volumeBars.Checked) m.addVolBars(indicatorHeight, 0x99ff99, 0xff9999, 0xc0c0c0); // // Add additional indicators as according to user selection. // addIndicator(m, ((ListItem)indicator2.SelectedItem).Key, indicatorHeight); addIndicator(m, ((ListItem)indicator3.SelectedItem).Key, indicatorHeight); addIndicator(m, ((ListItem)indicator4.SelectedItem).Key, indicatorHeight); // // output the chart // viewer.Chart = m; // // tooltips for the chart // viewer.ImageMap = m.getHTMLImageMap("", "", "title='" + m.getToolTipDateFormat() + " {value|P}'"); } /// <summary> /// Add a moving average line to the FinanceChart object. /// </summary> /// <param name="m">The FinanceChart object to add the line to.</param> /// <param name="avgType">The moving average type (SMA/EMA/TMA/WMA).</param> /// <param name="avgPeriod">The moving average period.</param> /// <param name="color">The color of the line.</param> /// <returns>The LineLayer object representing line layer created.</returns> protected LineLayer addMovingAvg(FinanceChart m, string avgType, int avgPeriod, int color) { if (avgPeriod > 1) { if (avgType == "SMA") return m.addSimpleMovingAvg(avgPeriod, color); else if (avgType == "EMA") return m.addExpMovingAvg(avgPeriod, color); else if (avgType == "TMA") return m.addTriMovingAvg(avgPeriod, color); else if (avgType == "WMA") return m.addWeightedMovingAvg(avgPeriod, color); } return null; } /// <summary> /// Add an indicator chart to the FinanceChart object. In this demo example, the indicator /// parameters (such as the period used to compute RSI, colors of the lines, etc.) are hard /// coded to commonly used values. You are welcome to design a more complex user interface /// to allow users to set the parameters. /// </summary> /// <param name="m">The FinanceChart object to add the line to.</param> /// <param name="indicator">The selected indicator.</param> /// <param name="height">Height of the chart in pixels</param> /// <returns>The XYChart object representing indicator chart.</returns> protected XYChart addIndicator(FinanceChart m, string indicator, int height) { if (indicator == "RSI") return m.addRSI(height, 14, 0x800080, 20, 0xff6666, 0x6666ff); else if (indicator == "StochRSI") return m.addStochRSI(height, 14, 0x800080, 30, 0xff6666, 0x6666ff); else if (indicator == "MACD") return m.addMACD(height, 26, 12, 9, 0xff, 0xff00ff, 0x8000); else if (indicator == "FStoch") return m.addFastStochastic(height, 14, 3, 0x6060, 0x606000); else if (indicator == "SStoch") return m.addSlowStochastic(height, 14, 3, 0x6060, 0x606000); else if (indicator == "ATR") return m.addATR(height, 14, 0x808080, 0xff); else if (indicator == "ADX") return m.addADX(height, 14, 0x8000, 0x800000, 0x80); else if (indicator == "DCW") return m.addDonchianWidth(height, 20, 0xff); else if (indicator == "BBW") return m.addBollingerWidth(height, 20, 2, 0xff); else if (indicator == "DPO") return m.addDPO(height, 20, 0xff); else if (indicator == "PVT") return m.addPVT(height, 0xff); else if (indicator == "Momentum") return m.addMomentum(height, 12, 0xff); else if (indicator == "Performance") return m.addPerformance(height, 0xff); else if (indicator == "ROC") return m.addROC(height, 12, 0xff); else if (indicator == "OBV") return m.addOBV(height, 0xff); else if (indicator == "AccDist") return m.addAccDist(height, 0xff); else if (indicator == "CLV") return m.addCLV(height, 0xff); else if (indicator == "WilliamR") return m.addWilliamR(height, 14, 0x800080, 30, 0xff6666, 0x6666ff); else if (indicator == "Aroon") return m.addAroon(height, 14, 0x339933, 0x333399); else if (indicator == "AroonOsc") return m.addAroonOsc(height, 14, 0xff); else if (indicator == "CCI") return m.addCCI(height, 20, 0x800080, 100, 0xff6666, 0x6666ff); else if (indicator == "EMV") return m.addEaseOfMovement(height, 9, 0x6060, 0x606000); else if (indicator == "MDX") return m.addMassIndex(height, 0x800080, 0xff6666, 0x6666ff); else if (indicator == "CVolatility") return m.addChaikinVolatility(height, 10, 10, 0xff); else if (indicator == "COscillator") return m.addChaikinOscillator(height, 0xff); else if (indicator == "CMF") return m.addChaikinMoneyFlow(height, 21, 0x8000); else if (indicator == "NVI") return m.addNVI(height, 255, 0xff, 0x883333); else if (indicator == "PVI") return m.addPVI(height, 255, 0xff, 0x883333); else if (indicator == "MFI") return m.addMFI(height, 14, 0x800080, 30, 0xff6666, 0x6666ff); else if (indicator == "PVO") return m.addPVO(height, 26, 12, 9, 0xff, 0xff00ff, 0x8000); else if (indicator == "PPO") return m.addPPO(height, 26, 12, 9, 0xff, 0xff00ff, 0x8000); else if (indicator == "UO") return m.addUltimateOscillator(height, 7, 14, 28, 0x800080, 20, 0xff6666, 0x6666ff); else if (indicator == "Vol") return m.addVolIndicator(height, 0x99ff99, 0xff9999, 0xc0c0c0); else if (indicator == "TRIX") return m.addTRIX(height, 12, 0xff); return null; } /// <summary> /// Creates a dummy chart to show an error message. /// </summary> /// <param name="viewer">The WinChartViewer to display the error message.</param> /// <param name="msg">The error message</param> protected void errMsg(WinChartViewer viewer, string msg) { MultiChart m = new MultiChart(400, 200); m.addTitle2(Chart.Center, msg, "Arial", 10).setMaxWidth(m.getWidth()); viewer.Image = m.makeImage(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // // Licensed under the MIT License. See LICENSE.txt in the project root for license information. using Microsoft.Graphics.Canvas; using Microsoft.Graphics.Canvas.Brushes; using Microsoft.Graphics.Canvas.Effects; using Microsoft.Graphics.Canvas.Text; using Microsoft.Graphics.Canvas.UI.Xaml; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Numerics; using Windows.Foundation; using Windows.UI; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace ExampleGallery { public sealed partial class DpiExample : UserControl, INotifyPropertyChanged { public enum SourceMode { DrawingSession, DefaultDpiBitmap, HighDpiBitmap, LowDpiBitmap, } public enum IntermediateMode { None, AutoDpiRenderTarget, HighDpiRenderTarget, LowDpiRenderTarget, ImageEffect, CommandList, ImageEffectInCommandList } public enum OutputMode { CanvasControl, CanvasImageBrush, CanvasImageSource, CanvasSwapChain, CanvasAnimatedControl, } public SourceMode CurrentSource { get; set; } public IntermediateMode CurrentIntermediate { get; set; } public OutputMode CurrentOutput { get; set; } public List<SourceMode> SourceModeList { get { return Utils.GetEnumAsList<SourceMode>(); } } public List<IntermediateMode> IntermediateModeList { get { return Utils.GetEnumAsList<IntermediateMode>(); } } public List<OutputMode> OutputModeList { get { return Utils.GetEnumAsList<OutputMode>(); } } const float testSize = 128; const float testOffset = 20; const float controlSize = testSize + testOffset * 2; const float defaultDpi = 96; const float highDpi = 192; const float lowDpi = 48; // We need two copies of all these graphics resources, one for the main CanvasDevice used on the // UI thread, plus a second set for use by the CanvasAnimatedControl which runs on a separate thread. class PerDeviceResources { public readonly ICanvasResourceCreatorWithDpi ResourceCreator; public readonly CanvasBitmap DefaultDpiBitmap; public readonly CanvasBitmap HighDpiBitmap; public readonly CanvasBitmap LowDpiBitmap; public readonly CanvasRenderTarget AutoDpiRenderTarget; public readonly CanvasRenderTarget HighDpiRenderTarget; public readonly CanvasRenderTarget LowDpiRenderTarget; public readonly SaturationEffect SaturationEffect; public readonly CanvasTextFormat TextFormat = new CanvasTextFormat { VerticalAlignment = CanvasVerticalAlignment.Center, HorizontalAlignment = CanvasHorizontalAlignment.Center, }; string message; int drawCount; public PerDeviceResources(ICanvasResourceCreatorWithDpi resourceCreator) { ResourceCreator = resourceCreator; DefaultDpiBitmap = CreateTestBitmap(resourceCreator, defaultDpi); HighDpiBitmap = CreateTestBitmap(resourceCreator, highDpi); LowDpiBitmap = CreateTestBitmap(resourceCreator, lowDpi); AutoDpiRenderTarget = new CanvasRenderTarget(resourceCreator, testSize, testSize); HighDpiRenderTarget = new CanvasRenderTarget(resourceCreator, testSize, testSize, highDpi); LowDpiRenderTarget = new CanvasRenderTarget(resourceCreator, testSize, testSize, lowDpi); SaturationEffect = new SaturationEffect { Saturation = 0 }; } public void InitMessage() { message = "The test graphic should fit the yellow guide markers, regardless of display DPI or what drawing options are selected.\n\n"; } public void AddMessage(string format, params object[] args) { message += string.Format(format, args); } public string GetFinalMessage() { AddMessage("\n\nRedraw count: {0}", ++drawCount); return message; } } PerDeviceResources mainDeviceResources; PerDeviceResources animatedDeviceResources; CanvasImageBrush imageBrush; CanvasImageSource imageSource; CanvasSwapChain swapChain; DispatcherTimer cycleTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(0.25) }; public event PropertyChangedEventHandler PropertyChanged; public DpiExample() { this.InitializeComponent(); cycleTimer.Tick += cycleTimer_Tick; } void control_Unloaded(object sender, RoutedEventArgs e) { cycleTimer.Stop(); // Explicitly remove references to allow the Win2D controls to get garbage collected canvasControl.RemoveFromVisualTree(); canvasControl = null; mainDeviceResources = null; animatedControl.RemoveFromVisualTree(); animatedControl = null; animatedDeviceResources = null; swapChainPanel.RemoveFromVisualTree(); swapChainPanel = null; } void Canvas_CreateResources(CanvasControl sender, object args) { mainDeviceResources = new PerDeviceResources(sender); imageBrush = new CanvasImageBrush(sender); imageSource = new CanvasImageSource(sender, controlSize, controlSize); imageControl.Source = imageSource; swapChain = new CanvasSwapChain(sender, controlSize, controlSize); swapChainPanel.SwapChain = swapChain; } void AnimatedCanvas_CreateResources(ICanvasAnimatedControl sender, object args) { animatedDeviceResources = new PerDeviceResources(sender); } void Canvas_Draw(CanvasControl sender, CanvasDrawEventArgs args) { mainDeviceResources.InitMessage(); switch (CurrentOutput) { case OutputMode.CanvasControl: DrawToOutput(mainDeviceResources, args.DrawingSession); break; case OutputMode.CanvasImageBrush: DrawViaImageBrush(args.DrawingSession); break; case OutputMode.CanvasImageSource: DrawToImageSource(args.DrawingSession); break; case OutputMode.CanvasSwapChain: DrawToSwapChain(); break; } // Show or hide overlay controls to fit the current mode. imageControl.Visibility = (CurrentOutput == OutputMode.CanvasImageSource) ? Visibility.Visible : Visibility.Collapsed; swapChainPanel.Visibility = (CurrentOutput == OutputMode.CanvasSwapChain) ? Visibility.Visible : Visibility.Collapsed; animatedControl.Visibility = (CurrentOutput == OutputMode.CanvasAnimatedControl) ? Visibility.Visible : Visibility.Collapsed; animatedControl.Paused = (CurrentOutput != OutputMode.CanvasAnimatedControl); // Update the info text. textBlock.Text = mainDeviceResources.GetFinalMessage(); } void AnimatedCanvas_Draw(ICanvasAnimatedControl sender, CanvasAnimatedDrawEventArgs args) { animatedDeviceResources.InitMessage(); DrawToOutput(animatedDeviceResources, args.DrawingSession); // Update the info text. var message = animatedDeviceResources.GetFinalMessage(); var task = textBlock.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { textBlock.Text = message; }); } void DrawToOutput(PerDeviceResources resources, CanvasDrawingSession ds) { if (CurrentIntermediate == IntermediateMode.None) { // We can either draw directly to the output... DrawSourceGraphic(resources, ds, testOffset); } else { // Or go via an intermediate such as a rendertarget or image effect. var intermediateImage = WrapSourceWithIntermediateImage(resources, CurrentIntermediate); ds.DrawImage(intermediateImage, testOffset, testOffset); } resources.AddMessage("{0} (dpi: {1})", CurrentOutput, ds.Dpi); } void DrawViaImageBrush(CanvasDrawingSession ds) { imageBrush.Image = WrapSourceWithIntermediateImage(mainDeviceResources, CurrentIntermediate); imageBrush.SourceRectangle = new Rect(0, 0, testSize, testSize); imageBrush.Transform = Matrix3x2.CreateTranslation(testOffset, testOffset); ds.FillRectangle(testOffset, testOffset, testSize, testSize, imageBrush); mainDeviceResources.AddMessage("CanvasImageBrush ->\nCanvasControl (dpi: {0})", ds.Dpi); } void DrawToImageSource(CanvasDrawingSession canvasControlDrawingSession) { // XAML doesn't support nested image source drawing sessions, so we must close // the main CanvasControl one before drawing to a different CanvasImageSource. canvasControlDrawingSession.Dispose(); using (var ds = imageSource.CreateDrawingSession(Colors.Transparent)) { DrawToOutput(mainDeviceResources, ds); } } void DrawToSwapChain() { using (var ds = swapChain.CreateDrawingSession(Colors.Transparent)) { DrawToOutput(mainDeviceResources, ds); } swapChain.Present(); } ICanvasImage WrapSourceWithIntermediateImage(PerDeviceResources resources, IntermediateMode mode) { switch (mode) { case IntermediateMode.ImageEffect: // We can either feed our graphics through an image effect... resources.SaturationEffect.Source = GetSourceBitmap(resources) ?? WrapSourceWithIntermediateImage(resources, IntermediateMode.None); resources.AddMessage("SaturationEffect ->\n"); return resources.SaturationEffect; case IntermediateMode.CommandList: var cl = new CanvasCommandList(resources.ResourceCreator); using (var ds = cl.CreateDrawingSession()) { DrawSourceGraphic(resources, ds, 0); } resources.AddMessage("CommandList ->\n"); return cl; case IntermediateMode.ImageEffectInCommandList: var cl2 = new CanvasCommandList(resources.ResourceCreator); using (var ds = cl2.CreateDrawingSession()) { ds.DrawImage(WrapSourceWithIntermediateImage(resources, IntermediateMode.ImageEffect)); } resources.AddMessage("CommandList ->\n"); return cl2; default: // ... or draw them into a rendertarget. var renderTarget = GetIntermediateRenderTarget(resources, mode); using (var ds = renderTarget.CreateDrawingSession()) { DrawSourceGraphic(resources, ds, 0); } resources.AddMessage("RenderTarget (dpi: {0}, size: {1}, pixels: {2}) ->\n", renderTarget.Dpi, renderTarget.Size, renderTarget.SizeInPixels); return renderTarget; } } void DrawSourceGraphic(PerDeviceResources resources, CanvasDrawingSession ds, float offset) { var source = GetSourceBitmap(resources); if (source != null) { // We can either draw a precreated bitmap... ds.DrawImage(source, offset, offset); } else { // ... or directly draw some shapes. ds.FillRectangle(offset, offset, testSize, testSize, Colors.Gray); ds.DrawLine(offset, offset, offset + testSize, offset + testSize, Colors.Red); ds.DrawLine(offset + testSize, offset, offset, offset + testSize, Colors.Red); ds.DrawRectangle(offset + 0.5f, offset + 0.5f, testSize - 1, testSize - 1, Colors.Blue); ds.DrawText("DPI test", new Vector2(offset + testSize / 2), Colors.Blue, resources.TextFormat); resources.AddMessage("DrawingSession ->\n"); } } CanvasBitmap GetSourceBitmap(PerDeviceResources resources) { CanvasBitmap bitmap; switch (CurrentSource) { case SourceMode.DefaultDpiBitmap: bitmap = resources.DefaultDpiBitmap; break; case SourceMode.HighDpiBitmap: bitmap = resources.HighDpiBitmap; break; case SourceMode.LowDpiBitmap: bitmap = resources.LowDpiBitmap; break; default: bitmap = null; break; } if (bitmap != null) { resources.AddMessage("Bitmap (dpi: {0}, size: {1}, pixels: {2}) ->\n", bitmap.Dpi, bitmap.Size, bitmap.SizeInPixels); } return bitmap; } static CanvasRenderTarget GetIntermediateRenderTarget(PerDeviceResources resources, IntermediateMode mode) { switch (mode) { case IntermediateMode.HighDpiRenderTarget: return resources.HighDpiRenderTarget; case IntermediateMode.LowDpiRenderTarget: return resources.LowDpiRenderTarget; default: return resources.AutoDpiRenderTarget; } } static CanvasBitmap CreateTestBitmap(ICanvasResourceCreatorWithDpi resourceCreator, float dpi) { int pixelSize = (int)Math.Round(testSize * dpi / defaultDpi); // Initialize to solid gray. Color[] colors = Enumerable.Repeat(Colors.Gray, pixelSize * pixelSize).ToArray(); // Diagonal lines. for (int i = 0; i < pixelSize; i++) { colors[i * pixelSize + i] = Colors.Red; colors[i * pixelSize + (pixelSize - i - 1)] = Colors.Red; } // Single pixel border. for (int i = 0; i < pixelSize; i++) { colors[i] = Colors.Blue; colors[i * pixelSize] = Colors.Blue; colors[i * pixelSize + pixelSize - 1] = Colors.Blue; colors[pixelSize * (pixelSize - 1) + i] = Colors.Blue; } if (dpi == defaultDpi) { // We could always just use the "else" path, but want to test this default overload as well. return CanvasBitmap.CreateFromColors(resourceCreator, colors, pixelSize, pixelSize); } else { return CanvasBitmap.CreateFromColors(resourceCreator, colors, pixelSize, pixelSize, dpi); } } void AutoCycle_Checked(object sender, RoutedEventArgs e) { cycleTimer.Start(); } void AutoCycle_Unchecked(object sender, RoutedEventArgs e) { cycleTimer.Stop(); } void cycleTimer_Tick(object sender, object e) { if (!cycleTimer.IsEnabled) return; // Increment the source mode. CurrentSource++; if (CurrentSource >= (SourceMode)Enum.GetValues(typeof(SourceMode)).Length) { CurrentSource = 0; CurrentIntermediate++; // Increment the intermediate mode. if (CurrentIntermediate >= (IntermediateMode)Enum.GetValues(typeof(IntermediateMode)).Length) { CurrentIntermediate = 0; // Increment the output mode. CurrentOutput++; if (CurrentOutput >= (OutputMode)Enum.GetValues(typeof(OutputMode)).Length) { CurrentOutput = 0; } PropertyChanged(this, new PropertyChangedEventArgs("CurrentOutput")); } PropertyChanged(this, new PropertyChangedEventArgs("CurrentIntermediate")); } PropertyChanged(this, new PropertyChangedEventArgs("CurrentSource")); } void SelectionChanged(object sender, SelectionChangedEventArgs e) { canvasControl.Invalidate(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System { using System; using System.Threading; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Security.Permissions; using System.Diagnostics.Contracts; // DateTimeOffset is a value type that consists of a DateTime and a time zone offset, // ie. how far away the time is from GMT. The DateTime is stored whole, and the offset // is stored as an Int16 internally to save space, but presented as a TimeSpan. // // The range is constrained so that both the represented clock time and the represented // UTC time fit within the boundaries of MaxValue. This gives it the same range as DateTime // for actual UTC times, and a slightly constrained range on one end when an offset is // present. // // This class should be substitutable for date time in most cases; so most operations // effectively work on the clock time. However, the underlying UTC time is what counts // for the purposes of identity, sorting and subtracting two instances. // // // There are theoretically two date times stored, the UTC and the relative local representation // or the 'clock' time. It actually does not matter which is stored in m_dateTime, so it is desirable // for most methods to go through the helpers UtcDateTime and ClockDateTime both to abstract this // out and for internal readability. [StructLayout(LayoutKind.Auto)] [Serializable] public struct DateTimeOffset : IComparable, IFormattable, ISerializable, IDeserializationCallback, IComparable<DateTimeOffset>, IEquatable<DateTimeOffset> { // Constants internal const Int64 MaxOffset = TimeSpan.TicksPerHour * 14; internal const Int64 MinOffset = -MaxOffset; private const long UnixEpochTicks = TimeSpan.TicksPerDay * DateTime.DaysTo1970; // 621,355,968,000,000,000 private const long UnixEpochSeconds = UnixEpochTicks / TimeSpan.TicksPerSecond; // 62,135,596,800 private const long UnixEpochMilliseconds = UnixEpochTicks / TimeSpan.TicksPerMillisecond; // 62,135,596,800,000 // Static Fields public static readonly DateTimeOffset MinValue = new DateTimeOffset(DateTime.MinTicks, TimeSpan.Zero); public static readonly DateTimeOffset MaxValue = new DateTimeOffset(DateTime.MaxTicks, TimeSpan.Zero); // Instance Fields private DateTime m_dateTime; private Int16 m_offsetMinutes; // Constructors // Constructs a DateTimeOffset from a tick count and offset public DateTimeOffset(long ticks, TimeSpan offset) { m_offsetMinutes = ValidateOffset(offset); // Let the DateTime constructor do the range checks DateTime dateTime = new DateTime(ticks); m_dateTime = ValidateDate(dateTime, offset); } // Constructs a DateTimeOffset from a DateTime. For Local and Unspecified kinds, // extracts the local offset. For UTC, creates a UTC instance with a zero offset. public DateTimeOffset(DateTime dateTime) { TimeSpan offset; if (dateTime.Kind != DateTimeKind.Utc) { // Local and Unspecified are both treated as Local offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime); } else { offset = new TimeSpan(0); } m_offsetMinutes = ValidateOffset(offset); m_dateTime = ValidateDate(dateTime, offset); } // Constructs a DateTimeOffset from a DateTime. And an offset. Always makes the clock time // consistent with the DateTime. For Utc ensures the offset is zero. For local, ensures that // the offset corresponds to the local. public DateTimeOffset(DateTime dateTime, TimeSpan offset) { if (dateTime.Kind == DateTimeKind.Local) { if (offset != TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime)) { throw new ArgumentException(Environment.GetResourceString("Argument_OffsetLocalMismatch"), "offset"); } } else if (dateTime.Kind == DateTimeKind.Utc) { if (offset != TimeSpan.Zero) { throw new ArgumentException(Environment.GetResourceString("Argument_OffsetUtcMismatch"), "offset"); } } m_offsetMinutes = ValidateOffset(offset); m_dateTime = ValidateDate(dateTime, offset); } // Constructs a DateTimeOffset from a given year, month, day, hour, // minute, second and offset. public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, TimeSpan offset) { m_offsetMinutes = ValidateOffset(offset); m_dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second), offset); } // Constructs a DateTimeOffset from a given year, month, day, hour, // minute, second, millsecond and offset public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, int millisecond, TimeSpan offset) { m_offsetMinutes = ValidateOffset(offset); m_dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second, millisecond), offset); } // Constructs a DateTimeOffset from a given year, month, day, hour, // minute, second, millsecond, Calendar and offset. public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar, TimeSpan offset) { m_offsetMinutes = ValidateOffset(offset); m_dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second, millisecond, calendar), offset); } // Returns a DateTimeOffset representing the current date and time. The // resolution of the returned value depends on the system timer. For // Windows NT 3.5 and later the timer resolution is approximately 10ms, // for Windows NT 3.1 it is approximately 16ms, and for Windows 95 and 98 // it is approximately 55ms. // public static DateTimeOffset Now { get { return new DateTimeOffset(DateTime.Now); } } public static DateTimeOffset UtcNow { get { return new DateTimeOffset(DateTime.UtcNow); } } public DateTime DateTime { get { return ClockDateTime; } } public DateTime UtcDateTime { [Pure] get { Contract.Ensures(Contract.Result<DateTime>().Kind == DateTimeKind.Utc); return DateTime.SpecifyKind(m_dateTime, DateTimeKind.Utc); } } public DateTime LocalDateTime { [Pure] get { Contract.Ensures(Contract.Result<DateTime>().Kind == DateTimeKind.Local); return UtcDateTime.ToLocalTime(); } } // Adjust to a given offset with the same UTC time. Can throw ArgumentException // public DateTimeOffset ToOffset(TimeSpan offset) { return new DateTimeOffset((m_dateTime + offset).Ticks, offset); } // Instance Properties // The clock or visible time represented. This is just a wrapper around the internal date because this is // the chosen storage mechanism. Going through this helper is good for readability and maintainability. // This should be used for display but not identity. private DateTime ClockDateTime { get { return new DateTime((m_dateTime + Offset).Ticks, DateTimeKind.Unspecified); } } // Returns the date part of this DateTimeOffset. The resulting value // corresponds to this DateTimeOffset with the time-of-day part set to // zero (midnight). // public DateTime Date { get { return ClockDateTime.Date; } } // Returns the day-of-month part of this DateTimeOffset. The returned // value is an integer between 1 and 31. // public int Day { get { Contract.Ensures(Contract.Result<int>() >= 1); Contract.Ensures(Contract.Result<int>() <= 31); return ClockDateTime.Day; } } // Returns the day-of-week part of this DateTimeOffset. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public DayOfWeek DayOfWeek { get { Contract.Ensures(Contract.Result<DayOfWeek>() >= DayOfWeek.Sunday); Contract.Ensures(Contract.Result<DayOfWeek>() <= DayOfWeek.Saturday); return ClockDateTime.DayOfWeek; } } // Returns the day-of-year part of this DateTimeOffset. The returned value // is an integer between 1 and 366. // public int DayOfYear { get { Contract.Ensures(Contract.Result<int>() >= 1); Contract.Ensures(Contract.Result<int>() <= 366); // leap year return ClockDateTime.DayOfYear; } } // Returns the hour part of this DateTimeOffset. The returned value is an // integer between 0 and 23. // public int Hour { get { Contract.Ensures(Contract.Result<int>() >= 0); Contract.Ensures(Contract.Result<int>() < 24); return ClockDateTime.Hour; } } // Returns the millisecond part of this DateTimeOffset. The returned value // is an integer between 0 and 999. // public int Millisecond { get { Contract.Ensures(Contract.Result<int>() >= 0); Contract.Ensures(Contract.Result<int>() < 1000); return ClockDateTime.Millisecond; } } // Returns the minute part of this DateTimeOffset. The returned value is // an integer between 0 and 59. // public int Minute { get { Contract.Ensures(Contract.Result<int>() >= 0); Contract.Ensures(Contract.Result<int>() < 60); return ClockDateTime.Minute; } } // Returns the month part of this DateTimeOffset. The returned value is an // integer between 1 and 12. // public int Month { get { Contract.Ensures(Contract.Result<int>() >= 1); return ClockDateTime.Month; } } public TimeSpan Offset { get { return new TimeSpan(0, m_offsetMinutes, 0); } } // Returns the second part of this DateTimeOffset. The returned value is // an integer between 0 and 59. // public int Second { get { Contract.Ensures(Contract.Result<int>() >= 0); Contract.Ensures(Contract.Result<int>() < 60); return ClockDateTime.Second; } } // Returns the tick count for this DateTimeOffset. The returned value is // the number of 100-nanosecond intervals that have elapsed since 1/1/0001 // 12:00am. // public long Ticks { get { return ClockDateTime.Ticks; } } public long UtcTicks { get { return UtcDateTime.Ticks; } } // Returns the time-of-day part of this DateTimeOffset. The returned value // is a TimeSpan that indicates the time elapsed since midnight. // public TimeSpan TimeOfDay { get { return ClockDateTime.TimeOfDay; } } // Returns the year part of this DateTimeOffset. The returned value is an // integer between 1 and 9999. // public int Year { get { Contract.Ensures(Contract.Result<int>() >= 1 && Contract.Result<int>() <= 9999); return ClockDateTime.Year; } } // Returns the DateTimeOffset resulting from adding the given // TimeSpan to this DateTimeOffset. // public DateTimeOffset Add(TimeSpan timeSpan) { return new DateTimeOffset(ClockDateTime.Add(timeSpan), Offset); } // Returns the DateTimeOffset resulting from adding a fractional number of // days to this DateTimeOffset. The result is computed by rounding the // fractional number of days given by value to the nearest // millisecond, and adding that interval to this DateTimeOffset. The // value argument is permitted to be negative. // public DateTimeOffset AddDays(double days) { return new DateTimeOffset(ClockDateTime.AddDays(days), Offset); } // Returns the DateTimeOffset resulting from adding a fractional number of // hours to this DateTimeOffset. The result is computed by rounding the // fractional number of hours given by value to the nearest // millisecond, and adding that interval to this DateTimeOffset. The // value argument is permitted to be negative. // public DateTimeOffset AddHours(double hours) { return new DateTimeOffset(ClockDateTime.AddHours(hours), Offset); } // Returns the DateTimeOffset resulting from the given number of // milliseconds to this DateTimeOffset. The result is computed by rounding // the number of milliseconds given by value to the nearest integer, // and adding that interval to this DateTimeOffset. The value // argument is permitted to be negative. // public DateTimeOffset AddMilliseconds(double milliseconds) { return new DateTimeOffset(ClockDateTime.AddMilliseconds(milliseconds), Offset); } // Returns the DateTimeOffset resulting from adding a fractional number of // minutes to this DateTimeOffset. The result is computed by rounding the // fractional number of minutes given by value to the nearest // millisecond, and adding that interval to this DateTimeOffset. The // value argument is permitted to be negative. // public DateTimeOffset AddMinutes(double minutes) { return new DateTimeOffset(ClockDateTime.AddMinutes(minutes), Offset); } public DateTimeOffset AddMonths(int months) { return new DateTimeOffset(ClockDateTime.AddMonths(months), Offset); } // Returns the DateTimeOffset resulting from adding a fractional number of // seconds to this DateTimeOffset. The result is computed by rounding the // fractional number of seconds given by value to the nearest // millisecond, and adding that interval to this DateTimeOffset. The // value argument is permitted to be negative. // public DateTimeOffset AddSeconds(double seconds) { return new DateTimeOffset(ClockDateTime.AddSeconds(seconds), Offset); } // Returns the DateTimeOffset resulting from adding the given number of // 100-nanosecond ticks to this DateTimeOffset. The value argument // is permitted to be negative. // public DateTimeOffset AddTicks(long ticks) { return new DateTimeOffset(ClockDateTime.AddTicks(ticks), Offset); } // Returns the DateTimeOffset resulting from adding the given number of // years to this DateTimeOffset. The result is computed by incrementing // (or decrementing) the year part of this DateTimeOffset by value // years. If the month and day of this DateTimeOffset is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTimeOffset becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of this DateTimeOffset. // public DateTimeOffset AddYears(int years) { return new DateTimeOffset(ClockDateTime.AddYears(years), Offset); } // Compares two DateTimeOffset values, returning an integer that indicates // their relationship. // public static int Compare(DateTimeOffset first, DateTimeOffset second) { return DateTime.Compare(first.UtcDateTime, second.UtcDateTime); } // Compares this DateTimeOffset to a given object. This method provides an // implementation of the IComparable interface. The object // argument must be another DateTimeOffset, or otherwise an exception // occurs. Null is considered less than any instance. // int IComparable.CompareTo(Object obj) { if (obj == null) return 1; if (!(obj is DateTimeOffset)) { throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDateTimeOffset")); } DateTime objUtc = ((DateTimeOffset)obj).UtcDateTime; DateTime utc = UtcDateTime; if (utc > objUtc) return 1; if (utc < objUtc) return -1; return 0; } public int CompareTo(DateTimeOffset other) { DateTime otherUtc = other.UtcDateTime; DateTime utc = UtcDateTime; if (utc > otherUtc) return 1; if (utc < otherUtc) return -1; return 0; } // Checks if this DateTimeOffset is equal to a given object. Returns // true if the given object is a boxed DateTimeOffset and its value // is equal to the value of this DateTimeOffset. Returns false // otherwise. // public override bool Equals(Object obj) { if (obj is DateTimeOffset) { return UtcDateTime.Equals(((DateTimeOffset)obj).UtcDateTime); } return false; } public bool Equals(DateTimeOffset other) { return UtcDateTime.Equals(other.UtcDateTime); } public bool EqualsExact(DateTimeOffset other) { // // returns true when the ClockDateTime, Kind, and Offset match // // currently the Kind should always be Unspecified, but there is always the possibility that a future version // of DateTimeOffset overloads the Kind field // return (ClockDateTime == other.ClockDateTime && Offset == other.Offset && ClockDateTime.Kind == other.ClockDateTime.Kind); } // Compares two DateTimeOffset values for equality. Returns true if // the two DateTimeOffset values are equal, or false if they are // not equal. // public static bool Equals(DateTimeOffset first, DateTimeOffset second) { return DateTime.Equals(first.UtcDateTime, second.UtcDateTime); } // Creates a DateTimeOffset from a Windows filetime. A Windows filetime is // a long representing the date and time as the number of // 100-nanosecond intervals that have elapsed since 1/1/1601 12:00am. // public static DateTimeOffset FromFileTime(long fileTime) { return new DateTimeOffset(DateTime.FromFileTime(fileTime)); } public static DateTimeOffset FromUnixTimeSeconds(long seconds) { const long MinSeconds = DateTime.MinTicks / TimeSpan.TicksPerSecond - UnixEpochSeconds; const long MaxSeconds = DateTime.MaxTicks / TimeSpan.TicksPerSecond - UnixEpochSeconds; if (seconds < MinSeconds || seconds > MaxSeconds) { throw new ArgumentOutOfRangeException("seconds", string.Format(Environment.GetResourceString("ArgumentOutOfRange_Range"), MinSeconds, MaxSeconds)); } long ticks = seconds * TimeSpan.TicksPerSecond + UnixEpochTicks; return new DateTimeOffset(ticks, TimeSpan.Zero); } public static DateTimeOffset FromUnixTimeMilliseconds(long milliseconds) { const long MinMilliseconds = DateTime.MinTicks / TimeSpan.TicksPerMillisecond - UnixEpochMilliseconds; const long MaxMilliseconds = DateTime.MaxTicks / TimeSpan.TicksPerMillisecond - UnixEpochMilliseconds; if (milliseconds < MinMilliseconds || milliseconds > MaxMilliseconds) { throw new ArgumentOutOfRangeException("milliseconds", string.Format(Environment.GetResourceString("ArgumentOutOfRange_Range"), MinMilliseconds, MaxMilliseconds)); } long ticks = milliseconds * TimeSpan.TicksPerMillisecond + UnixEpochTicks; return new DateTimeOffset(ticks, TimeSpan.Zero); } // ----- SECTION: private serialization instance methods ----------------* #if FEATURE_SERIALIZATION void IDeserializationCallback.OnDeserialization(Object sender) { try { m_offsetMinutes = ValidateOffset(Offset); m_dateTime = ValidateDate(ClockDateTime, Offset); } catch (ArgumentException e) { throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), e); } } [System.Security.SecurityCritical] // auto-generated_required void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } Contract.EndContractBlock(); info.AddValue("DateTime", m_dateTime); info.AddValue("OffsetMinutes", m_offsetMinutes); } DateTimeOffset(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } m_dateTime = (DateTime)info.GetValue("DateTime", typeof(DateTime)); m_offsetMinutes = (Int16)info.GetValue("OffsetMinutes", typeof(Int16)); } #endif // Returns the hash code for this DateTimeOffset. // public override int GetHashCode() { return UtcDateTime.GetHashCode(); } // Constructs a DateTimeOffset from a string. The string must specify a // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // public static DateTimeOffset Parse(String input) { TimeSpan offset; DateTime dateResult = DateTimeParse.Parse(input, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out offset); return new DateTimeOffset(dateResult.Ticks, offset); } // Constructs a DateTimeOffset from a string. The string must specify a // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // public static DateTimeOffset Parse(String input, IFormatProvider formatProvider) { return Parse(input, formatProvider, DateTimeStyles.None); } public static DateTimeOffset Parse(String input, IFormatProvider formatProvider, DateTimeStyles styles) { styles = ValidateStyles(styles, "styles"); TimeSpan offset; DateTime dateResult = DateTimeParse.Parse(input, DateTimeFormatInfo.GetInstance(formatProvider), styles, out offset); return new DateTimeOffset(dateResult.Ticks, offset); } // Constructs a DateTimeOffset from a string. The string must specify a // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // public static DateTimeOffset ParseExact(String input, String format, IFormatProvider formatProvider) { return ParseExact(input, format, formatProvider, DateTimeStyles.None); } // Constructs a DateTimeOffset from a string. The string must specify a // date and optionally a time in a culture-specific or universal format. // Leading and trailing whitespace characters are allowed. // public static DateTimeOffset ParseExact(String input, String format, IFormatProvider formatProvider, DateTimeStyles styles) { styles = ValidateStyles(styles, "styles"); TimeSpan offset; DateTime dateResult = DateTimeParse.ParseExact(input, format, DateTimeFormatInfo.GetInstance(formatProvider), styles, out offset); return new DateTimeOffset(dateResult.Ticks, offset); } public static DateTimeOffset ParseExact(String input, String[] formats, IFormatProvider formatProvider, DateTimeStyles styles) { styles = ValidateStyles(styles, "styles"); TimeSpan offset; DateTime dateResult = DateTimeParse.ParseExactMultiple(input, formats, DateTimeFormatInfo.GetInstance(formatProvider), styles, out offset); return new DateTimeOffset(dateResult.Ticks, offset); } public TimeSpan Subtract(DateTimeOffset value) { return UtcDateTime.Subtract(value.UtcDateTime); } public DateTimeOffset Subtract(TimeSpan value) { return new DateTimeOffset(ClockDateTime.Subtract(value), Offset); } public long ToFileTime() { return UtcDateTime.ToFileTime(); } public long ToUnixTimeSeconds() { // Truncate sub-second precision before offsetting by the Unix Epoch to avoid // the last digit being off by one for dates that result in negative Unix times. // // For example, consider the DateTimeOffset 12/31/1969 12:59:59.001 +0 // ticks = 621355967990010000 // ticksFromEpoch = ticks - UnixEpochTicks = -9990000 // secondsFromEpoch = ticksFromEpoch / TimeSpan.TicksPerSecond = 0 // // Notice that secondsFromEpoch is rounded *up* by the truncation induced by integer division, // whereas we actually always want to round *down* when converting to Unix time. This happens // automatically for positive Unix time values. Now the example becomes: // seconds = ticks / TimeSpan.TicksPerSecond = 62135596799 // secondsFromEpoch = seconds - UnixEpochSeconds = -1 // // In other words, we want to consistently round toward the time 1/1/0001 00:00:00, // rather than toward the Unix Epoch (1/1/1970 00:00:00). long seconds = UtcDateTime.Ticks / TimeSpan.TicksPerSecond; return seconds - UnixEpochSeconds; } public long ToUnixTimeMilliseconds() { // Truncate sub-millisecond precision before offsetting by the Unix Epoch to avoid // the last digit being off by one for dates that result in negative Unix times long milliseconds = UtcDateTime.Ticks / TimeSpan.TicksPerMillisecond; return milliseconds - UnixEpochMilliseconds; } public DateTimeOffset ToLocalTime() { return ToLocalTime(false); } internal DateTimeOffset ToLocalTime(bool throwOnOverflow) { return new DateTimeOffset(UtcDateTime.ToLocalTime(throwOnOverflow)); } public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return DateTimeFormat.Format(ClockDateTime, null, DateTimeFormatInfo.CurrentInfo, Offset); } public String ToString(String format) { Contract.Ensures(Contract.Result<String>() != null); return DateTimeFormat.Format(ClockDateTime, format, DateTimeFormatInfo.CurrentInfo, Offset); } public String ToString(IFormatProvider formatProvider) { Contract.Ensures(Contract.Result<String>() != null); return DateTimeFormat.Format(ClockDateTime, null, DateTimeFormatInfo.GetInstance(formatProvider), Offset); } public String ToString(String format, IFormatProvider formatProvider) { Contract.Ensures(Contract.Result<String>() != null); return DateTimeFormat.Format(ClockDateTime, format, DateTimeFormatInfo.GetInstance(formatProvider), Offset); } public DateTimeOffset ToUniversalTime() { return new DateTimeOffset(UtcDateTime); } public static Boolean TryParse(String input, out DateTimeOffset result) { TimeSpan offset; DateTime dateResult; Boolean parsed = DateTimeParse.TryParse(input, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out dateResult, out offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } public static Boolean TryParse(String input, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, "styles"); TimeSpan offset; DateTime dateResult; Boolean parsed = DateTimeParse.TryParse(input, DateTimeFormatInfo.GetInstance(formatProvider), styles, out dateResult, out offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, "styles"); TimeSpan offset; DateTime dateResult; Boolean parsed = DateTimeParse.TryParseExact(input, format, DateTimeFormatInfo.GetInstance(formatProvider), styles, out dateResult, out offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, "styles"); TimeSpan offset; DateTime dateResult; Boolean parsed = DateTimeParse.TryParseExactMultiple(input, formats, DateTimeFormatInfo.GetInstance(formatProvider), styles, out dateResult, out offset); result = new DateTimeOffset(dateResult.Ticks, offset); return parsed; } // Ensures the TimeSpan is valid to go in a DateTimeOffset. private static Int16 ValidateOffset(TimeSpan offset) { Int64 ticks = offset.Ticks; if (ticks % TimeSpan.TicksPerMinute != 0) { throw new ArgumentException(Environment.GetResourceString("Argument_OffsetPrecision"), "offset"); } if (ticks < MinOffset || ticks > MaxOffset) { throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("Argument_OffsetOutOfRange")); } return (Int16)(offset.Ticks / TimeSpan.TicksPerMinute); } // Ensures that the time and offset are in range. private static DateTime ValidateDate(DateTime dateTime, TimeSpan offset) { // The key validation is that both the UTC and clock times fit. The clock time is validated // by the DateTime constructor. Contract.Assert(offset.Ticks >= MinOffset && offset.Ticks <= MaxOffset, "Offset not validated."); // This operation cannot overflow because offset should have already been validated to be within // 14 hours and the DateTime instance is more than that distance from the boundaries of Int64. Int64 utcTicks = dateTime.Ticks - offset.Ticks; if (utcTicks < DateTime.MinTicks || utcTicks > DateTime.MaxTicks) { throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("Argument_UTCOutOfRange")); } // make sure the Kind is set to Unspecified // return new DateTime(utcTicks, DateTimeKind.Unspecified); } private static DateTimeStyles ValidateStyles(DateTimeStyles style, String parameterName) { if ((style & DateTimeFormatInfo.InvalidDateTimeStyles) != 0) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDateTimeStyles"), parameterName); } if (((style & (DateTimeStyles.AssumeLocal)) != 0) && ((style & (DateTimeStyles.AssumeUniversal)) != 0)) { throw new ArgumentException(Environment.GetResourceString("Argument_ConflictingDateTimeStyles"), parameterName); } if ((style & DateTimeStyles.NoCurrentDateDefault) != 0) { throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeOffsetInvalidDateTimeStyles"), parameterName); } Contract.EndContractBlock(); // RoundtripKind does not make sense for DateTimeOffset; ignore this flag for backward compatability with DateTime style &= ~DateTimeStyles.RoundtripKind; // AssumeLocal is also ignored as that is what we do by default with DateTimeOffset.Parse style &= ~DateTimeStyles.AssumeLocal; return style; } // Operators public static implicit operator DateTimeOffset (DateTime dateTime) { return new DateTimeOffset(dateTime); } public static DateTimeOffset operator +(DateTimeOffset dateTimeOffset, TimeSpan timeSpan) { return new DateTimeOffset(dateTimeOffset.ClockDateTime + timeSpan, dateTimeOffset.Offset); } public static DateTimeOffset operator -(DateTimeOffset dateTimeOffset, TimeSpan timeSpan) { return new DateTimeOffset(dateTimeOffset.ClockDateTime - timeSpan, dateTimeOffset.Offset); } public static TimeSpan operator -(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime - right.UtcDateTime; } public static bool operator ==(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime == right.UtcDateTime; } public static bool operator !=(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime != right.UtcDateTime; } public static bool operator <(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime < right.UtcDateTime; } public static bool operator <=(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime <= right.UtcDateTime; } public static bool operator >(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime > right.UtcDateTime; } public static bool operator >=(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime >= right.UtcDateTime; } } }
using System; using System.IO; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Microsoft.Net.Http.Headers; using OrchardCore.Admin; using OrchardCore.Deployment; using OrchardCore.DisplayManagement.Handlers; using OrchardCore.Environment.Shell; using OrchardCore.Environment.Shell.Distributed; using OrchardCore.Modules; using OrchardCore.Modules.FileProviders; using OrchardCore.Mvc.Core.Utilities; using OrchardCore.Navigation; using OrchardCore.Recipes; using OrchardCore.Security.Permissions; using OrchardCore.Setup; using OrchardCore.Tenants.Controllers; using OrchardCore.Tenants.Deployment; using OrchardCore.Tenants.Recipes; using OrchardCore.Tenants.Services; namespace OrchardCore.Tenants { public class Startup : StartupBase { private readonly AdminOptions _adminOptions; public Startup(IOptions<AdminOptions> adminOptions) { _adminOptions = adminOptions.Value; } public override void ConfigureServices(IServiceCollection services) { services.AddScoped<INavigationProvider, AdminMenu>(); services.AddScoped<IPermissionProvider, Permissions>(); services.AddSetup(); } public override void Configure(IApplicationBuilder builder, IEndpointRouteBuilder routes, IServiceProvider serviceProvider) { var adminControllerName = typeof(AdminController).ControllerName(); routes.MapAreaControllerRoute( name: "Tenants", areaName: "OrchardCore.Tenants", pattern: _adminOptions.AdminUrlPrefix + "/Tenants", defaults: new { controller = adminControllerName, action = nameof(AdminController.Index) } ); routes.MapAreaControllerRoute( name: "TenantsCreate", areaName: "OrchardCore.Tenants", pattern: _adminOptions.AdminUrlPrefix + "/Tenants/Create", defaults: new { controller = adminControllerName, action = nameof(AdminController.Create) } ); routes.MapAreaControllerRoute( name: "TenantsEdit", areaName: "OrchardCore.Tenants", pattern: _adminOptions.AdminUrlPrefix + "/Tenants/Edit/{id}", defaults: new { controller = adminControllerName, action = nameof(AdminController.Edit) } ); routes.MapAreaControllerRoute( name: "TenantsReload", areaName: "OrchardCore.Tenants", pattern: _adminOptions.AdminUrlPrefix + "/Tenants/Reload/{id}", defaults: new { controller = adminControllerName, action = nameof(AdminController.Reload) } ); } } [Feature("OrchardCore.Tenants.FileProvider")] public class FileProviderStartup : StartupBase { /// <summary> /// The path in the tenant's App_Data folder containing the files /// </summary> private const string AssetsPath = "wwwroot"; // Run after other middlewares public override int Order => 10; public override void ConfigureServices(IServiceCollection services) { services.AddSingleton<ITenantFileProvider>(serviceProvider => { var shellOptions = serviceProvider.GetRequiredService<IOptions<ShellOptions>>(); var shellSettings = serviceProvider.GetRequiredService<ShellSettings>(); string contentRoot = GetContentRoot(shellOptions.Value, shellSettings); if (!Directory.Exists(contentRoot)) { Directory.CreateDirectory(contentRoot); } return new TenantFileProvider(contentRoot); }); services.AddSingleton<IStaticFileProvider>(serviceProvider => { return serviceProvider.GetRequiredService<ITenantFileProvider>(); }); } public override void Configure(IApplicationBuilder app, IEndpointRouteBuilder routes, IServiceProvider serviceProvider) { var tenantFileProvider = serviceProvider.GetRequiredService<ITenantFileProvider>(); app.UseStaticFiles(new StaticFileOptions { FileProvider = tenantFileProvider, DefaultContentType = "application/octet-stream", ServeUnknownFileTypes = true, // Cache the tenant static files for 30 days OnPrepareResponse = ctx => { ctx.Context.Response.Headers[HeaderNames.CacheControl] = $"public, max-age={TimeSpan.FromDays(30).TotalSeconds}, s-max-age={TimeSpan.FromDays(365.25).TotalSeconds}"; } }); } private string GetContentRoot(ShellOptions shellOptions, ShellSettings shellSettings) { return Path.Combine(shellOptions.ShellsApplicationDataPath, shellOptions.ShellsContainerName, shellSettings.Name, AssetsPath); } } [Feature("OrchardCore.Tenants.Distributed")] public class DistributedStartup : StartupBase { public override void ConfigureServices(IServiceCollection services) { services.AddSingleton<DistributedShellMarkerService>(); } } [Feature("OrchardCore.Tenants.FeatureProfiles")] public class FeatureProfilesStartup : StartupBase { private readonly AdminOptions _adminOptions; public FeatureProfilesStartup(IOptions<AdminOptions> adminOptions) { _adminOptions = adminOptions.Value; } public override void ConfigureServices(IServiceCollection services) { services.AddScoped<INavigationProvider, FeatureProfilesAdminMenu>(); services.AddScoped<FeatureProfilesManager>(); services.AddScoped<IFeatureProfilesService, FeatureProfilesService>(); services.AddScoped<IFeatureProfilesSchemaService, FeatureProfilesSchemaService>(); services.AddRecipeExecutionStep<FeatureProfilesStep>(); } public override void Configure(IApplicationBuilder builder, IEndpointRouteBuilder routes, IServiceProvider serviceProvider) { var featureProfilesControllerName = typeof(FeatureProfilesController).ControllerName(); routes.MapAreaControllerRoute( name: "TenantFeatureProfilesIndex", areaName: "OrchardCore.Tenants", pattern: _adminOptions.AdminUrlPrefix + "/TenantFeatureProfiles", defaults: new { controller = featureProfilesControllerName, action = nameof(FeatureProfilesController.Index) } ); routes.MapAreaControllerRoute( name: "TenantFeatureProfilesCreate", areaName: "OrchardCore.Tenants", pattern: _adminOptions.AdminUrlPrefix + "/TenantFeatureProfiles/Create", defaults: new { controller = featureProfilesControllerName, action = nameof(FeatureProfilesController.Create) } ); routes.MapAreaControllerRoute( name: "TenantFeatureProfilesEdit", areaName: "OrchardCore.Tenants", pattern: _adminOptions.AdminUrlPrefix + "/TenantFeatureProfiles/Edit/{name}", defaults: new { controller = featureProfilesControllerName, action = nameof(FeatureProfilesController.Edit) } ); routes.MapAreaControllerRoute( name: "TenantFeatureProfilesDelete", areaName: "OrchardCore.Tenants", pattern: _adminOptions.AdminUrlPrefix + "/TenantFeatureProfiles/Delete/{name}", defaults: new { controller = featureProfilesControllerName, action = nameof(FeatureProfilesController.Delete) } ); } } [RequireFeatures("OrchardCore.Deployment", "OrchardCore.Tenants.FeatureProfiles")] public class FeatureProfilesDeployementStartup : StartupBase { public override void ConfigureServices(IServiceCollection services) { services.AddTransient<IDeploymentSource, AllFeatureProfilesDeploymentSource>(); services.AddSingleton<IDeploymentStepFactory>(new DeploymentStepFactory<AllFeatureProfilesDeploymentStep>()); services.AddScoped<IDisplayDriver<DeploymentStep>, AllFeatureProfilesDeploymentStepDriver>(); } } }
using System; using System.Collections; using Raksha.Asn1; namespace Raksha.Asn1.Cms { /** * a signed data object. */ public class SignedData : Asn1Encodable { private readonly DerInteger version; private readonly Asn1Set digestAlgorithms; private readonly ContentInfo contentInfo; private readonly Asn1Set certificates; private readonly Asn1Set crls; private readonly Asn1Set signerInfos; private readonly bool certsBer; private readonly bool crlsBer; public static SignedData GetInstance( object obj) { if (obj is SignedData) return (SignedData) obj; if (obj is Asn1Sequence) return new SignedData((Asn1Sequence) obj); throw new ArgumentException("Unknown object in factory: " + obj.GetType().FullName, "obj"); } public SignedData( Asn1Set digestAlgorithms, ContentInfo contentInfo, Asn1Set certificates, Asn1Set crls, Asn1Set signerInfos) { this.version = CalculateVersion(contentInfo.ContentType, certificates, crls, signerInfos); this.digestAlgorithms = digestAlgorithms; this.contentInfo = contentInfo; this.certificates = certificates; this.crls = crls; this.signerInfos = signerInfos; this.crlsBer = crls is BerSet; this.certsBer = certificates is BerSet; } // RFC3852, section 5.1: // IF ((certificates is present) AND // (any certificates with a type of other are present)) OR // ((crls is present) AND // (any crls with a type of other are present)) // THEN version MUST be 5 // ELSE // IF (certificates is present) AND // (any version 2 attribute certificates are present) // THEN version MUST be 4 // ELSE // IF ((certificates is present) AND // (any version 1 attribute certificates are present)) OR // (any SignerInfo structures are version 3) OR // (encapContentInfo eContentType is other than id-data) // THEN version MUST be 3 // ELSE version MUST be 1 // private DerInteger CalculateVersion( DerObjectIdentifier contentOid, Asn1Set certs, Asn1Set crls, Asn1Set signerInfs) { bool otherCert = false; bool otherCrl = false; bool attrCertV1Found = false; bool attrCertV2Found = false; if (certs != null) { foreach (object obj in certs) { if (obj is Asn1TaggedObject) { Asn1TaggedObject tagged = (Asn1TaggedObject)obj; if (tagged.TagNo == 1) { attrCertV1Found = true; } else if (tagged.TagNo == 2) { attrCertV2Found = true; } else if (tagged.TagNo == 3) { otherCert = true; break; } } } } if (otherCert) { return new DerInteger(5); } if (crls != null) { foreach (object obj in crls) { if (obj is Asn1TaggedObject) { otherCrl = true; break; } } } if (otherCrl) { return new DerInteger(5); } if (attrCertV2Found) { return new DerInteger(4); } if (attrCertV1Found || !CmsObjectIdentifiers.Data.Equals(contentOid) || CheckForVersion3(signerInfs)) { return new DerInteger(3); } return new DerInteger(1); } private bool CheckForVersion3( Asn1Set signerInfs) { foreach (object obj in signerInfs) { SignerInfo s = SignerInfo.GetInstance(obj); if (s.Version.Value.IntValue == 3) { return true; } } return false; } private SignedData( Asn1Sequence seq) { IEnumerator e = seq.GetEnumerator(); e.MoveNext(); version = (DerInteger)e.Current; e.MoveNext(); digestAlgorithms = ((Asn1Set)e.Current); e.MoveNext(); contentInfo = ContentInfo.GetInstance(e.Current); while (e.MoveNext()) { Asn1Object o = (Asn1Object)e.Current; // // an interesting feature of SignedData is that there appear // to be varying implementations... // for the moment we ignore anything which doesn't fit. // if (o is Asn1TaggedObject) { Asn1TaggedObject tagged = (Asn1TaggedObject)o; switch (tagged.TagNo) { case 0: certsBer = tagged is BerTaggedObject; certificates = Asn1Set.GetInstance(tagged, false); break; case 1: crlsBer = tagged is BerTaggedObject; crls = Asn1Set.GetInstance(tagged, false); break; default: throw new ArgumentException("unknown tag value " + tagged.TagNo); } } else { signerInfos = (Asn1Set) o; } } } public DerInteger Version { get { return version; } } public Asn1Set DigestAlgorithms { get { return digestAlgorithms; } } public ContentInfo EncapContentInfo { get { return contentInfo; } } public Asn1Set Certificates { get { return certificates; } } public Asn1Set CRLs { get { return crls; } } public Asn1Set SignerInfos { get { return signerInfos; } } /** * Produce an object suitable for an Asn1OutputStream. * <pre> * SignedData ::= Sequence { * version CMSVersion, * digestAlgorithms DigestAlgorithmIdentifiers, * encapContentInfo EncapsulatedContentInfo, * certificates [0] IMPLICIT CertificateSet OPTIONAL, * crls [1] IMPLICIT CertificateRevocationLists OPTIONAL, * signerInfos SignerInfos * } * </pre> */ public override Asn1Object ToAsn1Object() { Asn1EncodableVector v = new Asn1EncodableVector( version, digestAlgorithms, contentInfo); if (certificates != null) { if (certsBer) { v.Add(new BerTaggedObject(false, 0, certificates)); } else { v.Add(new DerTaggedObject(false, 0, certificates)); } } if (crls != null) { if (crlsBer) { v.Add(new BerTaggedObject(false, 1, crls)); } else { v.Add(new DerTaggedObject(false, 1, crls)); } } v.Add(signerInfos); return new BerSequence(v); } } }
// 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.Globalization; using System.IO; using System.Reflection; using System.Security; using Xunit; [assembly: System.Reflection.CustomAttributesTests.Data.Attr(77, name = "AttrSimple")] [assembly: System.Reflection.CustomAttributesTests.Data.Int32Attr(77, name = "Int32AttrSimple"), System.Reflection.CustomAttributesTests.Data.Int64Attr((Int64)77, name = "Int64AttrSimple"), System.Reflection.CustomAttributesTests.Data.StringAttr("hello", name = "StringAttrSimple"), System.Reflection.CustomAttributesTests.Data.EnumAttr(System.Reflection.CustomAttributesTests.Data.MyColorEnum.RED, name = "EnumAttrSimple"), System.Reflection.CustomAttributesTests.Data.TypeAttr(typeof(Object), name = "TypeAttrSimple")] [assembly: System.Runtime.CompilerServices.CompilationRelaxationsAttribute((Int32)8)] [assembly: System.Diagnostics.Debuggable((System.Diagnostics.DebuggableAttribute.DebuggingModes)263)] [assembly: System.CLSCompliant(false)] namespace System.Reflection.Tests { public class AssemblyTests : FileCleanupTestBase { private string SourceTestAssemblyPath { get; } = Path.Combine(Environment.CurrentDirectory, "TestAssembly.dll"); private string DestTestAssemblyPath { get; } private string LoadFromTestPath { get; } public AssemblyTests() { // Assembly.Location not supported (properly) on uapaot. DestTestAssemblyPath = Path.Combine(base.TestDirectory, "TestAssembly.dll"); LoadFromTestPath = Path.Combine(base.TestDirectory, "System.Runtime.Tests.dll"); // There is no dll to copy in ILC runs if (!PlatformDetection.IsNetNative) { File.Copy(SourceTestAssemblyPath, DestTestAssemblyPath); string currAssemblyPath = Path.Combine(Environment.CurrentDirectory, "System.Runtime.Tests.dll"); File.Copy(currAssemblyPath, LoadFromTestPath, true); } } public static IEnumerable<object[]> Equality_TestData() { yield return new object[] { Assembly.Load(new AssemblyName(typeof(int).GetTypeInfo().Assembly.FullName)), Assembly.Load(new AssemblyName(typeof(int).GetTypeInfo().Assembly.FullName)), true }; yield return new object[] { Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)), Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)), true }; yield return new object[] { Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)), typeof(AssemblyTests).Assembly, false }; } [Theory] [MemberData(nameof(Equality_TestData))] public void Equality(Assembly assembly1, Assembly assembly2, bool expected) { Assert.Equal(expected, assembly1 == assembly2); Assert.NotEqual(expected, assembly1 != assembly2); } [Fact] public void GetAssembly_Nullery() { AssertExtensions.Throws<ArgumentNullException>("type", () => Assembly.GetAssembly(null)); } public static IEnumerable<object[]> GetAssembly_TestData() { yield return new object[] { Assembly.Load(new AssemblyName(typeof(HashSet<int>).GetTypeInfo().Assembly.FullName)), Assembly.GetAssembly(typeof(HashSet<int>)), true }; yield return new object[] { Assembly.Load(new AssemblyName(typeof(int).GetTypeInfo().Assembly.FullName)), Assembly.GetAssembly(typeof(int)), true }; yield return new object[] { typeof(AssemblyTests).Assembly, Assembly.GetAssembly(typeof(AssemblyTests)), true }; } [Theory] [MemberData(nameof(GetAssembly_TestData))] public void GetAssembly(Assembly assembly1, Assembly assembly2, bool expected) { Assert.Equal(expected, assembly1.Equals(assembly2)); } public static IEnumerable<object[]> GetCallingAssembly_TestData() { yield return new object[] { typeof(AssemblyTests).Assembly, GetGetCallingAssembly(), true }; yield return new object[] { Assembly.GetCallingAssembly(), GetGetCallingAssembly(), false }; } [Theory] [MemberData(nameof(GetCallingAssembly_TestData))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "GetCallingAssembly() is not supported on UapAot")] public void GetCallingAssembly(Assembly assembly1, Assembly assembly2, bool expected) { Assert.Equal(expected, assembly1.Equals(assembly2)); } [Fact] public void GetExecutingAssembly() { Assert.True(typeof(AssemblyTests).Assembly.Equals(Assembly.GetExecutingAssembly())); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.GetSatelliteAssembly() not supported on UapAot")] public void GetSatelliteAssemblyNeg() { Assert.Throws<ArgumentNullException>(() => (typeof(AssemblyTests).Assembly.GetSatelliteAssembly(null))); Assert.Throws<System.IO.FileNotFoundException>(() => (typeof(AssemblyTests).Assembly.GetSatelliteAssembly(CultureInfo.InvariantCulture))); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.Load(String) not supported on UapAot")] public void AssemblyLoadFromString() { AssemblyName an = typeof(AssemblyTests).Assembly.GetName(); string fullName = an.FullName; string simpleName = an.Name; Assembly a1 = Assembly.Load(fullName); Assert.NotNull(a1); Assert.Equal(fullName, a1.GetName().FullName); Assembly a2 = Assembly.Load(simpleName); Assert.NotNull(a2); Assert.Equal(fullName, a2.GetName().FullName); } [Fact] public void AssemblyLoadFromStringNeg() { Assert.Throws<ArgumentNullException>(() => Assembly.Load((string)null)); Assert.Throws<ArgumentException>(() => Assembly.Load(string.Empty)); string emptyCName = new string('\0', 1); Assert.Throws<ArgumentException>(() => Assembly.Load(emptyCName)); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Assembly.Load(byte[]) not supported on UapAot")] public void AssemblyLoadFromBytes() { Assembly assembly = typeof(AssemblyTests).Assembly; byte[] aBytes = System.IO.File.ReadAllBytes(assembly.Location); Assembly loadedAssembly = Assembly.Load(aBytes); Assert.NotNull(loadedAssembly); Assert.Equal(assembly.FullName, loadedAssembly.FullName); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Assembly.Load(byte[]) not supported on UapAot")] public void AssemblyLoadFromBytesNeg() { Assert.Throws<ArgumentNullException>(() => Assembly.Load((byte[])null)); Assert.Throws<BadImageFormatException>(() => Assembly.Load(new byte[0])); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Assembly.Load(byte[]) not supported on UapAot")] public void AssemblyLoadFromBytesWithSymbols() { Assembly assembly = typeof(AssemblyTests).Assembly; byte[] aBytes = System.IO.File.ReadAllBytes(assembly.Location); byte[] symbols = System.IO.File.ReadAllBytes((System.IO.Path.ChangeExtension(assembly.Location, ".pdb"))); Assembly loadedAssembly = Assembly.Load(aBytes, symbols); Assert.NotNull(loadedAssembly); Assert.Equal(assembly.FullName, loadedAssembly.FullName); } [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Assembly.ReflectionOnlyLoad() not supported on UapAot")] public void AssemblyReflectionOnlyLoadFromString() { AssemblyName an = typeof(AssemblyTests).Assembly.GetName(); Assert.Throws<NotSupportedException>(() => Assembly.ReflectionOnlyLoad(an.FullName)); } [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Assembly.ReflectionOnlyLoad() not supported on UapAot")] public void AssemblyReflectionOnlyLoadFromBytes() { Assembly assembly = typeof(AssemblyTests).Assembly; byte[] aBytes = System.IO.File.ReadAllBytes(assembly.Location); Assert.Throws<NotSupportedException>(() => Assembly.ReflectionOnlyLoad(aBytes)); } [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Assembly.ReflectionOnlyLoad() not supported on UapAot")] public void AssemblyReflectionOnlyLoadFromNeg() { Assert.Throws<ArgumentNullException>(() => Assembly.ReflectionOnlyLoad((string)null)); Assert.Throws<ArgumentException>(() => Assembly.ReflectionOnlyLoad(string.Empty)); Assert.Throws<ArgumentNullException>(() => Assembly.ReflectionOnlyLoad((byte[])null)); } public static IEnumerable<object[]> GetModules_TestData() { yield return new object[] { LoadSystemCollectionsAssembly() }; yield return new object[] { LoadSystemReflectionAssembly() }; } [Theory] [MemberData(nameof(GetModules_TestData))] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.GetModules() is not supported on UapAot.")] public void GetModules_GetModule(Assembly assembly) { Assert.NotEmpty(assembly.GetModules()); foreach (Module module in assembly.GetModules()) { Assert.Equal(module, assembly.GetModule(module.ToString())); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.GetLoadedModules() is not supported on UapAot.")] public void GetLoadedModules() { Assembly assembly = typeof(AssemblyTests).Assembly; Assert.NotEmpty(assembly.GetLoadedModules()); foreach (Module module in assembly.GetLoadedModules()) { Assert.NotNull(module); Assert.Equal(module, assembly.GetModule(module.ToString())); } } public static IEnumerable<object[]> CreateInstance_TestData() { yield return new object[] { typeof(AssemblyTests).Assembly, typeof(AssemblyPublicClass).FullName, BindingFlags.CreateInstance, typeof(AssemblyPublicClass) }; yield return new object[] { typeof(int).Assembly, typeof(int).FullName, BindingFlags.Default, typeof(int) }; yield return new object[] { typeof(int).Assembly, typeof(Dictionary<int, string>).FullName, BindingFlags.Default, typeof(Dictionary<int, string>) }; } [Theory] [MemberData(nameof(CreateInstance_TestData))] public void CreateInstance(Assembly assembly, string typeName, BindingFlags bindingFlags, Type expectedType) { Assert.IsType(expectedType, assembly.CreateInstance(typeName, true, bindingFlags, null, null, null, null)); Assert.IsType(expectedType, assembly.CreateInstance(typeName, false, bindingFlags, null, null, null, null)); } public static IEnumerable<object[]> CreateInstance_Invalid_TestData() { yield return new object[] { "", typeof(ArgumentException) }; yield return new object[] { null, typeof(ArgumentNullException) }; yield return new object[] { typeof(AssemblyClassWithPrivateCtor).FullName, typeof(MissingMethodException) }; } [Theory] [MemberData(nameof(CreateInstance_Invalid_TestData))] public void CreateInstance_Invalid(string typeName, Type exceptionType) { Assembly assembly = typeof(AssemblyTests).Assembly; Assert.Throws(exceptionType, () => assembly.CreateInstance(typeName, true, BindingFlags.Public, null, null, null, null)); Assert.Throws(exceptionType, () => assembly.CreateInstance(typeName, false, BindingFlags.Public, null, null, null, null)); } [Fact] public void GetManifestResourceStream() { Assert.NotNull(typeof(AssemblyTests).Assembly.GetManifestResourceStream(typeof(AssemblyTests), "EmbeddedImage.png")); Assert.NotNull(typeof(AssemblyTests).Assembly.GetManifestResourceStream(typeof(AssemblyTests), "EmbeddedTextFile.txt")); Assert.Null(typeof(AssemblyTests).Assembly.GetManifestResourceStream(typeof(AssemblyTests), "IDontExist")); } [Fact] public void Test_GlobalAssemblyCache() { Assert.False(typeof(AssemblyTests).Assembly.GlobalAssemblyCache); } [Fact] public void Test_HostContext() { Assert.Equal(0, typeof(AssemblyTests).Assembly.HostContext); } [Fact] public void Test_IsFullyTrusted() { Assert.True(typeof(AssemblyTests).Assembly.IsFullyTrusted); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "The full .NET Framework supports SecurityRuleSet")] public void Test_SecurityRuleSet_Netcore() { Assert.Equal(SecurityRuleSet.None, typeof(AssemblyTests).Assembly.SecurityRuleSet); } [Fact] [SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "SecurityRuleSet is ignored in .NET Core")] public void Test_SecurityRuleSet_Netfx() { Assert.Equal(SecurityRuleSet.Level2, typeof(AssemblyTests).Assembly.SecurityRuleSet); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Assembly.LoadFile() not supported on UapAot")] public void Test_LoadFile() { Assembly currentAssembly = typeof(AssemblyTests).Assembly; const string RuntimeTestsDll = "System.Runtime.Tests.dll"; string fullRuntimeTestsPath = Path.GetFullPath(RuntimeTestsDll); var loadedAssembly1 = Assembly.LoadFile(fullRuntimeTestsPath); if (PlatformDetection.IsFullFramework) { Assert.Equal(currentAssembly, loadedAssembly1); } else { Assert.NotEqual(currentAssembly, loadedAssembly1); } string dir = Path.GetDirectoryName(fullRuntimeTestsPath); fullRuntimeTestsPath = Path.Combine(dir, ".", RuntimeTestsDll); Assembly loadedAssembly2 = Assembly.LoadFile(fullRuntimeTestsPath); if (PlatformDetection.IsFullFramework) { Assert.NotEqual(loadedAssembly1, loadedAssembly2); } else { Assert.Equal(loadedAssembly1, loadedAssembly2); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.Uap, "The full .NET Framework has a bug and throws a NullReferenceException")] public void LoadFile_NullPath_Netcore_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("path", () => Assembly.LoadFile(null)); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Assembly.LoadFile() not supported on UapAot")] public void LoadFile_NoSuchPath_ThrowsArgumentException() { Assert.Throws<ArgumentException>(() => Assembly.LoadFile("System.Runtime.Tests.dll")); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.UapAot, "The full .NET Framework supports Assembly.LoadFrom")] public void Test_LoadFromUsingHashValue_Netcore() { Assert.Throws<NotSupportedException>(() => Assembly.LoadFrom("abc", null, System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA1)); } [Fact] [SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "The implementation of Assembly.LoadFrom is stubbed out in .NET Core")] public void Test_LoadFromUsingHashValue_Netfx() { Assert.Throws<FileNotFoundException>(() => Assembly.LoadFrom("abc", null, System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA1)); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.UapAot, "The full .NET Framework supports more than one module per assembly")] public void Test_LoadModule_Netcore() { Assembly assembly = typeof(AssemblyTests).Assembly; Assert.Throws<NotImplementedException>(() => assembly.LoadModule("abc", null)); Assert.Throws<NotImplementedException>(() => assembly.LoadModule("abc", null, null)); } [Fact] [SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "The coreclr doesn't support more than one module per assembly")] public void Test_LoadModule_Netfx() { Assembly assembly = typeof(AssemblyTests).Assembly; AssertExtensions.Throws<ArgumentNullException>(null, () => assembly.LoadModule("abc", null)); AssertExtensions.Throws<ArgumentNullException>(null, () => assembly.LoadModule("abc", null, null)); } #pragma warning disable 618 [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.LoadFromWithPartialName() not supported on UapAot")] public void Test_LoadWithPartialName() { string simplename = typeof(AssemblyTests).Assembly.GetName().Name; var assem = Assembly.LoadWithPartialName(simplename); Assert.Equal(typeof(AssemblyTests).Assembly, assem); } #pragma warning restore 618 [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.LoadFrom() not supported on UapAot")] public void LoadFrom_SamePath_ReturnsEqualAssemblies() { Assembly assembly1 = Assembly.LoadFrom(DestTestAssemblyPath); Assembly assembly2 = Assembly.LoadFrom(DestTestAssemblyPath); Assert.Equal(assembly1, assembly2); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.LoadFrom() not supported on UapAot")] public void LoadFrom_SameIdentityAsAssemblyWithDifferentPath_ReturnsEqualAssemblies() { Assembly assembly1 = Assembly.LoadFrom(typeof(AssemblyTests).Assembly.Location); Assert.Equal(assembly1, typeof(AssemblyTests).Assembly); Assembly assembly2 = Assembly.LoadFrom(LoadFromTestPath); if (PlatformDetection.IsFullFramework) { Assert.NotEqual(assembly1, assembly2); } else { Assert.Equal(assembly1, assembly2); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.LoadFrom() not supported on UapAot")] public void LoadFrom_NullAssemblyFile_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("assemblyFile", () => Assembly.LoadFrom(null)); AssertExtensions.Throws<ArgumentNullException>("assemblyFile", () => Assembly.UnsafeLoadFrom(null)); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.LoadFrom() not supported on UapAot")] public void LoadFrom_EmptyAssemblyFile_ThrowsArgumentException() { Assert.Throws<ArgumentException>((() => Assembly.LoadFrom(""))); Assert.Throws<ArgumentException>((() => Assembly.UnsafeLoadFrom(""))); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.LoadFrom() not supported on UapAot")] public void LoadFrom_NoSuchFile_ThrowsFileNotFoundException() { Assert.Throws<FileNotFoundException>(() => Assembly.LoadFrom("NoSuchPath")); Assert.Throws<FileNotFoundException>(() => Assembly.UnsafeLoadFrom("NoSuchPath")); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.UnsafeLoadFrom() not supported on UapAot")] public void UnsafeLoadFrom_SamePath_ReturnsEqualAssemblies() { Assembly assembly1 = Assembly.UnsafeLoadFrom(DestTestAssemblyPath); Assembly assembly2 = Assembly.UnsafeLoadFrom(DestTestAssemblyPath); Assert.Equal(assembly1, assembly2); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework | TargetFrameworkMonikers.UapAot, "The implementation of LoadFrom(string, byte[], AssemblyHashAlgorithm is not supported in .NET Core.")] public void LoadFrom_WithHashValue_NetCoreCore_ThrowsNotSupportedException() { Assert.Throws<NotSupportedException>(() => Assembly.LoadFrom(DestTestAssemblyPath, new byte[0], Configuration.Assemblies.AssemblyHashAlgorithm.None)); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.GetFile() not supported on UapAot")] public void GetFile() { Assert.Throws<ArgumentNullException>(() => typeof(AssemblyTests).Assembly.GetFile(null)); Assert.Throws<ArgumentException>(() => typeof(AssemblyTests).Assembly.GetFile("")); Assert.Null(typeof(AssemblyTests).Assembly.GetFile("NonExistentfile.dll")); Assert.NotNull(typeof(AssemblyTests).Assembly.GetFile("System.Runtime.Tests.dll")); Assert.Equal(typeof(AssemblyTests).Assembly.GetFile("System.Runtime.Tests.dll").Name, typeof(AssemblyTests).Assembly.Location); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.GetFiles() not supported on UapAot")] public void GetFiles() { Assert.NotNull(typeof(AssemblyTests).Assembly.GetFiles()); Assert.Equal(typeof(AssemblyTests).Assembly.GetFiles().Length, 1); Assert.Equal(typeof(AssemblyTests).Assembly.GetFiles()[0].Name, typeof(AssemblyTests).Assembly.Location); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Assembly.CodeBase not supported on UapAot")] public void Load_AssemblyNameWithCodeBase() { AssemblyName an = typeof(AssemblyTests).Assembly.GetName(); Assert.NotNull(an.CodeBase); Assembly a = Assembly.Load(an); Assert.Equal(a, typeof(AssemblyTests).Assembly); } // Helpers private static Assembly GetGetCallingAssembly() { return Assembly.GetCallingAssembly(); } private static Assembly LoadSystemCollectionsAssembly() { // Force System.collections to be linked statically List<int> li = new List<int>(); li.Add(1); return Assembly.Load(new AssemblyName(typeof(List<int>).GetTypeInfo().Assembly.FullName)); } private static Assembly LoadSystemReflectionAssembly() { // Force System.Reflection to be linked statically return Assembly.Load(new AssemblyName(typeof(AssemblyName).GetTypeInfo().Assembly.FullName)); } public class AssemblyPublicClass { public class PublicNestedClass { } } private static class AssemblyPrivateClass { } public class AssemblyClassWithPrivateCtor { private AssemblyClassWithPrivateCtor() { } } } public class AssemblyCustomAttributeTest { [Fact] public void Test_Int32AttrSimple() { bool result = false; Type attrType = typeof(System.Reflection.CustomAttributesTests.Data.Int32Attr); string attrstr = "[System.Reflection.CustomAttributesTests.Data.Int32Attr((Int32)77, name = \"Int32AttrSimple\")]"; result = VerifyCustomAttribute(attrType, attrstr); Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType)); } [Fact] public void Test_Int64Attr() { bool result = false; Type attrType = typeof(System.Reflection.CustomAttributesTests.Data.Int64Attr); string attrstr = "[System.Reflection.CustomAttributesTests.Data.Int64Attr((Int64)77, name = \"Int64AttrSimple\")]"; result = VerifyCustomAttribute(attrType, attrstr); Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType)); } [Fact] public void Test_StringAttr() { bool result = false; Type attrType = typeof(System.Reflection.CustomAttributesTests.Data.StringAttr); string attrstr = "[System.Reflection.CustomAttributesTests.Data.StringAttr(\"hello\", name = \"StringAttrSimple\")]"; result = VerifyCustomAttribute(attrType, attrstr); Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType)); } [Fact] public void Test_EnumAttr() { bool result = false; Type attrType = typeof(System.Reflection.CustomAttributesTests.Data.EnumAttr); string attrstr = "[System.Reflection.CustomAttributesTests.Data.EnumAttr((System.Reflection.CustomAttributesTests.Data.MyColorEnum)1, name = \"EnumAttrSimple\")]"; result = VerifyCustomAttribute(attrType, attrstr); Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType)); } [Fact] public void Test_TypeAttr() { bool result = false; Type attrType = typeof(System.Reflection.CustomAttributesTests.Data.TypeAttr); string attrstr = "[System.Reflection.CustomAttributesTests.Data.TypeAttr(typeof(System.Object), name = \"TypeAttrSimple\")]"; result = VerifyCustomAttribute(attrType, attrstr); Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType)); } [Fact] public void Test_CompilationRelaxationsAttr() { bool result = false; Type attrType = typeof(System.Runtime.CompilerServices.CompilationRelaxationsAttribute); string attrstr = "[System.Runtime.CompilerServices.CompilationRelaxationsAttribute((Int32)8)]"; result = VerifyCustomAttribute(attrType, attrstr); Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType)); } [Fact] public void Test_AssemblyIdentityAttr() { bool result = false; Type attrType = typeof(System.Reflection.AssemblyTitleAttribute); string attrstr = "[System.Reflection.AssemblyTitleAttribute(\"System.Reflection.Tests\")]"; result = VerifyCustomAttribute(attrType, attrstr); Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType)); } [Fact] public void Test_AssemblyDescriptionAttribute() { bool result = false; Type attrType = typeof(System.Reflection.AssemblyDescriptionAttribute); string attrstr = "[System.Reflection.AssemblyDescriptionAttribute(\"System.Reflection.Tests\")]"; result = VerifyCustomAttribute(attrType, attrstr); Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType)); } [Fact] public void Test_AssemblyCompanyAttribute() { bool result = false; Type attrType = typeof(System.Reflection.AssemblyCompanyAttribute); string attrstr = "[System.Reflection.AssemblyCompanyAttribute(\"Microsoft Corporation\")]"; result = VerifyCustomAttribute(attrType, attrstr); Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType)); } [Fact] public void Test_CLSCompliantAttribute() { bool result = false; Type attrType = typeof(System.CLSCompliantAttribute); string attrstr = "[System.CLSCompliantAttribute((Boolean)True)]"; result = VerifyCustomAttribute(attrType, attrstr); Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType)); } [Fact] public void Test_DebuggableAttribute() { bool result = false; Type attrType = typeof(System.Diagnostics.DebuggableAttribute); string attrstr = "[System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute+DebuggingModes)263)]"; result = VerifyCustomAttribute(attrType, attrstr); Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType)); } [Fact] public void Test_SimpleAttribute() { bool result = false; Type attrType = typeof(System.Reflection.CustomAttributesTests.Data.Attr); string attrstr = "[System.Reflection.CustomAttributesTests.Data.Attr((Int32)77, name = \"AttrSimple\")]"; result = VerifyCustomAttribute(attrType, attrstr); Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType)); } private bool VerifyCustomAttribute(Type type, String attributeStr) { Assembly asm = typeof(AssemblyCustomAttributeTest).Assembly; foreach (CustomAttributeData cad in asm.GetCustomAttributesData()) { if (cad.AttributeType.Equals(type)) { return true; } } return false; } } public class AssemblyTests_GetTYpe { [Fact] public void AssemblyGetTypeNoQualifierAllowed() { Assembly a = typeof(G<int>).Assembly; string s = typeof(G<int>).AssemblyQualifiedName; Assert.Throws<ArgumentException>(() => a.GetType(s, throwOnError: true, ignoreCase: false)); } [Fact] public void AssemblyGetTypeDoesntSearchMscorlib() { Assembly a = typeof(AssemblyTests_GetTYpe).Assembly; Assert.Throws<TypeLoadException>(() => a.GetType("System.Object", throwOnError: true, ignoreCase: false)); Assert.Throws<TypeLoadException>(() => a.GetType("G`1[[System.Object]]", throwOnError: true, ignoreCase: false)); } [Fact] public void AssemblyGetTypeDefaultsToItself() { Assembly a = typeof(AssemblyTests_GetTYpe).Assembly; Type t = a.GetType("G`1[[G`1[[System.Int32, mscorlib]]]]", throwOnError: true, ignoreCase: false); Assert.Equal(typeof(G<G<int>>), t); } } } internal class G<T> { }
// // Copyright (c) 2003-2006 Jaroslaw Kowalski <jaak@jkowalski.net> // Copyright (c) 2006-2014 Piotr Fusik <piotr@fusik.info> // // All rights reserved. // // 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. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR 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 Sooda.Schema; using System; using System.Globalization; using System.Text; namespace Sooda.QL { public class SoqlParser { private SqlTokenizer tokenizer = new SqlTokenizer(); private SoqlParser(string query) { tokenizer.InitTokenizer(query); } private SoqlFunctionCallExpression ParseFunctionCall(string functionName) { SoqlExpressionCollection par = new SoqlExpressionCollection(); while (!tokenizer.IsEOF() && tokenizer.TokenType != SoqlTokenType.RightParen) { par.Add(ParseExpression()); if (tokenizer.TokenType != SoqlTokenType.Comma) break; tokenizer.GetNextToken(); } tokenizer.Expect(SoqlTokenType.RightParen); return new SoqlFunctionCallExpression(functionName, par); } private SoqlQueryExpression ParseSimplifiedQuery(string fromClass, string alias) { SoqlQueryExpression query = new SoqlQueryExpression(); query.From.Add(fromClass); query.FromAliases.Add(String.Empty); tokenizer.ExpectKeyword("where"); query.WhereClause = ParseBooleanExpression(); return query; } private SoqlExpression ParsePathLikeExpression(string firstKeyword) { if (0 == String.Compare(firstKeyword, "soodaclass", true, System.Globalization.CultureInfo.InvariantCulture)) return new SoqlSoodaClassExpression(); SoqlPathExpression prop = new SoqlPathExpression(firstKeyword); while (tokenizer.TokenType == SoqlTokenType.Dot) { tokenizer.GetNextToken(); if (tokenizer.TokenType == SoqlTokenType.Asterisk) { tokenizer.GetNextToken(); return new SoqlAsteriskExpression(prop); } else if (tokenizer.IsKeyword("contains")) // lowercase { string collectionName = prop.PropertyName; tokenizer.EatKeyword(); if (tokenizer.TokenType != SoqlTokenType.LeftParen) throw new SoqlException("'(' expected on Contains()", tokenizer.TokenPosition); SoqlExpression expr = ParseLiteralExpression(); return new SoqlContainsExpression(prop.Left, collectionName, expr); } else if (tokenizer.IsKeyword("count")) // lowercase { string collectionName = prop.PropertyName; tokenizer.EatKeyword(); return new SoqlCountExpression(prop.Left, collectionName); } else if (tokenizer.IsKeyword("soodaclass")) // lowercase { tokenizer.EatKeyword(); return new SoqlSoodaClassExpression(prop); } else { string keyword = tokenizer.EatKeyword(); prop = new SoqlPathExpression(prop, keyword); } } if (tokenizer.TokenType == SoqlTokenType.LeftParen) { tokenizer.GetNextToken(); string functionName = prop.PropertyName; while ((prop = prop.Left) != null) functionName = prop.PropertyName + "." + functionName; if (0 == String.Compare(functionName, "rawquery", true, System.Globalization.CultureInfo.InvariantCulture)) return ParseRawExpression(); return ParseFunctionCall(functionName); } return prop; } private SoqlRawExpression ParseRawExpression() { StringBuilder sb = new StringBuilder(); int parenBalance = 0; bool iws = tokenizer.IgnoreWhiteSpace; tokenizer.IgnoreWhiteSpace = false; while (!tokenizer.IsEOF() && (tokenizer.TokenType != SoqlTokenType.RightParen || parenBalance > 0)) { sb.Append(tokenizer.TokenValue); if (tokenizer.TokenType == SoqlTokenType.LeftParen) parenBalance++; if (tokenizer.TokenType == SoqlTokenType.RightParen) parenBalance--; tokenizer.GetNextToken(); } tokenizer.IgnoreWhiteSpace = iws; tokenizer.Expect(SoqlTokenType.RightParen); return new SoqlRawExpression(sb.ToString()); } private SoqlExpression ParseLiteralExpression() { if (tokenizer.IsToken(SoqlTokenType.LeftParen)) { tokenizer.GetNextToken(); SoqlExpression e; if (tokenizer.IsKeyword("select")) e = ParseQuery(); else e = ParseExpression(); tokenizer.Expect(SoqlTokenType.RightParen); return e; }; if (tokenizer.IsNumber()) { string numberString = (string)tokenizer.TokenValue; tokenizer.GetNextToken(); if (numberString.IndexOf('.') >= 0) { return new SoqlLiteralExpression(Double.Parse(numberString, CultureInfo.InvariantCulture)); } else { return new SoqlLiteralExpression(Int32.Parse(numberString, CultureInfo.InvariantCulture)); } } if (tokenizer.TokenType == SoqlTokenType.String) { SoqlExpression e = new SoqlLiteralExpression(tokenizer.StringTokenValue); tokenizer.GetNextToken(); return e; } if (tokenizer.TokenType == SoqlTokenType.LeftCurlyBrace) { tokenizer.GetNextToken(); int val = Int32.Parse((string)tokenizer.TokenValue); tokenizer.GetNextToken(); if (tokenizer.TokenType == SoqlTokenType.Colon) { tokenizer.GetNextToken(); SoqlLiteralValueModifiers modifiers = ParseLiteralValueModifiers(); tokenizer.Expect(SoqlTokenType.RightCurlyBrace); return new SoqlParameterLiteralExpression(val, modifiers); } else { tokenizer.Expect(SoqlTokenType.RightCurlyBrace); return new SoqlParameterLiteralExpression(val); } } if (tokenizer.TokenType == SoqlTokenType.Asterisk) { tokenizer.GetNextToken(); return new SoqlAsteriskExpression(null); } if (tokenizer.TokenType == SoqlTokenType.Keyword) { string keyword = tokenizer.EatKeyword(); if (0 == String.Compare(keyword, "not", true, System.Globalization.CultureInfo.InvariantCulture)) return new SoqlBooleanNegationExpression((SoqlBooleanExpression)ParseBooleanPredicate()); if (0 == String.Compare(keyword, "null", true, System.Globalization.CultureInfo.InvariantCulture)) return new SoqlNullLiteral(); if (0 == String.Compare(keyword, "true", true, System.Globalization.CultureInfo.InvariantCulture)) return new SoqlBooleanLiteralExpression(true); if (0 == String.Compare(keyword, "false", true, System.Globalization.CultureInfo.InvariantCulture)) return new SoqlBooleanLiteralExpression(false); /*if (tokenizer.IsKeyword("as")) { tokenizer.GetNextToken(); string alias = tokenizer.EatKeyword(); string className = keyword; return ParseSimplifiedQuery(className, alias); } */ if (tokenizer.IsKeyword("where")) { // className WHERE expr return ParseSimplifiedQuery(keyword, String.Empty); } return ParsePathLikeExpression(keyword); } if (tokenizer.TokenType == SoqlTokenType.Sub) { tokenizer.GetNextToken(); return new SoqlUnaryNegationExpression(ParseLiteralExpression()); } throw new SoqlException("Unexpected token: " + tokenizer.TokenValue, tokenizer.TokenPosition); } private SoqlExpression ParseMultiplicativeException() { SoqlExpression e = ParseLiteralExpression(); while (true) { if (tokenizer.IsToken(SoqlTokenType.Mul)) { tokenizer.GetNextToken(); e = new SoqlBinaryExpression(e, ParseLiteralExpression(), SoqlBinaryOperator.Mul); } else if (tokenizer.IsToken(SoqlTokenType.Div)) { tokenizer.GetNextToken(); e = new SoqlBinaryExpression(e, ParseLiteralExpression(), SoqlBinaryOperator.Div); } else if (tokenizer.IsToken(SoqlTokenType.Mod)) { tokenizer.GetNextToken(); e = new SoqlBinaryExpression(e, ParseLiteralExpression(), SoqlBinaryOperator.Mod); } else break; } return e; } private SoqlExpression ParseAdditiveExpression() { SoqlExpression e = ParseMultiplicativeException(); while (true) { if (tokenizer.IsToken(SoqlTokenType.Add)) { tokenizer.GetNextToken(); e = new SoqlBinaryExpression(e, ParseMultiplicativeException(), SoqlBinaryOperator.Add); } else if (tokenizer.IsToken(SoqlTokenType.Sub)) { tokenizer.GetNextToken(); e = new SoqlBinaryExpression(e, ParseMultiplicativeException(), SoqlBinaryOperator.Sub); } else break; } return e; } private SoqlExpression ParseInExpression(SoqlExpression lhs) { SoqlExpressionCollection rhs = new SoqlExpressionCollection(); tokenizer.ExpectKeyword("in"); tokenizer.Expect(SoqlTokenType.LeftParen); if (!tokenizer.IsToken(SoqlTokenType.RightParen)) { rhs.Add(ParseAdditiveExpression()); while (tokenizer.TokenType == SoqlTokenType.Comma) { tokenizer.Expect(SoqlTokenType.Comma); rhs.Add(ParseAdditiveExpression()); } } tokenizer.Expect(SoqlTokenType.RightParen); return new SoqlBooleanInExpression(lhs, rhs); } private SoqlExpression ParseBooleanRelation() { SoqlExpression e = ParseAdditiveExpression(); if (tokenizer.IsToken(SoqlTokenType.EQ)) { tokenizer.GetNextToken(); return new SoqlBooleanRelationalExpression(e, ParseAdditiveExpression(), SoqlRelationalOperator.Equal); }; if (tokenizer.IsToken(SoqlTokenType.NE)) { tokenizer.GetNextToken(); return new SoqlBooleanRelationalExpression(e, ParseAdditiveExpression(), SoqlRelationalOperator.NotEqual); }; if (tokenizer.IsToken(SoqlTokenType.LT)) { tokenizer.GetNextToken(); return new SoqlBooleanRelationalExpression(e, ParseAdditiveExpression(), SoqlRelationalOperator.Less); }; if (tokenizer.IsToken(SoqlTokenType.GT)) { tokenizer.GetNextToken(); return new SoqlBooleanRelationalExpression(e, ParseAdditiveExpression(), SoqlRelationalOperator.Greater); }; if (tokenizer.IsToken(SoqlTokenType.LE)) { tokenizer.GetNextToken(); return new SoqlBooleanRelationalExpression(e, ParseAdditiveExpression(), SoqlRelationalOperator.LessOrEqual); }; if (tokenizer.IsToken(SoqlTokenType.GE)) { tokenizer.GetNextToken(); return new SoqlBooleanRelationalExpression(e, ParseAdditiveExpression(), SoqlRelationalOperator.GreaterOrEqual); }; if (tokenizer.IsKeyword("like")) { tokenizer.GetNextToken(); return new SoqlBooleanRelationalExpression(e, ParseAdditiveExpression(), SoqlRelationalOperator.Like); } if (tokenizer.IsKeyword("is")) { bool notnull = false; tokenizer.GetNextToken(); if (tokenizer.IsKeyword("not")) { notnull = true; tokenizer.GetNextToken(); } tokenizer.ExpectKeyword("null"); return new SoqlBooleanIsNullExpression(e, notnull); } if (tokenizer.IsKeyword("in")) { return ParseInExpression(e); } return e; } private SoqlExpression ParseBooleanPredicate() { if (tokenizer.IsKeyword("exists")) { SoqlQueryExpression query; tokenizer.GetNextToken(); tokenizer.Expect(SoqlTokenType.LeftParen); if (tokenizer.IsKeyword("select")) { query = ParseQuery(); } else { query = new SoqlQueryExpression(); query.SelectExpressions.Add(new SoqlAsteriskExpression(null)); query.SelectAliases.Add(String.Empty); ParseFrom(query); tokenizer.ExpectKeyword("where"); query.WhereClause = ParseBooleanExpression(); } tokenizer.Expect(SoqlTokenType.RightParen); return new SoqlExistsExpression(query); } return ParseBooleanRelation(); } private SoqlExpression ParseBooleanAnd() { SoqlExpression e = ParseBooleanPredicate(); while (tokenizer.IsKeyword("and") || tokenizer.IsToken(SoqlTokenType.And)) { tokenizer.GetNextToken(); e = new SoqlBooleanAndExpression((SoqlBooleanExpression)e, (SoqlBooleanExpression)ParseBooleanPredicate()); } return e; } private SoqlExpression ParseBooleanOr() { SoqlExpression e = ParseBooleanAnd(); while (tokenizer.IsKeyword("or") || tokenizer.IsToken(SoqlTokenType.Or)) { tokenizer.GetNextToken(); e = new SoqlBooleanOrExpression((SoqlBooleanExpression)e, (SoqlBooleanExpression)ParseBooleanAnd()); } return e; } private SoqlBooleanExpression ParseBooleanExpression() { SoqlExpression expr = ParseBooleanOr(); if (!(expr is SoqlBooleanExpression)) { throw new SoqlException("Boolean expected"); } return (SoqlBooleanExpression)expr; } private SoqlExpression ParseExpression() { return ParseBooleanOr(); } private void ParseSelectExpressions(SoqlQueryExpression query) { for (;;) { SoqlExpression expr = ParseExpression(); string alias; if (tokenizer.IsKeyword("as")) { tokenizer.EatKeyword(); alias = tokenizer.EatKeyword(); } else { alias = String.Empty; } query.SelectExpressions.Add(expr); query.SelectAliases.Add(alias); if (!tokenizer.IsToken(SoqlTokenType.Comma)) break; tokenizer.GetNextToken(); } } private void ParseGroupByExpressions(SoqlQueryExpression query) { tokenizer.ExpectKeyword("group"); tokenizer.ExpectKeyword("by"); for (;;) { SoqlExpression expr = ParseExpression(); query.GroupByExpressions.Add(expr); if (!tokenizer.IsToken(SoqlTokenType.Comma)) break; tokenizer.GetNextToken(); } } private void ParseOrderByExpressions(SoqlQueryExpression query) { tokenizer.ExpectKeyword("order"); tokenizer.ExpectKeyword("by"); for (;;) { SoqlExpression expr = ParseExpression(); string order = "asc"; if (tokenizer.IsKeyword("asc")) { order = "asc"; tokenizer.GetNextToken(); } else if (tokenizer.IsKeyword("desc")) { order = "desc"; tokenizer.GetNextToken(); } query.OrderByExpressions.Add(expr); query.OrderByOrder.Add(order); if (!tokenizer.IsToken(SoqlTokenType.Comma)) break; tokenizer.GetNextToken(); } } private void ParseFrom(SoqlQueryExpression query) { for (;;) { string tableName = tokenizer.EatKeyword(); string alias; if (tokenizer.IsKeyword("as")) { tokenizer.EatKeyword(); alias = tokenizer.EatKeyword(); } else if (tokenizer.IsEOF() || tokenizer.IsKeyword("where") || tokenizer.IsKeyword("group") || tokenizer.IsKeyword("order") || tokenizer.IsKeyword("having") || tokenizer.TokenType == SoqlTokenType.Comma) { alias = String.Empty; } else { alias = tokenizer.EatKeyword(); } query.From.Add(tableName); query.FromAliases.Add(alias); if (!tokenizer.IsToken(SoqlTokenType.Comma)) break; tokenizer.GetNextToken(); } } private SoqlQueryExpression ParseQuery() { SoqlQueryExpression query = new SoqlQueryExpression(); tokenizer.ExpectKeyword("select"); if (tokenizer.IsKeyword("top")) { tokenizer.EatKeyword(); query.PageCount = Convert.ToInt32(tokenizer.TokenValue); tokenizer.GetNextToken(); } if (tokenizer.IsKeyword("skip")) { tokenizer.EatKeyword(); query.StartIdx = Convert.ToInt32(tokenizer.TokenValue); tokenizer.GetNextToken(); } if (tokenizer.IsKeyword("distinct")) { tokenizer.EatKeyword(); query.Distinct = true; } ParseSelectExpressions(query); tokenizer.ExpectKeyword("from"); ParseFrom(query); if (tokenizer.IsKeyword("where")) { tokenizer.EatKeyword(); query.WhereClause = ParseBooleanExpression(); } if (tokenizer.IsKeyword("group")) { ParseGroupByExpressions(query); } if (tokenizer.IsKeyword("having")) { tokenizer.EatKeyword(); query.Having = ParseBooleanExpression(); } if (tokenizer.IsKeyword("order")) { ParseOrderByExpressions(query); } return query; } public static SoqlBooleanExpression ParseWhereClause(string whereClause) { SoqlBooleanExpression e = ParseBooleanExpression(whereClause); if (e == null) throw new SoqlException("Expression is not of boolean type"); return e; } private SoqlLiteralValueModifiers ParseLiteralValueModifiers() { SoqlLiteralValueModifiers retVal = new SoqlLiteralValueModifiers(); string typeName = tokenizer.EatKeyword(); FieldDataType typeOverride = (FieldDataType)FieldDataType.Parse(typeof(FieldDataType), typeName); retVal.DataTypeOverride = typeOverride; return retVal; } public static SoqlLiteralValueModifiers ParseLiteralValueModifiers(string expr) { SoqlParser parser = new SoqlParser(expr); SoqlLiteralValueModifiers e = parser.ParseLiteralValueModifiers(); if (!parser.tokenizer.IsEOF()) throw new SoqlException("Unexpected token: " + parser.tokenizer.TokenValue, parser.tokenizer.TokenPosition); return e; } public static SoqlExpression ParseExpression(string expr) { SoqlParser parser = new SoqlParser(expr); SoqlExpression e = parser.ParseExpression(); if (!parser.tokenizer.IsEOF()) throw new SoqlException("Unexpected token: " + parser.tokenizer.TokenValue, parser.tokenizer.TokenPosition); return e; } public static void ParseOrderBy(SoqlQueryExpression query, string expr) { SoqlParser parser = new SoqlParser(expr); parser.ParseOrderByExpressions(query); if (!parser.tokenizer.IsEOF()) throw new SoqlException("Unexpected token: " + parser.tokenizer.TokenValue, parser.tokenizer.TokenPosition); } public static SoqlBooleanExpression ParseBooleanExpression(string expr) { SoqlParser parser = new SoqlParser(expr); SoqlBooleanExpression e = parser.ParseBooleanExpression(); if (!parser.tokenizer.IsEOF()) throw new SoqlException("Unexpected token: " + parser.tokenizer.TokenValue, parser.tokenizer.TokenPosition); return e; } public static SoqlQueryExpression ParseQuery(string expr) { SoqlParser parser = new SoqlParser(expr); SoqlQueryExpression q = parser.ParseQuery(); if (!parser.tokenizer.IsEOF()) throw new SoqlException("Unexpected token: " + parser.tokenizer.TokenValue, parser.tokenizer.TokenPosition); return q; } } }
using System; using System.Diagnostics.CodeAnalysis; using NBitcoin; using NBitcoin.Crypto; using NBitcoin.Secp256k1; namespace WalletWasabi.Crypto { public class SchnorrBlinding { public class Requester { private Scalar _v = Scalar.Zero; private Scalar _c = Scalar.Zero; private Scalar _w = Scalar.Zero; public Requester() { } public uint256 BlindScript(PubKey signerPubKey, PubKey rPubKey, Script script) { var msg = new uint256(Hashes.SHA256(script.ToBytes())); return BlindMessage(msg, rPubKey, signerPubKey); } public uint256 BlindMessage(uint256 message, PubKey rpubkey, PubKey signerPubKey) { var ctx = new ECMultGenContext(); Span<byte> tmp = stackalloc byte[32]; if (!Context.Instance.TryCreatePubKey(signerPubKey.ToBytes(), out var signerECPubkey)) { throw new FormatException("Invalid signer pubkey."); } if (!Context.Instance.TryCreatePubKey(rpubkey.ToBytes(), out var rECPubKey)) { throw new FormatException("Invalid r pubkey."); } var p = signerECPubkey.Q; var r = rECPubKey.Q.ToGroupElementJacobian(); var t = FE.Zero; retry: RandomUtils.GetBytes(tmp); _v = new Scalar(tmp, out int overflow); if (overflow != 0 || _v.IsZero) { goto retry; } RandomUtils.GetBytes(tmp); _w = new Scalar(tmp, out overflow); if (overflow != 0 || _v.IsZero) { goto retry; } var a1 = ctx.MultGen(_v); var a2 = _w * p; var a = r.AddVariable(a1, out _).AddVariable(a2, out _).ToGroupElement(); t = a.x.Normalize(); if (t.IsZero) { goto retry; } using (var sha = new SHA256()) { message.ToBytes(tmp, false); sha.Write(tmp); t.WriteToSpan(tmp); sha.Write(tmp); sha.GetHash(tmp); } _c = new Scalar(tmp, out overflow); if (overflow != 0 || _c.IsZero) { goto retry; } var cp = _c + _w.Negate(); // this is sent to the signer (blinded message) if (cp.IsZero) { goto retry; } cp.WriteToSpan(tmp); return new uint256(tmp); } public UnblindedSignature UnblindSignature(uint256 blindSignature) { Span<byte> tmp = stackalloc byte[32]; blindSignature.ToBytes(tmp); var sp = new Scalar(tmp, out int overflow); if (sp.IsZero || overflow != 0) { throw new ArgumentException("Invalid blindSignature", nameof(blindSignature)); } var s = sp + _v; if (s.IsZero || s.IsOverflow) { throw new ArgumentException("Invalid blindSignature", nameof(blindSignature)); } return new UnblindedSignature(_c, s); } public uint256 BlindMessage(byte[] message, PubKey rpubKey, PubKey signerPubKey) { var msg = new uint256(Hashes.SHA256(message)); return BlindMessage(msg, rpubKey, signerPubKey); } } public class Signer { public Signer(Key key) { Key = key; } // The signer key used for signing public Key Key { get; } public uint256 Sign(uint256 blindedMessage, Key rKey) { Span<byte> tmp = stackalloc byte[32]; blindedMessage.ToBytes(tmp); var cp = new Scalar(tmp, out int overflow); if (cp.IsZero || overflow != 0) { throw new ArgumentException("Invalid blinded message.", nameof(blindedMessage)); } ECPrivKey? r = null; ECPrivKey? d = null; try { if (!Context.Instance.TryCreateECPrivKey(rKey.ToBytes(), out r)) { throw new FormatException("Invalid key."); } if (!Context.Instance.TryCreateECPrivKey(Key.ToBytes(), out d)) { throw new FormatException("Invalid key."); } var sp = r.sec + (cp * d.sec).Negate(); sp.WriteToSpan(tmp); return new uint256(tmp); } finally { r?.Dispose(); d?.Dispose(); } } public bool VerifyUnblindedSignature(UnblindedSignature signature, uint256 dataHash) { return VerifySignature(dataHash, signature, Key.PubKey); } public bool VerifyUnblindedSignature(UnblindedSignature signature, byte[] data) { var hash = new uint256(Hashes.SHA256(data)); return VerifySignature(hash, signature, Key.PubKey); } } public static bool VerifySignature(uint256 message, UnblindedSignature signature, PubKey signerPubKey) { if (!Context.Instance.TryCreatePubKey(signerPubKey.ToBytes(), out var signerECPubkey)) { throw new FormatException("Invalid signer pubkey."); } var p = signerECPubkey.Q; var sG = (signature.S * EC.G).ToGroupElement(); var cP = p * signature.C; var r = cP + sG; var t = r.ToGroupElement().x.Normalize(); using var sha = new SHA256(); Span<byte> tmp = stackalloc byte[32]; message.ToBytes(tmp, false); sha.Write(tmp); t.WriteToSpan(tmp); sha.Write(tmp); sha.GetHash(tmp); return new Scalar(tmp) == signature.C; } } }
// Copyright (C) 2014 dot42 // // Original filename: ConcurrentDictionary.cs // // 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.Collections.Generic; using Dot42.Collections; using Java.Util; using Java.Util.Concurrent; namespace System.Collections.Concurrent { public class ConcurrentDictionary<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>> { internal readonly ConcurrentHashMap<TKey, TValue> map; /// <summary> /// Default ctor /// </summary> public ConcurrentDictionary() { map = new ConcurrentHashMap<TKey, TValue>(); } /// <summary> /// Creates an Dictionary with the given capacity /// </summary> public ConcurrentDictionary(int capacity) { map = new ConcurrentHashMap<TKey, TValue>(capacity); } /// <summary> /// Default ctor /// </summary> public ConcurrentDictionary(Java.Util.IMap<TKey, TValue> source) { map = new ConcurrentHashMap<TKey, TValue>(source); } /// <summary> /// Default ctor /// </summary> public ConcurrentDictionary(IEqualityComparer<TKey> comparer) { map = new ConcurrentHashMap<TKey, TValue>(); } /// <summary> /// Gets the number of elements /// </summary> public int Count { get { return map.Size(); } } /// <summary> /// Gets or sets the value associated with the specified key. /// </summary> /// <param name="key"></param> /// <returns></returns> public TValue this[TKey key] { get { if (map.ContainsKey(key)) return map.Get(key); throw new KeyNotFoundException(); } set { map.Put(key, value); } } /// <summary> /// Add the given key and value to the dictionary. /// </summary> public bool TryAdd(TKey key, TValue value) { if (map.ContainsKey(key)) return false; map.Put(key, value); return true; } /// <summary> /// Removes the given key from the dictionary. /// </summary> public bool TryRemove(TKey key, out TValue value) { if (map.ContainsKey(key)) { value = map.Remove(key); return true; } value = default(TValue); return false; } /// <summary> /// Remove all entries /// </summary> public void Clear() { map.Clear(); } /// <summary> /// Does this dictionary contain an element with given key? /// </summary> public bool ContainsKey(TKey key) { return map.ContainsKey(key); } /// <summary> /// Does this dictionary contain an element with given key? /// </summary> public bool ContainsValue(TValue value) { return map.ContainsValue(value); } /// <summary> /// Try to get a value from this dictionary. /// </summary> public bool TryGetValue(TKey key, out TValue value) { if (map.ContainsKey(key)) { value = map.Get(key); return true; } value = default(TValue); return false; } /// <summary> /// Gets the comparer used to compare keys. /// </summary> public IEqualityComparer<TKey> Comparer { get { throw new NotImplementedException("System.Collections.Concurrent.ConcurrentDictionary.Comparer"); } } /// <summary> /// Gets an enummerator to enumerate over all elements in this sequence. /// </summary> /// <returns></returns> public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { foreach (var entry in new IterableWrapper<IMap_IEntry<TKey, TValue>>(map.EntrySet())) { yield return new KeyValuePair<TKey, TValue>(entry.Key, entry.Value); } } /// <summary> /// Gets an enummerator to enumerate over all elements in this sequence. /// </summary> /// <returns></returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /* /// <summary> /// Gets the keys of the collection. /// </summary> public ICollection<TKey> Keys { get { return new KeyCollection(this); } } /// <summary> /// Gets the values of the collection. /// </summary> public ICollection<TValue> Values { get { return new ValueCollection(this); } } public sealed class KeyCollection : Java.Util.ICollection<TKey> { private readonly Java.Util.ICollection<TKey> keys; /// <summary> /// Default ctor /// </summary> public KeyCollection(Java.Util.Dictionary<TKey, TValue> dictionary) { keys = dictionary.map.KeySet(); } /// <summary> /// Gets an enummerator to enumerate over all elements in this sequence. /// </summary> /// <returns></returns> public IEnumerator<TKey> GetEnumerator() { return new IteratorWrapper<TKey>(keys); } /// <summary> /// Gets an enummerator to enumerate over all elements in this sequence. /// </summary> /// <returns></returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public int Count { get { return keys.Size(); } } public bool IsReadOnly { get { return true; } } public void Add(TKey item) { keys.Add(item); } public void Clear() { keys.Clear(); } public bool Contains(TKey item) { return keys.Contains(item); } public bool Remove(TKey item) { return keys.Remove(item); } public void CopyTo(TKey[] array, int index) { var i = 0; foreach (var key in this) { array[index + i++] = key; } } public bool IsSynchronized { get { return true; } } public object SyncRoot { get { throw new NotImplementedException(); } } public void CopyTo(Array array, int index) { throw new NotImplementedException(); } } public sealed class ValueCollection : Java.Util.ICollection<TValue> { private readonly Java.Util.ICollection<TValue> values; /// <summary> /// Default ctor /// </summary> public ValueCollection(Java.Util.Dictionary<TKey, TValue> dictionary) { values = dictionary.map.Values(); } /// <summary> /// Gets an enummerator to enumerate over all elements in this sequence. /// </summary> /// <returns></returns> public IEnumerator<TValue> GetEnumerator() { return new IteratorWrapper<TValue>(values); } /// <summary> /// Gets an enummerator to enumerate over all elements in this sequence. /// </summary> /// <returns></returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public int Count { get { return values.Size(); } } public bool IsReadOnly { get { return true; } } public void Add(TValue item) { values.Add(item); } public void Clear() { values.Clear(); } public bool Contains(TValue item) { return values.Contains(item); } public bool Remove(TValue item) { return values.Remove(item); } public void CopyTo(TValue[] array, int index) { throw new NotImplementedException(); } public bool IsSynchronized { get { return false; } } public object SyncRoot { get { throw new NotImplementedException(); } } public void CopyTo(Array array, int index) { throw new NotImplementedException(); } } */ } }
/* * 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. */ using System; using PriorityQueue = Lucene.Net.Util.PriorityQueue; namespace Lucene.Net.Search { /// <summary> Expert: A hit queue for sorting by hits by terms in more than one field. /// Uses <code>FieldCache.DEFAULT</code> for maintaining /// internal term lookup tables. /// /// This class will not resolve SortField.AUTO types, and expects the type /// of all SortFields used for construction to already have been resolved. /// {@link SortField#DetectFieldType(IndexReader, String)} is a utility method which /// may be used for field type detection. /// /// <b>NOTE:</b> This API is experimental and might change in /// incompatible ways in the next release. /// /// </summary> /// <since> 2.9 /// </since> /// <version> $Id: /// </version> /// <seealso cref="Searcher.Search(Query,Filter,int,Sort)"> /// </seealso> /// <seealso cref="FieldCache"> /// </seealso> public abstract class FieldValueHitQueue:PriorityQueue { internal sealed class Entry { internal int slot; internal int docID; internal float score; internal Entry(int slot, int docID, float score) { this.slot = slot; this.docID = docID; this.score = score; } public override System.String ToString() { return "slot:" + slot + " docID:" + docID + " score=" + score; } } /// <summary> An implementation of {@link FieldValueHitQueue} which is optimized in case /// there is just one comparator. /// </summary> private sealed class OneComparatorFieldValueHitQueue:FieldValueHitQueue { private FieldComparator comparator; private int oneReverseMul; public OneComparatorFieldValueHitQueue(SortField[] fields, int size):base(fields) { if (fields.Length == 0) { throw new System.ArgumentException("Sort must contain at least one field"); } SortField field = fields[0]; // AUTO is resolved before we are called System.Diagnostics.Debug.Assert(field.GetType() != SortField.AUTO); comparator = field.GetComparator(size, 0); oneReverseMul = field.reverse?- 1:1; comparators[0] = comparator; reverseMul[0] = oneReverseMul; Initialize(size); } /// <summary> Returns whether <code>a</code> is less relevant than <code>b</code>.</summary> /// <param name="a">ScoreDoc /// </param> /// <param name="b">ScoreDoc /// </param> /// <returns> <code>true</code> if document <code>a</code> should be sorted after document <code>b</code>. /// </returns> public override bool LessThan(System.Object a, System.Object b) { Entry hitA = (Entry) a; Entry hitB = (Entry) b; System.Diagnostics.Debug.Assert(hitA != hitB); System.Diagnostics.Debug.Assert(hitA.slot != hitB.slot); int c = oneReverseMul * comparator.Compare(hitA.slot, hitB.slot); if (c != 0) { return c > 0; } // avoid random sort order that could lead to duplicates (bug #31241): return hitA.docID > hitB.docID; } } /// <summary> An implementation of {@link FieldValueHitQueue} which is optimized in case /// there is more than one comparator. /// </summary> private sealed class MultiComparatorsFieldValueHitQueue:FieldValueHitQueue { public MultiComparatorsFieldValueHitQueue(SortField[] fields, int size):base(fields) { int numComparators = comparators.Length; for (int i = 0; i < numComparators; ++i) { SortField field = fields[i]; // AUTO is resolved before we are called System.Diagnostics.Debug.Assert(field.GetType() != SortField.AUTO); reverseMul[i] = field.reverse?- 1:1; comparators[i] = field.GetComparator(size, i); } Initialize(size); } public override bool LessThan(System.Object a, System.Object b) { Entry hitA = (Entry) a; Entry hitB = (Entry) b; System.Diagnostics.Debug.Assert(hitA != hitB); System.Diagnostics.Debug.Assert(hitA.slot != hitB.slot); int numComparators = comparators.Length; for (int i = 0; i < numComparators; ++i) { int c = reverseMul[i] * comparators[i].Compare(hitA.slot, hitB.slot); if (c != 0) { // Short circuit return c > 0; } } // avoid random sort order that could lead to duplicates (bug #31241): return hitA.docID > hitB.docID; } } // prevent instantiation and extension. private FieldValueHitQueue(SortField[] fields) { // When we get here, fields.length is guaranteed to be > 0, therefore no // need to check it again. // All these are required by this class's API - need to return arrays. // Therefore even in the case of a single comparator, create an array // anyway. this.fields = fields; int numComparators = fields.Length; comparators = new FieldComparator[numComparators]; reverseMul = new int[numComparators]; } /// <summary> Creates a hit queue sorted by the given list of fields. /// /// <p/><b>NOTE</b>: The instances returned by this method /// pre-allocate a full array of length <code>numHits</code>. /// /// </summary> /// <param name="fields">SortField array we are sorting by in priority order (highest /// priority first); cannot be <code>null</code> or empty /// </param> /// <param name="size">The number of hits to retain. Must be greater than zero. /// </param> /// <throws> IOException </throws> public static FieldValueHitQueue Create(SortField[] fields, int size) { if (fields.Length == 0) { throw new System.ArgumentException("Sort must contain at least one field"); } if (fields.Length == 1) { return new OneComparatorFieldValueHitQueue(fields, size); } else { return new MultiComparatorsFieldValueHitQueue(fields, size); } } internal virtual FieldComparator[] GetComparators() { return comparators; } internal virtual int[] GetReverseMul() { return reverseMul; } /// <summary>Stores the sort criteria being used. </summary> protected internal SortField[] fields; protected internal FieldComparator[] comparators; protected internal int[] reverseMul; public abstract override bool LessThan(System.Object a, System.Object b); /// <summary> Given a queue Entry, creates a corresponding FieldDoc /// that contains the values used to sort the given document. /// These values are not the raw values out of the index, but the internal /// representation of them. This is so the given search hit can be collated by /// a MultiSearcher with other search hits. /// /// </summary> /// <param name="entry">The Entry used to create a FieldDoc /// </param> /// <returns> The newly created FieldDoc /// </returns> /// <seealso cref="Searchable.Search(Weight,Filter,int,Sort)"> /// </seealso> internal virtual FieldDoc FillFields(Entry entry) { int n = comparators.Length; System.IComparable[] fields = new System.IComparable[n]; for (int i = 0; i < n; ++i) { fields[i] = comparators[i].Value(entry.slot); } //if (maxscore > 1.0f) doc.score /= maxscore; // normalize scores return new FieldDoc(entry.docID, entry.score, fields); } /// <summary>Returns the SortFields being used by this hit queue. </summary> internal virtual SortField[] GetFields() { return fields; } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Drawing; using System.Drawing.Imaging; using OSGeo.GDAL; namespace DotSpatial.Data.Rasters.GdalExtension { /// <summary> /// A tiled image based on GDAL data. /// </summary> public class GdalTiledImage : TiledImage { #region Fields private Band _alpha; private Band _blue; private Dataset _dataset; private Band _green; private Band _red; #endregion #region Constructors static GdalTiledImage() { GdalConfiguration.ConfigureGdal(); } /// <summary> /// Initializes a new instance of the <see cref="GdalTiledImage"/> class. /// </summary> /// <param name="fileName">The file name.</param> public GdalTiledImage(string fileName) : base(fileName) { WorldFile = new WorldFile { Affine = new double[6] }; ReadHeader(); } #endregion #region Methods /// <summary> /// Closes the image. /// </summary> public override void Close() { _dataset?.Dispose(); _dataset = null; base.Close(); } /// <summary> /// Attempts to open the specified file. /// </summary> public override void Open() { _dataset = Helpers.Open(Filename); _red = _dataset.GetRasterBand(1); if (_red.GetRasterColorInterpretation() == ColorInterp.GCI_PaletteIndex) { ReadPaletteBuffered(); } if (_red.GetRasterColorInterpretation() == ColorInterp.GCI_GrayIndex) { ReadGrayIndex(); } if (_red.GetRasterColorInterpretation() == ColorInterp.GCI_RedBand) { ReadRgb(); } if (_red.GetRasterColorInterpretation() == ColorInterp.GCI_AlphaBand) { ReadArgb(); } } private void ReadArgb() { if (_dataset.RasterCount < 4) { throw new GdalException("ARGB Format was indicated but there are only " + _dataset.RasterCount + " bands!"); } _alpha = _red; _red = _dataset.GetRasterBand(2); _green = _dataset.GetRasterBand(3); _blue = _dataset.GetRasterBand(4); int tw = TileCollection.TileWidth; int th = TileCollection.TileHeight; for (int row = 0; row < TileCollection.NumTilesTall(); row++) { for (int col = 0; col < TileCollection.NumTilesWide(); col++) { int width = TileCollection.GetTileWidth(col); int height = TileCollection.GetTileHeight(row); InRamImageData id = new InRamImageData(width, height); Bitmap image = new Bitmap(width, height, PixelFormat.Format32bppArgb); byte[] red = new byte[width * height]; byte[] g = new byte[width * height]; byte[] b = new byte[width * height]; byte[] a = new byte[width * height]; _red.ReadRaster(col * tw, row * th, width, height, red, width, height, 0, 0); _green.ReadRaster(col * tw, row * th, width, height, g, width, height, 0, 0); _blue.ReadRaster(col * tw, row * th, width, height, b, width, height, 0, 0); _alpha.ReadRaster(col * tw, row * th, width, height, a, width, height, 0, 0); BitmapData bData = image.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); Stride = bData.Stride; image.UnlockBits(bData); byte[] vals = new byte[Width * Height * 4]; int stride = Stride; const int Bpp = 4; for (int r = 0; r < height; r++) { for (int c = 0; c < width; c++) { vals[(r * stride) + (c * Bpp)] = b[(r * width) + c]; vals[(r * stride) + (c * Bpp) + 1] = g[(r * width) + c]; vals[(r * stride) + (c * Bpp) + 2] = red[(r * width) + c]; vals[(r * stride) + (c * Bpp) + 3] = a[(r * width) + c]; } } id.Values = vals; id.CopyValuesToBitmap(); TileCollection.Tiles[row, col] = id; } } SetTileBounds(Bounds.AffineCoefficients); } private void ReadGrayIndex() { int tw = TileCollection.TileWidth; int th = TileCollection.TileHeight; for (int row = 0; row < TileCollection.NumTilesTall(); row++) { for (int col = 0; col < TileCollection.NumTilesWide(); col++) { int width = TileCollection.GetTileWidth(col); int height = TileCollection.GetTileHeight(row); InRamImageData id = new InRamImageData(width, height); byte[] red = new byte[width * height]; _red.ReadRaster(col * tw, row * th, width, height, red, width, height, 0, 0); Bitmap image = new Bitmap(width, height); BitmapData bData = image.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); Stride = bData.Stride; image.UnlockBits(bData); byte[] vals = new byte[width * height * 4]; int stride = Stride; const int Bpp = 4; for (int r = 0; r < height; r++) { for (int c = 0; c < width; c++) { vals[(r * stride) + (c * Bpp)] = red[(r * width) + c]; vals[(r * stride) + (c * Bpp) + 1] = red[(r * width) + c]; vals[(r * stride) + (c * Bpp) + 2] = red[(r * width) + c]; vals[(r * stride) + (c * Bpp) + 3] = 255; } } id.Values = vals; id.CopyValuesToBitmap(); TileCollection.Tiles[row, col] = id; } } SetTileBounds(Bounds.AffineCoefficients); } private void ReadHeader() { _dataset = Helpers.Open(Filename); Init(_dataset.RasterXSize, _dataset.RasterYSize); NumBands = _dataset.RasterCount; WorldFile = new WorldFile { Affine = new double[6] }; double[] test = new double[6]; _dataset.GetGeoTransform(test); test = new AffineTransform(test).TransfromToCorner(0.5, 0.5); // shift origin by half a cell Bounds = new RasterBounds(Height, Width, test); WorldFile.Affine = test; Close(); } private void ReadPaletteBuffered() { ColorTable ct = _red.GetRasterColorTable(); if (ct == null) { throw new GdalException("Image was stored with a palette interpretation but has no color table."); } if (ct.GetPaletteInterpretation() != PaletteInterp.GPI_RGB) { throw new GdalException("Only RGB palette interpreation is currently supported by this plugin, " + ct.GetPaletteInterpretation() + " is not supported."); } int tw = TileCollection.TileWidth; int th = TileCollection.TileHeight; for (int row = 0; row < TileCollection.NumTilesTall(); row++) { for (int col = 0; col < TileCollection.NumTilesWide(); col++) { // takes into account that right and bottom tiles might be smaller. int width = TileCollection.GetTileWidth(col); int height = TileCollection.GetTileHeight(row); ImageData id = new ImageData(); byte[] red = new byte[width * height]; _red.ReadRaster(col * tw, row * th, width, height, red, width, height, 0, 0); Bitmap image = new Bitmap(width, height, PixelFormat.Format32bppArgb); BitmapData bData = image.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); Stride = bData.Stride; image.UnlockBits(bData); const int Bpp = 4; int stride = Stride; byte[] vals = new byte[width * height * 4]; byte[][] colorTable = new byte[256][]; for (int i = 0; i < 255; i++) { ColorEntry ce = ct.GetColorEntry(i); colorTable[i] = new[] { (byte)ce.c3, (byte)ce.c2, (byte)ce.c1, (byte)ce.c4 }; } for (int r = 0; r < height; r++) { for (int c = 0; c < width; c++) { Array.Copy(colorTable[red[c + (r * width)]], 0, vals, (row * stride) + (col * Bpp), 4); } } id.Values = vals; id.CopyValuesToBitmap(); TileCollection.Tiles[row, col] = id; } } SetTileBounds(Bounds.AffineCoefficients); } private void ReadRgb() { if (_dataset.RasterCount < 3) { throw new GdalException("RGB Format was indicated but there are only " + _dataset.RasterCount + " bands!"); } _green = _dataset.GetRasterBand(2); _blue = _dataset.GetRasterBand(3); int tw = TileCollection.TileWidth; int th = TileCollection.TileHeight; int ntt = TileCollection.NumTilesTall(); int ntw = TileCollection.NumTilesWide(); ProgressMeter pm = new ProgressMeter(ProgressHandler, "Reading Tiles ", ntt * ntw); for (int row = 0; row < ntt; row++) { for (int col = 0; col < ntw; col++) { int width = TileCollection.GetTileWidth(col); int height = TileCollection.GetTileHeight(row); InRamImageData id = new InRamImageData(width, height); Bitmap image = new Bitmap(width, height, PixelFormat.Format32bppArgb); byte[] red = new byte[width * height]; byte[] g = new byte[width * height]; byte[] b = new byte[width * height]; _red.ReadRaster(col * tw, row * th, width, height, red, width, height, 0, 0); _green.ReadRaster(col * tw, row * th, width, height, g, width, height, 0, 0); _blue.ReadRaster(col * tw, row * th, width, height, b, width, height, 0, 0); BitmapData bData = image.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); Stride = bData.Stride; image.UnlockBits(bData); byte[] vals = new byte[width * height * 4]; int stride = Stride; const int Bpp = 4; for (int r = 0; r < height; r++) { for (int c = 0; c < width; c++) { vals[(r * stride) + (c * Bpp)] = b[(r * width) + c]; vals[(r * stride) + (c * Bpp) + 1] = g[(r * width) + c]; vals[(r * stride) + (c * Bpp) + 2] = red[(r * width) + c]; vals[(r * stride) + (c * Bpp) + 3] = 255; } } id.Values = vals; id.CopyValuesToBitmap(); TileCollection.Tiles[row, col] = id; pm.CurrentValue = (row * ntw) + col; } } pm.Reset(); SetTileBounds(Bounds.AffineCoefficients); } #endregion } }
/* Copyright (c) 2006 - 2008 The Open Toolkit library. 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.Numerics; using System.Runtime.InteropServices; namespace Nu { /// <summary> /// Represents a 3x3 matrix containing 3D rotation and scale. /// Copied from - https://github.com/opentk/opentk/blob/3.x/src/OpenTK/Math/Matrix3.cs /// Modified by BGE to more closely conform to System.Numerics. /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Matrix3x3 : IEquatable<Matrix3x3> { /// <summary> /// First row of the matrix. /// </summary> public Vector3 Row0; /// <summary> /// Second row of the matrix. /// </summary> public Vector3 Row1; /// <summary> /// Third row of the matrix. /// </summary> public Vector3 Row2; /// <summary> /// The identity matrix. /// </summary> public static readonly Matrix3x3 Identity = new Matrix3x3(Vector3.UnitX, Vector3.UnitY, Vector3.UnitZ); /// <summary> /// The zero matrix. /// </summary> public static readonly Matrix3x3 Zero = new Matrix3x3(Vector3.Zero, Vector3.Zero, Vector3.Zero); /// <summary> /// Constructs a new instance. /// </summary> /// <param name="row0">Top row of the matrix</param> /// <param name="row1">Second row of the matrix</param> /// <param name="row2">Bottom row of the matrix</param> public Matrix3x3(Vector3 row0, Vector3 row1, Vector3 row2) { Row0 = row0; Row1 = row1; Row2 = row2; } /// <summary> /// Constructs a new instance. /// </summary> /// <param name="m00">First item of the first row of the matrix.</param> /// <param name="m01">Second item of the first row of the matrix.</param> /// <param name="m02">Third item of the first row of the matrix.</param> /// <param name="m10">First item of the second row of the matrix.</param> /// <param name="m11">Second item of the second row of the matrix.</param> /// <param name="m12">Third item of the second row of the matrix.</param> /// <param name="m20">First item of the third row of the matrix.</param> /// <param name="m21">Second item of the third row of the matrix.</param> /// <param name="m22">Third item of the third row of the matrix.</param> public Matrix3x3( float m00, float m01, float m02, float m10, float m11, float m12, float m20, float m21, float m22) { Row0 = new Vector3(m00, m01, m02); Row1 = new Vector3(m10, m11, m12); Row2 = new Vector3(m20, m21, m22); } /// <summary> /// Gets the determinant of this matrix. /// </summary> public float Determinant { get { float m11 = Row0.X, m12 = Row0.Y, m13 = Row0.Z, m21 = Row1.X, m22 = Row1.Y, m23 = Row1.Z, m31 = Row2.X, m32 = Row2.Y, m33 = Row2.Z; return m11 * m22 * m33 + m12 * m23 * m31 + m13 * m21 * m32 - m13 * m22 * m31 - m11 * m23 * m32 - m12 * m21 * m33; } } /// <summary> /// Gets the first column of this matrix. /// </summary> public Vector3 Column0 { get { return new Vector3(Row0.X, Row1.X, Row2.X); } } /// <summary> /// Gets the second column of this matrix. /// </summary> public Vector3 Column1 { get { return new Vector3(Row0.Y, Row1.Y, Row2.Y); } } /// <summary> /// Gets the third column of this matrix. /// </summary> public Vector3 Column2 { get { return new Vector3(Row0.Z, Row1.Z, Row2.Z); } } /// <summary> /// Gets or sets the value at row 1, column 1 of this instance. /// </summary> public float M11 { get { return Row0.X; } set { Row0.X = value; } } /// <summary> /// Gets or sets the value at row 1, column 2 of this instance. /// </summary> public float M12 { get { return Row0.Y; } set { Row0.Y = value; } } /// <summary> /// Gets or sets the value at row 1, column 3 of this instance. /// </summary> public float M13 { get { return Row0.Z; } set { Row0.Z = value; } } /// <summary> /// Gets or sets the value at row 2, column 1 of this instance. /// </summary> public float M21 { get { return Row1.X; } set { Row1.X = value; } } /// <summary> /// Gets or sets the value at row 2, column 2 of this instance. /// </summary> public float M22 { get { return Row1.Y; } set { Row1.Y = value; } } /// <summary> /// Gets or sets the value at row 2, column 3 of this instance. /// </summary> public float M23 { get { return Row1.Z; } set { Row1.Z = value; } } /// <summary> /// Gets or sets the value at row 3, column 1 of this instance. /// </summary> public float M31 { get { return Row2.X; } set { Row2.X = value; } } /// <summary> /// Gets or sets the value at row 3, column 2 of this instance. /// </summary> public float M32 { get { return Row2.Y; } set { Row2.Y = value; } } /// <summary> /// Gets or sets the value at row 3, column 3 of this instance. /// </summary> public float M33 { get { return Row2.Z; } set { Row2.Z = value; } } /// <summary> /// Gets or sets the values along the main diagonal of the matrix. /// </summary> public Vector3 Diagonal { get { return new Vector3(Row0.X, Row1.Y, Row2.Z); } set { Row0.X = value.X; Row1.Y = value.Y; Row2.Z = value.Z; } } /// <summary> /// Gets the trace of the matrix, the sum of the values along the diagonal. /// </summary> public float Trace { get { return Row0.X + Row1.Y + Row2.Z; } } /// <summary> /// Converts this instance into its inverse. /// </summary> public void Invert() { this = Matrix3x3.Invert(this); } /// <summary> /// Converts this instance into its transpose. /// </summary> public void Transpose() { this = Matrix3x3.Transpose(this); } /// <summary> /// Returns a normalised copy of this instance. /// </summary> public Matrix3x3 Normalized() { Matrix3x3 m = this; m.Normalize(); return m; } /// <summary> /// Divides each element in the Matrix by the <see cref="Determinant"/>. /// </summary> public void Normalize() { var determinant = this.Determinant; Row0 /= determinant; Row1 /= determinant; Row2 /= determinant; } /// <summary> /// Returns an inverted copy of this instance. /// </summary> public Matrix3x3 Inverted() { Matrix3x3 m = this; if (m.Determinant != 0) { m.Invert(); } return m; } /// <summary> /// Returns a copy of this Matrix3 without scale. /// </summary> public Matrix3x3 ClearScale() { Matrix3x3 m = this; m.Row0 = Vector3.Normalize(m.Row0); m.Row1 = Vector3.Normalize(m.Row1); m.Row2 = Vector3.Normalize(m.Row2); return m; } /// <summary> /// Returns a copy of this Matrix3 without rotation. /// </summary> public Matrix3x3 ClearRotation() { Matrix3x3 m = this; m.Row0 = new Vector3(m.Row0.Length(), 0, 0); m.Row1 = new Vector3(0, m.Row1.Length(), 0); m.Row2 = new Vector3(0, 0, m.Row2.Length()); return m; } /// <summary> /// Returns the scale component of this instance. /// </summary> public Vector3 ExtractScale() { return new Vector3(Row0.Length(), Row1.Length(), Row2.Length()); } /// <summary> /// Returns the rotation component of this instance. Quite slow. /// </summary> /// <param name="row_normalise">Whether the method should row-normalise (i.e. remove scale from) the Matrix. Pass false if you know it's already normalised.</param> public Quaternion ExtractRotation(bool row_normalise = true) { var row0 = Row0; var row1 = Row1; var row2 = Row2; if (row_normalise) { row0 = Vector3.Normalize(row0); row1 = Vector3.Normalize(row1); row2 = Vector3.Normalize(row2); } // code below adapted from Blender Quaternion q = new Quaternion(); double trace = 0.25 * (row0.X + row1.Y + row2.Z + 1.0); if (trace > 0) { double sq = Math.Sqrt(trace); q.W = (float)sq; sq = 1.0 / (4.0 * sq); q.X = (float)((row1.Z - row2.Y) * sq); q.Y = (float)((row2.X - row0.Z) * sq); q.Z = (float)((row0.Y - row1.X) * sq); } else if (row0.X > row1.Y && row0.X > row2.Z) { double sq = 2.0 * Math.Sqrt(1.0 + row0.X - row1.Y - row2.Z); q.X = (float)(0.25 * sq); sq = 1.0 / sq; q.W = (float)((row2.Y - row1.Z) * sq); q.Y = (float)((row1.X + row0.Y) * sq); q.Z = (float)((row2.X + row0.Z) * sq); } else if (row1.Y > row2.Z) { double sq = 2.0 * Math.Sqrt(1.0 + row1.Y - row0.X - row2.Z); q.Y = (float)(0.25 * sq); sq = 1.0 / sq; q.W = (float)((row2.X - row0.Z) * sq); q.X = (float)((row1.X + row0.Y) * sq); q.Z = (float)((row2.Y + row1.Z) * sq); } else { double sq = 2.0 * Math.Sqrt(1.0 + row2.Z - row0.X - row1.Y); q.Z = (float)(0.25 * sq); sq = 1.0 / sq; q.W = (float)((row1.X - row0.Y) * sq); q.X = (float)((row2.X + row0.Z) * sq); q.Y = (float)((row2.Y + row1.Z) * sq); } return Quaternion.Normalize(q); } /// <summary> /// Build a rotation matrix from the specified axis/angle rotation. /// </summary> /// <param name="axis">The axis to rotate about.</param> /// <param name="angle">Angle in radians to rotate counter-clockwise (looking in the direction of the given axis).</param> /// <param name="result">A matrix instance.</param> public static void CreateFromAxisAngle(Vector3 axis, float angle, out Matrix3x3 result) { //normalize and create a local copy of the vector. var axisN = Vector3.Normalize(axis); float axisX = axisN.X, axisY = axisN.Y, axisZ = axisN.Z; //calculate angles float cos = (float)System.Math.Cos(-angle); float sin = (float)System.Math.Sin(-angle); float t = 1.0f - cos; //do the conversion math once float tXX = t * axisX * axisX, tXY = t * axisX * axisY, tXZ = t * axisX * axisZ, tYY = t * axisY * axisY, tYZ = t * axisY * axisZ, tZZ = t * axisZ * axisZ; float sinX = sin * axisX, sinY = sin * axisY, sinZ = sin * axisZ; result.Row0.X = tXX + cos; result.Row0.Y = tXY - sinZ; result.Row0.Z = tXZ + sinY; result.Row1.X = tXY + sinZ; result.Row1.Y = tYY + cos; result.Row1.Z = tYZ - sinX; result.Row2.X = tXZ - sinY; result.Row2.Y = tYZ + sinX; result.Row2.Z = tZZ + cos; } /// <summary> /// Build a rotation matrix from the specified axis/angle rotation. /// </summary> /// <param name="axis">The axis to rotate about.</param> /// <param name="angle">Angle in radians to rotate counter-clockwise (looking in the direction of the given axis).</param> /// <returns>A matrix instance.</returns> public static Matrix3x3 CreateFromAxisAngle(Vector3 axis, float angle) { Matrix3x3 result; CreateFromAxisAngle(axis, angle, out result); return result; } /// <summary> /// Builds a rotation matrix for a rotation around the x-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <param name="result">The resulting Matrix3 instance.</param> public static void CreateRotationX(float angle, out Matrix3x3 result) { float cos = (float)System.Math.Cos(angle); float sin = (float)System.Math.Sin(angle); result = Identity; result.Row1.Y = cos; result.Row1.Z = sin; result.Row2.Y = -sin; result.Row2.Z = cos; } /// <summary> /// Builds a rotation matrix for a rotation around the x-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <returns>The resulting Matrix3 instance.</returns> public static Matrix3x3 CreateRotationX(float angle) { Matrix3x3 result; CreateRotationX(angle, out result); return result; } /// <summary> /// Builds a rotation matrix for a rotation around the y-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <param name="result">The resulting Matrix3 instance.</param> public static void CreateRotationY(float angle, out Matrix3x3 result) { float cos = (float)System.Math.Cos(angle); float sin = (float)System.Math.Sin(angle); result = Identity; result.Row0.X = cos; result.Row0.Z = -sin; result.Row2.X = sin; result.Row2.Z = cos; } /// <summary> /// Builds a rotation matrix for a rotation around the y-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <returns>The resulting Matrix3 instance.</returns> public static Matrix3x3 CreateRotationY(float angle) { Matrix3x3 result; CreateRotationY(angle, out result); return result; } /// <summary> /// Builds a rotation matrix for a rotation around the z-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <param name="result">The resulting Matrix3 instance.</param> public static void CreateRotationZ(float angle, out Matrix3x3 result) { float cos = (float)System.Math.Cos(angle); float sin = (float)System.Math.Sin(angle); result = Identity; result.Row0.X = cos; result.Row0.Y = sin; result.Row1.X = -sin; result.Row1.Y = cos; } /// <summary> /// Builds a rotation matrix for a rotation around the z-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <returns>The resulting Matrix3 instance.</returns> public static Matrix3x3 CreateRotationZ(float angle) { Matrix3x3 result; CreateRotationZ(angle, out result); return result; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="scale">Single scale factor for the x, y, and z axes.</param> /// <returns>A scale matrix.</returns> public static Matrix3x3 CreateScale(float scale) { Matrix3x3 result; CreateScale(scale, out result); return result; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="scale">Scale factors for the x, y, and z axes.</param> /// <returns>A scale matrix.</returns> public static Matrix3x3 CreateScale(Vector3 scale) { Matrix3x3 result; CreateScale(ref scale, out result); return result; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="x">Scale factor for the x axis.</param> /// <param name="y">Scale factor for the y axis.</param> /// <param name="z">Scale factor for the z axis.</param> /// <returns>A scale matrix.</returns> public static Matrix3x3 CreateScale(float x, float y, float z) { Matrix3x3 result; CreateScale(x, y, z, out result); return result; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="scale">Single scale factor for the x, y, and z axes.</param> /// <param name="result">A scale matrix.</param> public static void CreateScale(float scale, out Matrix3x3 result) { result = Identity; result.Row0.X = scale; result.Row1.Y = scale; result.Row2.Z = scale; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="scale">Scale factors for the x, y, and z axes.</param> /// <param name="result">A scale matrix.</param> public static void CreateScale(ref Vector3 scale, out Matrix3x3 result) { result = Identity; result.Row0.X = scale.X; result.Row1.Y = scale.Y; result.Row2.Z = scale.Z; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="x">Scale factor for the x axis.</param> /// <param name="y">Scale factor for the y axis.</param> /// <param name="z">Scale factor for the z axis.</param> /// <param name="result">A scale matrix.</param> public static void CreateScale(float x, float y, float z, out Matrix3x3 result) { result = Identity; result.Row0.X = x; result.Row1.Y = y; result.Row2.Z = z; } /// <summary> /// Adds two instances. /// </summary> /// <param name="left">The left operand of the addition.</param> /// <param name="right">The right operand of the addition.</param> /// <returns>A new instance that is the result of the addition.</returns> public static Matrix3x3 Add(Matrix3x3 left, Matrix3x3 right) { Matrix3x3 result; Add(ref left, ref right, out result); return result; } /// <summary> /// Adds two instances. /// </summary> /// <param name="left">The left operand of the addition.</param> /// <param name="right">The right operand of the addition.</param> /// <param name="result">A new instance that is the result of the addition.</param> public static void Add(ref Matrix3x3 left, ref Matrix3x3 right, out Matrix3x3 result) { result.Row0 = left.Row0 + right.Row0; result.Row1 = left.Row1 + right.Row1; result.Row2 = left.Row2 + right.Row2; } /// <summary> /// Multiplies two instances. /// </summary> /// <param name="left">The left operand of the multiplication.</param> /// <param name="right">The right operand of the multiplication.</param> /// <returns>A new instance that is the result of the multiplication</returns> public static Matrix3x3 Multiply(Matrix3x3 left, Matrix3x3 right) { Matrix3x3 result; Multiply(ref left, ref right, out result); return result; } /// <summary> /// Multiplies two instances. /// </summary> /// <param name="left">The left operand of the multiplication.</param> /// <param name="right">The right operand of the multiplication.</param> /// <param name="result">A new instance that is the result of the multiplication</param> public static void Multiply(ref Matrix3x3 left, ref Matrix3x3 right, out Matrix3x3 result) { float lM11 = left.Row0.X, lM12 = left.Row0.Y, lM13 = left.Row0.Z, lM21 = left.Row1.X, lM22 = left.Row1.Y, lM23 = left.Row1.Z, lM31 = left.Row2.X, lM32 = left.Row2.Y, lM33 = left.Row2.Z, rM11 = right.Row0.X, rM12 = right.Row0.Y, rM13 = right.Row0.Z, rM21 = right.Row1.X, rM22 = right.Row1.Y, rM23 = right.Row1.Z, rM31 = right.Row2.X, rM32 = right.Row2.Y, rM33 = right.Row2.Z; result.Row0.X = ((lM11 * rM11) + (lM12 * rM21)) + (lM13 * rM31); result.Row0.Y = ((lM11 * rM12) + (lM12 * rM22)) + (lM13 * rM32); result.Row0.Z = ((lM11 * rM13) + (lM12 * rM23)) + (lM13 * rM33); result.Row1.X = ((lM21 * rM11) + (lM22 * rM21)) + (lM23 * rM31); result.Row1.Y = ((lM21 * rM12) + (lM22 * rM22)) + (lM23 * rM32); result.Row1.Z = ((lM21 * rM13) + (lM22 * rM23)) + (lM23 * rM33); result.Row2.X = ((lM31 * rM11) + (lM32 * rM21)) + (lM33 * rM31); result.Row2.Y = ((lM31 * rM12) + (lM32 * rM22)) + (lM33 * rM32); result.Row2.Z = ((lM31 * rM13) + (lM32 * rM23)) + (lM33 * rM33); } /// <summary> /// Calculate the inverse of the given matrix /// </summary> /// <param name="mat">The matrix to invert</param> /// <param name="result">The inverse of the given matrix if it has one, or the input if it is singular</param> /// <exception cref="InvalidOperationException">Thrown if the Matrix3 is singular.</exception> public static void Invert(ref Matrix3x3 mat, out Matrix3x3 result) { int[] colIdx = { 0, 0, 0 }; int[] rowIdx = { 0, 0, 0 }; int[] pivotIdx = { -1, -1, -1 }; float[,] inverse = {{mat.Row0.X, mat.Row0.Y, mat.Row0.Z}, {mat.Row1.X, mat.Row1.Y, mat.Row1.Z}, {mat.Row2.X, mat.Row2.Y, mat.Row2.Z}}; int icol = 0; int irow = 0; for (int i = 0; i < 3; i++) { float maxPivot = 0.0f; for (int j = 0; j < 3; j++) { if (pivotIdx[j] != 0) { for (int k = 0; k < 3; ++k) { if (pivotIdx[k] == -1) { float absVal = System.Math.Abs(inverse[j, k]); if (absVal > maxPivot) { maxPivot = absVal; irow = j; icol = k; } } else if (pivotIdx[k] > 0) { result = mat; return; } } } } ++(pivotIdx[icol]); if (irow != icol) { for (int k = 0; k < 3; ++k) { float f = inverse[irow, k]; inverse[irow, k] = inverse[icol, k]; inverse[icol, k] = f; } } rowIdx[i] = irow; colIdx[i] = icol; float pivot = inverse[icol, icol]; if (pivot == 0.0f) { throw new InvalidOperationException("Matrix is singular and cannot be inverted."); } float oneOverPivot = 1.0f / pivot; inverse[icol, icol] = 1.0f; for (int k = 0; k < 3; ++k) { inverse[icol, k] *= oneOverPivot; } for (int j = 0; j < 3; ++j) { if (icol != j) { float f = inverse[j, icol]; inverse[j, icol] = 0.0f; for (int k = 0; k < 3; ++k) { inverse[j, k] -= inverse[icol, k] * f; } } } } for (int j = 2; j >= 0; --j) { int ir = rowIdx[j]; int ic = colIdx[j]; for (int k = 0; k < 3; ++k) { float f = inverse[k, ir]; inverse[k, ir] = inverse[k, ic]; inverse[k, ic] = f; } } result.Row0.X = inverse[0, 0]; result.Row0.Y = inverse[0, 1]; result.Row0.Z = inverse[0, 2]; result.Row1.X = inverse[1, 0]; result.Row1.Y = inverse[1, 1]; result.Row1.Z = inverse[1, 2]; result.Row2.X = inverse[2, 0]; result.Row2.Y = inverse[2, 1]; result.Row2.Z = inverse[2, 2]; } /// <summary> /// Calculate the inverse of the given matrix /// </summary> /// <param name="mat">The matrix to invert</param> /// <returns>The inverse of the given matrix if it has one, or the input if it is singular</returns> /// <exception cref="InvalidOperationException">Thrown if the Matrix4 is singular.</exception> public static Matrix3x3 Invert(Matrix3x3 mat) { Matrix3x3 result; Invert(ref mat, out result); return result; } /// <summary> /// Calculate the transpose of the given matrix /// </summary> /// <param name="mat">The matrix to transpose</param> /// <returns>The transpose of the given matrix</returns> public static Matrix3x3 Transpose(Matrix3x3 mat) { return new Matrix3x3(mat.Column0, mat.Column1, mat.Column2); } /// <summary> /// Calculate the transpose of the given matrix /// </summary> /// <param name="mat">The matrix to transpose</param> /// <param name="result">The result of the calculation</param> public static void Transpose(ref Matrix3x3 mat, out Matrix3x3 result) { result.Row0.X = mat.Row0.X; result.Row0.Y = mat.Row1.X; result.Row0.Z = mat.Row2.X; result.Row1.X = mat.Row0.Y; result.Row1.Y = mat.Row1.Y; result.Row1.Z = mat.Row2.Y; result.Row2.X = mat.Row0.Z; result.Row2.Y = mat.Row1.Z; result.Row2.Z = mat.Row2.Z; } /// <summary> /// Matrix multiplication /// </summary> /// <param name="left">left-hand operand</param> /// <param name="right">right-hand operand</param> /// <returns>A new Matrix3d which holds the result of the multiplication</returns> public static Matrix3x3 operator *(Matrix3x3 left, Matrix3x3 right) { return Matrix3x3.Multiply(left, right); } /// <summary> /// Compares two instances for equality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left equals right; false otherwise.</returns> public static bool operator ==(Matrix3x3 left, Matrix3x3 right) { return left.Equals(right); } /// <summary> /// Compares two instances for inequality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left does not equal right; false otherwise.</returns> public static bool operator !=(Matrix3x3 left, Matrix3x3 right) { return !left.Equals(right); } /// <summary> /// Returns a System.String that represents the current Matrix3d. /// </summary> /// <returns>The string representation of the matrix.</returns> public override string ToString() { return String.Format("{0}\n{1}\n{2}", Row0, Row1, Row2); } /// <summary> /// Returns the hashcode for this instance. /// </summary> /// <returns>A System.Int32 containing the unique hashcode for this instance.</returns> public override int GetHashCode() { unchecked { var hashCode = this.Row0.GetHashCode(); hashCode = (hashCode * 397) ^ this.Row1.GetHashCode(); hashCode = (hashCode * 397) ^ this.Row2.GetHashCode(); return hashCode; } } /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <param name="obj">The object to compare to.</param> /// <returns>True if the instances are equal; false otherwise.</returns> public override bool Equals(object obj) { if (!(obj is Matrix3x3)) { return false; } return this.Equals((Matrix3x3)obj); } /// <summary>Indicates whether the current matrix is equal to another matrix.</summary> /// <param name="other">A matrix to compare with this matrix.</param> /// <returns>true if the current matrix is equal to the matrix parameter; otherwise, false.</returns> public bool Equals(Matrix3x3 other) { return Row0 == other.Row0 && Row1 == other.Row1 && Row2 == other.Row2; } #region BGE's additional Matrix3x3 operations public static Matrix3x3 CreateTranslation(Vector2 v) { var m = Matrix3x3.Identity; m.M13 = v.X; m.M23 = v.Y; return m; } public static Matrix3x3 ExtractScaleMatrix(in Matrix3x3 m) { var scale = new Vector3(m.Row0.X, m.Row1.Y, m.Row2.Z); return Matrix3x3.CreateScale(scale); } public static Vector2 Multiply(in Vector2 v, in Matrix3x3 m) { var x = v.X * m.M11 + v.Y * m.M12 + m.M13; var y = v.X * m.M21 + v.Y * m.M22 + m.M23; var z = v.X * m.M31 + v.Y * m.M32 + m.M33; return new Vector2(x / z, y / z); } public static Vector2 operator *(Vector2 v, Matrix3x3 m) { return Multiply(in v, in m); } #endregion } }
namespace Zutatensuppe.DiabloInterface.Gui.Controls { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Windows.Forms; using Newtonsoft.Json; using Zutatensuppe.D2Reader.Models; using Zutatensuppe.DiabloInterface.Lib; using Zutatensuppe.DiabloInterface.Lib.Extensions; public partial class RuneSettingsPage : UserControl { static readonly ILogger Logger = Logging.CreateLogger(MethodBase.GetCurrentMethod().DeclaringType); public RuneSettingsPage() { Logger.Info("Initializing rune settings page."); InitializeComponent(); InitializeCharacterClassComboBox(); InitializeDifficultyComboBox(); InitializeRuneComboBox(); InitializeRunewordComboBox(); } private SplitContainer splitContainer1; private GroupBox classSettingsGroupBox; private ListBox characterListBox; private FlowLayoutPanel runeFlowLayout; private ComboBox runeComboBox; private Button runeButton; private Label difficultyLabel; private Label classLabel; private ComboBox difficultyComboBox; private ComboBox characterClassComboBox; private GroupBox runesGroupBox; private GroupBox runeListEditBox; private Button deleteSettingsButton; private Button addSettingsButton; private TableLayoutPanel tableLayoutPanel1; private ComboBox runewordComboBox; private Button runewordButton; IClassRuneSettings currentSettings; IReadOnlyList<IClassRuneSettings> settingsList; private void InitializeComponent() { this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.classSettingsGroupBox = new System.Windows.Forms.GroupBox(); this.deleteSettingsButton = new System.Windows.Forms.Button(); this.addSettingsButton = new System.Windows.Forms.Button(); this.characterListBox = new System.Windows.Forms.ListBox(); this.runesGroupBox = new System.Windows.Forms.GroupBox(); this.runeFlowLayout = new System.Windows.Forms.FlowLayoutPanel(); this.runeListEditBox = new System.Windows.Forms.GroupBox(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.difficultyComboBox = new System.Windows.Forms.ComboBox(); this.characterClassComboBox = new System.Windows.Forms.ComboBox(); this.classLabel = new System.Windows.Forms.Label(); this.difficultyLabel = new System.Windows.Forms.Label(); this.runeComboBox = new System.Windows.Forms.ComboBox(); this.runeButton = new System.Windows.Forms.Button(); this.runewordComboBox = new System.Windows.Forms.ComboBox(); this.runewordButton = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); this.classSettingsGroupBox.SuspendLayout(); this.runesGroupBox.SuspendLayout(); this.runeListEditBox.SuspendLayout(); this.tableLayoutPanel1.SuspendLayout(); this.SuspendLayout(); // // splitContainer1 // this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer1.Location = new System.Drawing.Point(0, 0); // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add(this.classSettingsGroupBox); this.splitContainer1.Panel1MinSize = 140; // // splitContainer1.Panel2 // this.splitContainer1.Panel2.Controls.Add(this.runesGroupBox); this.splitContainer1.Panel2.Controls.Add(this.runeListEditBox); this.splitContainer1.Panel2MinSize = 200; this.splitContainer1.Size = new System.Drawing.Size(497, 440); this.splitContainer1.SplitterDistance = 149; // // classSettingsGroupBox // this.classSettingsGroupBox.Controls.Add(this.deleteSettingsButton); this.classSettingsGroupBox.Controls.Add(this.addSettingsButton); this.classSettingsGroupBox.Controls.Add(this.characterListBox); this.classSettingsGroupBox.Dock = System.Windows.Forms.DockStyle.Fill; this.classSettingsGroupBox.Location = new System.Drawing.Point(0, 0); this.classSettingsGroupBox.MinimumSize = new System.Drawing.Size(140, 0); this.classSettingsGroupBox.Size = new System.Drawing.Size(149, 440); this.classSettingsGroupBox.Text = "Class Settings"; // // deleteSettingsButton // this.deleteSettingsButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; this.deleteSettingsButton.Location = new System.Drawing.Point(31, 414); this.deleteSettingsButton.Size = new System.Drawing.Size(59, 23); this.deleteSettingsButton.Text = "Remove"; this.deleteSettingsButton.Click += new System.EventHandler(this.DeleteSettingsButtonOnClick); // // addSettingsButton // this.addSettingsButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; this.addSettingsButton.Location = new System.Drawing.Point(96, 414); this.addSettingsButton.Size = new System.Drawing.Size(50, 23); this.addSettingsButton.Text = "Add"; this.addSettingsButton.Click += new System.EventHandler(this.AddSettingsButtonOnClick); // // characterListBox // this.characterListBox.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; this.characterListBox.FormattingEnabled = true; this.characterListBox.Location = new System.Drawing.Point(3, 16); this.characterListBox.Size = new System.Drawing.Size(143, 394); this.characterListBox.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.CharacterListBoxOnMouseDoubleClick); // // runesGroupBox // this.runesGroupBox.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; this.runesGroupBox.Controls.Add(this.runeFlowLayout); this.runesGroupBox.Location = new System.Drawing.Point(3, 3); this.runesGroupBox.Size = new System.Drawing.Size(337, 313); this.runesGroupBox.Text = "Runes"; // // runeFlowLayout // this.runeFlowLayout.Dock = System.Windows.Forms.DockStyle.Fill; this.runeFlowLayout.Location = new System.Drawing.Point(3, 16); this.runeFlowLayout.Size = new System.Drawing.Size(331, 294); // // runeListEditBox // this.runeListEditBox.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; this.runeListEditBox.Controls.Add(this.tableLayoutPanel1); this.runeListEditBox.Controls.Add(this.runeComboBox); this.runeListEditBox.Controls.Add(this.runeButton); this.runeListEditBox.Controls.Add(this.runewordComboBox); this.runeListEditBox.Controls.Add(this.runewordButton); this.runeListEditBox.Location = new System.Drawing.Point(3, 322); this.runeListEditBox.Size = new System.Drawing.Size(337, 115); this.runeListEditBox.Text = "Edit"; // // tableLayoutPanel1 // this.tableLayoutPanel1.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; this.tableLayoutPanel1.ColumnCount = 2; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel1.Controls.Add(this.difficultyComboBox, 1, 1); this.tableLayoutPanel1.Controls.Add(this.characterClassComboBox, 0, 1); this.tableLayoutPanel1.Controls.Add(this.classLabel, 0, 0); this.tableLayoutPanel1.Controls.Add(this.difficultyLabel, 1, 0); this.tableLayoutPanel1.Location = new System.Drawing.Point(3, 14); this.tableLayoutPanel1.Margin = new System.Windows.Forms.Padding(0); this.tableLayoutPanel1.RowCount = 2; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 14F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 22F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(331, 38); // // difficultyComboBox // this.difficultyComboBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; this.difficultyComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.difficultyComboBox.FormattingEnabled = true; this.difficultyComboBox.Location = new System.Drawing.Point(168, 17); this.difficultyComboBox.Size = new System.Drawing.Size(160, 21); this.difficultyComboBox.SelectedValueChanged += new System.EventHandler(this.DifficultyComboBoxOnSelectedValueChanged); // // characterClassComboBox // this.characterClassComboBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; this.characterClassComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.characterClassComboBox.FormattingEnabled = true; this.characterClassComboBox.Location = new System.Drawing.Point(3, 17); this.characterClassComboBox.Size = new System.Drawing.Size(159, 21); this.characterClassComboBox.SelectedValueChanged += new System.EventHandler(this.CharacterClassComboBoxOnSelectedValueChanged); // // classLabel // this.classLabel.AutoSize = true; this.classLabel.Location = new System.Drawing.Point(3, 0); this.classLabel.Size = new System.Drawing.Size(32, 13); this.classLabel.Text = "Class"; // // difficultyLabel // this.difficultyLabel.AutoSize = true; this.difficultyLabel.Location = new System.Drawing.Point(168, 0); this.difficultyLabel.Size = new System.Drawing.Size(47, 13); this.difficultyLabel.Text = "Difficulty"; // // runeComboBox // this.runeComboBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; this.runeComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.runeComboBox.FormattingEnabled = true; this.runeComboBox.Location = new System.Drawing.Point(6, 57); this.runeComboBox.Size = new System.Drawing.Size(229, 21); // // runeButton // this.runeButton.Anchor = AnchorStyles.Top | AnchorStyles.Right; this.runeButton.Location = new System.Drawing.Point(241, 55); this.runeButton.Size = new System.Drawing.Size(90, 23); this.runeButton.Text = "Add"; this.runeButton.Click += new System.EventHandler(this.RuneButtonOnClick); // // runewordComboBox // this.runewordComboBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; this.runewordComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.runewordComboBox.FormattingEnabled = true; this.runewordComboBox.Location = new System.Drawing.Point(6, 86); this.runewordComboBox.Size = new System.Drawing.Size(229, 21); // // runewordButton // this.runewordButton.Anchor = AnchorStyles.Top | AnchorStyles.Right; this.runewordButton.Location = new System.Drawing.Point(241, 84); this.runewordButton.Size = new System.Drawing.Size(90, 23); this.runewordButton.Text = "Add"; this.runewordButton.Click += new System.EventHandler(this.RunewordButtonOnClick); // // RuneSettingsPage // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.splitContainer1); this.Name = "RuneSettingsPage"; this.Size = new System.Drawing.Size(497, 440); this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit(); this.splitContainer1.ResumeLayout(false); this.classSettingsGroupBox.ResumeLayout(false); this.runesGroupBox.ResumeLayout(false); this.runeListEditBox.ResumeLayout(false); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this.ResumeLayout(false); } public IReadOnlyList<IClassRuneSettings> SettingsList { get => settingsList; set { if (value == null) { settingsList = new List<IClassRuneSettings>(); } else { settingsList = value; } var index = characterListBox.SelectedIndex; characterListBox.Items.Clear(); IList<CharacterClassListItem> items = settingsList.Select(item => new CharacterClassListItem(item)).ToList(); characterListBox.Items.AddRange(items.OfType<object>().ToArray()); if (index >= characterListBox.Items.Count) { index = characterListBox.Items.Count - 1; } characterListBox.SelectedIndex = items.Any() ? (index < 0 ? 0 : index) : -1; DisplayCharacterClassSettings(); } } IClassRuneSettings CurrentSettings { set { currentSettings = value; if (currentSettings == null) { runeButton.Enabled = false; runewordButton.Enabled = false; characterClassComboBox.Enabled = false; characterClassComboBox.SelectedIndex = -1; difficultyComboBox.Enabled = false; difficultyComboBox.SelectedIndex = -1; runeFlowLayout.Controls.ClearAndDispose(); return; } runeButton.Enabled = true; runewordButton.Enabled = true; characterClassComboBox.Enabled = true; characterClassComboBox.SelectedIndex = currentSettings.Class.HasValue ? (int)currentSettings.Class.Value + 1 : 0; difficultyComboBox.Enabled = true; difficultyComboBox.SelectedIndex = currentSettings.Difficulty.HasValue ? (int)currentSettings.Difficulty.Value + 1 : 0; runeFlowLayout.Controls.ClearAndDispose(); currentSettings.Runes.ForEach(AddRune); } } void InitializeCharacterClassComboBox() { characterClassComboBox.Items.Clear(); characterClassComboBox.Items.Add("Default"); AddEnumValues(characterClassComboBox, typeof(CharacterClass)); } void InitializeDifficultyComboBox() { difficultyComboBox.Items.Clear(); difficultyComboBox.Items.Add("Default"); AddEnumValues(difficultyComboBox, typeof(GameDifficulty)); } void InitializeRuneComboBox() { runeComboBox.Items.Clear(); AddEnumValues(runeComboBox, typeof(Rune)); runeComboBox.SelectedIndex = Math.Min(runeComboBox.Items.Count, 0); } void InitializeRunewordComboBox() { runewordComboBox.Items.Clear(); AddRunewords(runewordComboBox); runewordComboBox.SelectedIndex = Math.Min(runewordComboBox.Items.Count, 0); } void AddRunewords(ComboBox comboBox) { IEnumerable<Runeword> runewords = ReadRuneworsFile(); IEnumerable<RunewordListItem> items = from runeword in runewords select new RunewordListItem(runeword); comboBox.Items.AddRange(items.OfType<object>().ToArray()); } void AddEnumValues(ComboBox comboBox, Type enumType) { if (!enumType.IsEnum) throw new ArgumentException(@"Must be enum type.", nameof(enumType)); object[] enumValues = Enum.GetValues(enumType).OfType<object>().ToArray(); comboBox.Items.AddRange(enumValues); } IEnumerable<Runeword> ReadRuneworsFile() { using (var stream = new MemoryStream(Properties.Resources.runewords)) using (var streamReader = new StreamReader(stream)) using (var reader = new JsonTextReader(streamReader)) { var serializer = new JsonSerializer(); return serializer.Deserialize<List<Runeword>>(reader); } } void DisplayCharacterClassSettings() { if (characterListBox.SelectedIndex < 0) { if (characterListBox.Items.Count <= 0) CurrentSettings = null; return; } var item = characterListBox.SelectedItem as CharacterClassListItem; if (item?.Settings == null) return; CurrentSettings = item.Settings; } void RuneButtonOnClick(object sender, EventArgs e) { if (runeComboBox.SelectedIndex < 0) return; AddRune((Rune)runeComboBox.SelectedItem); } void RunewordButtonOnClick(object sender, EventArgs e) { var item = runewordComboBox.SelectedItem as RunewordListItem; item?.Runeword.Runes.ForEach(AddRune); } void AddRune(Rune rune) { var element = new RuneDisplayElement(rune); element.RemoveButtonClicked += RuneElementOnRemoveButtonClicked; runeFlowLayout.Controls.Add(element); UpdateSettingsRuneList(); } void RuneElementOnRemoveButtonClicked(object sender, EventArgs eventArgs) { var control = sender as RuneDisplayElement; if (control == null) return; runeFlowLayout.Controls.Remove(control); control.Dispose(); UpdateSettingsRuneList(); } void UpdateSettingsRuneList() { currentSettings.Runes = (from RuneDisplayElement element in runeFlowLayout.Controls select element.Rune).ToList(); } void CharacterClassComboBoxOnSelectedValueChanged(object sender, EventArgs e) { if (currentSettings == null) return; var comboBox = sender as ComboBox; if (comboBox == null) return; if (comboBox.SelectedIndex == 0) currentSettings.Class = null; else currentSettings.Class = (CharacterClass)comboBox.SelectedItem; RefreshSettingsItemText(currentSettings); } void DifficultyComboBoxOnSelectedValueChanged(object sender, EventArgs e) { if (currentSettings == null) return; var comboBox = sender as ComboBox; if (comboBox == null) return; if (comboBox.SelectedIndex == 0) currentSettings.Difficulty = null; else currentSettings.Difficulty = (GameDifficulty)comboBox.SelectedItem; RefreshSettingsItemText(currentSettings); } void RefreshSettingsItemText(IClassRuneSettings settings) { var items = characterListBox.Items; for (var i = 0; i < items.Count; ++i) { var item = (CharacterClassListItem)items[i]; if (item.Settings != settings) continue; // Modifying the item collection forces the text to update. items[i] = item; break; } } void AddSettingsButtonOnClick(object sender, EventArgs e) { List<IClassRuneSettings> settings = settingsList.ToList(); settings.Add(new ClassRuneSettings()); SettingsList = settings; characterListBox.SelectedIndex = characterListBox.Items.Count - 1; CurrentSettings = settings.Last(); } void DeleteSettingsButtonOnClick(object sender, EventArgs e) { if (characterListBox.SelectedIndex < 0) return; var selected = characterListBox.SelectedItem as CharacterClassListItem; var settings = selected?.Settings; if (settings == null) return; SettingsList = settingsList.Where(s => s != settings).ToList(); } void CharacterListBoxOnMouseDoubleClick(object sender, MouseEventArgs e) { var listBox = (ListBox)sender; var index = listBox.IndexFromPoint(e.Location); if (index == ListBox.NoMatches) return; var item = listBox.Items[index] as CharacterClassListItem; if (item == null) return; CurrentSettings = item.Settings; } class CharacterClassListItem { public CharacterClassListItem(IClassRuneSettings settings) { Settings = settings ?? throw new ArgumentNullException(nameof(settings)); } public IClassRuneSettings Settings { get; } public override string ToString() { if (!Settings.Difficulty.HasValue) return Settings.Class.HasValue ? $"{Settings.Class}" : "Default"; return Settings.Class.HasValue ? $"{Settings.Class} {Settings.Difficulty}" : $"Default {Settings.Difficulty}"; } } class RunewordListItem { public Runeword Runeword { get; } public RunewordListItem(Runeword runeword) { Runeword = runeword ?? throw new ArgumentNullException(nameof(runeword)); } public override string ToString() => Runeword.Name; } } }
// ----------------------------------------------------------------------- // <copyright file="LocalContext.cs" company="Asynkron HB"> // Copyright (C) 2015-2016 Asynkron HB All rights reserved // </copyright> // ----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Proto.Mailbox; using System.Collections.ObjectModel; namespace Proto { public class Context : IMessageInvoker, IContext, ISupervisor { private readonly Stack<Receive> _behavior; private readonly Receive _receiveMiddleware; private readonly Sender _senderMiddleware; private readonly Func<IActor> _producer; private readonly ISupervisorStrategy _supervisorStrategy; private HashSet<PID> _children; private object _message; private Receive _receive; private Timer _receiveTimeoutTimer; private bool _restarting; private RestartStatistics _restartStatistics; private Stack<object> _stash; private bool _stopping; private HashSet<PID> _watchers; private HashSet<PID> _watching; public Context(Func<IActor> producer, ISupervisorStrategy supervisorStrategy, Receive receiveMiddleware, Sender senderMiddleware, PID parent) { _producer = producer; _supervisorStrategy = supervisorStrategy; _receiveMiddleware = receiveMiddleware; _senderMiddleware = senderMiddleware; Parent = parent; _behavior = new Stack<Receive>(); _behavior.Push(ActorReceive); IncarnateActor(); //fast path if (parent != null) { _watchers = new HashSet<PID> { parent }; } } public IReadOnlyCollection<PID> Children => _children?.ToList(); public IActor Actor { get; private set; } public PID Parent { get; } public PID Self { get; internal set; } public object Message { get { var r = _message as MessageSender; return r != null ? r.Message : _message; } private set { _message = value; } } public PID Sender => (_message as MessageSender)?.Sender; public TimeSpan ReceiveTimeout { get; private set; } public void Stash() { if (_stash == null) { _stash = new Stack<object>(); } _stash.Push(Message); } public void Respond(object message) { Sender.Tell(message); } public PID Spawn(Props props) { var id = ProcessRegistry.Instance.NextId(); return SpawnNamed(props, id); } public PID SpawnPrefix(Props props, string prefix) { var name = prefix + ProcessRegistry.Instance.NextId(); return SpawnNamed(props, name); } public PID SpawnNamed(Props props, string name) { var pid = props.Spawn($"{Self.Id}/{name}", Self); if (_children == null) { _children = new HashSet<PID>(); } _children.Add(pid); //fast path add watched if (_watching == null) { _watching = new HashSet<PID>(); } _watching.Add(pid); return pid; } public void SetBehavior(Receive receive) { _behavior.Clear(); _behavior.Push(receive); _receive = receive; } public void PushBehavior(Receive receive) { _behavior.Push(receive); _receive = receive; } public void PopBehavior() { if (_behavior.Count <= 1) { throw new Exception("Can not unbecome actor base behavior"); } _receive = _behavior.Pop(); } public void Watch(PID pid) { pid.SendSystemMessage(new Watch(Self)); if (_watching == null) { _watching = new HashSet<PID>(); } _watching.Add(pid); } public void Unwatch(PID pid) { pid.SendSystemMessage(new Unwatch(Self)); if (_watching == null) { _watching = new HashSet<PID>(); } _watching.Remove(pid); } public void SetReceiveTimeout(TimeSpan duration) { if (duration == ReceiveTimeout) { return; } if (duration > TimeSpan.Zero) { StopReceiveTimeout(); } if (duration < TimeSpan.FromMilliseconds(1)) { duration = TimeSpan.FromMilliseconds(1); } ReceiveTimeout = duration; if (ReceiveTimeout > TimeSpan.Zero) { if (_receiveTimeoutTimer == null) { _receiveTimeoutTimer = new Timer(ReceiveTimeoutCallback, null, ReceiveTimeout, ReceiveTimeout); } else { ResetReceiveTimeout(); } } } public Task ReceiveAsync(object message) { return ProcessMessageAsync(message); } public Task InvokeSystemMessageAsync(object msg) { try { switch (msg) { case Started s: return InvokeUserMessageAsync(s); case Stop _: return HandleStopAsync(); case Terminated t: return HandleTerminatedAsync(t); case Watch w: HandleWatch(w); return Task.FromResult(0); case Unwatch uw: HandleUnwatch(uw); return Task.FromResult(0); case Failure f: HandleFailure(f); return Task.FromResult(0); case Restart r: return HandleRestartAsync(); case SuspendMailbox sm: return Task.FromResult(0); case ResumeMailbox rm: return Task.FromResult(0); default: Console.WriteLine("Unknown system message {0}", msg); return Task.FromResult(0); } } catch (Exception x) { Console.WriteLine("Error handling SystemMessage {0}", x); return Task.FromResult(0); } } public Task InvokeUserMessageAsync(object msg) { var influenceTimeout = true; if (ReceiveTimeout > TimeSpan.Zero) { var notInfluenceTimeout = msg is INotInfluenceReceiveTimeout; influenceTimeout = !notInfluenceTimeout; if (influenceTimeout) { StopReceiveTimeout(); } } var res = ProcessMessageAsync(msg); if (ReceiveTimeout != TimeSpan.Zero && influenceTimeout) { //special handle non completed tasks that need to reset ReceiveTimout if (!res.IsCompleted) { return res.ContinueWith(_ => ResetReceiveTimeout()); } ResetReceiveTimeout(); } return res; } public void EscalateFailure(Exception reason, object message) { if (_restartStatistics == null) { _restartStatistics = new RestartStatistics(0, null); } var failure = new Failure(Self, reason, _restartStatistics); if (Parent == null) { HandleRootFailure(failure); } else { Self.SendSystemMessage(SuspendMailbox.Instance); Parent.SendSystemMessage(failure); } } public void EscalateFailure(PID who, Exception reason) { Self.SendSystemMessage(SuspendMailbox.Instance); Parent.SendSystemMessage(new Failure(who, reason, _restartStatistics)); } public void RestartChildren(params PID[] pids) { for (int i = 0; i < pids.Length; i++) { pids[i].SendSystemMessage(Restart.Instance); } } public void StopChildren(params PID[] pids) { for (int i = 0; i < pids.Length; i++) { pids[i].SendSystemMessage(Stop.Instance); } } public void ResumeChildren(params PID[] pids) { for (int i = 0; i < pids.Length; i++) { pids[i].SendSystemMessage(ResumeMailbox.Instance); } } internal static Task DefaultReceive(IContext context) { var c = (Context)context; if (c.Message is PoisonPill) { c.Self.Stop(); return Proto.Actor.Done; } return c._receive(context); } internal static Task DefaultSender(IContext context, PID target, MessageEnvelope envelope) { target.Ref.SendUserMessage(target, envelope.Message, envelope.Sender); return Task.FromResult(0); } private Task ProcessMessageAsync(object msg) { Message = msg; if (_receiveMiddleware != null) { return _receiveMiddleware(this); } return DefaultReceive(this); } public void Tell(PID target, object message) { SendUserMessage(target, message, null); } public void Request(PID target, object message) { SendUserMessage(target, message, Self); } public Task<T> RequestAsync<T>(PID target, object message, TimeSpan timeout) => RequestAsync(target, message, new FutureProcess<T>(timeout)); public Task<T> RequestAsync<T>(PID target, object message, CancellationToken cancellationToken) => RequestAsync(target, message, new FutureProcess<T>(cancellationToken)); public Task<T> RequestAsync<T>(PID target, object message) => RequestAsync(target, message, new FutureProcess<T>()); private Task<T> RequestAsync<T>(PID target, object message, FutureProcess<T> future) { SendUserMessage(target, message, future.PID); return future.Task; } private void SendUserMessage(PID target, object message, PID sender) { if (_senderMiddleware != null) { var messageEnvelope = message as MessageEnvelope ?? new MessageEnvelope { Message = message, Header = new MessageHeader(), Sender = sender }; _senderMiddleware(this, target, messageEnvelope); } else { target.Ref.SendUserMessage(target, message, sender); } } private void IncarnateActor() { _restarting = false; _stopping = false; Actor = _producer(); SetBehavior(ActorReceive); } private async Task HandleRestartAsync() { _stopping = false; _restarting = true; await InvokeUserMessageAsync(Restarting.Instance); if (_children != null) { foreach (var child in _children) { child.Stop(); } } await TryRestartOrTerminateAsync(); } private void HandleUnwatch(Unwatch uw) { _watchers?.Remove(uw.Watcher); } private void HandleWatch(Watch w) { if (_watchers == null) { _watchers = new HashSet<PID>(); } _watchers.Add(w.Watcher); } private void HandleFailure(Failure msg) { if (Actor is ISupervisorStrategy supervisor) { supervisor.HandleFailure(this, msg.Who, msg.RestartStatistics, msg.Reason); return; } _supervisorStrategy.HandleFailure(this, msg.Who, msg.RestartStatistics, msg.Reason); } private async Task HandleTerminatedAsync(Terminated msg) { _children.Remove(msg.Who); _watching.Remove(msg.Who); await InvokeUserMessageAsync(msg); await TryRestartOrTerminateAsync(); } private void HandleRootFailure(Failure failure) { Supervision.DefaultStrategy.HandleFailure(this, failure.Who, failure.RestartStatistics, failure.Reason); } private async Task HandleStopAsync() { _restarting = false; _stopping = true; //this is intentional await InvokeUserMessageAsync(Stopping.Instance); if (_children != null) { foreach (var child in _children) { child.Stop(); } } await TryRestartOrTerminateAsync(); } private async Task TryRestartOrTerminateAsync() { if (_receiveTimeoutTimer != null) { StopReceiveTimeout(); _receiveTimeoutTimer = null; ReceiveTimeout = TimeSpan.Zero; } if (_children?.Count > 0) { return; } if (_restarting) { await RestartAsync(); return; } if (_stopping) { await StopAsync(); } } private async Task StopAsync() { ProcessRegistry.Instance.Remove(Self); //This is intentional await InvokeUserMessageAsync(Stopped.Instance); //Notify watchers } private async Task RestartAsync() { IncarnateActor(); Self.SendSystemMessage(ResumeMailbox.Instance); await InvokeUserMessageAsync(Started.Instance); if (_stash != null) { while (_stash.Any()) { var msg = _stash.Pop(); await InvokeUserMessageAsync(msg); } } } private Task ActorReceive(IContext ctx) { var task = Actor.ReceiveAsync(ctx); return task; } private void ResetReceiveTimeout() { _receiveTimeoutTimer?.Change(ReceiveTimeout, ReceiveTimeout); } private void StopReceiveTimeout() { _receiveTimeoutTimer?.Change(-1, -1); } private void ReceiveTimeoutCallback(object state) { Self.Request(Proto.ReceiveTimeout.Instance, null); } } }
// Copyright (c) 2021 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.IO; using System.Text; using System.Collections; using System.Net; using System.Configuration; using Alachisoft.NCache.Config; using Alachisoft.NCache.Caching; using Alachisoft.NCache.Runtime.Exceptions; using Alachisoft.NCache.Common.Util; namespace Alachisoft.NCache.Config { /// <summary> /// /// </summary> internal class ChannelConfigBuilder { /// <summary> /// /// </summary> /// <param name="properties"></param> /// <returns></returns> public static string BuildTCPConfiguration(IDictionary properties,long opTimeout) { StringBuilder b = new StringBuilder(2048); b.Append(BuildTCP(properties["tcp"] as IDictionary)).Append(":"); b.Append(BuildTCPPING(properties["tcpping"] as IDictionary)).Append(":"); b.Append(BuildQueue(properties["queue"] as IDictionary)).Append(":"); b.Append(Buildpbcast_GMS(properties["pbcast.gms"] as IDictionary,false)).Append(":"); b.Append(BuildTOTAL(properties["total"] as IDictionary,opTimeout)).Append(":"); b.Append(BuildVIEW_ENFORCER(properties["view-enforcer"] as IDictionary)); return b.ToString(); } public static string BuildTCPConfiguration(IDictionary properties,long opTimeout,bool isPor) { StringBuilder b = new StringBuilder(2048); b.Append(BuildTCP(properties["tcp"] as IDictionary)).Append(":"); b.Append(BuildTCPPING(properties["tcpping"] as IDictionary)).Append(":"); b.Append(BuildQueue(properties["queue"] as IDictionary)).Append(":"); b.Append(Buildpbcast_GMS(properties["pbcast.gms"] as IDictionary,isPor)).Append(":"); b.Append(BuildTOTAL(properties["total"] as IDictionary, opTimeout)).Append(":"); b.Append(BuildVIEW_ENFORCER(properties["view-enforcer"] as IDictionary)); return b.ToString(); } /// <summary> /// /// </summary> /// <param name="properties"></param> /// <returns></returns> public static string BuildUDPConfiguration(IDictionary properties) { StringBuilder b = new StringBuilder(2048); b.Append(BuildUDP(properties["udp"] as IDictionary)).Append(":"); b.Append(BuildPING(properties["ping"] as IDictionary)).Append(":"); b.Append(BuildMERGEFAST(properties["mergefast"] as IDictionary)).Append(":"); b.Append(BuildFD_SOCK(properties["fd-sock"] as IDictionary)).Append(":"); b.Append(BuildVERIFY_SUSPECT(properties["verify-suspect"] as IDictionary)).Append(":"); b.Append(BuildFRAG(properties["frag"] as IDictionary)).Append(":"); b.Append(BuildUNICAST(properties["unicast"] as IDictionary)).Append(":"); b.Append(BuildQueue(properties["queue"] as IDictionary)).Append(":"); b.Append(Buildpbcast_NAKACK(properties["pbcast.nakack"] as IDictionary)).Append(":"); b.Append(Buildpbcast_STABLE(properties["pbcast.stable"] as IDictionary)).Append(":"); b.Append(Buildpbcast_GMS(properties["pbcast.gms"] as IDictionary,false)).Append(":"); b.Append(BuildTOTAL(properties["total"] as IDictionary,5000)).Append(":"); b.Append(BuildVIEW_ENFORCER(properties["view-enforcer"] as IDictionary)); return b.ToString(); } private static string BuildUDP(IDictionary properties) { StringBuilder b = new StringBuilder(256); b.Append("UDP(") .Append(ConfigHelper.SafeGetPair(properties,"mcast_addr", "239.0.1.10")) .Append(ConfigHelper.SafeGetPair(properties,"mcast_port", 10001)) .Append(ConfigHelper.SafeGetPair(properties,"bind_addr", null)) .Append(ConfigHelper.SafeGetPair(properties,"bind_port", null)) .Append(ConfigHelper.SafeGetPair(properties,"port_range", 256)) .Append(ConfigHelper.SafeGetPair(properties,"ip_mcast", null)) //"false" .Append(ConfigHelper.SafeGetPair(properties,"mcast_send_buf_size", null)) //32000 .Append(ConfigHelper.SafeGetPair(properties,"mcast_recv_buf_size", null)) //64000 .Append(ConfigHelper.SafeGetPair(properties,"ucast_send_buf_size", null)) //32000 .Append(ConfigHelper.SafeGetPair(properties,"ucast_recv_buf_size", null)) //64000 .Append(ConfigHelper.SafeGetPair(properties,"max_bundle_size", null)) //32000 .Append(ConfigHelper.SafeGetPair(properties,"max_bundle_timeout", null)) //20 .Append(ConfigHelper.SafeGetPair(properties,"enable_bundling", null)) //"false" .Append(ConfigHelper.SafeGetPair(properties,"down_thread", null)) .Append(ConfigHelper.SafeGetPair(properties,"up_thread", null)) .Append(ConfigHelper.SafeGetPair(properties,"use_incoming_packet_handler", null)) .Append(ConfigHelper.SafeGetPair(properties,"use_outgoing_packet_handler", null)) .Append("ip_ttl=32;") .Append(")"); return b.ToString(); } private static string BuildPING(IDictionary properties) { StringBuilder b = new StringBuilder(256); b.Append("PING(") .Append(ConfigHelper.SafeGetPair(properties,"timeout", null)) //2000 .Append(ConfigHelper.SafeGetPair(properties,"num_initial_members", null)) //2 .Append(ConfigHelper.SafeGetPair(properties,"port_range", null)) //1 .Append(ConfigHelper.SafeGetPair(properties,"initial_hosts", null)) .Append(ConfigHelper.SafeGetPair(properties,"down_thread", null)) .Append(ConfigHelper.SafeGetPair(properties,"up_thread", null)) .Append(")"); return b.ToString(); } private static string BuildMERGEFAST(IDictionary properties) { StringBuilder b = new StringBuilder(16); b.Append("MERGEFAST(") .Append(ConfigHelper.SafeGetPair(properties,"down_thread", null)) .Append(ConfigHelper.SafeGetPair(properties,"up_thread", null)) .Append(")"); return b.ToString(); } private static string BuildFD_SOCK(IDictionary properties) { StringBuilder b = new StringBuilder(64); b.Append("FD_SOCK(") .Append(ConfigHelper.SafeGetPair(properties,"get_cache_timeout", null)) //3000 .Append(ConfigHelper.SafeGetPair(properties,"start_port", null)) //49152 .Append(ConfigHelper.SafeGetPair(properties,"num_tries", null)) //3 .Append(ConfigHelper.SafeGetPair(properties,"suspect_msg_interval", null)) //5000 .Append(ConfigHelper.SafeGetPair(properties,"down_thread", null)) .Append(ConfigHelper.SafeGetPair(properties,"up_thread", null)) .Append(")"); return b.ToString(); } private static string BuildVERIFY_SUSPECT(IDictionary properties) { StringBuilder b = new StringBuilder(32); b.Append("VERIFY_SUSPECT(") .Append(ConfigHelper.SafeGetPair(properties,"timeout", 1500)) .Append(ConfigHelper.SafeGetPair(properties,"num_msgs", null)) // null .Append(ConfigHelper.SafeGetPair(properties,"down_thread", null)) .Append(ConfigHelper.SafeGetPair(properties,"up_thread", null)) .Append(")"); return b.ToString(); } private static string BuildQueue(IDictionary properties) { StringBuilder b = new StringBuilder(32); b.Append("QUEUE(") .Append(ConfigHelper.SafeGetPair(properties,"down_thread", null)) .Append(ConfigHelper.SafeGetPair(properties,"up_thread", null)) .Append(")"); return b.ToString(); } private static string Buildpbcast_NAKACK(IDictionary properties) { StringBuilder b = new StringBuilder(128); b.Append("pbcast.NAKACK(") .Append(ConfigHelper.SafeGetPair(properties,"retransmit_timeout", null)) //"600,1200,2400,4800" .Append(ConfigHelper.SafeGetPair(properties,"gc_lag", 40)) .Append(ConfigHelper.SafeGetPair(properties,"max_xmit_size", null)) // 8192 .Append(ConfigHelper.SafeGetPair(properties,"use_mcast_xmit", null)) // "false" .Append(ConfigHelper.SafeGetPair(properties,"discard_delivered_msgs", null)) // "true" .Append(ConfigHelper.SafeGetPair(properties,"down_thread", null)) .Append(ConfigHelper.SafeGetPair(properties,"up_thread", null)) .Append(")"); return b.ToString(); } private static string BuildUNICAST(IDictionary properties) { StringBuilder b = new StringBuilder(64); b.Append("UNICAST(") .Append(ConfigHelper.SafeGetPair(properties,"timeout", null)) // "800,1600,3200,6400" .Append(ConfigHelper.SafeGetPair(properties,"window_size", null)) // -1 .Append(ConfigHelper.SafeGetPair(properties,"min_threshold", null)) // -1 .Append(ConfigHelper.SafeGetPair(properties,"down_thread", null)) .Append(ConfigHelper.SafeGetPair(properties,"up_thread", null)) .Append(")"); return b.ToString(); } private static string Buildpbcast_STABLE(IDictionary properties) { StringBuilder b = new StringBuilder(256); b.Append("pbcast.STABLE(") .Append(ConfigHelper.SafeGetPair(properties,"digest_timeout", null)) // 60000 .Append(ConfigHelper.SafeGetPair(properties,"desired_avg_gossip", null)) // 20000 .Append(ConfigHelper.SafeGetPair(properties,"stability_delay", null)) // 6000 .Append(ConfigHelper.SafeGetPair(properties,"max_gossip_runs", null)) // 3 .Append(ConfigHelper.SafeGetPair(properties,"max_bytes", null)) // 0 .Append(ConfigHelper.SafeGetPair(properties,"max_suspend_time", null)) // 600000 .Append(ConfigHelper.SafeGetPair(properties,"down_thread", null)) .Append(ConfigHelper.SafeGetPair(properties,"up_thread", null)) .Append(")"); return b.ToString(); } private static string BuildFRAG(IDictionary properties) { StringBuilder b = new StringBuilder(32); b.Append("FRAG(") .Append(ConfigHelper.SafeGetPair(properties,"frag_size", null)) .Append(ConfigHelper.SafeGetPair(properties,"down_thread", null)) .Append(ConfigHelper.SafeGetPair(properties,"up_thread", null)) .Append(")"); return b.ToString(); } private static string Buildpbcast_GMS(IDictionary properties,bool isPor) { StringBuilder b = new StringBuilder(256); if (isPor) { if (properties == null) properties = new Hashtable(); properties["is_part_replica"]= "true"; } b.Append("pbcast.GMS(") .Append(ConfigHelper.SafeGetPair(properties,"shun", null)) // "true" .Append(ConfigHelper.SafeGetPair(properties,"join_timeout", null)) // 5000 .Append(ConfigHelper.SafeGetPair(properties,"join_retry_timeout", null)) // 2000 .Append(ConfigHelper.SafeGetPair(properties, "join_retry_count", null)) // 3 .Append(ConfigHelper.SafeGetPair(properties,"leave_timeout", null)) // 5000 .Append(ConfigHelper.SafeGetPair(properties,"merge_timeout", null)) // 10000 .Append(ConfigHelper.SafeGetPair(properties,"digest_timeout", null)) // 5000 .Append(ConfigHelper.SafeGetPair(properties,"disable_initial_coord", null)) // false .Append(ConfigHelper.SafeGetPair(properties,"num_prev_mbrs", null)) // 50 .Append(ConfigHelper.SafeGetPair(properties,"print_local_addr", null)) // false .Append(ConfigHelper.SafeGetPair(properties,"down_thread", null)) .Append(ConfigHelper.SafeGetPair(properties,"up_thread", null)) .Append(ConfigHelper.SafeGetPair(properties, "is_part_replica", null)) .Append(")"); return b.ToString(); } private static string BuildTOTAL(IDictionary properties,long opTimeout) { StringBuilder b = new StringBuilder(8); b.Append("TOTAL(") .Append(ConfigHelper.SafeGetPair(properties,"timeout", null)) //"600,1200,2400,4800" .Append(ConfigHelper.SafeGetPair(properties,"down_thread", null)) .Append(ConfigHelper.SafeGetPair(properties,"up_thread", null)) .Append(ConfigHelper.SafeGetPair(properties, "op_timeout", opTimeout)) .Append(")"); return b.ToString(); } private static string BuildVIEW_ENFORCER(IDictionary properties) { StringBuilder b = new StringBuilder(16); b.Append("VIEW_ENFORCER(") .Append(ConfigHelper.SafeGetPair(properties,"down_thread", null)) .Append(ConfigHelper.SafeGetPair(properties,"up_thread", null)) .Append(")"); return b.ToString(); } private static string BuildTCPPING(IDictionary properties) { StringBuilder b = new StringBuilder(256); b.Append("TCPPING(") .Append(ConfigHelper.SafeGetPair(properties,"timeout", null)) //3000 .Append(ConfigHelper.SafeGetPair(properties,"port_range", null)) //5 .Append(ConfigHelper.SafeGetPair(properties,"static", null)) //false .Append(ConfigHelper.SafeGetPair(properties,"num_initial_members", null)) //2 .Append(ConfigHelper.SafeGetPair(properties,"initial_hosts", null)) .Append(ConfigHelper.SafeGetPair(properties,"discovery_addr", "228.8.8.8")) //228.8.8.8 .Append(ConfigHelper.SafeGetPair(properties,"discovery_port", 7700)) //7700 .Append(ConfigHelper.SafeGetPair(properties,"down_thread", null)) .Append(ConfigHelper.SafeGetPair(properties,"up_thread", null)) .Append(")"); return b.ToString(); } private static string BuildTCP(IDictionary properties) { string bindIP = ServiceConfiguration.BindToIP.ToString(); StringBuilder b = new StringBuilder(256); b.Append("TCP(") .Append(ConfigHelper.SafeGetPair(properties, "connection_retries", 0)) .Append(ConfigHelper.SafeGetPair(properties, "connection_retry_interval", 0)) .Append(ConfigHelper.SafeGetPair(properties, "bind_addr", bindIP)) .Append(ConfigHelper.SafeGetPair(properties, "start_port", null)) .Append(ConfigHelper.SafeGetPair(properties, "port_range", null)) .Append(ConfigHelper.SafeGetPair(properties, "send_buf_size", null)) //32000 .Append(ConfigHelper.SafeGetPair(properties, "recv_buf_size", null)) //64000 .Append(ConfigHelper.SafeGetPair(properties, "reaper_interval", null)) //0 .Append(ConfigHelper.SafeGetPair(properties, "conn_expire_time", null)) //0 .Append(ConfigHelper.SafeGetPair(properties, "skip_suspected_members", null)) //true .Append(ConfigHelper.SafeGetPair(properties, "down_thread", true)) .Append(ConfigHelper.SafeGetPair(properties, "up_thread", true)) .Append(")"); return b.ToString(); } } }
using System; using System.Collections.Generic; using System.Text; using System.IO; namespace NotJavaScript.Tree { public interface Expression { gType _TypeOf(Environment E); void _PhpOf (Environment E, StringWriter O); }; public interface Statement { void _PhpOf(Environment E, StringWriter O); }; public class Field { public gType Typ; public string Name; public Field(string n, gType t) { Typ = t; Name = n; } } public class Arguments { public List<Field> Args; public Arguments() { Args = new List<Field>(); } public void Add(Field x) { Args.Add(x); } public gType _TypeOf() { if (Args.Count == 0) return new Type_Unit(); if (Args.Count == 1) return Args[0].Typ; Type_Tuple TT = new Type_Tuple(); foreach(Field F in Args) TT.Add(F.Typ); return TT; } public void _PhpOf(Environment E, StringWriter O) { int k = 0; O.Write("("); foreach(Field F in Args) { if(k > 0) O.Write(","); O.Write("$" + F.Name); k++; } O.Write(")"); } public string str() { StringWriter O = new StringWriter(); int k = 0; O.Write("("); foreach(Field F in Args) { if(k > 0) O.Write(","); O.Write(F.Typ.str() + " " + F.Name); k++; } O.Write(")"); return O.ToString(); } }; public interface GlobalDecl { /* NamedFunction nf; Statement dc; public bool FirstPass() { return nf != null; } public GlobalDecl(NamedFunction f) { nf = f; dc = null; } public GlobalDecl(Statement d) { dc = d; nf = null; } public string foreplay() { return ""; } public string str() { if (nf != null) return nf.str() + Console.Out.NewLine; if (dc != null) { return dc.str() + Console.Out.NewLine; } return ""; } */ } public class NamedContractType : GlobalDecl { public Type_ContractByMembers Contract; string name; public NamedContractType(string n) { name = n; Contract = new Type_ContractByMembers(); } public void Compile(Environment E) { string cType = "Explicit_" + name + "_Obj"; E.WriteLine("class " + cType); E.WriteLine("{"); foreach (string x in Contract.Members.Keys) { E.WriteLine("\tpublic $" + x + ";"); } E.WriteLine("}"); E.AddContract(name, Contract); } public string _Prototype() { return Contract.str2(name) + ";"; } } public class ServiceImport : GlobalDecl { string Ident; string Here; bool Export; Type_Functional Typ; public ServiceImport(bool export, string idPHP, string idNJS, gType T) { if (!(T is Type_Functional)) throw new Exception("Functional!"); Export = export; Ident = idPHP; Here = idNJS; Typ = T as Type_Functional; } public void Compile(Environment E) { E.AddFunction(Here, Typ); E.WriteLine("class funptr_" + Here); E.WriteLine("{"); E.WriteLine("\tpublic function Ev($Par)"); E.WriteLine("\t{"); string P = ""; for (int k = 0; k < Typ.Arity(); k++) { if (k > 0) P += ","; P += "$Par[" + k + "]"; } E.WriteLine("\t\treturn " + Ident + "("+P+");"); E.WriteLine("\t}"); E.WriteLine("}"); } } public class UsingNamespace : GlobalDecl { public string Ident; public UsingNamespace(string id) { Ident = id; } } public class LinkInto : GlobalDecl { string Ident; gType Typ; public LinkInto(string id, gType T) { Ident = id; Typ = T; } public void Compile(Environment E) { E.AddFunction(Ident, Typ); } } public class ServiceInclude : GlobalDecl { public string Ident; public ServiceInclude(string id) { Ident = id; } public void Compile(Environment E) { E.WriteLine("include(\"service."+Ident.Replace("::",".").Trim()+".php\");"); } } public class NamedPrototype : GlobalDecl { gType returntype; public string name; Arguments args; public NamedPrototype(gType rt, string n, Arguments a) { returntype = rt; name = n; args = a; } public gType _TypeOf() { return new Type_Functional(args._TypeOf(), returntype); } public void Compile0(Environment E) { E.AddFunction(name, this._TypeOf()); } } public class NamedFunction : GlobalDecl { gType returntype; public string name; Arguments args; Block code; public bool Export; public NamedFunction(bool exp, gType rt, string n, Arguments a, Block b) { Export = exp; returntype = rt; name = n; args = a; code = b; } public gType _TypeOf() { return new Type_Functional(args._TypeOf(), returntype); } public string _Prototype(string ns) { return returntype.str() + " " + ns + "_NS_" + name + args.str() + ";"; } /* public string str() { string x = ""; x = "function " + name + args.str() + code.str(); return x; } */ public void Compile0(Environment E) { E.AddFunction(name, this._TypeOf()); } public void Compile1(Environment E) { E.CurrentReturnType = returntype; if (!name.Equals("main")) { E.Push(); int k = 0; foreach (Field F in args.Args) { E.Declare(F.Name, F.Typ); } StringWriter B = new StringWriter(); code._PhpOf(E, B); E.Pop(); string ParMap = ""; foreach (Field F in args.Args) { if (k > 0) ParMap += ","; ParMap += "$" + F.Name; //E.WriteLine("$" + F.Name + "=$Par[" + k+ "];"); k++; } E.WriteLine("function "+E.CurrentNameSpace+"_NS_" + name + "("+ParMap+")"); E.WriteLine(B.ToString().Trim()); E.WriteLine("class funptr_" + E.CurrentNameSpace+"_NS_" + name); E.WriteLine("{"); E.WriteLine("\tpublic function Ev("+ParMap+")"); E.WriteLine("\t{"); E.WriteLine("\t\treturn " + E.CurrentNameSpace+"_NS_"+ name + "("+ParMap+");"); E.WriteLine("\t}"); E.WriteLine("}"); } else { E.Push(); StringWriter B = new StringWriter(); code._PhpOf(E, B); E.Pop(); E.WriteLine("function main()"); /* foreach (Field F in args.Args) { E.WriteLine("$" + F.Name + "=$Par[\"" + F.Name + "\"];"); E.Declare(F.Name, F.Typ); } */ E.WriteLine(B.ToString().Trim()); } /* P.block()._PhpOf(Gamma, S); string E = S.ToString(); StreamWriter sw = new StreamWriter("c:\\xampplite\\htdocs\\njs\\index.php"); sw.WriteLine("<?"); Gamma.DumpHeader(sw); sw.Write(""+E+""); sw.WriteLine("?>"); sw.Flush(); sw.Close(); */ } } /* public class Arguments { List<string> Args; public Arguments() { Args = new List<string>(); } public void Add(string x) { Args.Add(x); } public string str() { string x = ""; foreach (string y in Args) { if (x.Length > 0) x += ","; x += y; } return "(" + x + ")"; } }; */ }
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" using System; namespace TheArtOfDev.HtmlRenderer.Adapters.Entities { /// <summary> /// Stores a set of four floating-point numbers that represent the location and size of a rectangle. /// </summary> public struct RRect { #region Fields and Consts /// <summary> /// Represents an instance of the <see cref="RRect" /> class with its members uninitialized. /// </summary> public static readonly RRect Empty = new RRect(); private double _height; private double _width; private double _x; private double _y; #endregion /// <summary> /// Initializes a new instance of the <see cref="RRect" /> class with the specified location and size. /// </summary> /// <param name="x">The x-coordinate of the upper-left corner of the rectangle. </param> /// <param name="y">The y-coordinate of the upper-left corner of the rectangle. </param> /// <param name="width">The width of the rectangle. </param> /// <param name="height">The height of the rectangle. </param> public RRect(double x, double y, double width, double height) { _x = x; _y = y; _width = width; _height = height; } /// <summary> /// Initializes a new instance of the <see cref="RRect" /> class with the specified location and size. /// </summary> /// <param name="location">A <see cref="RPoint" /> that represents the upper-left corner of the rectangular region.</param> /// <param name="size">A <see cref="RSize" /> that represents the width and height of the rectangular region.</param> public RRect(RPoint location, RSize size) { _x = location.X; _y = location.Y; _width = size.Width; _height = size.Height; } /// <summary> /// Gets or sets the coordinates of the upper-left corner of this <see cref="RRect" /> structure. /// </summary> /// <returns>A <see cref="RPoint" /> that represents the upper-left corner of this <see cref="RRect" /> structure.</returns> public RPoint Location { get { return new RPoint(X, Y); } set { X = value.X; Y = value.Y; } } /// <summary> /// Gets or sets the size of this <see cref="RRect" />. /// </summary> /// <returns>A <see cref="RSize" /> that represents the width and height of this <see cref="RRect" /> structure.</returns> public RSize Size { get { return new RSize(Width, Height); } set { Width = value.Width; Height = value.Height; } } /// <summary> /// Gets or sets the x-coordinate of the upper-left corner of this <see cref="RRect" /> structure. /// </summary> /// <returns> /// The x-coordinate of the upper-left corner of this <see cref="RRect" /> structure. /// </returns> public double X { get { return _x; } set { _x = value; } } /// <summary> /// Gets or sets the y-coordinate of the upper-left corner of this <see cref="RRect" /> structure. /// </summary> /// <returns> /// The y-coordinate of the upper-left corner of this <see cref="RRect" /> structure. /// </returns> public double Y { get { return _y; } set { _y = value; } } /// <summary> /// Gets or sets the width of this <see cref="RRect" /> structure. /// </summary> /// <returns> /// The width of this <see cref="RRect" /> structure. /// </returns> public double Width { get { return _width; } set { _width = value; } } /// <summary> /// Gets or sets the height of this <see cref="RRect" /> structure. /// </summary> /// <returns> /// The height of this <see cref="RRect" /> structure. /// </returns> public double Height { get { return _height; } set { _height = value; } } /// <summary> /// Gets the x-coordinate of the left edge of this <see cref="RRect" /> structure. /// </summary> /// <returns> /// The x-coordinate of the left edge of this <see cref="RRect" /> structure. /// </returns> public double Left { get { return X; } } /// <summary> /// Gets the y-coordinate of the top edge of this <see cref="RRect" /> structure. /// </summary> /// <returns> /// The y-coordinate of the top edge of this <see cref="RRect" /> structure. /// </returns> public double Top { get { return Y; } } /// <summary> /// Gets the x-coordinate that is the sum of <see cref="RRect.X" /> and /// <see /// cref="RRect.Width" /> /// of this <see cref="RRect" /> structure. /// </summary> /// <returns> /// The x-coordinate that is the sum of <see cref="RRect.X" /> and /// <see /// cref="RRect.Width" /> /// of this <see cref="RRect" /> structure. /// </returns> public double Right { get { return X + Width; } } /// <summary> /// Gets the y-coordinate that is the sum of <see cref="RRect.Y" /> and /// <see /// cref="RRect.Height" /> /// of this <see cref="RRect" /> structure. /// </summary> /// <returns> /// The y-coordinate that is the sum of <see cref="RRect.Y" /> and /// <see /// cref="RRect.Height" /> /// of this <see cref="RRect" /> structure. /// </returns> public double Bottom { get { return Y + Height; } } /// <summary> /// Tests whether the <see cref="RRect.Width" /> or /// <see /// cref="RRect.Height" /> /// property of this <see cref="RRect" /> has a value of zero. /// </summary> /// <returns> /// This property returns true if the <see cref="RRect.Width" /> or /// <see /// cref="RRect.Height" /> /// property of this <see cref="RRect" /> has a value of zero; otherwise, false. /// </returns> public bool IsEmpty { get { if (Width > 0.0) return Height <= 0.0; else return true; } } /// <summary> /// Tests whether two <see cref="RRect" /> structures have equal location and size. /// </summary> /// <returns> /// This operator returns true if the two specified <see cref="RRect" /> structures have equal /// <see cref="RRect.X" />, <see cref="RRect.Y" />, <see cref="RRect.Width" />, and <see cref="RRect.Height" /> properties. /// </returns> /// <param name="left"> /// The <see cref="RRect" /> structure that is to the left of the equality operator. /// </param> /// <param name="right"> /// The <see cref="RRect" /> structure that is to the right of the equality operator. /// </param> public static bool operator ==(RRect left, RRect right) { if (Math.Abs(left.X - right.X) < 0.001 && Math.Abs(left.Y - right.Y) < 0.001 && Math.Abs(left.Width - right.Width) < 0.001) return Math.Abs(left.Height - right.Height) < 0.001; else return false; } /// <summary> /// Tests whether two <see cref="RRect" /> structures differ in location or size. /// </summary> /// <returns> /// This operator returns true if any of the <see cref="RRect.X" /> , /// <see cref="RRect.Y" />, <see cref="RRect.Width" />, or <see cref="RRect.Height" /> /// properties of the two <see cref="RRect" /> structures are unequal; otherwise false. /// </returns> /// <param name="left"> /// The <see cref="RRect" /> structure that is to the left of the inequality operator. /// </param> /// <param name="right"> /// The <see cref="RRect" /> structure that is to the right of the inequality operator. /// </param> public static bool operator !=(RRect left, RRect right) { return !(left == right); } /// <summary> /// Creates a <see cref="RRect" /> structure with upper-left corner and lower-right corner at the specified locations. /// </summary> /// <returns> /// The new <see cref="RRect" /> that this method creates. /// </returns> /// <param name="left">The x-coordinate of the upper-left corner of the rectangular region. </param> /// <param name="top">The y-coordinate of the upper-left corner of the rectangular region. </param> /// <param name="right">The x-coordinate of the lower-right corner of the rectangular region. </param> /// <param name="bottom">The y-coordinate of the lower-right corner of the rectangular region. </param> public static RRect FromLTRB(double left, double top, double right, double bottom) { return new RRect(left, top, right - left, bottom - top); } /// <summary> /// Tests whether <paramref name="obj" /> is a <see cref="RRect" /> with the same location and size of this /// <see cref="RRect" />. /// </summary> /// <returns> /// This method returns true if <paramref name="obj" /> is a <see cref="RRect" /> and its X, Y, Width, and Height properties are equal to the corresponding properties of this /// <see cref="RRect" />; otherwise, false. /// </returns> /// <param name="obj"> /// The <see cref="T:System.Object" /> to test. /// </param> public override bool Equals(object obj) { if (!(obj is RRect)) return false; var rectangleF = (RRect)obj; if (Math.Abs(rectangleF.X - X) < 0.001 && Math.Abs(rectangleF.Y - Y) < 0.001 && Math.Abs(rectangleF.Width - Width) < 0.001) return Math.Abs(rectangleF.Height - Height) < 0.001; else return false; } /// <summary> /// Determines if the specified point is contained within this <see cref="RRect" /> structure. /// </summary> /// <returns> /// This method returns true if the point defined by <paramref name="x" /> and <paramref name="y" /> is contained within this /// <see cref="RRect" /> /// structure; otherwise false. /// </returns> /// <param name="x">The x-coordinate of the point to test. </param> /// <param name="y">The y-coordinate of the point to test. </param> public bool Contains(double x, double y) { if (X <= x && x < X + Width && Y <= y) return y < Y + Height; else return false; } /// <summary> /// Determines if the specified point is contained within this <see cref="RRect" /> structure. /// </summary> /// <returns> /// This method returns true if the point represented by the <paramref name="pt" /> parameter is contained within this /// <see cref="RRect" /> /// structure; otherwise false. /// </returns> /// <param name="pt">The <see cref="RPoint" /> to test.</param> public bool Contains(RPoint pt) { return Contains(pt.X, pt.Y); } /// <summary> /// Determines if the rectangular region represented by <paramref name="rect" /> is entirely contained within this /// <see cref="RRect" /> /// structure. /// </summary> /// <returns> /// This method returns true if the rectangular region represented by <paramref name="rect" /> is entirely contained within the rectangular region represented by this /// <see cref="RRect" /> /// ; otherwise false. /// </returns> /// <param name="rect"> /// The <see cref="RRect" /> to test. /// </param> public bool Contains(RRect rect) { if (X <= rect.X && rect.X + rect.Width <= X + Width && Y <= rect.Y) return rect.Y + rect.Height <= Y + Height; else return false; } /// <summary> /// Inflates this <see cref="RRect" /> structure by the specified amount. /// </summary> /// <param name="x"> /// The amount to inflate this <see cref="RRect" /> structure horizontally. /// </param> /// <param name="y"> /// The amount to inflate this <see cref="RRect" /> structure vertically. /// </param> public void Inflate(double x, double y) { X -= x; Y -= y; Width += 2f * x; Height += 2f * y; } /// <summary> /// Inflates this <see cref="RRect" /> by the specified amount. /// </summary> /// <param name="size">The amount to inflate this rectangle. </param> public void Inflate(RSize size) { Inflate(size.Width, size.Height); } /// <summary> /// Creates and returns an inflated copy of the specified <see cref="RRect" /> structure. The copy is inflated by the specified amount. The original rectangle remains unmodified. /// </summary> /// <returns> /// The inflated <see cref="RRect" />. /// </returns> /// <param name="rect"> /// The <see cref="RRect" /> to be copied. This rectangle is not modified. /// </param> /// <param name="x">The amount to inflate the copy of the rectangle horizontally. </param> /// <param name="y">The amount to inflate the copy of the rectangle vertically. </param> public static RRect Inflate(RRect rect, double x, double y) { RRect rectangleF = rect; rectangleF.Inflate(x, y); return rectangleF; } /// <summary> /// Replaces this <see cref="RRect" /> structure with the intersection of itself and the specified /// <see /// cref="RRect" /> /// structure. /// </summary> /// <param name="rect">The rectangle to intersect. </param> public void Intersect(RRect rect) { RRect rectangleF = Intersect(rect, this); X = rectangleF.X; Y = rectangleF.Y; Width = rectangleF.Width; Height = rectangleF.Height; } /// <summary> /// Returns a <see cref="RRect" /> structure that represents the intersection of two rectangles. If there is no intersection, and empty /// <see /// cref="RRect" /> /// is returned. /// </summary> /// <returns> /// A third <see cref="RRect" /> structure the size of which represents the overlapped area of the two specified rectangles. /// </returns> /// <param name="a">A rectangle to intersect. </param> /// <param name="b">A rectangle to intersect. </param> public static RRect Intersect(RRect a, RRect b) { double x = Math.Max(a.X, b.X); double num1 = Math.Min(a.X + a.Width, b.X + b.Width); double y = Math.Max(a.Y, b.Y); double num2 = Math.Min(a.Y + a.Height, b.Y + b.Height); if (num1 >= x && num2 >= y) return new RRect(x, y, num1 - x, num2 - y); else return Empty; } /// <summary> /// Determines if this rectangle intersects with <paramref name="rect" />. /// </summary> /// <returns> /// This method returns true if there is any intersection. /// </returns> /// <param name="rect">The rectangle to test. </param> public bool IntersectsWith(RRect rect) { if (rect.X < X + Width && X < rect.X + rect.Width && rect.Y < Y + Height) return Y < rect.Y + rect.Height; else return false; } /// <summary> /// Creates the smallest possible third rectangle that can contain both of two rectangles that form a union. /// </summary> /// <returns> /// A third <see cref="RRect" /> structure that contains both of the two rectangles that form the union. /// </returns> /// <param name="a">A rectangle to union. </param> /// <param name="b">A rectangle to union. </param> public static RRect Union(RRect a, RRect b) { double x = Math.Min(a.X, b.X); double num1 = Math.Max(a.X + a.Width, b.X + b.Width); double y = Math.Min(a.Y, b.Y); double num2 = Math.Max(a.Y + a.Height, b.Y + b.Height); return new RRect(x, y, num1 - x, num2 - y); } /// <summary> /// Adjusts the location of this rectangle by the specified amount. /// </summary> /// <param name="pos">The amount to offset the location. </param> public void Offset(RPoint pos) { Offset(pos.X, pos.Y); } /// <summary> /// Adjusts the location of this rectangle by the specified amount. /// </summary> /// <param name="x">The amount to offset the location horizontally. </param> /// <param name="y">The amount to offset the location vertically. </param> public void Offset(double x, double y) { X += x; Y += y; } /// <summary> /// Gets the hash code for this <see cref="RRect" /> structure. For information about the use of hash codes, see Object.GetHashCode. /// </summary> /// <returns>The hash code for this <see cref="RRect" /></returns> public override int GetHashCode() { return (int)(uint)X ^ ((int)(uint)Y << 13 | (int)((uint)Y >> 19)) ^ ((int)(uint)Width << 26 | (int)((uint)Width >> 6)) ^ ((int)(uint)Height << 7 | (int)((uint)Height >> 25)); } /// <summary> /// Converts the Location and Size of this <see cref="RRect" /> to a human-readable string. /// </summary> /// <returns> /// A string that contains the position, width, and height of this <see cref="RRect" /> structure for example, "{X=20, Y=20, Width=100, Height=50}". /// </returns> public override string ToString() { return "{X=" + X + ",Y=" + Y + ",Width=" + Width + ",Height=" + Height + "}"; } } }
// Copyright (c) Pomelo Foundation. All rights reserved. // Licensed under the MIT. See LICENSE in the project root for license information. using System; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Utilities; using Pomelo.EntityFrameworkCore.MySql.Infrastructure; using Pomelo.EntityFrameworkCore.MySql.Metadata.Internal; // ReSharper disable once CheckNamespace namespace Microsoft.EntityFrameworkCore { /// <summary> /// MySQL specific extension methods for <see cref="PropertyBuilder" />. /// </summary> public static class MySqlPropertyBuilderExtensions { /// <summary> /// Configures the key property to use the MySQL IDENTITY feature to generate values for new entities, /// when targeting MySQL. This method sets the property to be <see cref="ValueGenerated.OnAdd" />. /// </summary> /// <param name="propertyBuilder"> The builder for the property being configured. </param> /// <returns> The same builder instance so that multiple calls can be chained. </returns> public static PropertyBuilder UseMySqlIdentityColumn( [NotNull] this PropertyBuilder propertyBuilder) { Check.NotNull(propertyBuilder, nameof(propertyBuilder)); var property = propertyBuilder.Metadata; property.SetValueGenerationStrategy(MySqlValueGenerationStrategy.IdentityColumn); return propertyBuilder; } /// <summary> /// Configures the key property to use the MySQL IDENTITY feature to generate values for new entities, /// when targeting MySQL. This method sets the property to be <see cref="ValueGenerated.OnAdd" />. /// </summary> /// <typeparam name="TProperty"> The type of the property being configured. </typeparam> /// <param name="propertyBuilder"> The builder for the property being configured. </param> /// <returns> The same builder instance so that multiple calls can be chained. </returns> public static PropertyBuilder<TProperty> UseMySqlIdentityColumn<TProperty>( [NotNull] this PropertyBuilder<TProperty> propertyBuilder) => (PropertyBuilder<TProperty>)UseMySqlIdentityColumn((PropertyBuilder)propertyBuilder); /// <summary> /// Configures the key property to use the MySQL Computed feature to generate values for new entities, /// when targeting MySQL. This method sets the property to be <see cref="ValueGenerated.OnAddOrUpdate" />. /// </summary> /// <param name="propertyBuilder"> The builder for the property being configured. </param> /// <returns> The same builder instance so that multiple calls can be chained. </returns> public static PropertyBuilder UseMySqlComputedColumn( [NotNull] this PropertyBuilder propertyBuilder) { Check.NotNull(propertyBuilder, nameof(propertyBuilder)); var property = propertyBuilder.Metadata; property.SetValueGenerationStrategy(MySqlValueGenerationStrategy.ComputedColumn); return propertyBuilder; } /// <summary> /// Configures the key property to use the MySQL Computed feature to generate values for new entities, /// when targeting MySQL. This method sets the property to be <see cref="ValueGenerated.OnAddOrUpdate" />. /// </summary> /// <typeparam name="TProperty"> The type of the property being configured. </typeparam> /// <param name="propertyBuilder"> The builder for the property being configured. </param> /// <returns> The same builder instance so that multiple calls can be chained. </returns> public static PropertyBuilder<TProperty> UseMySqlComputedColumn<TProperty>( [NotNull] this PropertyBuilder<TProperty> propertyBuilder) => (PropertyBuilder<TProperty>)UseMySqlComputedColumn((PropertyBuilder)propertyBuilder); /// <summary> /// Configures the charset for the property's column. /// </summary> /// <param name="propertyBuilder">The builder for the property being configured.</param> /// <param name="charSet">The name of the charset to configure for the property's column.</param> /// <returns>The same builder instance so that multiple calls can be chained.</returns> public static PropertyBuilder HasCharSet( [NotNull] this PropertyBuilder propertyBuilder, string charSet) { Check.NotNull(propertyBuilder, nameof(propertyBuilder)); var property = propertyBuilder.Metadata; property.SetCharSet(charSet); return propertyBuilder; } /// <summary> /// Configures the charset for the property's column. /// </summary> /// <param name="propertyBuilder">The builder for the property being configured.</param> /// <param name="charSet">The name of the charset to configure for the property's column.</param> /// <returns>The same builder instance so that multiple calls can be chained.</returns> public static PropertyBuilder<TProperty> HasCharSet<TProperty>( [NotNull] this PropertyBuilder<TProperty> propertyBuilder, string charSet) => (PropertyBuilder<TProperty>)HasCharSet((PropertyBuilder)propertyBuilder, charSet); /// <summary> /// Configures the charset for the property's column. /// </summary> /// <param name="propertyBuilder">The builder for the property being configured.</param> /// <param name="charSet">The name of the charset to configure for the property's column.</param> /// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param> /// <returns> /// The same builder instance if the configuration was applied, /// <see langword="null" /> otherwise. /// </returns> public static IConventionPropertyBuilder HasCharSet( this IConventionPropertyBuilder propertyBuilder, string charSet, bool fromDataAnnotation = false) { if (!propertyBuilder.CanSetCharSet(charSet, fromDataAnnotation)) { return null; } propertyBuilder.Metadata.SetCharSet(charSet, fromDataAnnotation); return propertyBuilder; } /// <summary> /// Returns a value indicating whether the MySQL character set can be set on the column associated with this property. /// </summary> /// <param name="propertyBuilder"> The builder for the property being configured. </param> /// <param name="charSet"> The name of the character set. </param> /// <param name="fromDataAnnotation"> Indicates whether the configuration was specified using a data annotation. </param> /// <returns> <see langword="true" /> if the given value can be set as the character set for the column. </returns> public static bool CanSetCharSet( this IConventionPropertyBuilder propertyBuilder, string charSet, bool fromDataAnnotation = false) => propertyBuilder.CanSetAnnotation( MySqlAnnotationNames.CharSet, charSet, fromDataAnnotation); /// <summary> /// Configures the collation for the property's column. /// </summary> /// <param name="propertyBuilder">The builder for the property being configured.</param> /// <param name="collation">The name of the collation to configure for the property's column.</param> /// <returns>The same builder instance so that multiple calls can be chained.</returns> [Obsolete("Call 'UseCollation()' instead.")] public static PropertyBuilder HasCollation( [NotNull] this PropertyBuilder propertyBuilder, string collation) { Check.NotNull(propertyBuilder, nameof(propertyBuilder)); return propertyBuilder.UseCollation(collation); } /// <summary> /// Configures the collation for the property's column. /// </summary> /// <param name="propertyBuilder">The builder for the property being configured.</param> /// <param name="collation">The name of the collation to configure for the property's column.</param> /// <returns>The same builder instance so that multiple calls can be chained.</returns> [Obsolete("Call 'UseCollation()' instead.")] public static PropertyBuilder<TProperty> HasCollation<TProperty>( [NotNull] this PropertyBuilder<TProperty> propertyBuilder, string collation) => (PropertyBuilder<TProperty>)HasCollation((PropertyBuilder)propertyBuilder, collation); /// <summary> /// Restricts the Spatial Reference System Identifier (SRID) for the property's column. /// </summary> /// <param name="propertyBuilder">The builder for the property being configured.</param> /// <param name="srid">The SRID to configure for the property's column.</param> /// <returns>The same builder instance so that multiple calls can be chained.</returns> public static PropertyBuilder HasSpatialReferenceSystem( [NotNull] this PropertyBuilder propertyBuilder, int? srid) { Check.NotNull(propertyBuilder, nameof(propertyBuilder)); var property = propertyBuilder.Metadata; property.SetSpatialReferenceSystem(srid); return propertyBuilder; } /// <summary> /// Restricts the Spatial Reference System Identifier (SRID) for the property's column. /// </summary> /// <param name="propertyBuilder">The builder for the property being configured.</param> /// <param name="srid">The SRID to configure for the property's column.</param> /// <returns>The same builder instance so that multiple calls can be chained.</returns> public static PropertyBuilder<TProperty> HasSpatialReferenceSystem<TProperty>( [NotNull] this PropertyBuilder<TProperty> propertyBuilder, int? srid) => (PropertyBuilder<TProperty>)HasSpatialReferenceSystem((PropertyBuilder)propertyBuilder, srid); } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using FluentAssertions; using JsonApiDotNetCore.Serialization.Objects; using JsonApiDotNetCoreTests.IntegrationTests.Microservices.Messages; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using TestBuildingBlocks; using Xunit; namespace JsonApiDotNetCoreTests.IntegrationTests.Microservices.TransactionalOutboxPattern { public sealed partial class OutboxTests { [Fact] public async Task Create_user_writes_to_outbox() { // Arrange var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>(); string newLoginName = _fakers.DomainUser.Generate().LoginName; string newDisplayName = _fakers.DomainUser.Generate().DisplayName; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<OutgoingMessage>(); }); var requestBody = new { data = new { type = "domainUsers", attributes = new { loginName = newLoginName, displayName = newDisplayName } } }; const string route = "/domainUsers"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Created); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Attributes["loginName"].Should().Be(newLoginName); responseDocument.Data.SingleValue.Attributes["displayName"].Should().Be(newDisplayName); hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[] { (typeof(DomainUser), ResourceDefinitionHitCounter.ExtensibilityPoint.OnPrepareWriteAsync), (typeof(DomainUser), ResourceDefinitionHitCounter.ExtensibilityPoint.OnWritingAsync) }, options => options.WithStrictOrdering()); Guid newUserId = Guid.Parse(responseDocument.Data.SingleValue.Id); await _testContext.RunOnDatabaseAsync(async dbContext => { List<OutgoingMessage> messages = await dbContext.OutboxMessages.OrderBy(message => message.Id).ToListAsync(); messages.Should().HaveCount(1); var content = messages[0].GetContentAs<UserCreatedContent>(); content.UserId.Should().Be(newUserId); content.UserLoginName.Should().Be(newLoginName); content.UserDisplayName.Should().Be(newDisplayName); }); } [Fact] public async Task Create_user_in_group_writes_to_outbox() { // Arrange var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>(); DomainGroup existingGroup = _fakers.DomainGroup.Generate(); string newLoginName = _fakers.DomainUser.Generate().LoginName; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<OutgoingMessage>(); dbContext.Groups.Add(existingGroup); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "domainUsers", attributes = new { loginName = newLoginName }, relationships = new { group = new { data = new { type = "domainGroups", id = existingGroup.StringId } } } } }; const string route = "/domainUsers"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Created); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Attributes["loginName"].Should().Be(newLoginName); responseDocument.Data.SingleValue.Attributes["displayName"].Should().BeNull(); hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[] { (typeof(DomainUser), ResourceDefinitionHitCounter.ExtensibilityPoint.OnPrepareWriteAsync), (typeof(DomainUser), ResourceDefinitionHitCounter.ExtensibilityPoint.OnSetToOneRelationshipAsync), (typeof(DomainUser), ResourceDefinitionHitCounter.ExtensibilityPoint.OnWritingAsync) }, options => options.WithStrictOrdering()); Guid newUserId = Guid.Parse(responseDocument.Data.SingleValue.Id); await _testContext.RunOnDatabaseAsync(async dbContext => { List<OutgoingMessage> messages = await dbContext.OutboxMessages.OrderBy(message => message.Id).ToListAsync(); messages.Should().HaveCount(2); var content1 = messages[0].GetContentAs<UserCreatedContent>(); content1.UserId.Should().Be(newUserId); content1.UserLoginName.Should().Be(newLoginName); content1.UserDisplayName.Should().BeNull(); var content2 = messages[1].GetContentAs<UserAddedToGroupContent>(); content2.UserId.Should().Be(newUserId); content2.GroupId.Should().Be(existingGroup.Id); }); } [Fact] public async Task Update_user_writes_to_outbox() { // Arrange var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>(); DomainUser existingUser = _fakers.DomainUser.Generate(); string newLoginName = _fakers.DomainUser.Generate().LoginName; string newDisplayName = _fakers.DomainUser.Generate().DisplayName; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<OutgoingMessage>(); dbContext.Users.Add(existingUser); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "domainUsers", id = existingUser.StringId, attributes = new { loginName = newLoginName, displayName = newDisplayName } } }; string route = $"/domainUsers/{existingUser.StringId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[] { (typeof(DomainUser), ResourceDefinitionHitCounter.ExtensibilityPoint.OnPrepareWriteAsync), (typeof(DomainUser), ResourceDefinitionHitCounter.ExtensibilityPoint.OnWritingAsync) }, options => options.WithStrictOrdering()); await _testContext.RunOnDatabaseAsync(async dbContext => { List<OutgoingMessage> messages = await dbContext.OutboxMessages.OrderBy(message => message.Id).ToListAsync(); messages.Should().HaveCount(2); var content1 = messages[0].GetContentAs<UserLoginNameChangedContent>(); content1.UserId.Should().Be(existingUser.Id); content1.BeforeUserLoginName.Should().Be(existingUser.LoginName); content1.AfterUserLoginName.Should().Be(newLoginName); var content2 = messages[1].GetContentAs<UserDisplayNameChangedContent>(); content2.UserId.Should().Be(existingUser.Id); content2.BeforeUserDisplayName.Should().Be(existingUser.DisplayName); content2.AfterUserDisplayName.Should().Be(newDisplayName); }); } [Fact] public async Task Update_user_clear_group_writes_to_outbox() { // Arrange var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>(); DomainUser existingUser = _fakers.DomainUser.Generate(); existingUser.Group = _fakers.DomainGroup.Generate(); string newDisplayName = _fakers.DomainUser.Generate().DisplayName; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<OutgoingMessage>(); dbContext.Users.Add(existingUser); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "domainUsers", id = existingUser.StringId, attributes = new { displayName = newDisplayName }, relationships = new { group = new { data = (object)null } } } }; string route = $"/domainUsers/{existingUser.StringId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[] { (typeof(DomainUser), ResourceDefinitionHitCounter.ExtensibilityPoint.OnPrepareWriteAsync), (typeof(DomainUser), ResourceDefinitionHitCounter.ExtensibilityPoint.OnSetToOneRelationshipAsync), (typeof(DomainUser), ResourceDefinitionHitCounter.ExtensibilityPoint.OnWritingAsync) }, options => options.WithStrictOrdering()); await _testContext.RunOnDatabaseAsync(async dbContext => { List<OutgoingMessage> messages = await dbContext.OutboxMessages.OrderBy(message => message.Id).ToListAsync(); messages.Should().HaveCount(2); var content1 = messages[0].GetContentAs<UserDisplayNameChangedContent>(); content1.UserId.Should().Be(existingUser.Id); content1.BeforeUserDisplayName.Should().Be(existingUser.DisplayName); content1.AfterUserDisplayName.Should().Be(newDisplayName); var content2 = messages[1].GetContentAs<UserRemovedFromGroupContent>(); content2.UserId.Should().Be(existingUser.Id); content2.GroupId.Should().Be(existingUser.Group.Id); }); } [Fact] public async Task Update_user_add_to_group_writes_to_outbox() { // Arrange var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>(); DomainUser existingUser = _fakers.DomainUser.Generate(); DomainGroup existingGroup = _fakers.DomainGroup.Generate(); string newDisplayName = _fakers.DomainUser.Generate().DisplayName; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<OutgoingMessage>(); dbContext.AddInRange(existingUser, existingGroup); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "domainUsers", id = existingUser.StringId, attributes = new { displayName = newDisplayName }, relationships = new { group = new { data = new { type = "domainGroups", id = existingGroup.StringId } } } } }; string route = $"/domainUsers/{existingUser.StringId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[] { (typeof(DomainUser), ResourceDefinitionHitCounter.ExtensibilityPoint.OnPrepareWriteAsync), (typeof(DomainUser), ResourceDefinitionHitCounter.ExtensibilityPoint.OnSetToOneRelationshipAsync), (typeof(DomainUser), ResourceDefinitionHitCounter.ExtensibilityPoint.OnWritingAsync) }, options => options.WithStrictOrdering()); await _testContext.RunOnDatabaseAsync(async dbContext => { List<OutgoingMessage> messages = await dbContext.OutboxMessages.OrderBy(message => message.Id).ToListAsync(); messages.Should().HaveCount(2); var content1 = messages[0].GetContentAs<UserDisplayNameChangedContent>(); content1.UserId.Should().Be(existingUser.Id); content1.BeforeUserDisplayName.Should().Be(existingUser.DisplayName); content1.AfterUserDisplayName.Should().Be(newDisplayName); var content2 = messages[1].GetContentAs<UserAddedToGroupContent>(); content2.UserId.Should().Be(existingUser.Id); content2.GroupId.Should().Be(existingGroup.Id); }); } [Fact] public async Task Update_user_move_to_group_writes_to_outbox() { // Arrange var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>(); DomainUser existingUser = _fakers.DomainUser.Generate(); existingUser.Group = _fakers.DomainGroup.Generate(); DomainGroup existingGroup = _fakers.DomainGroup.Generate(); string newDisplayName = _fakers.DomainUser.Generate().DisplayName; await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<OutgoingMessage>(); dbContext.AddInRange(existingUser, existingGroup); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "domainUsers", id = existingUser.StringId, attributes = new { displayName = newDisplayName }, relationships = new { group = new { data = new { type = "domainGroups", id = existingGroup.StringId } } } } }; string route = $"/domainUsers/{existingUser.StringId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[] { (typeof(DomainUser), ResourceDefinitionHitCounter.ExtensibilityPoint.OnPrepareWriteAsync), (typeof(DomainUser), ResourceDefinitionHitCounter.ExtensibilityPoint.OnSetToOneRelationshipAsync), (typeof(DomainUser), ResourceDefinitionHitCounter.ExtensibilityPoint.OnWritingAsync) }, options => options.WithStrictOrdering()); await _testContext.RunOnDatabaseAsync(async dbContext => { List<OutgoingMessage> messages = await dbContext.OutboxMessages.OrderBy(message => message.Id).ToListAsync(); messages.Should().HaveCount(2); var content1 = messages[0].GetContentAs<UserDisplayNameChangedContent>(); content1.UserId.Should().Be(existingUser.Id); content1.BeforeUserDisplayName.Should().Be(existingUser.DisplayName); content1.AfterUserDisplayName.Should().Be(newDisplayName); var content2 = messages[1].GetContentAs<UserMovedToGroupContent>(); content2.UserId.Should().Be(existingUser.Id); content2.BeforeGroupId.Should().Be(existingUser.Group.Id); content2.AfterGroupId.Should().Be(existingGroup.Id); }); } [Fact] public async Task Delete_user_writes_to_outbox() { // Arrange var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>(); DomainUser existingUser = _fakers.DomainUser.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<OutgoingMessage>(); dbContext.Users.Add(existingUser); await dbContext.SaveChangesAsync(); }); string route = $"/domainUsers/{existingUser.StringId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[] { (typeof(DomainUser), ResourceDefinitionHitCounter.ExtensibilityPoint.OnWritingAsync) }, options => options.WithStrictOrdering()); await _testContext.RunOnDatabaseAsync(async dbContext => { List<OutgoingMessage> messages = await dbContext.OutboxMessages.OrderBy(message => message.Id).ToListAsync(); messages.Should().HaveCount(1); var content = messages[0].GetContentAs<UserDeletedContent>(); content.UserId.Should().Be(existingUser.Id); }); } [Fact] public async Task Delete_user_in_group_writes_to_outbox() { // Arrange var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>(); DomainUser existingUser = _fakers.DomainUser.Generate(); existingUser.Group = _fakers.DomainGroup.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<OutgoingMessage>(); dbContext.Users.Add(existingUser); await dbContext.SaveChangesAsync(); }); string route = $"/domainUsers/{existingUser.StringId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecuteDeleteAsync<string>(route); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[] { (typeof(DomainUser), ResourceDefinitionHitCounter.ExtensibilityPoint.OnWritingAsync) }, options => options.WithStrictOrdering()); await _testContext.RunOnDatabaseAsync(async dbContext => { List<OutgoingMessage> messages = await dbContext.OutboxMessages.OrderBy(message => message.Id).ToListAsync(); messages.Should().HaveCount(2); var content1 = messages[0].GetContentAs<UserRemovedFromGroupContent>(); content1.UserId.Should().Be(existingUser.Id); content1.GroupId.Should().Be(existingUser.Group.Id); var content2 = messages[1].GetContentAs<UserDeletedContent>(); content2.UserId.Should().Be(existingUser.Id); }); } [Fact] public async Task Clear_group_from_user_writes_to_outbox() { // Arrange var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>(); DomainUser existingUser = _fakers.DomainUser.Generate(); existingUser.Group = _fakers.DomainGroup.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<OutgoingMessage>(); dbContext.Users.Add(existingUser); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = (object)null }; string route = $"/domainUsers/{existingUser.StringId}/relationships/group"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[] { (typeof(DomainUser), ResourceDefinitionHitCounter.ExtensibilityPoint.OnPrepareWriteAsync), (typeof(DomainUser), ResourceDefinitionHitCounter.ExtensibilityPoint.OnSetToOneRelationshipAsync), (typeof(DomainUser), ResourceDefinitionHitCounter.ExtensibilityPoint.OnWritingAsync) }, options => options.WithStrictOrdering()); await _testContext.RunOnDatabaseAsync(async dbContext => { List<OutgoingMessage> messages = await dbContext.OutboxMessages.OrderBy(message => message.Id).ToListAsync(); messages.Should().HaveCount(1); var content = messages[0].GetContentAs<UserRemovedFromGroupContent>(); content.UserId.Should().Be(existingUser.Id); content.GroupId.Should().Be(existingUser.Group.Id); }); } [Fact] public async Task Assign_group_to_user_writes_to_outbox() { // Arrange var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>(); DomainUser existingUser = _fakers.DomainUser.Generate(); DomainGroup existingGroup = _fakers.DomainGroup.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<OutgoingMessage>(); dbContext.AddInRange(existingUser, existingGroup); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "domainGroups", id = existingGroup.StringId } }; string route = $"/domainUsers/{existingUser.StringId}/relationships/group"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[] { (typeof(DomainUser), ResourceDefinitionHitCounter.ExtensibilityPoint.OnPrepareWriteAsync), (typeof(DomainUser), ResourceDefinitionHitCounter.ExtensibilityPoint.OnSetToOneRelationshipAsync), (typeof(DomainUser), ResourceDefinitionHitCounter.ExtensibilityPoint.OnWritingAsync) }, options => options.WithStrictOrdering()); await _testContext.RunOnDatabaseAsync(async dbContext => { List<OutgoingMessage> messages = await dbContext.OutboxMessages.OrderBy(message => message.Id).ToListAsync(); messages.Should().HaveCount(1); var content = messages[0].GetContentAs<UserAddedToGroupContent>(); content.UserId.Should().Be(existingUser.Id); content.GroupId.Should().Be(existingGroup.Id); }); } [Fact] public async Task Replace_group_for_user_writes_to_outbox() { // Arrange var hitCounter = _testContext.Factory.Services.GetRequiredService<ResourceDefinitionHitCounter>(); DomainUser existingUser = _fakers.DomainUser.Generate(); existingUser.Group = _fakers.DomainGroup.Generate(); DomainGroup existingGroup = _fakers.DomainGroup.Generate(); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<OutgoingMessage>(); dbContext.AddInRange(existingUser, existingGroup); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "domainGroups", id = existingGroup.StringId } }; string route = $"/domainUsers/{existingUser.StringId}/relationships/group"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); hitCounter.HitExtensibilityPoints.Should().BeEquivalentTo(new[] { (typeof(DomainUser), ResourceDefinitionHitCounter.ExtensibilityPoint.OnPrepareWriteAsync), (typeof(DomainUser), ResourceDefinitionHitCounter.ExtensibilityPoint.OnSetToOneRelationshipAsync), (typeof(DomainUser), ResourceDefinitionHitCounter.ExtensibilityPoint.OnWritingAsync) }, options => options.WithStrictOrdering()); await _testContext.RunOnDatabaseAsync(async dbContext => { List<OutgoingMessage> messages = await dbContext.OutboxMessages.OrderBy(message => message.Id).ToListAsync(); messages.Should().HaveCount(1); var content = messages[0].GetContentAs<UserMovedToGroupContent>(); content.UserId.Should().Be(existingUser.Id); content.BeforeGroupId.Should().Be(existingUser.Group.Id); content.AfterGroupId.Should().Be(existingGroup.Id); }); } } }
// ---------- IDrivable.cs ---------- namespace CSharpTutA.cs { // An interface is a class with nothing but // abstract methods. Interfaces are used // to represent a contract an object may // decide to support. // Interfaces commonly have names that // are adjectives because adjectives // modify nouns (Objects). The also // describe abstract things // It is common to prefix your interfaces with // an I interface IDrivable { // Interfaces can have properties int Wheels { get; set; } double Speed { get; set; } // Classes that inherit an interface // must fulfill the contract and // implement every abstract method void Move(); void Stop(); } } // ---------- Vehicle.cs ---------- using System; namespace CSharpTutA.cs { class Vehicle : IDrivable { // Vehicle properties public string Brand { get; set; } public Vehicle(string brand = "No Brand", int wheels = 0, double speed = 0) { Brand = brand; Wheels = wheels; Speed = speed; } // Properties and methods from // the interface public double Speed {get; set;} public int Wheels {get; set;} public void Move() { Console.WriteLine($"The {Brand} Moves Forward at {Speed} MPH"); } public void Stop() { Console.WriteLine($"The {Brand} Stops"); Speed = 0; } } } // ---------- Program.cs ---------- using System; // A class can support multiple interfaces. // Create an interface Project -> Add New Item // and select Interface namespace CSharpTutA.cs { class Program { static void Main(string[] args) { // Create a Vehicle object Vehicle buick = new Vehicle("Buick", 4, 160); // Check if Vehicle implements // IDrivable if(buick is IDrivable) { buick.Move(); buick.Stop(); } else { Console.WriteLine("The {0} can't be driven", buick.Brand); } // We are now modeling the act of // picking up a remote, aiming it // at the TV, clicking the power // button and then watching as // the TV turns on and off // Pick up the TV remote IElectronicDevice TV = TVRemote.GetDevice(); // Create the power button PowerButton powBut = new PowerButton(TV); // Turn the TV on and off with each // press powBut.Execute(); powBut.Undo(); Console.ReadLine(); } } } // ---------- IElectronicDevice.cs ---------- namespace CSharpTutA.cs { // With interfaces you can create very // flexible systems. Here I'll model // generic electronic devices like // TVs and Radios and remotes that // control them and the buttons on the // remotes. interface IElectronicDevice { // We want each device to have // these capabilities void On(); void Off(); void VolumeUp(); void VolumeDown(); } } // ---------- Television.cs ---------- using System; namespace CSharpTutA.cs { // Because we implemented the // ElectronicDevice interface any // other device we create will know // exactly how to interface with it. class Television : IElectronicDevice { public int Volume { get; set; } public void Off() { Console.WriteLine("The TV is Off"); } public void On() { Console.WriteLine("The TV is On"); } public void VolumeDown() { if (Volume != 0) Volume--; Console.WriteLine($"The TV Volume is at {Volume}"); } public void VolumeUp() { if (Volume != 100) Volume++; Console.WriteLine($"The TV Volume is at {Volume}"); } } } // ---------- ICommand.cs ---------- namespace CSharpTutA.cs { interface ICommand { // We can model what happens when // a button is pressed for example // a power button. By breaking // everything down we can add // an infinite amount of flexibility void Execute(); void Undo(); } } // ---------- PowerButton.cs ---------- namespace CSharpTutA.cs { class PowerButton : ICommand { // You can refer to instances using // the interface IElectronicDevice device; // Now we get into the specifics of // what happens when the power button // is pressed. public PowerButton(IElectronicDevice device) { this.device = device; } public void Execute() { device.On(); } // You can provide a way to undo // an action just like the power // button does on a remote public void Undo() { device.Off(); } } } // ---------- TVRemote.cs ---------- namespace CSharpTutA.cs { class TVRemote { // Now we are modeling the action of // picking up the remote with our hand public static IElectronicDevice GetDevice() { return new Television(); } } }
// 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; using System.IO; using System.Threading; namespace System.Xml { /// <summary> /// The XmlCharType class is used for quick character type recognition /// which is optimized for the first 127 ascii characters. /// </summary> internal unsafe struct XmlCharType { // Surrogate constants internal const int SurHighStart = 0xd800; // 1101 10xx internal const int SurHighEnd = 0xdbff; internal const int SurLowStart = 0xdc00; // 1101 11xx internal const int SurLowEnd = 0xdfff; internal const int SurMask = 0xfc00; // 1111 11xx // Characters defined in the XML 1.0 Fourth Edition // Whitespace chars -- Section 2.3 [3] // Letters -- Appendix B [84] // Starting NCName characters -- Section 2.3 [5] (Starting Name characters without ':') // NCName characters -- Section 2.3 [4] (Name characters without ':') // Character data characters -- Section 2.2 [2] // PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%] Section 2.3 of spec internal const int fWhitespace = 1; internal const int fLetter = 2; internal const int fNCStartNameSC = 4; internal const int fNCNameSC = 8; internal const int fCharData = 16; internal const int fNCNameXml4e = 32; internal const int fText = 64; internal const int fAttrValue = 128; // bitmap for public ID characters - 1 bit per character 0x0 - 0x80; no character > 0x80 is a PUBLIC ID char private const string s_PublicIdBitmap = "\u2400\u0000\uffbb\uafff\uffff\u87ff\ufffe\u07ff"; // size of XmlCharType table private const uint CharPropertiesSize = (uint)char.MaxValue + 1; // static lock for XmlCharType class private static object s_Lock; private static object StaticLock { get { if (s_Lock == null) { object o = new object(); Interlocked.CompareExchange<object>(ref s_Lock, o, null); } return s_Lock; } } private static volatile byte* s_CharProperties; internal byte* charProperties; private static void InitInstance() { lock (StaticLock) { if (s_CharProperties != null) { return; } UnmanagedMemoryStream memStream = (UnmanagedMemoryStream)typeof(XmlWriter).Assembly.GetManifestResourceStream("XmlCharType.bin"); Debug.Assert(memStream.Length == CharPropertiesSize); byte* chProps = memStream.PositionPointer; Thread.MemoryBarrier(); // For weak memory models (IA64) s_CharProperties = chProps; } } private XmlCharType(byte* charProperties) { Debug.Assert(s_CharProperties != null); this.charProperties = charProperties; } public static XmlCharType Instance { get { if (s_CharProperties == null) { InitInstance(); } return new XmlCharType(s_CharProperties); } } // NOTE: This method will not be inlined (because it uses byte* charProperties) public bool IsWhiteSpace(char ch) { return (charProperties[ch] & fWhitespace) != 0; } // NOTE: This method will not be inlined (because it uses byte* charProperties) public bool IsNCNameSingleChar(char ch) { return (charProperties[ch] & fNCNameSC) != 0; } // NOTE: This method will not be inlined (because it uses byte* charProperties) public bool IsStartNCNameSingleChar(char ch) { return (charProperties[ch] & fNCStartNameSC) != 0; } public bool IsNameSingleChar(char ch) { return IsNCNameSingleChar(ch) || ch == ':'; } // NOTE: This method will not be inlined (because it uses byte* charProperties) public bool IsCharData(char ch) { return (charProperties[ch] & fCharData) != 0; } // [13] PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%] Section 2.3 of spec public bool IsPubidChar(char ch) { if (ch < (char)0x80) { return (s_PublicIdBitmap[ch >> 4] & (1 << (ch & 0xF))) != 0; } return false; } // TextChar = CharData - { 0xA, 0xD, '<', '&', ']' } // NOTE: This method will not be inlined (because it uses byte* charProperties) internal bool IsTextChar(char ch) { return (charProperties[ch] & fText) != 0; } // AttrValueChar = CharData - { 0xA, 0xD, 0x9, '<', '>', '&', '\'', '"' } // NOTE: This method will not be inlined (because it uses byte* charProperties) internal bool IsAttributeValueChar(char ch) { return (charProperties[ch] & fAttrValue) != 0; } // XML 1.0 Fourth Edition definitions // // NOTE: This method will not be inlined (because it uses byte* charProperties) public bool IsLetter(char ch) { return (charProperties[ch] & fLetter) != 0; } // NOTE: This method will not be inlined (because it uses byte* charProperties) // This method uses the XML 4th edition name character ranges public bool IsNCNameCharXml4e(char ch) { return (charProperties[ch] & fNCNameXml4e) != 0; } // This method uses the XML 4th edition name character ranges public bool IsStartNCNameCharXml4e(char ch) { return IsLetter(ch) || ch == '_'; } // This method uses the XML 4th edition name character ranges public bool IsNameCharXml4e(char ch) { return IsNCNameCharXml4e(ch) || ch == ':'; } // Digit methods public static bool IsDigit(char ch) { return InRange(ch, 0x30, 0x39); } // Surrogate methods internal static bool IsHighSurrogate(int ch) { return InRange(ch, SurHighStart, SurHighEnd); } internal static bool IsLowSurrogate(int ch) { return InRange(ch, SurLowStart, SurLowEnd); } internal static bool IsSurrogate(int ch) { return InRange(ch, SurHighStart, SurLowEnd); } internal static int CombineSurrogateChar(int lowChar, int highChar) { return (lowChar - SurLowStart) | ((highChar - SurHighStart) << 10) + 0x10000; } internal static void SplitSurrogateChar(int combinedChar, out char lowChar, out char highChar) { int v = combinedChar - 0x10000; lowChar = (char)(SurLowStart + v % 1024); highChar = (char)(SurHighStart + v / 1024); } internal bool IsOnlyWhitespace(string str) { return IsOnlyWhitespaceWithPos(str) == -1; } // Character checking on strings internal int IsOnlyWhitespaceWithPos(string str) { if (str != null) { for (int i = 0; i < str.Length; i++) { if ((charProperties[str[i]] & fWhitespace) == 0) { return i; } } } return -1; } internal int IsOnlyCharData(string str) { if (str != null) { for (int i = 0; i < str.Length; i++) { if ((charProperties[str[i]] & fCharData) == 0) { if (i + 1 >= str.Length || !(XmlCharType.IsHighSurrogate(str[i]) && XmlCharType.IsLowSurrogate(str[i + 1]))) { return i; } else { i++; } } } } return -1; } internal static bool IsOnlyDigits(string str, int startPos, int len) { Debug.Assert(str != null); Debug.Assert(startPos + len <= str.Length); Debug.Assert(startPos <= str.Length); for (int i = startPos; i < startPos + len; i++) { if (!IsDigit(str[i])) { return false; } } return true; } internal int IsPublicId(string str) { if (str != null) { for (int i = 0; i < str.Length; i++) { if (!IsPubidChar(str[i])) { return i; } } } return -1; } // This method tests whether a value is in a given range with just one test; start and end should be constants private static bool InRange(int value, int start, int end) { Debug.Assert(start <= end); return (uint)(value - start) <= (uint)(end - start); } #if XMLCHARTYPE_GEN_RESOURCE // // Code for generating XmlCharType.bin table and s_PublicIdBitmap // // build command line: csc XmlCharType.cs /d:XMLCHARTYPE_GEN_RESOURCE // public static void Main( string[] args ) { try { InitInstance(); // generate PublicId bitmap ushort[] bitmap = new ushort[0x80 >> 4]; for (int i = 0; i < s_PublicID.Length; i += 2) { for (int j = s_PublicID[i], last = s_PublicID[i + 1]; j <= last; j++) { bitmap[j >> 4] |= (ushort)(1 << (j & 0xF)); } } Console.Write("private const string s_PublicIdBitmap = \""); for (int i = 0; i < bitmap.Length; i++) { Console.Write("\\u{0:x4}", bitmap[i]); } Console.WriteLine("\";"); Console.WriteLine(); string fileName = ( args.Length == 0 ) ? "XmlCharType.bin" : args[0]; Console.Write( "Writing XmlCharType character properties to {0}...", fileName ); FileStream fs = new FileStream( fileName, FileMode.Create ); for ( int i = 0; i < CharPropertiesSize; i += 4096 ) { fs.Write( s_CharProperties, i, 4096 ); } fs.Close(); Console.WriteLine( "done." ); } catch ( Exception e ) { Console.WriteLine(); Console.WriteLine( "Exception: {0}", e.Message ); } } #endif } }
using System; using System.IO; using System.Net; using JetBrains.Annotations; using PatchKit.Logging; using PatchKit.Network; using PatchKit.Unity.Patcher.Cancellation; using PatchKit.Unity.Patcher.Debug; using PatchKit.Unity.Utilities; using UnityEngine.Networking; namespace PatchKit.Unity.Patcher.AppData.Remote.Downloaders { public sealed class BaseHttpDownloader : IBaseHttpDownloader { private class Handler : DownloadHandlerScript { private Action<byte[], int> _receiveData; public Handler(Action<byte[], int> receiveData) { _receiveData = receiveData; } protected override bool ReceiveData(byte[] data, int dataLength) { _receiveData(data, dataLength); return true; } } private readonly ILogger _logger; private static readonly int BufferSize = 5 * (int) Units.MB; private readonly string _url; private readonly int _timeout; private readonly byte[] _buffer; private bool _downloadHasBeenCalled; private BytesRange? _bytesRange; public event DataAvailableHandler DataAvailable; public BaseHttpDownloader(string url, int timeout) : this(url, timeout, PatcherLogManager.DefaultLogger) { } public BaseHttpDownloader([NotNull] string url, int timeout, [NotNull] ILogger logger) { if (string.IsNullOrEmpty(url)) throw new ArgumentException("Value cannot be null or empty.", "url"); if (timeout <= 0) throw new ArgumentOutOfRangeException("timeout"); if (logger == null) throw new ArgumentNullException("logger"); _url = url; _timeout = timeout; _logger = logger; _buffer = new byte[BufferSize]; ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true; ServicePointManager.DefaultConnectionLimit = 65535; } public void SetBytesRange(BytesRange? range) { _bytesRange = range; if (_bytesRange.HasValue && _bytesRange.Value.Start == 0 && _bytesRange.Value.End == -1) { _bytesRange = null; } } public void Download(CancellationToken cancellationToken) { try { _logger.LogDebug("Downloading..."); _logger.LogTrace("url = " + _url); _logger.LogTrace("bufferSize = " + BufferSize); _logger.LogTrace("bytesRange = " + (_bytesRange.HasValue ? _bytesRange.Value.Start + "-" + _bytesRange.Value.End : "(none)")); _logger.LogTrace("timeout = " + _timeout); Assert.MethodCalledOnlyOnce(ref _downloadHasBeenCalled, "Download"); UnityWebRequest request = null; Exception dataAvailableException = null; DateTime lastDataAvailable = DateTime.Now; UnityDispatcher.Invoke(() => { request = new UnityWebRequest(); request.uri = new Uri(_url); request.timeout = 0; if (_bytesRange.HasValue) { var bytesRangeEndText = _bytesRange.Value.End >= 0L ? _bytesRange.Value.End.ToString() : string.Empty; request.SetRequestHeader( "Range", "bytes=" + _bytesRange.Value.Start + "-" + bytesRangeEndText); } request.downloadHandler = new Handler((data, length) => { lastDataAvailable = DateTime.Now; if (DataAvailable != null && dataAvailableException == null) { try { DataAvailable.Invoke(data, length); } catch (Exception e) { dataAvailableException = e; } } }); }).WaitOne(); using (request) { using(request.downloadHandler) { UnityWebRequestAsyncOperation op = null; UnityDispatcher.Invoke(() => { op = request.SendWebRequest(); }).WaitOne(); bool requestIsDone = false; bool responseCodeHandled = false; while (!requestIsDone) { cancellationToken.ThrowIfCancellationRequested(); if ((DateTime.Now - lastDataAvailable).TotalMilliseconds > _timeout) { throw new ConnectionFailureException("Timeout."); } long requestResponseCode = 0; string requestError = null; UnityDispatcher.Invoke(() => { requestIsDone = request.isDone; requestResponseCode = request.responseCode; requestError = request.error; }).WaitOne(); if (requestError != null) { throw new ConnectionFailureException(requestError); } if (requestResponseCode > 0 && !responseCodeHandled) { _logger.LogDebug("Received response from server."); _logger.LogTrace("statusCode = " + requestResponseCode); if (Is2XXStatus((HttpStatusCode) requestResponseCode)) { _logger.LogDebug("Successful response. Reading response stream..."); } else if (Is4XXStatus((HttpStatusCode) requestResponseCode)) { throw new DataNotAvailableException(string.Format( "Request data for {0} is not available (status: {1})", _url, (HttpStatusCode) request.responseCode)); } else { throw new ServerErrorException(string.Format( "Server has experienced some issues with request for {0} which resulted in {1} status code.", _url, (HttpStatusCode) requestResponseCode)); } responseCodeHandled = true; } if (dataAvailableException != null) { throw dataAvailableException; } System.Threading.Thread.Sleep(100); } if (dataAvailableException != null) { throw dataAvailableException; } _logger.LogDebug("Stream has been read."); } } _logger.LogDebug("Downloading finished."); } catch (WebException webException) { _logger.LogError("Downloading has failed.", webException); throw new ConnectionFailureException( string.Format("Connection to server has failed while requesting {0}", _url), webException); } catch (Exception e) { _logger.LogError("Downloading has failed.", e); throw; } } // ReSharper disable once InconsistentNaming private static bool Is2XXStatus(HttpStatusCode statusCode) { return (int) statusCode >= 200 && (int) statusCode <= 299; } // ReSharper disable once InconsistentNaming private static bool Is4XXStatus(HttpStatusCode statusCode) { return (int) statusCode >= 400 && (int) statusCode <= 499; } } }
using UnityEngine; using System.Collections.Generic; namespace Pathfinding { /** Base class for the NavmeshCut and NavmeshAdd components */ public abstract class NavmeshClipper : VersionedMonoBehaviour { /** Called every time a NavmeshCut/NavmeshAdd component is enabled. */ static System.Action<NavmeshClipper> OnEnableCallback; /** Called every time a NavmeshCut/NavmeshAdd component is disabled. */ static System.Action<NavmeshClipper> OnDisableCallback; static readonly LinkedList<NavmeshClipper> all = new LinkedList<NavmeshClipper>(); readonly LinkedListNode<NavmeshClipper> node; public NavmeshClipper () { node = new LinkedListNode<NavmeshClipper>(this); } public static void AddEnableCallback (System.Action<NavmeshClipper> onEnable, System.Action<NavmeshClipper> onDisable) { OnEnableCallback += onEnable; OnDisableCallback += onDisable; for (var current = all.First; current != null; current = current.Next) { onEnable(current.Value); } } public static void RemoveEnableCallback (System.Action<NavmeshClipper> onEnable, System.Action<NavmeshClipper> onDisable) { OnEnableCallback -= onEnable; OnDisableCallback -= onDisable; for (var current = all.First; current != null; current = current.Next) { onDisable(current.Value); } } public static bool AnyEnableListeners { get { return OnEnableCallback != null; } } protected virtual void OnEnable () { all.AddFirst(node); if (OnEnableCallback != null) OnEnableCallback(this); } protected virtual void OnDisable () { if (OnDisableCallback != null) OnDisableCallback(this); all.Remove(node); } internal abstract void NotifyUpdated (); internal abstract Rect GetBounds (Pathfinding.Util.GraphTransform transform); public abstract bool RequiresUpdate (); public abstract void ForceUpdate (); } /** Navmesh cutting is used for fast recast/navmesh graph updates. * * Navmesh cutting is used to cut holes into an existing navmesh generated by a recast or navmesh graph. * Recast graphs usually only allow either just changing parameters on existing nodes (e.g make a whole triangle unwalkable) which is not very flexible or recalculate a whole tile which is pretty slow. * With navmesh cutting you can remove (cut) parts of the navmesh that is blocked by obstacles such as a new building in an RTS game however you cannot add anything new to the navmesh or change * the positions of the nodes.\n * * \youtube{qXi5qhhGNIw} * * \n * The NavmeshCut component uses a 2D shape to cut the navmesh with. A rectangle and circle shape is built in, but you can also specify a custom mesh to use. * The custom mesh should be a flat 2D shape like in the image below. The script will then find the contour of that mesh and use that shape as the cut. * Make sure that all normals are smooth and that the mesh contains no UV information. Otherwise Unity might split a vertex and then the script will not * find the correct contour. You should not use a very high polygon mesh since that will create a lot of nodes in the navmesh graph and slow * down pathfinding because of that. For very high polygon meshes it might even cause more suboptimal paths to be generated if it causes many * thin triangles to be added to the navmesh. * \shadowimage{navmeshcut_mesh.png} * * Note that the shape is not 3D so if you rotate the cut you will see that the 2D shape will be rotated and then just projected down on the XZ plane. * * To use a navmesh cut in your scene you need to have a TileHandlerHelper script somewhere in your scene. You should only have one though. * That script will take care of checking all the NavmeshCut components to see if they need to update the navmesh. * * In the scene view the NavmeshCut looks like an extruded 2D shape because a navmesh cut also has a height. It will only cut the part of the * navmesh which it touches. For performance it only checks the bounding boxes of the triangles in the navmesh, so it may cut triangles * whoose bounding boxes it intersects even if the triangle does not intersect the extructed shape. However in most cases this does not make a large difference. * * It is also possible to set the navmesh cut to dual mode by setting the #isDual field to true. This will prevent it from cutting a hole in the navmesh * and it will instead just split the navmesh along the border but keep both the interior and the exterior. This can be useful if you for example * want to change the penalty of some region which does not neatly line up with the navmesh triangles. It is often combined with the GraphUpdateScene component * (however note that the GraphUpdateScene component will not automatically reapply the penalty if the graph is updated again). * * By default the navmesh cut does not take rotation or scaling into account. If you want to do that, you can set the #useRotationAndScale field to true. * This is a bit slower, but it is not a very large difference. * * \version In 3.x navmesh cutting could only be used with recast graphs, but in 4.x they can be used with both recast and navmesh graphs. * * \astarpro * \see http://www.arongranberg.com/2013/08/navmesh-cutting/ */ [AddComponentMenu("Pathfinding/Navmesh/Navmesh Cut")] [HelpURL("http://arongranberg.com/astar/docs/class_pathfinding_1_1_navmesh_cut.php")] public class NavmeshCut : NavmeshClipper { public enum MeshType { Rectangle, Circle, CustomMesh } /** Shape of the cut */ [Tooltip("Shape of the cut")] public MeshType type; /** Custom mesh to use. * The contour(s) of the mesh will be extracted. * If you get the "max perturbations" error when cutting with this, check the normals on the mesh. * They should all point in the same direction. Try flipping them if that does not help. * * This mesh should only be a 2D surface, not a volume. */ [Tooltip("The contour(s) of the mesh will be extracted. This mesh should only be a 2D surface, not a volume (see documentation).")] public Mesh mesh; /** Size of the rectangle */ public Vector2 rectangleSize = new Vector2(1, 1); /** Radius of the circle */ public float circleRadius = 1; /** Number of vertices on the circle */ public int circleResolution = 6; /** The cut will be extruded to this height */ public float height = 1; /** Scale of the custom mesh, if used */ [Tooltip("Scale of the custom mesh")] public float meshScale = 1; public Vector3 center; /** Distance between positions to require an update of the navmesh. * A smaller distance gives better accuracy, but requires more updates when moving the object over time, * so it is often slower. * * \note Dynamic updating requires a TileHandlerHelper somewhere in the scene. */ [Tooltip("Distance between positions to require an update of the navmesh\nA smaller distance gives better accuracy, but requires more updates when moving the object over time, so it is often slower.")] public float updateDistance = 0.4f; /** Only makes a split in the navmesh, but does not remove the geometry to make a hole. * This is slower than a normal cut */ [Tooltip("Only makes a split in the navmesh, but does not remove the geometry to make a hole")] public bool isDual; /** Cuts geometry added by a NavmeshAdd component. * You rarely need to change this */ public bool cutsAddedGeom = true; /** How many degrees rotation that is required for an update to the navmesh. * Should be between 0 and 180. * * \note Dynamic updating requires a Tile Handler Helper somewhere in the scene. */ [Tooltip("How many degrees rotation that is required for an update to the navmesh. Should be between 0 and 180.")] public float updateRotationDistance = 10; /** Includes rotation and scale in calculations. * This is slower since a lot more matrix multiplications are needed but gives more flexibility. */ [Tooltip("Includes rotation in calculations. This is slower since a lot more matrix multiplications are needed but gives more flexibility.")] [UnityEngine.Serialization.FormerlySerializedAsAttribute("useRotation")] public bool useRotationAndScale; Vector3[][] contours; /** cached transform component */ protected Transform tr; Mesh lastMesh; Vector3 lastPosition; Quaternion lastRotation; protected override void Awake () { base.Awake(); tr = transform; } protected override void OnEnable () { base.OnEnable(); lastPosition = new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); lastRotation = tr.rotation; } /** Cached variable, to avoid allocations */ static readonly Dictionary<Int2, int> edges = new Dictionary<Int2, int>(); /** Cached variable, to avoid allocations */ static readonly Dictionary<int, int> pointers = new Dictionary<int, int>(); /** Forces this navmesh cut to update the navmesh. * * \note Dynamic updating requires a Tile Handler Helper somewhere in the scene. * This update is not instant, it is done the next time the TileHandlerHelper checks this instance for * if it needs updating. * * \see TileHandlerHelper.ForceUpdate() */ public override void ForceUpdate () { lastPosition = new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); } /** Returns true if this object has moved so much that it requires an update. * When an update to the navmesh has been done, call NotifyUpdated to be able to get * relavant output from this method again. */ public override bool RequiresUpdate () { return (tr.position-lastPosition).sqrMagnitude > updateDistance*updateDistance || (useRotationAndScale && (Quaternion.Angle(lastRotation, tr.rotation) > updateRotationDistance)); } /** * Called whenever this navmesh cut is used to update the navmesh. * Called once for each tile the navmesh cut is in. * You can override this method to execute custom actions whenever this happens. */ public virtual void UsedForCut () { } /** Internal method to notify the NavmeshCut that it has just been used to update the navmesh */ internal override void NotifyUpdated () { lastPosition = tr.position; if (useRotationAndScale) { lastRotation = tr.rotation; } } void CalculateMeshContour () { if (mesh == null) return; edges.Clear(); pointers.Clear(); Vector3[] verts = mesh.vertices; int[] tris = mesh.triangles; for (int i = 0; i < tris.Length; i += 3) { // Make sure it is clockwise if (VectorMath.IsClockwiseXZ(verts[tris[i+0]], verts[tris[i+1]], verts[tris[i+2]])) { int tmp = tris[i+0]; tris[i+0] = tris[i+2]; tris[i+2] = tmp; } edges[new Int2(tris[i+0], tris[i+1])] = i; edges[new Int2(tris[i+1], tris[i+2])] = i; edges[new Int2(tris[i+2], tris[i+0])] = i; } // Construct a list of pointers along all edges for (int i = 0; i < tris.Length; i += 3) { for (int j = 0; j < 3; j++) { if (!edges.ContainsKey(new Int2(tris[i+((j+1)%3)], tris[i+((j+0)%3)]))) { pointers[tris[i+((j+0)%3)]] = tris[i+((j+1)%3)]; } } } var contourBuffer = new List<Vector3[]>(); List<Vector3> buffer = Pathfinding.Util.ListPool<Vector3>.Claim(); // Follow edge pointers to generate the contours for (int i = 0; i < verts.Length; i++) { if (pointers.ContainsKey(i)) { buffer.Clear(); int s = i; do { int tmp = pointers[s]; //This path has been taken before if (tmp == -1) break; pointers[s] = -1; buffer.Add(verts[s]); s = tmp; if (s == -1) { Debug.LogError("Invalid Mesh '" + mesh.name + " in " + gameObject.name); break; } } while (s != i); if (buffer.Count > 0) contourBuffer.Add(buffer.ToArray()); } } // Return lists to the pool Pathfinding.Util.ListPool<Vector3>.Release(ref buffer); contours = contourBuffer.ToArray(); } /** Bounds in XZ space after transforming using the *inverse* transform of the \a inverseTranform parameter. * The transformation will typically transform the vertices to graph space and this is used to * figure out which tiles the cut intersects. */ internal override Rect GetBounds (Pathfinding.Util.GraphTransform inverseTranform) { var buffers = Pathfinding.Util.ListPool<List<Vector3> >.Claim(); GetContour(buffers); Rect r = new Rect(); for (int i = 0; i < buffers.Count; i++) { var buffer = buffers[i]; for (int k = 0; k < buffer.Count; k++) { var p = inverseTranform.InverseTransform(buffer[k]); if (k == 0) { r = new Rect(p.x, p.z, 0, 0); } else { r.xMax = System.Math.Max(r.xMax, p.x); r.yMax = System.Math.Max(r.yMax, p.z); r.xMin = System.Math.Min(r.xMin, p.x); r.yMin = System.Math.Min(r.yMin, p.z); } } } Pathfinding.Util.ListPool<List<Vector3> >.Release(ref buffers); return r; } /** * World space contour of the navmesh cut. * Fills the specified buffer with all contours. * The cut may contain several contours which is why the buffer is a list of lists. */ public void GetContour (List<List<Vector3> > buffer) { if (circleResolution < 3) circleResolution = 3; bool reverse; switch (type) { case MeshType.Rectangle: List<Vector3> buffer0 = Pathfinding.Util.ListPool<Vector3>.Claim(); buffer0.Add(new Vector3(-rectangleSize.x, 0, -rectangleSize.y)*0.5f); buffer0.Add(new Vector3(rectangleSize.x, 0, -rectangleSize.y)*0.5f); buffer0.Add(new Vector3(rectangleSize.x, 0, rectangleSize.y)*0.5f); buffer0.Add(new Vector3(-rectangleSize.x, 0, rectangleSize.y)*0.5f); reverse = (rectangleSize.x < 0) ^ (rectangleSize.y < 0); TransformBuffer(buffer0, reverse); buffer.Add(buffer0); break; case MeshType.Circle: buffer0 = Pathfinding.Util.ListPool<Vector3>.Claim(circleResolution); for (int i = 0; i < circleResolution; i++) { buffer0.Add(new Vector3(Mathf.Cos((i*2*Mathf.PI)/circleResolution), 0, Mathf.Sin((i*2*Mathf.PI)/circleResolution))*circleRadius); } reverse = circleRadius < 0; TransformBuffer(buffer0, reverse); buffer.Add(buffer0); break; case MeshType.CustomMesh: if (mesh != lastMesh || contours == null) { CalculateMeshContour(); lastMesh = mesh; } if (contours != null) { reverse = meshScale < 0; for (int i = 0; i < contours.Length; i++) { Vector3[] contour = contours[i]; buffer0 = Pathfinding.Util.ListPool<Vector3>.Claim(contour.Length); for (int x = 0; x < contour.Length; x++) { buffer0.Add(contour[x]*meshScale); } TransformBuffer(buffer0, reverse); buffer.Add(buffer0); } } break; } } void TransformBuffer (List<Vector3> buffer, bool reverse) { var offset = center; // Take rotation and scaling into account if (useRotationAndScale) { var local2world = tr.localToWorldMatrix; for (int i = 0; i < buffer.Count; i++) buffer[i] = local2world.MultiplyPoint3x4(buffer[i] + offset); reverse ^= VectorMath.ReversesFaceOrientationsXZ(local2world); } else { offset += tr.position; for (int i = 0; i < buffer.Count; i++) buffer[i] += offset; } if (reverse) buffer.Reverse(); } public static readonly Color GizmoColor = new Color(37.0f/255, 184.0f/255, 239.0f/255); public void OnDrawGizmos () { if (tr == null) tr = transform; var buffer = Pathfinding.Util.ListPool<List<Vector3> >.Claim(); GetContour(buffer); Gizmos.color = GizmoColor; // Draw all contours for (int i = 0; i < buffer.Count; i++) { var cont = buffer[i]; for (int j = 0; j < cont.Count; j++) { Vector3 p1 = cont[j]; Vector3 p2 = cont[(j+1) % cont.Count]; Gizmos.DrawLine(p1, p2); } } Pathfinding.Util.ListPool<List<Vector3> >.Release(ref buffer); } /** Y coordinate of the center of the bounding box in graph space */ internal float GetY (Pathfinding.Util.GraphTransform transform) { return transform.InverseTransform(useRotationAndScale ? tr.TransformPoint(center) : tr.position + center).y; } public void OnDrawGizmosSelected () { var buffer = Pathfinding.Util.ListPool<List<Vector3> >.Claim(); GetContour(buffer); var col = Color.Lerp(GizmoColor, Color.white, 0.5f); col.a *= 0.5f; Gizmos.color = col; var graph = AstarPath.active != null ? (AstarPath.active.data.recastGraph as NavmeshBase ?? AstarPath.active.data.navmesh) : null; var transform = graph != null ? graph.transform : Pathfinding.Util.GraphTransform.identityTransform; float ymid = GetY(transform); float ymin = ymid - height*0.5f; float ymax = ymid + height*0.5f; // Draw all contours for (int i = 0; i < buffer.Count; i++) { var cont = buffer[i]; for (int j = 0; j < cont.Count; j++) { Vector3 p1 = transform.InverseTransform(cont[j]); Vector3 p2 = transform.InverseTransform(cont[(j+1) % cont.Count]); Vector3 p1low = p1, p2low = p2, p1high = p1, p2high = p2; p1low.y = p2low.y = ymin; p1high.y = p2high.y = ymax; Gizmos.DrawLine(transform.Transform(p1low), transform.Transform(p2low)); Gizmos.DrawLine(transform.Transform(p1high), transform.Transform(p2high)); Gizmos.DrawLine(transform.Transform(p1low), transform.Transform(p1high)); } } Pathfinding.Util.ListPool<List<Vector3> >.Release(ref buffer); } } }
using System; using Moq; using Prism.Regions; using Xunit; namespace Prism.Wpf.Tests.Regions { public class RegionNavigationJournalFixture { [Fact] public void ConstructingJournalInitializesValues() { // Act RegionNavigationJournal target = new RegionNavigationJournal(); // Verify Assert.False(target.CanGoBack); Assert.False(target.CanGoForward); Assert.Null(target.CurrentEntry); Assert.Null(target.NavigationTarget); } [Fact] public void SettingNavigationServiceUpdatesValue() { // Prepare RegionNavigationJournal target = new RegionNavigationJournal(); Mock<INavigateAsync> mockINavigate = new Mock<INavigateAsync>(); // Act target.NavigationTarget = mockINavigate.Object; // Verify Assert.Same(mockINavigate.Object, target.NavigationTarget); } [Fact] public void RecordingNavigationUpdatesNavigationState() { // Prepare RegionNavigationJournal target = new RegionNavigationJournal(); Uri uri = new Uri("Uri", UriKind.Relative); RegionNavigationJournalEntry entry = new RegionNavigationJournalEntry() { Uri = uri }; // Act target.RecordNavigation(entry, true); // Verify Assert.False(target.CanGoBack); Assert.False(target.CanGoForward); Assert.Same(entry, target.CurrentEntry); } [Fact] public void RecordingNavigationMultipleTimesUpdatesNavigationState() { // Prepare RegionNavigationJournal target = new RegionNavigationJournal(); Uri uri1 = new Uri("Uri1", UriKind.Relative); RegionNavigationJournalEntry entry1 = new RegionNavigationJournalEntry() { Uri = uri1 }; Uri uri2 = new Uri("Uri2", UriKind.Relative); RegionNavigationJournalEntry entry2 = new RegionNavigationJournalEntry() { Uri = uri2 }; Uri uri3 = new Uri("Uri3", UriKind.Relative); RegionNavigationJournalEntry entry3 = new RegionNavigationJournalEntry() { Uri = uri3 }; // Act target.RecordNavigation(entry1, true); target.RecordNavigation(entry2, true); target.RecordNavigation(entry3, true); // Verify Assert.True(target.CanGoBack); Assert.False(target.CanGoForward); Assert.Same(entry3, target.CurrentEntry); } [Fact] public void ClearUpdatesNavigationState() { // Prepare RegionNavigationJournal target = new RegionNavigationJournal(); Uri uri1 = new Uri("Uri1", UriKind.Relative); RegionNavigationJournalEntry entry1 = new RegionNavigationJournalEntry() { Uri = uri1 }; Uri uri2 = new Uri("Uri2", UriKind.Relative); RegionNavigationJournalEntry entry2 = new RegionNavigationJournalEntry() { Uri = uri2 }; Uri uri3 = new Uri("Uri3", UriKind.Relative); RegionNavigationJournalEntry entry3 = new RegionNavigationJournalEntry() { Uri = uri3 }; target.RecordNavigation(entry1, true); target.RecordNavigation(entry2, true); target.RecordNavigation(entry3, true); // Act target.Clear(); // Verify Assert.False(target.CanGoBack); Assert.False(target.CanGoForward); Assert.Null(target.CurrentEntry); } [Fact] public void GoBackNavigatesBack() { // Prepare RegionNavigationJournal target = new RegionNavigationJournal(); Mock<INavigateAsync> mockNavigationTarget = new Mock<INavigateAsync>(); target.NavigationTarget = mockNavigationTarget.Object; Uri uri1 = new Uri("Uri1", UriKind.Relative); RegionNavigationJournalEntry entry1 = new RegionNavigationJournalEntry() { Uri = uri1 }; Uri uri2 = new Uri("Uri2", UriKind.Relative); RegionNavigationJournalEntry entry2 = new RegionNavigationJournalEntry() { Uri = uri2 }; Uri uri3 = new Uri("Uri3", UriKind.Relative); RegionNavigationJournalEntry entry3 = new RegionNavigationJournalEntry() { Uri = uri3 }; target.RecordNavigation(entry1, true); target.RecordNavigation(entry2, true); target.RecordNavigation(entry3, true); mockNavigationTarget .Setup(x => x.RequestNavigate(uri1, It.IsAny<Action<NavigationResult>>(), null)) .Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true))); mockNavigationTarget .Setup(x => x.RequestNavigate(uri2, It.IsAny<Action<NavigationResult>>(), null)) .Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true))); mockNavigationTarget .Setup(x => x.RequestNavigate(uri3, It.IsAny<Action<NavigationResult>>(), null)) .Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true))); // Act target.GoBack(); // Verify Assert.True(target.CanGoBack); Assert.True(target.CanGoForward); Assert.Same(entry2, target.CurrentEntry); mockNavigationTarget.Verify(x => x.RequestNavigate(uri1, It.IsAny<Action<NavigationResult>>(), null), Times.Never()); mockNavigationTarget.Verify(x => x.RequestNavigate(uri2, It.IsAny<Action<NavigationResult>>(), null), Times.Once()); mockNavigationTarget.Verify(x => x.RequestNavigate(uri3, It.IsAny<Action<NavigationResult>>(), null), Times.Never()); } [Fact] public void GoBackDoesNotChangeStateWhenNavigationFails() { // Prepare RegionNavigationJournal target = new RegionNavigationJournal(); Mock<INavigateAsync> mockNavigationTarget = new Mock<INavigateAsync>(); target.NavigationTarget = mockNavigationTarget.Object; Uri uri1 = new Uri("Uri1", UriKind.Relative); RegionNavigationJournalEntry entry1 = new RegionNavigationJournalEntry() { Uri = uri1 }; Uri uri2 = new Uri("Uri2", UriKind.Relative); RegionNavigationJournalEntry entry2 = new RegionNavigationJournalEntry() { Uri = uri2 }; Uri uri3 = new Uri("Uri3", UriKind.Relative); RegionNavigationJournalEntry entry3 = new RegionNavigationJournalEntry() { Uri = uri3 }; target.RecordNavigation(entry1, true); target.RecordNavigation(entry2, true); target.RecordNavigation(entry3, true); mockNavigationTarget .Setup(x => x.RequestNavigate(uri1, It.IsAny<Action<NavigationResult>>(), null)) .Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true))); mockNavigationTarget .Setup(x => x.RequestNavigate(uri2, It.IsAny<Action<NavigationResult>>(), null)) .Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, false))); mockNavigationTarget .Setup(x => x.RequestNavigate(uri3, It.IsAny<Action<NavigationResult>>(), null)) .Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true))); // Act target.GoBack(); // Verify Assert.True(target.CanGoBack); Assert.False(target.CanGoForward); Assert.Same(entry3, target.CurrentEntry); mockNavigationTarget.Verify(x => x.RequestNavigate(uri1, It.IsAny<Action<NavigationResult>>(), null), Times.Never()); mockNavigationTarget.Verify(x => x.RequestNavigate(uri2, It.IsAny<Action<NavigationResult>>(), null), Times.Once()); mockNavigationTarget.Verify(x => x.RequestNavigate(uri3, It.IsAny<Action<NavigationResult>>(), null), Times.Never()); } [Fact] public void GoBackMultipleTimesNavigatesBack() { // Prepare RegionNavigationJournal target = new RegionNavigationJournal(); Mock<INavigateAsync> mockNavigationTarget = new Mock<INavigateAsync>(); target.NavigationTarget = mockNavigationTarget.Object; Uri uri1 = new Uri("Uri1", UriKind.Relative); RegionNavigationJournalEntry entry1 = new RegionNavigationJournalEntry() { Uri = uri1 }; Uri uri2 = new Uri("Uri2", UriKind.Relative); RegionNavigationJournalEntry entry2 = new RegionNavigationJournalEntry() { Uri = uri2 }; Uri uri3 = new Uri("Uri3", UriKind.Relative); RegionNavigationJournalEntry entry3 = new RegionNavigationJournalEntry() { Uri = uri3 }; target.RecordNavigation(entry1, true); target.RecordNavigation(entry2, true); target.RecordNavigation(entry3, true); mockNavigationTarget .Setup(x => x.RequestNavigate(uri1, It.IsAny<Action<NavigationResult>>(), null)) .Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true))); mockNavigationTarget .Setup(x => x.RequestNavigate(uri2, It.IsAny<Action<NavigationResult>>(), null)) .Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true))); mockNavigationTarget .Setup(x => x.RequestNavigate(uri3, It.IsAny<Action<NavigationResult>>(), null)) .Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true))); // Act target.GoBack(); target.GoBack(); // Verify Assert.False(target.CanGoBack); Assert.True(target.CanGoForward); Assert.Same(entry1, target.CurrentEntry); mockNavigationTarget.Verify(x => x.RequestNavigate(uri1, It.IsAny<Action<NavigationResult>>(), null), Times.Once()); mockNavigationTarget.Verify(x => x.RequestNavigate(uri2, It.IsAny<Action<NavigationResult>>(), null), Times.Once()); mockNavigationTarget.Verify(x => x.RequestNavigate(uri3, It.IsAny<Action<NavigationResult>>(), null), Times.Never()); } [Fact] public void GoForwardNavigatesForward() { // Prepare RegionNavigationJournal target = new RegionNavigationJournal(); Mock<INavigateAsync> mockNavigationTarget = new Mock<INavigateAsync>(); target.NavigationTarget = mockNavigationTarget.Object; Uri uri1 = new Uri("Uri1", UriKind.Relative); RegionNavigationJournalEntry entry1 = new RegionNavigationJournalEntry() { Uri = uri1 }; Uri uri2 = new Uri("Uri2", UriKind.Relative); RegionNavigationJournalEntry entry2 = new RegionNavigationJournalEntry() { Uri = uri2 }; Uri uri3 = new Uri("Uri3", UriKind.Relative); RegionNavigationJournalEntry entry3 = new RegionNavigationJournalEntry() { Uri = uri3 }; target.RecordNavigation(entry1, true); target.RecordNavigation(entry2, true); target.RecordNavigation(entry3, true); mockNavigationTarget .Setup(x => x.RequestNavigate(uri1, It.IsAny<Action<NavigationResult>>(), null)) .Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true))); mockNavigationTarget .Setup(x => x.RequestNavigate(uri2, It.IsAny<Action<NavigationResult>>(), null)) .Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true))); mockNavigationTarget .Setup(x => x.RequestNavigate(uri3, It.IsAny<Action<NavigationResult>>(), null)) .Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true))); target.GoBack(); target.GoBack(); // Act target.GoForward(); // Verify Assert.True(target.CanGoBack); Assert.True(target.CanGoForward); Assert.Same(entry2, target.CurrentEntry); mockNavigationTarget.Verify(x => x.RequestNavigate(uri1, It.IsAny<Action<NavigationResult>>(), null), Times.Once()); mockNavigationTarget.Verify(x => x.RequestNavigate(uri2, It.IsAny<Action<NavigationResult>>(), null), Times.Exactly(2)); mockNavigationTarget.Verify(x => x.RequestNavigate(uri3, It.IsAny<Action<NavigationResult>>(), null), Times.Never()); } [Fact] public void GoForwardDoesNotChangeStateWhenNavigationFails() { // Prepare RegionNavigationJournal target = new RegionNavigationJournal(); Mock<INavigateAsync> mockNavigationTarget = new Mock<INavigateAsync>(); target.NavigationTarget = mockNavigationTarget.Object; Uri uri1 = new Uri("Uri1", UriKind.Relative); RegionNavigationJournalEntry entry1 = new RegionNavigationJournalEntry() { Uri = uri1 }; Uri uri2 = new Uri("Uri2", UriKind.Relative); RegionNavigationJournalEntry entry2 = new RegionNavigationJournalEntry() { Uri = uri2 }; Uri uri3 = new Uri("Uri3", UriKind.Relative); RegionNavigationJournalEntry entry3 = new RegionNavigationJournalEntry() { Uri = uri3 }; target.RecordNavigation(entry1, true); target.RecordNavigation(entry2, true); target.RecordNavigation(entry3, true); mockNavigationTarget .Setup(x => x.RequestNavigate(uri1, It.IsAny<Action<NavigationResult>>(), null)) .Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true))); mockNavigationTarget .Setup(x => x.RequestNavigate(uri2, It.IsAny<Action<NavigationResult>>(), null)) .Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true))); mockNavigationTarget .Setup(x => x.RequestNavigate(uri3, It.IsAny<Action<NavigationResult>>(), null)) .Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, false))); target.GoBack(); // Act target.GoForward(); // Verify Assert.True(target.CanGoBack); Assert.True(target.CanGoForward); Assert.Same(entry2, target.CurrentEntry); mockNavigationTarget.Verify(x => x.RequestNavigate(uri1, It.IsAny<Action<NavigationResult>>(), null), Times.Never()); mockNavigationTarget.Verify(x => x.RequestNavigate(uri2, It.IsAny<Action<NavigationResult>>(), null), Times.Once()); mockNavigationTarget.Verify(x => x.RequestNavigate(uri3, It.IsAny<Action<NavigationResult>>(), null), Times.Once()); } [Fact] public void GoForwardMultipleTimesNavigatesForward() { // Prepare RegionNavigationJournal target = new RegionNavigationJournal(); Mock<INavigateAsync> mockNavigationTarget = new Mock<INavigateAsync>(); target.NavigationTarget = mockNavigationTarget.Object; Uri uri1 = new Uri("Uri1", UriKind.Relative); RegionNavigationJournalEntry entry1 = new RegionNavigationJournalEntry() { Uri = uri1 }; Uri uri2 = new Uri("Uri2", UriKind.Relative); RegionNavigationJournalEntry entry2 = new RegionNavigationJournalEntry() { Uri = uri2 }; Uri uri3 = new Uri("Uri3", UriKind.Relative); RegionNavigationJournalEntry entry3 = new RegionNavigationJournalEntry() { Uri = uri3 }; target.RecordNavigation(entry1, true); target.RecordNavigation(entry2, true); target.RecordNavigation(entry3, true); mockNavigationTarget .Setup(x => x.RequestNavigate(uri1, It.IsAny<Action<NavigationResult>>(), null)) .Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true))); mockNavigationTarget .Setup(x => x.RequestNavigate(uri2, It.IsAny<Action<NavigationResult>>(), null)) .Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true))); mockNavigationTarget .Setup(x => x.RequestNavigate(uri3, It.IsAny<Action<NavigationResult>>(), null)) .Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true))); target.GoBack(); target.GoBack(); // Act target.GoForward(); target.GoForward(); // Verify Assert.True(target.CanGoBack); Assert.False(target.CanGoForward); Assert.Same(entry3, target.CurrentEntry); mockNavigationTarget.Verify(x => x.RequestNavigate(uri1, It.IsAny<Action<NavigationResult>>(), null), Times.Once()); mockNavigationTarget.Verify(x => x.RequestNavigate(uri2, It.IsAny<Action<NavigationResult>>(), null), Times.Exactly(2)); mockNavigationTarget.Verify(x => x.RequestNavigate(uri3, It.IsAny<Action<NavigationResult>>(), null), Times.Once()); } [Fact] public void WhenNavigationToNewUri_ThenCanNoLongerNavigateForward() { // Prepare RegionNavigationJournal target = new RegionNavigationJournal(); Mock<INavigateAsync> mockNavigationTarget = new Mock<INavigateAsync>(); target.NavigationTarget = mockNavigationTarget.Object; Uri uri1 = new Uri("Uri1", UriKind.Relative); RegionNavigationJournalEntry entry1 = new RegionNavigationJournalEntry() { Uri = uri1 }; Uri uri2 = new Uri("Uri2", UriKind.Relative); RegionNavigationJournalEntry entry2 = new RegionNavigationJournalEntry() { Uri = uri2 }; Uri uri3 = new Uri("Uri3", UriKind.Relative); RegionNavigationJournalEntry entry3 = new RegionNavigationJournalEntry() { Uri = uri3 }; Uri uri4 = new Uri("Uri4", UriKind.Relative); RegionNavigationJournalEntry entry4 = new RegionNavigationJournalEntry() { Uri = uri4 }; target.RecordNavigation(entry1, true); target.RecordNavigation(entry2, true); mockNavigationTarget .Setup(x => x.RequestNavigate(uri1, It.IsAny<Action<NavigationResult>>(), null)) .Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true))); mockNavigationTarget .Setup(x => x.RequestNavigate(uri2, It.IsAny<Action<NavigationResult>>(), null)) .Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true))); mockNavigationTarget .Setup(x => x.RequestNavigate(uri3, It.IsAny<Action<NavigationResult>>(), null)) .Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true))); target.GoBack(); Assert.True(target.CanGoForward); // Act target.RecordNavigation(entry3, true); // Verify Assert.False(target.CanGoForward); Assert.Equal(entry3, target.CurrentEntry); } [Fact] public void WhenSavePreviousFalseDoNotRecordEntry() { // Prepare RegionNavigationJournal target = new RegionNavigationJournal(); Mock<INavigateAsync> mockNavigationTarget = new Mock<INavigateAsync>(); target.NavigationTarget = mockNavigationTarget.Object; Uri uri1 = new Uri("Uri1", UriKind.Relative); RegionNavigationJournalEntry entry1 = new RegionNavigationJournalEntry() { Uri = uri1 }; Uri uri2 = new Uri("Uri2", UriKind.Relative); RegionNavigationJournalEntry entry2 = new RegionNavigationJournalEntry() { Uri = uri2 }; Uri uri3 = new Uri("Uri3", UriKind.Relative); RegionNavigationJournalEntry entry3 = new RegionNavigationJournalEntry() { Uri = uri3 }; Uri uri4 = new Uri("Uri4", UriKind.Relative); RegionNavigationJournalEntry entry4 = new RegionNavigationJournalEntry() { Uri = uri4 }; target.RecordNavigation(entry1, true); target.RecordNavigation(entry2, true); target.RecordNavigation(entry3, false); target.RecordNavigation(entry4, true); mockNavigationTarget .Setup(x => x.RequestNavigate(uri1, It.IsAny<Action<NavigationResult>>(), null)) .Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true))); mockNavigationTarget .Setup(x => x.RequestNavigate(uri2, It.IsAny<Action<NavigationResult>>(), null)) .Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true))); mockNavigationTarget .Setup(x => x.RequestNavigate(uri3, It.IsAny<Action<NavigationResult>>(), null)) .Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true))); mockNavigationTarget .Setup(x => x.RequestNavigate(uri4, It.IsAny<Action<NavigationResult>>(), null)) .Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true))); Assert.Equal(entry4, target.CurrentEntry); target.GoBack(); Assert.True(target.CanGoBack); Assert.True(target.CanGoForward); Assert.Same(entry2, target.CurrentEntry); mockNavigationTarget.Verify(x => x.RequestNavigate(uri1, It.IsAny<Action<NavigationResult>>(), null), Times.Never()); mockNavigationTarget.Verify(x => x.RequestNavigate(uri2, It.IsAny<Action<NavigationResult>>(), null), Times.Once()); mockNavigationTarget.Verify(x => x.RequestNavigate(uri3, It.IsAny<Action<NavigationResult>>(), null), Times.Never()); mockNavigationTarget.Verify(x => x.RequestNavigate(uri4, It.IsAny<Action<NavigationResult>>(), null), Times.Never()); } } }
#region Using directives using System; using System.Globalization; using System.IO; using System.Xml; #endregion // <summary>Contains AtomFeedParser.</summary> namespace Google.GData.Client { /// <summary>AtomFeedParser. /// </summary> public class AtomFeedParser : BaseFeedParser { /// <summary>holds the nametable used for parsing, based on XMLNameTable</summary> private readonly AtomParserNameTable nameTable; private VersionInformation versionInfo = new VersionInformation(); /// <summary>standard empty constructor</summary> public AtomFeedParser() { Tracing.TraceCall("constructing AtomFeedParser"); nameTable = new AtomParserNameTable(); nameTable.InitAtomParserNameTable(); } /// <summary>standard constructor</summary> public AtomFeedParser(IVersionAware v) { Tracing.TraceCall("constructing AtomFeedParser"); nameTable = new AtomParserNameTable(); nameTable.InitAtomParserNameTable(); versionInfo = new VersionInformation(v); } /// <summary> /// nametable for the xmlparser that the atomfeedparser uses /// </summary> public AtomParserNameTable Nametable { get { return nameTable; } } /// <summary>starts the parsing process</summary> /// <param name="streamInput">input stream to parse </param> /// <param name="feed">the basefeed object that should be set</param> public override void Parse(Stream streamInput, AtomFeed feed) { Tracing.TraceCall("feedparser starts parsing"); try { XmlReader reader = new XmlTextReader(streamInput, nameTable.Nametable); MoveToStartElement(reader); ParseFeed(reader, feed); } catch (Exception e) { throw new ClientFeedException("Parsing failed", e); } } /// <summary>tries to parse a category collection document</summary> /// <param name="reader"> xmlReader positioned at the start element</param> /// <param name="owner">the base object that the collection belongs to</param> /// <returns></returns> public AtomCategoryCollection ParseCategories(XmlReader reader, AtomBase owner) { Tracing.Assert(reader != null, "reader should not be null"); if (reader == null) { throw new ArgumentNullException("reader"); } AtomCategoryCollection ret = new AtomCategoryCollection(); MoveToStartElement(reader); Tracing.TraceCall("entering Categories Parser"); object localname = reader.LocalName; Tracing.TraceInfo("localname is: " + reader.LocalName); if (IsCurrentNameSpace(reader, BaseNameTable.AppPublishingNamespace(owner)) && localname.Equals(nameTable.Categories)) { Tracing.TraceInfo("Found categories document"); int depth = -1; while (NextChildElement(reader, ref depth)) { localname = reader.LocalName; if (IsCurrentNameSpace(reader, BaseNameTable.NSAtom)) { if (localname.Equals(nameTable.Category)) { AtomCategory category = ParseCategory(reader, owner); ret.Add(category); } } } } else { Tracing.TraceInfo("ParseCategories called and nothing was parsed" + localname); throw new ClientFeedException( "An invalid Atom Document was passed to the parser. This was not an app:categories document: " + localname); } return ret; } /// <summary>reads in the feed properties, updates the feed object, then starts /// working on the entries...</summary> /// <param name="reader"> xmlReader positioned at the Feed element</param> /// <param name="feed">the basefeed object that should be set</param> /// <returns> notifies user using event mechanism</returns> protected void ParseFeed(XmlReader reader, AtomFeed feed) { Tracing.Assert(reader != null, "reader should not be null"); if (reader == null) { throw new ArgumentNullException("reader"); } Tracing.Assert(feed != null, "feed should not be null"); if (feed == null) { throw new ArgumentNullException("feed"); } Tracing.TraceCall("entering AtomFeed Parser"); object localname = reader.LocalName; Tracing.TraceInfo("localname is: " + reader.LocalName); if (localname.Equals(nameTable.Feed)) { Tracing.TraceInfo("Found standard feed document"); // found the feed...... // now parse the source base of this element ParseSource(reader, feed); // feed parsing complete, send notfication OnNewAtomEntry(feed); } else if (localname.Equals(nameTable.Entry)) { Tracing.TraceInfo("Found entry document"); ParseEntry(reader); } else { Tracing.TraceInfo("ParseFeed called and nothing was parsed" + localname); // throw new ClientFeedException("An invalid Atom Document was passed to the parser. Neither Feed nor Entry started the document"); } OnParsingDone(); feed.MarkElementDirty(false); } /// <summary>parses xml to fill a precreated AtomSource object (might be a feed)</summary> /// <param name="reader">correctly positioned reader</param> /// <param name="source">created source object to be filled</param> /// <returns> </returns> protected void ParseSource(XmlReader reader, AtomSource source) { Tracing.Assert(reader != null, "reader should not be null"); if (reader == null) { throw new ArgumentNullException("reader"); } Tracing.Assert(source != null, "source should not be null"); if (source == null) { throw new ArgumentNullException("source"); } Tracing.TraceCall(); int depth = -1; ParseBasicAttributes(reader, source); while (NextChildElement(reader, ref depth)) { object localname = reader.LocalName; AtomFeed feed = source as AtomFeed; if (IsCurrentNameSpace(reader, BaseNameTable.NSAtom)) { if (localname.Equals(nameTable.Title)) { source.Title = ParseTextConstruct(reader, source); } else if (localname.Equals(nameTable.Updated)) { source.Updated = DateTime.Parse(Utilities.DecodedValue(reader.ReadString()), CultureInfo.InvariantCulture); } else if (localname.Equals(nameTable.Link)) { source.Links.Add(ParseLink(reader, source)); } else if (localname.Equals(nameTable.Id)) { source.Id = source.CreateAtomSubElement(reader, this) as AtomId; ParseBaseLink(reader, source.Id); } else if (localname.Equals(nameTable.Icon)) { source.Icon = source.CreateAtomSubElement(reader, this) as AtomIcon; ParseBaseLink(reader, source.Icon); } else if (localname.Equals(nameTable.Logo)) { source.Logo = source.CreateAtomSubElement(reader, this) as AtomLogo; ParseBaseLink(reader, source.Logo); } else if (localname.Equals(nameTable.Author)) { source.Authors.Add(ParsePerson(reader, source)); } else if (localname.Equals(nameTable.Contributor)) { source.Contributors.Add(ParsePerson(reader, source)); } else if (localname.Equals(nameTable.Subtitle)) { source.Subtitle = ParseTextConstruct(reader, source); } else if (localname.Equals(nameTable.Rights)) { source.Rights = ParseTextConstruct(reader, source); } else if (localname.Equals(nameTable.Generator)) { source.Generator = ParseGenerator(reader, source); } else if (localname.Equals(nameTable.Category)) { // need to make this another colleciton source.Categories.Add(ParseCategory(reader, source)); } else if (feed != null && localname.Equals(nameTable.Entry)) { ParseEntry(reader); } // this will either move the reader to the end of an element // if at the end, to the start of a new one. reader.Read(); } else if (feed != null && IsCurrentNameSpace(reader, BaseNameTable.gBatchNamespace)) { // parse the google batch extensions if they are there ParseBatch(reader, feed); } else if (feed != null && (IsCurrentNameSpace(reader, BaseNameTable.NSOpenSearchRss) || IsCurrentNameSpace(reader, BaseNameTable.NSOpenSearch11))) { if (localname.Equals(nameTable.TotalResults)) { feed.TotalResults = int.Parse(Utilities.DecodedValue(reader.ReadString()), CultureInfo.InvariantCulture); } else if (localname.Equals(nameTable.StartIndex)) { feed.StartIndex = int.Parse(Utilities.DecodedValue(reader.ReadString()), CultureInfo.InvariantCulture); } else if (localname.Equals(nameTable.ItemsPerPage)) { feed.ItemsPerPage = int.Parse(Utilities.DecodedValue(reader.ReadString()), CultureInfo.InvariantCulture); } } else { // default extension parsing. ParseExtensionElements(reader, source); } } } /// <summary>checks to see if the passed in namespace is the current one</summary> /// <param name="reader">correctly positioned xmlreader</param> /// <param name="namespaceToCompare">the namespace to test for</param> /// <returns> true if this is the one</returns> protected static bool IsCurrentNameSpace(XmlReader reader, string namespaceToCompare) { Tracing.Assert(reader != null, "reader should not be null"); if (reader == null) { throw new ArgumentNullException("reader"); } string curNamespace = reader.NamespaceURI; if (curNamespace.Length == 0) { curNamespace = reader.LookupNamespace(string.Empty); } return curNamespace == namespaceToCompare; } /// <summary>Parses the base attributes and puts the rest in extensions. /// This needs to happen AFTER known attributes are parsed.</summary> /// <param name="reader">correctly positioned xmlreader</param> /// <param name="baseObject">the base object to set the property on</param> /// <returns> true if an unknown attribute was found</returns> protected bool ParseBaseAttributes(XmlReader reader, AtomBase baseObject) { Tracing.Assert(reader != null, "reader should not be null"); if (reader == null) { throw new ArgumentNullException("reader"); } Tracing.Assert(baseObject != null, "baseObject should not be null"); if (baseObject == null) { throw new ArgumentNullException("baseObject"); } bool fRet = false; fRet = true; object localName = reader.LocalName; Tracing.TraceCall(); if (IsCurrentNameSpace(reader, BaseNameTable.NSXml)) { if (localName.Equals(nameTable.Base)) { baseObject.Base = new AtomUri(reader.Value); fRet = false; } else if (localName.Equals(nameTable.Language)) { baseObject.Language = Utilities.DecodedValue(reader.Value); fRet = false; } } else if (IsCurrentNameSpace(reader, BaseNameTable.gNamespace)) { ISupportsEtag se = baseObject as ISupportsEtag; if (se != null) { if (localName.Equals(nameTable.ETag)) { se.Etag = reader.Value; fRet = false; } } } if (fRet) { Tracing.TraceInfo("Found an unknown attribute"); OnNewExtensionElement(reader, baseObject); } return fRet; } /// <summary>parses extension elements, needs to happen when known attributes are done</summary> /// <param name="reader">correctly positioned xmlreader</param> /// <param name="baseObject">the base object to set the property on</param> protected void ParseExtensionElements(XmlReader reader, AtomBase baseObject) { Tracing.TraceCall(); if (reader == null) { throw new ArgumentNullException("reader", "No XmlReader supplied"); } if (baseObject == null) { throw new ArgumentNullException("baseObject", "No baseObject supplied"); } if (IsCurrentNameSpace(reader, BaseNameTable.NSAtom)) { Tracing.TraceInfo( "Found an unknown ATOM element = this might be a bug, either in the code or the document"); Tracing.TraceInfo("element: " + reader.LocalName + " position: " + reader.NodeType); // maybe we should throw here, but I rather not - makes parsing more flexible } else { // everything NOT in Atom, call it Tracing.TraceInfo("Found an unknown element"); OnNewExtensionElement(reader, baseObject); // position back to the element reader.MoveToElement(); } } /// <summary>nifty loop to check for base attributes for an object</summary> /// <param name="reader">correctly positioned xmlreader</param> /// <param name="baseObject">the base object to set the property on</param> protected void ParseBasicAttributes(XmlReader reader, AtomBase baseObject) { Tracing.TraceCall(); Tracing.Assert(reader != null, "reader should not be null"); if (reader == null) { throw new ArgumentNullException("reader"); } Tracing.Assert(baseObject != null, "baseObject should not be null"); if (baseObject == null) { throw new ArgumentNullException("baseObject"); } if (reader.NodeType == XmlNodeType.Element && reader.HasAttributes) { while (reader.MoveToNextAttribute()) { ParseBaseAttributes(reader, baseObject); } // position back to the element reader.MoveToElement(); } } /// <summary>parses a baselink object, like AtomId, AtomLogo, or AtomIcon</summary> /// <param name="reader"> correctly positioned xmlreader</param> /// <param name="baseLink">the base object to set the property on</param> /// <returns> </returns> protected void ParseBaseLink(XmlReader reader, AtomBaseLink baseLink) { Tracing.TraceCall(); Tracing.Assert(reader != null, "reader should not be null"); if (reader == null) { throw new ArgumentNullException("reader"); } Tracing.Assert(baseLink != null, "baseLink should not be null"); if (baseLink == null) { throw new ArgumentNullException("baseLink"); } ParseBasicAttributes(reader, baseLink); if (reader.NodeType == XmlNodeType.Element) { // read the element content baseLink.Uri = new AtomUri(Utilities.DecodedValue(reader.ReadString())); } } /// <summary>parses an author/person object</summary> /// <param name="reader"> an XmlReader positioned at the start of the author</param> /// <param name="owner">the object containing the person</param> /// <returns> the created author object</returns> protected AtomPerson ParsePerson(XmlReader reader, AtomBase owner) { Tracing.Assert(reader != null, "reader should not be null"); if (reader == null) { throw new ArgumentNullException("reader"); } Tracing.Assert(owner != null, "owner should not be null"); if (owner == null) { throw new ArgumentNullException("owner"); } Tracing.TraceCall(); object localname = null; AtomPerson author = owner.CreateAtomSubElement(reader, this) as AtomPerson; ParseBasicAttributes(reader, author); int lvl = -1; while (NextChildElement(reader, ref lvl)) { localname = reader.LocalName; if (localname.Equals(nameTable.Name)) { // author.Name = Utilities.DecodeString(Utilities.DecodedValue(reader.ReadString())); author.Name = Utilities.DecodedValue(reader.ReadString()); reader.Read(); } else if (localname.Equals(nameTable.Uri)) { author.Uri = new AtomUri(Utilities.DecodedValue(reader.ReadString())); reader.Read(); } else if (localname.Equals(nameTable.Email)) { author.Email = Utilities.DecodedValue(reader.ReadString()); reader.Read(); } else { // default extension parsing. ParseExtensionElements(reader, author); } } return author; } /// <summary>parses an xml stream to create an AtomCategory object</summary> /// <param name="reader">correctly positioned xmlreader</param> /// <param name="owner">the object containing the person</param> /// <returns> the created AtomCategory object</returns> protected AtomCategory ParseCategory(XmlReader reader, AtomBase owner) { Tracing.TraceCall(); Tracing.Assert(reader != null, "reader should not be null"); if (reader == null) { throw new ArgumentNullException("reader"); } if (owner == null) { throw new ArgumentNullException("owner"); } AtomCategory category = owner.CreateAtomSubElement(reader, this) as AtomCategory; if (category != null) { bool noChildren = reader.IsEmptyElement; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { object localname = reader.LocalName; if (localname.Equals(nameTable.Term)) { category.Term = Utilities.DecodedValue(reader.Value); } else if (localname.Equals(nameTable.Scheme)) { category.Scheme = new AtomUri(reader.Value); } else if (localname.Equals(nameTable.Label)) { category.Label = Utilities.DecodedValue(reader.Value); } else { ParseBaseAttributes(reader, category); } } } if (!noChildren) { reader.MoveToElement(); int lvl = -1; while (NextChildElement(reader, ref lvl)) { ParseExtensionElements(reader, category); } } } return category; } /// <summary>creates an atomlink object</summary> /// <param name="reader">correctly positioned xmlreader</param> /// <param name="owner">the object containing the person</param> /// <returns> the created AtomLink object</returns> protected AtomLink ParseLink(XmlReader reader, AtomBase owner) { Tracing.Assert(reader != null, "reader should not be null"); if (reader == null) { throw new ArgumentNullException("reader"); } if (owner == null) { throw new ArgumentNullException("owner"); } bool noChildren = reader.IsEmptyElement; Tracing.TraceCall(); AtomLink link = owner.CreateAtomSubElement(reader, this) as AtomLink; object localname = null; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { localname = reader.LocalName; if (localname.Equals(nameTable.HRef)) { link.HRef = new AtomUri(reader.Value); } else if (localname.Equals(nameTable.Rel)) { link.Rel = Utilities.DecodedValue(reader.Value); } else if (localname.Equals(nameTable.Type)) { link.Type = Utilities.DecodedValue(reader.Value); } else if (localname.Equals(nameTable.HRefLang)) { link.HRefLang = Utilities.DecodedValue(reader.Value); } else if (localname.Equals(nameTable.Title)) { link.Title = Utilities.DecodedValue(reader.Value); } else if (localname.Equals(nameTable.Length)) { link.Length = int.Parse(Utilities.DecodedValue(reader.Value), CultureInfo.InvariantCulture); } else { ParseBaseAttributes(reader, link); } } } if (!noChildren) { reader.MoveToElement(); int lvl = -1; while (NextChildElement(reader, ref lvl)) { ParseExtensionElements(reader, link); } } return link; } /// <summary>reads one of the feed entries at a time</summary> /// <param name="reader"> XmlReader positioned at the entry element</param> /// <returns> notifies user using event mechanism</returns> public void ParseEntry(XmlReader reader) { Tracing.Assert(reader != null, "reader should not be null"); if (reader == null) { throw new ArgumentNullException("reader"); } object localname = reader.LocalName; Tracing.TraceCall("Parsing atom entry"); if (localname.Equals(nameTable.Entry) == false) { throw new ClientFeedException("trying to parse an atom entry, but reader is not at the right spot"); } AtomEntry entry = OnCreateNewEntry(); ParseBasicAttributes(reader, entry); // remember the depth of entry int depth = -1; while (NextChildElement(reader, ref depth)) { localname = reader.LocalName; if (IsCurrentNameSpace(reader, BaseNameTable.NSAtom)) { if (localname.Equals(nameTable.Id)) { entry.Id = entry.CreateAtomSubElement(reader, this) as AtomId; ParseBaseLink(reader, entry.Id); } else if (localname.Equals(nameTable.Link)) { entry.Links.Add(ParseLink(reader, entry)); } else if (localname.Equals(nameTable.Updated)) { entry.Updated = DateTime.Parse(Utilities.DecodedValue(reader.ReadString()), CultureInfo.InvariantCulture); } else if (localname.Equals(nameTable.Published)) { entry.Published = DateTime.Parse(Utilities.DecodedValue(reader.ReadString()), CultureInfo.InvariantCulture); } else if (localname.Equals(nameTable.Author)) { entry.Authors.Add(ParsePerson(reader, entry)); } else if (localname.Equals(nameTable.Contributor)) { entry.Contributors.Add(ParsePerson(reader, entry)); } else if (localname.Equals(nameTable.Rights)) { entry.Rights = ParseTextConstruct(reader, entry); } else if (localname.Equals(nameTable.Category)) { AtomCategory category = ParseCategory(reader, entry); entry.Categories.Add(category); } else if (localname.Equals(nameTable.Summary)) { entry.Summary = ParseTextConstruct(reader, entry); } else if (localname.Equals(nameTable.Content)) { entry.Content = ParseContent(reader, entry); } else if (localname.Equals(nameTable.Source)) { entry.Source = entry.CreateAtomSubElement(reader, this) as AtomSource; ParseSource(reader, entry.Source); } else if (localname.Equals(nameTable.Title)) { entry.Title = ParseTextConstruct(reader, entry); } // all parse methods should leave the reader at the end of their element reader.Read(); } else if (IsCurrentNameSpace(reader, BaseNameTable.gBatchNamespace)) { // parse the google batch extensions if they are there ParseBatch(reader, entry); } else { // default extension parsing ParseExtensionElements(reader, entry); } } OnNewAtomEntry(entry); } /// <summary> /// parses the current position in the xml reader and fills /// the provided GDataEntryBatch property on the entry object /// </summary> /// <param name="reader">the xmlreader positioned at a batch element</param> /// <param name="entry">the atomentry object to fill in</param> protected void ParseBatch(XmlReader reader, AtomEntry entry) { if (reader == null) { throw new ArgumentNullException("reader"); } if (entry == null) { throw new ArgumentNullException("entry"); } if (IsCurrentNameSpace(reader, BaseNameTable.gBatchNamespace)) { object elementName = reader.LocalName; if (entry.BatchData == null) { entry.BatchData = new GDataBatchEntryData(); } GDataBatchEntryData batch = entry.BatchData; if (elementName.Equals(nameTable.BatchId)) { batch.Id = Utilities.DecodedValue(reader.ReadString()); } else if (elementName.Equals(nameTable.BatchOperation)) { batch.Type = ParseOperationType(reader); } else if (elementName.Equals(nameTable.BatchStatus)) { batch.Status = GDataBatchStatus.ParseBatchStatus(reader, this); } else if (elementName.Equals(nameTable.BatchInterrupt)) { batch.Interrupt = GDataBatchInterrupt.ParseBatchInterrupt(reader, this); } else { Tracing.TraceInfo("got an unknown batch element: " + elementName); // default extension parsing ParseExtensionElements(reader, entry); } } } /// <summary> /// reads the current positioned reader and creates a operationtype enum /// </summary> /// <param name="reader">XmlReader positioned at the start of the status element</param> /// <returns>GDataBatchOperationType</returns> protected GDataBatchOperationType ParseOperationType(XmlReader reader) { Tracing.Assert(reader != null, "reader should not be null"); if (reader == null) { throw new ArgumentNullException("reader"); } GDataBatchOperationType type = GDataBatchOperationType.Default; object localname = reader.LocalName; if (localname.Equals(nameTable.BatchOperation)) { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { localname = reader.LocalName; if (localname.Equals(nameTable.Type)) { type = (GDataBatchOperationType) Enum.Parse( typeof (GDataBatchOperationType), Utilities.DecodedValue(reader.Value), true); } } } } return type; } /// <summary> /// parses the current position in the xml reader and fills /// the provided GDataFeedBatch property on the feed object /// </summary> /// <param name="reader">the xmlreader positioned at a batch element</param> /// <param name="feed">the atomfeed object to fill in</param> protected void ParseBatch(XmlReader reader, AtomFeed feed) { if (reader == null) { throw new ArgumentNullException("reader"); } if (feed == null) { throw new ArgumentNullException("feed"); } if (IsCurrentNameSpace(reader, BaseNameTable.gBatchNamespace)) { object elementName = reader.LocalName; if (feed.BatchData == null) { feed.BatchData = new GDataBatchFeedData(); } GDataBatchFeedData batch = feed.BatchData; if (elementName.Equals(nameTable.BatchOperation)) { batch.Type = (GDataBatchOperationType) Enum.Parse(typeof (GDataBatchOperationType), reader.GetAttribute(BaseNameTable.XmlAttributeType), true); } else { Tracing.TraceInfo("got an unknown batch element: " + elementName); reader.Skip(); } } } /// <summary>parses an AtomTextConstruct</summary> /// <param name="reader">the xmlreader correctly positioned at the construct </param> /// <param name="owner">the container element</param> /// <returns>the new text construct </returns> protected AtomTextConstruct ParseTextConstruct(XmlReader reader, AtomBase owner) { Tracing.Assert(reader != null, "reader should not be null"); if (reader == null) { throw new ArgumentNullException("reader"); } if (owner == null) { throw new ArgumentNullException("owner"); } Tracing.TraceCall("Parsing atomTextConstruct"); AtomTextConstruct construct = owner.CreateAtomSubElement(reader, this) as AtomTextConstruct; if (reader.NodeType == XmlNodeType.Element) { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { object attributeName = reader.LocalName; if (attributeName.Equals(nameTable.Type)) { construct.Type = (AtomTextConstructType) Enum.Parse( typeof (AtomTextConstructType), Utilities.DecodedValue(reader.Value), true); } else { ParseBaseAttributes(reader, construct); } } } reader.MoveToElement(); switch (construct.Type) { case AtomTextConstructType.html: case AtomTextConstructType.text: construct.Text = Utilities.DecodedValue(reader.ReadString()); break; case AtomTextConstructType.xhtml: default: construct.Text = reader.ReadInnerXml(); break; } } return construct; } /// <summary>parses an AtomGenerator</summary> /// <param name="reader">the xmlreader correctly positioned at the generator </param> /// <param name="owner">the container element</param> /// <returns> </returns> protected AtomGenerator ParseGenerator(XmlReader reader, AtomBase owner) { Tracing.Assert(reader != null, "reader should not be null"); if (reader == null) { throw new ArgumentNullException("reader"); } if (owner == null) { throw new ArgumentNullException("owner"); } Tracing.TraceCall(); AtomGenerator generator = owner.CreateAtomSubElement(reader, this) as AtomGenerator; if (generator != null) { generator.Text = Utilities.DecodedValue(reader.ReadString()); if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { object attributeName = reader.LocalName; if (attributeName.Equals(nameTable.Uri)) { generator.Uri = new AtomUri(reader.Value); } else if (attributeName.Equals(nameTable.Version)) { generator.Version = Utilities.DecodedValue(reader.Value); } else { ParseBaseAttributes(reader, generator); } } } } return generator; } /// <summary>creates an AtomContent object by parsing an xml stream</summary> /// <param name="reader">a XMLReader positioned correctly </param> /// <param name="owner">the container element</param> /// <returns> null or an AtomContent object</returns> protected AtomContent ParseContent(XmlReader reader, AtomBase owner) { Tracing.Assert(reader != null, "reader should not be null"); if (reader == null) { throw new ArgumentNullException("reader"); } if (owner == null) { throw new ArgumentNullException("owner"); } AtomContent content = owner.CreateAtomSubElement(reader, this) as AtomContent; Tracing.TraceCall(); if (content != null) { if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { object localname = reader.LocalName; if (localname.Equals(nameTable.Type)) { content.Type = Utilities.DecodedValue(reader.Value); } else if (localname.Equals(nameTable.Src)) { content.Src = new AtomUri(reader.Value); } else { ParseBaseAttributes(reader, content); } } } if (MoveToStartElement(reader)) { if (content.Type.Equals("text") || content.Type.Equals("html") || content.Type.StartsWith("text/")) { // if it's text it get's just the string treatment. No // subelements are allowed here content.Content = Utilities.DecodedValue(reader.ReadString()); } else if (content.Type.Equals("xhtml") || content.Type.Contains("/xml") || content.Type.Contains("+xml")) { // do not get childlists if the element is empty. That would skip to the next element if (!reader.IsEmptyElement) { // everything else will be nodes in the extension element list // different media type. Create extension elements int lvl = -1; while (NextChildElement(reader, ref lvl)) { ParseExtensionElements(reader, content); } } } else { // everything else SHOULD be base 64 encoded, so one big string // i know the if statement could be combined with the text handling // but i consider it clearer to make a 3 cases statement than combine them content.Content = Utilities.DecodedValue(reader.ReadString()); } } } return content; } } }
// 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.Threading; using Xunit; namespace System.Linq.Parallel.Tests { public class ExceptTests { private const int DuplicateFactor = 4; public static IEnumerable<object[]> ExceptUnorderedData(int[] leftCounts, int[] rightCounts) { foreach (object[] parms in UnorderedSources.BinaryRanges(leftCounts.Cast<int>(), (l, r) => 0 - r / 2, rightCounts.Cast<int>())) { yield return parms.Take(4).Concat(new object[] { (int)parms[3] + (int)parms[4], Math.Max(0, (int)parms[1] - ((int)parms[3] + 1) / 2) }).ToArray(); } } public static IEnumerable<object[]> ExceptData(int[] leftCounts, int[] rightCounts) { foreach (object[] parms in ExceptUnorderedData(leftCounts, rightCounts)) { parms[0] = ((Labeled<ParallelQuery<int>>)parms[0]).Order(); yield return parms; } } public static IEnumerable<object[]> ExceptSourceMultipleData(int[] counts) { foreach (int leftCount in counts.Cast<int>()) { ParallelQuery<int> left = Enumerable.Range(0, leftCount * DuplicateFactor).Select(x => x % leftCount).ToArray().AsParallel().AsOrdered(); foreach (int rightCount in new[] { 0, 1, Math.Max(DuplicateFactor * 2, leftCount), 2 * Math.Max(DuplicateFactor, leftCount) }) { int rightStart = 0 - rightCount / 2; yield return new object[] { left, leftCount, ParallelEnumerable.Range(rightStart, rightCount), rightCount, rightStart + rightCount, Math.Max(0, leftCount - (rightCount + 1) / 2) }; } } } // // Except // [Theory] [MemberData(nameof(ExceptUnorderedData), new[] { 0, 1, 2, 16 }, new[] { 0, 1, 8 })] public static void Except_Unordered(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; IntegerRangeSet seen = new IntegerRangeSet(start, count); foreach (int i in leftQuery.Except(rightQuery)) { seen.Add(i); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(ExceptUnorderedData), new[] { 1024, 1024 * 16 }, new[] { 0, 1024, 1024 * 32 })] public static void Except_Unordered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { Except_Unordered(left, leftCount, right, rightCount, start, count); } [Theory] [MemberData(nameof(ExceptData), new[] { 0, 1, 2, 16 }, new[] { 0, 1, 8 })] public static void Except(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; int seen = start; foreach (int i in leftQuery.Except(rightQuery)) { Assert.Equal(seen++, i); } Assert.Equal(count + start, seen); } [Theory] [OuterLoop] [MemberData(nameof(ExceptData), new[] { 1024, 1024 * 16 }, new[] { 0, 1024, 1024 * 32 })] public static void Except_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { Except(left, leftCount, right, rightCount, start, count); } [Theory] [MemberData(nameof(ExceptUnorderedData), new[] { 0, 1, 2, 16 }, new[] { 0, 1, 8 })] public static void Except_Unordered_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; IntegerRangeSet seen = new IntegerRangeSet(start, count); Assert.All(leftQuery.Except(rightQuery).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(ExceptUnorderedData), new[] { 1024, 1024 * 16 }, new[] { 0, 1024, 1024 * 32 })] public static void Except_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { Except_Unordered_NotPipelined(left, leftCount, right, rightCount, start, count); } [Theory] [MemberData(nameof(ExceptData), new[] { 0, 1, 2, 16 }, new[] { 0, 1, 8 })] public static void Except_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; int seen = start; Assert.All(leftQuery.Except(rightQuery).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(count + start, seen); } [Theory] [OuterLoop] [MemberData(nameof(ExceptData), new[] { 1024, 1024 * 16 }, new[] { 0, 1024, 1024 * 32 })] public static void Except_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { Except_NotPipelined(left, leftCount, right, rightCount, start, count); } [Theory] [MemberData(nameof(ExceptUnorderedData), new[] { 0, 1, 2, 16 }, new[] { 0, 1, 8 })] public static void Except_Unordered_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; leftCount = Math.Min(DuplicateFactor * 2, leftCount); rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2); int expectedCount = Math.Max(0, leftCount - rightCount); IntegerRangeSet seen = new IntegerRangeSet(leftCount - expectedCount, expectedCount); foreach (int i in leftQuery.Except(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor), new ModularCongruenceComparer(DuplicateFactor * 2))) { seen.Add(i % (DuplicateFactor * 2)); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(ExceptUnorderedData), new[] { 1024, 1024 * 16 }, new[] { 0, 1024, 1024 * 32 })] public static void Except_Unordered_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { Except_Unordered_Distinct(left, leftCount, right, rightCount, start, count); } [Theory] [MemberData(nameof(ExceptData), new[] { 0, 1, 2, 16 }, new[] { 0, 1, 8 })] public static void Except_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; leftCount = Math.Min(DuplicateFactor * 2, leftCount); rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2); int expectedCount = Math.Max(0, leftCount - rightCount); int seen = expectedCount == 0 ? 0 : leftCount - expectedCount; foreach (int i in leftQuery.Except(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor), new ModularCongruenceComparer(DuplicateFactor * 2))) { Assert.Equal(seen++, i); } Assert.Equal(expectedCount == 0 ? 0 : leftCount, seen); } [Theory] [OuterLoop] [MemberData(nameof(ExceptData), new[] { 1024, 1024 * 16 }, new[] { 0, 1024, 1024 * 32 })] public static void Except_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { Except_Distinct(left, leftCount, right, rightCount, start, count); } [Theory] [MemberData(nameof(ExceptUnorderedData), new[] { 0, 1, 2, 16 }, new[] { 0, 1, 8 })] public static void Except_Unordered_Distinct_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; leftCount = Math.Min(DuplicateFactor * 2, leftCount); rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2); int expectedCount = Math.Max(0, leftCount - rightCount); IntegerRangeSet seen = new IntegerRangeSet(leftCount - expectedCount, expectedCount); Assert.All(leftQuery.Except(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor), new ModularCongruenceComparer(DuplicateFactor * 2)).ToList(), x => seen.Add(x % (DuplicateFactor * 2))); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(ExceptData), new[] { 1024, 1024 * 16 }, new[] { 0, 1024, 1024 * 32 })] public static void Except_Unordered_Distinct_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { Except_Unordered_Distinct_NotPipelined(left, leftCount, right, rightCount, start, count); } [Theory] [MemberData(nameof(ExceptData), new[] { 0, 1, 2, 16 }, new[] { 0, 1, 8 })] public static void Except_Distinct_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; leftCount = Math.Min(DuplicateFactor * 2, leftCount); rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2); int expectedCount = Math.Max(0, leftCount - rightCount); int seen = expectedCount == 0 ? 0 : leftCount - expectedCount; Assert.All(leftQuery.Except(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor), new ModularCongruenceComparer(DuplicateFactor * 2)).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(expectedCount == 0 ? 0 : leftCount, seen); } [Theory] [OuterLoop] [MemberData(nameof(ExceptData), new[] { 1024, 1024 * 16 }, new[] { 0, 1024, 1024 * 32 })] public static void Except_Distinct_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount, int start, int count) { Except_Distinct_NotPipelined(left, leftCount, right, rightCount, start, count); } [Theory] [MemberData(nameof(ExceptSourceMultipleData), new[] { 0, 1, 2, 16 })] public static void Except_Unordered_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int start, int count) { // The difference between this test and the previous, is that it's not possible to // get non-unique results from ParallelEnumerable.Range()... // Those tests either need modification of source (via .Select(x => x / DuplicateFactor) or similar, // or via a comparator that considers some elements equal. IntegerRangeSet seen = new IntegerRangeSet(start, count); Assert.All(leftQuery.AsUnordered().Except(rightQuery), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(ExceptSourceMultipleData), new[] { 1024, 1024 * 16 })] public static void Except_Unordered_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int start, int count) { Except_Unordered_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, start, count); } [Theory] [MemberData(nameof(ExceptSourceMultipleData), new[] { 0, 1, 2, 16 })] public static void Except_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int start, int count) { int seen = start; Assert.All(leftQuery.Except(rightQuery), x => Assert.Equal(seen++, x)); Assert.Equal(start + count, seen); } [Theory] [OuterLoop] [MemberData(nameof(ExceptSourceMultipleData), new[] { 1024, 1024 * 16 })] public static void Except_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int start, int count) { Except_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, start, count); } [Fact] public static void Except_NotSupportedException() { #pragma warning disable 618 Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Except(Enumerable.Range(0, 1))); Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Except(Enumerable.Range(0, 1), null)); #pragma warning restore 618 } [Fact] // Should not get the same setting from both operands. public static void Except_NoDuplicateSettings() { CancellationToken t = new CancellationTokenSource().Token; Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithCancellation(t).Except(ParallelEnumerable.Range(0, 1).WithCancellation(t))); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1).Except(ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1))); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default).Except(ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default))); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default).Except(ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default))); } [Fact] public static void Except_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Except(ParallelEnumerable.Range(0, 1))); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Except(null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Except(ParallelEnumerable.Range(0, 1), EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Except(null, EqualityComparer<int>.Default)); } } }
/* * * (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 System.Text; using System.Text.RegularExpressions; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using AjaxPro; using ASC.Core; using ASC.Core.Users; using ASC.ElasticSearch; using ASC.Forum; using ASC.Notify; using ASC.Notify.Model; using ASC.Notify.Recipients; using ASC.Web.Community.Modules.Forum.UserControls.Resources; using ASC.Web.Community.Search; using ASC.Web.Studio.Controls.FileUploader; using ASC.Web.Studio.Controls.FileUploader.HttpModule; using ASC.Web.Studio.Core; using ASC.Web.Studio.Utility; using ASC.Web.Studio.Utility.HtmlUtility; using ASC.Web.UserControls.Forum.Common; namespace ASC.Web.UserControls.Forum { public class ForumAttachmentUploadHanler : FileUploadHandler { public override FileUploadResult ProcessUpload(HttpContext context) { var result = new FileUploadResult { Success = false }; try { if (FileToUpload.HasFilesToUpload(context)) { var settingsID = new Guid(context.Request["SettingsID"]); var settings = Community.Forum.ForumManager.Settings; var thread = ForumDataProvider.GetThreadByID(TenantProvider.CurrentTenantID, Convert.ToInt32(context.Request["ThreadID"])); if (thread == null) return result; var forumManager = settings.ForumManager; var offsetPhysicalPath = string.Empty; forumManager.GetAttachmentVirtualDirPath(thread, settingsID, new Guid(context.Request["UserID"]), out offsetPhysicalPath); var file = new FileToUpload(context); var newFileName = GetFileName(file.FileName); var origFileName = newFileName; var i = 1; var store = forumManager.GetStore(); while (store.IsFile(offsetPhysicalPath + "\\" + newFileName)) { var ind = origFileName.LastIndexOf("."); newFileName = ind != -1 ? origFileName.Insert(ind, "_" + i.ToString()) : origFileName + "_" + i.ToString(); i++; } result.FileName = newFileName; result.FileURL = store.Save(offsetPhysicalPath + "\\" + newFileName, file.InputStream).ToString(); result.Data = new { OffsetPhysicalPath = offsetPhysicalPath + "\\" + newFileName, FileName = newFileName, Size = file.ContentLength, ContentType = file.FileContentType, SettingsID = settingsID }; result.Success = true; } } catch (Exception ex) { result.Success = false; result.Message = ex.Message; } return result; } } public enum NewPostType { Post = 0, Topic = 1, Poll = 2 } public enum PostAction { Normal = 0, Quote = 1, Reply = 2, Edit = 3 } public enum SubscriveViewType { Checked, Unchecked, Disable } internal class TagComparer : IEqualityComparer<Tag> { #region IEqualityComparer<Tag> Members public bool Equals(Tag x, Tag y) { if (Object.ReferenceEquals(x, y)) return true; if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null)) return false; return x.Name.Equals(y.Name, StringComparison.InvariantCultureIgnoreCase); } public int GetHashCode(Tag obj) { if (Object.ReferenceEquals(obj, null)) return 0; return string.IsNullOrEmpty(obj.Name) ? 0 : obj.Name.GetHashCode(); } #endregion } [AjaxNamespace("PostCreator")] public partial class NewPostControl : UserControl, INotifierView, ISubscriberView, IContextInitializer { [Serializable] internal class FileObj { public string fileName { get; set; } public string size { get; set; } public string offsetPhysicalPath { get; set; } public string contentType { get; set; } } public Guid SettingsID { get; set; } public NewPostType PostType { get; set; } public PostAction PostAction { get; set; } public Topic Topic { get; set; } public Thread Thread { get; set; } public Post ParentPost { get; set; } public Post EditedPost { get; set; } protected string _text = ""; private string _subject = ""; private string _tagString = ""; private ForumManager _forumManager; private bool _isSelectForum; private List<ThreadCategory> _categories = null; private List<Thread> _threads = null; private List<FileObj> Attachments { get; set; } protected string _errorMessage = ""; protected SubscriveViewType _subscribeViewType; protected PostTextFormatter _formatter = PostTextFormatter.FCKEditor; protected UserInfo _currentUser = null; protected Settings _settings; protected int _threadForAttachFiles = 0; protected string _attachmentsString = ""; private void InitScripts() { Page.RegisterBodyScripts("~/UserControls/Common/ckeditor/ckeditor-connector.js"); //Page.RegisterInlineScript("ckeditorConnector.load(function () {ForumManager.forumEditor = jq('#ckEditor').ckeditor({ toolbar : 'ComForum', filebrowserUploadUrl: '" + RenderRedirectUpload() + @"'}).editor;});"); Page.RegisterInlineScript("ckeditorConnector.load(function () {" + "ForumManager.forumEditor = CKEDITOR.replace('ckEditor', { toolbar : 'ComBlog', filebrowserUploadUrl: '" + RenderRedirectUpload() + "'});" + "ForumManager.forumEditor.on('change', function() {if (this.getData() == '') {jq('#btnPreview').addClass('disable');} else {jq('#btnPreview').removeClass('disable');}});" + "});"); var script = @"FileUploadManager.Init({ DropZone: 'forum_uploadDialogContainer', TargetContainerID: 'forum_uploadContainer', BrowseButton: 'forum_uploadButton', MaxSize: '" + SetupInfo.MaxUploadSize + @"', FileUploadHandler: 'ASC.Web.UserControls.Forum.ForumAttachmentUploadHanler,ASC.Web.Community', Data: { 'SettingsID': '" + SettingsID + @"', 'ThreadID': '" + _threadForAttachFiles + @"', 'UserID': '" + SecurityContext.CurrentAccount.ID + @"' }, OverAllProcessHolder: jq('#forum_overallprocessHolder'), OverAllProcessBarCssClass: 'forum_overAllProcessBarCssClass', OverallProgressText: '" + ForumUCResource.OverallProgress + @"', DeleteLinkCSSClass: 'forum_deleteLinkCSSClass', LoadingImageCSSClass: 'forum_loadingCSSClass', CompleteCSSClass: 'forum_completeCSSClass', DeleteAfterUpload: false, Events: { OnPreUploadStart: function() { FileUploadManager.DisableBrowseBtn(true); ForumManager.BlockButtons(); }, OnPostUploadStop: function() { jq('#forum_attachments').val(JSON.stringify(FileUploadManager.uploadedFiles)); FileUploadManager.DisableBrowseBtn(false); ForumManager.UnblockButtons(); } }, EmptyFileErrorMsg: """ + ForumUCResource.EmptyFileErrorMsg + @""", FileSizeErrorMsg: """ + ForumUCResource.FileSizeErrorMsg + @""" });"; Page.RegisterInlineScript(script); } protected void Page_Load(object sender, EventArgs e) { _settings = ASC.Web.Community.Forum.ForumManager.Settings; _forumManager = _settings.ForumManager; _currentUser = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID); Utility.RegisterTypeForAjax(typeof(TagSuggest)); Utility.RegisterTypeForAjax(this.GetType()); Utility.RegisterTypeForAjax(typeof(PostControl)); Page.RegisterBodyScripts("~/js/uploader/jquery.fileupload.js", "~/js/uploader/jquery.fileuploadmanager.js"); PostType = NewPostType.Topic; PostAction = PostAction.Normal; int idTopic = 0; int idThread = 0; if (!String.IsNullOrEmpty(Request[_settings.TopicParamName])) { try { idTopic = Convert.ToInt32(Request[_settings.TopicParamName]); } catch { idTopic = 0; } if (idTopic == 0) { Response.Redirect(_settings.StartPageAbsolutePath); return; } else PostType = NewPostType.Post; } else if (!String.IsNullOrEmpty(Request[_settings.ThreadParamName])) { try { idThread = Convert.ToInt32(Request[_settings.ThreadParamName]); } catch { idThread = 0; } if (idThread == 0) { Response.Redirect(_settings.StartPageAbsolutePath); return; } else PostType = NewPostType.Topic; int topicType = 0; try { topicType = Convert.ToInt32(Request[_settings.PostParamName]); } catch { topicType = 0; } if (topicType == 1) PostType = NewPostType.Poll; } else { int topicType = 0; try { topicType = Convert.ToInt32(Request[_settings.PostParamName]); } catch { topicType = 0; } if (topicType == 1) PostType = NewPostType.Poll; if (IsPostBack) { if (!String.IsNullOrEmpty(Request["forum_thread_id"])) { try { idThread = Convert.ToInt32(Request["forum_thread_id"]); } catch { idThread = 0; } } } else { ForumDataProvider.GetThreadCategories(TenantProvider.CurrentTenantID, out _categories, out _threads); foreach (var thread in _threads) { bool isAllow = false; if (PostType == NewPostType.Topic) isAllow = _forumManager.ValidateAccessSecurityAction(ForumAction.TopicCreate, thread); else if (PostType == NewPostType.Poll) isAllow = _forumManager.ValidateAccessSecurityAction(ForumAction.PollCreate, thread); if (isAllow) { idThread = thread.ID; Thread = thread; break; } } } if (idThread == 0) { Response.Redirect(_settings.StartPageAbsolutePath); return; } _isSelectForum = true; } if (PostType == NewPostType.Topic || PostType == NewPostType.Poll) { if (Thread == null) Thread = ForumDataProvider.GetThreadByID(TenantProvider.CurrentTenantID, idThread); if (Thread == null) { Response.Redirect(_settings.StartPageAbsolutePath); return; } if (Thread.Visible == false) Response.Redirect(_settings.StartPageAbsolutePath); _threadForAttachFiles = Thread.ID; if (PostType == NewPostType.Topic) { if (!_forumManager.ValidateAccessSecurityAction(ForumAction.TopicCreate, Thread)) { Response.Redirect(_settings.StartPageAbsolutePath); return; } } else if (PostType == NewPostType.Poll) { if (!_forumManager.ValidateAccessSecurityAction(ForumAction.PollCreate, Thread)) { Response.Redirect(_settings.StartPageAbsolutePath); return; } } } else if (PostType == NewPostType.Post) { int parentPostId = 0; if (!String.IsNullOrEmpty(Request[_settings.ActionParamName]) && !String.IsNullOrEmpty(Request[_settings.PostParamName])) { try { PostAction = (PostAction)Convert.ToInt32(Request[_settings.ActionParamName]); } catch { PostAction = PostAction.Normal; } try { parentPostId = Convert.ToInt32(Request[_settings.PostParamName]); } catch { parentPostId = 0; PostAction = PostAction.Normal; } } Topic = ForumDataProvider.GetTopicByID(TenantProvider.CurrentTenantID, idTopic); if (Topic == null) { Response.Redirect(_settings.StartPageAbsolutePath); return; } if (new Thread() { ID = Topic.ThreadID }.Visible == false) { Response.Redirect(_settings.StartPageAbsolutePath); return; } var recentPosts = ForumDataProvider.GetRecentTopicPosts(TenantProvider.CurrentTenantID, Topic.ID, 5, (PostAction == PostAction.Normal || PostAction == PostAction.Edit) ? 0 : parentPostId); if (recentPosts.Count > 0) { Label titleRecentPosts = new Label(); titleRecentPosts.Text = "<div class=\"headerPanelSmall-splitter\" style='margin-top:20px;'><b>" + ForumUCResource.RecentPostFromTopic + ":</b></div>"; _recentPostsHolder.Controls.Add(titleRecentPosts); int i = 0; foreach (Post post in recentPosts) { PostControl postControl = (PostControl)LoadControl(_settings.UserControlsVirtualPath + "/PostControl.ascx"); postControl.Post = post; postControl.SettingsID = SettingsID; postControl.IsEven = (i % 2 == 0); _recentPostsHolder.Controls.Add(postControl); i++; } } _threadForAttachFiles = Topic.ThreadID; if (PostAction == PostAction.Quote || PostAction == PostAction.Reply || PostAction == PostAction.Normal) { if (!_forumManager.ValidateAccessSecurityAction(ForumAction.PostCreate, Topic)) { Response.Redirect(_settings.StartPageAbsolutePath); return; } if (PostAction == PostAction.Quote || PostAction == PostAction.Reply) { ParentPost = ForumDataProvider.GetPostByID(TenantProvider.CurrentTenantID, parentPostId); if (ParentPost == null) { Response.Redirect(_settings.StartPageAbsolutePath); return; } } _subject = Topic.Title; if (PostAction == PostAction.Quote) { _text = String.Format(@"<div class=""mainQuote""> <div class=""quoteCaption""><span class=""bold"">{0}</span>&nbsp;{1}</div> <div id=""quote"" > <div class=""bord""><div class=""t""><div class=""r""> <div class=""b""><div class=""l""><div class=""c""> <div class=""reducer""> {2} </div> </div></div></div> </div></div></div> </div> </div><br/>", ParentPost.Poster.DisplayUserName(), ForumUCResource.QuoteCaptioon_Wrote + ":", ParentPost.Text); } if (PostAction == PostAction.Reply) _text = "<span class=\"headerPanelSmall-splitter\"><b>To: " + ParentPost.Poster.DisplayUserName() + "</b></span><br/><br/>"; } else if (PostAction == PostAction.Edit) { EditedPost = ForumDataProvider.GetPostByID(TenantProvider.CurrentTenantID, parentPostId); if (EditedPost == null) { Response.Redirect(_settings.StartPageAbsolutePath); return; } if (!_forumManager.ValidateAccessSecurityAction(ForumAction.PostEdit, EditedPost)) { Response.Redirect("Default.aspx"); return; } Topic = ForumDataProvider.GetTopicByID(TenantProvider.CurrentTenantID, EditedPost.TopicID); _text = EditedPost.Text; _subject = EditedPost.Subject; } } if (PostType != NewPostType.Poll) _pollMaster.Visible = false; else _pollMaster.QuestionFieldID = "forum_subject"; InitScripts(); if (IsPostBack) { _attachmentsString = Request["forum_attachments"] ?? ""; var jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); Attachments = jsSerializer.Deserialize<List<FileObj>>(_attachmentsString); #region IsPostBack if (PostType == NewPostType.Topic) { _subject = string.IsNullOrEmpty(Request["forum_subject"]) ? string.Empty : Request["forum_subject"].Trim(); } else if (PostType == NewPostType.Poll) { _subject = string.IsNullOrEmpty(_pollMaster.Name) ? string.Empty : _pollMaster.Name.Trim(); } if (String.IsNullOrEmpty(_subject) && PostType != NewPostType.Post) { _subject = ""; _errorMessage = "<div class=\"errorBox\">" + ForumUCResource.ErrorSubjectEmpty + "</div>"; return; } if (!String.IsNullOrEmpty(Request["forum_tags"])) { Regex r = new Regex(@"\s*,\s*", RegexOptions.Compiled); _tagString = r.Replace(Request["forum_tags"].Trim(), ","); } _text = Request["forum_text"].Trim(); if (String.IsNullOrEmpty(_text)) { _text = ""; Page.RegisterInlineScript("ForumManager.ShowInfoMessage('" + ForumUCResource.ErrorTextEmpty + "');"); return; } else { _text = _text.Replace("<br />", "<br />\r\n").TrimEnd('\r', '\n'); } if (String.IsNullOrEmpty(Request["forum_topSubscription"])) _subscribeViewType = SubscriveViewType.Disable; else { if (String.Equals(Request["forum_topSubscription"], "1", StringComparison.InvariantCultureIgnoreCase)) _subscribeViewType = SubscriveViewType.Checked; else _subscribeViewType = SubscriveViewType.Unchecked; } if (PostType == NewPostType.Post) { if (PostAction == PostAction.Edit) { EditedPost.Subject = _subject; EditedPost.Text = _text; EditedPost.Formatter = _formatter; try { ForumDataProvider.UpdatePost(TenantProvider.CurrentTenantID, EditedPost.ID, EditedPost.Subject, EditedPost.Text, EditedPost.Formatter); FactoryIndexer<PostWrapper>.UpdateAsync(EditedPost); if (IsAllowCreateAttachment) CreateAttachments(EditedPost); int postsOnPageCount = -1; int postsPageNumber = -1; CommonControlsConfigurer.FCKEditingComplete(_settings.FileStoreModuleID, EditedPost.ID.ToString(), EditedPost.Text, true); var redirectUrl = _settings.PostPageAbsolutePath + "&t=" + EditedPost.TopicID.ToString(); if (!String.IsNullOrEmpty(Request["p"])) { postsPageNumber = Convert.ToInt32(Request["p"]); redirectUrl += "&p=" + postsPageNumber.ToString(); } if (!String.IsNullOrEmpty(Request["size"])) { postsOnPageCount = Convert.ToInt32(Request["size"]); redirectUrl += "&size=" + postsOnPageCount.ToString(); } Response.Redirect(redirectUrl); return; } catch (Exception ex) { _errorMessage = "<div class=\"errorBox\">" + ex.Message.HtmlEncode() + "</div>"; return; } } else { var post = new Post(Topic.Title, _text); post.TopicID = Topic.ID; post.ParentPostID = ParentPost == null ? 0 : ParentPost.ID; post.Formatter = _formatter; post.IsApproved = _forumManager.ValidateAccessSecurityAction(ForumAction.ApprovePost, Topic); try { post.ID = ForumDataProvider.CreatePost(TenantProvider.CurrentTenantID, post.TopicID, post.ParentPostID, post.Subject, post.Text, post.IsApproved, post.Formatter); FactoryIndexer<PostWrapper>.IndexAsync(post); Topic.PostCount++; CommonControlsConfigurer.FCKEditingComplete(_settings.FileStoreModuleID, post.ID.ToString(), post.Text, false); if (IsAllowCreateAttachment) CreateAttachments(post); NotifyAboutNewPost(post); if (_subscribeViewType != SubscriveViewType.Disable) { _forumManager.PresenterFactory.GetPresenter<ISubscriberView>().SetView(this); if (this.GetSubscriptionState != null) this.GetSubscriptionState(this, new SubscribeEventArgs(SubscriptionConstants.NewPostInTopic, Topic.ID.ToString(), SecurityContext.CurrentAccount.ID)); if (this.IsSubscribe && _subscribeViewType == SubscriveViewType.Unchecked) { if (this.UnSubscribe != null) this.UnSubscribe(this, new SubscribeEventArgs(SubscriptionConstants.NewPostInTopic, Topic.ID.ToString(), SecurityContext.CurrentAccount.ID)); } else if (!this.IsSubscribe && _subscribeViewType == SubscriveViewType.Checked) { if (this.Subscribe != null) this.Subscribe(this, new SubscribeEventArgs(SubscriptionConstants.NewPostInTopic, Topic.ID.ToString(), SecurityContext.CurrentAccount.ID)); } } int numb_page = Convert.ToInt32(Math.Ceiling(Topic.PostCount / (_settings.PostCountOnPage * 1.0))); var postURL = _settings.LinkProvider.Post(post.ID, Topic.ID, numb_page); Response.Redirect(postURL); return; } catch (Exception ex) { _errorMessage = "<div class=\"errorBox\">" + ex.Message.HtmlEncode() + "</div>"; return; } #endregion } } if (PostType == NewPostType.Topic || PostType == NewPostType.Poll) { if (PostType == NewPostType.Poll && _pollMaster.AnswerVariants.Count < 2) { _errorMessage = "<div class=\"errorBox\">" + ForumUCResource.ErrorPollVariantCount + "</div>"; return; } try { var topic = new Topic(_subject, TopicType.Informational); topic.ThreadID = Thread.ID; topic.Tags = CreateTags(Thread); topic.Type = (PostType == NewPostType.Poll ? TopicType.Poll : TopicType.Informational); topic.ID = ForumDataProvider.CreateTopic(TenantProvider.CurrentTenantID, topic.ThreadID, topic.Title, topic.Type); foreach (var ace in ASC.Forum.Module.Constants.Aces) { CoreContext.AuthorizationManager.AddAce(new AzRecord(SecurityContext.CurrentAccount.ID, ace, ASC.Common.Security.Authorizing.AceType.Allow, topic)); } Topic = topic; FactoryIndexer<TopicWrapper>.IndexAsync(topic); foreach (var tag in topic.Tags) { if (tag.ID == 0) ForumDataProvider.CreateTag(TenantProvider.CurrentTenantID, topic.ID, tag.Name, tag.IsApproved); else ForumDataProvider.AttachTagToTopic(TenantProvider.CurrentTenantID, tag.ID, topic.ID); } var post = new Post(topic.Title, _text); post.TopicID = topic.ID; post.ParentPostID = 0; post.Formatter = _formatter; post.IsApproved = _forumManager.ValidateAccessSecurityAction(ForumAction.ApprovePost, Topic); post.ID = ForumDataProvider.CreatePost(TenantProvider.CurrentTenantID, post.TopicID, post.ParentPostID, post.Subject, post.Text, post.IsApproved, post.Formatter); FactoryIndexer<PostWrapper>.IndexAsync(post); CommonControlsConfigurer.FCKEditingComplete(_settings.FileStoreModuleID, post.ID.ToString(), post.Text, false); if (IsAllowCreateAttachment) CreateAttachments(post); if (PostType == NewPostType.Poll) { var answerVariants = new List<string>(); foreach (var answVariant in _pollMaster.AnswerVariants) answerVariants.Add(answVariant.Name); topic.QuestionID = ForumDataProvider.CreatePoll(TenantProvider.CurrentTenantID, topic.ID, _pollMaster.Singleton ? QuestionType.OneAnswer : QuestionType.SeveralAnswer, topic.Title, answerVariants); var topicWrapper = (TopicWrapper)topic; FactoryIndexer<TopicWrapper>.IndexAsync(topicWrapper); } NotifyAboutNewPost(post); if (_subscribeViewType == SubscriveViewType.Checked) { _forumManager.PresenterFactory.GetPresenter<ISubscriberView>().SetView(this); if (this.Subscribe != null) this.Subscribe(this, new SubscribeEventArgs(SubscriptionConstants.NewPostInTopic, topic.ID.ToString(), SecurityContext.CurrentAccount.ID)); } Response.Redirect(_settings.LinkProvider.Post(post.ID, topic.ID, 1)); return; } catch (Exception ex) { _errorMessage = "<div class=\"errorBox\">" + ex.Message.HtmlEncode() + "</div>"; return; } } } else { _forumManager.PresenterFactory.GetPresenter<ISubscriberView>().SetView(this); if (PostType == NewPostType.Poll || PostType == NewPostType.Topic) { if (this.GetSubscriptionState != null) this.GetSubscriptionState(this, new SubscribeEventArgs(SubscriptionConstants.NewPostInThread, Thread.ID.ToString(), SecurityContext.CurrentAccount.ID)); if (this.IsSubscribe) _subscribeViewType = SubscriveViewType.Disable; else _subscribeViewType = SubscriveViewType.Checked; } else if (PostType == NewPostType.Post && PostAction != PostAction.Edit) { if (this.GetSubscriptionState != null) this.GetSubscriptionState(this, new SubscribeEventArgs(SubscriptionConstants.NewPostInThread, Topic.ThreadID.ToString(), SecurityContext.CurrentAccount.ID)); if (this.IsSubscribe) _subscribeViewType = SubscriveViewType.Disable; else { if (SubscriptionConstants.SubscriptionProvider.IsUnsubscribe(new DirectRecipient(SecurityContext.CurrentAccount.ID.ToString(), SecurityContext.CurrentAccount.Name), SubscriptionConstants.NewPostInTopic, Topic.ID.ToString())) { _subscribeViewType = SubscriveViewType.Unchecked; } else _subscribeViewType = SubscriveViewType.Checked; } } else _subscribeViewType = SubscriveViewType.Disable; } } private void NotifyAboutNewPost(Post post) { int numb_page = Convert.ToInt32(Math.Ceiling(Topic.PostCount / (_settings.PostCountOnPage * 1.0))); string hostUrl = CommonLinkUtility.ServerRootPath; string topicURL = hostUrl + _settings.LinkProvider.PostList(Topic.ID); string postURL = hostUrl + _settings.LinkProvider.Post(post.ID, Topic.ID, numb_page); string threadURL = hostUrl + _settings.LinkProvider.TopicList(Topic.ThreadID); string userURL = hostUrl + CommonLinkUtility.GetUserProfile(post.PosterID); string postText = Regex.Replace(HtmlUtility.GetFull(post.Text), @"\r\n?|\n", string.Empty); var initatorInterceptor = new InitiatorInterceptor(new DirectRecipient(SecurityContext.CurrentAccount.ID.ToString(), SecurityContext.CurrentAccount.Name)); try { SubscriptionConstants.NotifyClient.AddInterceptor(initatorInterceptor); var poster = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID); _forumManager.PresenterFactory.GetPresenter<INotifierView>().SetView(this); SubscriptionConstants.NotifyClient.BeginSingleRecipientEvent(SubscriptionConstants.SyncName); if (SendNotify != null) { if (PostType == NewPostType.Poll || PostType == NewPostType.Topic) SendNotify(this, new NotifyEventArgs(SubscriptionConstants.NewTopicInForum, null) { ThreadTitle = Topic.ThreadTitle, TopicId = Topic.ID, TopicTitle = Topic.Title, Poster = poster, Date = post.CreateDate.ToShortString(), PostURL = postURL, TopicURL = topicURL, ThreadURL = threadURL, UserURL = userURL, PostText = postText }); SendNotify(this, new NotifyEventArgs(SubscriptionConstants.NewPostInThread, Topic.ThreadID.ToString()) { ThreadTitle = Topic.ThreadTitle, TopicTitle = Topic.Title, Poster = poster, Date = post.CreateDate.ToShortString(), PostURL = postURL, TopicURL = topicURL, ThreadURL = threadURL, UserURL = userURL, PostText = postText, TopicId = Topic.ID, PostId = post.ID, TenantId = Topic.TenantID }); SendNotify(this, new NotifyEventArgs(SubscriptionConstants.NewPostInTopic, Topic.ID.ToString()) { ThreadTitle = Topic.ThreadTitle, TopicTitle = Topic.Title, Poster = poster, Date = post.CreateDate.ToShortString(), PostURL = postURL, TopicURL = topicURL, ThreadURL = threadURL, UserURL = userURL, PostText = postText, TopicId = Topic.ID, PostId = post.ID, TenantId = Topic.TenantID }); } SubscriptionConstants.NotifyClient.EndSingleRecipientEvent(SubscriptionConstants.SyncName); } finally { SubscriptionConstants.NotifyClient.RemoveInterceptor(initatorInterceptor.Name); } } protected void TopicHeader() { if (PostType == NewPostType.Post || PostType == NewPostType.Poll) return; StringBuilder sb = new StringBuilder(); sb.Append("<div class=\"headerPanel-splitter requiredField\">"); sb.Append("<span class=\"requiredErrorText\"></span>"); sb.Append("<div class=\"headerPanelSmall-splitter headerPanelSmall\"><b>"); sb.Append(ForumUCResource.Topic); sb.Append(":</b></div>"); sb.Append("<div>"); sb.Append("<input class=\"textEdit\" style=\"width:100%;\" maxlength=\"450\" name=\"forum_subject\" id=\"forum_subject\" type=\"text\" value=\"" + HttpUtility.HtmlEncode(_subject) + "\" />"); sb.Append("</div>"); sb.Append("</div>"); Response.Write(sb.ToString()); } protected string RenderForumSelector() { if (!_isSelectForum) return ""; if (_threads == null) { ForumDataProvider.GetThreadCategories(TenantProvider.CurrentTenantID, out _categories, out _threads); _threads.RemoveAll(t => !t.Visible); } StringBuilder sb = new StringBuilder(); sb.Append("<div class=\"headerPanel-splitter\">"); sb.Append("<div class=\"headerPanelSmall-splitter\"><b>"); sb.Append(ForumUCResource.Thread); sb.Append(":</b></div>"); sb.Append("<div>"); sb.Append("<select name=\"forum_thread_id\" class=\"comboBox\" style='width:400px;'>"); var grouppedThread = _threads.GroupBy(t => t.CategoryID); foreach (var forumGroup in grouppedThread) { var category = _categories.FirstOrDefault(c => c.ID == forumGroup.Key); if (category != null) sb.Append("<optgroup label=\"" + category.Title + "\">"); foreach (var forum in forumGroup) { bool isAllow = false; if (PostType == NewPostType.Topic) isAllow = _forumManager.ValidateAccessSecurityAction(ForumAction.TopicCreate, forum); else if (PostType == NewPostType.Poll) isAllow = _forumManager.ValidateAccessSecurityAction(ForumAction.PollCreate, forum); if (isAllow) sb.Append("<option value=\"" + forum.ID + "\">" + forum.Title.HtmlEncode() + "</option>"); } if (category != null) sb.Append("</optgroup>"); } sb.Append("</select>"); sb.Append("</div>"); sb.Append("</div>"); return sb.ToString(); } private List<Tag> CreateTags(Thread thread) { if (string.IsNullOrEmpty(_tagString.Trim(',')) || !_forumManager.ValidateAccessSecurityAction(ForumAction.TagCreate, thread)) { return new List<Tag>(); } List<Tag> list; List<Tag> existingTags = ForumDataProvider.GetAllTags(TenantProvider.CurrentTenantID); var newTags = (from tagName in _tagString.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) where !existingTags.Exists(et => et.Name.Equals(tagName, StringComparison.InvariantCultureIgnoreCase)) select new Tag() { ID = 0, Name = tagName }).Distinct(new TagComparer()); var exTags = from exTag in existingTags from tagName in _tagString.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries) where tagName.Equals(exTag.Name, StringComparison.InvariantCultureIgnoreCase) select exTag; list = new List<Tag>(newTags.ToArray()); list.AddRange(exTags.ToArray()); return list; } protected void AddTags() { if (PostType != NewPostType.Topic && PostType != NewPostType.Poll) return; if (!_forumManager.ValidateAccessSecurityAction(ForumAction.TagCreate, Thread)) return; var sb = new StringBuilder(); sb.AppendLine("var ForumTagSearchHelper = new SearchHelper('forum_tags','forum_sh_item','forum_sh_itemselect','',\"ForumManager.SaveSearchTags(\'forum_search_tags\',ForumTagSearchHelper.SelectedItem.Value,ForumTagSearchHelper.SelectedItem.Help);\",\"TagSuggest\", \"GetSuggest\",\"'" + _settings.ID + "',\",true,false);"); Page.RegisterInlineScript(sb.ToString()); sb = new StringBuilder(); sb.Append("<div class=\"headerPanel-splitter\">"); sb.Append("<div class=\"headerPanelSmall-splitter\"><b>" + ForumUCResource.Tags + ":</b></div>"); sb.Append("<div>"); sb.Append("<input autocomplete=\"off\" class=\"textEdit\" style=\"width:100%\" type=\"text\" value=\"" + HttpUtility.HtmlEncode(_tagString) + "\" maxlength=\"3000\" id=\"forum_tags\" name=\"forum_tags\"/>"); sb.Append("<input type='hidden' id='forum_search_tags' name='forum_search_tags'/>"); sb.Append("</div>"); sb.Append("<div class=\"text-medium-describe\">" + ForumUCResource.HelpForTags + "</div>"); sb.Append("</div>"); Response.Write(sb.ToString()); } #region Attachments public bool IsAllowCreateAttachment { get { if (PostType == NewPostType.Post) return _forumManager.ValidateAccessSecurityAction(ForumAction.AttachmentCreate, Topic); else if (PostType == NewPostType.Poll || PostType == NewPostType.Topic) return _forumManager.ValidateAccessSecurityAction(ForumAction.AttachmentCreate, Thread); return false; } } private void CreateAttachments(Post post) { if (Attachments != null) { foreach (var attachItem in Attachments) { var attachment = new Attachment(); attachment.OffsetPhysicalPath = attachItem.offsetPhysicalPath; if (_forumManager.GetStore().IsFile(attachment.OffsetPhysicalPath) == false) continue; attachment.PostID = post.ID; attachment.Name = attachItem.fileName; attachment.Size = int.Parse(attachItem.size); attachment.MIMEContentType = attachItem.contentType; attachment.ID = ForumDataProvider.CreateAttachment(TenantProvider.CurrentTenantID, post.ID, attachment.Name, attachment.OffsetPhysicalPath, attachment.Size, attachment.ContentType, attachment.MIMEContentType); post.Attachments.Add(attachment); } } } #region Array Items Helper private static string GetNotNullArrayItem(string[] a, int index) { if (a == null || a.Length == 0) { return string.Empty; } return a.Length > index ? a[index] : string.Empty; } #endregion #endregion protected string RenderSubscription() { if (_subscribeViewType == SubscriveViewType.Disable) return ""; return "<input id='forum_topSubscriptionState' name='forum_topSubscription' value='" + (_subscribeViewType == SubscriveViewType.Checked ? "1" : "0") + "' type='hidden'/><input id=\"forum_topSubscription\" " + (_subscribeViewType == SubscriveViewType.Checked ? "checked='checked'" : "") + " type=\"checkbox\"/><label style='margin-left:5px; vertical-align: top;' for=\"forum_topSubscription\">" + ForumUCResource.SubscribeOnTopic + "</label>"; } [AjaxMethod(HttpSessionStateRequirement.ReadWrite)] public void RemoveAttachment(Guid settingsID, string offsetPath) { Community.Forum.ForumManager.Settings.ForumManager.RemoveAttachments(offsetPath); } #region INotifierView Members public event EventHandler<NotifyEventArgs> SendNotify; #endregion #region ISubscriberView Members public event EventHandler<SubscribeEventArgs> GetSubscriptionState; public bool IsSubscribe { get; set; } public event EventHandler<SubscribeEventArgs> Subscribe; public event EventHandler<SubscribeEventArgs> UnSubscribe; public event EventHandler<SubscribeEventArgs> UnSubscribeForSubscriptionType; #endregion protected string RenderRedirectUpload() { return string.Format("{0}://{1}:{2}{3}", Request.GetUrlRewriter().Scheme, Request.GetUrlRewriter().Host, Request.GetUrlRewriter().Port, VirtualPathUtility.ToAbsolute("~/") + "fckuploader.ashx?newEditor=true&esid=" + _settings.FileStoreModuleID + (PostAction == PostAction.Edit ? "&iid=" + EditedPost.ID.ToString() : "")); } protected void OnUnSubscribeForSubscriptionType(INotifyAction action, string objId, Guid userId) { if (UnSubscribeForSubscriptionType != null) UnSubscribeForSubscriptionType(this, new SubscribeEventArgs(action, objId, userId)); } [AjaxMethod(HttpSessionStateRequirement.ReadWrite)] public string CancelPost(Guid settingsID, string itemID) { var _settings = Community.Forum.ForumManager.Settings; if (String.IsNullOrEmpty(itemID) == false) CommonControlsConfigurer.FCKEditingCancel(_settings.FileStoreModuleID, itemID); else CommonControlsConfigurer.FCKEditingCancel(_settings.FileStoreModuleID); if (httpContext != null && httpContext.Request != null && httpContext.Request.UrlReferrer != null && !string.IsNullOrEmpty(httpContext.Request.UrlReferrer.Query)) { var q = httpContext.Request.UrlReferrer.Query; var start = q.IndexOf("t="); if (start == -1) start = q.IndexOf("f="); start += 2; var end = q.IndexOf("&", start, StringComparison.CurrentCultureIgnoreCase); if (end == -1) end = q.Length; var t = q.Substring(start, end - start); return (q.IndexOf("t=") > 0 ? _settings.PostPageAbsolutePath + "t=" : _settings.TopicPageAbsolutePath + "f=") + t; } else return _settings.StartPageAbsolutePath; } #region IContextInitializer Members public void InitializeContext(HttpContext context) { httpContext = context; } private HttpContext httpContext = null; #endregion } }
using System; using NUnit.Framework; using StructureMap.Configuration.DSL; using StructureMap.Diagnostics; using StructureMap.Graph; using StructureMap.Pipeline; using StructureMap.Testing.Configuration.DSL; using StructureMap.Testing.Widget; namespace StructureMap.Testing.Diagnostics { [TestFixture] public class ValidationBuildSessionTester : Registry { private ValidationBuildSession validatedSession(Action<Registry> action) { var registry = new Registry(); action(registry); PluginGraph graph = registry.Build(); var session = ValidationBuildSession.ValidateForPluginGraph(graph); session.PerformValidations(); return session; } private BuildError getFirstAndOnlyError(ValidationBuildSession session) { Assert.AreEqual(1, session.BuildErrors.Length); return session.BuildErrors[0]; } private LambdaInstance<IWidget> errorInstance() { return new LambdaInstance<IWidget>(delegate() { throw new NotSupportedException("You can't make me!"); }); } [Test] public void Attach_dependency_to_the_build_error_but_do_not_create_new_error_for_dependency() { ValidationBuildSession session = validatedSession(r => { r.For<IWidget>().Use(errorInstance().Named("BadInstance")); r.For<SomethingThatNeedsAWidget>().Use<SomethingThatNeedsAWidget>() .Named("DependentInstance") .Ctor<IWidget>().Is(x => x.TheInstanceNamed("BadInstance")); }); BuildError error = getFirstAndOnlyError(session); Assert.AreEqual(1, error.Dependencies.Count); BuildDependency dependency = error.Dependencies[0]; Assert.AreEqual(typeof (SomethingThatNeedsAWidget), dependency.PluginType); Assert.AreEqual("DependentInstance", dependency.Instance.Name); } [Test] public void Create_an_instance_for_the_first_time_happy_path() { ValidationBuildSession session = validatedSession( r => r.For<IWidget>().Use(new ColorWidget("Red"))); Assert.AreEqual(0, session.BuildErrors.Length); } [Test] public void Create_an_instance_that_fails_and_an_instance_that_depends_on_that_exception() { ValidationBuildSession session = validatedSession(r => { r.For<IWidget>().Use(errorInstance().Named("BadInstance")); r.For<SomethingThatNeedsAWidget>().Use<SomethingThatNeedsAWidget>() .Named("DependentInstance") .Ctor<IWidget>().Is(x => x.TheInstanceNamed("BadInstance")); }); Assert.AreEqual(1, session.BuildErrors.Length); BuildError error = session.Find(typeof (SomethingThatNeedsAWidget), "DependentInstance"); Assert.IsNull(error); BuildError error2 = session.Find(typeof (IWidget), "BadInstance"); Assert.IsNotNull(error2); } [Test] public void Create_an_instance_that_fails_because_of_an_inline_child() { ValidationBuildSession session = validatedSession( r => { r.For<SomethingThatNeedsAWidget>().Use<SomethingThatNeedsAWidget>() .Named("BadInstance") .Ctor<IWidget>().Is(errorInstance()); }); BuildError error = getFirstAndOnlyError(session); Assert.AreEqual("BadInstance", error.Instance.Name); Assert.AreEqual(typeof (SomethingThatNeedsAWidget), error.PluginType); } [Test] public void Create_an_instance_that_has_a_build_failure() { Instance instance = errorInstance().Named("Bad"); ValidationBuildSession session = validatedSession(registry => registry.For<IWidget>().Use(instance)); BuildError error = getFirstAndOnlyError(session); Assert.AreEqual(instance, error.Instance); Assert.AreEqual(typeof (IWidget), error.PluginType); Assert.IsNotNull(error.Exception); } [Test] public void do_not_fail_with_the_bidirectional_checks() { var container = new Container(r => { r.For<IWidget>().Use<ColorWidget>().Ctor<string>("color").Is("red"); r.For<Rule>().Use<WidgetRule>(); r.ForConcreteType<ClassThatNeedsWidgetAndRule1>(); r.ForConcreteType<ClassThatNeedsWidgetAndRule2>(); r.For<ClassThatNeedsWidgetAndRule2>().Use<ClassThatNeedsWidgetAndRule2>(); r.For<ClassThatNeedsWidgetAndRule2>().Use<ClassThatNeedsWidgetAndRule2>(); r.For<ClassThatNeedsWidgetAndRule2>().Use<ClassThatNeedsWidgetAndRule2>(); r.For<ClassThatNeedsWidgetAndRule2>().Use<ClassThatNeedsWidgetAndRule2>(). Ctor<Rule>().Is<ARule>(); }); container.AssertConfigurationIsValid(); } [Test] public void Happy_path_with_no_validation_errors() { ValidationBuildSession session = validatedSession( registry => registry.For<IWidget>().Use(new ColorWidget("Red"))); Assert.AreEqual(0, session.ValidationErrors.Length); } [Test] public void Request_an_instance_for_the_second_time_successfully_and_get_the_same_object() { var session = ValidationBuildSession.ValidateForPluginGraph(new PluginGraph()); var instance = new ObjectInstance(new ColorWidget("Red")); object widget1 = session.FindObject(typeof (IWidget), instance); object widget2 = session.FindObject(typeof (IWidget), instance); Assert.AreSame(widget1, widget2); } [Test] public void Successfully_build_an_object_that_has_multiple_validation_errors() { ValidationBuildSession session = validatedSession( registry => registry.For<SomethingThatHasValidationFailures>().Use<SomethingThatHasValidationFailures>()); Assert.AreEqual(2, session.ValidationErrors.Length); } [Test] public void Validate_a_single_object_with_both_a_passing_validation_method_and_a_failing_validation_method() { var instance = new ObjectInstance(new WidgetWithOneValidationFailure()); ValidationBuildSession session = validatedSession(registry => registry.For<IWidget>().Use(instance)); Assert.AreEqual(1, session.ValidationErrors.Length); ValidationError error = session.ValidationErrors[0]; Assert.AreEqual(typeof(IWidget), error.PluginType); Assert.AreEqual(instance, error.Instance); Assert.AreEqual("ValidateFailure", error.MethodName); error.Exception.ShouldBeOfType<NotImplementedException>(); } } public class ClassThatNeedsWidgetAndRule1 { public ClassThatNeedsWidgetAndRule1(IWidget widget, Rule rule) { } } public class ClassThatNeedsWidgetAndRule2 { public ClassThatNeedsWidgetAndRule2(IWidget widget, Rule rule, ClassThatNeedsWidgetAndRule1 class1) { } } public class WidgetWithOneValidationFailure : IWidget { #region IWidget Members public void DoSomething() { throw new NotImplementedException(); } #endregion [ValidationMethod] public void ValidateSuccess() { // everything is wonderful } [ValidationMethod] public void ValidateFailure() { throw new NotImplementedException("I'm not ready"); } } public class SomethingThatHasValidationFailures { [ValidationMethod] public void Validate1() { throw new NotSupportedException("You can't make me"); } [ValidationMethod] public void Validate2() { throw new NotImplementedException("Not ready yet"); } } public class SomethingThatNeedsAWidget { public SomethingThatNeedsAWidget(IWidget widget) { } } }
using System; using System.IO; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using Zeus; using Zeus.UserInterface; using Zeus.UserInterface.WinForms; using MyMeta; namespace MyGeneration.TemplateForms { /// <summary> /// Summary description for TemplateBrowser. /// </summary> public class TemplateBrowser : BaseWindow { private System.Windows.Forms.ToolBar toolBarToolbar; private System.Windows.Forms.ToolBarButton toolBarButtonOpen; private System.Windows.Forms.ToolBarButton toolBarSeparator2; private System.Windows.Forms.ToolBarButton toolBarButtonExecute; private System.Windows.Forms.ImageList imageListFormIcons; private System.Windows.Forms.TreeView treeViewTemplates; private System.Windows.Forms.ToolBarButton toolBarButtonRefresh; private System.Windows.Forms.ToolTip toolTipTemplateBrowser; private System.Windows.Forms.ToolBarButton toolBarButtonMode; private System.ComponentModel.IContainer components; public TemplateBrowser() { // // Required for Windows Form Designer support // InitializeComponent(); treeViewTemplates.MouseDown += new System.Windows.Forms.MouseEventHandler(this.treeViewTemplates_MouseDown); treeViewTemplates.DoubleClick += new System.EventHandler(this.treeViewTemplates_OnDoubleClick); treeViewTemplates.AfterExpand += new TreeViewEventHandler(this.treeViewTemplates_AfterExpand); treeViewTemplates.AfterCollapse += new TreeViewEventHandler(this.treeViewTemplates_AfterCollapse); treeViewTemplates.KeyDown += new KeyEventHandler(this.treeViewTemplates_KeyDown); treeViewTemplates.MouseMove += new MouseEventHandler(treeViewTemplates_MouseMove); LoadTemplates(); //LoadTemplatesByFile(); } public event EventHandler TemplateOpen; protected void OnTemplateOpen(string path) { if (this.TemplateOpen != null) { this.TemplateOpen(path, new EventArgs()); } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Load Templates By Namespace private void LoadTemplates() { this.treeViewTemplates.Nodes.Clear(); DefaultSettings settings = new DefaultSettings(); string defaultTemplatePath = settings.DefaultTemplateDirectory; string exePath = Directory.GetCurrentDirectory(); if (!Directory.Exists(defaultTemplatePath)) { defaultTemplatePath = exePath; } ArrayList templates = new ArrayList(); DirectoryInfo rootInfo = new DirectoryInfo(defaultTemplatePath); buildChildren(rootInfo, templates); RootTreeNode rootNode = new RootTreeNode("Zeus Templates by Namespace"); this.treeViewTemplates.Nodes.Add(rootNode); foreach (ZeusTemplate template in templates) { if (template.NamespacePathString.Trim() == string.Empty) { rootNode.AddSorted(new TemplateTreeNode(template)); } else { SortedTreeNode parentNode = rootNode; foreach (string ns in template.NamespacePath) { bool isFound = false; foreach (SortedTreeNode tmpNode in parentNode.Nodes) { if (tmpNode.Text == ns) { parentNode = tmpNode; isFound = true; break; } } if (!isFound) { FolderTreeNode ftn = new FolderTreeNode(ns); parentNode.AddSorted(ftn); parentNode = ftn; } } parentNode.AddSorted(new TemplateTreeNode(template)); } } rootNode.Expand(); } protected void buildChildren(DirectoryInfo rootInfo, ArrayList templates) { ZeusTemplate template; foreach (DirectoryInfo dirInfo in rootInfo.GetDirectories()) { this.buildChildren(dirInfo, templates); } foreach (FileInfo fileInfo in rootInfo.GetFiles()) { if ( (fileInfo.Extension == ".jgen") || (fileInfo.Extension == ".vbgen") || (fileInfo.Extension == ".csgen") || (fileInfo.Extension == ".zeus") ) { string filename = fileInfo.FullName; if (!templates.Contains(filename)) { try { template = new ZeusTemplate(filename); } catch { continue; } templates.Add(template); } } } } #endregion #region Load Templates By File private void LoadTemplatesByFile() { this.treeViewTemplates.Nodes.Clear(); DefaultSettings settings = new DefaultSettings(); string defaultTemplatePath = settings.DefaultTemplateDirectory; string exePath = Directory.GetCurrentDirectory(); if (!Directory.Exists(defaultTemplatePath)) { defaultTemplatePath = exePath; } ArrayList templates = new ArrayList(); DirectoryInfo rootInfo = new DirectoryInfo(defaultTemplatePath); RootTreeNode rootNode = new RootTreeNode("Zeus Templates by File"); this.treeViewTemplates.Nodes.Add(rootNode); buildChildren(rootNode, rootInfo); rootNode.Expand(); } protected void buildChildren(SortedTreeNode rootNode, DirectoryInfo rootInfo) { ZeusTemplate template; foreach (DirectoryInfo dirInfo in rootInfo.GetDirectories()) { FolderTreeNode node = new FolderTreeNode(dirInfo.Name); rootNode.AddSorted(node); this.buildChildren(node, dirInfo); } foreach (FileInfo fileInfo in rootInfo.GetFiles()) { if ( (fileInfo.Extension == ".jgen") || (fileInfo.Extension == ".vbgen") || (fileInfo.Extension == ".csgen") || (fileInfo.Extension == ".zeus") ) { string filename = fileInfo.FullName; try { template = new ZeusTemplate(filename); } catch { continue; } TemplateTreeNode node = new TemplateTreeNode(template, true); rootNode.AddSorted(node); } } } #endregion private void treeViewTemplates_AfterExpand(object sender, System.Windows.Forms.TreeViewEventArgs e) { if (e.Node is FolderTreeNode) { e.Node.SelectedImageIndex += 1; e.Node.ImageIndex += 1; } } private void treeViewTemplates_AfterCollapse(object sender, System.Windows.Forms.TreeViewEventArgs e) { if (e.Node is FolderTreeNode) { e.Node.SelectedImageIndex -= 1; e.Node.ImageIndex -= 1; } } private void treeViewTemplates_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { TreeNode node = (TreeNode)treeViewTemplates.GetNodeAt(e.X, e.Y); treeViewTemplates.SelectedNode = node; } private void treeViewTemplates_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.F5) { this.LoadTemplates(); return; } } private void treeViewTemplates_OnDoubleClick(object sender, System.EventArgs e) { if (this.treeViewTemplates.SelectedNode is TemplateTreeNode) { OnTemplateOpen( this.treeViewTemplates.SelectedNode.Tag.ToString() ); } } private void treeViewTemplates_MouseMove(object sender, MouseEventArgs e) { object obj = treeViewTemplates.GetNodeAt(e.X, e.Y); if (obj is TemplateTreeNode) { this.toolTipTemplateBrowser.SetToolTip(treeViewTemplates, ((TemplateTreeNode)obj).Comments); } else if ((obj is RootTreeNode) && (DateTime.Now.Hour == 1)) { this.toolTipTemplateBrowser.SetToolTip(treeViewTemplates, "Worship me as I generate your code."); } else { this.toolTipTemplateBrowser.SetToolTip(treeViewTemplates, string.Empty); } } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(TemplateBrowser)); this.toolBarToolbar = new System.Windows.Forms.ToolBar(); this.toolBarButtonRefresh = new System.Windows.Forms.ToolBarButton(); this.toolBarButtonMode = new System.Windows.Forms.ToolBarButton(); this.toolBarSeparator2 = new System.Windows.Forms.ToolBarButton(); this.toolBarButtonOpen = new System.Windows.Forms.ToolBarButton(); this.toolBarButtonExecute = new System.Windows.Forms.ToolBarButton(); this.imageListFormIcons = new System.Windows.Forms.ImageList(this.components); this.treeViewTemplates = new System.Windows.Forms.TreeView(); this.toolTipTemplateBrowser = new System.Windows.Forms.ToolTip(this.components); this.SuspendLayout(); // // toolBarToolbar // this.toolBarToolbar.Appearance = System.Windows.Forms.ToolBarAppearance.Flat; this.toolBarToolbar.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] { this.toolBarButtonRefresh, this.toolBarButtonMode, this.toolBarSeparator2, this.toolBarButtonOpen, this.toolBarButtonExecute}); this.toolBarToolbar.DropDownArrows = true; this.toolBarToolbar.ImageList = this.imageListFormIcons; this.toolBarToolbar.Location = new System.Drawing.Point(0, 0); this.toolBarToolbar.Name = "toolBarToolbar"; this.toolBarToolbar.ShowToolTips = true; this.toolBarToolbar.Size = new System.Drawing.Size(384, 28); this.toolBarToolbar.TabIndex = 0; this.toolBarToolbar.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBarToolbar_ButtonClick); // // toolBarButtonRefresh // this.toolBarButtonRefresh.ImageIndex = 2; this.toolBarButtonRefresh.ToolTipText = "Refresh Template Browser"; // // toolBarButtonMode // this.toolBarButtonMode.ImageIndex = 7; this.toolBarButtonMode.Style = System.Windows.Forms.ToolBarButtonStyle.ToggleButton; this.toolBarButtonMode.ToolTipText = "Browse Mode"; // // toolBarSeparator2 // this.toolBarSeparator2.Style = System.Windows.Forms.ToolBarButtonStyle.Separator; // // toolBarButtonOpen // this.toolBarButtonOpen.ImageIndex = 0; this.toolBarButtonOpen.ToolTipText = "Open Template"; // // toolBarButtonExecute // this.toolBarButtonExecute.ImageIndex = 1; this.toolBarButtonExecute.ToolTipText = "Execute Template"; // // imageListFormIcons // this.imageListFormIcons.ImageSize = new System.Drawing.Size(16, 16); this.imageListFormIcons.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageListFormIcons.ImageStream"))); this.imageListFormIcons.TransparentColor = System.Drawing.Color.Fuchsia; // // treeViewTemplates // this.treeViewTemplates.Dock = System.Windows.Forms.DockStyle.Fill; this.treeViewTemplates.ImageList = this.imageListFormIcons; this.treeViewTemplates.Location = new System.Drawing.Point(0, 28); this.treeViewTemplates.Name = "treeViewTemplates"; this.treeViewTemplates.Size = new System.Drawing.Size(384, 514); this.treeViewTemplates.TabIndex = 1; // // TemplateBrowser // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(384, 542); this.ControlBox = false; this.Controls.Add(this.treeViewTemplates); this.Controls.Add(this.toolBarToolbar); this.HideOnClose = true; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "TemplateBrowser"; this.ShowHint = WeifenLuo.WinFormsUI.DockState.DockLeft; this.Text = "Template Browser"; this.ResumeLayout(false); } #endregion private void toolBarToolbar_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e) { if ((e.Button == this.toolBarButtonRefresh) || (e.Button == this.toolBarButtonMode)) { if (this.toolBarButtonMode.Pushed) this.LoadTemplatesByFile(); else this.LoadTemplates(); } else if (e.Button == this.toolBarButtonOpen) { if (this.treeViewTemplates.SelectedNode is TemplateTreeNode) { OnTemplateOpen( this.treeViewTemplates.SelectedNode.Tag.ToString() ); } } else if (e.Button == this.toolBarButtonExecute) { if (this.treeViewTemplates.SelectedNode is TemplateTreeNode) { ZeusTemplate template = new ZeusTemplate(this.treeViewTemplates.SelectedNode.Tag.ToString()); ExecuteTemplate(template); } } } public void ExecuteTemplate(ZeusTemplate template) { this.Cursor = Cursors.WaitCursor; DefaultSettings settings = new DefaultSettings(); ZeusInput zin = new ZeusInput(); ZeusOutput zout = new ZeusOutput(); Hashtable objects = new Hashtable(); ZeusGuiContext guicontext; ZeusTemplateContext bodycontext = null; dbRoot myMeta = new dbRoot(); // Set the global variables for the default template/output paths zin["defaultTemplatePath"] = settings.DefaultTemplateDirectory; zin["defaultOutputPath"] = settings.DefaultOutputDirectory; string driver, connectionString; //if there is a connection string set, it in the input section here. if (settings.DbDriver != string.Empty) { driver = settings.DbDriver; connectionString = settings.ConnectionString; zin["dbDriver"] = driver; zin["dbConnectionString"] = connectionString; try { // Try to connect to the DB with MyMeta (using default connection info) myMeta.Connect(settings.DbDriver, settings.ConnectionString); // Set DB global variables and also input variables if (settings.DbTarget != string.Empty) myMeta.DbTarget = settings.DbTarget; if (settings.DbTargetMappingFile != string.Empty) myMeta.DbTargetMappingFileName = settings.DbTargetMappingFile; if (settings.LanguageMappingFile != string.Empty) myMeta.LanguageMappingFileName = settings.LanguageMappingFile; if (settings.DbTarget != string.Empty) myMeta.DbTarget = settings.DbTarget; if (settings.Language != string.Empty) myMeta.Language = settings.Language; if (settings.UserMetaDataFileName != string.Empty) myMeta.UserMetaDataFileName = settings.UserMetaDataFileName; } catch { // Give them an empty MyMeta myMeta = new dbRoot(); } } bool exceptionOccurred = false; bool result = false; try { // Add any objects here that need to be embedded in the script. objects.Add("MyMeta", myMeta); guicontext = new ZeusGuiContext(zin, new GuiController(), objects); template.GuiSegment.ZeusScriptingEngine.Executioner.ScriptTimeout = settings.ScriptTimeout; template.GuiSegment.ZeusScriptingEngine.Executioner.SetShowGuiHandler(new ShowGUIEventHandler(DynamicGUI_Display)); result = template.GuiSegment.Execute(guicontext); if (result) { bodycontext = new ZeusTemplateContext(guicontext); result = template.BodySegment.Execute(bodycontext); } } catch (Exception ex) { ZeusDisplayError formError = new ZeusDisplayError(ex); formError.SetControlsFromException(); formError.ShowDialog(this); exceptionOccurred = true; } if (!exceptionOccurred && result) { MessageBox.Show("Successfully rendered template: " + template.Title); } this.Cursor = Cursors.Default; } public void DynamicGUI_Display(GuiController gui, IZeusFunctionExecutioner executioner) { this.Cursor = Cursors.Default; try { DynamicForm df = new DynamicForm(gui, executioner); DialogResult result = df.ShowDialog(this); if(result == DialogResult.Cancel) { gui.IsCanceled = true; } } catch (Exception ex) { ZeusDisplayError formError = new ZeusDisplayError(ex); formError.SetControlsFromException(); formError.ShowDialog(this); } this.Cursor = Cursors.WaitCursor; } } public abstract class SortedTreeNode : TreeNode { public int AddSorted(TreeNode newnode) { int insertIndex = -1; for (int i = 0; i < this.Nodes.Count; i++) { TreeNode node = this.Nodes[i]; if (node.GetType() == newnode.GetType()) { if (newnode.Text.CompareTo(node.Text) <= 0) { insertIndex = i; break; } } else if (newnode is TemplateTreeNode) { continue; } else { insertIndex = i; break; } } if (insertIndex == -1) { insertIndex = this.Nodes.Add(newnode); } else { this.Nodes.Insert(insertIndex, newnode); } return insertIndex; } } public class RootTreeNode : SortedTreeNode { public RootTreeNode(string title) { //this.NodeFont = new System.Drawing.Font(FontFamily.GenericSansSerif, 8, FontStyle.Regular, GraphicsUnit.Point); this.Text = title; this.ImageIndex = this.SelectedImageIndex = 5; } } public class FolderTreeNode : SortedTreeNode { public FolderTreeNode(string text) { //this.NodeFont = new System.Drawing.Font(FontFamily.GenericSansSerif, 8, FontStyle.Regular, GraphicsUnit.Point); this.Text = text; this.ImageIndex = this.SelectedImageIndex = 3; } } public class TemplateTreeNode : SortedTreeNode { public string Comments = string.Empty; public TemplateTreeNode(ZeusTemplate template, bool usePathAsTitle) { //this.NodeFont = new System.Drawing.Font(FontFamily.GenericSansSerif, 8, FontStyle.Bold, GraphicsUnit.Point); this.ForeColor = Color.Blue; if (usePathAsTitle) this.Text = template.FileName; else this.Text = template.Title; this.Tag = template.FilePath + template.FileName; this.Comments = template.Comments; this.ImageIndex = this.SelectedImageIndex = 6; } public TemplateTreeNode(ZeusTemplate template) { //this.NodeFont = new System.Drawing.Font(FontFamily.GenericSansSerif, 8, FontStyle.Bold, GraphicsUnit.Point); this.ForeColor = Color.Blue; this.Text = template.Title; this.Tag = template.FilePath + template.FileName; this.Comments = template.Comments; this.ImageIndex = this.SelectedImageIndex = 6; } } }
using System; using System.Linq; using System.Drawing; using System.Collections.Generic; using System.Text; using MonoTouch.UIKit; using MonoTouch.Foundation; using System.Threading.Tasks; using MonoTouch.CoreAnimation; namespace XamarinStore.iOS { public class ProductListViewController : UITableViewController { const int ProductCellRowHeight = 300; static float ImageWidth = UIScreen.MainScreen.Bounds.Width * UIScreen.MainScreen.Scale; public event Action<Product> ProductTapped = delegate {}; ProductListViewSource source; Random random; public ProductListViewController () { Title = "Xamarin Store"; // Hide the back button text when you leave this View Controller. NavigationItem.BackBarButtonItem = new UIBarButtonItem ("", UIBarButtonItemStyle.Plain, handler: null); TableView.SeparatorStyle = UITableViewCellSeparatorStyle.None; TableView.RowHeight = ProductCellRowHeight; TableView.Source = source = new ProductListViewSource ( products => { ProductTapped (products); }, product=> { SurpriseProductSelected(product); }); random = new Random (); GetData (); } async void GetData () { source.Products = await WebService.Shared.GetProducts (); //Kicking off a task no need to await #pragma warning disable 4014 WebService.Shared.PreloadImages (320 * UIScreen.MainScreen.Scale); #pragma warning restore 4014 TableView.ReloadData (); } public override void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); NavigationItem.RightBarButtonItem = AppDelegate.Shared.CreateBasketButton (); } public void SurpriseProductSelected(Product surprise) { surprise.Color = surprise.Colors [random.Next(0, surprise.Colors.Count())]; // pick a random colour surprise.Size = surprise.Sizes [random.Next (0, surprise.Sizes.Count())]; // pick a random size WebService.Shared.CurrentOrder.Add (surprise.AsSurpriseProduct()); AppDelegate.Shared.UpdateProductsCount(); new UIAlertView ("Congratulations!", String.Format ("Your surprise will be displayed in your shopping basket under the name '{0}'", SurpriseProduct.SurpriseProductName), null, "Cool!", null).Show (); } class ProductListViewSource : UITableViewSource { readonly Action<Product> ProductSelected; readonly Action<Product> SurpriseProductSelected; Random random; UIAlertView alertView; public IReadOnlyList<Product> Products; public ProductListViewSource (Action<Product> productSelected, Action<Product> surpriseProductSelected) { ProductSelected = productSelected; SurpriseProductSelected = surpriseProductSelected; random = new Random(); } public override float GetHeightForRow (UITableView tableView, NSIndexPath indexPath) { if (indexPath.Section == 1) return 190; else return ProductCellRowHeight; } public override int NumberOfSections(UITableView tableView) { return (Products == null || Products.Count == 0) ? 1 : 2; } public override int RowsInSection (UITableView tableview, int section) { if (Products == null) return 1; else return (section == 0 ? Products.Count : 1); } public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { if (Products == null) return; switch (indexPath.Section) { case 0: // selected a product, continue normally ProductSelected(Products[indexPath.Row]); break; case 1: var onSuccess = new Action(() => { var eligibleProducts = Products .Where(p=> p.Price < 0.01) .ToList(); var surprise = eligibleProducts [random.Next (0, eligibleProducts.Count ())]; // pick a random product SurpriseProductSelected (surprise); }); this.alertView = new UIAlertView ("Are you sure?", "There's no knowing what colour and size it will be, nor which gender it will suit!\n\n(It may not even be a shirt...)", new SurpriseAlertViewDelegate(onSuccess), "Hm, I'd better not..", new [] { "I'm feeling lucky!" } ); this.alertView.Show (); break; } } public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { if (Products == null) { return new SpinnerCell (); } UITableViewCell cell = null; switch (indexPath.Section) { case 0: // normal cell cell = tableView.DequeueReusableCell(ProductListCell.CellId) as ProductListCell ?? new ProductListCell(); ((ProductListCell) cell).Product = Products[indexPath.Row]; return cell; case 1: cell = tableView.DequeueReusableCell (SurpriseMeListCell.CellId) as SurpriseMeListCell ?? new SurpriseMeListCell (); var typedCell = cell as SurpriseMeListCell; typedCell.NameLabel.Text = "Surprise Me!"; typedCell.PriceLabel.Text = "free"; return cell; } return cell; } class SurpriseAlertViewDelegate : UIAlertViewDelegate { readonly Action onSuccess; public SurpriseAlertViewDelegate(Action successAction) : base() { this.onSuccess = successAction; } public override void Clicked (UIAlertView alertview, int buttonIndex) { if (buttonIndex == 1) onSuccess (); } } } class SurpriseCellBGView : UIView { public override void Draw(RectangleF rect) { XamStoreStyleKit.DrawCellProto (rect.Size.Height, rect.Size.Width); } } class SurpriseMeListCell : UITableViewCell { public const string CellId = "SurpriseMeListCell"; static readonly SizeF PriceLabelPadding = new SizeF (16, 6); Product product; SurpriseCellBGView imageView; public UILabel NameLabel, PriceLabel; UIImageView shirtsImageView; public SurpriseMeListCell() { SelectionStyle = UITableViewCellSelectionStyle.None; ContentView.BackgroundColor = UIColor.LightGray; imageView = new SurpriseCellBGView { ClipsToBounds = true, }; shirtsImageView = new UIImageView { Image = UIImage.FromFile("allShirts.png"), BackgroundColor = UIColor.Clear, ContentMode = UIViewContentMode.ScaleAspectFill }; NameLabel = new UILabel { TextColor = UIColor.White, TextAlignment = UITextAlignment.Left, Font = UIFont.FromName ("HelveticaNeue-Light", 22), //ShadowColor = UIColor.DarkGray, //ShadowOffset = new System.Drawing.SizeF(.5f,.5f), Layer = { ShadowRadius = 3, ShadowColor = UIColor.Black.CGColor, ShadowOffset = new System.Drawing.SizeF(0,1f), ShadowOpacity = .5f, } }; PriceLabel = new UILabel { Alpha = 0.95f, TextColor = UIColor.White, BackgroundColor = Color.Green, TextAlignment = UITextAlignment.Center, Font = UIFont.FromName ("HelveticaNeue", 16), ShadowColor = UIColor.LightGray, ShadowOffset = new SizeF(.5f, .5f), }; var layer = PriceLabel.Layer; layer.CornerRadius = 3; ContentView.AddSubview (imageView); ContentView.AddSubview(shirtsImageView); ContentView.AddSubviews (NameLabel, PriceLabel); } public override void LayoutSubviews () { base.LayoutSubviews (); var bounds = ContentView.Bounds; imageView.Frame = bounds; NameLabel.Frame = new RectangleF ( bounds.X + 12, bounds.Bottom - 58, bounds.Width, 55 ); var priceSize = ((NSString)"free").StringSize (PriceLabel.Font); PriceLabel.Frame = new RectangleF ( bounds.Width - priceSize.Width - 2 * PriceLabelPadding.Width - 12, bounds.Bottom - priceSize.Height - 2 * PriceLabelPadding.Height - 14, priceSize.Width + 2 * PriceLabelPadding.Width, priceSize.Height + 2 * PriceLabelPadding.Height ); shirtsImageView.Frame = new RectangleF (bounds.X + 10, bounds.Y + 12, bounds.Width - 20, bounds.Height - 50); } } class ProductListCell : UITableViewCell { public const string CellId = "ProductListCell"; static readonly SizeF PriceLabelPadding = new SizeF (16, 6); Product product; TopAlignedImageView imageView; UILabel nameLabel, priceLabel; public Product Product { get { return product; } set { product = value; nameLabel.Text = product.Name; priceLabel.Text = product.PriceDescription.ToLower (); updateImage (); } } void updateImage() { var url = product.ImageForSize (ImageWidth); imageView.LoadUrl (url); } public ProductListCell () { SelectionStyle = UITableViewCellSelectionStyle.None; ContentView.BackgroundColor = UIColor.LightGray; imageView = new TopAlignedImageView { ClipsToBounds = true, }; nameLabel = new UILabel { TextColor = UIColor.White, TextAlignment = UITextAlignment.Left, Font = UIFont.FromName ("HelveticaNeue-Light", 22), //ShadowColor = UIColor.DarkGray, //ShadowOffset = new System.Drawing.SizeF(.5f,.5f), Layer = { ShadowRadius = 3, ShadowColor = UIColor.Black.CGColor, ShadowOffset = new System.Drawing.SizeF(0,1f), ShadowOpacity = .5f, } }; priceLabel = new UILabel { Alpha = 0.95f, TextColor = UIColor.White, BackgroundColor = Color.Green, TextAlignment = UITextAlignment.Center, Font = UIFont.FromName ("HelveticaNeue", 16), ShadowColor = UIColor.LightGray, ShadowOffset = new SizeF(.5f, .5f), }; var layer = priceLabel.Layer; layer.CornerRadius = 3; ContentView.AddSubviews (imageView, nameLabel, priceLabel); } public override void LayoutSubviews () { base.LayoutSubviews (); var bounds = ContentView.Bounds; imageView.Frame = bounds; nameLabel.Frame = new RectangleF ( bounds.X + 12, bounds.Bottom - 58, bounds.Width, 55 ); var priceSize = ((NSString)Product.PriceDescription).StringSize (priceLabel.Font); priceLabel.Frame = new RectangleF ( bounds.Width - priceSize.Width - 2 * PriceLabelPadding.Width - 12, bounds.Bottom - priceSize.Height - 2 * PriceLabelPadding.Height - 14, priceSize.Width + 2 * PriceLabelPadding.Width, priceSize.Height + 2 * PriceLabelPadding.Height ); } } } }
using System; using System.IO; using System.Text; using System.Collections; namespace LumiSoft.Net.Mime { /// <summary> /// Simple Mime constructor. /// Use this class if you need to construct simple email messages, use Mime class insted if you need to create complex messages. /// </summary> /// <example> /// <code> /// MimeConstructor m = new MimeConstructor(); /// m.From = new Mailbox("display name","sender@domain.com"); /// m.To = new Mailbox[]{new Mailbox("display name","to@domain.com")}; /// m.Subject = "test subject"; /// m.Text = "Test text"; /// /// // Get mime data /// // byte[] mimeData = m.ToByteData(); /// // or m.ToStream(storeStream) /// // or m.ToFile(fileName) /// </code> /// </example> [Obsolete("This class is will be removed, use Mime class instead.")] public class MimeConstructor { private HeaderFieldCollection m_pHeader = null; private string m_Body = ""; private string m_BodyHtml = ""; private string m_CharSet = ""; private Attachments m_pAttachments = null; /// <summary> /// Default constructor. /// </summary> public MimeConstructor() { m_pHeader = new HeaderFieldCollection(); m_pHeader.Add("From:",""); m_pHeader.Add("To:",""); m_pHeader.Add("Subject:",""); m_pHeader.Add("Date:",DateTime.Now.ToUniversalTime().ToString("r",System.Globalization.DateTimeFormatInfo.InvariantInfo)); m_pHeader.Add("Message-ID:","<" + Guid.NewGuid().ToString().Replace("-","") + "@" + System.Net.Dns.GetHostName() + ">"); m_pHeader.Add("MIME-Version:","1.0"); m_pAttachments = new Attachments(); m_CharSet = "utf-8"; } // REMOVE ME: obsolete #region method ConstructBinaryMime /// <summary> /// Constructs mime message. [obsolete] /// </summary> /// <returns></returns> [Obsolete("Use ToStream(storeStream) instead ! Warning: stream position in ToStream isn't set to 0 any more",true)] public MemoryStream ConstructBinaryMime() { MemoryStream ms = new MemoryStream(); ToStream(ms); ms.Position = 0; return ms; } #endregion // REMOVE ME: obsolete #region method ConstructMime /// <summary> /// Constructs mime message. [obsolete] /// </summary> /// <returns></returns> [Obsolete("Use ToStringData() instead",true)] public string ConstructMime() { return System.Text.Encoding.Default.GetString(ConstructBinaryMime().ToArray()); } #endregion #region function ConstructBody private string ConstructBody(string boundaryID) { // TODO: encode text as quoted-printable StringBuilder str = new StringBuilder(); str.Append("--" + boundaryID + "\r\n"); str.Append("Content-Type: text/plain;\r\n"); str.Append("\tcharset=\"" + m_CharSet + "\"\r\n"); str.Append("Content-Transfer-Encoding: base64\r\n\r\n"); str.Append(SplitString(Convert.ToBase64String(System.Text.Encoding.GetEncoding(m_CharSet).GetBytes(this.Body)) + "\r\n\r\n")); // We have html body, construct it. if(this.BodyHtml.Length > 0){ str.Append("--" + boundaryID + "\r\n"); str.Append("Content-Type: text/html;\r\n"); str.Append("\tcharset=\"" + m_CharSet + "\"\r\n"); str.Append("Content-Transfer-Encoding: base64\r\n\r\n"); str.Append(SplitString(Convert.ToBase64String(System.Text.Encoding.GetEncoding(m_CharSet).GetBytes(this.BodyHtml)))); } return str.ToString(); } #endregion //** Make some global method #region method AddressesToString /// <summary> /// Converts address array to RFC 2822 address field fomat. /// </summary> /// <param name="addresses"></param> /// <returns></returns> private string AddressesToString(MailboxAddress[] addresses) { string retVal = ""; for(int i=0;i<addresses.Length;i++){ // For last address don't add , and <TAB> if(i == (addresses.Length - 1)){ retVal += addresses[i].MailboxString; } else{ retVal += addresses[i].MailboxString + ",\t"; } } return retVal; } #endregion //** Make some global method #region method AddressesToArray /// <summary> /// Converts RFC 2822 address filed value to address array. /// </summary> /// <param name="addressFieldValue"></param> /// <returns></returns> private MailboxAddress[] AddressesToArray(string addressFieldValue) { // We need to parse right !!! // Can't use standard String.Split() because commas in quoted strings must be skiped. // Example: "ivar, test" <ivar@lumisoft.ee>,"xxx" <ivar2@lumisoft.ee> string[] retVal = TextUtils.SplitQuotedString(addressFieldValue,','); MailboxAddress[] xxx = new MailboxAddress[retVal.Length]; for(int i=0;i<retVal.Length;i++){ xxx[i] = MailboxAddress.Parse(retVal[i].Trim()); // Trim <TAB>s } return xxx; } #endregion #region method ToStringData /// <summary> /// Stores mime message to string. /// </summary> /// <returns></returns> public string ToStringData() { return System.Text.Encoding.Default.GetString(ToByteData()); } #endregion #region method ToByteData /// <summary> /// Stores mime message to byte[]. /// </summary> /// <returns></returns> public byte[] ToByteData() { MemoryStream ms = new MemoryStream(); ToStream(ms); return ms.ToArray(); } #endregion #region method ToFile /// <summary> /// Stores mime message to specified file. /// </summary> /// <param name="fileName">File name.</param> public void ToFile(string fileName) { using(FileStream fs = File.Create(fileName)){ ToStream(fs); } } #endregion #region method ToStream /// <summary> /// Stores mime message to specified stream. Stream position stays where mime writing ends. /// </summary> /// <param name="storeStream">Stream where to store mime message.</param> public void ToStream(Stream storeStream) { byte[] buf = null; string mainBoundaryID = "----=_NextPart_" + Guid.NewGuid().ToString().Replace("-","_"); // Write headers buf = System.Text.Encoding.Default.GetBytes(m_pHeader.ToHeaderString("utf-8")); storeStream.Write(buf,0,buf.Length); // Content-Type: buf = System.Text.Encoding.Default.GetBytes("Content-Type: " + "multipart/mixed;\r\n\tboundary=\"" + mainBoundaryID + "\"\r\n"); storeStream.Write(buf,0,buf.Length); // buf = System.Text.Encoding.Default.GetBytes("\r\nThis is a multi-part message in MIME format.\r\n\r\n"); storeStream.Write(buf,0,buf.Length); string bodyBoundaryID = "----=_NextPart_" + Guid.NewGuid().ToString().Replace("-","_"); buf = System.Text.Encoding.Default.GetBytes("--" + mainBoundaryID + "\r\n"); storeStream.Write(buf,0,buf.Length); buf = System.Text.Encoding.Default.GetBytes("Content-Type: multipart/alternative;\r\n\tboundary=\"" + bodyBoundaryID + "\"\r\n\r\n"); storeStream.Write(buf,0,buf.Length); buf = System.Text.Encoding.Default.GetBytes(ConstructBody(bodyBoundaryID)); storeStream.Write(buf,0,buf.Length); buf = System.Text.Encoding.Default.GetBytes("--" + bodyBoundaryID + "--\r\n"); storeStream.Write(buf,0,buf.Length); //-- Construct attachments foreach(Attachment att in m_pAttachments){ buf = System.Text.Encoding.Default.GetBytes("\r\n--" + mainBoundaryID + "\r\n"); storeStream.Write(buf,0,buf.Length); buf = System.Text.Encoding.Default.GetBytes("Content-Type: application/octet;\r\n\tname=\"" + Core.CanonicalEncode(att.FileName,m_CharSet) + "\"\r\n"); storeStream.Write(buf,0,buf.Length); buf = System.Text.Encoding.Default.GetBytes("Content-Transfer-Encoding: base64\r\n"); storeStream.Write(buf,0,buf.Length); buf = System.Text.Encoding.Default.GetBytes("Content-Disposition: attachment;\r\n\tfilename=\"" + Core.CanonicalEncode(att.FileName,m_CharSet) + "\"\r\n\r\n"); storeStream.Write(buf,0,buf.Length); buf = System.Text.Encoding.Default.GetBytes(SplitString(Convert.ToBase64String(att.FileData))); storeStream.Write(buf,0,buf.Length); } buf = System.Text.Encoding.Default.GetBytes("\r\n"); storeStream.Write(buf,0,buf.Length); buf = System.Text.Encoding.Default.GetBytes("--" + mainBoundaryID + "--\r\n"); storeStream.Write(buf,0,buf.Length); } #endregion #region method SplitString private string SplitString(string sIn) { StringBuilder str = new StringBuilder(); int len = sIn.Length; int pos = 0; while(pos < len){ if((len - pos) > 76){ str.Append(sIn.Substring(pos,76) + "\r\n"); } else{ str.Append(sIn.Substring(pos,sIn.Length - pos) + "\r\n"); } pos += 76; } return str.ToString(); } #endregion #region Properties Implementation /// <summary> /// Gets message header. You can do message header customization here. /// </summary> public HeaderFieldCollection Header { get{ return m_pHeader; } } /// <summary> /// Gets header as RFC 2822 message headers. /// </summary> public string HeaderString { get{ return m_pHeader.ToHeaderString("utf-8"); } } /// <summary> /// Gets or sets header field "<b>Message-ID:</b>" value. Returns null if value isn't set. /// </summary> public string MessageID { get{ if(m_pHeader.Contains("Message-ID:")){ return m_pHeader.GetFirst("Message-ID:").Value; } else{ return null; } } set{ if(m_pHeader.Contains("Message-ID:")){ m_pHeader.GetFirst("Message-ID:").Value = value; } else{ m_pHeader.Add("Message-ID:",value); } } } /// <summary> /// Gets or sets header field "<b>To:</b>" value. Returns null if value isn't set. /// </summary> public MailboxAddress[] To { get{ if(m_pHeader.Contains("To:")){ return AddressesToArray(m_pHeader.GetFirst("To:").Value); } else{ return null; } } set{ if(m_pHeader.Contains("To:")){ m_pHeader.GetFirst("To:").Value = AddressesToString(value); } else{ m_pHeader.Add("To:",AddressesToString(value)); } } } /// <summary> /// Gets or sets header field "<b>Cc:</b>" value. Returns null if value isn't set. /// </summary> public MailboxAddress[] Cc { get{ if(m_pHeader.Contains("Cc:")){ return AddressesToArray(m_pHeader.GetFirst("Cc:").Value); } else{ return null; } } set{ if(m_pHeader.Contains("Cc:")){ m_pHeader.GetFirst("Cc:").Value = AddressesToString(value); } else{ m_pHeader.Add("Cc:",AddressesToString(value)); } } } /// <summary> /// Gets or sets header field "<b>Bcc:</b>" value. Returns null if value isn't set. /// </summary> public MailboxAddress[] Bcc { get{ if(m_pHeader.Contains("Bcc:")){ return AddressesToArray(m_pHeader.GetFirst("Bcc:").Value); } else{ return null; } } set{ if(m_pHeader.Contains("Bcc:")){ m_pHeader.GetFirst("Bcc:").Value = AddressesToString(value); } else{ m_pHeader.Add("Bcc:",AddressesToString(value)); } } } /// <summary> /// Gets or sets header field "<b>From:</b>" value. Returns null if value isn't set. /// </summary> public MailboxAddress From { get{ if(m_pHeader.Contains("From:")){ return MailboxAddress.Parse(m_pHeader.GetFirst("From:").Value); } else{ return null; } } set{ if(m_pHeader.Contains("From:")){ m_pHeader.GetFirst("From:").Value = value.MailboxString; } else{ m_pHeader.Add("From:",value.MailboxString); } } } /// <summary> /// Gets or sets header field "<b>Disposition-Notification-To:</b>" value. Returns null if value isn't set. /// </summary> public string DSN { get{ if(m_pHeader.Contains("Disposition-Notification-To:")){ return m_pHeader.GetFirst("Disposition-Notification-To:").Value; } else{ return null; } } set{ if(m_pHeader.Contains("Disposition-Notification-To:")){ m_pHeader.GetFirst("Disposition-Notification-To:").Value = value; } else{ m_pHeader.Add("Disposition-Notification-To:",value); } } } /// <summary> /// Gets or sets header field "<b>Subject:</b>" value. Returns null if value isn't set. /// </summary> public string Subject { get{ if(m_pHeader.Contains("Subject:")){ return m_pHeader.GetFirst("Subject:").Value; } else{ return null; } } set{ if(m_pHeader.Contains("Subject:")){ m_pHeader.GetFirst("Subject:").Value = value; } else{ m_pHeader.Add("Subject:",value); } } } /// <summary> /// Gets or sets header field "<b>Date:</b>" value. Returns null if value isn't set. /// </summary> public DateTime Date { get{ if(m_pHeader.Contains("Date:")){ return DateTime.ParseExact(m_pHeader.GetFirst("Date:").Value,"r",System.Globalization.DateTimeFormatInfo.InvariantInfo); } else{ return DateTime.MinValue; } } set{ if(m_pHeader.Contains("Date:")){ m_pHeader.GetFirst("Date:").Value = value.ToUniversalTime().ToString("r",System.Globalization.DateTimeFormatInfo.InvariantInfo); } else{ m_pHeader.Add("Date:",value.ToUniversalTime().ToString("r",System.Globalization.DateTimeFormatInfo.InvariantInfo)); } } } /// <summary> /// Gets or sets body text. /// </summary> public string Body { get{ return m_Body; } set{ if(value == null){ m_Body = ""; } else{ m_Body = value; } } } /// <summary> /// Gets or sets html body. /// </summary> public string BodyHtml { get{ return m_BodyHtml; } set{ m_BodyHtml = value; } } /// <summary> /// Gets or sets message charset. Default is 'utf-8'. /// </summary> public string CharSet { get{ return m_CharSet; } set{ m_CharSet = value; } } /// <summary> /// Gets referance to attachments collection. /// </summary> public Attachments Attachments { get{ return m_pAttachments; } } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Web; using System.Web.Hosting; using System.Xml; using System.Xml.Serialization; using Hydra.Framework.RssToolkit.Rss; namespace Hydra.Framework.RssToolkit.Rss { /// <summary> /// helper class that provides memory and disk caching of the downloaded feeds /// </summary> public class DownloadManager { private static DownloadManager _downloadManager = new DownloadManager(); private readonly Dictionary<string, CacheInfo> _cache; private readonly int _defaultTtlMinutes; private readonly string _directoryOnDisk; private DownloadManager() { // create in-memory cache _cache = new Dictionary<string, CacheInfo>(); // get default ttl value from config _defaultTtlMinutes = GetTtlFromString(ConfigurationManager.AppSettings["defaultRssTtl"], 1); // prepare disk directory _directoryOnDisk = PrepareTempDir(); } /// <summary> /// Gets the Feed information. /// </summary> /// <param name="url">The URL.</param> /// <returns>string</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#")] public static Stream GetFeed(string url) { if (string.IsNullOrEmpty(url)) { throw new ArgumentException(string.Format(Resources.RssToolkit.Culture, Resources.RssToolkit.ArgmentException, "url")); } return _downloadManager.GetFeedDom(url).Data; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private static string PrepareTempDir() { try { string tempDir = ConfigurationManager.AppSettings["rssTempDir"]; if (string.IsNullOrEmpty(tempDir)) { if (HostingEnvironment.IsHosted) { tempDir = HttpRuntime.CodegenDir; } else { tempDir = Environment.GetEnvironmentVariable("TEMP"); if (string.IsNullOrEmpty(tempDir)) { tempDir = Environment.GetEnvironmentVariable("TMP"); if (string.IsNullOrEmpty(tempDir)) { tempDir = Directory.GetCurrentDirectory(); } } } tempDir = Path.Combine(tempDir, "rss"); } if (!Directory.Exists(tempDir)) { Directory.CreateDirectory(tempDir); } return tempDir; } catch { // don't cache on disk if can't do it return null; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private static string GetTempFileNamePrefixFromUrl(string url) { try { Uri uri = new Uri(url); return string.Format( CultureInfo.InvariantCulture, "{0}_{1:x8}", uri.Host.Replace('.', '_'), StableHash(uri.AbsolutePath)); } catch (UriFormatException) { return "rss"; } } // returns a hash that is always the same (unlink String.GetHashCode() which varies) public static int StableHash(string value) { int hash = 0x61E04917; // slurped from .Net runtime internals... foreach (char c in value) { hash <<= 5; hash ^= c; } return hash; } private static int GetTtlFromString(string ttlString, int defaultTtlMinutes) { if (!string.IsNullOrEmpty(ttlString)) { int ttlMinutes; if (int.TryParse(ttlString, out ttlMinutes)) { if (ttlMinutes >= 0) { return ttlMinutes; } } } return defaultTtlMinutes; } private CacheInfo GetFeedDom(string url) { CacheInfo dom = null; lock (_cache) { if (_cache.TryGetValue(url, out dom)) { if (DateTime.UtcNow > dom.Expiry) { TryDeleteFile(dom.FeedFilename); _cache.Remove(url); dom = null; } } } if (!CacheReadable(dom)) { dom = DownLoadFeedDom(url); lock (_cache) { _cache[url] = dom; } } return dom; } private static bool CacheReadable(CacheInfo dom) { return (dom != null && dom.Data != null && dom.Data.CanRead); } private CacheInfo DownLoadFeedDom(string url) { //// look for disk cache first CacheInfo dom = TryLoadFromDisk(url); if (CacheReadable(dom)) { return dom; } string ttlString = null; XmlDocument doc = new XmlDocument(); doc.Load(url); if (doc.SelectSingleNode("/rss/channel/ttl") != null) { ttlString = doc.SelectSingleNode("/rss/channel/ttl").Value; } //// compute expiry int ttlMinutes = GetTtlFromString(ttlString, _defaultTtlMinutes); DateTime utcExpiry = DateTime.UtcNow.AddMinutes(ttlMinutes); //// save to disk return TrySaveToDisk(doc, url, utcExpiry); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private CacheInfo TryLoadFromDisk(string url) { if (_directoryOnDisk == null) { return null; // no place to cache } CacheInfo found = null; // look for all files matching the prefix // looking for the one matching url that is not expired // removing expired (or invalid) ones string pattern = GetTempFileNamePrefixFromUrl(url) + "_*.feed"; string[] files = Directory.GetFiles(_directoryOnDisk, pattern, SearchOption.TopDirectoryOnly); foreach (string feedFilename in files) { XmlDocument feedDoc = null; bool isFeedFileValid = false; DateTime utcExpiryFromFeedFile = DateTime.MinValue; string urlFromFeedFile = null; try { feedDoc = new XmlDocument(); feedDoc.Load(feedFilename); // look for special XML comment (before the root tag)' // containing expiration and url XmlComment comment = feedDoc.DocumentElement.PreviousSibling as XmlComment; if (comment != null) { string c = comment.Value ?? string.Empty; int i = c.IndexOf('@'); long expiry; if (i >= 0 && long.TryParse(c.Substring(0, i), out expiry)) { utcExpiryFromFeedFile = DateTime.FromBinary(expiry); urlFromFeedFile = c.Substring(i + 1); isFeedFileValid = true; } } } catch (XmlException) { // error processing one file shouldn't stop processing other files } // remove invalid or expired file if (!isFeedFileValid || utcExpiryFromFeedFile < DateTime.UtcNow) { TryDeleteFile(feedFilename); // try next file continue; } // match url if (urlFromFeedFile == url) { // keep the one that expires last if (found == null || found.Expiry < utcExpiryFromFeedFile) { // if we have a previously found older expiration, kill it... if (found != null) { found.Dispose(); TryDeleteFile(found.FeedFilename); } // create DOM and set expiry (as found on disk) found = new CacheInfo(feedDoc, utcExpiryFromFeedFile, feedFilename); } } } // return best fit return found; } private void TryDeleteFile(string feedFilename) { if (string.IsNullOrEmpty(feedFilename)) return; try { File.Delete(feedFilename); } catch { // error deleting a file shouldn't stop processing other files } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private CacheInfo TrySaveToDisk(XmlDocument doc, string url, DateTime utcExpiry) { string fileName = null; if (_directoryOnDisk != null) { XmlComment comment = doc.CreateComment(string.Format(CultureInfo.InvariantCulture, "{0}@{1}", utcExpiry.ToBinary(), url)); doc.InsertBefore(comment, doc.DocumentElement); fileName = string.Format( CultureInfo.InvariantCulture, "{0}_{1:x8}.feed", GetTempFileNamePrefixFromUrl(url), Guid.NewGuid().GetHashCode()); try { doc.Save(Path.Combine(_directoryOnDisk, fileName)); } catch { // can't save to disk - not a problem fileName = null; } } return new CacheInfo(doc, utcExpiry, fileName); } private class CacheInfo : IDisposable { private readonly Stream data; private readonly DateTime expiry; private readonly string filename; public CacheInfo(XmlDocument doc, DateTime utcExpiry, string feedFilename) { MemoryStream documentStream = new MemoryStream(); doc.Save(documentStream); documentStream.Flush(); documentStream.Position = 0; this.data = documentStream; this.expiry = utcExpiry; this.filename = feedFilename; } /// <summary> /// Gets the expiration time in UTC. /// </summary> /// <value>The expiry.</value> public DateTime Expiry { get { return expiry; } } /// <summary> /// Gets the data stream /// </summary> /// <value>The data.</value> public Stream Data { get { return data; } } /// <summary> /// Gets the filename /// </summary> public string FeedFilename { get { return filename; } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { data.Dispose(); } } } }
// Copyright 2022 Google LLC // // 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 // // https://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. // Generated code. DO NOT EDIT! namespace Google.Apis.MyBusinessPlaceActions.v1 { /// <summary>The MyBusinessPlaceActions Service.</summary> public class MyBusinessPlaceActionsService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public MyBusinessPlaceActionsService() : this(new Google.Apis.Services.BaseClientService.Initializer()) { } /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public MyBusinessPlaceActionsService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { Locations = new LocationsResource(this); PlaceActionTypeMetadata = new PlaceActionTypeMetadataResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features => new string[0]; /// <summary>Gets the service name.</summary> public override string Name => "mybusinessplaceactions"; /// <summary>Gets the service base URI.</summary> public override string BaseUri => #if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45 BaseUriOverride ?? "https://mybusinessplaceactions.googleapis.com/"; #else "https://mybusinessplaceactions.googleapis.com/"; #endif /// <summary>Gets the service base path.</summary> public override string BasePath => ""; #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri => "https://mybusinessplaceactions.googleapis.com/batch"; /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath => "batch"; #endif /// <summary>Gets the Locations resource.</summary> public virtual LocationsResource Locations { get; } /// <summary>Gets the PlaceActionTypeMetadata resource.</summary> public virtual PlaceActionTypeMetadataResource PlaceActionTypeMetadata { get; } } /// <summary>A base abstract class for MyBusinessPlaceActions requests.</summary> public abstract class MyBusinessPlaceActionsBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { /// <summary>Constructs a new MyBusinessPlaceActionsBaseServiceRequest instance.</summary> protected MyBusinessPlaceActionsBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1 = 0, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2 = 1, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json = 0, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media = 1, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto = 2, } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary> /// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required /// unless you provide an OAuth 2.0 token. /// </summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary> /// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a /// user, but should not exceed 40 characters. /// </summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes MyBusinessPlaceActions parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "locations" collection of methods.</summary> public class LocationsResource { private const string Resource = "locations"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public LocationsResource(Google.Apis.Services.IClientService service) { this.service = service; PlaceActionLinks = new PlaceActionLinksResource(service); } /// <summary>Gets the PlaceActionLinks resource.</summary> public virtual PlaceActionLinksResource PlaceActionLinks { get; } /// <summary>The "placeActionLinks" collection of methods.</summary> public class PlaceActionLinksResource { private const string Resource = "placeActionLinks"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public PlaceActionLinksResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary> /// Creates a place action link associated with the specified location, and returns it. The request is /// considered duplicate if the `parent`, `place_action_link.uri` and `place_action_link.place_action_type` /// are the same as a previous request. /// </summary> /// <param name="body">The body of the request.</param> /// <param name="parent"> /// Required. The resource name of the location where to create this place action link. /// `locations/{location_id}`. /// </param> public virtual CreateRequest Create(Google.Apis.MyBusinessPlaceActions.v1.Data.PlaceActionLink body, string parent) { return new CreateRequest(service, body, parent); } /// <summary> /// Creates a place action link associated with the specified location, and returns it. The request is /// considered duplicate if the `parent`, `place_action_link.uri` and `place_action_link.place_action_type` /// are the same as a previous request. /// </summary> public class CreateRequest : MyBusinessPlaceActionsBaseServiceRequest<Google.Apis.MyBusinessPlaceActions.v1.Data.PlaceActionLink> { /// <summary>Constructs a new Create request.</summary> public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.MyBusinessPlaceActions.v1.Data.PlaceActionLink body, string parent) : base(service) { Parent = parent; Body = body; InitParameters(); } /// <summary> /// Required. The resource name of the location where to create this place action link. /// `locations/{location_id}`. /// </summary> [Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)] public virtual string Parent { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.MyBusinessPlaceActions.v1.Data.PlaceActionLink Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "create"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/{+parent}/placeActionLinks"; /// <summary>Initializes Create parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter { Name = "parent", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^locations/[^/]+$", }); } } /// <summary>Deletes a place action link from the specified location.</summary> /// <param name="name"> /// Required. The resource name of the place action link to remove from the location. /// </param> public virtual DeleteRequest Delete(string name) { return new DeleteRequest(service, name); } /// <summary>Deletes a place action link from the specified location.</summary> public class DeleteRequest : MyBusinessPlaceActionsBaseServiceRequest<Google.Apis.MyBusinessPlaceActions.v1.Data.Empty> { /// <summary>Constructs a new Delete request.</summary> public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>Required. The resource name of the place action link to remove from the location.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets the method name.</summary> public override string MethodName => "delete"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "DELETE"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/{+name}"; /// <summary>Initializes Delete parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^locations/[^/]+/placeActionLinks/[^/]+$", }); } } /// <summary>Gets the specified place action link.</summary> /// <param name="name">Required. The name of the place action link to fetch.</param> public virtual GetRequest Get(string name) { return new GetRequest(service, name); } /// <summary>Gets the specified place action link.</summary> public class GetRequest : MyBusinessPlaceActionsBaseServiceRequest<Google.Apis.MyBusinessPlaceActions.v1.Data.PlaceActionLink> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>Required. The name of the place action link to fetch.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets the method name.</summary> public override string MethodName => "get"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/{+name}"; /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^locations/[^/]+/placeActionLinks/[^/]+$", }); } } /// <summary>Lists the place action links for the specified location.</summary> /// <param name="parent"> /// Required. The name of the location whose place action links will be listed. `locations/{location_id}`. /// </param> public virtual ListRequest List(string parent) { return new ListRequest(service, parent); } /// <summary>Lists the place action links for the specified location.</summary> public class ListRequest : MyBusinessPlaceActionsBaseServiceRequest<Google.Apis.MyBusinessPlaceActions.v1.Data.ListPlaceActionLinksResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service) { Parent = parent; InitParameters(); } /// <summary> /// Required. The name of the location whose place action links will be listed. /// `locations/{location_id}`. /// </summary> [Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)] public virtual string Parent { get; private set; } /// <summary> /// Optional. A filter constraining the place action links to return. The response includes entries that /// match the filter. We support only the following filter: 1. place_action_type=XYZ where XYZ is a /// valid PlaceActionType. /// </summary> [Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)] public virtual string Filter { get; set; } /// <summary> /// Optional. How many place action links to return per page. Default of 10. The minimum is 1. /// </summary> [Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> PageSize { get; set; } /// <summary>Optional. If specified, returns the next page of place action links.</summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } /// <summary>Gets the method name.</summary> public override string MethodName => "list"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/{+parent}/placeActionLinks"; /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter { Name = "parent", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^locations/[^/]+$", }); RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter { Name = "filter", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter { Name = "pageSize", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>Updates the specified place action link and returns it.</summary> /// <param name="body">The body of the request.</param> /// <param name="name"> /// Optional. The resource name, in the format /// `locations/{location_id}/placeActionLinks/{place_action_link_id}`. The name field will only be /// considered in UpdatePlaceActionLink and DeletePlaceActionLink requests for updating and deleting links /// respectively. However, it will be ignored in CreatePlaceActionLink request, where `place_action_link_id` /// will be assigned by the server on successful creation of a new link and returned as part of the /// response. /// </param> public virtual PatchRequest Patch(Google.Apis.MyBusinessPlaceActions.v1.Data.PlaceActionLink body, string name) { return new PatchRequest(service, body, name); } /// <summary>Updates the specified place action link and returns it.</summary> public class PatchRequest : MyBusinessPlaceActionsBaseServiceRequest<Google.Apis.MyBusinessPlaceActions.v1.Data.PlaceActionLink> { /// <summary>Constructs a new Patch request.</summary> public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.MyBusinessPlaceActions.v1.Data.PlaceActionLink body, string name) : base(service) { Name = name; Body = body; InitParameters(); } /// <summary> /// Optional. The resource name, in the format /// `locations/{location_id}/placeActionLinks/{place_action_link_id}`. The name field will only be /// considered in UpdatePlaceActionLink and DeletePlaceActionLink requests for updating and deleting /// links respectively. However, it will be ignored in CreatePlaceActionLink request, where /// `place_action_link_id` will be assigned by the server on successful creation of a new link and /// returned as part of the response. /// </summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary> /// Required. The specific fields to update. The only editable fields are `uri`, `place_action_type` and /// `is_preferred`. If the updated link already exists at the same location with the same /// `place_action_type` and `uri`, fails with an `ALREADY_EXISTS` error. /// </summary> [Google.Apis.Util.RequestParameterAttribute("updateMask", Google.Apis.Util.RequestParameterType.Query)] public virtual object UpdateMask { get; set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.MyBusinessPlaceActions.v1.Data.PlaceActionLink Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "patch"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "PATCH"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/{+name}"; /// <summary>Initializes Patch parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^locations/[^/]+/placeActionLinks/[^/]+$", }); RequestParameters.Add("updateMask", new Google.Apis.Discovery.Parameter { Name = "updateMask", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } } /// <summary>The "placeActionTypeMetadata" collection of methods.</summary> public class PlaceActionTypeMetadataResource { private const string Resource = "placeActionTypeMetadata"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public PlaceActionTypeMetadataResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Returns the list of available place action types for a location or country.</summary> public virtual ListRequest List() { return new ListRequest(service); } /// <summary>Returns the list of available place action types for a location or country.</summary> public class ListRequest : MyBusinessPlaceActionsBaseServiceRequest<Google.Apis.MyBusinessPlaceActions.v1.Data.ListPlaceActionTypeMetadataResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service) : base(service) { InitParameters(); } /// <summary> /// Optional. A filter constraining the place action types to return metadata for. The response includes /// entries that match the filter. We support only the following filters: 1. location=XYZ where XYZ is a /// string indicating the resource name of a location, in the format `locations/{location_id}`. 2. /// region_code=XYZ where XYZ is a Unicode CLDR region code to find available action types. If no filter is /// provided, all place action types are returned. /// </summary> [Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)] public virtual string Filter { get; set; } /// <summary> /// Optional. The IETF BCP-47 code of language to get display names in. If this language is not available, /// they will be provided in English. /// </summary> [Google.Apis.Util.RequestParameterAttribute("languageCode", Google.Apis.Util.RequestParameterType.Query)] public virtual string LanguageCode { get; set; } /// <summary>Optional. How many action types to include per page. Default is 10, minimum is 1.</summary> [Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> PageSize { get; set; } /// <summary> /// Optional. If specified, the next page of place action type metadata is retrieved. The `pageToken` is /// returned when a call to `placeActionTypeMetadata.list` returns more results than can fit into the /// requested page size. /// </summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } /// <summary>Gets the method name.</summary> public override string MethodName => "list"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/placeActionTypeMetadata"; /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter { Name = "filter", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("languageCode", new Google.Apis.Discovery.Parameter { Name = "languageCode", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter { Name = "pageSize", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } } namespace Google.Apis.MyBusinessPlaceActions.v1.Data { /// <summary> /// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical /// example is to use it as the request or the response type of an API method. For instance: service Foo { rpc /// Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON /// object `{}`. /// </summary> public class Empty : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response message for PlaceActions.ListPlaceActionLinks.</summary> public class ListPlaceActionLinksResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// If there are more place action links than the requested page size, then this field is populated with a token /// to fetch the next page of results. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>The returned list of place action links.</summary> [Newtonsoft.Json.JsonPropertyAttribute("placeActionLinks")] public virtual System.Collections.Generic.IList<PlaceActionLink> PlaceActionLinks { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response message for PlaceActions.ListPlaceActionTypeMetadata.</summary> public class ListPlaceActionTypeMetadataResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// If the number of action types exceeded the requested page size, this field will be populated with a token to /// fetch the next page on a subsequent call to `placeActionTypeMetadata.list`. If there are no more results, /// this field will not be present in the response. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>A collection of metadata for the available place action types.</summary> [Newtonsoft.Json.JsonPropertyAttribute("placeActionTypeMetadata")] public virtual System.Collections.Generic.IList<PlaceActionTypeMetadata> PlaceActionTypeMetadata { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Represents a place action link and its attributes.</summary> public class PlaceActionLink : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Output only. The time when the place action link was created.</summary> [Newtonsoft.Json.JsonPropertyAttribute("createTime")] public virtual object CreateTime { get; set; } /// <summary>Output only. Indicates whether this link can be edited by the client.</summary> [Newtonsoft.Json.JsonPropertyAttribute("isEditable")] public virtual System.Nullable<bool> IsEditable { get; set; } /// <summary> /// Optional. Whether this link is preferred by the merchant. Only one link can be marked as preferred per place /// action type at a location. If a future request marks a different link as preferred for the same place action /// type, then the current preferred link (if any exists) will lose its preference. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("isPreferred")] public virtual System.Nullable<bool> IsPreferred { get; set; } /// <summary> /// Optional. The resource name, in the format /// `locations/{location_id}/placeActionLinks/{place_action_link_id}`. The name field will only be considered in /// UpdatePlaceActionLink and DeletePlaceActionLink requests for updating and deleting links respectively. /// However, it will be ignored in CreatePlaceActionLink request, where `place_action_link_id` will be assigned /// by the server on successful creation of a new link and returned as part of the response. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>Required. The type of place action that can be performed using this link.</summary> [Newtonsoft.Json.JsonPropertyAttribute("placeActionType")] public virtual string PlaceActionType { get; set; } /// <summary>Output only. Specifies the provider type.</summary> [Newtonsoft.Json.JsonPropertyAttribute("providerType")] public virtual string ProviderType { get; set; } /// <summary>Output only. The time when the place action link was last modified.</summary> [Newtonsoft.Json.JsonPropertyAttribute("updateTime")] public virtual object UpdateTime { get; set; } /// <summary> /// Required. The link uri. The same uri can be reused for different action types across different locations. /// However, only one place action link is allowed for each unique combination of (uri, place action type, /// location). /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("uri")] public virtual string Uri { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Metadata for supported place action types.</summary> public class PlaceActionTypeMetadata : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// The localized display name for the attribute, if available; otherwise, the English display name. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("displayName")] public virtual string DisplayName { get; set; } /// <summary>The place action type.</summary> [Newtonsoft.Json.JsonPropertyAttribute("placeActionType")] public virtual string PlaceActionType { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web; using System.Web.Configuration; using System.Web.Hosting; using System.Web.Routing; using System.Web.Security; using System.Xml; using System.Xml.Linq; using System.Xml.XPath; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Security; namespace Umbraco.Core.Configuration { //NOTE: Do not expose this class ever until we cleanup all configuration including removal of static classes, etc... // we have this two tasks logged: // http://issues.umbraco.org/issue/U4-58 // http://issues.umbraco.org/issue/U4-115 //TODO: Replace checking for if the app settings exist and returning an empty string, instead return the defaults! /// <summary> /// The GlobalSettings Class contains general settings information for the entire Umbraco instance based on information from web.config appsettings /// </summary> internal class GlobalSettings { #region Private static fields private static Version _version; private static readonly object Locker = new object(); //make this volatile so that we can ensure thread safety with a double check lock private static volatile string _reservedUrlsCache; private static string _reservedPathsCache; private static StartsWithContainer _reservedList = new StartsWithContainer(); private static string _reservedPaths; private static string _reservedUrls; //ensure the built on (non-changeable) reserved paths are there at all times private const string StaticReservedPaths = "~/app_plugins/,~/install/,"; private const string StaticReservedUrls = "~/config/splashes/booting.aspx,~/config/splashes/noNodes.aspx,~/VSEnterpriseHelper.axd,"; #endregion /// <summary> /// Used in unit testing to reset all config items that were set with property setters (i.e. did not come from config) /// </summary> private static void ResetInternal() { _reservedUrlsCache = null; _reservedPaths = null; _reservedUrls = null; } /// <summary> /// Resets settings that were set programmatically, to their initial values. /// </summary> /// <remarks>To be used in unit tests.</remarks> internal static void Reset() { ResetInternal(); } /// <summary> /// Gets the reserved urls from web.config. /// </summary> /// <value>The reserved urls.</value> public static string ReservedUrls { get { if (_reservedUrls == null) { var urls = ConfigurationManager.AppSettings.ContainsKey("umbracoReservedUrls") ? ConfigurationManager.AppSettings["umbracoReservedUrls"] : string.Empty; //ensure the built on (non-changeable) reserved paths are there at all times _reservedUrls = StaticReservedUrls + urls; } return _reservedUrls; } internal set { _reservedUrls = value; } } /// <summary> /// Gets the reserved paths from web.config /// </summary> /// <value>The reserved paths.</value> public static string ReservedPaths { get { if (_reservedPaths == null) { var reservedPaths = StaticReservedPaths; //always add the umbraco path to the list if (ConfigurationManager.AppSettings.ContainsKey("umbracoPath") && !ConfigurationManager.AppSettings["umbracoPath"].IsNullOrWhiteSpace()) { reservedPaths += ConfigurationManager.AppSettings["umbracoPath"].EnsureEndsWith(','); } var allPaths = ConfigurationManager.AppSettings.ContainsKey("umbracoReservedPaths") ? ConfigurationManager.AppSettings["umbracoReservedPaths"] : string.Empty; _reservedPaths = reservedPaths + allPaths; } return _reservedPaths; } internal set { _reservedPaths = value; } } /// <summary> /// Gets the name of the content XML file. /// </summary> /// <value>The content XML.</value> /// <remarks> /// Defaults to ~/App_Data/umbraco.config /// </remarks> public static string ContentXmlFile { get { return ConfigurationManager.AppSettings.ContainsKey("umbracoContentXML") ? ConfigurationManager.AppSettings["umbracoContentXML"] : "~/App_Data/umbraco.config"; } } /// <summary> /// Gets the path to the storage directory (/data by default). /// </summary> /// <value>The storage directory.</value> public static string StorageDirectory { get { return ConfigurationManager.AppSettings.ContainsKey("umbracoStorageDirectory") ? ConfigurationManager.AppSettings["umbracoStorageDirectory"] : "~/App_Data"; } } /// <summary> /// Gets the path to umbraco's root directory (/umbraco by default). /// </summary> /// <value>The path.</value> public static string Path { get { return ConfigurationManager.AppSettings.ContainsKey("umbracoPath") ? IOHelper.ResolveUrl(ConfigurationManager.AppSettings["umbracoPath"]) : string.Empty; } } /// <summary> /// This returns the string of the MVC Area route. /// </summary> /// <remarks> /// THIS IS TEMPORARY AND SHOULD BE REMOVED WHEN WE MIGRATE/UPDATE THE CONFIG SETTINGS TO BE A REAL CONFIG SECTION /// AND SHOULD PROBABLY BE HANDLED IN A MORE ROBUST WAY. /// /// This will return the MVC area that we will route all custom routes through like surface controllers, etc... /// We will use the 'Path' (default ~/umbraco) to create it but since it cannot contain '/' and people may specify a path of ~/asdf/asdf/admin /// we will convert the '/' to '-' and use that as the path. its a bit lame but will work. /// /// We also make sure that the virtual directory (SystemDirectories.Root) is stripped off first, otherwise we'd end up with something /// like "MyVirtualDirectory-Umbraco" instead of just "Umbraco". /// </remarks> public static string UmbracoMvcArea { get { if (Path.IsNullOrWhiteSpace()) { throw new InvalidOperationException("Cannot create an MVC Area path without the umbracoPath specified"); } var path = Path; if (path.StartsWith(SystemDirectories.Root)) // beware of TrimStart, see U4-2518 path = path.Substring(SystemDirectories.Root.Length); return path.TrimStart('~').TrimStart('/').Replace('/', '-').Trim().ToLower(); } } /// <summary> /// Gets the path to umbraco's client directory (/umbraco_client by default). /// This is a relative path to the Umbraco Path as it always must exist beside the 'umbraco' /// folder since the CSS paths to images depend on it. /// </summary> /// <value>The path.</value> public static string ClientPath { get { return Path + "/../umbraco_client"; } } /// <summary> /// Gets the database connection string /// </summary> /// <value>The database connection string.</value> [Obsolete("Use System.Configuration.ConfigurationManager.ConnectionStrings[\"umbracoDbDSN\"] instead")] public static string DbDsn { get { var settings = ConfigurationManager.ConnectionStrings[UmbracoConnectionName]; var connectionString = string.Empty; if (settings != null) { connectionString = settings.ConnectionString; // The SqlCe connectionString is formatted slightly differently, so we need to update it if (settings.ProviderName.Contains("SqlServerCe")) connectionString = string.Format("datalayer=SQLCE4Umbraco.SqlCEHelper,SQLCE4Umbraco;{0}", connectionString); } return connectionString; } set { if (DbDsn != value) { if (value.ToLower().Contains("SQLCE4Umbraco.SqlCEHelper".ToLower())) { ApplicationContext.Current.DatabaseContext.ConfigureEmbeddedDatabaseConnection(); } else { ApplicationContext.Current.DatabaseContext.ConfigureDatabaseConnection(value); } } } } public const string UmbracoConnectionName = "umbracoDbDSN"; public const string UmbracoMigrationName = "Umbraco"; /// <summary> /// Gets or sets the configuration status. This will return the version number of the currently installed umbraco instance. /// </summary> /// <value>The configuration status.</value> public static string ConfigurationStatus { get { return ConfigurationManager.AppSettings.ContainsKey("umbracoConfigurationStatus") ? ConfigurationManager.AppSettings["umbracoConfigurationStatus"] : string.Empty; } set { SaveSetting("umbracoConfigurationStatus", value); } } /// <summary> /// Gets or sets the Umbraco members membership providers' useLegacyEncoding state. This will return a boolean /// </summary> /// <value>The useLegacyEncoding status.</value> public static bool UmbracoMembershipProviderLegacyEncoding { get { return IsConfiguredMembershipProviderUsingLegacyEncoding(Constants.Conventions.Member.UmbracoMemberProviderName); } set { SetMembershipProvidersLegacyEncoding(Constants.Conventions.Member.UmbracoMemberProviderName, value); } } /// <summary> /// Gets or sets the Umbraco users membership providers' useLegacyEncoding state. This will return a boolean /// </summary> /// <value>The useLegacyEncoding status.</value> public static bool UmbracoUsersMembershipProviderLegacyEncoding { get { return IsConfiguredMembershipProviderUsingLegacyEncoding(UmbracoConfig.For.UmbracoSettings().Providers.DefaultBackOfficeUserProvider); } set { SetMembershipProvidersLegacyEncoding(UmbracoConfig.For.UmbracoSettings().Providers.DefaultBackOfficeUserProvider, value); } } /// <summary> /// Saves a setting into the configuration file. /// </summary> /// <param name="key">Key of the setting to be saved.</param> /// <param name="value">Value of the setting to be saved.</param> internal static void SaveSetting(string key, string value) { var fileName = IOHelper.MapPath(string.Format("{0}/web.config", SystemDirectories.Root)); var xml = XDocument.Load(fileName, LoadOptions.PreserveWhitespace); var appSettings = xml.Root.DescendantsAndSelf("appSettings").Single(); // Update appSetting if it exists, or else create a new appSetting for the given key and value var setting = appSettings.Descendants("add").FirstOrDefault(s => s.Attribute("key").Value == key); if (setting == null) appSettings.Add(new XElement("add", new XAttribute("key", key), new XAttribute("value", value))); else setting.Attribute("value").Value = value; xml.Save(fileName, SaveOptions.DisableFormatting); ConfigurationManager.RefreshSection("appSettings"); } /// <summary> /// Removes a setting from the configuration file. /// </summary> /// <param name="key">Key of the setting to be removed.</param> internal static void RemoveSetting(string key) { var fileName = IOHelper.MapPath(string.Format("{0}/web.config", SystemDirectories.Root)); var xml = XDocument.Load(fileName, LoadOptions.PreserveWhitespace); var appSettings = xml.Root.DescendantsAndSelf("appSettings").Single(); var setting = appSettings.Descendants("add").FirstOrDefault(s => s.Attribute("key").Value == key); if (setting != null) { setting.Remove(); xml.Save(fileName, SaveOptions.DisableFormatting); ConfigurationManager.RefreshSection("appSettings"); } } private static void SetMembershipProvidersLegacyEncoding(string providerName, bool useLegacyEncoding) { //check if this can even be configured. var membershipProvider = Membership.Providers[providerName] as MembershipProviderBase; if (membershipProvider == null) { return; } if (membershipProvider.GetType().Namespace == "umbraco.providers.members") { //its the legacy one, this cannot be changed return; } var webConfigFilename = IOHelper.MapPath(string.Format("{0}/web.config", SystemDirectories.Root)); var webConfigXml = XDocument.Load(webConfigFilename, LoadOptions.PreserveWhitespace); var membershipConfigs = webConfigXml.XPathSelectElements("configuration/system.web/membership/providers/add").ToList(); if (membershipConfigs.Any() == false) return; var provider = membershipConfigs.SingleOrDefault(c => c.Attribute("name") != null && c.Attribute("name").Value == providerName); if (provider == null) return; provider.SetAttributeValue("useLegacyEncoding", useLegacyEncoding); webConfigXml.Save(webConfigFilename, SaveOptions.DisableFormatting); } private static bool IsConfiguredMembershipProviderUsingLegacyEncoding(string providerName) { //check if this can even be configured. var membershipProvider = Membership.Providers[providerName] as MembershipProviderBase; if (membershipProvider == null) { return false; } return membershipProvider.UseLegacyEncoding; } /// <summary> /// Gets the full path to root. /// </summary> /// <value>The fullpath to root.</value> public static string FullpathToRoot { get { return IOHelper.GetRootDirectorySafe(); } } /// <summary> /// Gets a value indicating whether umbraco is running in [debug mode]. /// </summary> /// <value><c>true</c> if [debug mode]; otherwise, <c>false</c>.</value> public static bool DebugMode { get { try { if (HttpContext.Current != null) { return HttpContext.Current.IsDebuggingEnabled; } //go and get it from config directly var section = ConfigurationManager.GetSection("system.web/compilation") as CompilationSection; return section != null && section.Debug; } catch { return false; } } } /// <summary> /// Gets a value indicating whether the current version of umbraco is configured. /// </summary> /// <value><c>true</c> if configured; otherwise, <c>false</c>.</value> public static bool Configured { get { try { string configStatus = ConfigurationStatus; string currentVersion = UmbracoVersion.Current.ToString(3); if (currentVersion != configStatus) { LogHelper.Debug<GlobalSettings>("CurrentVersion different from configStatus: '" + currentVersion + "','" + configStatus + "'"); } return (configStatus == currentVersion); } catch { return false; } } } /// <summary> /// Gets the time out in minutes. /// </summary> /// <value>The time out in minutes.</value> public static int TimeOutInMinutes { get { try { return int.Parse(ConfigurationManager.AppSettings["umbracoTimeOutInMinutes"]); } catch { return 20; } } } /// <summary> /// Gets a value indicating whether umbraco uses directory urls. /// </summary> /// <value><c>true</c> if umbraco uses directory urls; otherwise, <c>false</c>.</value> public static bool UseDirectoryUrls { get { try { return bool.Parse(ConfigurationManager.AppSettings["umbracoUseDirectoryUrls"]); } catch { return false; } } } /// <summary> /// Returns a string value to determine if umbraco should skip version-checking. /// </summary> /// <value>The version check period in days (0 = never).</value> public static int VersionCheckPeriod { get { try { return int.Parse(ConfigurationManager.AppSettings["umbracoVersionCheckPeriod"]); } catch { return 7; } } } /// <summary> /// Returns a string value to determine if umbraco should disbable xslt extensions /// </summary> /// <value><c>"true"</c> if version xslt extensions are disabled, otherwise, <c>"false"</c></value> [Obsolete("This is no longer used and will be removed from the codebase in future releases")] public static string DisableXsltExtensions { get { return ConfigurationManager.AppSettings.ContainsKey("umbracoDisableXsltExtensions") ? ConfigurationManager.AppSettings["umbracoDisableXsltExtensions"] : "false"; } } internal static bool ContentCacheXmlStoredInCodeGen { get { //defaults to false return ConfigurationManager.AppSettings.ContainsKey("umbracoContentXMLUseLocalTemp") && bool.Parse(ConfigurationManager.AppSettings["umbracoContentXMLUseLocalTemp"]); //default to false } } /// <summary> /// Returns a string value to determine if umbraco should use Xhtml editing mode in the wysiwyg editor /// </summary> /// <value><c>"true"</c> if Xhtml mode is enable, otherwise, <c>"false"</c></value> [Obsolete("This is no longer used and will be removed from the codebase in future releases")] public static string EditXhtmlMode { get { return "true"; } } /// <summary> /// Gets the default UI language. /// </summary> /// <value>The default UI language.</value> public static string DefaultUILanguage { get { return ConfigurationManager.AppSettings.ContainsKey("umbracoDefaultUILanguage") ? ConfigurationManager.AppSettings["umbracoDefaultUILanguage"] : string.Empty; } } /// <summary> /// Gets the profile URL. /// </summary> /// <value>The profile URL.</value> public static string ProfileUrl { get { //the default will be 'profiler' return ConfigurationManager.AppSettings.ContainsKey("umbracoProfileUrl") ? ConfigurationManager.AppSettings["umbracoProfileUrl"] : "profiler"; } } /// <summary> /// Gets a value indicating whether umbraco should hide top level nodes from generated urls. /// </summary> /// <value> /// <c>true</c> if umbraco hides top level nodes from urls; otherwise, <c>false</c>. /// </value> public static bool HideTopLevelNodeFromPath { get { try { return bool.Parse(ConfigurationManager.AppSettings["umbracoHideTopLevelNodeFromPath"]); } catch { return false; } } } /// <summary> /// Gets the current version. /// </summary> /// <value>The current version.</value> [Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)] public static string CurrentVersion { get { return UmbracoVersion.Current.ToString(3); } } /// <summary> /// Gets the major version number. /// </summary> /// <value>The major version number.</value> [Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)] public static int VersionMajor { get { return UmbracoVersion.Current.Major; } } /// <summary> /// Gets the minor version number. /// </summary> /// <value>The minor version number.</value> [Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)] public static int VersionMinor { get { return UmbracoVersion.Current.Minor; } } /// <summary> /// Gets the patch version number. /// </summary> /// <value>The patch version number.</value> [Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)] public static int VersionPatch { get { return UmbracoVersion.Current.Build; } } /// <summary> /// Gets the version comment (like beta or RC). /// </summary> /// <value>The version comment.</value> [Obsolete("Use Umbraco.Core.Configuration.UmbracoVersion.Current instead", false)] public static string VersionComment { get { return Umbraco.Core.Configuration.UmbracoVersion.CurrentComment; } } /// <summary> /// Requests the is in umbraco application directory structure. /// </summary> /// <param name="context">The context.</param> /// <returns></returns> public static bool RequestIsInUmbracoApplication(HttpContext context) { return context.Request.Path.ToLower().IndexOf(IOHelper.ResolveUrl(SystemDirectories.Umbraco).ToLower()) > -1; } public static bool RequestIsInUmbracoApplication(HttpContextBase context) { return context.Request.Path.ToLower().IndexOf(IOHelper.ResolveUrl(SystemDirectories.Umbraco).ToLower()) > -1; } /// <summary> /// Gets a value indicating whether umbraco should force a secure (https) connection to the backoffice. /// </summary> /// <value><c>true</c> if [use SSL]; otherwise, <c>false</c>.</value> public static bool UseSSL { get { try { return bool.Parse(ConfigurationManager.AppSettings["umbracoUseSSL"]); } catch { return false; } } } /// <summary> /// Gets the umbraco license. /// </summary> /// <value>The license.</value> public static string License { get { string license = "<A href=\"http://umbraco.org/redir/license\" target=\"_blank\">the open source license MIT</A>. The umbraco UI is freeware licensed under the umbraco license."; var versionDoc = new XmlDocument(); var versionReader = new XmlTextReader(IOHelper.MapPath(SystemDirectories.Umbraco + "/version.xml")); versionDoc.Load(versionReader); versionReader.Close(); // check for license try { string licenseUrl = versionDoc.SelectSingleNode("/version/licensing/licenseUrl").FirstChild.Value; string licenseValidation = versionDoc.SelectSingleNode("/version/licensing/licenseValidation").FirstChild.Value; string licensedTo = versionDoc.SelectSingleNode("/version/licensing/licensedTo").FirstChild.Value; if (licensedTo != "" && licenseUrl != "") { license = "umbraco Commercial License<br/><b>Registered to:</b><br/>" + licensedTo.Replace("\n", "<br/>") + "<br/><b>For use with domain:</b><br/>" + licenseUrl; } } catch { } return license; } } /// <summary> /// Determines whether the current request is reserved based on the route table and /// whether the specified URL is reserved or is inside a reserved path. /// </summary> /// <param name="url"></param> /// <param name="httpContext"></param> /// <param name="routes">The route collection to lookup the request in</param> /// <returns></returns> public static bool IsReservedPathOrUrl(string url, HttpContextBase httpContext, RouteCollection routes) { if (httpContext == null) throw new ArgumentNullException("httpContext"); if (routes == null) throw new ArgumentNullException("routes"); //check if the current request matches a route, if so then it is reserved. var route = routes.GetRouteData(httpContext); if (route != null) return true; //continue with the standard ignore routine return IsReservedPathOrUrl(url); } /// <summary> /// Determines whether the specified URL is reserved or is inside a reserved path. /// </summary> /// <param name="url">The URL to check.</param> /// <returns> /// <c>true</c> if the specified URL is reserved; otherwise, <c>false</c>. /// </returns> public static bool IsReservedPathOrUrl(string url) { if (_reservedUrlsCache == null) { lock (Locker) { if (_reservedUrlsCache == null) { // store references to strings to determine changes _reservedPathsCache = GlobalSettings.ReservedPaths; _reservedUrlsCache = GlobalSettings.ReservedUrls; string _root = SystemDirectories.Root.Trim().ToLower(); // add URLs and paths to a new list StartsWithContainer _newReservedList = new StartsWithContainer(); foreach (string reservedUrl in _reservedUrlsCache.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)) { if (string.IsNullOrWhiteSpace(reservedUrl)) continue; //resolves the url to support tilde chars string reservedUrlTrimmed = IOHelper.ResolveUrl(reservedUrl.Trim()).Trim().ToLower(); if (reservedUrlTrimmed.Length > 0) _newReservedList.Add(reservedUrlTrimmed); } foreach (string reservedPath in _reservedPathsCache.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)) { bool trimEnd = !reservedPath.EndsWith("/"); if (string.IsNullOrWhiteSpace(reservedPath)) continue; //resolves the url to support tilde chars string reservedPathTrimmed = IOHelper.ResolveUrl(reservedPath.Trim()).Trim().ToLower(); if (reservedPathTrimmed.Length > 0) _newReservedList.Add(reservedPathTrimmed + (reservedPathTrimmed.EndsWith("/") ? "" : "/")); } // use the new list from now on _reservedList = _newReservedList; } } } //The url should be cleaned up before checking: // * If it doesn't contain an '.' in the path then we assume it is a path based URL, if that is the case we should add an trailing '/' because all of our reservedPaths use a trailing '/' // * We shouldn't be comparing the query at all var pathPart = url.Split('?')[0]; if (!pathPart.Contains(".") && !pathPart.EndsWith("/")) { pathPart += "/"; } // return true if url starts with an element of the reserved list return _reservedList.StartsWith(pathPart.ToLowerInvariant()); } /// <summary> /// Structure that checks in logarithmic time /// if a given string starts with one of the added keys. /// </summary> private class StartsWithContainer { /// <summary>Internal sorted list of keys.</summary> public SortedList<string, string> _list = new SortedList<string, string>(StartsWithComparator.Instance); /// <summary> /// Adds the specified new key. /// </summary> /// <param name="newKey">The new key.</param> public void Add(string newKey) { // if the list already contains an element that begins with newKey, return if (String.IsNullOrEmpty(newKey) || StartsWith(newKey)) return; // create a new collection, so the old one can still be accessed SortedList<string, string> newList = new SortedList<string, string>(_list.Count + 1, StartsWithComparator.Instance); // add only keys that don't already start with newKey, others are unnecessary foreach (string key in _list.Keys) if (!key.StartsWith(newKey)) newList.Add(key, null); // add the new key newList.Add(newKey, null); // update the list (thread safe, _list was never in incomplete state) _list = newList; } /// <summary> /// Checks if the given string starts with any of the added keys. /// </summary> /// <param name="target">The target.</param> /// <returns>true if a key is found that matches the start of target</returns> /// <remarks> /// Runs in O(s*log(n)), with n the number of keys and s the length of target. /// </remarks> public bool StartsWith(string target) { return _list.ContainsKey(target); } /// <summary>Comparator that tests if a string starts with another.</summary> /// <remarks>Not a real comparator, since it is not reflexive. (x==y does not imply y==x)</remarks> private sealed class StartsWithComparator : IComparer<string> { /// <summary>Default string comparer.</summary> private readonly static Comparer<string> _stringComparer = Comparer<string>.Default; /// <summary>Gets an instance of the StartsWithComparator.</summary> public static readonly StartsWithComparator Instance = new StartsWithComparator(); /// <summary> /// Tests if whole begins with all characters of part. /// </summary> /// <param name="part">The part.</param> /// <param name="whole">The whole.</param> /// <returns> /// Returns 0 if whole starts with part, otherwise performs standard string comparison. /// </returns> public int Compare(string part, string whole) { // let the default string comparer deal with null or when part is not smaller then whole if (part == null || whole == null || part.Length >= whole.Length) return _stringComparer.Compare(part, whole); ////ensure both have a / on the end //part = part.EndsWith("/") ? part : part + "/"; //whole = whole.EndsWith("/") ? whole : whole + "/"; //if (part.Length >= whole.Length) // return _stringComparer.Compare(part, whole); // loop through all characters that part and whole have in common int pos = 0; bool match; do { match = (part[pos] == whole[pos]); } while (match && ++pos < part.Length); // return result of last comparison return match ? 0 : (part[pos] < whole[pos] ? -1 : 1); } } } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * 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.ComponentModel.Composition; using QuantConnect.Api; using QuantConnect.API; using QuantConnect.Brokerages; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Packets; using QuantConnect.Securities; namespace QuantConnect.Interfaces { /// <summary> /// API for QuantConnect.com /// </summary> [InheritedExport(typeof(IApi))] public interface IApi : IDisposable { /// <summary> /// Initialize the control system /// </summary> void Initialize(int userId, string token, string dataFolder); /// <summary> /// Create a project with the specified name and language via QuantConnect.com API /// </summary> /// <param name="name">Project name</param> /// <param name="language">Programming language to use</param> /// <returns><see cref="ProjectResponse"/> that includes information about the newly created project</returns> ProjectResponse CreateProject(string name, Language language); /// <summary> /// Read in a project from the QuantConnect.com API. /// </summary> /// <param name="projectId">Project id you own</param> /// <returns><see cref="ProjectResponse"/> about a specific project</returns> ProjectResponse ReadProject(int projectId); /// <summary> /// Add a file to a project /// </summary> /// <param name="projectId">The project to which the file should be added</param> /// <param name="name">The name of the new file</param> /// <param name="content">The content of the new file</param> /// <returns><see cref="ProjectFilesResponse"/> that includes information about the newly created file</returns> ProjectFilesResponse AddProjectFile(int projectId, string name, string content); /// <summary> /// Update the name of a file /// </summary> /// <param name="projectId">Project id to which the file belongs</param> /// <param name="oldFileName">The current name of the file</param> /// <param name="newFileName">The new name for the file</param> /// <returns><see cref="RestResponse"/> indicating success</returns> RestResponse UpdateProjectFileName(int projectId, string oldFileName, string newFileName); /// <summary> /// Update the contents of a file /// </summary> /// <param name="projectId">Project id to which the file belongs</param> /// <param name="fileName">The name of the file that should be updated</param> /// <param name="newFileContents">The new contents of the file</param> /// <returns><see cref="RestResponse"/> indicating success</returns> RestResponse UpdateProjectFileContent(int projectId, string fileName, string newFileContents); /// <summary> /// Read a file in a project /// </summary> /// <param name="projectId">Project id to which the file belongs</param> /// <param name="fileName">The name of the file</param> /// <returns><see cref="ProjectFilesResponse"/> that includes the file information</returns> ProjectFilesResponse ReadProjectFile(int projectId, string fileName); /// <summary> /// Read all files in a project /// </summary> /// <param name="projectId">Project id to which the file belongs</param> /// <returns><see cref="ProjectFilesResponse"/> that includes the information about all files in the project</returns> ProjectFilesResponse ReadProjectFiles(int projectId); /// <summary> /// Delete a file in a project /// </summary> /// <param name="projectId">Project id to which the file belongs</param> /// <param name="name">The name of the file that should be deleted</param> /// <returns><see cref="ProjectFilesResponse"/> that includes the information about all files in the project</returns> RestResponse DeleteProjectFile(int projectId, string name); /// <summary> /// Delete a specific project owned by the user from QuantConnect.com /// </summary> /// <param name="projectId">Project id we own and wish to delete</param> /// <returns>RestResponse indicating success</returns> RestResponse DeleteProject(int projectId); /// <summary> /// Read back a list of all projects on the account for a user. /// </summary> /// <returns>Container for list of projects</returns> ProjectResponse ListProjects(); /// <summary> /// Create a new compile job request for this project id. /// </summary> /// <param name="projectId">Project id we wish to compile.</param> /// <returns>Compile object result</returns> Compile CreateCompile(int projectId); /// <summary> /// Read a compile packet job result. /// </summary> /// <param name="projectId">Project id we sent for compile</param> /// <param name="compileId">Compile id return from the creation request</param> /// <returns>Compile object result</returns> Compile ReadCompile(int projectId, string compileId); /// <summary> /// Create a new backtest from a specified projectId and compileId /// </summary> /// <param name="projectId"></param> /// <param name="compileId"></param> /// <param name="backtestName"></param> /// <returns></returns> Backtest CreateBacktest(int projectId, string compileId, string backtestName); /// <summary> /// Read out the full result of a specific backtest /// </summary> /// <param name="projectId">Project id for the backtest we'd like to read</param> /// <param name="backtestId">Backtest id for the backtest we'd like to read</param> /// <returns>Backtest result object</returns> Backtest ReadBacktest(int projectId, string backtestId); /// <summary> /// Update the backtest name /// </summary> /// <param name="projectId">Project id to update</param> /// <param name="backtestId">Backtest id to update</param> /// <param name="backtestName">New backtest name to set</param> /// <param name="backtestNote">Note attached to the backtest</param> /// <returns>Rest response on success</returns> RestResponse UpdateBacktest(int projectId, string backtestId, string backtestName = "", string backtestNote = ""); /// <summary> /// Delete a backtest from the specified project and backtestId. /// </summary> /// <param name="projectId">Project for the backtest we want to delete</param> /// <param name="backtestId">Backtest id we want to delete</param> /// <returns>RestResponse on success</returns> RestResponse DeleteBacktest(int projectId, string backtestId); /// <summary> /// Get a list of backtests for a specific project id /// </summary> /// <param name="projectId">Project id to search</param> /// <returns>BacktestList container for list of backtests</returns> BacktestList ListBacktests(int projectId); /// <summary> /// Gets the logs of a specific live algorithm /// </summary> /// <param name="projectId">Project Id of the live running algorithm</param> /// <param name="algorithmId">Algorithm Id of the live running algorithm</param> /// <param name="startTime">No logs will be returned before this time. Should be in UTC</param> /// <param name="endTime">No logs will be returned after this time. Should be in UTC</param> /// <returns>List of strings that represent the logs of the algorithm</returns> LiveLog ReadLiveLogs(int projectId, string algorithmId, DateTime? startTime = null, DateTime? endTime = null); /// <summary> /// Gets the link to the downloadable data. /// </summary> /// <param name="symbol">Symbol of security of which data will be requested.</param> /// <param name="resolution">Resolution of data requested.</param> /// <param name="date">Date of the data requested.</param> /// <returns>Link to the downloadable data.</returns> Link ReadDataLink(Symbol symbol, Resolution resolution, DateTime date); /// <summary> /// Method to download and save the data purchased through QuantConnect /// </summary> /// <param name="symbol">Symbol of security of which data will be requested.</param> /// <param name="resolution">Resolution of data requested.</param> /// <param name="date">Date of the data requested.</param> /// <returns>A bool indicating whether the data was successfully downloaded or not.</returns> bool DownloadData(Symbol symbol, Resolution resolution, DateTime date); /// <summary> /// Create a new live algorithm for a logged in user. /// </summary> /// <param name="projectId">Id of the project on QuantConnect</param> /// <param name="compileId">Id of the compilation on QuantConnect</param> /// <param name="serverType">Type of server instance that will run the algorithm</param> /// <param name="baseLiveAlgorithmSettings">Brokerage specific <see cref="BaseLiveAlgorithmSettings">BaseLiveAlgorithmSettings</see>.</param> /// <returns>Information regarding the new algorithm <see cref="LiveAlgorithm"/></returns> LiveAlgorithm CreateLiveAlgorithm(int projectId, string compileId, string serverType, BaseLiveAlgorithmSettings baseLiveAlgorithmSettings, string versionId = "-1"); /// <summary> /// Get a list of live running algorithms for a logged in user. /// </summary> /// <param name="status">Filter the statuses of the algorithms returned from the api</param> /// <param name="startTime">Earliest launched time of the algorithms returned by the Api</param> /// <param name="endTime">Latest launched time of the algorithms returned by the Api</param> /// <returns>List of live algorithm instances</returns> LiveList ListLiveAlgorithms(AlgorithmStatus? status = null, DateTime? startTime = null, DateTime? endTime = null); /// <summary> /// Read out a live algorithm in the project id specified. /// </summary> /// <param name="projectId">Project id to read</param> /// <param name="deployId">Specific instance id to read</param> /// <returns>Live object with the results</returns> LiveAlgorithmResults ReadLiveAlgorithm(int projectId, string deployId); /// <summary> /// Liquidate a live algorithm from the specified project. /// </summary> /// <param name="projectId">Project for the live instance we want to stop</param> /// <returns></returns> RestResponse LiquidateLiveAlgorithm(int projectId); /// <summary> /// Stop a live algorithm from the specified project. /// </summary> /// <param name="projectId">Project for the live algo we want to delete</param> /// <returns></returns> RestResponse StopLiveAlgorithm(int projectId); //Status StatusRead(int projectId, string algorithmId); //RestResponse StatusUpdate(int projectId, string algorithmId, AlgorithmStatus status, string message = ""); //LogControl LogAllowanceRead(); //void LogAllowanceUpdate(string backtestId, string url, int length); //void StatisticsUpdate(int projectId, string algorithmId, decimal unrealized, decimal fees, decimal netProfit, decimal holdings, decimal equity, decimal netReturn, decimal volume, int trades, double sharpe); //void NotifyOwner(int projectId, string algorithmId, string subject, string body); //IEnumerable<MarketHoursSegment> MarketHours(int projectId, DateTime time, Symbol symbol); /// <summary> /// Get the algorithm current status, active or cancelled from the user /// </summary> /// <param name="algorithmId"></param> /// <param name="userId">The user id of the algorithm</param> /// <returns></returns> AlgorithmControl GetAlgorithmStatus(string algorithmId, int userId); /// <summary> /// Set the algorithm status from the worker to update the UX e.g. if there was an error. /// </summary> /// <param name="algorithmId">Algorithm id we're setting.</param> /// <param name="status">Status enum of the current worker</param> /// <param name="message">Message for the algorithm status event</param> void SetAlgorithmStatus(string algorithmId, AlgorithmStatus status, string message = ""); /// <summary> /// Send the statistics to storage for performance tracking. /// </summary> /// <param name="algorithmId">Identifier for algorithm</param> /// <param name="unrealized">Unrealized gainloss</param> /// <param name="fees">Total fees</param> /// <param name="netProfit">Net profi</param> /// <param name="holdings">Algorithm holdings</param> /// <param name="equity">Total equity</param> /// <param name="netReturn">Algorithm return</param> /// <param name="volume">Volume traded</param> /// <param name="trades">Total trades since inception</param> /// <param name="sharpe">Sharpe ratio since inception</param> void SendStatistics(string algorithmId, decimal unrealized, decimal fees, decimal netProfit, decimal holdings, decimal equity, decimal netReturn, decimal volume, int trades, double sharpe); /// <summary> /// Market Status Today: REST call. /// </summary> /// <param name="time">The date we need market hours for</param> /// <param name="symbol"></param> /// <returns>Market open hours.</returns> IEnumerable<MarketHoursSegment> MarketToday(DateTime time, Symbol symbol); /// <summary> /// Store logs in the cloud /// </summary> /// <param name="logs">The list of individual logs to be stored</param> /// <param name="job">The <see cref="AlgorithmNodePacket"/> used to generate the url to the logs</param> /// <param name="permissions">The <see cref="StoragePermissions"/> for the file</param> /// <param name="async">Bool indicating whether the method to <see cref="Store"/> should be async</param> /// <returns>The url where the logs can be accessed</returns> string StoreLogs(List<string> logs, AlgorithmNodePacket job, StoragePermissions permissions, bool async = false); /// <summary> /// Store data in the cloud /// </summary> void Store(string data, string location, StoragePermissions permissions, bool async = false); /// <summary> /// Send an email to the user associated with the specified algorithm id /// </summary> /// <param name="algorithmId">The algorithm id</param> /// <param name="subject">The email subject</param> /// <param name="body">The email message body</param> void SendUserEmail(string algorithmId, string subject, string body); /// <summary> /// Adds the specified symbols to the subscription /// </summary> /// <param name="symbols">The symbols to be added keyed by SecurityType</param> void LiveSubscribe(IEnumerable<Symbol> symbols); /// <summary> /// Removes the specified symbols to the subscription /// </summary> /// <param name="symbols">The symbols to be removed keyed by SecurityType</param> void LiveUnsubscribe(IEnumerable<Symbol> symbols); /// <summary> /// Get next ticks if they have arrived from the server. /// </summary> /// <returns>Array of <see cref="BaseData"/></returns> IEnumerable<BaseData> GetLiveData(); } }
using System; using System.Collections.Specialized; using System.Threading.Tasks; using commercetools.Common; using Newtonsoft.Json; namespace commercetools.CustomObjects { /// <summary> /// Provides access to the functions in the CustomObjects section of the API. /// </summary> /// <see href="https://docs.commercetools.com/http-api-projects-custom-objects.html"/> public class CustomObjectManager { #region Constants private const string ENDPOINT_PREFIX = "/custom-objects"; #endregion #region Member Variables private readonly IClient _client; #endregion #region Constructors /// <summary> /// Constructor /// </summary> /// <param name="client">Client</param> public CustomObjectManager(IClient client) { _client = client; } #endregion #region API Methods /// <summary> /// Gets a CustomObject by its ID /// </summary> /// <param name="customObjectId">ID of the custom object</param> /// <returns>CustomObject</returns> /// <see href="https://docs.commercetools.com/http-api-projects-custom-objects.html#get-customobject-by-id"/> public Task<Response<CustomObject<T>>> GetCustomObjectByIdAsync<T>(string customObjectId) { if (string.IsNullOrWhiteSpace(customObjectId)) { throw new ArgumentException("CustomObject ID is required"); } string endpoint = string.Concat(ENDPOINT_PREFIX, "/", customObjectId); return _client.GetAsync<CustomObject<T>>(endpoint); } /// <summary> /// Gets a CustomObject by its container and key /// </summary> /// <param name="container">CustomObject container</param> /// <param name="key">CustomObject key</param> /// <returns>CustomObject</returns> /// <see href="https://docs.commercetools.com/http-api-projects-custom-objects.html#get-customobject-by-container-and-key" /> public Task<Response<CustomObject<T>>> GetCustomObjectByContainerAndKeyAsync<T>(string container, string key) { if (string.IsNullOrWhiteSpace(container)) { throw new ArgumentException("Container is required"); } if (string.IsNullOrWhiteSpace(key)) { throw new ArgumentException("Key is required"); } string endpoint = string.Concat(ENDPOINT_PREFIX, "/", container, "/", key); return _client.GetAsync<CustomObject<T>>(endpoint); } /// <summary> /// Queries for CustomObjects /// </summary> /// <param name="where">Where</param> /// <param name="sort">Sort</param> /// <param name="limit">Limit</param> /// <param name="offset">Offset</param> /// <returns>CustomObjectQueryResult</returns> /// <see href="https://docs.commercetools.com/http-api-projects-custom-objects.html#query-customobjects" /> public Task<Response<CustomObjectQueryResult<T>>> QueryCustomObjectsAsync<T>(string where = null, string sort = null, int limit = -1, int offset = -1) { NameValueCollection values = new NameValueCollection(); if (!string.IsNullOrWhiteSpace(where)) { values.Add("where", where); } if (!string.IsNullOrWhiteSpace(sort)) { values.Add("sort", sort); } if (limit > 0) { values.Add("limit", limit.ToString()); } if (offset >= 0) { values.Add("offset", offset.ToString()); } return _client.GetAsync<CustomObjectQueryResult<T>>(ENDPOINT_PREFIX, values); } /// <summary> /// Creates or updates a CustomObject. /// /// If a CustomObject with the same key already exists, it is updated. Otherwise, it is created. /// </summary> /// <param name="customObjectDraft">CustomObjectDraft</param> /// <returns>CustomObject</returns> /// <see href="https://docs.commercetools.com/http-api-projects-custom-objects.html#create-or-update-a-customobject" /> public Task<Response<CustomObject<T>>> CreateOrUpdateCustomObjectAsync<T>(CustomObjectDraft<T> customObjectDraft) { if (string.IsNullOrWhiteSpace(customObjectDraft.Container)) { throw new ArgumentException("Container is required"); } if (string.IsNullOrWhiteSpace(customObjectDraft.Key)) { throw new ArgumentException("Key is required"); } if (customObjectDraft.Value == null) { throw new ArgumentException("Value is required"); } string payload = JsonConvert.SerializeObject(customObjectDraft, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); return _client.PostAsync<CustomObject<T>>(ENDPOINT_PREFIX, payload); } /// <summary> /// Deletes a CustomObject /// </summary> /// <param name="customObject">CustomObject to delete</param> /// <param name="dataErasure">Whether or not to erase data</param> /// <returns>CustomObject</returns> /// <see href="https://docs.commercetools.com/http-api-projects-custom-objects.html#delete-customobject-by-id" /> public Task<Response<CustomObject<T>>> DeleteCustomObjectAsync<T>(CustomObject<T> customObject, bool dataErasure = false) { return DeleteCustomObjectAsync<T>(customObject.Id, customObject.Version, dataErasure); } /// <summary> /// Deletes a CustomObject /// </summary> /// <param name="customObjectId">CustomObject ID</param> /// <param name="version">CustomObject version</param> /// <param name="dataErasure">Whether or not to erase data</param> /// <returns>CustomObject</returns> /// <see href="https://docs.commercetools.com/http-api-projects-custom-objects.html#delete-customobject-by-id" /> public Task<Response<CustomObject<T>>> DeleteCustomObjectAsync<T>(string customObjectId, int? version = null, bool dataErasure = false) { if (string.IsNullOrWhiteSpace(customObjectId)) { throw new ArgumentException("CustomObject ID is required"); } NameValueCollection values = new NameValueCollection(); if (version != null && version >= 1) { values.Add(nameof(version), version.ToString()); } if (dataErasure) { values.Add(nameof(dataErasure), dataErasure.ToString()); } string endpoint = string.Concat(ENDPOINT_PREFIX, "/", customObjectId); return _client.DeleteAsync<CustomObject<T>>(endpoint, values); } /// <summary> /// Deletes a CustomObject /// </summary> /// <param name="container">CustomObject container</param> /// <param name="key">CustomObject key</param> /// <param name="dataErasure">Whether or not to erase data</param> /// <returns>CustomObject</returns> /// <see href="https://docs.commercetools.com/http-api-projects-custom-objects.html#delete-customobject-by-container-and-key" /> public Task<Response<CustomObject<T>>> DeleteCustomObjectByContainerAndKeyAsync<T>(string container, string key, bool dataErasure = false) { if (string.IsNullOrWhiteSpace(container)) { throw new ArgumentException("Container is required"); } if (string.IsNullOrWhiteSpace(key)) { throw new ArgumentException("Key is required"); } NameValueCollection values = new NameValueCollection(); if (dataErasure) { values.Add(nameof(dataErasure), dataErasure.ToString()); } string endpoint = string.Concat(ENDPOINT_PREFIX, "/", container, "/", key); return _client.DeleteAsync<CustomObject<T>>(endpoint, values); } #endregion } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using OpenTK; using OpenTK.Graphics; using osu.Framework.Allocation; using osu.Framework.Configuration; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osu.Game.Overlays; using osu.Framework.Graphics.UserInterface; using osu.Game.Graphics.UserInterface; using osu.Framework.Graphics.Cursor; using osu.Game.Graphics.Containers; using osu.Game.Overlays.Profile; namespace osu.Game.Users { public class UserPanel : OsuClickableContainer, IHasContextMenu { private readonly User user; private const float height = 100; private const float content_padding = 10; private const float status_height = 30; private Container statusBar; private Box statusBg; private OsuSpriteText statusMessage; private Container content; protected override Container<Drawable> Content => content; public readonly Bindable<UserStatus> Status = new Bindable<UserStatus>(); public new Action Action; protected Action ViewProfile; public UserPanel(User user) { if (user == null) throw new ArgumentNullException(nameof(user)); this.user = user; Height = height - status_height; } [BackgroundDependencyLoader(permitNulls: true)] private void load(OsuColour colours, UserProfileOverlay profile) { if (colours == null) throw new ArgumentNullException(nameof(colours)); FillFlowContainer infoContainer; AddInternal(content = new Container { RelativeSizeAxes = Axes.Both, Masking = true, CornerRadius = 5, EdgeEffect = new EdgeEffectParameters { Type = EdgeEffectType.Shadow, Colour = Color4.Black.Opacity(0.25f), Radius = 4, }, Children = new Drawable[] { new DelayedLoadWrapper(new UserCoverBackground(user) { RelativeSizeAxes = Axes.Both, Anchor = Anchor.Centre, Origin = Anchor.Centre, FillMode = FillMode.Fill, OnLoadComplete = d => d.FadeInFromZero(400, Easing.Out) }, 300) { RelativeSizeAxes = Axes.Both }, new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.Black.Opacity(0.7f), }, new Container { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Padding = new MarginPadding { Top = content_padding, Horizontal = content_padding }, Children = new Drawable[] { new UpdateableAvatar { Size = new Vector2(height - status_height - content_padding * 2), User = user, Masking = true, CornerRadius = 5, EdgeEffect = new EdgeEffectParameters { Type = EdgeEffectType.Shadow, Colour = Color4.Black.Opacity(0.25f), Radius = 4, }, }, new Container { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Left = height - status_height - content_padding }, Children = new Drawable[] { new OsuSpriteText { Text = user.Username, TextSize = 18, Font = @"Exo2.0-SemiBoldItalic", }, infoContainer = new FillFlowContainer { Anchor = Anchor.BottomLeft, Origin = Anchor.BottomLeft, AutoSizeAxes = Axes.X, Height = 20f, Direction = FillDirection.Horizontal, Spacing = new Vector2(5f, 0f), Children = new Drawable[] { new DrawableFlag(user.Country) { Width = 30f, RelativeSizeAxes = Axes.Y, }, }, }, }, }, }, }, statusBar = new Container { Anchor = Anchor.BottomLeft, Origin = Anchor.BottomLeft, RelativeSizeAxes = Axes.X, Alpha = 0f, Children = new Drawable[] { statusBg = new Box { RelativeSizeAxes = Axes.Both, Alpha = 0.5f, }, new FillFlowContainer { Anchor = Anchor.Centre, Origin = Anchor.Centre, AutoSizeAxes = Axes.Both, Spacing = new Vector2(5f, 0f), Children = new Drawable[] { new SpriteIcon { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Icon = FontAwesome.fa_circle_o, Shadow = true, Size = new Vector2(14), }, statusMessage = new OsuSpriteText { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Font = @"Exo2.0-Semibold", }, }, }, }, }, } }); if (user.IsSupporter) { infoContainer.Add(new SupporterIcon { RelativeSizeAxes = Axes.Y, Width = 20f, }); } Status.ValueChanged += displayStatus; Status.ValueChanged += status => statusBg.FadeColour(status?.GetAppropriateColour(colours) ?? colours.Gray5, 500, Easing.OutQuint); base.Action = ViewProfile = () => { Action?.Invoke(); profile?.ShowUser(user); }; } protected override void LoadComplete() { base.LoadComplete(); Status.TriggerChange(); } private void displayStatus(UserStatus status) { const float transition_duration = 500; if (status == null) { statusBar.ResizeHeightTo(0f, transition_duration, Easing.OutQuint); statusBar.FadeOut(transition_duration, Easing.OutQuint); this.ResizeHeightTo(height - status_height, transition_duration, Easing.OutQuint); } else { statusBar.ResizeHeightTo(status_height, transition_duration, Easing.OutQuint); statusBar.FadeIn(transition_duration, Easing.OutQuint); this.ResizeHeightTo(height, transition_duration, Easing.OutQuint); statusMessage.Text = status.Message; } } public MenuItem[] ContextMenuItems => new MenuItem[] { new OsuMenuItem("View Profile", MenuItemType.Highlighted, ViewProfile), }; } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows.Forms; using Zutatensuppe.D2Reader.Models; using Zutatensuppe.DiabloInterface.Gui.Controls; using Zutatensuppe.DiabloInterface.Gui.Forms; using System.Reflection; using Zutatensuppe.DiabloInterface.Lib.Services; using Zutatensuppe.DiabloInterface.Lib; namespace Zutatensuppe.DiabloInterface.Gui { public class MainWindow : WsExCompositedForm { static readonly Lib.ILogger Logger = Lib.Logging.CreateLogger(MethodBase.GetCurrentMethod().DeclaringType); private readonly IDiabloInterface di; private ToolStripMenuItem loadConfigMenuItem; private Form debugWindow; private AbstractLayout layout; public MainWindow(IDiabloInterface di) { this.di = di; Logger.Info("Creating main window."); RegisterServiceEventHandlers(); InitializeComponent(); PopulateConfigFileListContextMenu(this.di.configService.ConfigFileCollection); ApplyConfig(this.di.configService.CurrentConfig); } void RegisterServiceEventHandlers() { di.configService.Changed += ConfigChanged; di.configService.CollectionChanged += ConfigCollectionChanged; } void UnregisterServiceEventHandlers() { di.configService.Changed -= ConfigChanged; di.configService.CollectionChanged -= ConfigCollectionChanged; } void ConfigChanged(object sender, ApplicationConfigEventArgs e) { if (InvokeRequired) { Invoke((Action)(() => ConfigChanged(sender, e))); return; } ApplyConfig(e.Config); } void ConfigCollectionChanged(object sender, ConfigCollectionEventArgs e) { if (InvokeRequired) { Invoke((Action)(() => ConfigCollectionChanged(sender, e))); return; } PopulateConfigFileListContextMenu(e.Collection); } private void InitializeComponent() { var difficultyItem = new ToolStripMenuItem(); foreach (GameDifficulty diff in Enum.GetValues(typeof(GameDifficulty))) { var item = new ToolStripMenuItem(); item.Checked = difficultyItem.DropDownItems.Count == 0; item.Text = Enum.GetName(typeof(GameDifficulty), diff); item.Click += (object s, EventArgs e) => GameDifficultyClick(s, diff); difficultyItem.DropDownItems.Add(item); } difficultyItem.Text = "Difficulty"; var configItem = new ToolStripMenuItem(); configItem.Image = Properties.Resources.wrench_orange; configItem.ShortcutKeys = Keys.Control | Keys.U; configItem.Text = "Config"; configItem.Click += new EventHandler(ConfigMenuItemOnClick); var resetItem = new ToolStripMenuItem(); resetItem.Image = Properties.Resources.arrow_refresh; resetItem.ShortcutKeys = Keys.Control | Keys.R; resetItem.Text = "Reset"; resetItem.Click += new EventHandler(ResetMenuItemOnClick); var debugItem = new ToolStripMenuItem(); debugItem.Image = Properties.Resources.bug; debugItem.Text = "Debug"; debugItem.Click += new EventHandler(DebugMenuItemOnClick); var exitItem = new ToolStripMenuItem(); exitItem.Image = Properties.Resources.cross; exitItem.Text = "Exit"; exitItem.Click += new EventHandler(ExitMenuItemOnClick); var copySeedItem = new ToolStripMenuItem(); copySeedItem.Text = "Copy current seed"; copySeedItem.Click += new EventHandler(CopySeedItemOnClick); loadConfigMenuItem = new ToolStripMenuItem(); loadConfigMenuItem.Text = "Load Config"; var contextMenu = new ContextMenuStrip(); contextMenu.Items.AddRange(new ToolStripItem[] { difficultyItem, copySeedItem, configItem, loadConfigMenuItem, resetItem, debugItem, exitItem }); AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); AutoScaleMode = AutoScaleMode.Font; AutoSize = true; AutoSizeMode = AutoSizeMode.GrowAndShrink; BackColor = System.Drawing.Color.Black; ClientSize = new System.Drawing.Size(730, 514); ContextMenuStrip = contextMenu; Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 238); FormBorderStyle = FormBorderStyle.FixedSingle; Icon = Properties.Resources.di; MaximizeBox = false; MinimizeBox = false; Text = $@"DiabloInterface v{Application.ProductVersion}"; } void ApplyConfig(ApplicationConfig config) { // nothing to do if correct layout already if (layout is HorizontalLayout && config.DisplayLayoutHorizontal) return; // remove old layout if (layout != null) { Controls.Remove(layout); layout.Dispose(); layout = null; } // create new layout var nextLayout = config.DisplayLayoutHorizontal ? new HorizontalLayout(di) as AbstractLayout : new VerticalLayout(di); Controls.Add(nextLayout); layout = nextLayout; } void PopulateConfigFileListContextMenu(IEnumerable<FileInfo> configFileCollection) { var items = configFileCollection.Select(CreateConfigToolStripMenuItem).ToArray(); loadConfigMenuItem.DropDownItems.Clear(); loadConfigMenuItem.DropDownItems.AddRange(items); } ToolStripMenuItem CreateConfigToolStripMenuItem(FileInfo f) { var item = new ToolStripMenuItem(); item.Text = Path.GetFileNameWithoutExtension(f.Name); item.Click += (object s, EventArgs e) => LoadConfigFile(s, f.FullName); return item; } void LoadConfigFile(object sender, string fileName) { // TODO: LoadSettings should throw a custom Exception with information about why this happened. if (!di.configService.Load(fileName)) { Logger.Error($"Failed to load config from file: {fileName}."); MessageBox.Show( $@"Failed to load config.{Environment.NewLine}See the error log for more details.", @"Config Error", MessageBoxButtons.OK, MessageBoxIcon.Error ); } } void ExitMenuItemOnClick(object sender, EventArgs e) { Close(); } void CopySeedItemOnClick(object sender, EventArgs e) { if (di?.game?.DataReader?.Game?.Seed == null) { MessageBox.Show( $@"No seed available.", @"Info", MessageBoxButtons.OK, MessageBoxIcon.Information ); return; } Clipboard.SetText($"{di.game.DataReader.Game.Seed}"); MessageBox.Show( $@"Seed {di.game.DataReader.Game.Seed} copied.", @"Success", MessageBoxButtons.OK, MessageBoxIcon.Information ); } void ResetMenuItemOnClick(object sender, EventArgs e) { di.plugins.Reset(); layout?.Reset(); } void ConfigMenuItemOnClick(object sender, EventArgs e) { using (var window = new ConfigWindow(di)) window.ShowDialog(); } void DebugMenuItemOnClick(object sender, EventArgs e) { if (debugWindow == null || debugWindow.IsDisposed) debugWindow = new DebugWindow(di); debugWindow.Show(); } void GameDifficultyClick(object sender, GameDifficulty difficulty) { Logger.Info($"Setting target difficulty to {difficulty}."); var clicked = (ToolStripMenuItem)sender; var parent = (ToolStripMenuItem)clicked.OwnerItem; foreach (ToolStripMenuItem item in parent.DropDownItems) item.Checked = item == clicked; di.game.TargetDifficulty = difficulty; } protected override void OnFormClosing(FormClosingEventArgs e) { UnregisterServiceEventHandlers(); base.OnFormClosing(e); } } }
using System; using System.Linq; using System.Collections.Generic; using SharpDX.Direct2D1; using SharpDX; using SharpDX.DXGI; using System.Runtime.InteropServices; using SharpDX.DirectWrite; using Engine; using DWriteFactory = SharpDX.DirectWrite.Factory; using System.Diagnostics; using Engine.Assets.FontLoader; using System.IO; using System.Collections.Concurrent; using Engine.Interface; namespace Engine.Assets { public class AssetManager : IAssetManager { private struct FontDescription { public string Name; public float Size; public FontDescription(string name, float size) { Name = name; Size = size; } } private struct BitmapBrushDescription { public Bitmap Bitmap; public BitmapBrushProperties? BitmapBrushProps; public BrushProperties? BrushProps; public BitmapBrushDescription(Bitmap bitmap, BitmapBrushProperties? bitmapProps, BrushProperties? brushProps) { Bitmap = bitmap; BitmapBrushProps = bitmapProps; BrushProps = brushProps; } } private static string _rootDirectory = AppDomain.CurrentDomain.BaseDirectory; public static string RootDirectory { get { return _rootDirectory; } set { if(!value.EndsWith("/")) value += '/'; _rootDirectory = AppDomain.CurrentDomain.BaseDirectory + '/' + value; } } private static readonly ConcurrentDictionary<Color, SolidColorBrush> _solidColorBrushResources = new ConcurrentDictionary<Color, SolidColorBrush>(); private static readonly ConcurrentDictionary<string, Bitmap> _bitmapResources = new ConcurrentDictionary<string, Bitmap>(); private static readonly ConcurrentDictionary<FontDescription, TextFormat> _fontResources = new ConcurrentDictionary<FontDescription, TextFormat>(); private static AssetManager _singleton; private ResourceFontCollectionLoader _fontLoader; private RenderTarget _renderTarget2D; public RenderTarget RenderTarget2D { get { return _renderTarget2D; } } public SharpDX.Direct2D1.Factory Factory2D { get { return _renderTarget2D.Factory; } } private DWriteFactory _dwriteFactory; private const string FallbackFontFamilyName = "Comic Sans MS"; private FontCollection _embeddedFonts; private FontCollection _systemFonts; public bool IsDisposed { get; private set; } internal AssetManager(RenderTarget renderTarget2D) : base() { Debug.Assert(renderTarget2D != null, "RenderTarget should not be null"); if(_singleton != null) _singleton.Dispose(); _renderTarget2D = renderTarget2D; _dwriteFactory = new DWriteFactory(); _singleton = this; _loadFontResources(); IsDisposed = false; } ~AssetManager() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposeManagedResources) { IsDisposed = true; if (_fontLoader != null && !_fontLoader.IsDisposed) _fontLoader.Dispose(); if (_embeddedFonts != null && !_embeddedFonts.IsDisposed) _embeddedFonts.Dispose(); if (_systemFonts != null && !_systemFonts.IsDisposed) _systemFonts.Dispose(); if (_dwriteFactory != null && !_dwriteFactory.IsDisposed) _dwriteFactory.Dispose(); foreach (Bitmap bitmap in _bitmapResources.Values) { if (!bitmap.IsDisposed) bitmap.Dispose(); } _bitmapResources.Clear(); foreach (TextFormat font in _fontResources.Values) { if (!font.IsDisposed) font.Dispose(); } _fontResources.Clear(); foreach (SolidColorBrush brush in _solidColorBrushResources.Values) { if (!brush.IsDisposed) brush.Dispose(); } _solidColorBrushResources.Clear(); } private void _loadFontResources() { _fontLoader = new ResourceFontCollectionLoader(_dwriteFactory); _embeddedFonts = new FontCollection(_dwriteFactory, _fontLoader, _fontLoader.Key); _systemFonts = _dwriteFactory.GetSystemFontCollection(true); } TextureAsset IAssetManager.LoadTexture(string file) { Bitmap result = null; if (_bitmapResources.TryGetValue(file, out result) && !result.IsDisposed) return new TextureAsset(result); Stream stream; if (File.Exists(RootDirectory + file)) stream = File.OpenRead(RootDirectory + file); else if (File.Exists(file)) stream = File.OpenRead(file); else { stream = (from assembly in AppDomain.CurrentDomain.GetAssemblies() from name in assembly.GetManifestResourceNames() where String.Compare(file, name, true) != 0 select assembly.GetManifestResourceStream(name)).FirstOrDefault(); } if (stream == null) { Console.Error.WriteLine("Failed to load bitmap asset: {0}", file); // TODO: Have some sort of placeholder texture to feed back, even a single pixel return null; } try { using (var newBitmap = new System.Drawing.Bitmap(stream)) { var sourceArea = new System.Drawing.Rectangle(0, 0, newBitmap.Width, newBitmap.Height); var bitmapProperties = new BitmapProperties(new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied)); var size = new DrawingSize(newBitmap.Width, newBitmap.Height); // Transform pixels from BGRA to RGBA int stride = newBitmap.Width * sizeof(int); using (var tempStream = new DataStream(newBitmap.Height * stride, true, true)) { // Lock System.Drawing.Bitmap var bitmapData = newBitmap.LockBits(sourceArea, System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); // Convert all pixels for (int y = 0; y < newBitmap.Height; y++) { int offset = bitmapData.Stride * y; for (int x = 0; x < newBitmap.Width; x++) { // Not optimized byte B = Marshal.ReadByte(bitmapData.Scan0, offset++); byte G = Marshal.ReadByte(bitmapData.Scan0, offset++); byte R = Marshal.ReadByte(bitmapData.Scan0, offset++); byte A = Marshal.ReadByte(bitmapData.Scan0, offset++); int rgba = R | (G << 8) | (B << 16) | (A << 24); tempStream.Write(rgba); } } newBitmap.UnlockBits(bitmapData); tempStream.Position = 0; try { result = new Bitmap(_renderTarget2D, size, tempStream, stride, bitmapProperties); } catch (NullReferenceException) { throw new AssetLoadException("Graphics device uninitialized"); } } } } catch (ArgumentException) { Console.Error.WriteLine("Invalid data stream while loading bitmap data"); } finally { stream.Dispose(); } _bitmapResources.AddOrUpdate(file, result, (key, oldValue) => { if (!oldValue.IsDisposed) oldValue.Dispose(); return result; }); return new TextureAsset(result); } FontAsset IAssetManager.LoadFont(string assetName, float fontSize, FontWeight weight, FontStyle style, FontStretch stretch) { Debug.Assert(!String.IsNullOrEmpty(assetName), "Must provide a valid font name"); Debug.Assert(fontSize > .9999, "Font size must be larger than 1"); var desc = new FontDescription(assetName, fontSize); TextFormat font; if (_fontResources.TryGetValue(desc, out font) && !font.IsDisposed) return new FontAsset(font); FontCollection collection; int i = 0; if (_embeddedFonts.FindFamilyName(assetName, out i)) { collection = _embeddedFonts; } else if (_systemFonts.FindFamilyName(assetName, out i)) { collection = _systemFonts; } else { collection = _systemFonts; assetName = FallbackFontFamilyName; } font = new TextFormat( _dwriteFactory, assetName, collection, weight, style, stretch, fontSize); _fontResources.AddOrUpdate(desc, font, (key, oldValue) => { if (!oldValue.IsDisposed) oldValue.Dispose(); return font; }); return new FontAsset(font); } TextLayout IAssetManager.MakeTextLayout(TextFormat textFormat, string text, float maxWidth, float maxHeight) { System.Diagnostics.Debug.Assert(textFormat != null && !textFormat.IsDisposed, "Can not create layout from null or disposed TextFormat"); return new TextLayout(_dwriteFactory, text, textFormat, maxWidth, maxHeight); } BrushAsset IAssetManager.LoadBrush(Color color) { SolidColorBrush brush; if (_solidColorBrushResources.TryGetValue(color, out brush) && !brush.IsDisposed) return new BrushAsset(brush); brush = new SolidColorBrush(RenderTarget2D, color); _solidColorBrushResources.AddOrUpdate(color, brush, (key, oldValue) => { if(!oldValue.IsDisposed) oldValue.Dispose(); return brush; }); return new BrushAsset(brush); } BrushAsset IAssetManager.LoadBrush(Bitmap bitmap, BitmapBrushProperties? bitmapBrushProps, BrushProperties? brushProps) { /// TODFO: THis needs to be finished!!!! BitmapBrush brush = new BitmapBrush(RenderTarget2D, bitmap, bitmapBrushProps, brushProps); return new BrushAsset(brush); } } [Serializable] public class AssetLoadException : Exception { public AssetLoadException(string msg) : base(msg) { } } }
// 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.Diagnostics; using System.Net.Security; using System.Runtime.InteropServices; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography; using System.Text; using Microsoft.Win32.SafeHandles; internal static partial class Interop { internal static partial class Ssl { internal delegate int SslCtxSetVerifyCallback(int preverify_ok, IntPtr x509_ctx); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EnsureLibSslInitialized")] internal static extern void EnsureLibSslInitialized(); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslV2_3Method")] internal static extern IntPtr SslV2_3Method(); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslV3Method")] internal static extern IntPtr SslV3Method(); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_TlsV1Method")] internal static extern IntPtr TlsV1Method(); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_TlsV1_1Method")] internal static extern IntPtr TlsV1_1Method(); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_TlsV1_2Method")] internal static extern IntPtr TlsV1_2Method(); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslCreate")] internal static extern SafeSslHandle SslCreate(SafeSslContextHandle ctx); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetError")] internal static extern SslErrorCode SslGetError(SafeSslHandle ssl, int ret); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetError")] internal static extern SslErrorCode SslGetError(IntPtr ssl, int ret); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslDestroy")] internal static extern void SslDestroy(IntPtr ssl); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetConnectState")] internal static extern void SslSetConnectState(SafeSslHandle ssl); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetAcceptState")] internal static extern void SslSetAcceptState(SafeSslHandle ssl); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetVersion")] private static extern IntPtr SslGetVersion(SafeSslHandle ssl); internal static string GetProtocolVersion(SafeSslHandle ssl) { return Marshal.PtrToStringAnsi(SslGetVersion(ssl)); } [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetSslConnectionInfo")] internal static extern bool GetSslConnectionInfo( SafeSslHandle ssl, out int dataCipherAlg, out int keyExchangeAlg, out int dataHashAlg, out int dataKeySize, out int hashKeySize); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslWrite")] internal static unsafe extern int SslWrite(SafeSslHandle ssl, byte* buf, int num); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslRead")] internal static extern int SslRead(SafeSslHandle ssl, byte[] buf, int num); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_IsSslRenegotiatePending")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool IsSslRenegotiatePending(SafeSslHandle ssl); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslShutdown")] internal static extern int SslShutdown(IntPtr ssl); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetBio")] internal static extern void SslSetBio(SafeSslHandle ssl, SafeBioHandle rbio, SafeBioHandle wbio); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslDoHandshake")] internal static extern int SslDoHandshake(SafeSslHandle ssl); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_IsSslStateOK")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool IsSslStateOK(SafeSslHandle ssl); // NOTE: this is just an (unsafe) overload to the BioWrite method from Interop.Bio.cs. [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BioWrite")] internal static unsafe extern int BioWrite(SafeBioHandle b, byte* data, int len); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetPeerCertificate")] internal static extern SafeX509Handle SslGetPeerCertificate(SafeSslHandle ssl); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetPeerCertChain")] internal static extern SafeSharedX509StackHandle SslGetPeerCertChain(SafeSslHandle ssl); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetPeerFinished")] internal static extern int SslGetPeerFinished(SafeSslHandle ssl, IntPtr buf, int count); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetFinished")] internal static extern int SslGetFinished(SafeSslHandle ssl, IntPtr buf, int count); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSessionReused")] internal static extern bool SslSessionReused(SafeSslHandle ssl); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslAddExtraChainCert")] internal static extern bool SslAddExtraChainCert(SafeSslHandle ssl, SafeX509Handle x509); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetClientCAList")] private static extern SafeSharedX509NameStackHandle SslGetClientCAList_private(SafeSslHandle ssl); internal static SafeSharedX509NameStackHandle SslGetClientCAList(SafeSslHandle ssl) { Crypto.CheckValidOpenSslHandle(ssl); SafeSharedX509NameStackHandle handle = SslGetClientCAList_private(ssl); if (!handle.IsInvalid) { handle.SetParent(ssl); } return handle; } internal static class SslMethods { internal static readonly IntPtr TLSv1_method = TlsV1Method(); internal static readonly IntPtr TLSv1_1_method = TlsV1_1Method(); internal static readonly IntPtr TLSv1_2_method = TlsV1_2Method(); internal static readonly IntPtr SSLv3_method = SslV3Method(); internal static readonly IntPtr SSLv23_method = SslV2_3Method(); } internal enum SslErrorCode { SSL_ERROR_NONE = 0, SSL_ERROR_SSL = 1, SSL_ERROR_WANT_READ = 2, SSL_ERROR_WANT_WRITE = 3, SSL_ERROR_SYSCALL = 5, SSL_ERROR_ZERO_RETURN = 6, // NOTE: this SslErrorCode value doesn't exist in OpenSSL, but // we use it to distinguish when a renegotiation is pending. // Choosing an arbitrarily large value that shouldn't conflict // with any actual OpenSSL error codes SSL_ERROR_RENEGOTIATE = 29304 } } } namespace Microsoft.Win32.SafeHandles { internal sealed class SafeSslHandle : SafeHandle { private SafeBioHandle _readBio; private SafeBioHandle _writeBio; private bool _isServer; private bool _handshakeCompleted = false; public bool IsServer { get { return _isServer; } } public SafeBioHandle InputBio { get { return _readBio; } } public SafeBioHandle OutputBio { get { return _writeBio; } } internal void MarkHandshakeCompleted() { _handshakeCompleted = true; } public static SafeSslHandle Create(SafeSslContextHandle context, bool isServer) { SafeBioHandle readBio = Interop.Crypto.CreateMemoryBio(); if (readBio.IsInvalid) { return new SafeSslHandle(); } SafeBioHandle writeBio = Interop.Crypto.CreateMemoryBio(); if (writeBio.IsInvalid) { readBio.Dispose(); return new SafeSslHandle(); } SafeSslHandle handle = Interop.Ssl.SslCreate(context); if (handle.IsInvalid) { readBio.Dispose(); writeBio.Dispose(); return handle; } handle._isServer = isServer; // After SSL_set_bio, the BIO handles are owned by SSL pointer // and are automatically freed by SSL_free. To prevent a double // free, we need to keep the ref counts bumped up till SSL_free bool gotRef = false; readBio.DangerousAddRef(ref gotRef); try { bool ignore = false; writeBio.DangerousAddRef(ref ignore); } catch { if (gotRef) { readBio.DangerousRelease(); } throw; } Interop.Ssl.SslSetBio(handle, readBio, writeBio); handle._readBio = readBio; handle._writeBio = writeBio; if (isServer) { Interop.Ssl.SslSetAcceptState(handle); } else { Interop.Ssl.SslSetConnectState(handle); } return handle; } public override bool IsInvalid { get { return handle == IntPtr.Zero; } } protected override bool ReleaseHandle() { if (_handshakeCompleted) { Disconnect(); } Interop.Ssl.SslDestroy(handle); if (_readBio != null) { _readBio.SetHandleAsInvalid(); // BIO got freed in SslDestroy } if (_writeBio != null) { _writeBio.SetHandleAsInvalid(); // BIO got freed in SslDestroy } return true; } private void Disconnect() { Debug.Assert(!IsInvalid, "Expected a valid context in Disconnect"); // Because we set "quiet shutdown" on the SSL_CTX, SslShutdown is supposed // to always return 1 (completed success). In "close-notify" shutdown (the // opposite of quiet) there's also 0 (incomplete success) and negative // (probably async IO WANT_READ/WANT_WRITE, but need to check) return codes // to handle. // // If quiet shutdown is ever not set, see // https://www.openssl.org/docs/manmaster/ssl/SSL_shutdown.html // for guidance on how to rewrite this method. int retVal = Interop.Ssl.SslShutdown(handle); Debug.Assert(retVal == 1); } private SafeSslHandle() : base(IntPtr.Zero, true) { } internal SafeSslHandle(IntPtr validSslPointer, bool ownsHandle) : base(IntPtr.Zero, ownsHandle) { handle = validSslPointer; } } internal sealed class SafeChannelBindingHandle : SafeHandle { [StructLayout(LayoutKind.Sequential)] private struct SecChannelBindings { internal int InitiatorLength; internal int InitiatorOffset; internal int AcceptorAddrType; internal int AcceptorLength; internal int AcceptorOffset; internal int ApplicationDataLength; internal int ApplicationDataOffset; } private const int CertHashMaxSize = 128; private static readonly byte[] s_tlsServerEndPointByteArray = Encoding.UTF8.GetBytes("tls-server-end-point:"); private static readonly byte[] s_tlsUniqueByteArray = Encoding.UTF8.GetBytes("tls-unique:"); private static readonly int s_secChannelBindingSize = Marshal.SizeOf<SecChannelBindings>(); private readonly int _cbtPrefixByteArraySize; internal int Length { get; private set; } internal IntPtr CertHashPtr { get; private set; } internal void SetCertHash(byte[] certHashBytes) { Debug.Assert(certHashBytes != null, "check certHashBytes is not null"); Debug.Assert(certHashBytes.Length <= CertHashMaxSize); int length = certHashBytes.Length; Marshal.Copy(certHashBytes, 0, CertHashPtr, length); SetCertHashLength(length); } private byte[] GetPrefixBytes(ChannelBindingKind kind) { Debug.Assert(kind == ChannelBindingKind.Endpoint || kind == ChannelBindingKind.Unique); return kind == ChannelBindingKind.Endpoint ? s_tlsServerEndPointByteArray : s_tlsUniqueByteArray; } internal SafeChannelBindingHandle(ChannelBindingKind kind) : base(IntPtr.Zero, true) { byte[] cbtPrefix = GetPrefixBytes(kind); _cbtPrefixByteArraySize = cbtPrefix.Length; handle = Marshal.AllocHGlobal(s_secChannelBindingSize + _cbtPrefixByteArraySize + CertHashMaxSize); IntPtr cbtPrefixPtr = handle + s_secChannelBindingSize; Marshal.Copy(cbtPrefix, 0, cbtPrefixPtr, _cbtPrefixByteArraySize); CertHashPtr = cbtPrefixPtr + _cbtPrefixByteArraySize; Length = CertHashMaxSize; } internal void SetCertHashLength(int certHashLength) { int cbtLength = _cbtPrefixByteArraySize + certHashLength; Length = s_secChannelBindingSize + cbtLength; SecChannelBindings channelBindings = new SecChannelBindings() { ApplicationDataLength = cbtLength, ApplicationDataOffset = s_secChannelBindingSize }; Marshal.StructureToPtr(channelBindings, handle, true); } public override bool IsInvalid => handle == IntPtr.Zero; protected override bool ReleaseHandle() { Marshal.FreeHGlobal(handle); SetHandle(IntPtr.Zero); return true; } } }
using UnityEngine; using UnityEditor; using System; using System.Collections; using System.Collections.Generic; public class AkWwiseProjectData : ScriptableObject { [Serializable] public class ByteArrayWrapper { public ByteArrayWrapper(byte[] byteArray) { bytes = byteArray; } public byte[] bytes; } [Serializable] public class AkInformation { public string Name; public string Path; public List<PathElement> PathAndIcons = new List<PathElement>(); public int ID; public byte[] Guid = null; } [Serializable] public class GroupValue : AkInformation { public List<string> values = new List<string>(); public List<PathElement> ValueIcons = new List<PathElement>(); public List<int> valueIDs = new List<int>(); //Unity can't serialize a list of arrays. So we create a serializable wrapper class for our array public List<ByteArrayWrapper> ValueGuids = new List<ByteArrayWrapper>(); } [Serializable] public class Event : AkInformation { public float maxAttenuation; } [Serializable] public class WorkUnit : IComparable { public WorkUnit(){} public WorkUnit(string in_physicalPath) { PhysicalPath = in_physicalPath; } public string PhysicalPath; public string ParentPhysicalPath; public string Guid; public int CompareTo( object other ) { WorkUnit otherWwu = other as WorkUnit; return PhysicalPath.CompareTo (otherWwu.PhysicalPath); } //DateTime Objects are not serializable, so we have to use its binary format (64 bit long). //But apparently long isn't serializable neither, so we split it into two int [SerializeField] private int m_lastTimePsrt1 = 0; [SerializeField] private int m_lastTimePart2 = 0; public void SetLastTime(DateTime in_time) { long timeBin = in_time.ToBinary(); m_lastTimePsrt1 = (int)timeBin; m_lastTimePart2 = (int)(timeBin >> 32); } public DateTime GetLastTime() { long timeBin = (long)m_lastTimePart2; timeBin <<= 32; timeBin |= (uint)m_lastTimePsrt1; return DateTime.FromBinary(timeBin); } } public class WorkUnit_CompareByPhysicalPath : IComparer { int IComparer.Compare(object a, object b) { WorkUnit wwuA = a as WorkUnit; WorkUnit wwuB = b as WorkUnit; return wwuA.PhysicalPath.CompareTo (wwuB.PhysicalPath); } } public class AkInformation_CompareByName : IComparer { int IComparer.Compare(object a, object b) { AkInformation AkInfA = a as AkInformation; AkInformation AkInfB = b as AkInformation; return AkInfA.Name.CompareTo(AkInfB.Name); } } [Serializable] public class EventWorkUnit : WorkUnit { public List<Event> List = new List<Event>(); } [Serializable] public class AkInfoWorkUnit : WorkUnit { public List<AkInformation> List = new List<AkInformation>(); } [Serializable] public class GroupValWorkUnit : WorkUnit { public List<GroupValue> List = new List<GroupValue>(); } [Serializable] public class PathElement { public string ElementName; public WwiseObjectType ObjectType; public PathElement(string Name, WwiseObjectType objType) { ElementName = Name; ObjectType = objType; } } public string CurrentPluginConfig; public enum WwiseObjectType { // Insert Wwise icons description here NONE, AUXBUS, BUS, EVENT, FOLDER, PHYSICALFOLDER, PROJECT, SOUNDBANK, STATE, STATEGROUP, SWITCH, SWITCHGROUP, WORKUNIT, GAMEPARAMETER, TRIGGER } //Can't use a list of WorkUnit and cast it when needed because unity will serialize it as //Workunit and all the child class's fields will be deleted public List<EventWorkUnit> EventWwu = new List<EventWorkUnit>(); public List<AkInfoWorkUnit> AuxBusWwu = new List<AkInfoWorkUnit>(); public List<GroupValWorkUnit> StateWwu = new List<GroupValWorkUnit>(); public List<GroupValWorkUnit> SwitchWwu = new List<GroupValWorkUnit>(); public List<AkInfoWorkUnit> BankWwu = new List<AkInfoWorkUnit>(); public List<AkInfoWorkUnit> RtpcWwu = new List<AkInfoWorkUnit>(); public List<AkInfoWorkUnit> TriggerWwu = new List<AkInfoWorkUnit>(); //Contains the path of all items that are expanded in the Wwise picker public List<string> ExpandedItems = new List<string> (); //An IComparer that enables us to sort work units by their physical path public static WorkUnit_CompareByPhysicalPath s_compareByPhysicalPath = new WorkUnit_CompareByPhysicalPath(); //An IComparer that enables us to sort AkInformations by their physical name public static AkInformation_CompareByName s_compareAkInformationByName = new AkInformation_CompareByName(); public ArrayList GetWwuListByString(string in_wwuType) { if (String.Equals(in_wwuType, "Events", StringComparison.OrdinalIgnoreCase)) { return ArrayList.Adapter(EventWwu); } else if (String.Equals(in_wwuType, "States", StringComparison.OrdinalIgnoreCase)) { return ArrayList.Adapter(StateWwu); } else if (String.Equals(in_wwuType, "Switches", StringComparison.OrdinalIgnoreCase)) { return ArrayList.Adapter(SwitchWwu); } else if (String.Equals(in_wwuType, "Master-Mixer Hierarchy", StringComparison.OrdinalIgnoreCase)) { return ArrayList.Adapter(AuxBusWwu); } else if (String.Equals(in_wwuType, "SoundBanks", StringComparison.OrdinalIgnoreCase)) { return ArrayList.Adapter(BankWwu); } else if (String.Equals(in_wwuType, "Game Parameters", StringComparison.OrdinalIgnoreCase)) { return ArrayList.Adapter(RtpcWwu); } else if (String.Equals(in_wwuType, "Triggers", StringComparison.OrdinalIgnoreCase)) { return ArrayList.Adapter(TriggerWwu); } return null; } public WorkUnit NewChildWorkUnit(string in_wwuType) { if(String.Equals(in_wwuType, "Events", StringComparison.OrdinalIgnoreCase)) { return new EventWorkUnit(); } else if(String.Equals(in_wwuType, "States", StringComparison.OrdinalIgnoreCase) || String.Equals(in_wwuType, "Switches", StringComparison.OrdinalIgnoreCase)) { return new GroupValWorkUnit(); } else if(String.Equals(in_wwuType, "Master-Mixer Hierarchy", StringComparison.OrdinalIgnoreCase) || String.Equals(in_wwuType, "SoundBanks", StringComparison.OrdinalIgnoreCase) || String.Equals(in_wwuType, "Game Parameters", StringComparison.OrdinalIgnoreCase) || String.Equals(in_wwuType, "Triggers", StringComparison.OrdinalIgnoreCase)) { return new AkInfoWorkUnit(); } return null; } public bool IsSupportedWwuType(string in_wwuType) { if(String.Equals(in_wwuType, "Events", StringComparison.OrdinalIgnoreCase)) { return true; } else if(String.Equals(in_wwuType, "States", StringComparison.OrdinalIgnoreCase)) { return true; } else if(String.Equals(in_wwuType, "Switches", StringComparison.OrdinalIgnoreCase)) { return true; } else if(String.Equals(in_wwuType, "Master-Mixer Hierarchy", StringComparison.OrdinalIgnoreCase)) { return true; } else if(String.Equals(in_wwuType, "SoundBanks", StringComparison.OrdinalIgnoreCase)) { return true; } else if (String.Equals(in_wwuType, "Game Parameters", StringComparison.OrdinalIgnoreCase)) { return true; } else if (String.Equals(in_wwuType, "Triggers", StringComparison.OrdinalIgnoreCase)) { return true; } return false; } public byte[] GetEventGuidById(int in_ID) { for(int i = 0; i < AkWwiseProjectInfo.GetData().EventWwu.Count; i++) { AkWwiseProjectData.Event e = AkWwiseProjectInfo.GetData().EventWwu[i].List.Find(x => x.ID == in_ID); if(e != null) { return e.Guid; } } return null; } public byte[] GetBankGuidByName(string in_name) { for(int i = 0; i < AkWwiseProjectInfo.GetData().BankWwu.Count; i++) { AkWwiseProjectData.AkInformation bank = AkWwiseProjectInfo.GetData().BankWwu[i].List.Find(x => x.Name.Equals(in_name)); if(bank != null) { return bank.Guid; } } return null; } public byte[] GetEnvironmentGuidByName(string in_name) { for(int i = 0; i < AkWwiseProjectInfo.GetData().AuxBusWwu.Count; i++) { AkWwiseProjectData.AkInformation auxBus = AkWwiseProjectInfo.GetData().AuxBusWwu[i].List.Find(x => x.Name.Equals(in_name)); if(auxBus != null) { return auxBus.Guid; } } return null; } public byte[][] GetStateGuidByName(string in_groupName, string in_valueName) { byte[][] guids = new byte[][]{new byte[16], new byte[16]}; for(int i = 0; i < AkWwiseProjectInfo.GetData().StateWwu.Count; i++) { AkWwiseProjectData.GroupValue stateGroup = AkWwiseProjectInfo.GetData().StateWwu[i].List.Find(x => x.Name.Equals(in_groupName)); if(stateGroup != null) { guids[0] = stateGroup.Guid; int index = stateGroup.values.FindIndex(x => x == in_valueName); guids[1] = stateGroup.ValueGuids[index].bytes; return guids; } } return null; } public byte[][] GetSwitchGuidByName(string in_groupName, string in_valueName) { byte[][] guids = new byte[][]{new byte[16], new byte[16]}; for(int i = 0; i < AkWwiseProjectInfo.GetData().SwitchWwu.Count; i++) { AkWwiseProjectData.GroupValue switchGroup = AkWwiseProjectInfo.GetData().SwitchWwu[i].List.Find(x => x.Name.Equals(in_groupName)); if(switchGroup != null) { guids[0] = switchGroup.Guid; int index = switchGroup.values.FindIndex(x => x == in_valueName); guids[1] = switchGroup.ValueGuids[index].bytes; return guids; } } return null; } //DateTime Objects are not serializable, so we have to use its binary format (64 bit long). //But apparently long isn't serializable neither, so we split it into two int [SerializeField] private int m_lastPopulateTimePsrt1 = 0; [SerializeField] private int m_lastPopulateTimePart2 = 0; public void SetLastPopulateTime(DateTime in_time) { long timeBin = in_time.ToBinary (); m_lastPopulateTimePsrt1 = (int)timeBin; m_lastPopulateTimePart2 = (int)(timeBin >> 32); } public DateTime GetLastPopulateTime() { long timeBin = (long)m_lastPopulateTimePart2; timeBin <<= 32; timeBin |= (uint)m_lastPopulateTimePsrt1; return DateTime.FromBinary (timeBin); } public bool autoPopulateEnabled = true; //This data is a copy of the AkInitializer parameters. //We need it to reapply the same values to copies of the object in different scenes //It sits in this object so it is serialized in the same "asset" file public string basePath = AkInitializer.c_DefaultBasePath; public string language = AkInitializer.c_Language; public int defaultPoolSize = AkInitializer.c_DefaultPoolSize; public int lowerPoolSize = AkInitializer.c_LowerPoolSize; public int streamingPoolSize = AkInitializer.c_StreamingPoolSize; public int preparePoolSize = AkInitializer.c_PreparePoolSize; public float memoryCutoffThreshold = AkInitializer.c_MemoryCutoffThreshold; public int callbackManagerBufferSize = AkInitializer.c_CallbackManagerBufferSize; public void SaveInitSettings(AkInitializer in_AkInit) { if (!AkWwisePicker.WwiseProjectFound) { return; } if (!CompareInitSettings(in_AkInit)) { Undo.RecordObject(this, "Save Init Settings"); basePath = in_AkInit.basePath; language = in_AkInit.language; defaultPoolSize = in_AkInit.defaultPoolSize; lowerPoolSize = in_AkInit.lowerPoolSize; streamingPoolSize = in_AkInit.streamingPoolSize; preparePoolSize = in_AkInit.preparePoolSize; memoryCutoffThreshold = in_AkInit.memoryCutoffThreshold; callbackManagerBufferSize = in_AkInit.callbackManagerBufferSize; } } public void CopyInitSettings(AkInitializer in_AkInit) { if (!CompareInitSettings(in_AkInit)) { Undo.RecordObject(in_AkInit, "Copy Init Settings"); in_AkInit.basePath = basePath; in_AkInit.language = language; in_AkInit.defaultPoolSize = defaultPoolSize; in_AkInit.lowerPoolSize = lowerPoolSize; in_AkInit.streamingPoolSize = streamingPoolSize; in_AkInit.preparePoolSize = preparePoolSize; in_AkInit.memoryCutoffThreshold = memoryCutoffThreshold; in_AkInit.callbackManagerBufferSize = callbackManagerBufferSize; } } private bool CompareInitSettings(AkInitializer in_AkInit) { return basePath == in_AkInit.basePath && language == in_AkInit.language && defaultPoolSize == in_AkInit.defaultPoolSize && lowerPoolSize == in_AkInit.lowerPoolSize && streamingPoolSize == in_AkInit.streamingPoolSize && preparePoolSize == in_AkInit.preparePoolSize && memoryCutoffThreshold == in_AkInit.memoryCutoffThreshold && callbackManagerBufferSize == in_AkInit.callbackManagerBufferSize; } public float GetEventMaxAttenuation(int in_eventID) { for(int i = 0; i < EventWwu.Count; i++) { for(int j = 0; j < EventWwu[i].List.Count; j++) { if(EventWwu[i].List[j].ID.Equals(in_eventID)) return EventWwu[i].List[j].maxAttenuation; } } return 0.0f; } public void Reset() { EventWwu = new List<EventWorkUnit>(); StateWwu = new List<GroupValWorkUnit>(); SwitchWwu = new List<GroupValWorkUnit>(); BankWwu = new List<AkInfoWorkUnit>(); AuxBusWwu = new List<AkInfoWorkUnit>(); RtpcWwu = new List<AkInfoWorkUnit>(); TriggerWwu = new List<AkInfoWorkUnit>(); } }
using System; namespace AsterNET.FastAGI { /// <summary> /// The BaseAGIScript provides some convinience methods to make it easier to /// write custom AGIScripts.<br/> /// Just extend it by your own AGIScripts. /// </summary> public abstract class AGIScript { #region Answer() /// <summary> /// Answers the channel. /// </summary> protected internal void Answer() { this.Channel.SendCommand(new Command.AnswerCommand()); } #endregion #region Hangup() /// <summary> /// Hangs the channel up. /// </summary> protected internal void Hangup() { this.Channel.SendCommand(new Command.HangupCommand()); } #endregion #region SetAutoHangup /// <summary> /// Cause the channel to automatically hangup at the given number of seconds in the future.<br/> /// 0 disables the autohangup feature. /// </summary> protected internal void SetAutoHangup(int time) { this.Channel.SendCommand(new Command.SetAutoHangupCommand(time)); } #endregion #region SetCallerId /// <summary> /// Sets the caller id on the current channel.<br/> /// The raw caller id to set, for example "John Doe<1234>". /// </summary> protected internal void SetCallerId(string callerId) { this.Channel.SendCommand(new Command.SetCallerIdCommand(callerId)); } #endregion #region PlayMusicOnHold() /// <summary> /// Plays music on hold from the default music on hold class. /// </summary> protected internal void PlayMusicOnHold() { this.Channel.SendCommand(new Command.SetMusicOnCommand()); } #endregion #region PlayMusicOnHold(string musicOnHoldClass) /// <summary> /// Plays music on hold from the given music on hold class. /// </summary> /// <param name="musicOnHoldClass">the music on hold class to play music from as configures in Asterisk's <musiconhold.conf/code>.</param> protected internal void PlayMusicOnHold(string musicOnHoldClass) { this.Channel.SendCommand(new Command.SetMusicOnCommand(musicOnHoldClass)); } #endregion #region StopMusicOnHold() /// <summary> /// Stops playing music on hold. /// </summary> protected internal void StopMusicOnHold() { this.Channel.SendCommand(new Command.SetMusicOffCommand()); } #endregion #region GetChannelStatus /// <summary> /// Returns the status of the channel.<br/> /// Return values: /// <ul> /// <li>0 Channel is down and available /// <li>1 Channel is down, but reserved /// <li>2 Channel is off hook /// <li>3 Digits (or equivalent) have been dialed /// <li>4 Line is ringing /// <li>5 Remote end is ringing /// <li>6 Line is up /// <li>7 Line is busy /// </ul> /// /// </summary> /// <returns> the status of the channel. /// </returns> protected internal int GetChannelStatus() { AGIChannel channel = this.Channel; channel.SendCommand(new Command.ChannelStatusCommand()); return channel.LastReply.ResultCode; } #endregion #region GetData(string file) /// <summary> /// Plays the given file and waits for the user to enter DTMF digits until he /// presses '#'. The user may interrupt the streaming by starting to enter /// digits. /// </summary> /// <param name="file">the name of the file to play</param> /// <returns> a String containing the DTMF the user entered</returns> protected internal string GetData(string file) { AGIChannel channel = this.Channel; channel.SendCommand(new Command.GetDataCommand(file)); return channel.LastReply.GetResult(); } #endregion #region GetData(string file, int timeout) /// <summary> /// Plays the given file and waits for the user to enter DTMF digits until he /// presses '#' or the timeout occurs. The user may interrupt the streaming /// by starting to enter digits. /// </summary> /// <param name="file">the name of the file to play</param> /// <param name="timeout">the timeout in milliseconds to wait for user input.<br/> /// 0 means standard timeout value, -1 means "ludicrous time" /// (essentially never times out).</param> /// <returns> a String containing the DTMF the user entered</returns> protected internal string GetData(string file, long timeout) { AGIChannel channel = this.Channel; channel.SendCommand(new Command.GetDataCommand(file, timeout)); return channel.LastReply.GetResult(); } #endregion #region GetData(string file, int timeout, int maxDigits) /// <summary> /// Plays the given file and waits for the user to enter DTMF digits until he /// presses '#' or the timeout occurs or the maximum number of digits has /// been entered. The user may interrupt the streaming by starting to enter /// digits. /// </summary> /// <param name="file">the name of the file to play</param> /// <param name="timeout">the timeout in milliseconds to wait for user input.<br/> /// 0 means standard timeout value, -1 means "ludicrous time" /// (essentially never times out).</param> /// <param name="maxDigits">the maximum number of digits the user is allowed to enter</param> /// <returns> a String containing the DTMF the user entered</returns> protected internal string GetData(string file, long timeout, int maxDigits) { AGIChannel channel = this.Channel; channel.SendCommand(new Command.GetDataCommand(file, timeout, maxDigits)); return channel.LastReply.GetResult(); } #endregion #region GetOption(string file, string escapeDigits) /// <summary> /// Plays the given file, and waits for the user to press one of the given /// digits. If none of the esacpe digits is pressed while streaming the file /// it waits for the default timeout of 5 seconds still waiting for the user /// to press a digit. /// </summary> /// <param name="file">the name of the file to stream, must not include extension.</param> /// <param name="escapeDigits">contains the digits that the user is expected to press.</param> /// <returns> the DTMF digit pressed or 0x0 if none was pressed.</returns> protected internal char GetOption(string file, string escapeDigits) { AGIChannel channel = this.Channel; channel.SendCommand(new Command.GetOptionCommand(file, escapeDigits)); return channel.LastReply.ResultCodeAsChar; } #endregion #region GetOption(string file, string escapeDigits, int timeout) /// <summary> /// Plays the given file, and waits for the user to press one of the given /// digits. If none of the esacpe digits is pressed while streaming the file /// it waits for the specified timeout still waiting for the user to press a /// digit. /// </summary> /// <param name="file">the name of the file to stream, must not include extension.</param> /// <param name="escapeDigits">contains the digits that the user is expected to press.</param> /// <param name="timeout">the timeout in seconds to wait if none of the defined esacpe digits was presses while streaming.</param> /// <returns> the DTMF digit pressed or 0x0 if none was pressed.</returns> protected internal char GetOption(string file, string escapeDigits, int timeout) { AGIChannel channel = this.Channel; channel.SendCommand(new Command.GetOptionCommand(file, escapeDigits, timeout)); return channel.LastReply.ResultCodeAsChar; } #endregion #region Exec(string application) /// <summary> /// Executes the given command. /// </summary> /// <param name="application">the name of the application to execute, for example "Dial".</param> /// <returns> the return code of the application of -2 if the application was not found.</returns> protected internal int Exec(string application) { AGIChannel channel = this.Channel; channel.SendCommand(new Command.ExecCommand(application)); return channel.LastReply.ResultCode; } #endregion #region Exec(string application, string options) /// <summary> /// Executes the given command. /// </summary> /// <param name="application">the name of the application to execute, for example "Dial".</param> /// <param name="options">the parameters to pass to the application, for example "SIP/123".</param> /// <returns> the return code of the application of -2 if the application was not found.</returns> protected internal int Exec(string application, string options) { AGIChannel channel = this.Channel; channel.SendCommand(new Command.ExecCommand(application, options)); return channel.LastReply.ResultCode; } #endregion #region SetContext /// <summary> /// Sets the context for continuation upon exiting the application. /// </summary> protected internal void SetContext(string context) { this.Channel.SendCommand(new Command.SetContextCommand(context)); } #endregion #region SetExtension /// <summary> /// Sets the extension for continuation upon exiting the application. /// </summary> protected internal void SetExtension(string extension) { this.Channel.SendCommand(new Command.SetExtensionCommand(extension)); } #endregion #region SetPriority(int priority) /// <summary> /// Sets the priority for continuation upon exiting the application. /// </summary> protected internal void SetPriority(int priority) { this.Channel.SendCommand(new Command.SetPriorityCommand(priority)); } #endregion #region SetPriority(string label priority) /// <summary> /// Sets the label for continuation upon exiting the application. /// </summary> protected internal void SetPriority(string label) { this.Channel.SendCommand(new Command.SetPriorityCommand(label)); } #endregion #region StreamFile(string file) /// <summary> /// Plays the given file. /// </summary> /// <param name="file">name of the file to play.</param> protected internal void StreamFile(string file) { this.Channel.SendCommand(new Command.StreamFileCommand(file)); } #endregion #region StreamFile(string file, string escapeDigits) /// <summary> /// Plays the given file and allows the user to escape by pressing one of the given digit. /// </summary> /// <param name="file">name of the file to play.</param> /// <param name="escapeDigits">a String containing the DTMF digits that allow the user to escape.</param> /// <returns> the DTMF digit pressed or 0x0 if none was pressed.</returns> protected internal char StreamFile(string file, string escapeDigits) { AGIChannel channel = this.Channel; channel.SendCommand(new Command.StreamFileCommand(file, escapeDigits)); return channel.LastReply.ResultCodeAsChar; } #endregion #region SayDigits(string digits) /// <summary> /// Says the given digit string. /// </summary> /// <param name="digits">the digit string to say.</param> protected internal void SayDigits(string digits) { this.Channel.SendCommand(new Command.SayDigitsCommand(digits)); } #endregion #region SayDigits(string digits, string escapeDigits) /// <summary> /// Says the given number, returning early if any of the given DTMF number /// are received on the channel. /// </summary> /// <param name="digits">the digit string to say.</param> /// <param name="escapeDigits">a String containing the DTMF digits that allow the user to escape.</param> /// <returns> the DTMF digit pressed or 0x0 if none was pressed.</returns> protected internal char SayDigits(string digits, string escapeDigits) { AGIChannel channel = this.Channel; channel.SendCommand(new Command.SayDigitsCommand(digits, escapeDigits)); return channel.LastReply.ResultCodeAsChar; } #endregion #region SayNumber(string number) /// <summary> /// Says the given number. /// </summary> /// <param name="number">the number to say.</param> protected internal void SayNumber(string number) { this.Channel.SendCommand(new Command.SayNumberCommand(number)); } #endregion #region SayNumber(string number, string escapeDigits) /// <summary> /// Says the given number, returning early if any of the given DTMF number /// are received on the channel. /// </summary> /// <param name="number">the number to say.</param> /// <param name="escapeDigits">a String containing the DTMF digits that allow the user to escape.</param> /// <returns> the DTMF digit pressed or 0x0 if none was pressed.</returns> protected internal char SayNumber(string number, string escapeDigits) { AGIChannel channel = this.Channel; channel.SendCommand(new Command.SayNumberCommand(number, escapeDigits)); return channel.LastReply.ResultCodeAsChar; } #endregion #region SayPhonetic(string text) /// <summary> /// Says the given character string with phonetics. /// </summary> /// <param name="text">the text to say.</param> protected internal void SayPhonetic(string text) { this.Channel.SendCommand(new Command.SayPhoneticCommand(text)); } #endregion #region SayPhonetic(string text, string escapeDigits) /// <summary> /// Says the given character string with phonetics, returning early if any of /// the given DTMF number are received on the channel. /// </summary> /// <param name="text">the text to say.</param> /// <param name="escapeDigits">a String containing the DTMF digits that allow the user to escape.</param> /// <returns> the DTMF digit pressed or 0x0 if none was pressed.</returns> protected internal char SayPhonetic(string text, string escapeDigits) { AGIChannel channel = this.Channel; channel.SendCommand(new Command.SayPhoneticCommand(text, escapeDigits)); return channel.LastReply.ResultCodeAsChar; } #endregion #region SayAlpha(string text) /// <summary> /// Says the given character string. /// </summary> /// <param name="text">the text to say.</param> protected internal void SayAlpha(string text) { this.Channel.SendCommand(new Command.SayAlphaCommand(text)); } #endregion #region SayAlpha(string text, string escapeDigits) /// <summary> /// Says the given character string, returning early if any of the given DTMF /// number are received on the channel. /// </summary> /// <param name="text">the text to say.</param> /// <param name="escapeDigits">a String containing the DTMF digits that allow the user to escape.</param> /// <returns> the DTMF digit pressed or 0x0 if none was pressed.</returns> protected internal char SayAlpha(string text, string escapeDigits) { AGIChannel channel = this.Channel; channel.SendCommand(new Command.SayAlphaCommand(text, escapeDigits)); return channel.LastReply.ResultCodeAsChar; } #endregion #region SayTime(long time) /// <summary> /// Says the given time. /// </summary> /// <param name="time">the time to say in seconds since 00:00:00 on January 1, 1970.</param> protected internal void SayTime(long time) { this.Channel.SendCommand(new Command.SayTimeCommand(time)); } #endregion #region SayTime(long time, string escapeDigits) /// <summary> /// Says the given time, returning early if any of the given DTMF number are /// received on the channel. /// </summary> /// <param name="time">the time to say in seconds since 00:00:00 on January 1, 1970.</param> /// <param name="escapeDigits">a String containing the DTMF digits that allow the user to escape.</param> /// <returns> the DTMF digit pressed or 0x0 if none was pressed.</returns> protected internal char SayTime(long time, string escapeDigits) { AGIChannel channel = this.Channel; channel.SendCommand(new Command.SayTimeCommand(time, escapeDigits)); return channel.LastReply.ResultCodeAsChar; } #endregion #region GetVariable(string name) /// <summary> /// Returns the value of the given channel variable. /// </summary> /// <param name="name">the name of the variable to retrieve.</param> /// <returns> the value of the given variable or null if not set.</returns> protected internal string GetVariable(string name) { AGIChannel channel = this.Channel; channel.SendCommand(new Command.GetVariableCommand(name)); if (channel.LastReply.ResultCode != 1) return null; return channel.LastReply.Extra; } #endregion #region SetVariable(string name, string value_Renamed) /// <summary> /// Sets the value of the given channel variable to a new value. /// </summary> /// <param name="name">the name of the variable to retrieve.</param> /// <param name="val">the new value to set.</param> protected internal void SetVariable(string name, string val) { this.Channel.SendCommand(new Command.SetVariableCommand(name, val)); } #endregion #region WaitForDigit(int timeout) /// <summary> /// Waits up to 'timeout' milliseconds to receive a DTMF digit. /// </summary> /// <param name="timeout">timeout the milliseconds to wait for the channel to receive a DTMF digit, -1 will wait forever.</param> /// <returns> the DTMF digit pressed or 0x0 if none was pressed.</returns> protected internal char WaitForDigit(int timeout) { AGIChannel channel = this.Channel; channel.SendCommand(new Command.WaitForDigitCommand(timeout)); return channel.LastReply.ResultCodeAsChar; } #endregion #region GetFullVariable(string name) /// <summary> /// Returns the value of the current channel variable, unlike getVariable() /// this method understands complex variable names and builtin variables.<br/> /// Available since Asterisk 1.2. /// </summary> /// <param name="name">the name of the variable to retrieve.</param> /// <returns>the value of the given variable or null if not et.</returns> protected internal string GetFullVariable(string name) { AGIChannel channel = this.Channel; channel.SendCommand(new Command.GetFullVariableCommand(name)); if (channel.LastReply.ResultCode != 1) return null; return channel.LastReply.Extra; } #endregion #region GetFullVariable(string name, string channel) /// <summary> /// Returns the value of the given channel variable.<br/> /// Available since Asterisk 1.2. /// </summary> /// <param name="name">the name of the variable to retrieve.</param> /// <param name="channel">the name of the channel.</param> /// <returns>the value of the given variable or null if not set.</returns> protected internal string GetFullVariable(string name, string channelName) { AGIChannel channel = this.Channel; channel.SendCommand(new Command.GetFullVariableCommand(name, channelName)); if (channel.LastReply.ResultCode != 1) return null; return channel.LastReply.Extra; } #endregion #region SayDateTime(...) /// <summary> /// Says the given time.<br/> /// Available since Asterisk 1.2. /// </summary> /// <param name="time">the time to say in seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal Time (UTC)</param> protected internal void SayDateTime(long time) { this.Channel.SendCommand(new Command.SayDateTimeCommand(time)); } /// <summary> /// Says the given time and allows interruption by one of the given escape digits.<br/> /// Available since Asterisk 1.2. /// </summary> /// <param name="time">the time to say in seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal Time (UTC)</param> /// <param name="escapeDigits">the digits that allow the user to interrupt this command or null for none.</param> /// <returns>the DTMF digit pressed or 0x0 if none was pressed.</returns> protected internal char SayDateTime(long time, string escapeDigits) { AGIChannel channel = this.Channel; channel.SendCommand(new Command.SayDateTimeCommand(time, escapeDigits)); return channel.LastReply.ResultCodeAsChar; } /// <summary> /// Says the given time in the given format and allows interruption by one of the given escape digits.<br/> /// Available since Asterisk 1.2. /// </summary> /// <param name="time">the time to say in seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal Time (UTC)</param> /// <param name="escapeDigits">the digits that allow the user to interrupt this command or null for none.</param> /// <param name="format">the format the time should be said in</param> /// <returns>the DTMF digit pressed or 0x0 if none was pressed.</returns> protected internal char SayDateTime(long time, string escapeDigits, string format) { AGIChannel channel = this.Channel; channel.SendCommand(new Command.SayDateTimeCommand(time, escapeDigits, format)); return channel.LastReply.ResultCodeAsChar; } /// <summary> /// Says the given time in the given format and timezone and allows interruption by one of the given escape digits.<br/> /// Available since Asterisk 1.2. /// </summary> /// <param name="time">the time to say in seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal Time (UTC)</param> /// <param name="escapeDigits">the digits that allow the user to interrupt this command or null for none.</param> /// <param name="format">the format the time should be said in</param> /// <param name="timezone">the timezone to use when saying the time, for example "UTC" or "Europe/Berlin".</param> /// <returns>the DTMF digit pressed or 0x0 if none was pressed.</returns> protected internal char SayDateTime(long time, string escapeDigits, string format, string timezone) { AGIChannel channel = this.Channel; channel.SendCommand(new Command.SayDateTimeCommand(time, escapeDigits, format, timezone)); return channel.LastReply.ResultCodeAsChar; } #endregion #region DatabaseGet(string family, string key) /// <summary> /// Retrieves an entry in the Asterisk database for a given family and key. /// </summary> /// <param name="family">the family of the entry to retrieve.</param> /// <param name="key">key the key of the entry to retrieve.</param> /// <return>the value of the given family and key or null if there is no such value.</return> protected internal string DatabaseGet(string family, string key) { AGIChannel channel = this.Channel; channel.SendCommand(new Command.DatabaseGetCommand(family, key)); if (channel.LastReply.ResultCode != 1) return null; return channel.LastReply.Extra; } #endregion #region DatabasePut(string family, string key, string value) /// <summary> /// Adds or updates an entry in the Asterisk database for a given family, key and value. /// </summary> /// <param name="family">the family of the entry to add or update.</param> /// <param name="key">the key of the entry to add or update.</param> /// <param name="value">the new value of the entry.</param> protected internal void DatabasePut(string family, string key, string value) { this.Channel.SendCommand(new Command.DatabasePutCommand(family, key, value)); } #endregion #region DatabaseDel(string family, string key) /// <summary> /// Deletes an entry in the Asterisk database for a given family and key. /// </summary> /// <param name="family">the family of the entry to delete.</param> /// <param name="key">the key of the entry to delete.</param> protected internal void DatabaseDel(string family, string key) { this.Channel.SendCommand(new Command.DatabaseDelCommand(family, key)); } #endregion #region DatabaseDelTree(String family) /// <summary> /// Deletes a whole family of entries in the Asterisk database. /// </summary> /// <param name="family">the family to delete.</param> protected internal void DatabaseDelTree(string family) { this.Channel.SendCommand(new Command.DatabaseDelTreeCommand(family)); } #endregion #region DatabaseDelTree(string family, string keytree) /// <summary> /// Deletes all entries of a given family in the Asterisk database that have a key that starts with a given prefix. /// </summary> /// <param name="family">the family of the entries to delete.</param> /// <param name="keytree">the prefix of the keys of the entries to delete.</param> protected internal void DatabaseDelTree(string family, string keytree) { this.Channel.SendCommand(new Command.DatabaseDelTreeCommand(family, keytree)); } #endregion #region Verbose(string message, int level) /// <summary> /// Sends a message to the Asterisk console via the verbose message system. /// </summary> /// <param name="message">the message to send</param> /// <param name="level">the verbosity level to use. Must be in [1..4]</param> public void Verbose(string message, int level) { this.Channel.SendCommand(new Command.VerboseCommand(message, level)); } #endregion #region RecordFile(...) /// <summary> /// Record to a file until a given dtmf digit in the sequence is received.<br/> /// Returns -1 on hangup or error.<br/> /// The format will specify what kind of file will be recorded. The timeout is /// the maximum record time in milliseconds, or -1 for no timeout. Offset samples /// is optional, and if provided will seek to the offset without exceeding the /// end of the file. "maxSilence" is the number of seconds of maxSilence allowed /// before the function returns despite the lack of dtmf digits or reaching /// timeout. /// </summary> /// <param name="file">the name of the file to stream, must not include extension.</param> /// <param name="format">the format of the file to be recorded, for example "wav".</param> /// <param name="escapeDigits">contains the digits that allow the user to end recording.</param> /// <param name="timeout">the maximum record time in milliseconds, or -1 for no timeout.</param> /// <returns>result code</returns> protected internal int RecordFile(string file, string format, string escapeDigits, int timeout) { AGIChannel channel = this.Channel; channel.SendCommand(new Command.RecordFileCommand(file, format, escapeDigits, timeout)); return channel.LastReply.ResultCode; } /// <summary> /// Record to a file until a given dtmf digit in the sequence is received.<br/> /// Returns -1 on hangup or error.<br/> /// The format will specify what kind of file will be recorded. The timeout is /// the maximum record time in milliseconds, or -1 for no timeout. Offset samples /// is optional, and if provided will seek to the offset without exceeding the /// end of the file. "maxSilence" is the number of seconds of maxSilence allowed /// before the function returns despite the lack of dtmf digits or reaching /// timeout. /// </summary> /// <param name="file">the name of the file to stream, must not include extension.</param> /// <param name="format">the format of the file to be recorded, for example "wav".</param> /// <param name="escapeDigits">contains the digits that allow the user to end recording.</param> /// <param name="timeout">the maximum record time in milliseconds, or -1 for no timeout.</param> /// <param name="offset">the offset samples to skip.</param> /// <param name="beep">true if a beep should be played before recording.</param> /// <param name="maxSilence">The amount of silence (in seconds) to allow before returning despite the lack of dtmf digits or reaching timeout.</param> /// <returns>result code</returns> protected internal int RecordFile(string file, string format, string escapeDigits, int timeout, int offset, bool beep, int maxSilence) { AGIChannel channel = this.Channel; channel.SendCommand(new Command.RecordFileCommand(file, format, escapeDigits, timeout, offset, beep, maxSilence)); return channel.LastReply.ResultCode; } #endregion #region ControlStreamFile(...) /// <summary> /// Plays the given file, allowing playback to be interrupted by the given /// digits, if any, and allows the listner to control the stream.<br/> /// If offset is provided then the audio will seek to sample offset before play /// starts.<br/> /// Returns 0 if playback completes without a digit being pressed, or the ASCII /// numerical value of the digit if one was pressed, or -1 on error or if the /// channel was disconnected. <br/> /// Remember, the file extension must not be included in the filename.<br/> /// Available since Asterisk 1.2 /// </summary> /// <seealso cref="Command.ControlStreamFileCommand"/> /// <param name="file">the name of the file to stream, must not include extension.</param> /// <returns>result code</returns> protected internal int ControlStreamFile(string file) { AGIChannel channel = this.Channel; channel.SendCommand(new Command.ControlStreamFileCommand(file)); return channel.LastReply.ResultCode; } /// <summary> /// Plays the given file, allowing playback to be interrupted by the given /// digits, if any, and allows the listner to control the stream.<br/> /// If offset is provided then the audio will seek to sample offset before play /// starts.<br/> /// Returns 0 if playback completes without a digit being pressed, or the ASCII /// numerical value of the digit if one was pressed, or -1 on error or if the /// channel was disconnected. <br/> /// Remember, the file extension must not be included in the filename.<br/> /// Available since Asterisk 1.2 /// </summary> /// <seealso cref="Command.ControlStreamFileCommand"/> /// <param name="file">the name of the file to stream, must not include extension.</param> /// <param name="escapeDigits">contains the digits that allow the user to interrupt this command.</param> /// <returns>result code</returns> protected internal int ControlStreamFile(string file, string escapeDigits) { AGIChannel channel = this.Channel; channel.SendCommand(new Command.ControlStreamFileCommand(file, escapeDigits)); return channel.LastReply.ResultCode; } /// <summary> /// Plays the given file, allowing playback to be interrupted by the given /// digits, if any, and allows the listner to control the stream.<br/> /// If offset is provided then the audio will seek to sample offset before play /// starts.<br/> /// Returns 0 if playback completes without a digit being pressed, or the ASCII /// numerical value of the digit if one was pressed, or -1 on error or if the /// channel was disconnected. <br/> /// Remember, the file extension must not be included in the filename.<br/> /// Available since Asterisk 1.2 /// </summary> /// <seealso cref="Command.ControlStreamFileCommand"/> /// <param name="file">the name of the file to stream, must not include extension.</param> /// <param name="escapeDigits">contains the digits that allow the user to interrupt this command.</param> /// <param name="offset">the offset samples to skip before streaming.</param> /// <returns>result code</returns> protected internal int ControlStreamFile(string file, string escapeDigits, int offset) { AGIChannel channel = this.Channel; channel.SendCommand(new Command.ControlStreamFileCommand(file, escapeDigits, offset)); return channel.LastReply.ResultCode; } /// <summary> /// Plays the given file, allowing playback to be interrupted by the given /// digits, if any, and allows the listner to control the stream.<br/> /// If offset is provided then the audio will seek to sample offset before play /// starts.<br/> /// Returns 0 if playback completes without a digit being pressed, or the ASCII /// numerical value of the digit if one was pressed, or -1 on error or if the /// channel was disconnected. <br/> /// Remember, the file extension must not be included in the filename.<br/> /// Available since Asterisk 1.2 /// </summary> /// <seealso cref="Command.ControlStreamFileCommand"/> /// <param name="file">the name of the file to stream, must not include extension.</param> /// <param name="escapeDigits">contains the digits that allow the user to interrupt this command.</param> /// <param name="offset">the offset samples to skip before streaming.</param> /// <param name="forwardDigit">the digit for fast forward.</param> /// <param name="rewindDigit">the digit for rewind.</param> /// <param name="pauseDigit">the digit for pause and unpause.</param> /// <returns>result code</returns> protected internal int ControlStreamFile(string file, string escapeDigits, int offset, string forwardDigit, string rewindDigit, string pauseDigit) { AGIChannel channel = this.Channel; channel.SendCommand(new Command.ControlStreamFileCommand(file, escapeDigits, offset, forwardDigit, rewindDigit, pauseDigit)); return channel.LastReply.ResultCode; } #endregion #region SendCommand(Command.AGICommand command) /// <summary> /// Sends the given command to the channel attached to the current thread. /// </summary> /// <param name="command">the command to send to Asterisk</param> /// <returns> the reply received from Asterisk</returns> /// <throws> AGIException if the command could not be processed properly </throws> private AGIReply SendCommand(Command.AGICommand command) { return this.Channel.SendCommand(command); } #endregion #region Channel protected internal AGIChannel Channel { get { AGIChannel channel = AGIConnectionHandler.Channel; if (channel == null) throw new SystemException("Trying to send command from an invalid thread"); return channel; } } #endregion #region Service(AGIRequest param1, AGIChannel param2); public abstract void Service(AGIRequest param1, AGIChannel param2); #endregion } }
/* * Copyright 2012-2021 The Pkcs11Interop 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. */ /* * Written for the Pkcs11Interop project by: * Jaroslav IMRICH <jimrich@jimrich.sk> */ using System; using System.IO; using Net.Pkcs11Interop.Common; using Net.Pkcs11Interop.LowLevelAPI40; using Net.Pkcs11Interop.LowLevelAPI40.MechanismParams; using NUnit.Framework; using NativeULong = System.UInt32; // Note: Code in this file is generated automatically. namespace Net.Pkcs11Interop.Tests.LowLevelAPI40 { /// <summary> /// C_EncryptInit, C_Encrypt, C_EncryptUpdate, C_EncryptFinish, C_DecryptInit, C_Decrypt, C_DecryptUpdate and C_DecryptFinish tests. /// </summary> [TestFixture()] public class _20_EncryptAndDecryptTest { /// <summary> /// C_EncryptInit, C_Encrypt, C_DecryptInit and C_Decrypt test. /// </summary> [Test()] public void _01_EncryptAndDecryptSinglePartTest() { Helpers.CheckPlatform(); CKR rv = CKR.CKR_OK; using (Pkcs11Library pkcs11Library = new Pkcs11Library(Settings.Pkcs11LibraryPath)) { rv = pkcs11Library.C_Initialize(Settings.InitArgs40); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Find first slot with token present NativeULong slotId = Helpers.GetUsableSlot(pkcs11Library); NativeULong session = CK.CK_INVALID_HANDLE; rv = pkcs11Library.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Login as normal user rv = pkcs11Library.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, ConvertUtils.UInt32FromInt32(Settings.NormalUserPinArray.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Generate symetric key NativeULong keyId = CK.CK_INVALID_HANDLE; rv = Helpers.GenerateKey(pkcs11Library, session, ref keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Generate random initialization vector byte[] iv = new byte[8]; rv = pkcs11Library.C_GenerateRandom(session, iv, ConvertUtils.UInt32FromInt32(iv.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Specify encryption mechanism with initialization vector as parameter. // Note that CkmUtils.CreateMechanism() automaticaly copies iv into newly allocated unmanaged memory. CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_DES3_CBC, iv); // Initialize encryption operation rv = pkcs11Library.C_EncryptInit(session, ref mechanism, keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Our new password"); // Get length of encrypted data in first call NativeULong encryptedDataLen = 0; rv = pkcs11Library.C_Encrypt(session, sourceData, ConvertUtils.UInt32FromInt32(sourceData.Length), null, ref encryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsTrue(encryptedDataLen > 0); // Allocate array for encrypted data byte[] encryptedData = new byte[encryptedDataLen]; // Get encrypted data in second call rv = pkcs11Library.C_Encrypt(session, sourceData, ConvertUtils.UInt32FromInt32(sourceData.Length), encryptedData, ref encryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Do something interesting with encrypted data // Initialize decryption operation rv = pkcs11Library.C_DecryptInit(session, ref mechanism, keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Get length of decrypted data in first call NativeULong decryptedDataLen = 0; rv = pkcs11Library.C_Decrypt(session, encryptedData, ConvertUtils.UInt32FromInt32(encryptedData.Length), null, ref decryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsTrue(decryptedDataLen > 0); // Allocate array for decrypted data byte[] decryptedData = new byte[decryptedDataLen]; // Get decrypted data in second call rv = pkcs11Library.C_Decrypt(session, encryptedData, ConvertUtils.UInt32FromInt32(encryptedData.Length), decryptedData, ref decryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Do something interesting with decrypted data Assert.IsTrue(ConvertUtils.BytesToBase64String(sourceData) == ConvertUtils.BytesToBase64String(decryptedData)); // In LowLevelAPI we have to free unmanaged memory taken by mechanism parameter (iv in this case) UnmanagedMemory.Free(ref mechanism.Parameter); mechanism.ParameterLen = 0; rv = pkcs11Library.C_DestroyObject(session, keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11Library.C_Logout(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11Library.C_CloseSession(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11Library.C_Finalize(IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } } /// <summary> /// C_EncryptInit, C_EncryptUpdate, C_EncryptFinish, C_DecryptInit, C_DecryptUpdate and C_DecryptFinish test. /// </summary> [Test()] public void _02_EncryptAndDecryptMultiPartTest() { Helpers.CheckPlatform(); CKR rv = CKR.CKR_OK; using (Pkcs11Library pkcs11Library = new Pkcs11Library(Settings.Pkcs11LibraryPath)) { rv = pkcs11Library.C_Initialize(Settings.InitArgs40); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Find first slot with token present NativeULong slotId = Helpers.GetUsableSlot(pkcs11Library); NativeULong session = CK.CK_INVALID_HANDLE; rv = pkcs11Library.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Login as normal user rv = pkcs11Library.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, ConvertUtils.UInt32FromInt32(Settings.NormalUserPinArray.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Generate symetric key NativeULong keyId = CK.CK_INVALID_HANDLE; rv = Helpers.GenerateKey(pkcs11Library, session, ref keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Generate random initialization vector byte[] iv = new byte[8]; rv = pkcs11Library.C_GenerateRandom(session, iv, ConvertUtils.UInt32FromInt32(iv.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Specify encryption mechanism with initialization vector as parameter. // Note that CkmUtils.CreateMechanism() automaticaly copies iv into newly allocated unmanaged memory. CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_DES3_CBC, iv); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Our new password"); byte[] encryptedData = null; byte[] decryptedData = null; // Multipart encryption functions C_EncryptUpdate and C_EncryptFinal can be used i.e. for encryption of streamed data using (MemoryStream inputStream = new MemoryStream(sourceData), outputStream = new MemoryStream()) { // Initialize encryption operation rv = pkcs11Library.C_EncryptInit(session, ref mechanism, keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Prepare buffer for source data part // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long byte[] part = new byte[8]; // Prepare buffer for encrypted data part // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long byte[] encryptedPart = new byte[8]; NativeULong encryptedPartLen = ConvertUtils.UInt32FromInt32(encryptedPart.Length); // Read input stream with source data int bytesRead = 0; while ((bytesRead = inputStream.Read(part, 0, part.Length)) > 0) { // Encrypt each individual source data part encryptedPartLen = ConvertUtils.UInt32FromInt32(encryptedPart.Length); rv = pkcs11Library.C_EncryptUpdate(session, part, ConvertUtils.UInt32FromInt32(bytesRead), encryptedPart, ref encryptedPartLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Append encrypted data part to the output stream outputStream.Write(encryptedPart, 0, ConvertUtils.UInt32ToInt32(encryptedPartLen)); } // Get the length of last encrypted data part in first call byte[] lastEncryptedPart = null; NativeULong lastEncryptedPartLen = 0; rv = pkcs11Library.C_EncryptFinal(session, null, ref lastEncryptedPartLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Allocate array for the last encrypted data part lastEncryptedPart = new byte[lastEncryptedPartLen]; // Get the last encrypted data part in second call rv = pkcs11Library.C_EncryptFinal(session, lastEncryptedPart, ref lastEncryptedPartLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Append the last encrypted data part to the output stream outputStream.Write(lastEncryptedPart, 0, ConvertUtils.UInt32ToInt32(lastEncryptedPartLen)); // Read whole output stream to the byte array so we can compare results more easily encryptedData = outputStream.ToArray(); } // Do something interesting with encrypted data // Multipart decryption functions C_DecryptUpdate and C_DecryptFinal can be used i.e. for decryption of streamed data using (MemoryStream inputStream = new MemoryStream(encryptedData), outputStream = new MemoryStream()) { // Initialize decryption operation rv = pkcs11Library.C_DecryptInit(session, ref mechanism, keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Prepare buffer for encrypted data part // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long byte[] encryptedPart = new byte[8]; // Prepare buffer for decrypted data part // Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long byte[] part = new byte[8]; NativeULong partLen = ConvertUtils.UInt32FromInt32(part.Length); // Read input stream with encrypted data int bytesRead = 0; while ((bytesRead = inputStream.Read(encryptedPart, 0, encryptedPart.Length)) > 0) { // Decrypt each individual encrypted data part partLen = ConvertUtils.UInt32FromInt32(part.Length); rv = pkcs11Library.C_DecryptUpdate(session, encryptedPart, ConvertUtils.UInt32FromInt32(bytesRead), part, ref partLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Append decrypted data part to the output stream outputStream.Write(part, 0, ConvertUtils.UInt32ToInt32(partLen)); } // Get the length of last decrypted data part in first call byte[] lastPart = null; NativeULong lastPartLen = 0; rv = pkcs11Library.C_DecryptFinal(session, null, ref lastPartLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Allocate array for the last decrypted data part lastPart = new byte[lastPartLen]; // Get the last decrypted data part in second call rv = pkcs11Library.C_DecryptFinal(session, lastPart, ref lastPartLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Append the last decrypted data part to the output stream outputStream.Write(lastPart, 0, ConvertUtils.UInt32ToInt32(lastPartLen)); // Read whole output stream to the byte array so we can compare results more easily decryptedData = outputStream.ToArray(); } // Do something interesting with decrypted data Assert.IsTrue(ConvertUtils.BytesToBase64String(sourceData) == ConvertUtils.BytesToBase64String(decryptedData)); // In LowLevelAPI we have to free unmanaged memory taken by mechanism parameter (iv in this case) UnmanagedMemory.Free(ref mechanism.Parameter); mechanism.ParameterLen = 0; rv = pkcs11Library.C_DestroyObject(session, keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11Library.C_Logout(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11Library.C_CloseSession(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11Library.C_Finalize(IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } } /// <summary> /// C_EncryptInit, C_Encrypt, C_DecryptInit and C_Decrypt test with CKM_RSA_PKCS_OAEP mechanism. /// </summary> [Test()] public void _03_EncryptAndDecryptSinglePartOaepTest() { Helpers.CheckPlatform(); CKR rv = CKR.CKR_OK; using (Pkcs11Library pkcs11Library = new Pkcs11Library(Settings.Pkcs11LibraryPath)) { rv = pkcs11Library.C_Initialize(Settings.InitArgs40); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Find first slot with token present NativeULong slotId = Helpers.GetUsableSlot(pkcs11Library); NativeULong session = CK.CK_INVALID_HANDLE; rv = pkcs11Library.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Login as normal user rv = pkcs11Library.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, ConvertUtils.UInt32FromInt32(Settings.NormalUserPinArray.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Generate asymetric key pair NativeULong pubKeyId = CK.CK_INVALID_HANDLE; NativeULong privKeyId = CK.CK_INVALID_HANDLE; rv = Helpers.GenerateKeyPair(pkcs11Library, session, ref pubKeyId, ref privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Specify mechanism parameters CK_RSA_PKCS_OAEP_PARAMS mechanismParams = new CK_RSA_PKCS_OAEP_PARAMS(); mechanismParams.HashAlg = ConvertUtils.UInt32FromCKM(CKM.CKM_SHA_1); mechanismParams.Mgf = ConvertUtils.UInt32FromCKG(CKG.CKG_MGF1_SHA1); mechanismParams.Source = ConvertUtils.UInt32FromUInt32(CKZ.CKZ_DATA_SPECIFIED); mechanismParams.SourceData = IntPtr.Zero; mechanismParams.SourceDataLen = 0; // Specify encryption mechanism with parameters // Note that CkmUtils.CreateMechanism() automaticaly copies mechanismParams into newly allocated unmanaged memory. CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_RSA_PKCS_OAEP, mechanismParams); // Initialize encryption operation rv = pkcs11Library.C_EncryptInit(session, ref mechanism, pubKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world"); // Get length of encrypted data in first call NativeULong encryptedDataLen = 0; rv = pkcs11Library.C_Encrypt(session, sourceData, ConvertUtils.UInt32FromInt32(sourceData.Length), null, ref encryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsTrue(encryptedDataLen > 0); // Allocate array for encrypted data byte[] encryptedData = new byte[encryptedDataLen]; // Get encrypted data in second call rv = pkcs11Library.C_Encrypt(session, sourceData, ConvertUtils.UInt32FromInt32(sourceData.Length), encryptedData, ref encryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Do something interesting with encrypted data // Initialize decryption operation rv = pkcs11Library.C_DecryptInit(session, ref mechanism, privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Get length of decrypted data in first call NativeULong decryptedDataLen = 0; rv = pkcs11Library.C_Decrypt(session, encryptedData, ConvertUtils.UInt32FromInt32(encryptedData.Length), null, ref decryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); Assert.IsTrue(decryptedDataLen > 0); // Allocate array for decrypted data byte[] decryptedData = new byte[decryptedDataLen]; // Get decrypted data in second call rv = pkcs11Library.C_Decrypt(session, encryptedData, ConvertUtils.UInt32FromInt32(encryptedData.Length), decryptedData, ref decryptedDataLen); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Array may need to be shrinked if (decryptedData.Length != ConvertUtils.UInt32ToInt32(decryptedDataLen)) Array.Resize(ref decryptedData, ConvertUtils.UInt32ToInt32(decryptedDataLen)); // Do something interesting with decrypted data Assert.IsTrue(ConvertUtils.BytesToBase64String(sourceData) == ConvertUtils.BytesToBase64String(decryptedData)); // In LowLevelAPI we have to free unmanaged memory taken by mechanism parameter UnmanagedMemory.Free(ref mechanism.Parameter); mechanism.ParameterLen = 0; rv = pkcs11Library.C_DestroyObject(session, privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11Library.C_DestroyObject(session, pubKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11Library.C_Logout(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11Library.C_CloseSession(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11Library.C_Finalize(IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } } } }
// // Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // 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 Jaroslaw Kowalski 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR 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 NLog.Conditions; namespace NLog.LayoutRenderers { using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using NLog.Common; using NLog.Config; using NLog.Internal; /// <summary> /// Exception information provided through /// a call to one of the Logger.*Exception() methods. /// </summary> [LayoutRenderer("exception")] [ThreadAgnostic] public class ExceptionLayoutRenderer : LayoutRenderer { private string _format; private string _innerFormat = string.Empty; private readonly Dictionary<ExceptionRenderingFormat, Action<StringBuilder, Exception>> _renderingfunctions; private static readonly Dictionary<String, ExceptionRenderingFormat> _formatsMapping = new Dictionary<string, ExceptionRenderingFormat>(StringComparer.OrdinalIgnoreCase) { {"MESSAGE",ExceptionRenderingFormat.Message}, {"TYPE", ExceptionRenderingFormat.Type}, {"SHORTTYPE",ExceptionRenderingFormat.ShortType}, {"TOSTRING",ExceptionRenderingFormat.ToString}, {"METHOD",ExceptionRenderingFormat.Method}, {"STACKTRACE", ExceptionRenderingFormat.StackTrace}, {"DATA",ExceptionRenderingFormat.Data}, }; /// <summary> /// Initializes a new instance of the <see cref="ExceptionLayoutRenderer" /> class. /// </summary> public ExceptionLayoutRenderer() { this.Format = "message"; this.Separator = " "; this.ExceptionDataSeparator = ";"; this.InnerExceptionSeparator = EnvironmentHelper.NewLine; this.MaxInnerExceptionLevel = 0; _renderingfunctions = new Dictionary<ExceptionRenderingFormat, Action<StringBuilder, Exception>>() { {ExceptionRenderingFormat.Message, AppendMessage}, {ExceptionRenderingFormat.Type, AppendType}, {ExceptionRenderingFormat.ShortType, AppendShortType}, {ExceptionRenderingFormat.ToString, AppendToString}, {ExceptionRenderingFormat.Method, AppendMethod}, {ExceptionRenderingFormat.StackTrace, AppendStackTrace}, {ExceptionRenderingFormat.Data, AppendData} }; } /// <summary> /// Gets or sets the format of the output. Must be a comma-separated list of exception /// properties: Message, Type, ShortType, ToString, Method, StackTrace. /// This parameter value is case-insensitive. /// </summary> /// <see cref="Formats"/> /// <see cref="ExceptionRenderingFormat"/> /// <docgen category='Rendering Options' order='10' /> [DefaultParameter] public string Format { get { return this._format; } set { this._format = value; Formats = CompileFormat(value); } } /// <summary> /// Gets or sets the format of the output of inner exceptions. Must be a comma-separated list of exception /// properties: Message, Type, ShortType, ToString, Method, StackTrace. /// This parameter value is case-insensitive. /// </summary> /// <docgen category='Rendering Options' order='10' /> public string InnerFormat { get { return this._innerFormat; } set { this._innerFormat = value; InnerFormats = CompileFormat(value); } } /// <summary> /// Gets or sets the separator used to concatenate parts specified in the Format. /// </summary> /// <docgen category='Rendering Options' order='10' /> [DefaultValue(" ")] public string Separator { get; set; } /// <summary> /// Gets or sets the separator used to concatenate exception data specified in the Format. /// </summary> /// <docgen category='Rendering Options' order='10' /> [DefaultValue(";")] public string ExceptionDataSeparator { get; set; } /// <summary> /// Gets or sets the maximum number of inner exceptions to include in the output. /// By default inner exceptions are not enabled for compatibility with NLog 1.0. /// </summary> /// <docgen category='Rendering Options' order='10' /> [DefaultValue(0)] public int MaxInnerExceptionLevel { get; set; } /// <summary> /// Gets or sets the separator between inner exceptions. /// </summary> /// <docgen category='Rendering Options' order='10' /> public string InnerExceptionSeparator { get; set; } /// <summary> /// Gets the formats of the output of inner exceptions to be rendered in target. /// </summary> /// <docgen category='Rendering Options' order='10' /> /// <see cref="ExceptionRenderingFormat"/> public List<ExceptionRenderingFormat> Formats { get; private set; } /// <summary> /// Gets the formats of the output to be rendered in target. /// </summary> /// <docgen category='Rendering Options' order='10' /> /// <see cref="ExceptionRenderingFormat"/> public List<ExceptionRenderingFormat> InnerFormats { get; private set; } /// <summary> /// Renders the specified exception information and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { Exception primaryException = logEvent.Exception; if (primaryException != null) { var sb2 = new StringBuilder(128); string separator = string.Empty; foreach (ExceptionRenderingFormat renderingFormat in this.Formats) { var sbCurrentRender = new StringBuilder(); var currentRenderFunction = _renderingfunctions[renderingFormat]; currentRenderFunction(sbCurrentRender, primaryException); if (sbCurrentRender.Length > 0) { sb2.Append(separator); sb2.Append(sbCurrentRender); } separator = this.Separator; } Exception currentException = primaryException.InnerException; int currentLevel = 0; while (currentException != null && currentLevel < this.MaxInnerExceptionLevel) { AppendInnerException(sb2, currentException); currentException = currentException.InnerException; currentLevel++; } #if !NET3_5 && !SILVERLIGHT4 AggregateException asyncException = primaryException as AggregateException; if (asyncException != null) { AppendAggregateException(primaryException, currentLevel, sb2, asyncException); } #endif builder.Append(sb2.ToString()); } } #if !NET3_5 && !SILVERLIGHT4 private void AppendAggregateException(Exception primaryException, int currentLevel, StringBuilder builder, AggregateException asyncException) { asyncException = asyncException.Flatten(); if (asyncException.InnerExceptions != null) { for (int i = 0; i < asyncException.InnerExceptions.Count && currentLevel < this.MaxInnerExceptionLevel; i++, currentLevel++) { var currentException = asyncException.InnerExceptions[i]; if (ReferenceEquals(currentException, primaryException.InnerException)) continue; // Skip firstException when it is innerException if (currentException == null) { InternalLogger.Debug("Skipping rendering exception as exception is null"); continue; } AppendInnerException(builder, currentException); currentLevel++; currentException = currentException.InnerException; while (currentException != null && currentLevel < this.MaxInnerExceptionLevel) { AppendInnerException(builder, currentException); currentException = currentException.InnerException; currentLevel++; } } } } #endif private void AppendInnerException(StringBuilder sb2, Exception currentException) { // separate inner exceptions sb2.Append(this.InnerExceptionSeparator); string separator = string.Empty; foreach (ExceptionRenderingFormat renderingFormat in this.InnerFormats ?? this.Formats) { sb2.Append(separator); var currentRenderFunction = _renderingfunctions[renderingFormat]; currentRenderFunction(sb2, currentException); separator = this.Separator; } } /// <summary> /// Appends the Message of an Exception to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The exception containing the Message to append.</param> protected virtual void AppendMessage(StringBuilder sb, Exception ex) { try { sb.Append(ex.Message); } catch (Exception exception) { var message = $"Exception in {typeof(ExceptionLayoutRenderer).FullName}.AppendMessage(): {exception.GetType().FullName}."; sb.Append("NLog message: "); sb.Append(message); InternalLogger.Warn(exception, message); } } /// <summary> /// Appends the method name from Exception's stack trace to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose method name should be appended.</param> protected virtual void AppendMethod(StringBuilder sb, Exception ex) { #if SILVERLIGHT sb.Append(ParseMethodNameFromStackTrace(ex.StackTrace)); #else if (ex.TargetSite != null) { sb.Append(ex.TargetSite.ToString()); } #endif } /// <summary> /// Appends the stack trace from an Exception to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose stack trace should be appended.</param> protected virtual void AppendStackTrace(StringBuilder sb, Exception ex) { if (!string.IsNullOrEmpty(ex.StackTrace)) sb.Append(ex.StackTrace); } /// <summary> /// Appends the result of calling ToString() on an Exception to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose call to ToString() should be appended.</param> protected virtual void AppendToString(StringBuilder sb, Exception ex) { sb.Append(ex.ToString()); } /// <summary> /// Appends the type of an Exception to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose type should be appended.</param> protected virtual void AppendType(StringBuilder sb, Exception ex) { sb.Append(ex.GetType().FullName); } /// <summary> /// Appends the short type of an Exception to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose short type should be appended.</param> protected virtual void AppendShortType(StringBuilder sb, Exception ex) { sb.Append(ex.GetType().Name); } /// <summary> /// Appends the contents of an Exception's Data property to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="ex">The Exception whose Data property elements should be appended.</param> protected virtual void AppendData(StringBuilder sb, Exception ex) { if (ex.Data != null && ex.Data.Count > 0) { string separator = string.Empty; foreach (var key in ex.Data.Keys) { sb.Append(separator); sb.AppendFormat("{0}: {1}", key, ex.Data[key]); separator = ExceptionDataSeparator; } } } /// <summary> /// Split the string and then compile into list of Rendering formats. /// </summary> /// <param name="formatSpecifier"></param> /// <returns></returns> private static List<ExceptionRenderingFormat> CompileFormat(string formatSpecifier) { List<ExceptionRenderingFormat> formats = new List<ExceptionRenderingFormat>(); string[] parts = formatSpecifier.Replace(" ", string.Empty).Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); foreach (string s in parts) { ExceptionRenderingFormat renderingFormat; if (_formatsMapping.TryGetValue(s, out renderingFormat)) { formats.Add(renderingFormat); } else { InternalLogger.Warn("Unknown exception data target: {0}", s); } } return formats; } #if SILVERLIGHT /// <summary> /// Find name of method on stracktrace. /// </summary> /// <param name="stackTrace">Full stracktrace</param> /// <returns></returns> protected static string ParseMethodNameFromStackTrace(string stackTrace) { if (string.IsNullOrEmpty(stackTrace)) return string.Empty; // get the first line of the stack trace string stackFrameLine; int p = stackTrace.IndexOfAny(new[] { '\r', '\n' }); if (p >= 0) { stackFrameLine = stackTrace.Substring(0, p); } else { stackFrameLine = stackTrace; } // stack trace is composed of lines which look like this // // at NLog.UnitTests.LayoutRenderers.ExceptionTests.GenericClass`3.Method2[T1,T2,T3](T1 aaa, T2 b, T3 o, Int32 i, DateTime now, Nullable`1 gfff, List`1[] something) // // "at " prefix can be localized so we cannot hard-code it but it's followed by a space, class name (which does not have a space in it) and opening parenthesis int lastSpace = -1; int startPos = 0; int endPos = stackFrameLine.Length; for (int i = 0; i < stackFrameLine.Length; ++i) { switch (stackFrameLine[i]) { case ' ': lastSpace = i; break; case '(': startPos = lastSpace + 1; break; case ')': endPos = i + 1; // end the loop i = stackFrameLine.Length; break; } } return stackTrace.Substring(startPos, endPos - startPos); } #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; using System.IO; using System.Text; using System.Diagnostics; using System.Globalization; namespace Microsoft.Xml { using System; // XmlTextEncoder // // This class does special handling of text content for XML. For example // it will replace special characters with entities whenever necessary. internal class XmlTextEncoder { // // Fields // // output text writer private TextWriter _textWriter; // true when writing out the content of attribute value private bool _inAttribute; // quote char of the attribute (when inAttribute) private char _quoteChar; // caching of attribute value private StringBuilder _attrValue; private bool _cacheAttrValue; // XmlCharType private XmlCharType _xmlCharType; // // Constructor // internal XmlTextEncoder(TextWriter textWriter) { _textWriter = textWriter; _quoteChar = '"'; _xmlCharType = XmlCharType.Instance; } // // Internal methods and properties // internal char QuoteChar { set { _quoteChar = value; } } internal void StartAttribute(bool cacheAttrValue) { _inAttribute = true; _cacheAttrValue = cacheAttrValue; if (cacheAttrValue) { if (_attrValue == null) { _attrValue = new StringBuilder(); } else { _attrValue.Length = 0; } } } internal void EndAttribute() { if (_cacheAttrValue) { _attrValue.Length = 0; } _inAttribute = false; _cacheAttrValue = false; } internal string AttributeValue { get { if (_cacheAttrValue) { return _attrValue.ToString(); } else { return String.Empty; } } } internal void WriteSurrogateChar(char lowChar, char highChar) { if (!XmlCharType.IsLowSurrogate(lowChar) || !XmlCharType.IsHighSurrogate(highChar)) { throw XmlConvert.CreateInvalidSurrogatePairException(lowChar, highChar); } _textWriter.Write(highChar); _textWriter.Write(lowChar); } #if FEATURE_NETCORE [System.Security.SecurityCritical] #endif internal void Write(char[] array, int offset, int count) { if (null == array) { throw new ArgumentNullException("array"); } if (0 > offset) { throw new ArgumentOutOfRangeException("offset"); } if (0 > count) { throw new ArgumentOutOfRangeException("count"); } if (count > array.Length - offset) { throw new ArgumentOutOfRangeException("count"); } if (_cacheAttrValue) { _attrValue.Append(array, offset, count); } int endPos = offset + count; int i = offset; char ch = (char)0; for (; ; ) { int startPos = i; unsafe { while (i < endPos && (_xmlCharType.charProperties[ch = array[i]] & XmlCharType.fAttrValue) != 0) { // ( xmlCharType.IsAttributeValueChar( ( ch = array[i] ) ) ) ) { i++; } } if (startPos < i) { _textWriter.Write(array, startPos, i - startPos); } if (i == endPos) { break; } switch (ch) { case (char)0x9: _textWriter.Write(ch); break; case (char)0xA: case (char)0xD: if (_inAttribute) { WriteCharEntityImpl(ch); } else { _textWriter.Write(ch); } break; case '<': WriteEntityRefImpl("lt"); break; case '>': WriteEntityRefImpl("gt"); break; case '&': WriteEntityRefImpl("amp"); break; case '\'': if (_inAttribute && _quoteChar == ch) { WriteEntityRefImpl("apos"); } else { _textWriter.Write('\''); } break; case '"': if (_inAttribute && _quoteChar == ch) { WriteEntityRefImpl("quot"); } else { _textWriter.Write('"'); } break; default: if (XmlCharType.IsHighSurrogate(ch)) { if (i + 1 < endPos) { WriteSurrogateChar(array[++i], ch); } else { throw new ArgumentException(ResXml.Xml_SurrogatePairSplit); } } else if (XmlCharType.IsLowSurrogate(ch)) { throw XmlConvert.CreateInvalidHighSurrogateCharException(ch); } else { Debug.Assert((ch < 0x20 && !_xmlCharType.IsWhiteSpace(ch)) || (ch > 0xFFFD)); WriteCharEntityImpl(ch); } break; } i++; } } internal void WriteSurrogateCharEntity(char lowChar, char highChar) { if (!XmlCharType.IsLowSurrogate(lowChar) || !XmlCharType.IsHighSurrogate(highChar)) { throw XmlConvert.CreateInvalidSurrogatePairException(lowChar, highChar); } int surrogateChar = XmlCharType.CombineSurrogateChar(lowChar, highChar); if (_cacheAttrValue) { _attrValue.Append(highChar); _attrValue.Append(lowChar); } _textWriter.Write("&#x"); _textWriter.Write(surrogateChar.ToString("X", NumberFormatInfo.InvariantInfo)); _textWriter.Write(';'); } #if FEATURE_NETCORE [System.Security.SecurityCritical] #endif internal void Write(string text) { if (text == null) { return; } if (_cacheAttrValue) { _attrValue.Append(text); } // scan through the string to see if there are any characters to be escaped int len = text.Length; int i = 0; int startPos = 0; char ch = (char)0; for (; ; ) { unsafe { while (i < len && (_xmlCharType.charProperties[ch = text[i]] & XmlCharType.fAttrValue) != 0) { // ( xmlCharType.IsAttributeValueChar( ( ch = text[i] ) ) ) ) { i++; } } if (i == len) { // reached the end of the string -> write it whole out _textWriter.Write(text); return; } if (_inAttribute) { if (ch == 0x9) { i++; continue; } } else { if (ch == 0x9 || ch == 0xA || ch == 0xD || ch == '"' || ch == '\'') { i++; continue; } } // some character that needs to be escaped is found: break; } char[] helperBuffer = new char[256]; for (; ; ) { if (startPos < i) { WriteStringFragment(text, startPos, i - startPos, helperBuffer); } if (i == len) { break; } switch (ch) { case (char)0x9: _textWriter.Write(ch); break; case (char)0xA: case (char)0xD: if (_inAttribute) { WriteCharEntityImpl(ch); } else { _textWriter.Write(ch); } break; case '<': WriteEntityRefImpl("lt"); break; case '>': WriteEntityRefImpl("gt"); break; case '&': WriteEntityRefImpl("amp"); break; case '\'': if (_inAttribute && _quoteChar == ch) { WriteEntityRefImpl("apos"); } else { _textWriter.Write('\''); } break; case '"': if (_inAttribute && _quoteChar == ch) { WriteEntityRefImpl("quot"); } else { _textWriter.Write('"'); } break; default: if (XmlCharType.IsHighSurrogate(ch)) { if (i + 1 < len) { WriteSurrogateChar(text[++i], ch); } else { throw XmlConvert.CreateInvalidSurrogatePairException(text[i], ch); } } else if (XmlCharType.IsLowSurrogate(ch)) { throw XmlConvert.CreateInvalidHighSurrogateCharException(ch); } else { Debug.Assert((ch < 0x20 && !_xmlCharType.IsWhiteSpace(ch)) || (ch > 0xFFFD)); WriteCharEntityImpl(ch); } break; } i++; startPos = i; unsafe { while (i < len && (_xmlCharType.charProperties[ch = text[i]] & XmlCharType.fAttrValue) != 0) { // ( xmlCharType.IsAttributeValueChar( ( text[i] ) ) ) ) { i++; } } } } #if FEATURE_NETCORE [System.Security.SecurityCritical] #endif internal void WriteRawWithSurrogateChecking(string text) { if (text == null) { return; } if (_cacheAttrValue) { _attrValue.Append(text); } int len = text.Length; int i = 0; char ch = (char)0; for (; ; ) { unsafe { while (i < len && ((_xmlCharType.charProperties[ch = text[i]] & XmlCharType.fCharData) != 0 // ( xmlCharType.IsCharData( ( ch = text[i] ) ) || ch < 0x20)) { i++; } } if (i == len) { break; } if (XmlCharType.IsHighSurrogate(ch)) { if (i + 1 < len) { char lowChar = text[i + 1]; if (XmlCharType.IsLowSurrogate(lowChar)) { i += 2; continue; } else { throw XmlConvert.CreateInvalidSurrogatePairException(lowChar, ch); } } throw new ArgumentException(ResXml.Xml_InvalidSurrogateMissingLowChar); } else if (XmlCharType.IsLowSurrogate(ch)) { throw XmlConvert.CreateInvalidHighSurrogateCharException(ch); } else { i++; } } _textWriter.Write(text); return; } internal void WriteRaw(string value) { if (_cacheAttrValue) { _attrValue.Append(value); } _textWriter.Write(value); } internal void WriteRaw(char[] array, int offset, int count) { if (null == array) { throw new ArgumentNullException("array"); } if (0 > count) { throw new ArgumentOutOfRangeException("count"); } if (0 > offset) { throw new ArgumentOutOfRangeException("offset"); } if (count > array.Length - offset) { throw new ArgumentOutOfRangeException("count"); } if (_cacheAttrValue) { _attrValue.Append(array, offset, count); } _textWriter.Write(array, offset, count); } internal void WriteCharEntity(char ch) { if (XmlCharType.IsSurrogate(ch)) { throw new ArgumentException(ResXml.Xml_InvalidSurrogateMissingLowChar); } string strVal = ((int)ch).ToString("X", NumberFormatInfo.InvariantInfo); if (_cacheAttrValue) { _attrValue.Append("&#x"); _attrValue.Append(strVal); _attrValue.Append(';'); } WriteCharEntityImpl(strVal); } internal void WriteEntityRef(string name) { if (_cacheAttrValue) { _attrValue.Append('&'); _attrValue.Append(name); _attrValue.Append(';'); } WriteEntityRefImpl(name); } internal void Flush() { // TODO? } // // Private implementation methods // // This is a helper method to woraround the fact that TextWriter does not have a Write method // for fragment of a string such as Write( string, offset, count). // The string fragment will be written out by copying into a small helper buffer and then // calling textWriter to write out the buffer. private void WriteStringFragment(string str, int offset, int count, char[] helperBuffer) { int bufferSize = helperBuffer.Length; while (count > 0) { int copyCount = count; if (copyCount > bufferSize) { copyCount = bufferSize; } str.CopyTo(offset, helperBuffer, 0, copyCount); _textWriter.Write(helperBuffer, 0, copyCount); offset += copyCount; count -= copyCount; } } private void WriteCharEntityImpl(char ch) { WriteCharEntityImpl(((int)ch).ToString("X", NumberFormatInfo.InvariantInfo)); } private void WriteCharEntityImpl(string strVal) { _textWriter.Write("&#x"); _textWriter.Write(strVal); _textWriter.Write(';'); } private void WriteEntityRefImpl(string name) { _textWriter.Write('&'); _textWriter.Write(name); _textWriter.Write(';'); } } }
/* * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */ namespace TypeSql.Antlr.Runtime.Tree { using System.Collections.Generic; using StringBuilder = System.Text.StringBuilder; /** A utility class to generate DOT diagrams (graphviz) from * arbitrary trees. You can pass in your own templates and * can pass in any kind of tree or use Tree interface method. * I wanted this separator so that you don't have to include * ST just to use the org.antlr.runtime.tree.* package. * This is a set of non-static methods so you can subclass * to override. For example, here is an invocation: * * CharStream input = new ANTLRInputStream(System.in); * TLexer lex = new TLexer(input); * CommonTokenStream tokens = new CommonTokenStream(lex); * TParser parser = new TParser(tokens); * TParser.e_return r = parser.e(); * Tree t = (Tree)r.tree; * System.out.println(t.toStringTree()); * DOTTreeGenerator gen = new DOTTreeGenerator(); * StringTemplate st = gen.toDOT(t); * System.out.println(st); */ public class DotTreeGenerator { readonly string[] HeaderLines = { "digraph {", "", "\tordering=out;", "\tranksep=.4;", "\tbgcolor=\"lightgrey\"; node [shape=box, fixedsize=false, fontsize=12, fontname=\"Helvetica-bold\", fontcolor=\"blue\"", "\t\twidth=.25, height=.25, color=\"black\", fillcolor=\"white\", style=\"filled, solid, bold\"];", "\tedge [arrowsize=.5, color=\"black\", style=\"bold\"]", "" }; const string Footer = "}"; const string NodeFormat = " {0} [label=\"{1}\"];"; const string EdgeFormat = " {0} -> {1} // \"{2}\" -> \"{3}\""; /** Track node to number mapping so we can get proper node name back */ Dictionary<object, int> nodeToNumberMap = new Dictionary<object, int>(); /** Track node number so we can get unique node names */ int nodeNumber = 0; /** Generate DOT (graphviz) for a whole tree not just a node. * For example, 3+4*5 should generate: * * digraph { * node [shape=plaintext, fixedsize=true, fontsize=11, fontname="Courier", * width=.4, height=.2]; * edge [arrowsize=.7] * "+"->3 * "+"->"*" * "*"->4 * "*"->5 * } * * Takes a Tree interface object. */ public virtual string ToDot( object tree, ITreeAdaptor adaptor ) { StringBuilder builder = new StringBuilder(); foreach ( string line in HeaderLines ) builder.AppendLine( line ); nodeNumber = 0; var nodes = DefineNodes( tree, adaptor ); nodeNumber = 0; var edges = DefineEdges( tree, adaptor ); foreach ( var s in nodes ) builder.AppendLine( s ); builder.AppendLine(); foreach ( var s in edges ) builder.AppendLine( s ); builder.AppendLine(); builder.AppendLine( Footer ); return builder.ToString(); } public virtual string ToDot( ITree tree ) { return ToDot( tree, new CommonTreeAdaptor() ); } protected virtual IEnumerable<string> DefineNodes( object tree, ITreeAdaptor adaptor ) { if ( tree == null ) yield break; int n = adaptor.GetChildCount( tree ); if ( n == 0 ) { // must have already dumped as child from previous // invocation; do nothing yield break; } // define parent node yield return GetNodeText( adaptor, tree ); // for each child, do a "<unique-name> [label=text]" node def for ( int i = 0; i < n; i++ ) { object child = adaptor.GetChild( tree, i ); yield return GetNodeText( adaptor, child ); foreach ( var t in DefineNodes( child, adaptor ) ) yield return t; } } protected virtual IEnumerable<string> DefineEdges( object tree, ITreeAdaptor adaptor ) { if ( tree == null ) yield break; int n = adaptor.GetChildCount( tree ); if ( n == 0 ) { // must have already dumped as child from previous // invocation; do nothing yield break; } string parentName = "n" + GetNodeNumber( tree ); // for each child, do a parent -> child edge using unique node names string parentText = adaptor.GetText( tree ); for ( int i = 0; i < n; i++ ) { object child = adaptor.GetChild( tree, i ); string childText = adaptor.GetText( child ); string childName = "n" + GetNodeNumber( child ); yield return string.Format( EdgeFormat, parentName, childName, FixString( parentText ), FixString( childText ) ); foreach ( var t in DefineEdges( child, adaptor ) ) yield return t; } } protected virtual string GetNodeText( ITreeAdaptor adaptor, object t ) { string text = adaptor.GetText( t ); string uniqueName = "n" + GetNodeNumber( t ); return string.Format( NodeFormat, uniqueName, FixString( text ) ); } protected virtual int GetNodeNumber( object t ) { int i; if ( nodeToNumberMap.TryGetValue( t, out i ) ) { return i; } else { nodeToNumberMap[t] = nodeNumber; nodeNumber++; return nodeNumber - 1; } } protected virtual string FixString( string text ) { if ( text != null ) { text = System.Text.RegularExpressions.Regex.Replace( text, "\"", "\\\\\"" ); text = System.Text.RegularExpressions.Regex.Replace( text, "\\t", " " ); text = System.Text.RegularExpressions.Regex.Replace( text, "\\n", "\\\\n" ); text = System.Text.RegularExpressions.Regex.Replace( text, "\\r", "\\\\r" ); if ( text.Length > 20 ) text = text.Substring( 0, 8 ) + "..." + text.Substring( text.Length - 8 ); } return text; } } }
using System; using System.Collections.Generic; using System.Text; using System.Xml.Serialization; using Rynchodon.Attached; using Rynchodon.Autopilot; using Rynchodon.Instructions; using Rynchodon.Utility; using Rynchodon.Utility.Network; using Sandbox.Game.Entities.Blocks; using Sandbox.Game.Entities.Cube; using Sandbox.Game.Gui; using Sandbox.ModAPI; using VRage.Collections; using VRage.Game.ModAPI; using VRage.Utils; using VRageMath; using Ingame = Sandbox.ModAPI.Ingame; namespace Rynchodon.AntennaRelay { public class TextPanel : BlockInstructions { [Serializable] public class Builder_TextPanel { [XmlAttribute] public long BlockId; public byte Options; } [Flags] private enum Option : byte { None = 0, DisplayDetected = 1, GPS = 2, EntityId = 4, AutopilotStatus = 8, Refresh = 16, } private const char separator = ':'; private const string radarIconId = "Radar"; private const string timeString = "Current as of: "; private const string tab = " "; private static readonly char[] OptionsSeparators = { ',', ';', ':' }; private static readonly List<long> s_detectedIds = new List<long>(); [OnWorldLoad] private static void CreateTerminal() { Logger.DebugLog("entered", Logger.severity.TRACE); TerminalControlHelper.EnsureTerminalControlCreated<MyTextPanel>(); MyTerminalAction<MyTextPanel> textPanel_displayEntities = new MyTerminalAction<MyTextPanel>("DisplayEntities", new StringBuilder("Display Entities"), "Textures\\GUI\\Icons\\Actions\\Start.dds") { ValidForGroups = false, ActionWithParameters = TextPanel_DisplayEntities }; MyTerminalControlFactory.AddAction(textPanel_displayEntities); MyTerminalControlFactory.AddControl(new MyTerminalControlSeparator<MyTextPanel>()); AddCheckbox("DisplayDetected", "Display Detected", "Write detected entities to the public text of the panel", Option.DisplayDetected); AddCheckbox("DisplayGPS", "Display GPS", "Write gps with detected entities", Option.GPS); AddCheckbox("DisplayEntityId", "Display Entity ID", "Write entity ID with detected entities", Option.EntityId); AddCheckbox("DisplayAutopilotStatus", "Display Autopilot Status", "Write the status of nearby Autopilots to the public text of the panel", Option.AutopilotStatus); } private static void AddCheckbox(string id, string title, string toolTip, Option opt) { MyTerminalControlCheckbox<MyTextPanel> control = new MyTerminalControlCheckbox<MyTextPanel>(id, MyStringId.GetOrCompute(title), MyStringId.GetOrCompute(toolTip)); new ValueSync<bool, TextPanel>(control, (panel) => (panel.m_optionsTerminal & opt) == opt, (panel, value) => { if (value) panel.m_optionsTerminal |= opt; else panel.m_optionsTerminal &= ~opt; }); MyTerminalControlFactory.AddControl(control); } /// <param name="args">EntityIds as long</param> private static void TextPanel_DisplayEntities(MyFunctionalBlock block, ListReader<Ingame.TerminalActionParameter> args) { s_detectedIds.Clear(); for (int i = 0; i < args.Count; i++) { if (args[i].TypeCode != TypeCode.Int64) { Logger.DebugLog("TerminalActionParameter # " + i + " is of wrong type, expected Int64, got " + args[i].TypeCode, Logger.severity.WARNING); if (MyAPIGateway.Session.Player != null) block.AppendCustomInfo("Failed to display entities:\nTerminalActionParameter #" + i + " is of wrong type, expected Int64 (AKA long), got " + args[i].TypeCode + '\n'); return; } s_detectedIds.Add((long)args[i].Value); } TextPanel panel; if (!Registrar.TryGetValue(block.EntityId, out panel)) { Logger.AlwaysLog("Text panel not found in registrar: " + block.EntityId, Logger.severity.ERROR); return; } Logger.DebugLog("Found text panel with id: " + block.EntityId); panel.Display(s_detectedIds); } private readonly Ingame.IMyTextPanel m_textPanel; private Option m_optionsTerminal; private IMyTerminalBlock myTermBlock; private RelayClient m_networkClient; private Option m_options; private List<sortableLastSeen> m_sortableList; private TimeSpan m_lastDisplay; private Logable Log { get { return new Logable(myTermBlock); } } public TextPanel(IMyCubeBlock block) : base(block) { m_textPanel = block as Ingame.IMyTextPanel; myTermBlock = block as IMyTerminalBlock; m_networkClient = new RelayClient(block); Log.DebugLog("init: " + m_block.DisplayNameText); Registrar.Add(block, this); } public void ResumeFromSave(Builder_TextPanel builder) { if (this.m_block.EntityId != builder.BlockId) throw new ArgumentException("Serialized block id " + builder.BlockId + " does not match block id " + this.m_block.EntityId); this.m_optionsTerminal = (Option)builder.Options; } protected override bool ParseAll(string instructions) { string[] opts = instructions.RemoveWhitespace().Split(OptionsSeparators); m_options = Option.None; foreach (string opt in opts) { float dontCare; if (float.TryParse(opt, out dontCare)) return false; Option option; if (Enum.TryParse(opt, true, out option)) m_options |= option; else return false; } return m_options != Option.None; } public void Update100() { UpdateInstructions(); if (m_optionsTerminal != Option.None) m_options = m_optionsTerminal; else if (!HasInstructions) return; if ((m_options & Option.DisplayDetected) != 0) Display(); else if ((m_options & Option.AutopilotStatus) != 0) DisplyAutopilotStatus(); if ((m_options & Option.Refresh) != 0) { m_textPanel.ShowTextureOnScreen(); m_textPanel.ShowPublicTextOnScreen(); } } private void Display(List<long> entityIds = null) { if (entityIds != null) UpdateInstructions(); //Log.DebugLog("Building display list", "Display()", Logger.severity.TRACE); RelayStorage store = m_networkClient.GetStorage(); if (store == null) { m_textPanel.WritePublicText("No network connection"); return; } m_sortableList = ResourcePool<List<sortableLastSeen>>.Get(); if (entityIds == null) AllLastSeen(store); else SelectLastSeen(store, entityIds); if (m_sortableList.Count == 0) { m_textPanel.WritePublicText("No entities detected"); m_sortableList.Clear(); ResourcePool<List<sortableLastSeen>>.Return(m_sortableList); return; } m_lastDisplay = Globals.ElapsedTime; m_sortableList.Sort(); StringBuilder displayText = new StringBuilder(); displayText.Append(timeString); displayText.Append(DateTime.Now.ToLongTimeString()); displayText.AppendLine(); int count = 0; foreach (sortableLastSeen sortable in m_sortableList) { sortable.TextForPlayer(displayText, count++); if (count >= 20) break; } m_sortableList.Clear(); ResourcePool<List<sortableLastSeen>>.Return(m_sortableList); string displayString = displayText.ToString(); //Log.DebugLog("Writing to panel: " + m_textPanel.DisplayNameText + ":\n\t" + displayString, "Display()", Logger.severity.TRACE); m_textPanel.WritePublicText(displayText.ToString()); } private void AllLastSeen(RelayStorage store) { Vector3D myPos = m_block.GetPosition(); store.ForEachLastSeen((LastSeen seen) => { IMyCubeGrid grid = seen.Entity as IMyCubeGrid; if (grid != null && AttachedGrid.IsGridAttached(m_block.CubeGrid, grid, AttachedGrid.AttachmentKind.Physics)) return; ExtensionsRelations.Relations relations = m_block.getRelationsTo(seen.Entity, ExtensionsRelations.Relations.Enemy).highestPriority(); m_sortableList.Add(new sortableLastSeen(myPos, seen, relations, m_options)); //Log.DebugLog("item: " + seen.Entity.getBestName() + ", relations: " + relations, "Display()"); }); } private void SelectLastSeen(RelayStorage store, List<long> entityIds) { Vector3D myPos = m_block.GetPosition(); foreach (long id in entityIds) { LastSeen seen; if (store.TryGetLastSeen(id, out seen)) { ExtensionsRelations.Relations relations = m_block.getRelationsTo(seen.Entity, ExtensionsRelations.Relations.Enemy).highestPriority(); m_sortableList.Add(new sortableLastSeen(myPos, seen, relations, m_options)); //Log.DebugLog("item: " + seen.Entity.getBestName() + ", relations: " + relations, "Display_FromProgram()"); } } } private void DisplyAutopilotStatus() { //Log.DebugLog("Building autopilot list", "DisplyAutopilotStatus()", Logger.severity.TRACE); RelayStorage store = m_networkClient.GetStorage(); if (store == null) { m_textPanel.WritePublicText("No network connection"); return; } List<SortableAutopilot> autopilots = ResourcePool<List<SortableAutopilot>>.Get(); Vector3D mypos = m_block.GetPosition(); Registrar.ForEach<AutopilotTerminal>(ap => { IRelayPart relayPart; if (RelayClient.TryGetRelayPart((IMyCubeBlock)ap.m_block, out relayPart) && relayPart.GetStorage() == store && m_block.canControlBlock(ap.m_block)) autopilots.Add(new SortableAutopilot(ap, mypos)); }); autopilots.Sort(); StringBuilder displayText = new StringBuilder(); displayText.Append(timeString); displayText.Append(DateTime.Now.ToLongTimeString()); displayText.AppendLine(); int count = 0; foreach (SortableAutopilot ap in autopilots) { displayText.Append(tab); displayText.Append(ap.Autopilot.m_block.CubeGrid.DisplayName); displayText.Append(tab); displayText.Append(PrettySI.makePretty(ap.Distance)); displayText.AppendLine("m"); ap.Autopilot.AppendingCustomInfo(displayText); displayText.AppendLine(); count++; if (count >= 5) break; } autopilots.Clear(); ResourcePool<List<SortableAutopilot>>.Return(autopilots); string displayString = displayText.ToString(); //Log.DebugLog("Writing to panel: " + m_textPanel.DisplayNameText + ":\n\t" + displayString, "DisplyAutopilotStatus()", Logger.severity.TRACE); m_textPanel.WritePublicText(displayText.ToString()); } private class sortableLastSeen : IComparable<sortableLastSeen> { private readonly ExtensionsRelations.Relations relations; private readonly double distance; private readonly int seconds; private readonly LastSeen seen; private readonly Vector3D predictedPos; private readonly Option options; private static readonly string GPStag1 = tab + tab + "GPS"; private sortableLastSeen() { } public sortableLastSeen(Vector3D myPos, LastSeen seen, ExtensionsRelations.Relations relations, Option options) { this.seen = seen; this.relations = relations; TimeSpan sinceLastSeen; predictedPos = seen.predictPosition(out sinceLastSeen); distance = (predictedPos - myPos).Length(); seconds = (int)sinceLastSeen.TotalSeconds; this.options = options; } public void TextForPlayer(StringBuilder builder, int count) { string time = (seconds / 60).ToString("00") + separator + (seconds % 60).ToString("00"); bool friendly = relations.HasAnyFlag(ExtensionsRelations.Relations.Faction) || relations.HasAnyFlag(ExtensionsRelations.Relations.Owner); string bestName = friendly ? seen.Entity.getBestName() : seen.HostileName(); builder.Append(relations); builder.Append(tab); builder.Append(seen.Type); builder.Append(tab); //if (friendly) //{ builder.Append(bestName); builder.Append(tab); //} if (!friendly) { if (seen.isRecent_Radar()) { builder.Append("Has Radar"); builder.Append(tab); } if (seen.isRecent_Jam()) { builder.Append("Has Jammer"); builder.Append(tab); } } builder.AppendLine(); builder.Append(tab); builder.Append(tab); builder.Append(PrettySI.makePretty(distance)); builder.Append('m'); builder.Append(tab); builder.Append(time); if (seen.RadarInfoIsRecent()) { builder.Append(tab); builder.Append(seen.Info.Pretty_Volume()); } builder.AppendLine(); // GPS tag if ((options & Option.GPS) != 0) { builder.Append(GPStag1); if (friendly) builder.Append(bestName); else { builder.Append(relations); builder.Append(seen.Type); builder.Append('#'); builder.Append(count); } builder.Append(separator); builder.Append((int)predictedPos.X); builder.Append(separator); builder.Append((int)predictedPos.Y); builder.Append(separator); builder.Append((int)predictedPos.Z); builder.Append(separator); builder.AppendLine(); } // Entity id if ((options & Option.EntityId) != 0) { builder.Append(tab); builder.Append(tab); builder.Append("ID: "); builder.Append(seen.Entity.EntityId); builder.AppendLine(); } } /// <summary> /// sort by relations, then by distance /// </summary> public int CompareTo(sortableLastSeen other) { if (this.relations != other.relations) return this.relations.CompareTo(other.relations); return this.distance.CompareTo(other.distance); } } private class SortableAutopilot : IComparable<SortableAutopilot> { private float? distance; public readonly AutopilotTerminal Autopilot; public readonly float DistanceSquared; public float Distance { get { if (!distance.HasValue) distance = (float)Math.Sqrt(DistanceSquared); return distance.Value; } } public SortableAutopilot(AutopilotTerminal autopilot, Vector3D mypos) { this.distance = null; this.Autopilot = autopilot; this.DistanceSquared = (float)Vector3D.DistanceSquared(autopilot.m_block.GetPosition(), mypos); } public int CompareTo(SortableAutopilot other) { if (this.Autopilot.m_autopilotStatus == other.Autopilot.m_autopilotStatus) { Logger.DebugLog("same status: " + this.Autopilot.m_autopilotStatus); return this.DistanceSquared.CompareTo(other.DistanceSquared); } Logger.DebugLog("diff status: " + this.Autopilot.m_autopilotStatus + " vs " + other.Autopilot.m_autopilotStatus + ", diff: " + ((int)other.Autopilot.m_autopilotStatus - (int)this.Autopilot.m_autopilotStatus)); return (int)other.Autopilot.m_autopilotStatus - (int)this.Autopilot.m_autopilotStatus; } } } }
using System; using System.IO; using System.Linq; using System.Threading.Tasks; using Baseline; using Marten.Exceptions; using Marten.Schema; using Weasel.Postgresql; namespace Marten.Storage { public class TenantSchema: IDocumentSchema { private readonly StorageFeatures _features; private readonly Tenant _tenant; public TenantSchema(StoreOptions options, Tenant tenant) { _features = options.Storage; _tenant = tenant; StoreOptions = options; DdlRules = options.Advanced.DdlRules; } public StoreOptions StoreOptions { get; } public DdlRules DdlRules { get; } public void WriteDatabaseCreationScriptFile(string filename) { var sql = ToDatabaseScript(); new FileSystem().WriteStringToFile(filename, sql); } public void WriteDatabaseCreationScriptByType(string directory) { var system = new FileSystem(); system.DeleteDirectory(directory); system.CreateDirectory(directory); var features = _features.AllActiveFeatures(_tenant).ToArray(); writeDatabaseSchemaGenerationScript(directory, system, features); foreach (var feature in features) { var file = directory.AppendPath(feature.Identifier + ".sql"); DdlRules.WriteTemplatedFile(file, (r, w) => { feature.Write(r, w); }); } } private void writeDatabaseSchemaGenerationScript(string directory, FileSystem system, IFeatureSchema[] schemaObjects) { var allSchemaNames = StoreOptions.Storage.AllSchemaNames(); var script = DatabaseSchemaGenerator.GenerateScript(StoreOptions, allSchemaNames); var writer = new StringWriter(); if (script.IsNotEmpty()) { writer.WriteLine(script); writer.WriteLine(); } foreach (var feature in schemaObjects) { writer.WriteLine($"\\i {feature.Identifier}.sql"); } var filename = directory.AppendPath("all.sql"); system.WriteStringToFile(filename, writer.ToString()); } public async Task<SchemaMigration> CreateMigration() { var @objects = _features.AllActiveFeatures(_tenant).SelectMany(x => x.Objects).ToArray(); using var conn = _tenant.CreateConnection(); await conn.OpenAsync(); return await SchemaMigration.Determine(conn, @objects); } public string ToDatabaseScript() { var writer = new StringWriter(); StoreOptions.Advanced.DdlRules.WriteScript(writer, (r, w) => { var allSchemaNames = StoreOptions.Storage.AllSchemaNames(); DatabaseSchemaGenerator.WriteSql(StoreOptions, allSchemaNames, w); foreach (var feature in _features.AllActiveFeatures(_tenant)) { feature.Write(r, w); } }); return writer.ToString(); } public async Task WriteMigrationFile(string filename) { if (!Path.IsPathRooted(filename)) { filename = AppContext.BaseDirectory.AppendPath(filename); } var patch = await CreateMigration(); DdlRules.WriteTemplatedFile(filename, (r, w) => { patch.WriteAllUpdates(w, r, AutoCreate.All); }); var dropFile = SchemaMigration.ToDropFileName(filename); DdlRules.WriteTemplatedFile(dropFile, (r, w) => { patch.WriteAllRollbacks(w, r); }); } public async Task AssertDatabaseMatchesConfiguration() { var patch = await CreateMigration(); if (patch.Difference != SchemaPatchDifference.None) { throw new SchemaValidationException(patch.UpdateSql); } } public async Task ApplyAllConfiguredChangesToDatabase(AutoCreate? withCreateSchemaObjects = null) { var defaultAutoCreate = StoreOptions.AutoCreateSchemaObjects != AutoCreate.None ? StoreOptions.AutoCreateSchemaObjects : AutoCreate.CreateOrUpdate; var patch = await CreateMigration(); if (patch.Difference == SchemaPatchDifference.None) return; using var conn = _tenant.CreateConnection(); await conn.OpenAsync(); try { var martenLogger = StoreOptions.Logger(); await patch.ApplyAll(conn, DdlRules, withCreateSchemaObjects ?? defaultAutoCreate, sql => martenLogger.SchemaChange(sql)); _tenant.MarkAllFeaturesAsChecked(); } catch (Exception e) { throw new MartenSchemaException("All Configured Changes", patch.UpdateSql, e); } } public async Task<SchemaMigration> CreateMigration(Type documentType) { var mapping = _features.MappingFor(documentType); using var conn = _tenant.CreateConnection(); await conn.OpenAsync(); var migration = await SchemaMigration.Determine(conn, mapping.Schema.Objects); return migration; } public async Task WriteMigrationFileByType(string directory) { var system = new FileSystem(); system.DeleteDirectory(directory); system.CreateDirectory(directory); var features = _features.AllActiveFeatures(_tenant).ToArray(); writeDatabaseSchemaGenerationScript(directory, system, features); using var conn = _tenant.CreateConnection(); await conn.OpenAsync(); foreach (var feature in features) { var migration = await SchemaMigration.Determine(conn, feature.Objects); if (migration.Difference == SchemaPatchDifference.None) { continue; } var file = directory.AppendPath(feature.Identifier + ".sql"); DdlRules.WriteTemplatedFile(file, (r, w) => { migration.WriteAllUpdates(w, r, AutoCreate.CreateOrUpdate); }); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Win32; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Threading; using System; #if !ES_BUILD_AGAINST_DOTNET_V35 using Contract = System.Diagnostics.Contracts.Contract; #else using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract; #endif #if ES_BUILD_AGAINST_DOTNET_V35 using Microsoft.Internal; // for Tuple (can't define alias for open generic types so we "use" the whole namespace) #endif #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { // New in CLR4.0 internal enum ControllerCommand { // Strictly Positive numbers are for provider-specific commands, negative number are for 'shared' commands. 256 // The first 256 negative numbers are reserved for the framework. Update = 0, // Not used by EventPrividerBase. SendManifest = -1, Enable = -2, Disable = -3, }; /// <summary> /// Only here because System.Diagnostics.EventProvider needs one more extensibility hook (when it gets a /// controller callback) /// </summary> [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] internal class EventProvider : IDisposable { // This is the windows EVENT_DATA_DESCRIPTOR structure. We expose it because this is what // subclasses of EventProvider use when creating efficient (but unsafe) version of // EventWrite. We do make it a nested type because we really don't expect anyone to use // it except subclasses (and then only rarely). public struct EventData { internal unsafe ulong Ptr; internal uint Size; internal uint Reserved; } /// <summary> /// A struct characterizing ETW sessions (identified by the etwSessionId) as /// activity-tracing-aware or legacy. A session that's activity-tracing-aware /// has specified one non-zero bit in the reserved range 44-47 in the /// 'allKeywords' value it passed in for a specific EventProvider. /// </summary> public struct SessionInfo { internal int sessionIdBit; // the index of the bit used for tracing in the "reserved" field of AllKeywords internal int etwSessionId; // the machine-wide ETW session ID internal SessionInfo(int sessionIdBit_, int etwSessionId_) { sessionIdBit = sessionIdBit_; etwSessionId = etwSessionId_; } } private static bool m_setInformationMissing; [SecurityCritical] UnsafeNativeMethods.ManifestEtw.EtwEnableCallback m_etwCallback; // Trace Callback function private long m_regHandle; // Trace Registration Handle private byte m_level; // Tracing Level private long m_anyKeywordMask; // Trace Enable Flags private long m_allKeywordMask; // Match all keyword private List<SessionInfo> m_liveSessions; // current live sessions (Tuple<sessionIdBit, etwSessionId>) private bool m_enabled; // Enabled flag from Trace callback private Guid m_providerId; // Control Guid internal bool m_disposed; // when true provider has unregistered [ThreadStatic] private static WriteEventErrorCode s_returnCode; // The last return code private const int s_basicTypeAllocationBufferSize = 16; private const int s_etwMaxNumberArguments = 32; private const int s_etwAPIMaxRefObjCount = 8; private const int s_maxEventDataDescriptors = 128; private const int s_traceEventMaximumSize = 65482; private const int s_traceEventMaximumStringSize = 32724; [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] public enum WriteEventErrorCode : int { //check mapping to runtime codes NoError = 0, NoFreeBuffers = 1, EventTooBig = 2, NullInput = 3, TooManyArgs = 4, Other = 5, }; // <SecurityKernel Critical="True" Ring="1"> // <ReferencesCritical Name="Method: Register():Void" Ring="1" /> // </SecurityKernel> /// <summary> /// Constructs a new EventProvider. This causes the class to be registered with the OS and /// if an ETW controller turns on the logging then logging will start. /// </summary> /// <param name="providerGuid">The GUID that identifies this provider to the system.</param> [System.Security.SecurityCritical] #pragma warning disable 618 [PermissionSet(SecurityAction.Demand, Unrestricted = true)] #pragma warning restore 618 [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "guid")] protected EventProvider(Guid providerGuid) { m_providerId = providerGuid; // // Register the ProviderId with ETW // Register(providerGuid); } internal EventProvider() { } /// <summary> /// This method registers the controlGuid of this class with ETW. We need to be running on /// Vista or above. If not a PlatformNotSupported exception will be thrown. If for some /// reason the ETW Register call failed a NotSupported exception will be thrown. /// </summary> // <SecurityKernel Critical="True" Ring="0"> // <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventRegister(System.Guid&,Microsoft.Win32.UnsafeNativeMethods.ManifestEtw+EtwEnableCallback,System.Void*,System.Int64&):System.UInt32" /> // <SatisfiesLinkDemand Name="Win32Exception..ctor(System.Int32)" /> // <ReferencesCritical Name="Method: EtwEnableCallBack(Guid&, Int32, Byte, Int64, Int64, Void*, Void*):Void" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] internal unsafe void Register(Guid providerGuid) { m_providerId = providerGuid; uint status; m_etwCallback = new UnsafeNativeMethods.ManifestEtw.EtwEnableCallback(EtwEnableCallBack); status = EventRegister(ref m_providerId, m_etwCallback); if (status != 0) { throw new ArgumentException(Win32Native.GetMessage(unchecked((int)status))); } } [System.Security.SecurityCritical] internal unsafe int SetInformation( UnsafeNativeMethods.ManifestEtw.EVENT_INFO_CLASS eventInfoClass, void* data, int dataSize) { int status = UnsafeNativeMethods.ManifestEtw.ERROR_NOT_SUPPORTED; if (!m_setInformationMissing) { try { status = UnsafeNativeMethods.ManifestEtw.EventSetInformation( m_regHandle, eventInfoClass, data, dataSize); } catch (TypeLoadException) { m_setInformationMissing = true; } } return status; } // // implement Dispose Pattern to early deregister from ETW insted of waiting for // the finalizer to call deregistration. // Once the user is done with the provider it needs to call Close() or Dispose() // If neither are called the finalizer will unregister the provider anyway // public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } // <SecurityKernel Critical="True" TreatAsSafe="Does not expose critical resource" Ring="1"> // <ReferencesCritical Name="Method: Deregister():Void" Ring="1" /> // </SecurityKernel> [System.Security.SecuritySafeCritical] protected virtual void Dispose(bool disposing) { // // explicit cleanup is done by calling Dispose with true from // Dispose() or Close(). The disposing arguement is ignored because there // are no unmanaged resources. // The finalizer calls Dispose with false. // // // check if the object has been allready disposed // if (m_disposed) return; // Disable the provider. m_enabled = false; // Do most of the work under a lock to avoid shutdown race. lock (EventListener.EventListenersLock) { // Double check if (m_disposed) return; Deregister(); m_disposed = true; } } /// <summary> /// This method deregisters the controlGuid of this class with ETW. /// /// </summary> public virtual void Close() { Dispose(); } ~EventProvider() { Dispose(false); } /// <summary> /// This method un-registers from ETW. /// </summary> // <SecurityKernel Critical="True" Ring="0"> // <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventUnregister(System.Int64):System.Int32" /> // </SecurityKernel> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "Microsoft.Win32.UnsafeNativeMethods.ManifestEtw.EventUnregister(System.Int64)"), System.Security.SecurityCritical] private unsafe void Deregister() { // // Unregister from ETW using the RegHandle saved from // the register call. // if (m_regHandle != 0) { EventUnregister(); m_regHandle = 0; } } // <SecurityKernel Critical="True" Ring="0"> // <UsesUnsafeCode Name="Parameter filterData of type: Void*" /> // <UsesUnsafeCode Name="Parameter callbackContext of type: Void*" /> // </SecurityKernel> [System.Security.SecurityCritical] unsafe void EtwEnableCallBack( [In] ref System.Guid sourceId, [In] int controlCode, [In] byte setLevel, [In] long anyKeyword, [In] long allKeyword, [In] UnsafeNativeMethods.ManifestEtw.EVENT_FILTER_DESCRIPTOR* filterData, [In] void* callbackContext ) { // This is an optional callback API. We will therefore ignore any failures that happen as a // result of turning on this provider as to not crash the app. // EventSource has code to validate whther initialization it expected to occur actually occurred try { ControllerCommand command = ControllerCommand.Update; IDictionary<string, string> args = null; byte[] data; int keyIndex; bool skipFinalOnControllerCommand = false; if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_ENABLE_PROVIDER) { m_enabled = true; m_level = setLevel; m_anyKeywordMask = anyKeyword; m_allKeywordMask = allKeyword; List<Tuple<SessionInfo, bool>> sessionsChanged = GetSessions(); foreach (var session in sessionsChanged) { int sessionChanged = session.Item1.sessionIdBit; int etwSessionId = session.Item1.etwSessionId; bool bEnabling = session.Item2; skipFinalOnControllerCommand = true; args = null; // reinitialize args for every session... // if we get more than one session changed we have no way // of knowing which one "filterData" belongs to if (sessionsChanged.Count > 1) filterData = null; // read filter data only when a session is being *added* if (bEnabling && GetDataFromController(etwSessionId, filterData, out command, out data, out keyIndex)) { args = new Dictionary<string, string>(4); while (keyIndex < data.Length) { int keyEnd = FindNull(data, keyIndex); int valueIdx = keyEnd + 1; int valueEnd = FindNull(data, valueIdx); if (valueEnd < data.Length) { string key = System.Text.Encoding.UTF8.GetString(data, keyIndex, keyEnd - keyIndex); string value = System.Text.Encoding.UTF8.GetString(data, valueIdx, valueEnd - valueIdx); args[key] = value; } keyIndex = valueEnd + 1; } } // execute OnControllerCommand once for every session that has changed. OnControllerCommand(command, args, (bEnabling ? sessionChanged : -sessionChanged), etwSessionId); } } else if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_DISABLE_PROVIDER) { m_enabled = false; m_level = 0; m_anyKeywordMask = 0; m_allKeywordMask = 0; m_liveSessions = null; } else if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_CAPTURE_STATE) { command = ControllerCommand.SendManifest; } else return; // per spec you ignore commands you don't recognise. if (!skipFinalOnControllerCommand) OnControllerCommand(command, args, 0, 0); } catch (Exception) { // We want to ignore any failures that happen as a result of turning on this provider as to // not crash the app. } } // New in CLR4.0 protected virtual void OnControllerCommand(ControllerCommand command, IDictionary<string, string> arguments, int sessionId, int etwSessionId) { } protected EventLevel Level { get { return (EventLevel)m_level; } set { m_level = (byte)value; } } protected EventKeywords MatchAnyKeyword { get { return (EventKeywords)m_anyKeywordMask; } set { m_anyKeywordMask = unchecked((long)value); } } protected EventKeywords MatchAllKeyword { get { return (EventKeywords)m_allKeywordMask; } set { m_allKeywordMask = unchecked((long)value); } } static private int FindNull(byte[] buffer, int idx) { while (idx < buffer.Length && buffer[idx] != 0) idx++; return idx; } /// <summary> /// Determines the ETW sessions that have been added and/or removed to the set of /// sessions interested in the current provider. It does so by (1) enumerating over all /// ETW sessions that enabled 'this.m_Guid' for the current process ID, and (2) /// comparing the current list with a list it cached on the previous invocation. /// /// The return value is a list of tuples, where the SessionInfo specifies the /// ETW session that was added or remove, and the bool specifies whether the /// session was added or whether it was removed from the set. /// </summary> [System.Security.SecuritySafeCritical] private List<Tuple<SessionInfo, bool>> GetSessions() { List<SessionInfo> liveSessionList = null; GetSessionInfo((Action<int, long>) ((etwSessionId, matchAllKeywords) => GetSessionInfoCallback(etwSessionId, matchAllKeywords, ref liveSessionList))); List<Tuple<SessionInfo, bool>> changedSessionList = new List<Tuple<SessionInfo, bool>>(); // first look for sessions that have gone away (or have changed) // (present in the m_liveSessions but not in the new liveSessionList) if (m_liveSessions != null) { foreach(SessionInfo s in m_liveSessions) { int idx; if ((idx = IndexOfSessionInList(liveSessionList, s.etwSessionId)) < 0 || (liveSessionList[idx].sessionIdBit != s.sessionIdBit)) changedSessionList.Add(Tuple.Create(s, false)); } } // next look for sessions that were created since the last callback (or have changed) // (present in the new liveSessionList but not in m_liveSessions) if (liveSessionList != null) { foreach (SessionInfo s in liveSessionList) { int idx; if ((idx = IndexOfSessionInList(m_liveSessions, s.etwSessionId)) < 0 || (m_liveSessions[idx].sessionIdBit != s.sessionIdBit)) changedSessionList.Add(Tuple.Create(s, true)); } } m_liveSessions = liveSessionList; return changedSessionList; } /// <summary> /// This method is the callback used by GetSessions() when it calls into GetSessionInfo(). /// It updates a List{SessionInfo} based on the etwSessionId and matchAllKeywords that /// GetSessionInfo() passes in. /// </summary> private static void GetSessionInfoCallback(int etwSessionId, long matchAllKeywords, ref List<SessionInfo> sessionList) { uint sessionIdBitMask = (uint)SessionMask.FromEventKeywords(unchecked((ulong)matchAllKeywords)); // an ETW controller that specifies more than the mandated bit for our EventSource // will be ignored... if (bitcount(sessionIdBitMask) > 1) return; if (sessionList == null) sessionList = new List<SessionInfo>(8); if (bitcount(sessionIdBitMask) == 1) { // activity-tracing-aware etw session sessionList.Add(new SessionInfo(bitindex(sessionIdBitMask)+1, etwSessionId)); } else { // legacy etw session sessionList.Add(new SessionInfo(bitcount((uint)SessionMask.All)+1, etwSessionId)); } } /// <summary> /// This method enumerates over all active ETW sessions that have enabled 'this.m_Guid' /// for the current process ID, calling 'action' for each session, and passing it the /// ETW session and the 'AllKeywords' the session enabled for the current provider. /// </summary> [System.Security.SecurityCritical] private unsafe void GetSessionInfo(Action<int, long> action) { int buffSize = 256; // An initial guess that probably works most of the time. byte* buffer; for (; ; ) { var space = stackalloc byte[buffSize]; buffer = space; var hr = 0; fixed (Guid* provider = &m_providerId) { hr = UnsafeNativeMethods.ManifestEtw.EnumerateTraceGuidsEx(UnsafeNativeMethods.ManifestEtw.TRACE_QUERY_INFO_CLASS.TraceGuidQueryInfo, provider, sizeof(Guid), buffer, buffSize, ref buffSize); } if (hr == 0) break; if (hr != 122 /* ERROR_INSUFFICIENT_BUFFER */) return; } var providerInfos = (UnsafeNativeMethods.ManifestEtw.TRACE_GUID_INFO*)buffer; var providerInstance = (UnsafeNativeMethods.ManifestEtw.TRACE_PROVIDER_INSTANCE_INFO*)&providerInfos[1]; int processId = unchecked((int)Win32Native.GetCurrentProcessId()); // iterate over the instances of the EventProvider in all processes for (int i = 0; i < providerInfos->InstanceCount; i++) { if (providerInstance->Pid == processId) { var enabledInfos = (UnsafeNativeMethods.ManifestEtw.TRACE_ENABLE_INFO*)&providerInstance[1]; // iterate over the list of active ETW sessions "listening" to the current provider for (int j = 0; j < providerInstance->EnableCount; j++) action(enabledInfos[j].LoggerId, enabledInfos[j].MatchAllKeyword); } if (providerInstance->NextOffset == 0) break; Contract.Assert(0 <= providerInstance->NextOffset && providerInstance->NextOffset < buffSize); var structBase = (byte*)providerInstance; providerInstance = (UnsafeNativeMethods.ManifestEtw.TRACE_PROVIDER_INSTANCE_INFO*)&structBase[providerInstance->NextOffset]; } } /// <summary> /// Returns the index of the SesisonInfo from 'sessions' that has the specified 'etwSessionId' /// or -1 if the value is not present. /// </summary> private static int IndexOfSessionInList(List<SessionInfo> sessions, int etwSessionId) { if (sessions == null) return -1; // for non-coreclr code we could use List<T>.FindIndex(Predicate<T>), but we need this to compile // on coreclr as well for (int i = 0; i < sessions.Count; ++i) if (sessions[i].etwSessionId == etwSessionId) return i; return -1; } /// <summary> /// Gets any data to be passed from the controller to the provider. It starts with what is passed /// into the callback, but unfortunately this data is only present for when the provider is active /// at the time the controller issues the command. To allow for providers to activate after the /// controller issued a command, we also check the registry and use that to get the data. The function /// returns an array of bytes representing the data, the index into that byte array where the data /// starts, and the command being issued associated with that data. /// </summary> [System.Security.SecurityCritical] private unsafe bool GetDataFromController(int etwSessionId, UnsafeNativeMethods.ManifestEtw.EVENT_FILTER_DESCRIPTOR* filterData, out ControllerCommand command, out byte[] data, out int dataStart) { data = null; dataStart = 0; if (filterData == null) { #if !ES_BUILD_PCL && !FEATURE_PAL string regKey = @"\Microsoft\Windows\CurrentVersion\Winevt\Publishers\{" + m_providerId + "}"; if (System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntPtr)) == 8) regKey = @"HKEY_LOCAL_MACHINE\Software" + @"\Wow6432Node" + regKey; else regKey = @"HKEY_LOCAL_MACHINE\Software" + regKey; string valueName = "ControllerData_Session_" + etwSessionId.ToString(CultureInfo.InvariantCulture); // we need to assert this permission for partial trust scenarios (new RegistryPermission(RegistryPermissionAccess.Read, regKey)).Assert(); data = Microsoft.Win32.Registry.GetValue(regKey, valueName, null) as byte[]; if (data != null) { // We only used the persisted data from the registry for updates. command = ControllerCommand.Update; return true; } #endif } else { if (filterData->Ptr != 0 && 0 < filterData->Size && filterData->Size <= 1024) { data = new byte[filterData->Size]; Marshal.Copy((IntPtr)filterData->Ptr, data, 0, data.Length); } command = (ControllerCommand) filterData->Type; return true; } command = ControllerCommand.Update; return false; } /// <summary> /// IsEnabled, method used to test if provider is enabled /// </summary> public bool IsEnabled() { return m_enabled; } /// <summary> /// IsEnabled, method used to test if event is enabled /// </summary> /// <param name="level"> /// Level to test /// </param> /// <param name="keywords"> /// Keyword to test /// </param> public bool IsEnabled(byte level, long keywords) { // // If not enabled at all, return false. // if (!m_enabled) { return false; } // This also covers the case of Level == 0. if ((level <= m_level) || (m_level == 0)) { // // Check if Keyword is enabled // if ((keywords == 0) || (((keywords & m_anyKeywordMask) != 0) && ((keywords & m_allKeywordMask) == m_allKeywordMask))) { return true; } } return false; } // There's a small window of time in EventSource code where m_provider is non-null but the // m_regHandle has not been set yet. This method allows EventSource to check if this is the case... internal bool IsValid() { return m_regHandle != 0; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public static WriteEventErrorCode GetLastWriteEventError() { return s_returnCode; } // // Helper function to set the last error on the thread // private static void SetLastError(int error) { switch (error) { case UnsafeNativeMethods.ManifestEtw.ERROR_ARITHMETIC_OVERFLOW: case UnsafeNativeMethods.ManifestEtw.ERROR_MORE_DATA: s_returnCode = WriteEventErrorCode.EventTooBig; break; case UnsafeNativeMethods.ManifestEtw.ERROR_NOT_ENOUGH_MEMORY: s_returnCode = WriteEventErrorCode.NoFreeBuffers; break; } } // <SecurityKernel Critical="True" Ring="0"> // <UsesUnsafeCode Name="Local intptrPtr of type: IntPtr*" /> // <UsesUnsafeCode Name="Local intptrPtr of type: Int32*" /> // <UsesUnsafeCode Name="Local longptr of type: Int64*" /> // <UsesUnsafeCode Name="Local uintptr of type: UInt32*" /> // <UsesUnsafeCode Name="Local ulongptr of type: UInt64*" /> // <UsesUnsafeCode Name="Local charptr of type: Char*" /> // <UsesUnsafeCode Name="Local byteptr of type: Byte*" /> // <UsesUnsafeCode Name="Local shortptr of type: Int16*" /> // <UsesUnsafeCode Name="Local sbyteptr of type: SByte*" /> // <UsesUnsafeCode Name="Local ushortptr of type: UInt16*" /> // <UsesUnsafeCode Name="Local floatptr of type: Single*" /> // <UsesUnsafeCode Name="Local doubleptr of type: Double*" /> // <UsesUnsafeCode Name="Local boolptr of type: Boolean*" /> // <UsesUnsafeCode Name="Local guidptr of type: Guid*" /> // <UsesUnsafeCode Name="Local decimalptr of type: Decimal*" /> // <UsesUnsafeCode Name="Local booleanptr of type: Boolean*" /> // <UsesUnsafeCode Name="Parameter dataDescriptor of type: EventData*" /> // <UsesUnsafeCode Name="Parameter dataBuffer of type: Byte*" /> // </SecurityKernel> [System.Security.SecurityCritical] private static unsafe object EncodeObject(ref object data, ref EventData* dataDescriptor, ref byte* dataBuffer, ref uint totalEventSize) /*++ Routine Description: This routine is used by WriteEvent to unbox the object type and to fill the passed in ETW data descriptor. Arguments: data - argument to be decoded dataDescriptor - pointer to the descriptor to be filled (updated to point to the next empty entry) dataBuffer - storage buffer for storing user data, needed because cant get the address of the object (updated to point to the next empty entry) Return Value: null if the object is a basic type other than string or byte[]. String otherwise --*/ { Again: dataDescriptor->Reserved = 0; string sRet = data as string; byte[] blobRet = null; if (sRet != null) { dataDescriptor->Size = ((uint)sRet.Length + 1) * 2; } else if ((blobRet = data as byte[]) != null) { // first store array length *(int*)dataBuffer = blobRet.Length; dataDescriptor->Ptr = (ulong)dataBuffer; dataDescriptor->Size = 4; totalEventSize += dataDescriptor->Size; // then the array parameters dataDescriptor++; dataBuffer += s_basicTypeAllocationBufferSize; dataDescriptor->Size = (uint)blobRet.Length; } else if (data is IntPtr) { dataDescriptor->Size = (uint)sizeof(IntPtr); IntPtr* intptrPtr = (IntPtr*)dataBuffer; *intptrPtr = (IntPtr)data; dataDescriptor->Ptr = (ulong)intptrPtr; } else if (data is int) { dataDescriptor->Size = (uint)sizeof(int); int* intptr = (int*)dataBuffer; *intptr = (int)data; dataDescriptor->Ptr = (ulong)intptr; } else if (data is long) { dataDescriptor->Size = (uint)sizeof(long); long* longptr = (long*)dataBuffer; *longptr = (long)data; dataDescriptor->Ptr = (ulong)longptr; } else if (data is uint) { dataDescriptor->Size = (uint)sizeof(uint); uint* uintptr = (uint*)dataBuffer; *uintptr = (uint)data; dataDescriptor->Ptr = (ulong)uintptr; } else if (data is UInt64) { dataDescriptor->Size = (uint)sizeof(ulong); UInt64* ulongptr = (ulong*)dataBuffer; *ulongptr = (ulong)data; dataDescriptor->Ptr = (ulong)ulongptr; } else if (data is char) { dataDescriptor->Size = (uint)sizeof(char); char* charptr = (char*)dataBuffer; *charptr = (char)data; dataDescriptor->Ptr = (ulong)charptr; } else if (data is byte) { dataDescriptor->Size = (uint)sizeof(byte); byte* byteptr = (byte*)dataBuffer; *byteptr = (byte)data; dataDescriptor->Ptr = (ulong)byteptr; } else if (data is short) { dataDescriptor->Size = (uint)sizeof(short); short* shortptr = (short*)dataBuffer; *shortptr = (short)data; dataDescriptor->Ptr = (ulong)shortptr; } else if (data is sbyte) { dataDescriptor->Size = (uint)sizeof(sbyte); sbyte* sbyteptr = (sbyte*)dataBuffer; *sbyteptr = (sbyte)data; dataDescriptor->Ptr = (ulong)sbyteptr; } else if (data is ushort) { dataDescriptor->Size = (uint)sizeof(ushort); ushort* ushortptr = (ushort*)dataBuffer; *ushortptr = (ushort)data; dataDescriptor->Ptr = (ulong)ushortptr; } else if (data is float) { dataDescriptor->Size = (uint)sizeof(float); float* floatptr = (float*)dataBuffer; *floatptr = (float)data; dataDescriptor->Ptr = (ulong)floatptr; } else if (data is double) { dataDescriptor->Size = (uint)sizeof(double); double* doubleptr = (double*)dataBuffer; *doubleptr = (double)data; dataDescriptor->Ptr = (ulong)doubleptr; } else if (data is bool) { // WIN32 Bool is 4 bytes dataDescriptor->Size = 4; int* intptr = (int*)dataBuffer; if (((bool)data)) { *intptr = 1; } else { *intptr = 0; } dataDescriptor->Ptr = (ulong)intptr; } else if (data is Guid) { dataDescriptor->Size = (uint)sizeof(Guid); Guid* guidptr = (Guid*)dataBuffer; *guidptr = (Guid)data; dataDescriptor->Ptr = (ulong)guidptr; } else if (data is decimal) { dataDescriptor->Size = (uint)sizeof(decimal); decimal* decimalptr = (decimal*)dataBuffer; *decimalptr = (decimal)data; dataDescriptor->Ptr = (ulong)decimalptr; } else if (data is DateTime) { const long UTCMinTicks = 504911232000000000; long dateTimeTicks = 0; // We cannot translate dates sooner than 1/1/1601 in UTC. // To avoid getting an ArgumentOutOfRangeException we compare with 1/1/1601 DateTime ticks if (((DateTime)data).Ticks > UTCMinTicks) dateTimeTicks = ((DateTime)data).ToFileTimeUtc(); dataDescriptor->Size = (uint)sizeof(long); long* longptr = (long*)dataBuffer; *longptr = dateTimeTicks; dataDescriptor->Ptr = (ulong)longptr; } else { if (data is System.Enum) { Type underlyingType = Enum.GetUnderlyingType(data.GetType()); if (underlyingType == typeof(int)) { #if !ES_BUILD_PCL data = ((IConvertible)data).ToInt32(null); #else data = (int)data; #endif goto Again; } else if (underlyingType == typeof(long)) { #if !ES_BUILD_PCL data = ((IConvertible)data).ToInt64(null); #else data = (long)data; #endif goto Again; } } // To our eyes, everything else is a just a string if (data == null) sRet = ""; else sRet = data.ToString(); dataDescriptor->Size = ((uint)sRet.Length + 1) * 2; } totalEventSize += dataDescriptor->Size; // advance buffers dataDescriptor++; dataBuffer += s_basicTypeAllocationBufferSize; return (object)sRet ?? (object)blobRet; } /// <summary> /// WriteEvent, method to write a parameters with event schema properties /// </summary> /// <param name="eventDescriptor"> /// Event Descriptor for this event. /// </param> /// <param name="childActivityID"> /// childActivityID is marked as 'related' to the current activity ID. /// </param> /// <param name="eventPayload"> /// Payload for the ETW event. /// </param> // <SecurityKernel Critical="True" Ring="0"> // <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventWrite(System.Int64,EventDescriptor&,System.UInt32,System.Void*):System.UInt32" /> // <UsesUnsafeCode Name="Local dataBuffer of type: Byte*" /> // <UsesUnsafeCode Name="Local pdata of type: Char*" /> // <UsesUnsafeCode Name="Local userData of type: EventData*" /> // <UsesUnsafeCode Name="Local userDataPtr of type: EventData*" /> // <UsesUnsafeCode Name="Local currentBuffer of type: Byte*" /> // <UsesUnsafeCode Name="Local v0 of type: Char*" /> // <UsesUnsafeCode Name="Local v1 of type: Char*" /> // <UsesUnsafeCode Name="Local v2 of type: Char*" /> // <UsesUnsafeCode Name="Local v3 of type: Char*" /> // <UsesUnsafeCode Name="Local v4 of type: Char*" /> // <UsesUnsafeCode Name="Local v5 of type: Char*" /> // <UsesUnsafeCode Name="Local v6 of type: Char*" /> // <UsesUnsafeCode Name="Local v7 of type: Char*" /> // <ReferencesCritical Name="Method: EncodeObject(Object&, EventData*, Byte*):String" Ring="1" /> // </SecurityKernel> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Performance-critical code")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] [System.Security.SecurityCritical] internal unsafe bool WriteEvent(ref EventDescriptor eventDescriptor, Guid* activityID, Guid* childActivityID, params object[] eventPayload) { int status = 0; if (IsEnabled(eventDescriptor.Level, eventDescriptor.Keywords)) { int argCount = 0; unsafe { argCount = eventPayload.Length; if (argCount > s_etwMaxNumberArguments) { s_returnCode = WriteEventErrorCode.TooManyArgs; return false; } uint totalEventSize = 0; int index; int refObjIndex = 0; List<int> refObjPosition = new List<int>(s_etwAPIMaxRefObjCount); List<object> dataRefObj = new List<object>(s_etwAPIMaxRefObjCount); EventData* userData = stackalloc EventData[2 * argCount]; EventData* userDataPtr = (EventData*)userData; byte* dataBuffer = stackalloc byte[s_basicTypeAllocationBufferSize * 2 * argCount]; // Assume 16 chars for non-string argument byte* currentBuffer = dataBuffer; // // The loop below goes through all the arguments and fills in the data // descriptors. For strings save the location in the dataString array. // Calculates the total size of the event by adding the data descriptor // size value set in EncodeObject method. // bool hasNonStringRefArgs = false; for (index = 0; index < eventPayload.Length; index++) { if (eventPayload[index] != null) { object supportedRefObj; supportedRefObj = EncodeObject(ref eventPayload[index], ref userDataPtr, ref currentBuffer, ref totalEventSize); if (supportedRefObj != null) { // EncodeObject advanced userDataPtr to the next empty slot int idx = (int)(userDataPtr - userData - 1); if (!(supportedRefObj is string)) { if (eventPayload.Length + idx + 1 - index > s_etwMaxNumberArguments) { s_returnCode = WriteEventErrorCode.TooManyArgs; return false; } hasNonStringRefArgs = true; } dataRefObj.Add(supportedRefObj); refObjPosition.Add(idx); refObjIndex++; } } else { s_returnCode = WriteEventErrorCode.NullInput; return false; } } // update argCount based on ctual number of arguments written to 'userData' argCount = (int)(userDataPtr - userData); if (totalEventSize > s_traceEventMaximumSize) { s_returnCode = WriteEventErrorCode.EventTooBig; return false; } // the optimized path (using "fixed" instead of allocating pinned GCHandles if (!hasNonStringRefArgs && (refObjIndex < s_etwAPIMaxRefObjCount)) { // Fast path: at most 8 string arguments // ensure we have at least s_etwAPIMaxStringCount in dataString, so that // the "fixed" statement below works while (refObjIndex < s_etwAPIMaxRefObjCount) { dataRefObj.Add(null); ++refObjIndex; } // // now fix any string arguments and set the pointer on the data descriptor // fixed (char* v0 = (string)dataRefObj[0], v1 = (string)dataRefObj[1], v2 = (string)dataRefObj[2], v3 = (string)dataRefObj[3], v4 = (string)dataRefObj[4], v5 = (string)dataRefObj[5], v6 = (string)dataRefObj[6], v7 = (string)dataRefObj[7]) { userDataPtr = (EventData*)userData; if (dataRefObj[0] != null) { userDataPtr[refObjPosition[0]].Ptr = (ulong)v0; } if (dataRefObj[1] != null) { userDataPtr[refObjPosition[1]].Ptr = (ulong)v1; } if (dataRefObj[2] != null) { userDataPtr[refObjPosition[2]].Ptr = (ulong)v2; } if (dataRefObj[3] != null) { userDataPtr[refObjPosition[3]].Ptr = (ulong)v3; } if (dataRefObj[4] != null) { userDataPtr[refObjPosition[4]].Ptr = (ulong)v4; } if (dataRefObj[5] != null) { userDataPtr[refObjPosition[5]].Ptr = (ulong)v5; } if (dataRefObj[6] != null) { userDataPtr[refObjPosition[6]].Ptr = (ulong)v6; } if (dataRefObj[7] != null) { userDataPtr[refObjPosition[7]].Ptr = (ulong)v7; } status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(m_regHandle, ref eventDescriptor, activityID, childActivityID, argCount, userData); } } else { // Slow path: use pinned handles userDataPtr = (EventData*)userData; GCHandle[] rgGCHandle = new GCHandle[refObjIndex]; for (int i = 0; i < refObjIndex; ++i) { // below we still use "fixed" to avoid taking dependency on the offset of the first field // in the object (the way we would need to if we used GCHandle.AddrOfPinnedObject) rgGCHandle[i] = GCHandle.Alloc(dataRefObj[i], GCHandleType.Pinned); if (dataRefObj[i] is string) { fixed (char* p = (string)dataRefObj[i]) userDataPtr[refObjPosition[i]].Ptr = (ulong)p; } else { fixed (byte* p = (byte[])dataRefObj[i]) userDataPtr[refObjPosition[i]].Ptr = (ulong)p; } } status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(m_regHandle, ref eventDescriptor, activityID, childActivityID, argCount, userData); for (int i = 0; i < refObjIndex; ++i) { rgGCHandle[i].Free(); } } } } if (status != 0) { SetLastError((int)status); return false; } return true; } /// <summary> /// WriteEvent, method to be used by generated code on a derived class /// </summary> /// <param name="eventDescriptor"> /// Event Descriptor for this event. /// </param> /// <param name="childActivityID"> /// If this event is generating a child activity (WriteEventTransfer related activity) this is child activity /// This can be null for events that do not generate a child activity. /// </param> /// <param name="dataCount"> /// number of event descriptors /// </param> /// <param name="data"> /// pointer do the event data /// </param> // <SecurityKernel Critical="True" Ring="0"> // <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventWrite(System.Int64,EventDescriptor&,System.UInt32,System.Void*):System.UInt32" /> // </SecurityKernel> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] [System.Security.SecurityCritical] internal unsafe protected bool WriteEvent(ref EventDescriptor eventDescriptor, Guid* activityID, Guid* childActivityID, int dataCount, IntPtr data) { if (childActivityID != null) { // activity transfers are supported only for events that specify the Send or Receive opcode Contract.Assert((EventOpcode)eventDescriptor.Opcode == EventOpcode.Send || (EventOpcode)eventDescriptor.Opcode == EventOpcode.Receive || (EventOpcode)eventDescriptor.Opcode == EventOpcode.Start || (EventOpcode)eventDescriptor.Opcode == EventOpcode.Stop); } int status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(m_regHandle, ref eventDescriptor, activityID, childActivityID, dataCount, (EventData*)data); if (status != 0) { SetLastError(status); return false; } return true; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] [System.Security.SecurityCritical] internal unsafe bool WriteEventRaw( ref EventDescriptor eventDescriptor, Guid* activityID, Guid* relatedActivityID, int dataCount, IntPtr data) { int status; status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper( m_regHandle, ref eventDescriptor, activityID, relatedActivityID, dataCount, (EventData*)data); if (status != 0) { SetLastError(status); return false; } return true; } // These are look-alikes to the Manifest based ETW OS APIs that have been shimmed to work // either with Manifest ETW or Classic ETW (if Manifest based ETW is not available). [SecurityCritical] private unsafe uint EventRegister(ref Guid providerId, UnsafeNativeMethods.ManifestEtw.EtwEnableCallback enableCallback) { m_providerId = providerId; m_etwCallback = enableCallback; return UnsafeNativeMethods.ManifestEtw.EventRegister(ref providerId, enableCallback, null, ref m_regHandle); } [SecurityCritical] private uint EventUnregister() { uint status = UnsafeNativeMethods.ManifestEtw.EventUnregister(m_regHandle); m_regHandle = 0; return status; } static int[] nibblebits = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4}; private static int bitcount(uint n) { int count = 0; for(; n != 0; n = n >> 4) count += nibblebits[n & 0x0f]; return count; } private static int bitindex(uint n) { Contract.Assert(bitcount(n) == 1); int idx = 0; while ((n & (1 << idx)) == 0) idx++; return idx; } } }
/* **************************************************************************** * * 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.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if FEATURE_CORE_DLR using System.Linq.Expressions; #else using dynamic = System.Object; using Microsoft.Scripting.Ast; #endif #if FEATURE_REMOTING using System.Runtime.Remoting; #else using MarshalByRefObject = System.Object; #endif using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.Serialization; using System.Dynamic; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; namespace Microsoft.Scripting.Hosting { /// <summary> /// A ScriptScope is a unit of execution for code. It consists of a global Scope which /// all code executes in. A ScriptScope can have an arbitrary initializer and arbitrary /// reloader. /// /// ScriptScope is not thread safe. Host should either lock when multiple threads could /// access the same module or should make a copy for each thread. /// /// Hosting API counterpart for <see cref="Scope"/>. /// </summary> #if !SILVERLIGHT && !WIN8 && !WP75 [DebuggerTypeProxy(typeof(ScriptScope.DebugView))] #endif public sealed class ScriptScope : MarshalByRefObject, IDynamicMetaObjectProvider { private readonly Scope _scope; private readonly ScriptEngine _engine; internal ScriptScope(ScriptEngine engine, Scope scope) { Assert.NotNull(engine, scope); _scope = scope; _engine = engine; } internal Scope Scope { get { return _scope; } } /// <summary> /// Gets an engine for the language associated with this scope. /// Returns invariant engine if the scope is language agnostic. /// </summary> public ScriptEngine Engine { get { return _engine; } } /// <summary> /// Gets a value stored in the scope under the given name. /// </summary> /// <exception cref="MissingMemberException">The specified name is not defined in the scope.</exception> /// <exception cref="ArgumentNullException"><paramref name="name"/> is a <c>null</c> reference.</exception> public dynamic GetVariable(string name) { return _engine.LanguageContext.ScopeGetVariable(Scope, name); } /// <summary> /// Gets a value stored in the scope under the given name. /// Converts the result to the specified type using the conversion that the language associated with the scope defines. /// If no language is associated with the scope, the default CLR conversion is attempted. /// </summary> /// <exception cref="MissingMemberException">The specified name is not defined in the scope.</exception> /// <exception cref="ArgumentNullException"><paramref name="name"/> is a <c>null</c> reference.</exception> public T GetVariable<T>(string name) { return _engine.LanguageContext.ScopeGetVariable<T>(Scope, name); } /// <summary> /// Tries to get a value stored in the scope under the given name. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="name"/> is a <c>null</c> reference.</exception> public bool TryGetVariable(string name, out dynamic value) { return _engine.LanguageContext.ScopeTryGetVariable(Scope, name, out value); } /// <summary> /// Tries to get a value stored in the scope under the given name. /// Converts the result to the specified type using the conversion that the language associated with the scope defines. /// If no language is associated with the scope, the default CLR conversion is attempted. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="name"/> is a <c>null</c> reference.</exception> public bool TryGetVariable<T>(string name, out T value) { object result; if(_engine.LanguageContext.ScopeTryGetVariable(Scope, name, out result)) { value = _engine.Operations.ConvertTo<T>(result); return true; } value = default(T); return false; } /// <summary> /// Sets the name to the specified value. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="name"/> is a <c>null</c> reference.</exception> public void SetVariable(string name, object value) { _engine.LanguageContext.ScopeSetVariable(Scope, name, value); } #if FEATURE_REMOTING /// <summary> /// Gets a handle for a value stored in the scope under the given name. /// </summary> /// <exception cref="MissingMemberException">The specified name is not defined in the scope.</exception> /// <exception cref="ArgumentNullException"><paramref name="name"/> is a <c>null</c> reference.</exception> public ObjectHandle GetVariableHandle(string name) { return new ObjectHandle((object)GetVariable(name)); } /// <summary> /// Tries to get a handle for a value stored in the scope under the given name. /// Returns <c>true</c> if there is such name, <c>false</c> otherwise. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="name"/> is a <c>null</c> reference.</exception> public bool TryGetVariableHandle(string name, out ObjectHandle handle) { object value; if (TryGetVariable(name, out value)) { handle = new ObjectHandle(value); return true; } else { handle = null; return false; } } /// <summary> /// Sets the name to the specified value. /// </summary> /// <exception cref="SerializationException"> /// The value held by the handle isn't from the scope's app-domain and isn't serializable or MarshalByRefObject. /// </exception> /// <exception cref="ArgumentNullException"><paramref name="name"/> or <paramref name="handle"/> is a <c>null</c> reference.</exception> public void SetVariable(string name, ObjectHandle handle) { ContractUtils.RequiresNotNull(handle, "handle"); SetVariable(name, handle.Unwrap()); } #endif /// <summary> /// Determines if this context or any outer scope contains the defined name. /// </summary> /// <exception cref="ArgumentNullException"><paramref name="name"/> is a <c>null</c> reference.</exception> public bool ContainsVariable(string name) { object dummy; return TryGetVariable(name, out dummy); } /// <summary> /// Removes the variable of the given name from this scope. /// </summary> /// <returns><c>true</c> if the value existed in the scope before it has been removed.</returns> /// <exception cref="ArgumentNullException"><paramref name="name"/> is a <c>null</c> reference.</exception> public bool RemoveVariable(string name) { if (_engine.Operations.ContainsMember(_scope, name)) { _engine.Operations.RemoveMember(_scope, name); return true; } return false; } /// <summary> /// Gets a list of variable names stored in the scope. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public IEnumerable<string> GetVariableNames() { // Remoting: we eagerly enumerate all variables to avoid cross domain calls for each item. return _engine.Operations.GetMemberNames((object)_scope.Storage); } /// <summary> /// Gets an array of variable names and their values stored in the scope. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public IEnumerable<KeyValuePair<string, dynamic>> GetItems() { // Remoting: we eagerly enumerate all variables to avoid cross domain calls for each item. var result = new List<KeyValuePair<string, object>>(); foreach (string name in GetVariableNames()) { result.Add(new KeyValuePair<string, object>(name, (object)_engine.Operations.GetMember((object)_scope.Storage, name))); } result.TrimExcess(); return result; } #region DebugView #if !SILVERLIGHT && !WIN8 && !WP75 internal sealed class DebugView { private readonly ScriptScope _scope; public DebugView(ScriptScope scope) { Assert.NotNull(scope); _scope = scope; } public ScriptEngine Language { get { return _scope._engine; } } public System.Collections.Hashtable Variables { get { System.Collections.Hashtable result = new System.Collections.Hashtable(); foreach (var variable in _scope.GetItems()) { result[variable.Key] = (object)variable.Value; } return result; } } } #endif #endregion #region IDynamicMetaObjectProvider implementation DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter) { return new Meta(parameter, this); } private sealed class Meta : DynamicMetaObject { internal Meta(Expression parameter, ScriptScope scope) : base(parameter, BindingRestrictions.Empty, scope) { } // TODO: support for IgnoreCase in underlying ScriptScope APIs public override DynamicMetaObject BindGetMember(GetMemberBinder action) { var result = Expression.Variable(typeof(object), "result"); var fallback = action.FallbackGetMember(this); return new DynamicMetaObject( Expression.Block( new ParameterExpression[] { result }, Expression.Condition( Expression.Call( Expression.Convert(Expression, typeof(ScriptScope)), typeof(ScriptScope).GetMethod("TryGetVariable", new[] { typeof(string), typeof(object).MakeByRefType() }), Expression.Constant(action.Name), result ), result, Expression.Convert(fallback.Expression, typeof(object)) ) ), BindingRestrictions.GetTypeRestriction(Expression, typeof(ScriptScope)).Merge(fallback.Restrictions) ); } // TODO: support for IgnoreCase in underlying ScriptScope APIs public override DynamicMetaObject BindSetMember(SetMemberBinder action, DynamicMetaObject value) { Expression objValue = Expression.Convert(value.Expression, typeof(object)); return new DynamicMetaObject( Expression.Block( Expression.Call( Expression.Convert(Expression, typeof(ScriptScope)), typeof(ScriptScope).GetMethod("SetVariable", new[] { typeof(string), typeof(object) }), Expression.Constant(action.Name), objValue ), objValue ), Restrictions.Merge(value.Restrictions).Merge(BindingRestrictions.GetTypeRestriction(Expression, typeof(ScriptScope))) ); } // TODO: support for IgnoreCase in underlying ScriptScope APIs public override DynamicMetaObject BindDeleteMember(DeleteMemberBinder action) { var fallback = action.FallbackDeleteMember(this); return new DynamicMetaObject( Expression.IfThenElse( Expression.Call( Expression.Convert(Expression, typeof(ScriptScope)), typeof(ScriptScope).GetMethod("RemoveVariable"), Expression.Constant(action.Name) ), Expression.Empty(), fallback.Expression ), Restrictions.Merge(BindingRestrictions.GetTypeRestriction(Expression, typeof(ScriptScope))).Merge(fallback.Restrictions) ); } // TODO: support for IgnoreCase in underlying ScriptScope APIs public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder action, DynamicMetaObject[] args) { var fallback = action.FallbackInvokeMember(this, args); var result = Expression.Variable(typeof(object), "result"); var fallbackInvoke = action.FallbackInvoke(new DynamicMetaObject(result, BindingRestrictions.Empty), args, null); return new DynamicMetaObject( Expression.Block( new ParameterExpression[] { result }, Expression.Condition( Expression.Call( Expression.Convert(Expression, typeof(ScriptScope)), typeof(ScriptScope).GetMethod("TryGetVariable", new[] { typeof(string), typeof(object).MakeByRefType() }), Expression.Constant(action.Name), result ), Expression.Convert(fallbackInvoke.Expression, typeof(object)), Expression.Convert(fallback.Expression, typeof(object)) ) ), BindingRestrictions.Combine(args).Merge(BindingRestrictions.GetTypeRestriction(Expression, typeof(ScriptScope))).Merge(fallback.Restrictions) ); } public override IEnumerable<string> GetDynamicMemberNames() { return ((ScriptScope)Value).GetVariableNames(); } } #endregion #if FEATURE_REMOTING // TODO: Figure out what is the right lifetime public override object InitializeLifetimeService() { return null; } #endif } }
#nullable enable using System; using System.Collections.Concurrent; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Logging; using Avalonia.Platform; using Avalonia.Threading; namespace Avalonia.X11 { internal unsafe class X11PlatformLifetimeEvents : IDisposable, IPlatformLifetimeEventsImpl { private readonly AvaloniaX11Platform _platform; private const ulong SmcSaveYourselfProcMask = 1L; private const ulong SmcDieProcMask = 2L; private const ulong SmcSaveCompleteProcMask = 4L; private const ulong SmcShutdownCancelledProcMask = 8L; private static readonly ConcurrentDictionary<IntPtr, X11PlatformLifetimeEvents> s_nativeToManagedMapper = new ConcurrentDictionary<IntPtr, X11PlatformLifetimeEvents>(); private static readonly SMLib.SmcSaveYourselfProc s_saveYourselfProcDelegate = SmcSaveYourselfHandler; private static readonly SMLib.SmcDieProc s_dieDelegate = SmcDieHandler; private static readonly SMLib.SmcShutdownCancelledProc s_shutdownCancelledDelegate = SmcShutdownCancelledHandler; private static readonly SMLib.SmcSaveCompleteProc s_saveCompleteDelegate = SmcSaveCompleteHandler; private static readonly SMLib.SmcInteractProc s_smcInteractDelegate = StaticInteractHandler; private static readonly SMLib.SmcErrorHandler s_smcErrorHandlerDelegate = StaticErrorHandler; private static readonly ICELib.IceErrorHandler s_iceErrorHandlerDelegate = StaticErrorHandler; private static readonly ICELib.IceIOErrorHandler s_iceIoErrorHandlerDelegate = StaticIceIOErrorHandler; private static readonly SMLib.IceWatchProc s_iceWatchProcDelegate = IceWatchHandler; private static SMLib.SmcCallbacks s_callbacks = new SMLib.SmcCallbacks() { ShutdownCancelled = Marshal.GetFunctionPointerForDelegate(s_shutdownCancelledDelegate), Die = Marshal.GetFunctionPointerForDelegate(s_dieDelegate), SaveYourself = Marshal.GetFunctionPointerForDelegate(s_saveYourselfProcDelegate), SaveComplete = Marshal.GetFunctionPointerForDelegate(s_saveCompleteDelegate) }; private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); private readonly IntPtr _currentIceConn; private readonly IntPtr _currentSmcConn; private bool _saveYourselfPhase; internal X11PlatformLifetimeEvents(AvaloniaX11Platform platform) { _platform = platform; if (ICELib.IceAddConnectionWatch( Marshal.GetFunctionPointerForDelegate(s_iceWatchProcDelegate), IntPtr.Zero) == 0) { Logger.TryGet(LogEventLevel.Warning, LogArea.X11Platform)?.Log(this, "SMLib was unable to add an ICE connection watcher."); return; } var errorBuf = new char[255]; var smcConn = SMLib.SmcOpenConnection(null!, IntPtr.Zero, 1, 0, SmcSaveYourselfProcMask | SmcSaveCompleteProcMask | SmcShutdownCancelledProcMask | SmcDieProcMask, ref s_callbacks, out _, out _, errorBuf.Length, errorBuf); if (smcConn == IntPtr.Zero) { Logger.TryGet(LogEventLevel.Warning, LogArea.X11Platform)?.Log(this, $"SMLib/ICELib reported a new error: {new string(errorBuf)}"); return; } if (!s_nativeToManagedMapper.TryAdd(smcConn, this)) { Logger.TryGet(LogEventLevel.Warning, LogArea.X11Platform)?.Log(this, "SMLib was unable to add this instance to the native to managed map."); return; } _ = SMLib.SmcSetErrorHandler(Marshal.GetFunctionPointerForDelegate(s_smcErrorHandlerDelegate)); _ = ICELib.IceSetErrorHandler(Marshal.GetFunctionPointerForDelegate(s_iceErrorHandlerDelegate)); _ = ICELib.IceSetIOErrorHandler(Marshal.GetFunctionPointerForDelegate(s_iceIoErrorHandlerDelegate)); _currentSmcConn = smcConn; _currentIceConn = SMLib.SmcGetIceConnection(smcConn); Task.Run(() => { var token = _cancellationTokenSource.Token; while (!token.IsCancellationRequested) HandleRequests(); }, _cancellationTokenSource.Token); } public void Dispose() { if (_currentSmcConn == IntPtr.Zero) return; s_nativeToManagedMapper.TryRemove(_currentSmcConn, out _); _ = SMLib.SmcCloseConnection(_currentSmcConn, 1, new[] { $"{nameof(X11PlatformLifetimeEvents)} was disposed in managed code." }); } private static void SmcSaveCompleteHandler(IntPtr smcConn, IntPtr clientData) { GetInstance(smcConn)?.SaveCompleteHandler(); } private static X11PlatformLifetimeEvents? GetInstance(IntPtr smcConn) { return s_nativeToManagedMapper.TryGetValue(smcConn, out var instance) ? instance : null; } private static void SmcShutdownCancelledHandler(IntPtr smcConn, IntPtr clientData) { GetInstance(smcConn)?.ShutdownCancelledHandler(); } private static void SmcDieHandler(IntPtr smcConn, IntPtr clientData) { GetInstance(smcConn)?.DieHandler(); } private static void SmcSaveYourselfHandler(IntPtr smcConn, IntPtr clientData, int saveType, bool shutdown, int interactStyle, bool fast) { GetInstance(smcConn)?.SaveYourselfHandler(smcConn, clientData, shutdown, fast); } private static void StaticInteractHandler(IntPtr smcConn, IntPtr clientData) { GetInstance(smcConn)?.InteractHandler(smcConn); } private static void StaticIceIOErrorHandler(IntPtr iceConn) { Logger.TryGet(LogEventLevel.Warning, LogArea.X11Platform)?.Log(null, "ICELib reported an unknown IO Error."); } private static void StaticErrorHandler(IntPtr smcConn, bool swap, int offendingMinorOpcode, ulong offendingSequence, int errorClass, int severity, IntPtr values) { GetInstance(smcConn) ?.ErrorHandler(swap, offendingMinorOpcode, offendingSequence, errorClass, severity, values); } // ReSharper disable UnusedParameter.Local private void ErrorHandler(bool swap, int offendingMinorOpcode, ulong offendingSequence, int errorClass, int severity, IntPtr values) { Logger.TryGet(LogEventLevel.Warning, LogArea.X11Platform)?.Log(this, "SMLib reported an error:" + $" severity {severity:X}" + $" mOpcode {offendingMinorOpcode:X}" + $" mSeq {offendingSequence:X}" + $" errClass {errorClass:X}."); } private void HandleRequests() { if (ICELib.IceProcessMessages(_currentIceConn, out _, out _) == ICELib.IceProcessMessagesStatus.IceProcessMessagesIoError) { Logger.TryGet(LogEventLevel.Warning, LogArea.X11Platform)?.Log(this, "SMLib lost its underlying ICE connection."); Dispose(); } } private void SaveCompleteHandler() { _saveYourselfPhase = false; } private void ShutdownCancelledHandler() { if (_saveYourselfPhase) SMLib.SmcSaveYourselfDone(_currentSmcConn, true); _saveYourselfPhase = false; } private void DieHandler() { Dispose(); } private void SaveYourselfHandler(IntPtr smcConn, IntPtr clientData, bool shutdown, bool fast) { if (_saveYourselfPhase) { SMLib.SmcSaveYourselfDone(smcConn, true); } _saveYourselfPhase = true; if (shutdown && !fast) { var _ = SMLib.SmcInteractRequest(smcConn, SMLib.SmDialogValue.SmDialogError, Marshal.GetFunctionPointerForDelegate(s_smcInteractDelegate), clientData); } else { SMLib.SmcSaveYourselfDone(smcConn, true); _saveYourselfPhase = false; } } private void InteractHandler(IntPtr smcConn) { Dispatcher.UIThread.Post(() => ActualInteractHandler(smcConn)); } private void ActualInteractHandler(IntPtr smcConn) { var e = new ShutdownRequestedEventArgs(); if (_platform.Options?.EnableSessionManagement ?? false) { ShutdownRequested?.Invoke(this, e); } SMLib.SmcInteractDone(smcConn, e.Cancel); if (e.Cancel) { return; } _saveYourselfPhase = false; SMLib.SmcSaveYourselfDone(smcConn, true); } private static void IceWatchHandler(IntPtr iceConn, IntPtr clientData, bool opening, IntPtr* watchData) { if (!opening) return; ICELib.IceRemoveConnectionWatch(Marshal.GetFunctionPointerForDelegate(s_iceWatchProcDelegate), IntPtr.Zero); } public event EventHandler<ShutdownRequestedEventArgs>? ShutdownRequested; } }
// 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; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using System.Runtime.InteropServices.ComTypes; using Microsoft.DiaSymReader; using Roslyn.Utilities; namespace Roslyn.Test.PdbUtilities { public sealed class SymReader : ISymUnmanagedReader, ISymUnmanagedReader2, ISymUnmanagedReader3, IDisposable { /// <summary> /// Mock implementation: instead of a single reader with multiple versions, we'll use an array /// of readers - each with a single version. We do this so that we can implement /// <see cref="ISymUnmanagedReader3.GetSymAttributeByVersion"/> on top of /// <see cref="ISymUnmanagedReader.GetSymAttribute"/>. /// </summary> private readonly ISymUnmanagedReader[] _readerVersions; private readonly DummyMetadataImport _metadataImport; private readonly PEReader _peReaderOpt; private bool _isDisposed; public SymReader(Stream pdbStream) : this(new[] { pdbStream }, null, null) { } public SymReader(byte[] pdbImage) : this(new[] { new MemoryStream(pdbImage) }, null, null) { } public SymReader(byte[] pdbImage, byte[] peImage) : this(new[] { new MemoryStream(pdbImage) }, new MemoryStream(peImage), null) { } public SymReader(Stream pdbStream, Stream peStream) : this(new[] { pdbStream }, peStream, null) { } public SymReader(Stream pdbStream, MetadataReader metadataReader) : this(new[] { pdbStream }, null, metadataReader) { } public SymReader(Stream[] pdbStreamsByVersion, Stream peStreamOpt, MetadataReader metadataReaderOpt) { if (peStreamOpt != null) { _peReaderOpt = new PEReader(peStreamOpt); _metadataImport = new DummyMetadataImport(_peReaderOpt.GetMetadataReader()); } else { _metadataImport = new DummyMetadataImport(metadataReaderOpt); } _readerVersions = pdbStreamsByVersion.Select( pdbStream => SymUnmanagedReaderTestExtensions.CreateReader(pdbStream, _metadataImport)).ToArray(); // If ISymUnmanagedReader3 is available, then we shouldn't be passing in multiple byte streams - one should suffice. Debug.Assert(!(UnversionedReader is ISymUnmanagedReader3) || _readerVersions.Length == 1); } private ISymUnmanagedReader UnversionedReader => _readerVersions[0]; public int GetDocuments(int cDocs, out int pcDocs, ISymUnmanagedDocument[] pDocs) { return UnversionedReader.GetDocuments(cDocs, out pcDocs, pDocs); } public int GetMethod(int methodToken, out ISymUnmanagedMethod retVal) { // The EE should never be calling ISymUnmanagedReader.GetMethod. In order to account // for EnC updates, it should always be calling GetMethodByVersion instead. throw ExceptionUtilities.Unreachable; } public int GetMethodByVersion(int methodToken, int version, out ISymUnmanagedMethod retVal) { // Versions are 1-based. Debug.Assert(version >= 1); var reader = _readerVersions[version - 1]; version = _readerVersions.Length > 1 ? 1 : version; return reader.GetMethodByVersion(methodToken, version, out retVal); } public int GetSymAttribute(int token, string name, int sizeBuffer, out int lengthBuffer, byte[] buffer) { // The EE should never be calling ISymUnmanagedReader.GetSymAttribute. // In order to account for EnC updates, it should always be calling // ISymUnmanagedReader3.GetSymAttributeByVersion instead. throw ExceptionUtilities.Unreachable; } public int GetSymAttributeByVersion(int methodToken, int version, string name, int bufferLength, out int count, byte[] customDebugInformation) { // Versions are 1-based. Debug.Assert(version >= 1); return _readerVersions[version - 1].GetSymAttribute(methodToken, name, bufferLength, out count, customDebugInformation); } public int GetUserEntryPoint(out int entryPoint) { return UnversionedReader.GetUserEntryPoint(out entryPoint); } void IDisposable.Dispose() { if (!_isDisposed) { for (int i = 0; i < _readerVersions.Length; i++) { int hr = (_readerVersions[i] as ISymUnmanagedDispose).Destroy(); SymUnmanagedReaderExtensions.ThrowExceptionForHR(hr); _readerVersions[i] = null; } _peReaderOpt?.Dispose(); _metadataImport.Dispose(); _isDisposed = true; } } public int GetDocument(string url, Guid language, Guid languageVendor, Guid documentType, out ISymUnmanagedDocument document) { return UnversionedReader.GetDocument(url, language, languageVendor, documentType, out document); } public int GetVariables(int methodToken, int bufferLength, out int count, ISymUnmanagedVariable[] variables) { return UnversionedReader.GetVariables(methodToken, bufferLength, out count, variables); } public int GetGlobalVariables(int bufferLength, out int count, ISymUnmanagedVariable[] variables) { return UnversionedReader.GetGlobalVariables(bufferLength, out count, variables); } public int GetMethodFromDocumentPosition(ISymUnmanagedDocument document, int line, int column, out ISymUnmanagedMethod method) { return UnversionedReader.GetMethodFromDocumentPosition(document, line, column, out method); } public int GetNamespaces(int bufferLength, out int count, ISymUnmanagedNamespace[] namespaces) { return UnversionedReader.GetNamespaces(bufferLength, out count, namespaces); } public int Initialize(object metadataImporter, string fileName, string searchPath, IStream stream) { return UnversionedReader.Initialize(metadataImporter, fileName, searchPath, stream); } public int UpdateSymbolStore(string fileName, IStream stream) { return UnversionedReader.UpdateSymbolStore(fileName, stream); } public int ReplaceSymbolStore(string fileName, IStream stream) { return UnversionedReader.ReplaceSymbolStore(fileName, stream); } public int GetSymbolStoreFileName(int bufferLength, out int count, char[] name) { return UnversionedReader.GetSymbolStoreFileName(bufferLength, out count, name); } public int GetMethodsFromDocumentPosition(ISymUnmanagedDocument document, int line, int column, int bufferLength, out int count, ISymUnmanagedMethod[] methods) { return UnversionedReader.GetMethodsFromDocumentPosition(document, line, column, bufferLength, out count, methods); } public int GetDocumentVersion(ISymUnmanagedDocument document, out int version, out bool isCurrent) { return UnversionedReader.GetDocumentVersion(document, out version, out isCurrent); } public int GetMethodVersion(ISymUnmanagedMethod method, out int version) { return UnversionedReader.GetMethodVersion(method, out version); } public int GetMethodByVersionPreRemap(int methodToken, int version, out ISymUnmanagedMethod method) { throw new NotImplementedException(); } public int GetSymAttributePreRemap(int methodToken, string name, int bufferLength, out int count, byte[] customDebugInformation) { throw new NotImplementedException(); } public int GetMethodsInDocument(ISymUnmanagedDocument document, int bufferLength, out int count, ISymUnmanagedMethod[] methods) { throw new NotImplementedException(); } public int GetSymAttributeByVersionPreRemap(int methodToken, int version, string name, int bufferLength, out int count, byte[] customDebugInformation) { throw new NotImplementedException(); } } }
#region License // Copyright (c) 2007-2018, Sean Chambers <schambers80@gmail.com> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System.Data; using FluentMigrator.Expressions; using FluentMigrator.Infrastructure; using FluentMigrator.Model; namespace FluentMigrator.Builders.Create.Table { /// <summary> /// An expression builder for a <see cref="CreateTableExpression"/> /// </summary> public class CreateTableExpressionBuilder : ExpressionBuilderWithColumnTypesBase<CreateTableExpression, ICreateTableColumnOptionOrWithColumnSyntax>, ICreateTableWithColumnOrSchemaOrDescriptionSyntax, ICreateTableColumnAsTypeSyntax, ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax, IColumnExpressionBuilder { private readonly IMigrationContext _context; /// <summary> /// Initializes a new instance of the <see cref="CreateTableExpressionBuilder"/> class. /// </summary> /// <param name="expression">The underlying expression</param> /// <param name="context">The migration context</param> public CreateTableExpressionBuilder(CreateTableExpression expression, IMigrationContext context) : base(expression) { _context = context; ColumnHelper = new ColumnExpressionBuilderHelper(this, context); } /// <summary> /// Gets or sets the current column definition /// </summary> public ColumnDefinition CurrentColumn { get; set; } /// <summary> /// Gets or sets the current foreign key definition /// </summary> public ForeignKeyDefinition CurrentForeignKey { get; set; } /// <summary> /// Gets or sets the column expression builder helper /// </summary> public ColumnExpressionBuilderHelper ColumnHelper { get; set; } /// <inheritdoc /> public ICreateTableWithColumnSyntax InSchema(string schemaName) { Expression.SchemaName = schemaName; return this; } /// <inheritdoc /> public ICreateTableColumnAsTypeSyntax WithColumn(string name) { var column = new ColumnDefinition { Name = name, TableName = Expression.TableName, ModificationType = ColumnModificationType.Create }; Expression.Columns.Add(column); CurrentColumn = column; return this; } /// <inheritdoc /> public ICreateTableWithColumnOrSchemaSyntax WithDescription(string description) { Expression.TableDescription = description; return this; } /// <inheritdoc /> public ICreateTableColumnOptionOrWithColumnSyntax WithDefault(SystemMethods method) { CurrentColumn.DefaultValue = method; return this; } /// <inheritdoc /> public ICreateTableColumnOptionOrWithColumnSyntax WithDefaultValue(object value) { CurrentColumn.DefaultValue = value; return this; } /// <inheritdoc /> public ICreateTableColumnOptionOrWithColumnSyntax WithColumnDescription(string description) { CurrentColumn.ColumnDescription = description; return this; } /// <inheritdoc /> public ICreateTableColumnOptionOrWithColumnSyntax Identity() { CurrentColumn.IsIdentity = true; return this; } /// <inheritdoc /> public ICreateTableColumnOptionOrWithColumnSyntax Indexed() { return Indexed(null); } /// <inheritdoc /> public ICreateTableColumnOptionOrWithColumnSyntax Indexed(string indexName) { ColumnHelper.Indexed(indexName); return this; } /// <inheritdoc /> public ICreateTableColumnOptionOrWithColumnSyntax PrimaryKey() { CurrentColumn.IsPrimaryKey = true; return this; } /// <inheritdoc /> public ICreateTableColumnOptionOrWithColumnSyntax PrimaryKey(string primaryKeyName) { CurrentColumn.IsPrimaryKey = true; CurrentColumn.PrimaryKeyName = primaryKeyName; return this; } /// <inheritdoc /> public ICreateTableColumnOptionOrWithColumnSyntax Nullable() { ColumnHelper.SetNullable(true); return this; } /// <inheritdoc /> public ICreateTableColumnOptionOrWithColumnSyntax NotNullable() { ColumnHelper.SetNullable(false); return this; } /// <inheritdoc /> public ICreateTableColumnOptionOrWithColumnSyntax Unique() { ColumnHelper.Unique(null); return this; } /// <inheritdoc /> public ICreateTableColumnOptionOrWithColumnSyntax Unique(string indexName) { ColumnHelper.Unique(indexName); return this; } /// <inheritdoc /> public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax ForeignKey(string primaryTableName, string primaryColumnName) { return ForeignKey(null, null, primaryTableName, primaryColumnName); } /// <inheritdoc /> public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax ForeignKey(string foreignKeyName, string primaryTableName, string primaryColumnName) { return ForeignKey(foreignKeyName, null, primaryTableName, primaryColumnName); } /// <inheritdoc /> public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax ForeignKey( string foreignKeyName, string primaryTableSchema, string primaryTableName, string primaryColumnName) { CurrentColumn.IsForeignKey = true; var fk = new CreateForeignKeyExpression { ForeignKey = new ForeignKeyDefinition { Name = foreignKeyName, PrimaryTable = primaryTableName, PrimaryTableSchema = primaryTableSchema, ForeignTable = Expression.TableName, ForeignTableSchema = Expression.SchemaName } }; fk.ForeignKey.PrimaryColumns.Add(primaryColumnName); fk.ForeignKey.ForeignColumns.Add(CurrentColumn.Name); _context.Expressions.Add(fk); CurrentForeignKey = fk.ForeignKey; CurrentColumn.ForeignKey = fk.ForeignKey; return this; } /// <inheritdoc /> public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax ReferencedBy(string foreignTableName, string foreignColumnName) { return ReferencedBy(null, null, foreignTableName, foreignColumnName); } /// <inheritdoc /> public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax ReferencedBy(string foreignKeyName, string foreignTableName, string foreignColumnName) { return ReferencedBy(foreignKeyName, null, foreignTableName, foreignColumnName); } /// <inheritdoc /> public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax ReferencedBy( string foreignKeyName, string foreignTableSchema, string foreignTableName, string foreignColumnName) { var fk = new CreateForeignKeyExpression { ForeignKey = new ForeignKeyDefinition { Name = foreignKeyName, PrimaryTable = Expression.TableName, PrimaryTableSchema = Expression.SchemaName, ForeignTable = foreignTableName, ForeignTableSchema = foreignTableSchema } }; fk.ForeignKey.PrimaryColumns.Add(CurrentColumn.Name); fk.ForeignKey.ForeignColumns.Add(foreignColumnName); _context.Expressions.Add(fk); CurrentForeignKey = fk.ForeignKey; return this; } /// <inheritdoc /> public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax ForeignKey() { CurrentColumn.IsForeignKey = true; return this; } /// <inheritdoc /> public override ColumnDefinition GetColumnForType() { return CurrentColumn; } /// <inheritdoc /> public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax OnDelete(Rule rule) { CurrentForeignKey.OnDelete = rule; return this; } /// <inheritdoc /> public ICreateTableColumnOptionOrForeignKeyCascadeOrWithColumnSyntax OnUpdate(Rule rule) { CurrentForeignKey.OnUpdate = rule; return this; } /// <inheritdoc /> public ICreateTableColumnOptionOrWithColumnSyntax OnDeleteOrUpdate(Rule rule) { OnDelete(rule); OnUpdate(rule); return this; } /// <inheritdoc /> string IColumnExpressionBuilder.SchemaName => Expression.SchemaName; /// <inheritdoc /> string IColumnExpressionBuilder.TableName => Expression.TableName; /// <inheritdoc /> ColumnDefinition IColumnExpressionBuilder.Column => CurrentColumn; } }
/* **************************************************************************** * * 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.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if FEATURE_CORE_DLR using System.Linq.Expressions; #else using Microsoft.Scripting.Ast; #endif using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using Microsoft.Scripting.Utils; using System.Threading; using Microsoft.Scripting.Runtime; using AstUtils = Microsoft.Scripting.Ast.Utils; namespace Microsoft.Scripting.Actions { /// <summary> /// NamespaceTracker represent a CLS namespace. /// </summary> public class NamespaceTracker : MemberTracker, IMembersList, IEnumerable<KeyValuePair<string, object>> { // _dict contains all the currently loaded entries. However, there may be pending types that have // not yet been loaded in _typeNames internal Dictionary<string, MemberTracker> _dict = new Dictionary<string, MemberTracker>(); internal readonly List<Assembly> _packageAssemblies = new List<Assembly>(); internal readonly Dictionary<Assembly, TypeNames> _typeNames = new Dictionary<Assembly, TypeNames>(); private readonly string _fullName; // null for the TopReflectedPackage private TopNamespaceTracker _topPackage; private int _id; private static int _masterId; #region Protected API Surface protected NamespaceTracker(string name) { UpdateId(); _fullName = name; } public override string ToString() { return base.ToString() + ":" + _fullName; } #endregion #region Internal API Surface internal NamespaceTracker GetOrMakeChildPackage(string childName, Assembly assem) { // lock is held when this is called Assert.NotNull(childName, assem); Debug.Assert(childName.IndexOf('.') == -1); // This is the simple name, not the full name Debug.Assert(_packageAssemblies.Contains(assem)); // Parent namespace must contain all the assemblies of the child MemberTracker ret; if (_dict.TryGetValue(childName, out ret)) { // If we have a module, then we add the assembly to the InnerModule // If it's not a module, we'll wipe it out below, eg "def System(): pass" then // "import System" will result in the namespace being visible. NamespaceTracker package = ret as NamespaceTracker; if (package != null) { if (!package._packageAssemblies.Contains(assem)) { package._packageAssemblies.Add(assem); package.UpdateSubtreeIds(); } return package; } } return MakeChildPackage(childName, assem); } private NamespaceTracker MakeChildPackage(string childName, Assembly assem) { // lock is held when this is called Assert.NotNull(childName, assem); NamespaceTracker rp = new NamespaceTracker(GetFullChildName(childName)); rp.SetTopPackage(_topPackage); rp._packageAssemblies.Add(assem); _dict[childName] = rp; return rp; } private string GetFullChildName(string childName) { Assert.NotNull(childName); Debug.Assert(childName.IndexOf('.') == -1); // This is the simple name, not the full name if (_fullName == null) { return childName; } return _fullName + "." + childName; } private static Type LoadType(Assembly assem, string fullTypeName) { Assert.NotNull(assem, fullTypeName); Type type = assem.GetType(fullTypeName); // We should ignore nested types. They will be loaded when the containing type is loaded Debug.Assert(type == null || !type.IsNested()); return type; } internal void AddTypeName(string typeName, Assembly assem) { // lock is held when this is called Assert.NotNull(typeName, assem); Debug.Assert(typeName.IndexOf('.') == -1); // This is the simple name, not the full name if (!_typeNames.ContainsKey(assem)) { _typeNames[assem] = new TypeNames(assem, _fullName); } _typeNames[assem].AddTypeName(typeName); string normalizedTypeName = ReflectionUtils.GetNormalizedTypeName(typeName); if (_dict.ContainsKey(normalizedTypeName)) { // A similarly named type, namespace, or module already exists. Type newType = LoadType(assem, GetFullChildName(typeName)); if (newType != null) { object existingValue = _dict[normalizedTypeName]; TypeTracker existingTypeEntity = existingValue as TypeTracker; if (existingTypeEntity == null) { // Replace the existing namespace or module with the new type Debug.Assert(existingValue is NamespaceTracker); _dict[normalizedTypeName] = MemberTracker.FromMemberInfo(newType.GetTypeInfo()); } else { // Unify the new type with the existing type _dict[normalizedTypeName] = TypeGroup.UpdateTypeEntity(existingTypeEntity, TypeTracker.GetTypeTracker(newType)); } } } } /// <summary> /// Loads all the types from all assemblies that contribute to the current namespace (but not child namespaces) /// </summary> private void LoadAllTypes() { foreach (TypeNames typeNameList in _typeNames.Values) { foreach (string typeName in typeNameList.GetNormalizedTypeNames()) { object value; if (!TryGetValue(typeName, out value)) { Debug.Assert(false, "We should never get here as TryGetMember should raise a TypeLoadException"); throw new TypeLoadException(typeName); } } } } #endregion public override string Name { get { return _fullName; } } protected void DiscoverAllTypes(Assembly assem) { // lock is held when this is called Assert.NotNull(assem); NamespaceTracker previousPackage = null; string previousFullNamespace = String.Empty; // Note that String.Empty is not a valid namespace foreach (TypeName typeName in AssemblyTypeNames.GetTypeNames(assem, _topPackage.DomainManager.Configuration.PrivateBinding)) { NamespaceTracker package; Debug.Assert(typeName.Namespace != String.Empty); if (typeName.Namespace == previousFullNamespace) { // We have a cache hit. We dont need to call GetOrMakePackageHierarchy (which generates // a fair amount of temporary substrings) package = previousPackage; } else { package = GetOrMakePackageHierarchy(assem, typeName.Namespace); previousFullNamespace = typeName.Namespace; previousPackage = package; } package.AddTypeName(typeName.Name, assem); } } /// <summary> /// Populates the tree with nodes for each part of the namespace /// </summary> /// <param name="assem"></param> /// <param name="fullNamespace">Full namespace name. It can be null (for top-level types)</param> /// <returns></returns> private NamespaceTracker GetOrMakePackageHierarchy(Assembly assem, string fullNamespace) { // lock is held when this is called Assert.NotNull(assem); if (fullNamespace == null) { // null is the top-level namespace return this; } NamespaceTracker ret = this; string[] pieces = fullNamespace.Split('.'); for (int i = 0; i < pieces.Length; i++) { ret = ret.GetOrMakeChildPackage(pieces[i], assem); } return ret; } /// <summary> /// As a fallback, so if the type does exist in any assembly. This would happen if a new type was added /// that was not in the hardcoded list of types. /// This code is not accurate because: /// 1. We dont deal with generic types (TypeCollision). /// 2. Previous calls to GetCustomMemberNames (eg. "from foo import *" in Python) would not have included this type. /// 3. This does not deal with new namespaces added to the assembly /// </summary> private MemberTracker CheckForUnlistedType(string nameString) { Assert.NotNull(nameString); string fullTypeName = GetFullChildName(nameString); foreach (Assembly assem in _packageAssemblies) { Type type = assem.GetType(fullTypeName); if (type == null || type.IsNested()) { continue; } bool publishType = type.IsPublic() || _topPackage.DomainManager.Configuration.PrivateBinding; if (!publishType) { continue; } // We dont use TypeCollision.UpdateTypeEntity here because we do not handle generic type names return TypeTracker.GetTypeTracker(type); } return null; } #region IAttributesCollection Members public bool TryGetValue(string name, out object value) { MemberTracker tmp; bool res = TryGetValue(name, out tmp); value = tmp; return res; } public bool TryGetValue(string name, out MemberTracker value) { lock (_topPackage.HierarchyLock) { LoadNamespaces(); if (_dict.TryGetValue(name, out value)) { return true; } MemberTracker existingTypeEntity = null; if (name.IndexOf('.') != -1) { value = null; return false; } // Look up the type names and load the type if its name exists foreach (KeyValuePair<Assembly, TypeNames> kvp in _typeNames) { if (!kvp.Value.Contains(name)) { continue; } existingTypeEntity = kvp.Value.UpdateTypeEntity((TypeTracker)existingTypeEntity, name); } if (existingTypeEntity == null) { existingTypeEntity = CheckForUnlistedType(name); } if (existingTypeEntity != null) { _dict[name] = existingTypeEntity; value = existingTypeEntity; return true; } return false; } } public bool ContainsKey(string name) { object dummy; return TryGetValue(name, out dummy); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")] public object this[string name] { get { object res; if (TryGetValue(name, out res)) { return res; } throw new KeyNotFoundException(); } } public int Count { get { return _dict.Count; } } public ICollection<string> Keys { get { LoadNamespaces(); lock (_topPackage.HierarchyLock) { var res = new List<string>(); return (ICollection<string>)AddKeys(res); } } } private IList AddKeys(IList res) { foreach (string s in _dict.Keys) { res.Add(s); } foreach (KeyValuePair<Assembly, TypeNames> kvp in _typeNames) { foreach (string typeName in kvp.Value.GetNormalizedTypeNames()) { if (!res.Contains(typeName)) { res.Add(typeName); } } } return res; } #endregion #region IEnumerable<KeyValuePair<string, object>> Members public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { foreach (var key in Keys) { yield return new KeyValuePair<string, object>(key, this[key]); } } #endregion IEnumerator IEnumerable.GetEnumerator() { foreach (var key in Keys) { yield return new KeyValuePair<string, object>(key, this[key]); } } public IList<Assembly> PackageAssemblies { get { LoadNamespaces(); return _packageAssemblies; } } protected virtual void LoadNamespaces() { if (_topPackage != null) { _topPackage.LoadNamespaces(); } } protected void SetTopPackage(TopNamespaceTracker pkg) { Assert.NotNull(pkg); _topPackage = pkg; } /// <summary> /// This stores all the public non-nested type names in a single namespace and from a single assembly. /// This allows inspection of the namespace without eagerly loading all the types. Eagerly loading /// types slows down startup, increases working set, and is semantically incorrect as it can trigger /// TypeLoadExceptions sooner than required. /// </summary> internal class TypeNames { List<string> _simpleTypeNames = new List<string>(); Dictionary<string, List<string>> _genericTypeNames = new Dictionary<string, List<string>>(); Assembly _assembly; string _fullNamespace; internal TypeNames(Assembly assembly, string fullNamespace) { _assembly = assembly; _fullNamespace = fullNamespace; } internal bool Contains(string normalizedTypeName) { Debug.Assert(normalizedTypeName.IndexOf('.') == -1); // This is the simple name, not the full name Debug.Assert(ReflectionUtils.GetNormalizedTypeName(normalizedTypeName) == normalizedTypeName); return _simpleTypeNames.Contains(normalizedTypeName) || _genericTypeNames.ContainsKey(normalizedTypeName); } internal MemberTracker UpdateTypeEntity(TypeTracker existingTypeEntity, string normalizedTypeName) { Debug.Assert(normalizedTypeName.IndexOf('.') == -1); // This is the simple name, not the full name Debug.Assert(ReflectionUtils.GetNormalizedTypeName(normalizedTypeName) == normalizedTypeName); // Look for a non-generic type if (_simpleTypeNames.Contains(normalizedTypeName)) { Type newType = LoadType(_assembly, GetFullChildName(normalizedTypeName)); if (newType != null) { existingTypeEntity = TypeGroup.UpdateTypeEntity(existingTypeEntity, TypeTracker.GetTypeTracker(newType)); } } // Look for generic types if (_genericTypeNames.ContainsKey(normalizedTypeName)) { List<string> actualNames = _genericTypeNames[normalizedTypeName]; foreach (string actualName in actualNames) { Type newType = LoadType(_assembly, GetFullChildName(actualName)); if (newType != null) { existingTypeEntity = TypeGroup.UpdateTypeEntity(existingTypeEntity, TypeTracker.GetTypeTracker(newType)); } } } return existingTypeEntity; } internal void AddTypeName(string typeName) { Debug.Assert(typeName.IndexOf('.') == -1); // This is the simple name, not the full name string normalizedName = ReflectionUtils.GetNormalizedTypeName(typeName); if (normalizedName == typeName) { _simpleTypeNames.Add(typeName); } else { List<string> actualNames; if (_genericTypeNames.ContainsKey(normalizedName)) { actualNames = _genericTypeNames[normalizedName]; } else { actualNames = new List<string>(); _genericTypeNames[normalizedName] = actualNames; } actualNames.Add(typeName); } } string GetFullChildName(string childName) { Debug.Assert(childName.IndexOf('.') == -1); // This is the simple name, not the full name if (_fullNamespace == null) { return childName; } return _fullNamespace + "." + childName; } internal ICollection<string> GetNormalizedTypeNames() { List<string> normalizedTypeNames = new List<string>(); normalizedTypeNames.AddRange(_simpleTypeNames); normalizedTypeNames.AddRange(_genericTypeNames.Keys); return normalizedTypeNames; } } public int Id { get { return _id; } } #region IMembersList Members public IList<string> GetMemberNames() { LoadNamespaces(); lock (_topPackage.HierarchyLock) { List<string> res = new List<string>(); AddKeys(res); res.Sort(); return res; } } #endregion public override TrackerTypes MemberType { get { return TrackerTypes.Namespace; } } public override Type DeclaringType { get { return null; } } private void UpdateId() { _id = Interlocked.Increment(ref _masterId); } protected void UpdateSubtreeIds() { // lock is held when this is called UpdateId(); foreach (KeyValuePair<string, MemberTracker> kvp in _dict) { NamespaceTracker ns = kvp.Value as NamespaceTracker; if (ns != null) { ns.UpdateSubtreeIds(); } } } } }
/************************************************************************************ Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved. Licensed under the Oculus SDK License Version 3.4.1 (the "License"); you may not use the Oculus SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at https://developer.oculus.com/licenses/sdk-3.4.1 Unless required by applicable law or agreed to in writing, the Oculus SDK 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. ************************************************************************************/ #if !UNITY_5_6_OR_NEWER #error Oculus Utilities require Unity 5.6 or higher. #endif using System; using System.Collections.Generic; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif /// <summary> /// Configuration data for Oculus virtual reality. /// </summary> public class OVRManager : MonoBehaviour { public enum TrackingOrigin { EyeLevel = OVRPlugin.TrackingOrigin.EyeLevel, FloorLevel = OVRPlugin.TrackingOrigin.FloorLevel, } public enum EyeTextureFormat { Default = OVRPlugin.EyeTextureFormat.Default, R16G16B16A16_FP = OVRPlugin.EyeTextureFormat.R16G16B16A16_FP, R11G11B10_FP = OVRPlugin.EyeTextureFormat.R11G11B10_FP, } public enum TiledMultiResLevel { Off = OVRPlugin.TiledMultiResLevel.Off, LMSLow = OVRPlugin.TiledMultiResLevel.LMSLow, LMSMedium = OVRPlugin.TiledMultiResLevel.LMSMedium, LMSHigh = OVRPlugin.TiledMultiResLevel.LMSHigh, } /// <summary> /// Gets the singleton instance. /// </summary> public static OVRManager instance { get; private set; } /// <summary> /// Gets a reference to the active display. /// </summary> public static OVRDisplay display { get; private set; } /// <summary> /// Gets a reference to the active sensor. /// </summary> public static OVRTracker tracker { get; private set; } /// <summary> /// Gets a reference to the active boundary system. /// </summary> public static OVRBoundary boundary { get; private set; } private static OVRProfile _profile; /// <summary> /// Gets the current profile, which contains information about the user's settings and body dimensions. /// </summary> public static OVRProfile profile { get { if (_profile == null) _profile = new OVRProfile(); return _profile; } } private IEnumerable<Camera> disabledCameras; float prevTimeScale; /// <summary> /// Occurs when an HMD attached. /// </summary> public static event Action HMDAcquired; /// <summary> /// Occurs when an HMD detached. /// </summary> public static event Action HMDLost; /// <summary> /// Occurs when an HMD is put on the user's head. /// </summary> public static event Action HMDMounted; /// <summary> /// Occurs when an HMD is taken off the user's head. /// </summary> public static event Action HMDUnmounted; /// <summary> /// Occurs when VR Focus is acquired. /// </summary> public static event Action VrFocusAcquired; /// <summary> /// Occurs when VR Focus is lost. /// </summary> public static event Action VrFocusLost; /// <summary> /// Occurs when Input Focus is acquired. /// </summary> public static event Action InputFocusAcquired; /// <summary> /// Occurs when Input Focus is lost. /// </summary> public static event Action InputFocusLost; /// <summary> /// Occurs when the active Audio Out device has changed and a restart is needed. /// </summary> public static event Action AudioOutChanged; /// <summary> /// Occurs when the active Audio In device has changed and a restart is needed. /// </summary> public static event Action AudioInChanged; /// <summary> /// Occurs when the sensor gained tracking. /// </summary> public static event Action TrackingAcquired; /// <summary> /// Occurs when the sensor lost tracking. /// </summary> public static event Action TrackingLost; /// <summary> /// Occurs when Health & Safety Warning is dismissed. /// </summary> //Disable the warning about it being unused. It's deprecated. #pragma warning disable 0067 [Obsolete] public static event Action HSWDismissed; #pragma warning restore private static bool _isHmdPresentCached = false; private static bool _isHmdPresent = false; private static bool _wasHmdPresent = false; /// <summary> /// If true, a head-mounted display is connected and present. /// </summary> public static bool isHmdPresent { get { if (!_isHmdPresentCached) { _isHmdPresentCached = true; _isHmdPresent = OVRPlugin.hmdPresent; } return _isHmdPresent; } private set { _isHmdPresentCached = true; _isHmdPresent = value; } } /// <summary> /// Gets the audio output device identifier. /// </summary> /// <description> /// On Windows, this is a string containing the GUID of the IMMDevice for the Windows audio endpoint to use. /// </description> public static string audioOutId { get { return OVRPlugin.audioOutId; } } /// <summary> /// Gets the audio input device identifier. /// </summary> /// <description> /// On Windows, this is a string containing the GUID of the IMMDevice for the Windows audio endpoint to use. /// </description> public static string audioInId { get { return OVRPlugin.audioInId; } } private static bool _hasVrFocusCached = false; private static bool _hasVrFocus = false; private static bool _hadVrFocus = false; /// <summary> /// If true, the app has VR Focus. /// </summary> public static bool hasVrFocus { get { if (!_hasVrFocusCached) { _hasVrFocusCached = true; _hasVrFocus = OVRPlugin.hasVrFocus; } return _hasVrFocus; } private set { _hasVrFocusCached = true; _hasVrFocus = value; } } private static bool _hadInputFocus = true; /// <summary> /// If true, the app has Input Focus. /// </summary> public static bool hasInputFocus { get { return OVRPlugin.hasInputFocus; } } /// <summary> /// If true, chromatic de-aberration will be applied, improving the image at the cost of texture bandwidth. /// </summary> public bool chromatic { get { if (!isHmdPresent) return false; return OVRPlugin.chromatic; } set { if (!isHmdPresent) return; OVRPlugin.chromatic = value; } } [Header("Performance/Quality")] /// <summary> /// If true, distortion rendering work is submitted a quarter-frame early to avoid pipeline stalls and increase CPU-GPU parallelism. /// </summary> [Tooltip("If true, distortion rendering work is submitted a quarter-frame early to avoid pipeline stalls and increase CPU-GPU parallelism.")] public bool queueAhead = true; /// <summary> /// If true, Unity will use the optimal antialiasing level for quality/performance on the current hardware. /// </summary> [Tooltip("If true, Unity will use the optimal antialiasing level for quality/performance on the current hardware.")] public bool useRecommendedMSAALevel = false; /// <summary> /// If true, both eyes will see the same image, rendered from the center eye pose, saving performance. /// </summary> [SerializeField] [Tooltip("If true, both eyes will see the same image, rendered from the center eye pose, saving performance.")] private bool _monoscopic = false; public bool monoscopic { get { if (!isHmdPresent) return _monoscopic; return OVRPlugin.monoscopic; } set { if (!isHmdPresent) return; OVRPlugin.monoscopic = value; _monoscopic = value; } } /// <summary> /// If true, dynamic resolution will be enabled /// </summary> [Tooltip("If true, dynamic resolution will be enabled On PC")] public bool enableAdaptiveResolution = false; /// <summary> /// Adaptive Resolution is based on Unity engine's renderViewportScale/eyeTextureResolutionScale feature /// But renderViewportScale was broken in an array of Unity engines, this function help to filter out those broken engines /// </summary> public static bool IsAdaptiveResSupportedByEngine() { #if UNITY_2017_1_OR_NEWER return Application.unityVersion != "2017.1.0f1"; #else return false; #endif } /// <summary> /// Min RenderScale the app can reach under adaptive resolution mode ( enableAdaptiveResolution = true ); /// </summary> [RangeAttribute(0.5f, 2.0f)] [Tooltip("Min RenderScale the app can reach under adaptive resolution mode")] public float minRenderScale = 0.7f; /// <summary> /// Max RenderScale the app can reach under adaptive resolution mode ( enableAdaptiveResolution = true ); /// </summary> [RangeAttribute(0.5f, 2.0f)] [Tooltip("Max RenderScale the app can reach under adaptive resolution mode")] public float maxRenderScale = 1.0f; /// <summary> /// Set the relative offset rotation of head poses /// </summary> [SerializeField] [Tooltip("Set the relative offset rotation of head poses")] private Vector3 _headPoseRelativeOffsetRotation; public Vector3 headPoseRelativeOffsetRotation { get { return _headPoseRelativeOffsetRotation; } set { OVRPlugin.Quatf rotation; OVRPlugin.Vector3f translation; if (OVRPlugin.GetHeadPoseModifier(out rotation, out translation)) { Quaternion finalRotation = Quaternion.Euler(value); rotation = finalRotation.ToQuatf(); OVRPlugin.SetHeadPoseModifier(ref rotation, ref translation); } _headPoseRelativeOffsetRotation = value; } } /// <summary> /// Set the relative offset translation of head poses /// </summary> [SerializeField] [Tooltip("Set the relative offset translation of head poses")] private Vector3 _headPoseRelativeOffsetTranslation; public Vector3 headPoseRelativeOffsetTranslation { get { OVRPlugin.Quatf rotation; OVRPlugin.Vector3f translation; if (OVRPlugin.GetHeadPoseModifier(out rotation, out translation)) { return translation.FromFlippedZVector3f(); } else { return Vector3.zero; } } set { OVRPlugin.Quatf rotation; OVRPlugin.Vector3f translation; if (OVRPlugin.GetHeadPoseModifier(out rotation, out translation)) { if (translation.FromFlippedZVector3f() != value) { translation = value.ToFlippedZVector3f(); OVRPlugin.SetHeadPoseModifier(ref rotation, ref translation); } } _headPoseRelativeOffsetTranslation = value; } } #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN /// <summary> /// If true, the MixedRealityCapture properties will be displayed /// </summary> [HideInInspector] public bool expandMixedRealityCapturePropertySheet = false; /// <summary> /// If true, Mixed Reality mode will be enabled /// </summary> [HideInInspector, Tooltip("If true, Mixed Reality mode will be enabled. It would be always set to false when the game is launching without editor")] public bool enableMixedReality = false; public enum CompositionMethod { External, Direct, Sandwich } /// <summary> /// Composition method /// </summary> [HideInInspector] public CompositionMethod compositionMethod = CompositionMethod.External; /// <summary> /// Extra hidden layers /// </summary> [HideInInspector, Tooltip("Extra hidden layers")] public LayerMask extraHiddenLayers; /// <summary> /// If true, Mixed Reality mode will use direct composition from the first web camera /// </summary> public enum CameraDevice { WebCamera0, WebCamera1, ZEDCamera } /// <summary> /// The camera device for direct composition /// </summary> [HideInInspector, Tooltip("The camera device for direct composition")] public CameraDevice capturingCameraDevice = CameraDevice.WebCamera0; /// <summary> /// Flip the camera frame horizontally /// </summary> [HideInInspector, Tooltip("Flip the camera frame horizontally")] public bool flipCameraFrameHorizontally = false; /// <summary> /// Flip the camera frame vertically /// </summary> [HideInInspector, Tooltip("Flip the camera frame vertically")] public bool flipCameraFrameVertically = false; /// <summary> /// Delay the touch controller pose by a short duration (0 to 0.5 second) to match the physical camera latency /// </summary> [HideInInspector, Tooltip("Delay the touch controller pose by a short duration (0 to 0.5 second) to match the physical camera latency")] public float handPoseStateLatency = 0.0f; /// <summary> /// Delay the foreground / background image in the sandwich composition to match the physical camera latency. The maximum duration is sandwichCompositionBufferedFrames / {Game FPS} /// </summary> [HideInInspector, Tooltip("Delay the foreground / background image in the sandwich composition to match the physical camera latency. The maximum duration is sandwichCompositionBufferedFrames / {Game FPS}")] public float sandwichCompositionRenderLatency = 0.0f; /// <summary> /// The number of frames are buffered in the SandWich composition. The more buffered frames, the more memory it would consume. /// </summary> [HideInInspector, Tooltip("The number of frames are buffered in the SandWich composition. The more buffered frames, the more memory it would consume.")] public int sandwichCompositionBufferedFrames = 8; /// <summary> /// Chroma Key Color /// </summary> [HideInInspector, Tooltip("Chroma Key Color")] public Color chromaKeyColor = Color.green; /// <summary> /// Chroma Key Similarity /// </summary> [HideInInspector, Tooltip("Chroma Key Similarity")] public float chromaKeySimilarity = 0.60f; /// <summary> /// Chroma Key Smooth Range /// </summary> [HideInInspector, Tooltip("Chroma Key Smooth Range")] public float chromaKeySmoothRange = 0.03f; /// <summary> /// Chroma Key Spill Range /// </summary> [HideInInspector, Tooltip("Chroma Key Spill Range")] public float chromaKeySpillRange = 0.06f; /// <summary> /// Use dynamic lighting (Depth sensor required) /// </summary> [HideInInspector, Tooltip("Use dynamic lighting (Depth sensor required)")] public bool useDynamicLighting = false; public enum DepthQuality { Low, Medium, High } /// <summary> /// The quality level of depth image. The lighting could be more smooth and accurate with high quality depth, but it would also be more costly in performance. /// </summary> [HideInInspector, Tooltip("The quality level of depth image. The lighting could be more smooth and accurate with high quality depth, but it would also be more costly in performance.")] public DepthQuality depthQuality = DepthQuality.Medium; /// <summary> /// Smooth factor in dynamic lighting. Larger is smoother /// </summary> [HideInInspector, Tooltip("Smooth factor in dynamic lighting. Larger is smoother")] public float dynamicLightingSmoothFactor = 8.0f; /// <summary> /// The maximum depth variation across the edges. Make it smaller to smooth the lighting on the edges. /// </summary> [HideInInspector, Tooltip("The maximum depth variation across the edges. Make it smaller to smooth the lighting on the edges.")] public float dynamicLightingDepthVariationClampingValue = 0.001f; public enum VirtualGreenScreenType { Off, OuterBoundary, PlayArea } /// <summary> /// Set the current type of the virtual green screen /// </summary> [HideInInspector, Tooltip("Type of virutal green screen ")] public VirtualGreenScreenType virtualGreenScreenType = VirtualGreenScreenType.Off; /// <summary> /// Top Y of virtual screen /// </summary> [HideInInspector, Tooltip("Top Y of virtual green screen")] public float virtualGreenScreenTopY = 10.0f; /// <summary> /// Bottom Y of virtual screen /// </summary> [HideInInspector, Tooltip("Bottom Y of virtual green screen")] public float virtualGreenScreenBottomY = -10.0f; /// <summary> /// When using a depth camera (e.g. ZED), whether to use the depth in virtual green screen culling. /// </summary> [HideInInspector, Tooltip("When using a depth camera (e.g. ZED), whether to use the depth in virtual green screen culling.")] public bool virtualGreenScreenApplyDepthCulling = false; /// <summary> /// The tolerance value (in meter) when using the virtual green screen with a depth camera. Make it bigger if the foreground objects got culled incorrectly. /// </summary> [HideInInspector, Tooltip("The tolerance value (in meter) when using the virtual green screen with a depth camera. Make it bigger if the foreground objects got culled incorrectly.")] public float virtualGreenScreenDepthTolerance = 0.2f; #endif /// <summary> /// The number of expected display frames per rendered frame. /// </summary> public int vsyncCount { get { if (!isHmdPresent) return 1; return OVRPlugin.vsyncCount; } set { if (!isHmdPresent) return; OVRPlugin.vsyncCount = value; } } /// <summary> /// Gets the current battery level. /// </summary> /// <returns><c>battery level in the range [0.0,1.0]</c> /// <param name="batteryLevel">Battery level.</param> public static float batteryLevel { get { if (!isHmdPresent) return 1f; return OVRPlugin.batteryLevel; } } /// <summary> /// Gets the current battery temperature. /// </summary> /// <returns><c>battery temperature in Celsius</c> /// <param name="batteryTemperature">Battery temperature.</param> public static float batteryTemperature { get { if (!isHmdPresent) return 0f; return OVRPlugin.batteryTemperature; } } /// <summary> /// Gets the current battery status. /// </summary> /// <returns><c>battery status</c> /// <param name="batteryStatus">Battery status.</param> public static int batteryStatus { get { if (!isHmdPresent) return -1; return (int)OVRPlugin.batteryStatus; } } /// <summary> /// Gets the current volume level. /// </summary> /// <returns><c>volume level in the range [0,1].</c> public static float volumeLevel { get { if (!isHmdPresent) return 0f; return OVRPlugin.systemVolume; } } /// <summary> /// Gets or sets the current CPU performance level (0-2). Lower performance levels save more power. /// </summary> public static int cpuLevel { get { if (!isHmdPresent) return 2; return OVRPlugin.cpuLevel; } set { if (!isHmdPresent) return; OVRPlugin.cpuLevel = value; } } /// <summary> /// Gets or sets the current GPU performance level (0-2). Lower performance levels save more power. /// </summary> public static int gpuLevel { get { if (!isHmdPresent) return 2; return OVRPlugin.gpuLevel; } set { if (!isHmdPresent) return; OVRPlugin.gpuLevel = value; } } /// <summary> /// If true, the CPU and GPU are currently throttled to save power and/or reduce the temperature. /// </summary> public static bool isPowerSavingActive { get { if (!isHmdPresent) return false; return OVRPlugin.powerSaving; } } /// <summary> /// Gets or sets the eye texture format. /// </summary> public static EyeTextureFormat eyeTextureFormat { get { return (OVRManager.EyeTextureFormat)OVRPlugin.GetDesiredEyeTextureFormat(); } set { OVRPlugin.SetDesiredEyeTextureFormat((OVRPlugin.EyeTextureFormat)value); } } /// <summary> /// Gets if tiled-based multi-resolution technique is supported /// This feature is only supported on QCOMM-based Android devices /// </summary> public static bool tiledMultiResSupported { get { return OVRPlugin.tiledMultiResSupported; } } /// <summary> /// Gets or sets the tiled-based multi-resolution level /// This feature is only supported on QCOMM-based Android devices /// </summary> public static TiledMultiResLevel tiledMultiResLevel { get { if (!OVRPlugin.tiledMultiResSupported) { Debug.LogWarning("Tiled-based Multi-resolution feature is not supported"); } return (TiledMultiResLevel)OVRPlugin.tiledMultiResLevel; } set { if (!OVRPlugin.tiledMultiResSupported) { Debug.LogWarning("Tiled-based Multi-resolution feature is not supported"); } OVRPlugin.tiledMultiResLevel = (OVRPlugin.TiledMultiResLevel)value; } } /// <summary> /// Gets if the GPU Utility is supported /// This feature is only supported on QCOMM-based Android devices /// </summary> public static bool gpuUtilSupported { get { return OVRPlugin.gpuUtilSupported; } } /// <summary> /// Gets the GPU Utilised Level (0.0 - 1.0) /// This feature is only supported on QCOMM-based Android devices /// </summary> public static float gpuUtilLevel { get { if (!OVRPlugin.gpuUtilSupported) { Debug.LogWarning("GPU Util is not supported"); } return OVRPlugin.gpuUtilLevel; } } [Header("Tracking")] [SerializeField] [Tooltip("Defines the current tracking origin type.")] private OVRManager.TrackingOrigin _trackingOriginType = OVRManager.TrackingOrigin.EyeLevel; /// <summary> /// Defines the current tracking origin type. /// </summary> public OVRManager.TrackingOrigin trackingOriginType { get { if (!isHmdPresent) return _trackingOriginType; return (OVRManager.TrackingOrigin)OVRPlugin.GetTrackingOriginType(); } set { if (!isHmdPresent) return; if (OVRPlugin.SetTrackingOriginType((OVRPlugin.TrackingOrigin)value)) { // Keep the field exposed in the Unity Editor synchronized with any changes. _trackingOriginType = value; } } } /// <summary> /// If true, head tracking will affect the position of each OVRCameraRig's cameras. /// </summary> [Tooltip("If true, head tracking will affect the position of each OVRCameraRig's cameras.")] public bool usePositionTracking = true; /// <summary> /// If true, head tracking will affect the rotation of each OVRCameraRig's cameras. /// </summary> [HideInInspector] public bool useRotationTracking = true; /// <summary> /// If true, the distance between the user's eyes will affect the position of each OVRCameraRig's cameras. /// </summary> [Tooltip("If true, the distance between the user's eyes will affect the position of each OVRCameraRig's cameras.")] public bool useIPDInPositionTracking = true; /// <summary> /// If true, each scene load will cause the head pose to reset. /// </summary> [Tooltip("If true, each scene load will cause the head pose to reset.")] public bool resetTrackerOnLoad = false; /// <summary> /// If true, the Reset View in the universal menu will cause the pose to be reset. This should generally be /// enabled for applications with a stationary position in the virtual world and will allow the View Reset /// command to place the person back to a predefined location (such as a cockpit seat). /// Set this to false if you have a locomotion system because resetting the view would effectively teleport /// the player to potentially invalid locations. /// </summary> [Tooltip("If true, the Reset View in the universal menu will cause the pose to be reset. This should generally be enabled for applications with a stationary position in the virtual world and will allow the View Reset command to place the person back to a predefined location (such as a cockpit seat). Set this to false if you have a locomotion system because resetting the view would effectively teleport the player to potentially invalid locations.")] public bool AllowRecenter = true; [SerializeField] [Tooltip("Specifies HMD recentering behavior when controller recenter is performed. True recenters the HMD as well, false does not.")] private bool _reorientHMDOnControllerRecenter = true; /// <summary> /// Defines the recentering mode specified in the tooltip above. /// </summary> public bool reorientHMDOnControllerRecenter { get { if (!isHmdPresent) return false; return OVRPlugin.GetReorientHMDOnControllerRecenter(); } set { if (!isHmdPresent) return; OVRPlugin.SetReorientHMDOnControllerRecenter(value); } } /// <summary> /// True if the current platform supports virtual reality. /// </summary> public bool isSupportedPlatform { get; private set; } private static bool _isUserPresentCached = false; private static bool _isUserPresent = false; private static bool _wasUserPresent = false; /// <summary> /// True if the user is currently wearing the display. /// </summary> public bool isUserPresent { get { if (!_isUserPresentCached) { _isUserPresentCached = true; _isUserPresent = OVRPlugin.userPresent; } return _isUserPresent; } private set { _isUserPresentCached = true; _isUserPresent = value; } } private static bool prevAudioOutIdIsCached = false; private static bool prevAudioInIdIsCached = false; private static string prevAudioOutId = string.Empty; private static string prevAudioInId = string.Empty; private static bool wasPositionTracked = false; public static System.Version utilitiesVersion { get { return OVRPlugin.wrapperVersion; } } public static System.Version pluginVersion { get { return OVRPlugin.version; } } public static System.Version sdkVersion { get { return OVRPlugin.nativeSDKVersion; } } #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN private static bool prevEnableMixedReality = false; private static bool MixedRealityEnabledFromCmd() { var args = System.Environment.GetCommandLineArgs(); for (int i = 0; i < args.Length; i++) { if (args[i].ToLower() == "-mixedreality") return true; } return false; } private static bool UseDirectCompositionFromCmd() { var args = System.Environment.GetCommandLineArgs(); for (int i = 0; i < args.Length; i++) { if (args[i].ToLower() == "-directcomposition") return true; } return false; } private static bool UseExternalCompositionFromCmd() { var args = System.Environment.GetCommandLineArgs(); for (int i = 0; i < args.Length; i++) { if (args[i].ToLower() == "-externalcomposition") return true; } return false; } private static bool CreateMixedRealityCaptureConfigurationFileFromCmd() { var args = System.Environment.GetCommandLineArgs(); for (int i = 0; i < args.Length; i++) { if (args[i].ToLower() == "-create_mrc_config") return true; } return false; } private static bool LoadMixedRealityCaptureConfigurationFileFromCmd() { var args = System.Environment.GetCommandLineArgs(); for (int i = 0; i < args.Length; i++) { if (args[i].ToLower() == "-load_mrc_config") return true; } return false; } #endif internal static bool IsUnityAlphaOrBetaVersion() { string ver = Application.unityVersion; int pos = ver.Length - 1; while (pos >= 0 && ver[pos] >= '0' && ver[pos] <= '9') { --pos; } if (pos >= 0 && (ver[pos] == 'a' || ver[pos] == 'b')) return true; return false; } internal static string UnityAlphaOrBetaVersionWarningMessage = "WARNING: It's not recommended to use Unity alpha/beta release in Oculus development. Use a stable release if you encounter any issue."; #region Unity Messages private void Awake() { // Only allow one instance at runtime. if (instance != null) { enabled = false; DestroyImmediate(this); return; } instance = this; Debug.Log("Unity v" + Application.unityVersion + ", " + "Oculus Utilities v" + OVRPlugin.wrapperVersion + ", " + "OVRPlugin v" + OVRPlugin.version + ", " + "SDK v" + OVRPlugin.nativeSDKVersion + "."); #if !UNITY_EDITOR if (IsUnityAlphaOrBetaVersion()) { Debug.LogWarning(UnityAlphaOrBetaVersionWarningMessage); } #endif #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN var supportedTypes = UnityEngine.Rendering.GraphicsDeviceType.Direct3D11.ToString() + ", " + UnityEngine.Rendering.GraphicsDeviceType.Direct3D12.ToString(); if (!supportedTypes.Contains(SystemInfo.graphicsDeviceType.ToString())) Debug.LogWarning("VR rendering requires one of the following device types: (" + supportedTypes + "). Your graphics device: " + SystemInfo.graphicsDeviceType.ToString()); #endif // Detect whether this platform is a supported platform RuntimePlatform currPlatform = Application.platform; if (currPlatform == RuntimePlatform.Android || // currPlatform == RuntimePlatform.LinuxPlayer || currPlatform == RuntimePlatform.OSXEditor || currPlatform == RuntimePlatform.OSXPlayer || currPlatform == RuntimePlatform.WindowsEditor || currPlatform == RuntimePlatform.WindowsPlayer) { isSupportedPlatform = true; } else { isSupportedPlatform = false; } if (!isSupportedPlatform) { Debug.LogWarning("This platform is unsupported"); return; } #if UNITY_ANDROID && !UNITY_EDITOR // Turn off chromatic aberration by default to save texture bandwidth. chromatic = false; #endif #if UNITY_STANDALONE_WIN && !UNITY_EDITOR enableMixedReality = false; // we should never start the standalone game in MxR mode, unless the command-line parameter is provided #endif #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN bool loadMrcConfig = LoadMixedRealityCaptureConfigurationFileFromCmd(); bool createMrcConfig = CreateMixedRealityCaptureConfigurationFileFromCmd(); if (loadMrcConfig || createMrcConfig) { OVRMixedRealityCaptureSettings mrcSettings = ScriptableObject.CreateInstance<OVRMixedRealityCaptureSettings>(); mrcSettings.ReadFrom(this); if (loadMrcConfig) { mrcSettings.CombineWithConfigurationFile(); mrcSettings.ApplyTo(this); } if (createMrcConfig) { mrcSettings.WriteToConfigurationFile(); } ScriptableObject.Destroy(mrcSettings); } if (MixedRealityEnabledFromCmd()) { enableMixedReality = true; } if (enableMixedReality) { Debug.Log("OVR: Mixed Reality mode enabled"); if (UseDirectCompositionFromCmd()) { compositionMethod = CompositionMethod.Direct; } if (UseExternalCompositionFromCmd()) { compositionMethod = CompositionMethod.External; } Debug.Log("OVR: CompositionMethod : " + compositionMethod); } #endif #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN if (enableAdaptiveResolution && !OVRManager.IsAdaptiveResSupportedByEngine()) { enableAdaptiveResolution = false; UnityEngine.Debug.LogError("Your current Unity Engine " + Application.unityVersion + " might have issues to support adaptive resolution, please disable it under OVRManager"); } #endif Initialize(); if (resetTrackerOnLoad) display.RecenterPose(); #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN // Force OcculusionMesh on all the time, you can change the value to false if you really need it be off for some reasons, // be aware there are performance drops if you don't use occlusionMesh. OVRPlugin.occlusionMesh = true; #endif } #if UNITY_EDITOR private static bool _scriptsReloaded; [UnityEditor.Callbacks.DidReloadScripts] static void ScriptsReloaded() { _scriptsReloaded = true; } #endif void Initialize() { if (display == null) display = new OVRDisplay(); if (tracker == null) tracker = new OVRTracker(); if (boundary == null) boundary = new OVRBoundary(); reorientHMDOnControllerRecenter = _reorientHMDOnControllerRecenter; } #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN private bool suppressDisableMixedRealityBecauseOfNoMainCameraWarning = false; #endif private void Update() { #if UNITY_EDITOR if (_scriptsReloaded) { _scriptsReloaded = false; instance = this; Initialize(); } #endif if (OVRPlugin.shouldQuit) Application.Quit(); if (AllowRecenter && OVRPlugin.shouldRecenter) { OVRManager.display.RecenterPose(); } if (trackingOriginType != _trackingOriginType) trackingOriginType = _trackingOriginType; tracker.isEnabled = usePositionTracking; OVRPlugin.rotation = useRotationTracking; OVRPlugin.useIPDInPositionTracking = useIPDInPositionTracking; // Dispatch HMD events. isHmdPresent = OVRPlugin.hmdPresent; if (useRecommendedMSAALevel && QualitySettings.antiAliasing != display.recommendedMSAALevel) { Debug.Log("The current MSAA level is " + QualitySettings.antiAliasing + ", but the recommended MSAA level is " + display.recommendedMSAALevel + ". Switching to the recommended level."); QualitySettings.antiAliasing = display.recommendedMSAALevel; } if (monoscopic != _monoscopic) { monoscopic = _monoscopic; } if (headPoseRelativeOffsetRotation != _headPoseRelativeOffsetRotation) { headPoseRelativeOffsetRotation = _headPoseRelativeOffsetRotation; } if (headPoseRelativeOffsetTranslation != _headPoseRelativeOffsetTranslation) { headPoseRelativeOffsetTranslation = _headPoseRelativeOffsetTranslation; } if (_wasHmdPresent && !isHmdPresent) { try { if (HMDLost != null) HMDLost(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } if (!_wasHmdPresent && isHmdPresent) { try { if (HMDAcquired != null) HMDAcquired(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } _wasHmdPresent = isHmdPresent; // Dispatch HMD mounted events. isUserPresent = OVRPlugin.userPresent; if (_wasUserPresent && !isUserPresent) { try { if (HMDUnmounted != null) HMDUnmounted(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } if (!_wasUserPresent && isUserPresent) { try { if (HMDMounted != null) HMDMounted(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } _wasUserPresent = isUserPresent; // Dispatch VR Focus events. hasVrFocus = OVRPlugin.hasVrFocus; if (_hadVrFocus && !hasVrFocus) { try { if (VrFocusLost != null) VrFocusLost(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } if (!_hadVrFocus && hasVrFocus) { try { if (VrFocusAcquired != null) VrFocusAcquired(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } _hadVrFocus = hasVrFocus; // Dispatch VR Input events. bool hasInputFocus = OVRPlugin.hasInputFocus; if (_hadInputFocus && !hasInputFocus) { try { if (InputFocusLost != null) InputFocusLost(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } if (!_hadInputFocus && hasInputFocus) { try { if (InputFocusAcquired != null) InputFocusAcquired(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } _hadInputFocus = hasInputFocus; // Changing effective rendering resolution dynamically according performance #if (UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN) if (enableAdaptiveResolution) { #if UNITY_2017_2_OR_NEWER if (UnityEngine.XR.XRSettings.eyeTextureResolutionScale < maxRenderScale) { // Allocate renderScale to max to avoid re-allocation UnityEngine.XR.XRSettings.eyeTextureResolutionScale = maxRenderScale; } else { // Adjusting maxRenderScale in case app started with a larger renderScale value maxRenderScale = Mathf.Max(maxRenderScale, UnityEngine.XR.XRSettings.eyeTextureResolutionScale); } minRenderScale = Mathf.Min(minRenderScale, maxRenderScale); float minViewportScale = minRenderScale / UnityEngine.XR.XRSettings.eyeTextureResolutionScale; float recommendedViewportScale = OVRPlugin.GetEyeRecommendedResolutionScale() / UnityEngine.XR.XRSettings.eyeTextureResolutionScale; recommendedViewportScale = Mathf.Clamp(recommendedViewportScale, minViewportScale, 1.0f); UnityEngine.XR.XRSettings.renderViewportScale = recommendedViewportScale; #else if (UnityEngine.VR.VRSettings.renderScale < maxRenderScale) { // Allocate renderScale to max to avoid re-allocation UnityEngine.VR.VRSettings.renderScale = maxRenderScale; } else { // Adjusting maxRenderScale in case app started with a larger renderScale value maxRenderScale = Mathf.Max(maxRenderScale, UnityEngine.VR.VRSettings.renderScale); } minRenderScale = Mathf.Min(minRenderScale, maxRenderScale); float minViewportScale = minRenderScale / UnityEngine.VR.VRSettings.renderScale; float recommendedViewportScale = OVRPlugin.GetEyeRecommendedResolutionScale() / UnityEngine.VR.VRSettings.renderScale; recommendedViewportScale = Mathf.Clamp(recommendedViewportScale, minViewportScale, 1.0f); UnityEngine.VR.VRSettings.renderViewportScale = recommendedViewportScale; #endif } #endif // Dispatch Audio Device events. string audioOutId = OVRPlugin.audioOutId; if (!prevAudioOutIdIsCached) { prevAudioOutId = audioOutId; prevAudioOutIdIsCached = true; } else if (audioOutId != prevAudioOutId) { try { if (AudioOutChanged != null) AudioOutChanged(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } prevAudioOutId = audioOutId; } string audioInId = OVRPlugin.audioInId; if (!prevAudioInIdIsCached) { prevAudioInId = audioInId; prevAudioInIdIsCached = true; } else if (audioInId != prevAudioInId) { try { if (AudioInChanged != null) AudioInChanged(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } prevAudioInId = audioInId; } // Dispatch tracking events. if (wasPositionTracked && !tracker.isPositionTracked) { try { if (TrackingLost != null) TrackingLost(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } if (!wasPositionTracked && tracker.isPositionTracked) { try { if (TrackingAcquired != null) TrackingAcquired(); } catch (Exception e) { Debug.LogError("Caught Exception: " + e); } } wasPositionTracked = tracker.isPositionTracked; display.Update(); OVRInput.Update(); #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN if (enableMixedReality || prevEnableMixedReality) { Camera mainCamera = FindMainCamera(); if (Camera.main != null) { suppressDisableMixedRealityBecauseOfNoMainCameraWarning = false; if (enableMixedReality) { OVRMixedReality.Update(this.gameObject, mainCamera, compositionMethod, useDynamicLighting, capturingCameraDevice, depthQuality); } if (prevEnableMixedReality && !enableMixedReality) { OVRMixedReality.Cleanup(); } prevEnableMixedReality = enableMixedReality; } else { if (!suppressDisableMixedRealityBecauseOfNoMainCameraWarning) { Debug.LogWarning("Main Camera is not set, Mixed Reality disabled"); suppressDisableMixedRealityBecauseOfNoMainCameraWarning = true; } } } #endif } private bool multipleMainCameraWarningPresented = false; private Camera FindMainCamera() { GameObject[] objects = GameObject.FindGameObjectsWithTag("MainCamera"); List<Camera> cameras = new List<Camera>(4); foreach (GameObject obj in objects) { Camera camera = obj.GetComponent<Camera>(); if (camera != null && camera.enabled) { OVRCameraRig cameraRig = camera.GetComponentInParent<OVRCameraRig>(); if (cameraRig != null && cameraRig.trackingSpace != null) { cameras.Add(camera); } } } if (cameras.Count == 0) { return Camera.main; // pick one of the cameras which tagged as "MainCamera" } else if (cameras.Count == 1) { return cameras[0]; } else { if (!multipleMainCameraWarningPresented) { Debug.LogWarning("Multiple MainCamera found. Assume the real MainCamera is the camera with the least depth"); multipleMainCameraWarningPresented = true; } // return the camera with least depth cameras.Sort((Camera c0, Camera c1) => { return c0.depth < c1.depth ? -1 : (c0.depth > c1.depth ? 1 : 0); }); return cameras[0]; } } private void OnDisable() { #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN OVRMixedReality.Cleanup(); #endif } private void LateUpdate() { OVRHaptics.Process(); } private void FixedUpdate() { OVRInput.FixedUpdate(); } /// <summary> /// Leaves the application/game and returns to the launcher/dashboard /// </summary> public void ReturnToLauncher() { // show the platform UI quit prompt OVRManager.PlatformUIConfirmQuit(); } #endregion public static void PlatformUIConfirmQuit() { if (!isHmdPresent) return; OVRPlugin.ShowUI(OVRPlugin.PlatformUI.ConfirmQuit); } }
// 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="ImmutableSortedDictionary{TKey, TValue}.Builder"/> class. /// </content> [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] public sealed partial class ImmutableSortedDictionary<TKey, TValue> { /// <summary> /// A sorted dictionary that mutates with little or no memory allocations, /// can produce and/or build on immutable sorted dictionary instances very efficiently. /// </summary> /// <remarks> /// <para> /// 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.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Ignored")] [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(ImmutableSortedDictionaryBuilderDebuggerProxy<,>))] public sealed class Builder : IDictionary<TKey, TValue>, IReadOnlyDictionary<TKey, TValue>, IDictionary { /// <summary> /// The binary tree used to store the contents of the map. Contents are typically not entirely frozen. /// </summary> private Node _root = Node.EmptyNode; /// <summary> /// The key comparer. /// </summary> private IComparer<TKey> _keyComparer = Comparer<TKey>.Default; /// <summary> /// The value comparer. /// </summary> private IEqualityComparer<TValue> _valueComparer = EqualityComparer<TValue>.Default; /// <summary> /// The number of entries in the map. /// </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 ImmutableSortedDictionary<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="Builder"/> class. /// </summary> /// <param name="map">A map to act as the basis for a new map.</param> internal Builder(ImmutableSortedDictionary<TKey, TValue> map) { Requires.NotNull(map, nameof(map)); _root = map._root; _keyComparer = map.KeyComparer; _valueComparer = map.ValueComparer; _count = map.Count; _immutable = map; } #region IDictionary<TKey, TValue> Properties and Indexer /// <summary> /// See <see cref="IDictionary{TKey, TValue}"/> /// </summary> ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { return this.Root.Keys.ToArray(this.Count); } } /// <summary> /// See <see cref="IReadOnlyDictionary{TKey, TValue}"/> /// </summary> public IEnumerable<TKey> Keys { get { return this.Root.Keys; } } /// <summary> /// See <see cref="IDictionary{TKey, TValue}"/> /// </summary> ICollection<TValue> IDictionary<TKey, TValue>.Values { get { return this.Root.Values.ToArray(this.Count); } } /// <summary> /// See <see cref="IReadOnlyDictionary{TKey, TValue}"/> /// </summary> public IEnumerable<TValue> Values { get { return this.Root.Values; } } /// <summary> /// Gets the number of elements in this map. /// </summary> public int Count { get { return _count; } } /// <summary> /// Gets a value indicating whether this instance is read-only. /// </summary> /// <value>Always <c>false</c>.</value> bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return false; } } #endregion /// <summary> /// Gets the current version of the contents of this builder. /// </summary> internal int Version { get { return _version; } } /// <summary> /// Gets or sets the root node that represents the data in this collection. /// </summary> private Node 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; } } } #region IDictionary<TKey, TValue> Indexer /// <summary> /// Gets or sets the value for a given key. /// </summary> /// <param name="key">The key.</param> /// <returns>The value associated with the given key.</returns> public TValue this[TKey key] { get { TValue value; if (this.TryGetValue(key, out value)) { return value; } throw new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString())); } set { bool replacedExistingValue, mutated; this.Root = _root.SetItem(key, value, _keyComparer, _valueComparer, out replacedExistingValue, out mutated); if (mutated && !replacedExistingValue) { _count++; } } } #if FEATURE_ITEMREFAPI /// <summary> /// Returns a read-only reference to the value associated with the provided key. /// </summary> /// <exception cref="KeyNotFoundException">If the key is not present.</exception> public ref readonly TValue ValueRef(TKey key) { Requires.NotNullAllowStructs(key, nameof(key)); return ref _root.ValueRef(key, _keyComparer); } #endif #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; } } /// <summary> /// Gets or sets the key comparer. /// </summary> /// <value> /// The key comparer. /// </value> public IComparer<TKey> KeyComparer { get { return _keyComparer; } set { Requires.NotNull(value, nameof(value)); if (value != _keyComparer) { var newRoot = Node.EmptyNode; int count = 0; foreach (var item in this) { bool mutated; newRoot = newRoot.Add(item.Key, item.Value, value, _valueComparer, out mutated); if (mutated) { count++; } } _keyComparer = value; this.Root = newRoot; _count = count; } } } /// <summary> /// Gets or sets the value comparer. /// </summary> /// <value> /// The value comparer. /// </value> public IEqualityComparer<TValue> ValueComparer { get { return _valueComparer; } set { Requires.NotNull(value, nameof(value)); if (value != _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. _valueComparer = value; _immutable = null; // invalidate cached immutable } } } #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="index">The zero-based index in <paramref name="array"/> at which copying begins.</param> void ICollection.CopyTo(Array array, int index) { this.Root.CopyTo(array, index, this.Count); } #endregion #region IDictionary<TKey, TValue> Methods /// <summary> /// See <see cref="IDictionary{TKey, TValue}"/> /// </summary> public void Add(TKey key, TValue value) { bool mutated; this.Root = this.Root.Add(key, value, _keyComparer, _valueComparer, out mutated); if (mutated) { _count++; } } /// <summary> /// See <see cref="IDictionary{TKey, TValue}"/> /// </summary> public bool ContainsKey(TKey key) { return this.Root.ContainsKey(key, _keyComparer); } /// <summary> /// See <see cref="IDictionary{TKey, TValue}"/> /// </summary> public bool Remove(TKey key) { bool mutated; this.Root = this.Root.Remove(key, _keyComparer, out mutated); if (mutated) { _count--; } return mutated; } /// <summary> /// See <see cref="IDictionary{TKey, TValue}"/> /// </summary> public bool TryGetValue(TKey key, out TValue value) { return this.Root.TryGetValue(key, _keyComparer, out value); } /// <summary> /// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface. /// </summary> public bool TryGetKey(TKey equalKey, out TKey actualKey) { Requires.NotNullAllowStructs(equalKey, nameof(equalKey)); return this.Root.TryGetKey(equalKey, _keyComparer, out actualKey); } /// <summary> /// See <see cref="IDictionary{TKey, TValue}"/> /// </summary> public void Add(KeyValuePair<TKey, TValue> item) { this.Add(item.Key, item.Value); } /// <summary> /// See <see cref="IDictionary{TKey, TValue}"/> /// </summary> public void Clear() { this.Root = ImmutableSortedDictionary<TKey, TValue>.Node.EmptyNode; _count = 0; } /// <summary> /// See <see cref="IDictionary{TKey, TValue}"/> /// </summary> public bool Contains(KeyValuePair<TKey, TValue> item) { return this.Root.Contains(item, _keyComparer, _valueComparer); } /// <summary> /// See <see cref="IDictionary{TKey, TValue}"/> /// </summary> void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { this.Root.CopyTo(array, arrayIndex, this.Count); } /// <summary> /// See <see cref="IDictionary{TKey, TValue}"/> /// </summary> public bool Remove(KeyValuePair<TKey, TValue> item) { if (this.Contains(item)) { return this.Remove(item.Key); } return false; } /// <summary> /// See <see cref="IDictionary{TKey, TValue}"/> /// </summary> public ImmutableSortedDictionary<TKey, TValue>.Enumerator GetEnumerator() { return this.Root.GetEnumerator(this); } /// <summary> /// See <see cref="IDictionary{TKey, TValue}"/> /// </summary> IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// See <see cref="IDictionary{TKey, TValue}"/> /// </summary> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion #region Public methods /// <summary> /// Determines whether the <see cref="ImmutableSortedDictionary{TKey, TValue}"/> /// contains an element with the specified value. /// </summary> /// <param name="value"> /// The value to locate in the <see cref="ImmutableSortedDictionary{TKey, TValue}"/>. /// The value can be null for reference types. /// </param> /// <returns> /// true if the <see cref="ImmutableSortedDictionary{TKey, TValue}"/> contains /// an element with the specified value; otherwise, false. /// </returns> [Pure] public bool ContainsValue(TValue value) { return _root.ContainsValue(value, _valueComparer); } /// <summary> /// Removes any entries from the dictionaries with keys that match those found in the specified sequence. /// </summary> /// <param name="items">The keys for entries to remove from the dictionary.</param> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public void AddRange(IEnumerable<KeyValuePair<TKey, TValue>> items) { Requires.NotNull(items, nameof(items)); foreach (var pair in items) { this.Add(pair); } } /// <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> /// 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 for 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 sorted 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 ImmutableSortedDictionary<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 = Wrap(this.Root, _count, _keyComparer, _valueComparer); } return _immutable; } #endregion } } /// <summary> /// A simple view of the immutable collection that the debugger can show to the developer. /// </summary> internal class ImmutableSortedDictionaryBuilderDebuggerProxy<TKey, TValue> { /// <summary> /// The collection to be enumerated. /// </summary> private readonly ImmutableSortedDictionary<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="ImmutableSortedDictionaryBuilderDebuggerProxy{TKey, TValue}"/> class. /// </summary> /// <param name="map">The collection to display in the debugger</param> public ImmutableSortedDictionaryBuilderDebuggerProxy(ImmutableSortedDictionary<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; } } } }
// 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.ComponentModel; using System.Data.SqlClient; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Text.RegularExpressions; using Xunit; namespace System.Runtime.Serialization.Formatters.Tests { public partial class BinaryFormatterTests : RemoteExecutorTestBase { [Theory] [MemberData(nameof(BasicObjectsRoundtrip_MemberData))] public void ValidateBasicObjectsRoundtrip(object obj, FormatterAssemblyStyle assemblyFormat, TypeFilterLevel filterLevel, FormatterTypeStyle typeFormat) { object clone = BinaryFormatterHelpers.Clone(obj, null, assemblyFormat, filterLevel, typeFormat); // string.Empty and DBNull are both singletons if (!ReferenceEquals(obj, string.Empty) && !(obj is DBNull)) { Assert.NotSame(obj, clone); } EqualityExtensions.CheckEquals(obj, clone, isSamePlatform: true); } // Used for updating blobs in BinaryFormatterTestData.cs //[Fact] public void UpdateBlobs() { string testDataFilePath = GetTestDataFilePath(); string[] coreTypeBlobs = SerializableEqualityComparers_MemberData() .Concat(SerializableObjects_MemberData()) .Select(record => BinaryFormatterHelpers.ToBase64String(record[0])) .ToArray(); var (numberOfBlobs, numberOfFoundBlobs, numberOfUpdatedBlobs) = UpdateCoreTypeBlobs(testDataFilePath, coreTypeBlobs); Console.WriteLine($"{numberOfBlobs} existing blobs" + $"{Environment.NewLine}{numberOfFoundBlobs} found blobs with regex search" + $"{Environment.NewLine}{numberOfUpdatedBlobs} updated blobs with regex replace"); } [Theory] [MemberData(nameof(SerializableObjects_MemberData))] public void ValidateAgainstBlobs(object obj, string[] blobs) => ValidateAndRoundtrip(obj, blobs, false); [Theory] [MemberData(nameof(SerializableEqualityComparers_MemberData))] public void ValidateEqualityComparersAgainstBlobs(object obj, string[] blobs) => ValidateAndRoundtrip(obj, blobs, true); private static void ValidateAndRoundtrip(object obj, string[] blobs, bool isEqualityComparer) { if (obj == null) { throw new ArgumentNullException("The serializable object must not be null", nameof(obj)); } if (blobs == null || blobs.Length == 0) { throw new ArgumentOutOfRangeException($"Type {obj} has no blobs to deserialize and test equality against. Blob: " + BinaryFormatterHelpers.ToBase64String(obj, FormatterAssemblyStyle.Full)); } SanityCheckBlob(obj, blobs); // SqlException isn't deserializable from Desktop --> Core. // Therefore we remove the second blob which is the one from Desktop. if (!PlatformDetection.IsFullFramework && (obj is SqlException || obj is ReflectionTypeLoadException || obj is LicenseException)) { var tmpList = new List<string>(blobs); tmpList.RemoveAt(1); blobs = tmpList.ToArray(); } // We store our framework blobs in index 1 int platformBlobIndex = PlatformDetection.IsFullFramework ? 1 : 0; for (int i = 0; i < blobs.Length; i++) { // Check if the current blob is from the current running platform. bool isSamePlatform = i == platformBlobIndex; if (isEqualityComparer) { ValidateEqualityComparer(BinaryFormatterHelpers.FromBase64String(blobs[i], FormatterAssemblyStyle.Simple)); ValidateEqualityComparer(BinaryFormatterHelpers.FromBase64String(blobs[i], FormatterAssemblyStyle.Full)); } else { EqualityExtensions.CheckEquals(obj, BinaryFormatterHelpers.FromBase64String(blobs[i], FormatterAssemblyStyle.Simple), isSamePlatform); EqualityExtensions.CheckEquals(obj, BinaryFormatterHelpers.FromBase64String(blobs[i], FormatterAssemblyStyle.Full), isSamePlatform); } } } [Fact] public void ArraySegmentDefaultCtor() { // This is workaround for Xunit bug which tries to pretty print test case name and enumerate this object. // When inner array is not initialized it throws an exception when this happens. object obj = new ArraySegment<int>(); string corefxBlob = "AAEAAAD/////AQAAAAAAAAAEAQAAAHJTeXN0ZW0uQXJyYXlTZWdtZW50YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0DAAAABl9hcnJheQdfb2Zmc2V0Bl9jb3VudAcAAAgICAoAAAAAAAAAAAs="; string netfxBlob = "AAEAAAD/////AQAAAAAAAAAEAQAAAHJTeXN0ZW0uQXJyYXlTZWdtZW50YDFbW1N5c3RlbS5JbnQzMiwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0DAAAABl9hcnJheQdfb2Zmc2V0Bl9jb3VudAcAAAgICAoAAAAAAAAAAAs="; EqualityExtensions.CheckEquals(obj, BinaryFormatterHelpers.FromBase64String(corefxBlob, FormatterAssemblyStyle.Full), isSamePlatform: true); EqualityExtensions.CheckEquals(obj, BinaryFormatterHelpers.FromBase64String(netfxBlob, FormatterAssemblyStyle.Full), isSamePlatform: true); } [Fact] public void ValidateDeserializationOfObjectWithDifferentAssemblyVersion() { // To generate this properly, change AssemblyVersion to a value which is unlikely to happen in production and generate base64(serialized-data) // For this test 9.98.7.987 is being used var obj = new SomeType() { SomeField = 7 }; string serializedObj = @"AAEAAAD/////AQAAAAAAAAAMAgAAAHNTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249OS45OC43Ljk4NywgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViBQEAAAA2U3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlNvbWVUeXBlAQAAAAlTb21lRmllbGQACAIAAAAHAAAACw=="; var deserialized = (SomeType)BinaryFormatterHelpers.FromBase64String(serializedObj, FormatterAssemblyStyle.Simple); Assert.Equal(obj, deserialized); } [Fact] public void ValidateDeserializationOfObjectWithGenericTypeWhichGenericArgumentHasDifferentAssemblyVersion() { // To generate this properly, change AssemblyVersion to a value which is unlikely to happen in production and generate base64(serialized-data) // For this test 9.98.7.987 is being used var obj = new GenericTypeWithArg<SomeType>() { Test = new SomeType() { SomeField = 9 } }; string serializedObj = @"AAEAAAD/////AQAAAAAAAAAMAgAAAHNTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249OS45OC43Ljk4NywgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViBQEAAADxAVN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5HZW5lcmljVHlwZVdpdGhBcmdgMVtbU3lzdGVtLlJ1bnRpbWUuU2VyaWFsaXphdGlvbi5Gb3JtYXR0ZXJzLlRlc3RzLlNvbWVUeXBlLCBTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMsIFZlcnNpb249OS45OC43Ljk4NywgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj05ZDc3Y2M3YWQzOWI2OGViXV0BAAAABFRlc3QENlN5c3RlbS5SdW50aW1lLlNlcmlhbGl6YXRpb24uRm9ybWF0dGVycy5UZXN0cy5Tb21lVHlwZQIAAAACAAAACQMAAAAFAwAAADZTeXN0ZW0uUnVudGltZS5TZXJpYWxpemF0aW9uLkZvcm1hdHRlcnMuVGVzdHMuU29tZVR5cGUBAAAACVNvbWVGaWVsZAAIAgAAAAkAAAAL"; var deserialized = (GenericTypeWithArg<SomeType>)BinaryFormatterHelpers.FromBase64String(serializedObj, FormatterAssemblyStyle.Simple); Assert.Equal(obj, deserialized); } [Fact] public void RoundtripManyObjectsInOneStream() { object[][] objects = SerializableObjects_MemberData().ToArray(); var s = new MemoryStream(); var f = new BinaryFormatter(); foreach (object[] obj in objects) { f.Serialize(s, obj[0]); } s.Position = 0; foreach (object[] obj in objects) { object clone = f.Deserialize(s); EqualityExtensions.CheckEquals(obj[0], clone, isSamePlatform: true); } } [Fact] public void SameObjectRepeatedInArray() { object o = new object(); object[] arr = new[] { o, o, o, o, o }; object[] result = BinaryFormatterHelpers.Clone(arr); Assert.Equal(arr.Length, result.Length); Assert.NotSame(arr, result); Assert.NotSame(arr[0], result[0]); for (int i = 1; i < result.Length; i++) { Assert.Same(result[0], result[i]); } } [Theory] [MemberData(nameof(NonSerializableTypes_MemberData))] public void ValidateNonSerializableTypes(object obj, FormatterAssemblyStyle assemblyFormat, TypeFilterLevel filterLevel, FormatterTypeStyle typeFormat) { var f = new BinaryFormatter() { AssemblyFormat = assemblyFormat, FilterLevel = filterLevel, TypeFormat = typeFormat }; using (var s = new MemoryStream()) { Assert.Throws<SerializationException>(() => f.Serialize(s, obj)); } } [Fact] public void SerializeNonSerializableTypeWithSurrogate() { var p = new NonSerializablePair<int, string>() { Value1 = 1, Value2 = "2" }; Assert.False(p.GetType().IsSerializable); Assert.Throws<SerializationException>(() => BinaryFormatterHelpers.Clone(p)); NonSerializablePair<int, string> result = BinaryFormatterHelpers.Clone(p, new NonSerializablePairSurrogate()); Assert.NotSame(p, result); Assert.Equal(p.Value1, result.Value1); Assert.Equal(p.Value2, result.Value2); } [Fact] public void SerializationEvents_FireAsExpected() { var f = new BinaryFormatter(); var obj = new IncrementCountsDuringRoundtrip(null); Assert.Equal(0, obj.IncrementedDuringOnSerializingMethod); Assert.Equal(0, obj.IncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod); using (var s = new MemoryStream()) { f.Serialize(s, obj); s.Position = 0; Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod); Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod); var result = (IncrementCountsDuringRoundtrip)f.Deserialize(s); Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod); Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod); Assert.Equal(1, result.IncrementedDuringOnSerializingMethod); Assert.Equal(0, result.IncrementedDuringOnSerializedMethod); Assert.Equal(1, result.IncrementedDuringOnDeserializingMethod); Assert.Equal(1, result.IncrementedDuringOnDeserializedMethod); } } [Fact] public void SerializationEvents_DerivedTypeWithEvents_FireAsExpected() { var f = new BinaryFormatter(); var obj = new DerivedIncrementCountsDuringRoundtrip(null); Assert.Equal(0, obj.IncrementedDuringOnSerializingMethod); Assert.Equal(0, obj.IncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnSerializingMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializedMethod); using (var s = new MemoryStream()) { f.Serialize(s, obj); s.Position = 0; Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod); Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod); Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializingMethod); Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializedMethod); var result = (DerivedIncrementCountsDuringRoundtrip)f.Deserialize(s); Assert.Equal(1, obj.IncrementedDuringOnSerializingMethod); Assert.Equal(1, obj.IncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.IncrementedDuringOnDeserializedMethod); Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializingMethod); Assert.Equal(1, obj.DerivedIncrementedDuringOnSerializedMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializingMethod); Assert.Equal(0, obj.DerivedIncrementedDuringOnDeserializedMethod); Assert.Equal(1, result.IncrementedDuringOnSerializingMethod); Assert.Equal(0, result.IncrementedDuringOnSerializedMethod); Assert.Equal(1, result.IncrementedDuringOnDeserializingMethod); Assert.Equal(1, result.IncrementedDuringOnDeserializedMethod); Assert.Equal(1, result.DerivedIncrementedDuringOnSerializingMethod); Assert.Equal(0, result.DerivedIncrementedDuringOnSerializedMethod); Assert.Equal(1, result.DerivedIncrementedDuringOnDeserializingMethod); Assert.Equal(1, result.DerivedIncrementedDuringOnDeserializedMethod); } } [Fact] public void Properties_Roundtrip() { var f = new BinaryFormatter(); Assert.Null(f.Binder); var binder = new DelegateBinder(); f.Binder = binder; Assert.Same(binder, f.Binder); Assert.NotNull(f.Context); Assert.Null(f.Context.Context); Assert.Equal(StreamingContextStates.All, f.Context.State); var context = new StreamingContext(StreamingContextStates.Clone); f.Context = context; Assert.Equal(StreamingContextStates.Clone, f.Context.State); Assert.Null(f.SurrogateSelector); var selector = new SurrogateSelector(); f.SurrogateSelector = selector; Assert.Same(selector, f.SurrogateSelector); Assert.Equal(FormatterAssemblyStyle.Simple, f.AssemblyFormat); f.AssemblyFormat = FormatterAssemblyStyle.Full; Assert.Equal(FormatterAssemblyStyle.Full, f.AssemblyFormat); Assert.Equal(TypeFilterLevel.Full, f.FilterLevel); f.FilterLevel = TypeFilterLevel.Low; Assert.Equal(TypeFilterLevel.Low, f.FilterLevel); Assert.Equal(FormatterTypeStyle.TypesAlways, f.TypeFormat); f.TypeFormat = FormatterTypeStyle.XsdString; Assert.Equal(FormatterTypeStyle.XsdString, f.TypeFormat); } [Fact] public void SerializeDeserialize_InvalidArguments_ThrowsException() { var f = new BinaryFormatter(); AssertExtensions.Throws<ArgumentNullException>("serializationStream", () => f.Serialize(null, new object())); AssertExtensions.Throws<ArgumentNullException>("serializationStream", () => f.Deserialize(null)); Assert.Throws<SerializationException>(() => f.Deserialize(new MemoryStream())); // seekable, 0-length } [Theory] [InlineData(FormatterAssemblyStyle.Simple, false)] [InlineData(FormatterAssemblyStyle.Full, true)] public void MissingField_FailsWithAppropriateStyle(FormatterAssemblyStyle style, bool exceptionExpected) { var f = new BinaryFormatter(); var s = new MemoryStream(); f.Serialize(s, new Version1ClassWithoutField()); s.Position = 0; f = new BinaryFormatter() { AssemblyFormat = style }; f.Binder = new DelegateBinder { BindToTypeDelegate = (_, __) => typeof(Version2ClassWithoutOptionalField) }; if (exceptionExpected) { Assert.Throws<SerializationException>(() => f.Deserialize(s)); } else { var result = (Version2ClassWithoutOptionalField)f.Deserialize(s); Assert.NotNull(result); Assert.Equal(null, result.Value); } } [Theory] [InlineData(FormatterAssemblyStyle.Simple)] [InlineData(FormatterAssemblyStyle.Full)] public void OptionalField_Missing_Success(FormatterAssemblyStyle style) { var f = new BinaryFormatter(); var s = new MemoryStream(); f.Serialize(s, new Version1ClassWithoutField()); s.Position = 0; f = new BinaryFormatter() { AssemblyFormat = style }; f.Binder = new DelegateBinder { BindToTypeDelegate = (_, __) => typeof(Version2ClassWithOptionalField) }; var result = (Version2ClassWithOptionalField)f.Deserialize(s); Assert.NotNull(result); Assert.Equal(null, result.Value); } [Fact] public void ObjectReference_RealObjectSerialized() { var obj = new ObjRefReturnsObj { Real = 42 }; object real = BinaryFormatterHelpers.Clone<object>(obj); Assert.Equal(42, real); } // Test is disabled becaues it can cause improbable memory allocations leading to interminable paging. // We're keeping the code because it could be useful to a dev making local changes to binary formatter code. //[OuterLoop] //[Theory] //[MemberData(nameof(FuzzInputs_MemberData))] public void Deserialize_FuzzInput(object obj, Random rand) { // Get the serialized data for the object byte[] data = BinaryFormatterHelpers.ToByteArray(obj, FormatterAssemblyStyle.Simple); // Make some "random" changes to it for (int i = 1; i < rand.Next(1, 100); i++) { data[rand.Next(data.Length)] = (byte)rand.Next(256); } // Try to deserialize that. try { BinaryFormatterHelpers.FromByteArray(data, FormatterAssemblyStyle.Simple); // Since there's no checksum, it's possible we changed data that didn't corrupt the instance } catch (ArgumentOutOfRangeException) { } catch (ArrayTypeMismatchException) { } catch (DecoderFallbackException) { } catch (FormatException) { } catch (IndexOutOfRangeException) { } catch (InvalidCastException) { } catch (OutOfMemoryException) { } catch (OverflowException) { } catch (NullReferenceException) { } catch (SerializationException) { } catch (TargetInvocationException) { } catch (ArgumentException) { } catch (FileLoadException) { } } [Fact] public void Deserialize_EndOfStream_ThrowsException() { var f = new BinaryFormatter(); var s = new MemoryStream(); f.Serialize(s, 1024); for (long i = s.Length - 1; i >= 0; i--) { s.Position = 0; byte[] data = new byte[i]; Assert.Equal(data.Length, s.Read(data, 0, data.Length)); Assert.Throws<SerializationException>(() => f.Deserialize(new MemoryStream(data))); } } [Theory] [MemberData(nameof(CrossProcessObjects_MemberData))] public void Roundtrip_CrossProcess(object obj) { string outputPath = GetTestFilePath(); string inputPath = GetTestFilePath(); // Serialize out to a file using (FileStream fs = File.OpenWrite(outputPath)) { new BinaryFormatter().Serialize(fs, obj); } // In another process, deserialize from that file and serialize to another RemoteInvoke((remoteInput, remoteOutput) => { Assert.False(File.Exists(remoteOutput)); using (FileStream input = File.OpenRead(remoteInput)) using (FileStream output = File.OpenWrite(remoteOutput)) { var b = new BinaryFormatter(); b.Serialize(output, b.Deserialize(input)); return SuccessExitCode; } }, outputPath, inputPath).Dispose(); // Deserialize what the other process serialized and compare it to the original using (FileStream fs = File.OpenRead(inputPath)) { object deserialized = new BinaryFormatter().Deserialize(fs); Assert.Equal(obj, deserialized); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Framework fails when serializing arrays with non-zero lower bounds")] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "UAPAOT does not support non-zero lower bounds")] public void Roundtrip_ArrayContainingArrayAtNonZeroLowerBound() { BinaryFormatterHelpers.Clone(Array.CreateInstance(typeof(uint[]), new[] { 5 }, new[] { 1 })); } private static void ValidateEqualityComparer(object obj) { Type objType = obj.GetType(); Assert.True(objType.IsGenericType, $"Type `{objType.FullName}` must be generic."); Assert.Equal("System.Collections.Generic.ObjectEqualityComparer`1", objType.GetGenericTypeDefinition().FullName); Assert.Equal(obj.GetType().GetGenericArguments()[0], objType.GetGenericArguments()[0]); } private static void SanityCheckBlob(object obj, string[] blobs) { // These types are unstable during serialization and produce different blobs. if (obj is WeakReference<Point> || obj is Collections.Specialized.HybridDictionary || obj is TimeZoneInfo.AdjustmentRule) { return; } // In most cases exceptions in Core have a different layout than in Desktop, // therefore we are skipping the string comparison of the blobs. if (obj is Exception) { return; } // Check if runtime generated blob is the same as the stored one int frameworkBlobNumber = PlatformDetection.IsFullFramework ? 1 : 0; if (frameworkBlobNumber < blobs.Length) { string runtimeBlob = BinaryFormatterHelpers.ToBase64String(obj, FormatterAssemblyStyle.Full); string storedComparableBlob = CreateComparableBlobInfo(blobs[frameworkBlobNumber]); string runtimeComparableBlob = CreateComparableBlobInfo(runtimeBlob); Assert.True(storedComparableBlob == runtimeComparableBlob, $"The stored blob for type {obj.GetType().FullName} is outdated and needs to be updated.{Environment.NewLine}{Environment.NewLine}" + $"-------------------- Stored blob ---------------------{Environment.NewLine}" + $"Encoded: {blobs[frameworkBlobNumber]}{Environment.NewLine}" + $"Decoded: {storedComparableBlob}{Environment.NewLine}{Environment.NewLine}" + $"--------------- Runtime generated blob ---------------{Environment.NewLine}" + $"Encoded: {runtimeBlob}{Environment.NewLine}" + $"Decoded: {runtimeComparableBlob}"); } } private static string GetTestDataFilePath() { string GetRepoRootPath() { var exeFile = new FileInfo(Assembly.GetExecutingAssembly().Location); DirectoryInfo root = exeFile.Directory; while (!Directory.Exists(Path.Combine(root.FullName, ".git"))) { if (root.Parent == null) return null; root = root.Parent; } return root.FullName; } // Get path to binary formatter test data string repositoryRootPath = GetRepoRootPath(); Assert.NotNull(repositoryRootPath); string testDataFilePath = Path.Combine(repositoryRootPath, "src", "System.Runtime.Serialization.Formatters", "tests", "BinaryFormatterTestData.cs"); Assert.True(File.Exists(testDataFilePath)); return testDataFilePath; } private static string CreateComparableBlobInfo(string base64Blob) { string lineSeparator = ((char)0x2028).ToString(); string paragraphSeparator = ((char)0x2029).ToString(); byte[] data = Convert.FromBase64String(base64Blob); base64Blob = Encoding.UTF8.GetString(data); return Regex.Replace(base64Blob, @"Version=\d.\d.\d.\d.", "Version=0.0.0.0", RegexOptions.Multiline) .Replace("\r\n", string.Empty) .Replace("\n", string.Empty) .Replace("\r", string.Empty) .Replace(lineSeparator, string.Empty) .Replace(paragraphSeparator, string.Empty); } private static (int blobs, int foundBlobs, int updatedBlobs) UpdateCoreTypeBlobs(string testDataFilePath, string[] blobs) { // Replace existing test data blobs with updated ones string[] testDataLines = File.ReadAllLines(testDataFilePath); List<string> updatedTestDataLines = new List<string>(); int numberOfBlobs = 0; int numberOfFoundBlobs = 0; int numberOfUpdatedBlobs = 0; for (int i = 0; i < testDataLines.Length; i++) { string testDataLine = testDataLines[i]; if (!testDataLine.Trim().StartsWith("yield") || numberOfBlobs >= blobs.Length) { updatedTestDataLines.Add(testDataLine); continue; } string pattern = null; string replacement = null; if (PlatformDetection.IsFullFramework) { pattern = ", \"AAEAAAD[^\"]+\"(?!,)"; replacement = ", \"" + blobs[numberOfBlobs] + "\""; } else { pattern = "\"AAEAAAD[^\"]+\","; replacement = "\"" + blobs[numberOfBlobs] + "\","; } Regex regex = new Regex(pattern); Match match = regex.Match(testDataLine); if (match.Success) { numberOfFoundBlobs++; } string updatedLine = regex.Replace(testDataLine, replacement); if (testDataLine != updatedLine) { numberOfUpdatedBlobs++; } testDataLine = updatedLine; updatedTestDataLines.Add(testDataLine); numberOfBlobs++; } // Check if all blobs were recognized and write updates to file Assert.Equal(numberOfBlobs, blobs.Length); File.WriteAllLines(testDataFilePath, updatedTestDataLines); return (numberOfBlobs, numberOfFoundBlobs, numberOfUpdatedBlobs); } private class DelegateBinder : SerializationBinder { public Func<string, string, Type> BindToTypeDelegate = null; public override Type BindToType(string assemblyName, string typeName) => BindToTypeDelegate?.Invoke(assemblyName, typeName); } } }
#region File Description //----------------------------------------------------------------------------- // BeeKeeper.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System.Collections.Generic; #endregion namespace HoneycombRush { /// <summary> /// Represents the beekeeper, the player's avatar. /// </summary> public class BeeKeeper : TexturedDrawableGameComponent { #region Enums /// <summary> /// Represents the direction in which the beekeeper is walking. /// </summary> enum WalkingDirection { Down = 0, Up = 8, Left = 16, Right = 24, LeftDown = 32, RightDown = 40, LeftUp = 48, RightUp = 56 } #endregion #region Fields/Properties // Animation name constants const string LegAnimationKey = "LegAnimation"; const string BodyAnimationKey = "BodyAnimation"; const string SmokeAnimationKey = "SmokeAnimation"; const string ShootingAnimationKey = "ShootingAnimation"; const string BeekeeperCollectingHoneyAnimationKey = "BeekeeperCollectiongHoney"; const string BeekeeperDesposingHoneyAnimationKey = "BeekeeperDesposingHoney"; Vector2 bodySize = new Vector2(85, 132); Vector2 velocity; Vector2 smokeAdjustment; SpriteEffects lastEffect; SpriteEffects currentEffect; // Beekeeper state variables bool needToShootSmoke; bool isStung; bool isFlashing; bool isDrawnLastStungInterval; bool isDepositingHoney; TimeSpan stungTime; TimeSpan stungDuration; TimeSpan flashingDuration; TimeSpan depositHoneyUpdatingInterval = TimeSpan.FromMilliseconds(200); TimeSpan depositHoneyUpdatingTimer = TimeSpan.Zero; TimeSpan shootSmokePuffTimer = TimeSpan.Zero; readonly TimeSpan shootSmokePuffTimerInitialValue = TimeSpan.FromMilliseconds(325); Texture2D smokeAnimationTexture; Texture2D smokePuffTexture; const int MaxSmokePuffs = 20; /// <summary> /// Contains all smoke puffs which are currently active /// </summary> public Queue<SmokePuff> FiredSmokePuffs { get; private set; } /// <summary> /// Serves as a pool of available smoke puff objects. /// </summary> Stack<SmokePuff> availableSmokePuffs; int stungDrawingInterval = 5; int stungDrawingCounter = 0; int honeyDepositFrameCount; int depositHoneyTimerCounter = -1; int collectiongHoneyFrameCounter; AsyncCallback depositHoneyCallback; WalkingDirection direction = WalkingDirection.Up; int lastFrameCounter; public bool IsStung { get { return isStung; } } public bool IsFlashing { get { return isFlashing; } } /// <summary> /// Mark the beekeeper as shooting or not shooting smoke. /// </summary> public bool IsShootingSmoke { set { if (!isStung) { needToShootSmoke = value; if (value) { // Placeholder } else { shootSmokePuffTimer = TimeSpan.Zero; } } } } public override Rectangle Bounds { get { int height = (int)bodySize.Y / 10 * 8; int width = (int)bodySize.X / 10 * 5; int offsetY = ((int)bodySize.Y - height) / 2; int offsetX = ((int)bodySize.X - width) / 2; return new Rectangle((int)position.X + offsetX, (int)position.Y + offsetY, width, height); } } public override Rectangle CentralCollisionArea { get { Rectangle bounds = Bounds; int height = (int)Bounds.Height / 10 * 5; int width = (int)Bounds.Width / 10 * 8; int offsetY = ((int)Bounds.Height - height) / 2; int offsetX = ((int)Bounds.Width - width) / 2; return new Rectangle((int)Bounds.X + offsetX, (int)Bounds.Y + offsetY, width, height); } } public bool IsDepostingHoney { get { return isDepositingHoney; } } public bool IsCollectingHoney { get; set; } public Vector2 Position { get { return position; } } public Rectangle ThumbStickArea { get; set; } public bool IsInMotion { get; set; } #endregion #region Initialization /// <summary> /// Creates a new beekeeper instance. /// </summary> /// <param name="game">The game object.</param> /// <param name="gamePlayScreen">The gameplay screen.</param> public BeeKeeper(Game game, GameplayScreen gamePlayScreen) : base(game, gamePlayScreen) { } /// <summary> /// Initialize the beekepper. /// </summary> public override void Initialize() { // Initialize the animation AnimationDefinitions[LegAnimationKey].PlayFromFrameIndex(0); AnimationDefinitions[BodyAnimationKey].PlayFromFrameIndex(0); AnimationDefinitions[SmokeAnimationKey].PlayFromFrameIndex(0); AnimationDefinitions[ShootingAnimationKey].PlayFromFrameIndex(0); AnimationDefinitions[BeekeeperCollectingHoneyAnimationKey].PlayFromFrameIndex(0); AnimationDefinitions[BeekeeperDesposingHoneyAnimationKey].PlayFromFrameIndex(0); isStung = false; stungDuration = TimeSpan.FromSeconds(1); flashingDuration = TimeSpan.FromSeconds(2); availableSmokePuffs = new Stack<SmokePuff>(MaxSmokePuffs); FiredSmokePuffs = new Queue<SmokePuff>(MaxSmokePuffs); base.Initialize(); } /// <summary> /// Loads content that will be used later on by the beekeeper. /// </summary> protected override void LoadContent() { smokeAnimationTexture = Game.Content.Load<Texture2D>("Textures/SmokeAnimationStrip"); smokePuffTexture = Game.Content.Load<Texture2D>("Textures/SmokePuff"); position = new Vector2(Game.GraphicsDevice.Viewport.Width / 2 - (int)bodySize.X / 2, Game.GraphicsDevice.Viewport.Height / 2 - (int)bodySize.Y / 2); // Create smoke puffs for the smoke puff pool for (int i = 0; i < MaxSmokePuffs; i++) { availableSmokePuffs.Push(new SmokePuff(Game, gamePlayScreen, smokePuffTexture)); } base.LoadContent(); } #endregion #region Update /// <summary> /// Updates the beekeeper's status. /// </summary> /// <param name="gameTime">Game time information</param> public override void Update(GameTime gameTime) { if (!(gamePlayScreen.IsActive)) { base.Update(gameTime); return; } if (IsCollectingHoney) { // We want this animation to use a sub animation // So must calculate when to call the sub animation if (collectiongHoneyFrameCounter > 3) { AnimationDefinitions[BeekeeperCollectingHoneyAnimationKey].Update(gameTime, true, true); } else { AnimationDefinitions[BeekeeperCollectingHoneyAnimationKey].Update(gameTime, true, false); } collectiongHoneyFrameCounter++; } else { collectiongHoneyFrameCounter = 0; } if (isDepositingHoney) { if (depositHoneyUpdatingTimer == TimeSpan.Zero) { depositHoneyUpdatingTimer = gameTime.TotalGameTime; } AnimationDefinitions[BeekeeperDesposingHoneyAnimationKey].Update(gameTime, true); } // The oldest smoke puff might have expired and should therefore be recycled if ((FiredSmokePuffs.Count > 0) && (FiredSmokePuffs.Peek().IsGone)) { availableSmokePuffs.Push(FiredSmokePuffs.Dequeue()); } // If the beeKeeper is stung by a bee we want to create a flashing // effect. if (isStung || isFlashing) { stungDrawingCounter++; if (stungDrawingCounter > stungDrawingInterval) { stungDrawingCounter = 0; isDrawnLastStungInterval = !isDrawnLastStungInterval; } // if time is up, end the flashing effect if (stungTime + stungDuration < gameTime.TotalGameTime) { isStung = false; if (stungTime + stungDuration + flashingDuration < gameTime.TotalGameTime) { isFlashing = false; stungDrawingCounter = -1; } AnimationDefinitions[LegAnimationKey].Update(gameTime, IsInMotion); } } else { AnimationDefinitions[LegAnimationKey].Update(gameTime, IsInMotion); } if (needToShootSmoke) { AnimationDefinitions[SmokeAnimationKey].Update(gameTime, needToShootSmoke); shootSmokePuffTimer -= gameTime.ElapsedGameTime; if (shootSmokePuffTimer <= TimeSpan.Zero) { ShootSmoke(); shootSmokePuffTimer = shootSmokePuffTimerInitialValue; } } base.Update(gameTime); } #endregion #region Render /// <summary> /// Renders the beekeeper. /// </summary> /// <param name="gameTime"></param> public override void Draw(GameTime gameTime) { if (!(gamePlayScreen.IsActive)) { base.Draw(gameTime); return; } // Make sure not to draw the beekeeper while flashing if (isStung || isFlashing) { if (stungDrawingCounter != stungDrawingInterval) { if (isDrawnLastStungInterval) { return; } } } spriteBatch.Begin(); // if stung we want to show another animation if (isStung) { spriteBatch.Draw(Game.Content.Load<Texture2D>("Textures/hit"), position, Color.White); spriteBatch.End(); return; } // If collecting honey, draw the appropriate animation if (IsCollectingHoney) { AnimationDefinitions[BeekeeperCollectingHoneyAnimationKey].Draw(spriteBatch, position, SpriteEffects.None); spriteBatch.End(); return; } if (isDepositingHoney) { if (VirtualThumbsticks.LeftThumbstick != Vector2.Zero) { isDepositingHoney = false; AudioManager.StopSound("DepositingIntoVat_Loop"); } // We want the deposit duration to sync with the deposit // animation // So we manage the timing ourselves if (depositHoneyUpdatingTimer != TimeSpan.Zero && depositHoneyUpdatingTimer + depositHoneyUpdatingInterval < gameTime.TotalGameTime) { depositHoneyTimerCounter++; depositHoneyUpdatingTimer = TimeSpan.Zero; } AnimationDefinitions[BeekeeperDesposingHoneyAnimationKey].Draw(spriteBatch, position, SpriteEffects.None); if (depositHoneyTimerCounter == honeyDepositFrameCount - 1) { isDepositingHoney = false; depositHoneyCallback.Invoke(null); AnimationDefinitions[BeekeeperDesposingHoneyAnimationKey].PlayFromFrameIndex(0); } spriteBatch.End(); return; } bool hadDirectionChanged = false; WalkingDirection tempDirection = direction; DetermineDirection(ref tempDirection, ref smokeAdjustment); // Indicate the direction has changed if (tempDirection != direction) { hadDirectionChanged = true; direction = tempDirection; } if (hadDirectionChanged) { // Update the animation lastFrameCounter = 0; AnimationDefinitions[LegAnimationKey].PlayFromFrameIndex(lastFrameCounter + (int)direction); AnimationDefinitions[ShootingAnimationKey].PlayFromFrameIndex(lastFrameCounter + (int)direction); AnimationDefinitions[BodyAnimationKey].PlayFromFrameIndex(lastFrameCounter + (int)direction); } else { // Because our animation is 8 cells, but the row is 16 cells, // we need to reset the counter after 8 rounds if (lastFrameCounter == 8) { lastFrameCounter = 0; AnimationDefinitions[LegAnimationKey].PlayFromFrameIndex(lastFrameCounter + (int)direction); AnimationDefinitions[ShootingAnimationKey].PlayFromFrameIndex( lastFrameCounter + (int)direction); AnimationDefinitions[BodyAnimationKey].PlayFromFrameIndex(lastFrameCounter + (int)direction); } else { lastFrameCounter++; } } AnimationDefinitions[LegAnimationKey].Draw(spriteBatch, position, 1f, SpriteEffects.None); if (needToShootSmoke) { // Draw the body AnimationDefinitions[ShootingAnimationKey].Draw(spriteBatch, position, 1f, SpriteEffects.None); // If true we need to draw smoke if (smokeAdjustment != Vector2.Zero) { AnimationDefinitions[SmokeAnimationKey].Draw(spriteBatch, position + smokeAdjustment, 1f, GetSpriteEffect(VirtualThumbsticks.LeftThumbstick)); } } else { AnimationDefinitions[BodyAnimationKey].Draw(spriteBatch, position, 1f, SpriteEffects.None); } spriteBatch.End(); base.Draw(gameTime); } #endregion #region Public Methods /// <summary> /// Checks if a given rectanlge intersects with one of the smoke puffs fired by the beekeeper. /// </summary> /// <param name="checkRectangle">The rectangle to check for collisions with smoke puffs.</param> /// <returns>One of the smoke puffs with which the supplied regtangle collides, or null if it collides with /// none.</returns> public SmokePuff CheckSmokeCollision(Rectangle checkRectangle) { foreach (SmokePuff smokePuff in FiredSmokePuffs) { if (checkRectangle.HasCollision(smokePuff.CentralCollisionArea)) { return smokePuff; } } return null; } /// <summary> /// Maek the beekeeper as being stung by a bee. /// </summary> /// <param name="occurTime">The time at which the beekeeper was stung.</param> public void Stung(TimeSpan occurTime) { if (!isStung && !isFlashing) { isStung = true; isFlashing = true; stungTime = occurTime; needToShootSmoke = false; } } /// <summary> /// Updates the beekeeper's position. /// </summary> /// <param name="movement">A vector which contains the desired adjustment to /// the beekeeper's position.</param> public void SetMovement(Vector2 movement) { if (!IsStung) { velocity = movement; position += velocity; } } /// <summary> /// Makes sure the beekeeper's direction matches his movement direction. /// </summary> /// <param name="movementDirection">A vector indicating the beekeeper's movement /// direction.</param> public void SetDirection(Vector2 movementDirection) { currentEffect = GetSpriteEffect(movementDirection); } /// <summary> /// Starts the process of transferring honey to the honey vat. /// </summary> /// <param name="honeyDepositFrameCount">The amount of frames in the honey /// depositing animation.</param> /// <param name="callback">Callback to invoke once the process is /// complete.</param> public void StartTransferHoney(int honeyDepositFrameCount, AsyncCallback callback) { depositHoneyCallback = callback; this.honeyDepositFrameCount = honeyDepositFrameCount; isDepositingHoney = true; depositHoneyTimerCounter = 0; } /// <summary> /// Marks the honey transfer process as complete. /// </summary> public void EndTransferHoney() { isDepositingHoney = false; } #endregion #region Private Method /// <summary> /// Shoots a puff of smoke. If too many puffs of smoke have already been fired, the oldest one vanishes and /// is replaced with a new one. /// </summary> private void ShootSmoke() { SmokePuff availableSmokePuff; if (availableSmokePuffs.Count > 0) { // Take a smoke puff from the pool availableSmokePuff = availableSmokePuffs.Pop(); } else { // Take the oldest smoke puff and use it availableSmokePuff = FiredSmokePuffs.Dequeue(); } Vector2 beeKeeperCenter = Bounds.Center.GetVector(); Vector2 smokeInitialPosition = beeKeeperCenter; availableSmokePuff.Fire(smokeInitialPosition, GetSmokeVelocityVector()); FiredSmokePuffs.Enqueue(availableSmokePuff); } /// <summary> /// Used to return a vector which will serve as shot smoke velocity. /// </summary> /// <returns>A vector which serves as the initial velocity of smoke puffs being shot.</returns> private Vector2 GetSmokeVelocityVector() { Vector2 initialVector; switch (direction) { case WalkingDirection.Down: initialVector = new Vector2(0, 1); break; case WalkingDirection.Up: initialVector = new Vector2(0, -1); break; case WalkingDirection.Left: initialVector = new Vector2(-1, 0); break; case WalkingDirection.Right: initialVector = new Vector2(1, 0); break; case WalkingDirection.LeftDown: initialVector = new Vector2(-1, 1); break; case WalkingDirection.RightDown: initialVector = new Vector2(1, 1); break; case WalkingDirection.LeftUp: initialVector = new Vector2(-1, -1); break; case WalkingDirection.RightUp: initialVector = new Vector2(1, -1); break; default: throw new InvalidOperationException("Determining the vector for an invalid walking direction"); } return initialVector * 2f + velocity * 1f; } /// <summary> /// Returns an effect appropriate to the supplied vector which either does /// nothing or flips the beekeeper horizontally. /// </summary> /// <param name="movementDirection">A vector depicting the beekeeper's /// movement.</param> /// <returns>A sprite effect that should be applied to the beekeeper.</returns> private SpriteEffects GetSpriteEffect(Vector2 movementDirection) { // Checks if the user input is in the thumb stick area if (VirtualThumbsticks.LeftThumbstickCenter.HasValue && ThumbStickArea.Contains((int)VirtualThumbsticks.LeftThumbstickCenter.Value.X, (int)VirtualThumbsticks.LeftThumbstickCenter.Value.Y)) { // If beekeeper is facing left if (movementDirection.X < 0) { lastEffect = SpriteEffects.FlipHorizontally; } else if (movementDirection.X > 0) { lastEffect = SpriteEffects.None; } } return lastEffect; } /// <summary> /// Returns movement information according to the current virtual thumbstick input. /// </summary> /// <param name="tempDirection">Enum describing the inpot direction.</param> /// <param name="smokeAjustment">Adjustment to smoke position according to input direction.</param> private void DetermineDirection(ref WalkingDirection tempDirection, ref Vector2 smokeAjustment) { if (!VirtualThumbsticks.LeftThumbstickCenter.HasValue) { return; } Rectangle touchPointRectangle = new Rectangle((int)VirtualThumbsticks.LeftThumbstickCenter.Value.X, (int)VirtualThumbsticks.LeftThumbstickCenter.Value.Y, 1, 1); if (ThumbStickArea.Intersects(touchPointRectangle)) { if (Math.Abs(VirtualThumbsticks.LeftThumbstick.X) > Math.Abs(VirtualThumbsticks.LeftThumbstick.Y)) { DetermineDirectionDominantX(ref tempDirection, ref smokeAjustment); } else { DetermineDirectionDominantY(ref tempDirection, ref smokeAjustment); } } } /// <summary> /// Returns movement information according to the current virtual thumbstick input, given that advancement /// along the X axis is greater than along the Y axis. /// </summary> /// <param name="tempDirection">Enum describing the input direction.</param> /// <param name="smokeAjustment">Adjustment to smoke position according to input direction.</param> private void DetermineDirectionDominantX(ref WalkingDirection tempDirection, ref Vector2 smokeAjustment) { if (VirtualThumbsticks.LeftThumbstick.X > 0) { if (VirtualThumbsticks.LeftThumbstick.Y > 0.25f) { tempDirection = WalkingDirection.RightDown; smokeAjustment = new Vector2(85, 30); } else if (VirtualThumbsticks.LeftThumbstick.Y < -0.25f) { tempDirection = WalkingDirection.RightUp; smokeAjustment = new Vector2(85, 0); } else { tempDirection = WalkingDirection.Right; smokeAjustment = new Vector2(85, 15); } } else { if (VirtualThumbsticks.LeftThumbstick.Y > 0.25f) { tempDirection = WalkingDirection.LeftDown; smokeAjustment = new Vector2(-85, 30); } else if (VirtualThumbsticks.LeftThumbstick.Y < -0.25f) { tempDirection = WalkingDirection.LeftUp; smokeAjustment = new Vector2(-85, 0); } else { tempDirection = WalkingDirection.Left; smokeAjustment = new Vector2(-85, 15); } } } /// <summary> /// Returns movement information according to the current virtual thumbstick input, given that advancement /// along the Y axis is greater than along the X axis. /// </summary> /// <param name="tempDirection">Enum describing the input direction.</param> /// <param name="smokeAjustment">Adjustment to smoke position according to input direction.</param> private void DetermineDirectionDominantY(ref WalkingDirection tempDirection, ref Vector2 smokeAjustment) { if (VirtualThumbsticks.LeftThumbstick.Y > 0) { if (VirtualThumbsticks.LeftThumbstick.X > 0.25f) { tempDirection = WalkingDirection.RightDown; smokeAjustment = new Vector2(85, 0); } else if (VirtualThumbsticks.LeftThumbstick.X < -0.25f) { tempDirection = WalkingDirection.LeftDown; smokeAjustment = new Vector2(-85, 0); } else { tempDirection = WalkingDirection.Down; smokeAjustment = Vector2.Zero; } } else { if (VirtualThumbsticks.LeftThumbstick.X > 0.25f) { tempDirection = WalkingDirection.RightUp; smokeAjustment = new Vector2(85, 30); } else if (VirtualThumbsticks.LeftThumbstick.X < -0.25f) { tempDirection = WalkingDirection.LeftUp; smokeAjustment = new Vector2(-85, 30); } else { tempDirection = WalkingDirection.Up; smokeAjustment = Vector2.Zero; } } } #endregion } }
// 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; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.Formatters; using Microsoft.Extensions.Primitives; namespace Microsoft.AspNetCore.Mvc.ModelBinding { /// <summary> /// Represents the state of an attempt to bind values from an HTTP Request to an action method, which includes /// validation information. /// </summary> public class ModelStateDictionary : IReadOnlyDictionary<string, ModelStateEntry?> { // Make sure to update the doc headers if this value is changed. /// <summary> /// The default value for <see cref="MaxAllowedErrors"/> of <c>200</c>. /// </summary> public static readonly int DefaultMaxAllowedErrors = 200; private const char DelimiterDot = '.'; private const char DelimiterOpen = '['; private readonly ModelStateNode _root; private int _maxAllowedErrors; /// <summary> /// Initializes a new instance of the <see cref="ModelStateDictionary"/> class. /// </summary> public ModelStateDictionary() : this(DefaultMaxAllowedErrors) { } /// <summary> /// Initializes a new instance of the <see cref="ModelStateDictionary"/> class. /// </summary> public ModelStateDictionary(int maxAllowedErrors) { MaxAllowedErrors = maxAllowedErrors; var emptySegment = new StringSegment(buffer: string.Empty); _root = new ModelStateNode(subKey: emptySegment) { Key = string.Empty }; } /// <summary> /// Initializes a new instance of the <see cref="ModelStateDictionary"/> class by using values that are copied /// from the specified <paramref name="dictionary"/>. /// </summary> /// <param name="dictionary">The <see cref="ModelStateDictionary"/> to copy values from.</param> public ModelStateDictionary(ModelStateDictionary dictionary) : this(dictionary?.MaxAllowedErrors ?? DefaultMaxAllowedErrors) { if (dictionary == null) { throw new ArgumentNullException(nameof(dictionary)); } Merge(dictionary); } /// <summary> /// Root entry for the <see cref="ModelStateDictionary"/>. /// </summary> public ModelStateEntry Root => _root; /// <summary> /// Gets or sets the maximum allowed model state errors in this instance of <see cref="ModelStateDictionary"/>. /// Defaults to <c>200</c>. /// </summary> /// <remarks> /// <para> /// <see cref="ModelStateDictionary"/> tracks the number of model errors added by calls to /// <see cref="AddModelError(string, Exception, ModelMetadata)"/> or /// <see cref="TryAddModelError(string, Exception, ModelMetadata)"/>. /// Once the value of <c>MaxAllowedErrors - 1</c> is reached, if another attempt is made to add an error, /// the error message will be ignored and a <see cref="TooManyModelErrorsException"/> will be added. /// </para> /// <para> /// Errors added via modifying <see cref="ModelStateEntry"/> directly do not count towards this limit. /// </para> /// </remarks> public int MaxAllowedErrors { get { return _maxAllowedErrors; } set { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value)); } _maxAllowedErrors = value; } } /// <summary> /// Gets a value indicating whether or not the maximum number of errors have been /// recorded. /// </summary> /// <remarks> /// Returns <c>true</c> if a <see cref="TooManyModelErrorsException"/> has been recorded; /// otherwise <c>false</c>. /// </remarks> public bool HasReachedMaxErrors => ErrorCount >= MaxAllowedErrors; /// <summary> /// Gets the number of errors added to this instance of <see cref="ModelStateDictionary"/> via /// <see cref="M:AddModelError"/> or <see cref="M:TryAddModelError"/>. /// </summary> public int ErrorCount { get; private set; } /// <inheritdoc /> public int Count { get; private set; } /// <summary> /// Gets the key sequence. /// </summary> public KeyEnumerable Keys => new KeyEnumerable(this); /// <inheritdoc /> IEnumerable<string> IReadOnlyDictionary<string, ModelStateEntry?>.Keys => Keys; /// <summary> /// Gets the value sequence. /// </summary> public ValueEnumerable Values => new ValueEnumerable(this); /// <inheritdoc /> IEnumerable<ModelStateEntry> IReadOnlyDictionary<string, ModelStateEntry?>.Values => Values; /// <summary> /// Gets a value that indicates whether any model state values in this model state dictionary is invalid or not validated. /// </summary> public bool IsValid { get { var state = ValidationState; return state == ModelValidationState.Valid || state == ModelValidationState.Skipped; } } /// <inheritdoc /> public ModelValidationState ValidationState => GetValidity(_root) ?? ModelValidationState.Valid; /// <inheritdoc /> public ModelStateEntry? this[string key] { get { if (key == null) { throw new ArgumentNullException(nameof(key)); } TryGetValue(key, out var entry); return entry; } } // Flag that indicates if TooManyModelErrorException has already been added to this dictionary. private bool HasRecordedMaxModelError { get; set; } /// <summary> /// Adds the specified <paramref name="exception"/> to the <see cref="ModelStateEntry.Errors"/> instance /// that is associated with the specified <paramref name="key"/>. If the maximum number of allowed /// errors has already been recorded, ensures that a <see cref="TooManyModelErrorsException"/> exception is /// recorded instead. /// </summary> /// <remarks> /// This method allows adding the <paramref name="exception"/> to the current <see cref="ModelStateDictionary"/> /// when <see cref="ModelMetadata"/> is not available or the exact <paramref name="exception"/> /// must be maintained for later use (even if it is for example a <see cref="FormatException"/>). /// Where <see cref="ModelMetadata"/> is available, use <see cref="AddModelError(string, Exception, ModelMetadata)"/> instead. /// </remarks> /// <param name="key">The key of the <see cref="ModelStateEntry"/> to add errors to.</param> /// <param name="exception">The <see cref="Exception"/> to add.</param> /// <returns> /// <c>True</c> if the given error was added, <c>false</c> if the error was ignored. /// See <see cref="MaxAllowedErrors"/>. /// </returns> public bool TryAddModelException(string key, Exception exception) { if (key == null) { throw new ArgumentNullException(nameof(key)); } if (exception == null) { throw new ArgumentNullException(nameof(exception)); } if ((exception is InputFormatterException || exception is ValueProviderException) && !string.IsNullOrEmpty(exception.Message)) { // InputFormatterException, ValueProviderException is a signal that the message is safe to expose to clients return TryAddModelError(key, exception.Message); } if (ErrorCount >= MaxAllowedErrors - 1) { EnsureMaxErrorsReachedRecorded(); return false; } ErrorCount++; AddModelErrorCore(key, exception); return true; } /// <summary> /// Adds the specified <paramref name="exception"/> to the <see cref="ModelStateEntry.Errors"/> instance /// that is associated with the specified <paramref name="key"/>. If the maximum number of allowed /// errors has already been recorded, ensures that a <see cref="TooManyModelErrorsException"/> exception is /// recorded instead. /// </summary> /// <param name="key">The key of the <see cref="ModelStateEntry"/> to add errors to.</param> /// <param name="exception">The <see cref="Exception"/> to add. Some exception types will be replaced with /// a descriptive error message.</param> /// <param name="metadata">The <see cref="ModelMetadata"/> associated with the model.</param> public void AddModelError(string key, Exception exception, ModelMetadata metadata) { if (key == null) { throw new ArgumentNullException(nameof(key)); } if (exception == null) { throw new ArgumentNullException(nameof(exception)); } if (metadata == null) { throw new ArgumentNullException(nameof(metadata)); } TryAddModelError(key, exception, metadata); } /// <summary> /// Attempts to add the specified <paramref name="exception"/> to the <see cref="ModelStateEntry.Errors"/> /// instance that is associated with the specified <paramref name="key"/>. If the maximum number of allowed /// errors has already been recorded, ensures that a <see cref="TooManyModelErrorsException"/> exception is /// recorded instead. /// </summary> /// <param name="key">The key of the <see cref="ModelStateEntry"/> to add errors to.</param> /// <param name="exception">The <see cref="Exception"/> to add. Some exception types will be replaced with /// a descriptive error message.</param> /// <param name="metadata">The <see cref="ModelMetadata"/> associated with the model.</param> /// <returns> /// <c>True</c> if the given error was added, <c>false</c> if the error was ignored. /// See <see cref="MaxAllowedErrors"/>. /// </returns> public bool TryAddModelError(string key, Exception exception, ModelMetadata metadata) { if (key == null) { throw new ArgumentNullException(nameof(key)); } if (exception == null) { throw new ArgumentNullException(nameof(exception)); } if (metadata == null) { throw new ArgumentNullException(nameof(metadata)); } if (ErrorCount >= MaxAllowedErrors - 1) { EnsureMaxErrorsReachedRecorded(); return false; } if (exception is FormatException || exception is OverflowException) { // Convert FormatExceptions and OverflowExceptions to Invalid value messages. TryGetValue(key, out var entry); // Not using metadata.GetDisplayName() or a single resource to avoid strange messages like // "The value '' is not valid." (when no value was provided, not even an empty string) and // "The supplied value is invalid for Int32." (when error is for an element or parameter). var messageProvider = metadata.ModelBindingMessageProvider; var name = metadata.DisplayName ?? metadata.PropertyName; string errorMessage; if (entry == null && name == null) { errorMessage = messageProvider.NonPropertyUnknownValueIsInvalidAccessor(); } else if (entry == null) { errorMessage = messageProvider.UnknownValueIsInvalidAccessor(name!); } else if (name == null) { errorMessage = messageProvider.NonPropertyAttemptedValueIsInvalidAccessor(entry.AttemptedValue!); } else { errorMessage = messageProvider.AttemptedValueIsInvalidAccessor(entry.AttemptedValue!, name); } return TryAddModelError(key, errorMessage); } else if ((exception is InputFormatterException || exception is ValueProviderException) && !string.IsNullOrEmpty(exception.Message)) { // InputFormatterException, ValueProviderException is a signal that the message is safe to expose to clients return TryAddModelError(key, exception.Message); } ErrorCount++; AddModelErrorCore(key, exception); return true; } /// <summary> /// Adds the specified <paramref name="errorMessage"/> to the <see cref="ModelStateEntry.Errors"/> instance /// that is associated with the specified <paramref name="key"/>. If the maximum number of allowed /// errors has already been recorded, ensures that a <see cref="TooManyModelErrorsException"/> exception is /// recorded instead. /// </summary> /// <param name="key">The key of the <see cref="ModelStateEntry"/> to add errors to.</param> /// <param name="errorMessage">The error message to add.</param> public void AddModelError(string key, string errorMessage) { if (key == null) { throw new ArgumentNullException(nameof(key)); } if (errorMessage == null) { throw new ArgumentNullException(nameof(errorMessage)); } TryAddModelError(key, errorMessage); } /// <summary> /// Attempts to add the specified <paramref name="errorMessage"/> to the <see cref="ModelStateEntry.Errors"/> /// instance that is associated with the specified <paramref name="key"/>. If the maximum number of allowed /// errors has already been recorded, ensures that a <see cref="TooManyModelErrorsException"/> exception is /// recorded instead. /// </summary> /// <param name="key">The key of the <see cref="ModelStateEntry"/> to add errors to.</param> /// <param name="errorMessage">The error message to add.</param> /// <returns> /// <c>True</c> if the given error was added, <c>false</c> if the error was ignored. /// See <see cref="MaxAllowedErrors"/>. /// </returns> public bool TryAddModelError(string key, string errorMessage) { if (key == null) { throw new ArgumentNullException(nameof(key)); } if (errorMessage == null) { throw new ArgumentNullException(nameof(errorMessage)); } if (ErrorCount >= MaxAllowedErrors - 1) { EnsureMaxErrorsReachedRecorded(); return false; } ErrorCount++; var modelState = GetOrAddNode(key); Count += !modelState.IsContainerNode ? 0 : 1; modelState.ValidationState = ModelValidationState.Invalid; modelState.MarkNonContainerNode(); modelState.Errors.Add(errorMessage); return true; } /// <summary> /// Returns the aggregate <see cref="ModelValidationState"/> for items starting with the /// specified <paramref name="key"/>. /// </summary> /// <param name="key">The key to look up model state errors for.</param> /// <returns>Returns <see cref="ModelValidationState.Unvalidated"/> if no entries are found for the specified /// key, <see cref="ModelValidationState.Invalid"/> if at least one instance is found with one or more model /// state errors; <see cref="ModelValidationState.Valid"/> otherwise.</returns> public ModelValidationState GetFieldValidationState(string key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } var item = GetNode(key); return GetValidity(item) ?? ModelValidationState.Unvalidated; } /// <summary> /// Returns <see cref="ModelValidationState"/> for the <paramref name="key"/>. /// </summary> /// <param name="key">The key to look up model state errors for.</param> /// <returns>Returns <see cref="ModelValidationState.Unvalidated"/> if no entry is found for the specified /// key, <see cref="ModelValidationState.Invalid"/> if an instance is found with one or more model /// state errors; <see cref="ModelValidationState.Valid"/> otherwise.</returns> public ModelValidationState GetValidationState(string key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } if (TryGetValue(key, out var validationState)) { return validationState.ValidationState; } return ModelValidationState.Unvalidated; } /// <summary> /// Marks the <see cref="ModelStateEntry.ValidationState"/> for the entry with the specified /// <paramref name="key"/> as <see cref="ModelValidationState.Valid"/>. /// </summary> /// <param name="key">The key of the <see cref="ModelStateEntry"/> to mark as valid.</param> public void MarkFieldValid(string key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } var modelState = GetOrAddNode(key); if (modelState.ValidationState == ModelValidationState.Invalid) { throw new InvalidOperationException(Resources.Validation_InvalidFieldCannotBeReset); } Count += !modelState.IsContainerNode ? 0 : 1; modelState.MarkNonContainerNode(); modelState.ValidationState = ModelValidationState.Valid; } /// <summary> /// Marks the <see cref="ModelStateEntry.ValidationState"/> for the entry with the specified <paramref name="key"/> /// as <see cref="ModelValidationState.Skipped"/>. /// </summary> /// <param name="key">The key of the <see cref="ModelStateEntry"/> to mark as skipped.</param> public void MarkFieldSkipped(string key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } var modelState = GetOrAddNode(key); if (modelState.ValidationState == ModelValidationState.Invalid) { throw new InvalidOperationException(Resources.Validation_InvalidFieldCannotBeReset_ToSkipped); } Count += !modelState.IsContainerNode ? 0 : 1; modelState.MarkNonContainerNode(); modelState.ValidationState = ModelValidationState.Skipped; } /// <summary> /// Copies the values from the specified <paramref name="dictionary"/> into this instance, overwriting /// existing values if keys are the same. /// </summary> /// <param name="dictionary">The <see cref="ModelStateDictionary"/> to copy values from.</param> public void Merge(ModelStateDictionary dictionary) { if (dictionary == null) { return; } foreach (var source in dictionary) { var target = GetOrAddNode(source.Key); Count += !target.IsContainerNode ? 0 : 1; ErrorCount += source.Value.Errors.Count - target.Errors.Count; target.Copy(source.Value); target.MarkNonContainerNode(); } } /// <summary> /// Sets the of <see cref="ModelStateEntry.RawValue"/> and <see cref="ModelStateEntry.AttemptedValue"/> for /// the <see cref="ModelStateEntry"/> with the specified <paramref name="key"/>. /// </summary> /// <param name="key">The key for the <see cref="ModelStateEntry"/> entry.</param> /// <param name="rawValue">The raw value for the <see cref="ModelStateEntry"/> entry.</param> /// <param name="attemptedValue"> /// The values of <paramref name="rawValue"/> in a comma-separated <see cref="string"/>. /// </param> public void SetModelValue(string key, object? rawValue, string? attemptedValue) { if (key == null) { throw new ArgumentNullException(nameof(key)); } var modelState = GetOrAddNode(key); Count += !modelState.IsContainerNode ? 0 : 1; modelState.RawValue = rawValue; modelState.AttemptedValue = attemptedValue; modelState.MarkNonContainerNode(); } /// <summary> /// Sets the value for the <see cref="ModelStateEntry"/> with the specified <paramref name="key"/>. /// </summary> /// <param name="key">The key for the <see cref="ModelStateEntry"/> entry</param> /// <param name="valueProviderResult"> /// A <see cref="ValueProviderResult"/> with data for the <see cref="ModelStateEntry"/> entry. /// </param> public void SetModelValue(string key, ValueProviderResult valueProviderResult) { if (key == null) { throw new ArgumentNullException(nameof(key)); } // Avoid creating a new array for rawValue if there's only one value. object? rawValue; if (valueProviderResult == ValueProviderResult.None) { rawValue = null; } else if (valueProviderResult.Length == 1) { rawValue = valueProviderResult.Values[0]; } else { rawValue = valueProviderResult.Values.ToArray(); } SetModelValue(key, rawValue, valueProviderResult.ToString()); } /// <summary> /// Clears <see cref="ModelStateDictionary"/> entries that match the key that is passed as parameter. /// </summary> /// <param name="key">The key of <see cref="ModelStateDictionary"/> to clear.</param> public void ClearValidationState(string key) { // If key is null or empty, clear all entries in the dictionary // else just clear the ones that have key as prefix var entries = FindKeysWithPrefix(key ?? string.Empty); foreach (var entry in entries) { entry.Value.Errors.Clear(); entry.Value.ValidationState = ModelValidationState.Unvalidated; } } private ModelStateNode? GetNode(string key) { var current = _root; if (key.Length > 0) { var match = default(MatchResult); do { var subKey = FindNext(key, ref match); current = current.GetNode(subKey); // Path not found, exit early if (current == null) { break; } } while (match.Type != Delimiter.None); } return current; } private ModelStateNode GetOrAddNode(string key) { Debug.Assert(key != null); // For a key of the format, foo.bar[0].baz[qux] we'll create the following nodes: // foo // -> bar // -> [0] // -> baz // -> [qux] var current = _root; if (key.Length > 0) { var match = default(MatchResult); do { var subKey = FindNext(key, ref match); current = current.GetOrAddNode(subKey); } while (match.Type != Delimiter.None); if (current.Key == null) { // New Node - Set key current.Key = key; } } return current; } // Shared function factored out for clarity, force inlining to put back in [MethodImpl(MethodImplOptions.AggressiveInlining)] private static StringSegment FindNext(string key, ref MatchResult currentMatch) { var index = currentMatch.Index; var matchType = Delimiter.None; for (; index < key.Length; index++) { var ch = key[index]; if (ch == DelimiterDot) { matchType = Delimiter.Dot; break; } else if (ch == DelimiterOpen) { matchType = Delimiter.OpenBracket; break; } } var keyStart = currentMatch.Type == Delimiter.OpenBracket ? currentMatch.Index - 1 : currentMatch.Index; currentMatch.Type = matchType; currentMatch.Index = index + 1; return new StringSegment(key, keyStart, index - keyStart); } private static ModelValidationState? GetValidity(ModelStateNode? node) { if (node == null) { return null; } ModelValidationState? validationState = null; if (!node.IsContainerNode) { validationState = ModelValidationState.Valid; if (node.ValidationState == ModelValidationState.Unvalidated) { // If any entries of a field is unvalidated, we'll treat the tree as unvalidated. return ModelValidationState.Unvalidated; } if (node.ValidationState == ModelValidationState.Invalid) { validationState = node.ValidationState; } } if (node.ChildNodes != null) { for (var i = 0; i < node.ChildNodes.Count; i++) { var entryState = GetValidity(node.ChildNodes[i]); if (entryState == ModelValidationState.Unvalidated) { return entryState; } if (validationState == null || entryState == ModelValidationState.Invalid) { validationState = entryState; } } } return validationState; } private void EnsureMaxErrorsReachedRecorded() { if (!HasRecordedMaxModelError) { var exception = new TooManyModelErrorsException(Resources.ModelStateDictionary_MaxModelStateErrors); AddModelErrorCore(string.Empty, exception); HasRecordedMaxModelError = true; ErrorCount++; } } private void AddModelErrorCore(string key, Exception exception) { var modelState = GetOrAddNode(key); Count += !modelState.IsContainerNode ? 0 : 1; modelState.ValidationState = ModelValidationState.Invalid; modelState.MarkNonContainerNode(); modelState.Errors.Add(exception); } /// <summary> /// Removes all keys and values from this instance of <see cref="ModelStateDictionary"/>. /// </summary> public void Clear() { Count = 0; HasRecordedMaxModelError = false; ErrorCount = 0; _root.Reset(); _root.ChildNodes?.Clear(); } /// <inheritdoc /> public bool ContainsKey(string key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } return !GetNode(key)?.IsContainerNode ?? false; } /// <summary> /// Removes the <see cref="ModelStateEntry"/> with the specified <paramref name="key"/>. /// </summary> /// <param name="key">The key.</param> /// <returns><c>true</c> if the element is successfully removed; otherwise <c>false</c>. This method also /// returns <c>false</c> if key was not found.</returns> public bool Remove(string key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } var node = GetNode(key); if (node?.IsContainerNode == false) { Count--; ErrorCount -= node.Errors.Count; node.Reset(); return true; } return false; } /// <inheritdoc /> public bool TryGetValue(string key, [NotNullWhen(true)] out ModelStateEntry? value) { if (key == null) { throw new ArgumentNullException(nameof(key)); } var result = GetNode(key); if (result?.IsContainerNode == false) { value = result; return true; } value = null; return false; } /// <summary> /// Returns an enumerator that iterates through this instance of <see cref="ModelStateDictionary"/>. /// </summary> /// <returns>An <see cref="Enumerator"/>.</returns> public Enumerator GetEnumerator() => new Enumerator(this, prefix: string.Empty); /// <inheritdoc /> IEnumerator<KeyValuePair<string, ModelStateEntry?>> IEnumerable<KeyValuePair<string, ModelStateEntry?>>.GetEnumerator() => GetEnumerator(); /// <inheritdoc /> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); /// <summary> /// <para> /// This API supports the MVC's infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </para> /// </summary> public static bool StartsWithPrefix(string prefix, string key) { if (prefix == null) { throw new ArgumentNullException(nameof(prefix)); } if (key == null) { throw new ArgumentNullException(nameof(key)); } if (prefix.Length == 0) { // Everything is prefixed by the empty string. return true; } if (prefix.Length > key.Length) { return false; // Not long enough. } if (!key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) { return false; } if (key.Length == prefix.Length) { // Exact match return true; } var charAfterPrefix = key[prefix.Length]; if (charAfterPrefix == '.' || charAfterPrefix == '[') { return true; } return false; } /// <summary> /// Gets a <see cref="PrefixEnumerable"/> that iterates over this instance of <see cref="ModelStateDictionary"/> /// using the specified <paramref name="prefix"/>. /// </summary> /// <param name="prefix">The prefix.</param> /// <returns>The <see cref="PrefixEnumerable"/>.</returns> public PrefixEnumerable FindKeysWithPrefix(string prefix) { if (prefix == null) { throw new ArgumentNullException(nameof(prefix)); } return new PrefixEnumerable(this, prefix); } private struct MatchResult { public Delimiter Type; public int Index; } private enum Delimiter { None = 0, Dot, OpenBracket } [DebuggerDisplay("SubKey={SubKey}, Key={Key}, ValidationState={ValidationState}")] private class ModelStateNode : ModelStateEntry { private bool _isContainerNode = true; public ModelStateNode(StringSegment subKey) { SubKey = subKey; } public List<ModelStateNode>? ChildNodes { get; set; } public override IReadOnlyList<ModelStateEntry>? Children => ChildNodes; public string Key { get; set; } = default!; public StringSegment SubKey { get; } public override bool IsContainerNode => _isContainerNode; public void MarkNonContainerNode() { _isContainerNode = false; } public void Copy(ModelStateEntry entry) { RawValue = entry.RawValue; AttemptedValue = entry.AttemptedValue; Errors.Clear(); for (var i = 0; i < entry.Errors.Count; i++) { Errors.Add(entry.Errors[i]); } ValidationState = entry.ValidationState; } public void Reset() { _isContainerNode = true; RawValue = null; AttemptedValue = null; ValidationState = ModelValidationState.Unvalidated; Errors.Clear(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ModelStateNode? GetNode(StringSegment subKey) { ModelStateNode? modelStateNode = null; if (subKey.Length == 0) { modelStateNode = this; } else if (ChildNodes != null) { var index = BinarySearch(subKey); if (index >= 0) { modelStateNode = ChildNodes[index]; } } return modelStateNode; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ModelStateNode GetOrAddNode(StringSegment subKey) { ModelStateNode modelStateNode; if (subKey.Length == 0) { modelStateNode = this; } else if (ChildNodes == null) { ChildNodes = new List<ModelStateNode>(1); modelStateNode = new ModelStateNode(subKey); ChildNodes.Add(modelStateNode); } else { var index = BinarySearch(subKey); if (index >= 0) { modelStateNode = ChildNodes[index]; } else { modelStateNode = new ModelStateNode(subKey); ChildNodes.Insert(~index, modelStateNode); } } return modelStateNode; } public override ModelStateEntry? GetModelStateForProperty(string propertyName) => GetNode(new StringSegment(propertyName)); private int BinarySearch(StringSegment searchKey) { Debug.Assert(ChildNodes != null); var low = 0; var high = ChildNodes.Count - 1; while (low <= high) { var mid = low + ((high - low) / 2); var midKey = ChildNodes[mid].SubKey; var result = midKey.Length - searchKey.Length; if (result == 0) { result = string.Compare( midKey.Buffer, midKey.Offset, searchKey.Buffer, searchKey.Offset, searchKey.Length, StringComparison.OrdinalIgnoreCase); } if (result == 0) { return mid; } if (result < 0) { low = mid + 1; } else { high = mid - 1; } } return ~low; } } /// <summary> /// Enumerates over <see cref="ModelStateDictionary"/> to provide entries that start with the /// specified prefix. /// </summary> public readonly struct PrefixEnumerable : IEnumerable<KeyValuePair<string, ModelStateEntry>> { private readonly ModelStateDictionary _dictionary; private readonly string _prefix; /// <summary> /// Initializes a new instance of <see cref="PrefixEnumerable"/>. /// </summary> /// <param name="dictionary">The <see cref="ModelStateDictionary"/>.</param> /// <param name="prefix">The prefix.</param> public PrefixEnumerable(ModelStateDictionary dictionary, string prefix) { if (dictionary == null) { throw new ArgumentNullException(nameof(dictionary)); } if (prefix == null) { throw new ArgumentNullException(nameof(prefix)); } _dictionary = dictionary; _prefix = prefix; } /// <inheritdoc /> public Enumerator GetEnumerator() => new Enumerator(_dictionary, _prefix); IEnumerator<KeyValuePair<string, ModelStateEntry>> IEnumerable<KeyValuePair<string, ModelStateEntry>>.GetEnumerator() => GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } /// <summary> /// An <see cref="IEnumerator{T}"/> for <see cref="PrefixEnumerable"/>. /// </summary> public struct Enumerator : IEnumerator<KeyValuePair<string, ModelStateEntry>> { private readonly ModelStateNode? _rootNode; private ModelStateNode _modelStateNode; private List<ModelStateNode>? _nodes; private int _index; private bool _visitedRoot; /// <summary> /// Intializes a new instance of <see cref="Enumerator"/>. /// </summary> /// <param name="dictionary">The <see cref="ModelStateDictionary"/>.</param> /// <param name="prefix">The prefix.</param> public Enumerator(ModelStateDictionary dictionary, string prefix) { if (dictionary == null) { throw new ArgumentNullException(nameof(dictionary)); } if (prefix == null) { throw new ArgumentNullException(nameof(prefix)); } _index = -1; _rootNode = dictionary.GetNode(prefix); _modelStateNode = default!; _nodes = null; _visitedRoot = false; } /// <inheritdoc /> public KeyValuePair<string, ModelStateEntry> Current => new KeyValuePair<string, ModelStateEntry>(_modelStateNode.Key, _modelStateNode); object IEnumerator.Current => Current; /// <inheritdoc /> public void Dispose() { } /// <inheritdoc /> public bool MoveNext() { if (_rootNode == null) { return false; } if (!_visitedRoot) { // Visit the root node _visitedRoot = true; if (_rootNode.ChildNodes?.Count > 0) { _nodes = new List<ModelStateNode> { _rootNode }; } if (!_rootNode.IsContainerNode) { _modelStateNode = _rootNode; return true; } } if (_nodes == null) { return false; } while (_nodes.Count > 0) { var node = _nodes[0]; if (_index == node.ChildNodes!.Count - 1) { // We've exhausted the current sublist. _nodes.RemoveAt(0); _index = -1; continue; } else { _index++; } var currentChild = node.ChildNodes[_index]; if (currentChild.ChildNodes?.Count > 0) { _nodes.Add(currentChild); } if (!currentChild.IsContainerNode) { _modelStateNode = currentChild; return true; } } return false; } /// <inheritdoc /> public void Reset() { _index = -1; _nodes?.Clear(); _visitedRoot = false; _modelStateNode = default!; } } /// <summary> /// A <see cref="IEnumerable{T}"/> for keys in <see cref="ModelStateDictionary"/>. /// </summary> public readonly struct KeyEnumerable : IEnumerable<string> { private readonly ModelStateDictionary _dictionary; /// <summary> /// Initializes a new instance of <see cref="KeyEnumerable"/>. /// </summary> /// <param name="dictionary">The <see cref="ModelStateDictionary"/>.</param> public KeyEnumerable(ModelStateDictionary dictionary) { _dictionary = dictionary; } /// <inheritdoc /> public KeyEnumerator GetEnumerator() => new KeyEnumerator(_dictionary, prefix: string.Empty); IEnumerator<string> IEnumerable<string>.GetEnumerator() => GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } /// <summary> /// An <see cref="IEnumerator{T}"/> for keys in <see cref="ModelStateDictionary"/>. /// </summary> public struct KeyEnumerator : IEnumerator<string> { private Enumerator _prefixEnumerator; /// <summary> /// Initializes a new instance of <see cref="KeyEnumerable"/>. /// </summary> /// <param name="dictionary">The <see cref="ModelStateDictionary"/>.</param> /// <param name="prefix">The prefix.</param> public KeyEnumerator(ModelStateDictionary dictionary, string prefix) { _prefixEnumerator = new Enumerator(dictionary, prefix); Current = default!; } /// <inheritdoc /> public string Current { get; private set; } object IEnumerator.Current => Current; /// <inheritdoc /> public void Dispose() => _prefixEnumerator.Dispose(); /// <inheritdoc /> public bool MoveNext() { var result = _prefixEnumerator.MoveNext(); if (result) { var current = _prefixEnumerator.Current; Current = current.Key; } else { Current = default!; } return result; } /// <inheritdoc /> public void Reset() { _prefixEnumerator.Reset(); Current = default!; } } /// <summary> /// An <see cref="IEnumerable"/> for <see cref="ModelStateEntry"/>. /// </summary> public readonly struct ValueEnumerable : IEnumerable<ModelStateEntry> { private readonly ModelStateDictionary _dictionary; /// <summary> /// Initializes a new instance of <see cref="ValueEnumerable"/>. /// </summary> /// <param name="dictionary">The <see cref="ModelStateDictionary"/>.</param> public ValueEnumerable(ModelStateDictionary dictionary) { _dictionary = dictionary; } /// <inheritdoc /> public ValueEnumerator GetEnumerator() => new ValueEnumerator(_dictionary, prefix: string.Empty); IEnumerator<ModelStateEntry> IEnumerable<ModelStateEntry>.GetEnumerator() => GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } /// <summary> /// An enumerator for <see cref="ModelStateEntry"/>. /// </summary> public struct ValueEnumerator : IEnumerator<ModelStateEntry> { private Enumerator _prefixEnumerator; /// <summary> /// Initializes a new instance of <see cref="ValueEnumerator"/>. /// </summary> /// <param name="dictionary">The <see cref="ModelStateDictionary"/>.</param> /// <param name="prefix">The prefix to enumerate.</param> public ValueEnumerator(ModelStateDictionary dictionary, string prefix) { _prefixEnumerator = new Enumerator(dictionary, prefix); Current = default!; } /// <inheritdoc /> public ModelStateEntry Current { get; private set; } object IEnumerator.Current => Current; /// <inheritdoc /> public void Dispose() => _prefixEnumerator.Dispose(); /// <inheritdoc /> public bool MoveNext() { var result = _prefixEnumerator.MoveNext(); if (result) { var current = _prefixEnumerator.Current; Current = current.Value; } else { Current = default!; } return result; } /// <inheritdoc /> public void Reset() { _prefixEnumerator.Reset(); Current = default!; } } } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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. //----------------------------------------------------------------------------- new GFXStateBlockData( AL_DepthVisualizeState ) { zDefined = true; zEnable = false; zWriteEnable = false; samplersDefined = true; samplerStates[0] = SamplerClampPoint; // depth samplerStates[1] = SamplerClampLinear; // viz color lookup }; new GFXStateBlockData( AL_DefaultVisualizeState ) { blendDefined = true; blendEnable = true; blendSrc = GFXBlendSrcAlpha; blendDest = GFXBlendInvSrcAlpha; zDefined = true; zEnable = false; zWriteEnable = false; samplersDefined = true; samplerStates[0] = SamplerClampPoint; // #prepass samplerStates[1] = SamplerClampLinear; // depthviz }; new ShaderData( AL_DepthVisualizeShader ) { DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl"; DXPixelShaderFile = "shaders/common/lighting/advanced/dbgDepthVisualizeP.hlsl"; OGLVertexShaderFile = "shaders/common/postFx/postFxV.glsl"; OGLPixelShaderFile = "shaders/common/lighting/advanced/gl/dbgDepthVisualizeP.glsl"; samplerNames[0] = "prepassBuffer"; samplerNames[1] = "depthViz"; pixVersion = 2.0; }; singleton PostEffect( AL_DepthVisualize ) { shader = AL_DepthVisualizeShader; stateBlock = AL_DefaultVisualizeState; texture[0] = "#prepass"; texture[1] = "depthviz"; target = "$backBuffer"; renderPriority = 9999; }; function AL_DepthVisualize::onEnabled( %this ) { AL_NormalsVisualize.disable(); AL_LightColorVisualize.disable(); AL_LightSpecularVisualize.disable(); $AL_NormalsVisualizeVar = false; $AL_LightColorVisualizeVar = false; $AL_LightSpecularVisualizeVar = false; return true; } new ShaderData( AL_NormalsVisualizeShader ) { DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl"; DXPixelShaderFile = "shaders/common/lighting/advanced/dbgNormalVisualizeP.hlsl"; OGLVertexShaderFile = "shaders/common/postFx/postFxV.glsl"; OGLPixelShaderFile = "shaders/common/lighting/advanced/gl/dbgNormalVisualizeP.glsl"; samplerNames[0] = "prepassTex"; pixVersion = 2.0; }; singleton PostEffect( AL_NormalsVisualize ) { shader = AL_NormalsVisualizeShader; stateBlock = AL_DefaultVisualizeState; texture[0] = "#prepass"; target = "$backBuffer"; renderPriority = 9999; }; function AL_NormalsVisualize::onEnabled( %this ) { AL_DepthVisualize.disable(); AL_LightColorVisualize.disable(); AL_LightSpecularVisualize.disable(); $AL_DepthVisualizeVar = false; $AL_LightColorVisualizeVar = false; $AL_LightSpecularVisualizeVar = false; return true; } new ShaderData( AL_LightColorVisualizeShader ) { DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl"; DXPixelShaderFile = "shaders/common/lighting/advanced/dbgLightColorVisualizeP.hlsl"; OGLVertexShaderFile = "shaders/common/postFx/postFxV.glsl"; OGLPixelShaderFile = "shaders/common/lighting/advanced/dl/dbgLightColorVisualizeP.glsl"; samplerNames[0] = "lightInfoBuffer"; pixVersion = 2.0; }; singleton PostEffect( AL_LightColorVisualize ) { shader = AL_LightColorVisualizeShader; stateBlock = AL_DefaultVisualizeState; texture[0] = "#lightinfo"; target = "$backBuffer"; renderPriority = 9999; }; function AL_LightColorVisualize::onEnabled( %this ) { AL_NormalsVisualize.disable(); AL_DepthVisualize.disable(); AL_LightSpecularVisualize.disable(); $AL_NormalsVisualizeVar = false; $AL_DepthVisualizeVar = false; $AL_LightSpecularVisualizeVar = false; return true; } new ShaderData( AL_LightSpecularVisualizeShader ) { DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl"; DXPixelShaderFile = "shaders/common/lighting/advanced/dbgLightSpecularVisualizeP.hlsl"; OGLVertexShaderFile = "shaders/common/postFx/postFxV.glsl"; OGLPixelShaderFile = "shaders/common/lighting/advanced/dl/dbgLightSpecularVisualizeP.glsl"; samplerNames[0] = "lightInfoBuffer"; pixVersion = 2.0; }; singleton PostEffect( AL_LightSpecularVisualize ) { shader = AL_LightSpecularVisualizeShader; stateBlock = AL_DefaultVisualizeState; texture[0] = "#lightinfo"; target = "$backBuffer"; renderPriority = 9999; }; function AL_LightSpecularVisualize::onEnabled( %this ) { AL_NormalsVisualize.disable(); AL_DepthVisualize.disable(); AL_LightColorVisualize.disable(); $AL_NormalsVisualizeVar = false; $AL_DepthVisualizeVar = false; $AL_LightColorVisualizeVar = false; return true; } /// Toggles the visualization of the AL depth buffer. function toggleDepthViz( %enable ) { if ( %enable $= "" ) { $AL_DepthVisualizeVar = AL_DepthVisualize.isEnabled() ? false : true; AL_DepthVisualize.toggle(); } else if ( %enable ) AL_DepthVisualize.enable(); else if ( !%enable ) AL_DepthVisualize.disable(); } /// Toggles the visualization of the AL normals buffer. function toggleNormalsViz( %enable ) { if ( %enable $= "" ) { $AL_NormalsVisualizeVar = AL_NormalsVisualize.isEnabled() ? false : true; AL_NormalsVisualize.toggle(); } else if ( %enable ) AL_NormalsVisualize.enable(); else if ( !%enable ) AL_NormalsVisualize.disable(); } /// Toggles the visualization of the AL lighting color buffer. function toggleLightColorViz( %enable ) { if ( %enable $= "" ) { $AL_LightColorVisualizeVar = AL_LightColorVisualize.isEnabled() ? false : true; AL_LightColorVisualize.toggle(); } else if ( %enable ) AL_LightColorVisualize.enable(); else if ( !%enable ) AL_LightColorVisualize.disable(); } /// Toggles the visualization of the AL lighting specular power buffer. function toggleLightSpecularViz( %enable ) { if ( %enable $= "" ) { $AL_LightSpecularVisualizeVar = AL_LightSpecularVisualize.isEnabled() ? false : true; AL_LightSpecularVisualize.toggle(); } else if ( %enable ) AL_LightSpecularVisualize.enable(); else if ( !%enable ) AL_LightSpecularVisualize.disable(); }
using System.Collections.Generic; using Xunit; using Shouldly; using System; namespace AutoMapper.UnitTests { public class When_overriding_global_ignore : AutoMapperSpecBase { Destination _destination; public class Source { public int ShouldBeMapped { get; set; } } public class Destination { public int ShouldBeMapped { get; set; } } protected override MapperConfiguration Configuration => new MapperConfiguration(cfg => { cfg.AddGlobalIgnore("ShouldBeMapped"); cfg.CreateMap<Source, Destination>().ForMember(d => d.ShouldBeMapped, o => o.MapFrom(src => 12)); }); protected override void Because_of() { _destination = Mapper.Map<Destination>(new Source()); } [Fact] public void Should_not_ignore() { _destination.ShouldBeMapped.ShouldBe(12); } } public class IgnoreAllTests { public class Source { public string ShouldBeMapped { get; set; } } public class Destination { public string ShouldBeMapped { get; set; } public string StartingWith_ShouldNotBeMapped { get; set; } public List<string> StartingWith_ShouldBeNullAfterwards { get; set; } public string AnotherString_ShouldBeNullAfterwards { get; set; } } public class DestinationWrongType { public Destination ShouldBeMapped { get; set; } } public class FooProfile : Profile { public FooProfile() { CreateMap<Source, Destination>() .ForMember(dest => dest.AnotherString_ShouldBeNullAfterwards, opt => opt.Ignore()); } } [Fact] public void GlobalIgnore_ignores_all_properties_beginning_with_string() { var config = new MapperConfiguration(cfg => { cfg.AddGlobalIgnore("StartingWith"); cfg.CreateMap<Source, Destination>() .ForMember(dest => dest.AnotherString_ShouldBeNullAfterwards, opt => opt.Ignore()); }); config.CreateMapper().Map<Source, Destination>(new Source{ShouldBeMapped = "true"}); config.AssertConfigurationIsValid(); } [Fact] public void GlobalIgnore_ignores_all_properties_beginning_with_string_in_profiles() { var config = new MapperConfiguration(cfg => { cfg.AddGlobalIgnore("StartingWith"); cfg.AddProfile<FooProfile>(); }); config.CreateMapper().Map<Source, Destination>(new Source{ShouldBeMapped = "true"}); config.AssertConfigurationIsValid(); } [Fact] public void GlobalIgnore_ignores_properties_with_names_matching_but_different_types() { var config = new MapperConfiguration(cfg => { cfg.AddGlobalIgnore("ShouldBeMapped"); cfg.CreateMap<Source, DestinationWrongType>(); }); config.CreateMapper().Map<Source, DestinationWrongType>(new Source { ShouldBeMapped = "true" }); config.AssertConfigurationIsValid(); } [Fact] public void Ignored_properties_should_be_default_value() { var config = new MapperConfiguration(cfg => { cfg.AddGlobalIgnore("StartingWith"); cfg.CreateMap<Source, Destination>() .ForMember(dest => dest.AnotherString_ShouldBeNullAfterwards, opt => opt.Ignore()); }); Destination destination = config.CreateMapper().Map<Source, Destination>(new Source { ShouldBeMapped = "true" }); destination.StartingWith_ShouldBeNullAfterwards.ShouldBe(null); destination.StartingWith_ShouldNotBeMapped.ShouldBe(null); } [Fact] public void Ignore_supports_two_different_values() { var config = new MapperConfiguration(cfg => { cfg.AddGlobalIgnore("StartingWith"); cfg.AddGlobalIgnore("AnotherString"); cfg.CreateMap<Source, Destination>(); }); Destination destination = config.CreateMapper().Map<Source, Destination>(new Source { ShouldBeMapped = "true" }); destination.AnotherString_ShouldBeNullAfterwards.ShouldBe(null); destination.StartingWith_ShouldNotBeMapped.ShouldBe(null); } } public class IgnoreAttributeTests { public class Source { public string ShouldBeMapped { get; set; } public string ShouldNotBeMapped { get; set; } } public class Destination { public string ShouldBeMapped { get; set; } [IgnoreMap] public string ShouldNotBeMapped { get; set; } } [Fact] public void Ignore_On_Source_Field() { var config = new MapperConfiguration(cfg => cfg.CreateMap<Source, Destination>()); config.AssertConfigurationIsValid(); Source source = new Source { ShouldBeMapped = "Value1", ShouldNotBeMapped = "Value2" }; Destination destination = config.CreateMapper().Map<Source, Destination>(source); destination.ShouldNotBeMapped.ShouldBe(null); } } public class ReverseMapIgnoreAttributeTests { public class Source { public string ShouldBeMapped { get; set; } public string ShouldNotBeMapped { get; set; } } public class Destination { public string ShouldBeMapped { get; set; } [IgnoreMap] public string ShouldNotBeMapped { get; set; } } [Fact] public void Ignore_On_Source_Field() { var config = new MapperConfiguration(cfg => cfg.CreateMap<Source, Destination>() .ReverseMap()); config.AssertConfigurationIsValid(); Destination source = new Destination { ShouldBeMapped = "Value1", ShouldNotBeMapped = "Value2" }; Source destination = config.CreateMapper().Map<Destination, Source>(source); destination.ShouldNotBeMapped.ShouldBe(null); } public class Source2 { } public class Destination2 { [IgnoreMap] public string ShouldNotThrowExceptionOnReverseMapping { get; set; } } [Fact] public void Sould_not_throw_exception_when_reverse_property_does_not_exist() { typeof(ArgumentOutOfRangeException).ShouldNotBeThrownBy(() => new MapperConfiguration(cfg => cfg.CreateMap<Source2, Destination2>() .ReverseMap())); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsAzureSpecials { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// SubscriptionInMethodOperations operations. /// </summary> internal partial class SubscriptionInMethodOperations : IServiceOperations<AutoRestAzureSpecialParametersTestClient>, ISubscriptionInMethodOperations { /// <summary> /// Initializes a new instance of the SubscriptionInMethodOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal SubscriptionInMethodOperations(AutoRestAzureSpecialParametersTestClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestAzureSpecialParametersTestClient /// </summary> public AutoRestAzureSpecialParametersTestClient Client { get; private set; } /// <summary> /// POST method with subscriptionId modeled in the method. pass in /// subscription id = '1234-5678-9012-3456' to succeed /// </summary> /// <param name='subscriptionId'> /// This should appear as a method parameter, use value '1234-5678-9012-3456' /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> PostMethodLocalValidWithHttpMessagesAsync(string subscriptionId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (subscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("subscriptionId", subscriptionId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PostMethodLocalValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/subscriptionId/method/string/none/path/local/1234-5678-9012-3456/{subscriptionId}").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(subscriptionId)); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// POST method with subscriptionId modeled in the method. pass in /// subscription id = null, client-side validation should prevent you from /// making this call /// </summary> /// <param name='subscriptionId'> /// This should appear as a method parameter, use value null, client-side /// validation should prvenet the call /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> PostMethodLocalNullWithHttpMessagesAsync(string subscriptionId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (subscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("subscriptionId", subscriptionId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PostMethodLocalNull", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/subscriptionId/method/string/none/path/local/null/{subscriptionId}").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(subscriptionId)); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// POST method with subscriptionId modeled in the method. pass in /// subscription id = '1234-5678-9012-3456' to succeed /// </summary> /// <param name='subscriptionId'> /// Should appear as a method parameter -use value '1234-5678-9012-3456' /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> PostPathLocalValidWithHttpMessagesAsync(string subscriptionId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (subscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("subscriptionId", subscriptionId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PostPathLocalValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/subscriptionId/path/string/none/path/local/1234-5678-9012-3456/{subscriptionId}").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(subscriptionId)); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// POST method with subscriptionId modeled in the method. pass in /// subscription id = '1234-5678-9012-3456' to succeed /// </summary> /// <param name='subscriptionId'> /// The subscriptionId, which appears in the path, the value is always /// '1234-5678-9012-3456' /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> PostSwaggerLocalValidWithHttpMessagesAsync(string subscriptionId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (subscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("subscriptionId", subscriptionId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PostSwaggerLocalValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/subscriptionId/swagger/string/none/path/local/1234-5678-9012-3456/{subscriptionId}").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(subscriptionId)); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using NUnit.Framework.Constraints; namespace OpenQA.Selenium { [TestFixture] public class TypingTest : DriverTestFixture { [Test] [Category("Javascript")] public void ShouldFireKeyPressEvents() { driver.Url = javascriptPage; IWebElement keyReporter = driver.FindElement(By.Id("keyReporter")); keyReporter.SendKeys("a"); IWebElement result = driver.FindElement(By.Id("result")); string text = result.Text; Assert.IsTrue(text.Contains("press:"), "Text should contain 'press:'. Actual text: {0}", text); } [Test] [Category("Javascript")] public void ShouldFireKeyDownEvents() { driver.Url = javascriptPage; IWebElement keyReporter = driver.FindElement(By.Id("keyReporter")); keyReporter.SendKeys("I"); IWebElement result = driver.FindElement(By.Id("result")); string text = result.Text; Assert.IsTrue(text.Contains("down:"), "Text should contain 'down:'. Actual text: {0}", text); } [Test] [Category("Javascript")] public void ShouldFireKeyUpEvents() { driver.Url = javascriptPage; IWebElement keyReporter = driver.FindElement(By.Id("keyReporter")); keyReporter.SendKeys("a"); IWebElement result = driver.FindElement(By.Id("result")); string text = result.Text; Assert.IsTrue(text.Contains("up:"), "Text should contain 'up:'. Actual text: {0}", text); } [Test] public void ShouldTypeLowerCaseLetters() { driver.Url = javascriptPage; IWebElement keyReporter = driver.FindElement(By.Id("keyReporter")); keyReporter.SendKeys("abc def"); Assert.AreEqual("abc def", keyReporter.GetAttribute("value")); } [Test] public void ShouldBeAbleToTypeCapitalLetters() { driver.Url = javascriptPage; IWebElement keyReporter = driver.FindElement(By.Id("keyReporter")); keyReporter.SendKeys("ABC DEF"); Assert.AreEqual("ABC DEF", keyReporter.GetAttribute("value")); } [Test] public void ShouldBeAbleToTypeQuoteMarks() { driver.Url = javascriptPage; IWebElement keyReporter = driver.FindElement(By.Id("keyReporter")); keyReporter.SendKeys("\""); Assert.AreEqual("\"", keyReporter.GetAttribute("value")); } [Test] public void ShouldBeAbleToTypeTheAtCharacter() { // simon: I tend to use a US/UK or AUS keyboard layout with English // as my primary language. There are consistent reports that we're // not handling i18nised keyboards properly. This test exposes this // in a lightweight manner when my keyboard is set to the DE mapping // and we're using IE. driver.Url = javascriptPage; IWebElement keyReporter = driver.FindElement(By.Id("keyReporter")); keyReporter.SendKeys("@"); Assert.AreEqual("@", keyReporter.GetAttribute("value")); } [Test] public void ShouldBeAbleToMixUpperAndLowerCaseLetters() { driver.Url = javascriptPage; IWebElement keyReporter = driver.FindElement(By.Id("keyReporter")); keyReporter.SendKeys("me@eXample.com"); Assert.AreEqual("me@eXample.com", keyReporter.GetAttribute("value")); } [Test] [Category("Javascript")] public void ArrowKeysShouldNotBePrintable() { driver.Url = javascriptPage; IWebElement keyReporter = driver.FindElement(By.Id("keyReporter")); keyReporter.SendKeys(Keys.ArrowLeft); Assert.AreEqual(string.Empty, keyReporter.GetAttribute("value")); } [Test] [IgnoreBrowser(Browser.HtmlUnit)] public void ShouldBeAbleToUseArrowKeys() { driver.Url = javascriptPage; IWebElement keyReporter = driver.FindElement(By.Id("keyReporter")); keyReporter.SendKeys("Tet" + Keys.ArrowLeft + "s"); Assert.AreEqual("Test", keyReporter.GetAttribute("value")); } [Test] [Category("Javascript")] public void WillSimulateAKeyUpWhenEnteringTextIntoInputElements() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyUp")); element.SendKeys("I like cheese"); IWebElement result = driver.FindElement(By.Id("result")); Assert.AreEqual("I like cheese", result.Text); } [Test] [Category("Javascript")] public void WillSimulateAKeyDownWhenEnteringTextIntoInputElements() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyDown")); element.SendKeys("I like cheese"); IWebElement result = driver.FindElement(By.Id("result")); // Because the key down gets the result before the input element is // filled, we're a letter short here Assert.AreEqual("I like chees", result.Text); } [Test] [Category("Javascript")] public void WillSimulateAKeyPressWhenEnteringTextIntoInputElements() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyPress")); element.SendKeys("I like cheese"); IWebElement result = driver.FindElement(By.Id("result")); // Because the key down gets the result before the input element is // filled, we're a letter short here Assert.AreEqual("I like chees", result.Text); } [Test] [Category("Javascript")] public void WillSimulateAKeyUpWhenEnteringTextIntoTextAreas() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyUpArea")); element.SendKeys("I like cheese"); IWebElement result = driver.FindElement(By.Id("result")); Assert.AreEqual("I like cheese", result.Text); } [Test] [Category("Javascript")] public void WillSimulateAKeyDownWhenEnteringTextIntoTextAreas() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyDownArea")); element.SendKeys("I like cheese"); IWebElement result = driver.FindElement(By.Id("result")); // Because the key down gets the result before the input element is // filled, we're a letter short here Assert.AreEqual("I like chees", result.Text); } [Test] [Category("Javascript")] public void WillSimulateAKeyPressWhenEnteringTextIntoTextAreas() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyPressArea")); element.SendKeys("I like cheese"); IWebElement result = driver.FindElement(By.Id("result")); // Because the key down gets the result before the input element is // filled, we're a letter short here Assert.AreEqual("I like chees", result.Text); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.Firefox, "Firefox demands to have the focus on the window already.")] public void ShouldFireFocusKeyEventsInTheRightOrder() { driver.Url = javascriptPage; IWebElement result = driver.FindElement(By.Id("result")); IWebElement element = driver.FindElement(By.Id("theworks")); element.SendKeys("a"); Assert.AreEqual("focus keydown keypress keyup", result.Text.Trim()); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.IE, "Firefox-specific test. IE does not report key press event.")] [IgnoreBrowser(Browser.HtmlUnit, "firefox-specific")] [IgnoreBrowser(Browser.Chrome, "Firefox-specific test. Chrome does not report key press event.")] [IgnoreBrowser(Browser.PhantomJS, "Firefox-specific test. PhantomJS does not report key press event.")] public void ShouldReportKeyCodeOfArrowKeys() { driver.Url = javascriptPage; IWebElement result = driver.FindElement(By.Id("result")); IWebElement element = driver.FindElement(By.Id("keyReporter")); element.SendKeys(Keys.ArrowDown); Assert.AreEqual("down: 40 press: 40 up: 40", result.Text.Trim()); element.SendKeys(Keys.ArrowUp); Assert.AreEqual("down: 38 press: 38 up: 38", result.Text.Trim()); element.SendKeys(Keys.ArrowLeft); Assert.AreEqual("down: 37 press: 37 up: 37", result.Text.Trim()); element.SendKeys(Keys.ArrowRight); Assert.AreEqual("down: 39 press: 39 up: 39", result.Text.Trim()); // And leave no rubbish/printable keys in the "keyReporter" Assert.AreEqual(string.Empty, element.GetAttribute("value")); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.Chrome, "untested user agents")] [IgnoreBrowser(Browser.HtmlUnit, "untested user agents")] public void ShouldReportKeyCodeOfArrowKeysUpDownEvents() { driver.Url = javascriptPage; IWebElement result = driver.FindElement(By.Id("result")); IWebElement element = driver.FindElement(By.Id("keyReporter")); element.SendKeys(Keys.ArrowDown); string text = result.Text.Trim(); Assert.IsTrue(text.Contains("down: 40"), "Text should contain 'down: 40'. Actual text: {}", text); Assert.IsTrue(text.Contains("up: 40"), "Text should contain 'up: 40'. Actual text: {}", text); element.SendKeys(Keys.ArrowUp); text = result.Text.Trim(); Assert.IsTrue(text.Trim().Contains("down: 38"), "Text should contain 'down: 38'. Actual text: {}", text); Assert.IsTrue(text.Trim().Contains("up: 38"), "Text should contain 'up: 38'. Actual text: {}", text); element.SendKeys(Keys.ArrowLeft); text = result.Text.Trim(); Assert.IsTrue(text.Trim().Contains("down: 37"), "Text should contain 'down: 37'. Actual text: {}", text); Assert.IsTrue(text.Trim().Contains("up: 37"), "Text should contain 'up: 37'. Actual text: {}", text); element.SendKeys(Keys.ArrowRight); text = result.Text.Trim(); Assert.IsTrue(text.Trim().Contains("down: 39"), "Text should contain 'down: 39'. Actual text: {}", text); Assert.IsTrue(text.Trim().Contains("up: 39"), "Text should contain 'up: 39'. Actual text: {}", text); // And leave no rubbish/printable keys in the "keyReporter" Assert.AreEqual(string.Empty, element.GetAttribute("value")); } [Test] [Category("Javascript")] public void NumericNonShiftKeys() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyReporter")); string numericLineCharsNonShifted = "`1234567890-=[]\\;,.'/42"; element.SendKeys(numericLineCharsNonShifted); Assert.AreEqual(numericLineCharsNonShifted, element.GetAttribute("value")); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "untested user agents")] public void NumericShiftKeys() { driver.Url = javascriptPage; IWebElement result = driver.FindElement(By.Id("result")); IWebElement element = driver.FindElement(By.Id("keyReporter")); string numericShiftsEtc = "~!@#$%^&*()_+{}:\"<>?|END~"; element.SendKeys(numericShiftsEtc); Assert.AreEqual(numericShiftsEtc, element.GetAttribute("value")); string text = result.Text.Trim(); Assert.IsTrue(text.Contains(" up: 16"), "Text should contain ' up: 16'. Actual text: {0}", text); } [Test] [Category("Javascript")] public void LowerCaseAlphaKeys() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyReporter")); String lowerAlphas = "abcdefghijklmnopqrstuvwxyz"; element.SendKeys(lowerAlphas); Assert.AreEqual(lowerAlphas, element.GetAttribute("value")); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "untested user agents")] public void UppercaseAlphaKeys() { driver.Url = javascriptPage; IWebElement result = driver.FindElement(By.Id("result")); IWebElement element = driver.FindElement(By.Id("keyReporter")); String upperAlphas = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; element.SendKeys(upperAlphas); Assert.AreEqual(upperAlphas, element.GetAttribute("value")); string text = result.Text.Trim(); Assert.IsTrue(text.Contains(" up: 16"), "Text should contain ' up: 16'. Actual text: {0}", text); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "untested user agents")] public void AllPrintableKeys() { driver.Url = javascriptPage; IWebElement result = driver.FindElement(By.Id("result")); IWebElement element = driver.FindElement(By.Id("keyReporter")); String allPrintable = "!\"#$%&'()*+,-./0123456789:;<=>?@ ABCDEFGHIJKLMNO" + "PQRSTUVWXYZ [\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; element.SendKeys(allPrintable); Assert.AreEqual(allPrintable, element.GetAttribute("value")); string text = result.Text.Trim(); Assert.IsTrue(text.Contains(" up: 16"), "Text should contain ' up: 16'. Actual text: {0}", text); } [Test] [IgnoreBrowser(Browser.HtmlUnit, "untested user agents")] public void ArrowKeysAndPageUpAndDown() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyReporter")); element.SendKeys("a" + Keys.Left + "b" + Keys.Right + Keys.Up + Keys.Down + Keys.PageUp + Keys.PageDown + "1"); Assert.AreEqual("ba1", element.GetAttribute("value")); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "untested user agents")] public void HomeAndEndAndPageUpAndPageDownKeys() { // FIXME: macs don't have HOME keys, would PGUP work? if (System.Environment.OSVersion.Platform == PlatformID.MacOSX) { return; } driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyReporter")); element.SendKeys("abc" + Keys.Home + "0" + Keys.Left + Keys.Right + Keys.PageUp + Keys.PageDown + Keys.End + "1" + Keys.Home + "0" + Keys.PageUp + Keys.End + "111" + Keys.Home + "00"); Assert.AreEqual("0000abc1111", element.GetAttribute("value")); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "untested user agents")] public void DeleteAndBackspaceKeys() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyReporter")); element.SendKeys("abcdefghi"); Assert.AreEqual("abcdefghi", element.GetAttribute("value")); element.SendKeys(Keys.Left + Keys.Left + Keys.Delete); Assert.AreEqual("abcdefgi", element.GetAttribute("value")); element.SendKeys(Keys.Left + Keys.Left + Keys.Backspace); Assert.AreEqual("abcdfgi", element.GetAttribute("value")); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "untested user agents")] public void SpecialSpaceKeys() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyReporter")); element.SendKeys("abcd" + Keys.Space + "fgh" + Keys.Space + "ij"); Assert.AreEqual("abcd fgh ij", element.GetAttribute("value")); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "untested user agents")] public void NumberpadKeys() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyReporter")); element.SendKeys("abcd" + Keys.Multiply + Keys.Subtract + Keys.Add + Keys.Decimal + Keys.Separator + Keys.NumberPad0 + Keys.NumberPad9 + Keys.Add + Keys.Semicolon + Keys.Equal + Keys.Divide + Keys.NumberPad3 + "abcd"); Assert.AreEqual("abcd*-+.,09+;=/3abcd", element.GetAttribute("value")); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "untested user agents")] public void NumberpadAndFunctionKeys() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyReporter")); element.SendKeys("FUNCTION" + Keys.F4 + "-KEYS" + Keys.F4); element.SendKeys("" + Keys.F4 + "-TOO" + Keys.F4); Assert.AreEqual("FUNCTION-KEYS-TOO", element.GetAttribute("value")); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "untested user agents")] [IgnoreBrowser(Browser.Safari, "Issue 4221")] public void ShiftSelectionDeletes() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyReporter")); element.SendKeys("abcd efgh"); Assert.AreEqual(element.GetAttribute("value"), "abcd efgh"); //Could be chord problem element.SendKeys(Keys.Shift + Keys.Left + Keys.Left + Keys.Left); element.SendKeys(Keys.Delete); Assert.AreEqual("abcd e", element.GetAttribute("value")); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "untested user agents")] public void ChordControlHomeShiftEndDelete() { // FIXME: macs don't have HOME keys, would PGUP work? if (System.Environment.OSVersion.Platform == PlatformID.MacOSX) { return; } driver.Url = javascriptPage; IWebElement result = driver.FindElement(By.Id("result")); IWebElement element = driver.FindElement(By.Id("keyReporter")); element.SendKeys("!\"#$%&'()*+,-./0123456789:;<=>?@ ABCDEFG"); element.SendKeys(Keys.Home); element.SendKeys("" + Keys.Shift + Keys.End + Keys.Delete); Assert.AreEqual(string.Empty, element.GetAttribute("value")); string text = result.Text.Trim(); Assert.IsTrue(text.Contains(" up: 16"), "Text should contain ' up: 16'. Actual text: {0}", text); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "untested user agents")] public void ChordReveseShiftHomeSelectionDeletes() { // FIXME: macs don't have HOME keys, would PGUP work? if (System.Environment.OSVersion.Platform == PlatformID.MacOSX) { return; } driver.Url = javascriptPage; IWebElement result = driver.FindElement(By.Id("result")); IWebElement element = driver.FindElement(By.Id("keyReporter")); element.SendKeys("done" + Keys.Home); Assert.AreEqual("done", element.GetAttribute("value")); //Sending chords element.SendKeys("" + Keys.Shift + "ALL " + Keys.Home); Assert.AreEqual("ALL done", element.GetAttribute("value")); element.SendKeys(Keys.Delete); Assert.AreEqual("done", element.GetAttribute("value"), "done"); element.SendKeys("" + Keys.End + Keys.Shift + Keys.Home); Assert.AreEqual("done", element.GetAttribute("value")); // Note: trailing SHIFT up here string text = result.Text.Trim(); Assert.IsTrue(text.Contains(" up: 16"), "Text should contain ' up: 16'. Actual text: {0}", text); element.SendKeys("" + Keys.Delete); Assert.AreEqual(string.Empty, element.GetAttribute("value")); } // control-x control-v here for cut & paste tests, these work on windows // and linux, but not on the MAC. [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "untested user agents")] public void ChordControlCutAndPaste() { // FIXME: macs don't have HOME keys, would PGUP work? if (System.Environment.OSVersion.Platform == PlatformID.MacOSX) { return; } driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("keyReporter")); IWebElement result = driver.FindElement(By.Id("result")); String paste = "!\"#$%&'()*+,-./0123456789:;<=>?@ ABCDEFG"; element.SendKeys(paste); Assert.AreEqual(paste, element.GetAttribute("value")); //Chords element.SendKeys("" + Keys.Home + Keys.Shift + Keys.End); string text = result.Text.Trim(); Assert.IsTrue(text.Contains(" up: 16"), "Text should contain ' up: 16'. Actual text: {0}", text); element.SendKeys(Keys.Control + "x"); Assert.AreEqual(string.Empty, element.GetAttribute("value")); element.SendKeys(Keys.Control + "v"); Assert.AreEqual(paste, element.GetAttribute("value")); element.SendKeys("" + Keys.Left + Keys.Left + Keys.Left + Keys.Shift + Keys.End); element.SendKeys(Keys.Control + "x" + "v"); Assert.AreEqual(paste, element.GetAttribute("value")); element.SendKeys(Keys.Home); element.SendKeys(Keys.Control + "v"); element.SendKeys(Keys.Control + "v" + "v"); element.SendKeys(Keys.Control + "v" + "v" + "v"); Assert.AreEqual("EFGEFGEFGEFGEFGEFG" + paste, element.GetAttribute("value")); element.SendKeys("" + Keys.End + Keys.Shift + Keys.Home + Keys.Null + Keys.Delete); Assert.AreEqual(element.GetAttribute("value"), string.Empty); } [Test] [Category("Javascript")] public void ShouldTypeIntoInputElementsThatHaveNoTypeAttribute() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Id("no-type")); element.SendKeys("Should Say Cheese"); Assert.AreEqual("Should Say Cheese", element.GetAttribute("value")); } [Test] [Category("Javascript")] public void ShouldNotTypeIntoElementsThatPreventKeyDownEvents() { driver.Url = javascriptPage; IWebElement silent = driver.FindElement(By.Name("suppress")); silent.SendKeys("s"); Assert.AreEqual(string.Empty, silent.GetAttribute("value")); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.IE, "Firefox-specific test. IE does not report key press event.")] [IgnoreBrowser(Browser.Chrome, "firefox-specific")] [IgnoreBrowser(Browser.PhantomJS, "firefox-specific")] [IgnoreBrowser(Browser.Safari, "firefox-specific")] [IgnoreBrowser(Browser.Opera, "firefox-specific")] [IgnoreBrowser(Browser.IPhone, "firefox-specific")] [IgnoreBrowser(Browser.Android, "firefox-specific")] public void GenerateKeyPressEventEvenWhenElementPreventsDefault() { driver.Url = javascriptPage; IWebElement silent = driver.FindElement(By.Name("suppress")); IWebElement result = driver.FindElement(By.Id("result")); silent.SendKeys("s"); string text = result.Text; Assert.IsTrue(text.Contains("press"), "Text should contain 'press'. Actual text: {0}", text); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "Cannot type on contentEditable with synthetic events")] [IgnoreBrowser(Browser.Safari, "Cannot type on contentEditable with synthetic events")] [IgnoreBrowser(Browser.PhantomJS, "Cannot type on contentEditable with synthetic events")] [IgnoreBrowser(Browser.Android, "Does not support contentEditable")] [IgnoreBrowser(Browser.IPhone, "Does not support contentEditable")] [IgnoreBrowser(Browser.Opera, "Does not support contentEditable")] public void TypingIntoAnIFrameWithContentEditableOrDesignModeSet() { driver.Url = richTextPage; driver.SwitchTo().Frame("editFrame"); IWebElement element = driver.SwitchTo().ActiveElement(); element.SendKeys("Fishy"); driver.SwitchTo().DefaultContent(); IWebElement trusted = driver.FindElement(By.Id("istrusted")); IWebElement id = driver.FindElement(By.Id("tagId")); Assert.That(trusted.Text, Is.EqualTo("[true]").Or.EqualTo("[n/a]").Or.EqualTo("[]")); Assert.That(id.Text, Is.EqualTo("[frameHtml]").Or.EqualTo("[theBody]")); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "Cannot type on contentEditable with synthetic events")] [IgnoreBrowser(Browser.Android, "Does not support contentEditable")] [IgnoreBrowser(Browser.IPhone, "Does not support contentEditable")] [IgnoreBrowser(Browser.Opera, "Does not support contentEditable")] public void NonPrintableCharactersShouldWorkWithContentEditableOrDesignModeSet() { driver.Url = richTextPage; // not tested on mac // FIXME: macs don't have HOME keys, would PGUP work? if (System.Environment.OSVersion.Platform == PlatformID.MacOSX) { return; } driver.SwitchTo().Frame("editFrame"); IWebElement element = driver.SwitchTo().ActiveElement(); //Chords element.SendKeys("Dishy" + Keys.Backspace + Keys.Left + Keys.Left); element.SendKeys(Keys.Left + Keys.Left + "F" + Keys.Delete + Keys.End + "ee!"); Assert.AreEqual(element.Text, "Fishee!"); } [Test] public void ShouldBeAbleToTypeOnAnEmailInputField() { driver.Url = formsPage; IWebElement email = driver.FindElement(By.Id("email")); email.SendKeys("foobar"); Assert.AreEqual("foobar", email.GetAttribute("value")); } [Test] [IgnoreBrowser(Browser.HtmlUnit, "Cannot type on contentEditable with synthetic events")] [IgnoreBrowser(Browser.Safari, "Cannot type on contentEditable with synthetic events")] [IgnoreBrowser(Browser.PhantomJS, "Cannot type on contentEditable with synthetic events")] [IgnoreBrowser(Browser.Android, "Does not support contentEditable")] [IgnoreBrowser(Browser.IPhone, "Does not support contentEditable")] [IgnoreBrowser(Browser.Opera, "Does not support contentEditable")] public void testShouldBeAbleToTypeIntoEmptyContentEditableElement() { driver.Url = readOnlyPage; IWebElement editable = driver.FindElement(By.Id("content-editable")); editable.Clear(); editable.SendKeys("cheese"); // requires focus on OS X Assert.AreEqual("cheese", editable.Text); } } }
// // DialogViewController.cs: drives MonoTouch.Dialog // // Author: // Miguel de Icaza // // Code to support pull-to-refresh based on Martin Bowling's TweetTableView // which is based in turn in EGOTableViewPullRefresh code which was created // by Devin Doty and is Copyrighted 2009 enormego and released under the // MIT X11 license // using System; using UIKit; using CoreGraphics; using System.Collections.Generic; using Foundation; namespace MonoTouch.Dialog { /// <summary> /// The DialogViewController is the main entry point to use MonoTouch.Dialog, /// it provides a simplified API to the UITableViewController. /// </summary> public class DialogViewController : UITableViewController { public UITableViewStyle Style = UITableViewStyle.Grouped; public event Action<NSIndexPath> OnSelection; UISearchBar searchBar; UITableView tableView; RefreshTableHeaderView refreshView; RootElement root; bool pushing; bool dirty; bool reloading; /// <summary> /// The root element displayed by the DialogViewController, the value can be changed during runtime to update the contents. /// </summary> public RootElement Root { get { return root; } set { if (root == value) return; if (root != null) root.Dispose (); root = value; root.TableView = tableView; ReloadData (); } } EventHandler refreshRequested; /// <summary> /// If you assign a handler to this event before the view is shown, the /// DialogViewController will have support for pull-to-refresh UI. /// </summary> public event EventHandler RefreshRequested { add { if (tableView != null) throw new ArgumentException ("You should set the handler before the controller is shown"); refreshRequested += value; } remove { refreshRequested -= value; } } // If the value is true, we are enabled, used in the source for quick computation bool enableSearch; public bool EnableSearch { get { return enableSearch; } set { if (enableSearch == value) return; // After MonoTouch 3.0, we can allow for the search to be enabled/disable if (tableView != null) throw new ArgumentException ("You should set EnableSearch before the controller is shown"); enableSearch = value; } } // If set, we automatically scroll the content to avoid showing the search bar until // the user manually pulls it down. public bool AutoHideSearch { get; set; } public string SearchPlaceholder { get; set; } /// <summary> /// Invoke this method to trigger a data refresh. /// </summary> /// <remarks> /// This will invoke the RerfeshRequested event handler, the code attached to it /// should start the background operation to fetch the data and when it completes /// it should call ReloadComplete to restore the control state. /// </remarks> public void TriggerRefresh () { TriggerRefresh (false); } void TriggerRefresh (bool showStatus) { if (refreshRequested == null) return; if (reloading) return; reloading = true; if (refreshView != null) refreshView.SetActivity (true); refreshRequested (this, EventArgs.Empty); if (reloading && showStatus && refreshView != null){ UIView.BeginAnimations ("reloadingData"); UIView.SetAnimationDuration (0.2); var tableInset = TableView.ContentInset; tableInset.Top += 60; TableView.ContentInset = tableInset; UIView.CommitAnimations (); } } /// <summary> /// Invoke this method to signal that a reload has completed, this will update the UI accordingly. /// </summary> public void ReloadComplete () { if (refreshView != null) refreshView.LastUpdate = DateTime.Now; if (!reloading) return; reloading = false; if (refreshView == null) return; refreshView.SetActivity (false); refreshView.Flip (false); UIView.BeginAnimations ("doneReloading"); UIView.SetAnimationDuration (0.3f); var tableInset = TableView.ContentInset; tableInset.Top -= 60; TableView.ContentInset = tableInset; refreshView.SetStatus (RefreshViewStatus.PullToReload); UIView.CommitAnimations (); } /// <summary> /// Controls whether the DialogViewController should auto rotate /// </summary> public bool Autorotate { get; set; } public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation) { return Autorotate || toInterfaceOrientation == UIInterfaceOrientation.Portrait; } public override void DidRotate (UIInterfaceOrientation fromInterfaceOrientation) { base.DidRotate (fromInterfaceOrientation); //Fixes the RefreshView's size if it is shown during rotation if (refreshView != null) { var bounds = View.Bounds; refreshView.Frame = new CGRect (0, -bounds.Height, bounds.Width, bounds.Height); } ReloadData (); } Section [] originalSections; Element [][] originalElements; /// <summary> /// Allows caller to programatically activate the search bar and start the search process /// </summary> public void StartSearch () { if (originalSections != null) return; searchBar.BecomeFirstResponder (); originalSections = Root.Sections.ToArray (); originalElements = new Element [originalSections.Length][]; for (int i = 0; i < originalSections.Length; i++) originalElements [i] = originalSections [i].Elements.ToArray (); } /// <summary> /// Allows the caller to programatically stop searching. /// </summary> public virtual void FinishSearch () { if (originalSections == null) return; Root.Sections = new List<Section> (originalSections); originalSections = null; originalElements = null; searchBar.ResignFirstResponder (); ReloadData (); } public delegate void SearchTextEventHandler (object sender, SearchChangedEventArgs args); public event SearchTextEventHandler SearchTextChanged; public virtual void OnSearchTextChanged (string text) { if (SearchTextChanged != null) SearchTextChanged (this, new SearchChangedEventArgs (text)); } public void PerformFilter (string text) { if (originalSections == null) return; OnSearchTextChanged (text); var newSections = new List<Section> (); for (int sidx = 0; sidx < originalSections.Length; sidx++){ Section newSection = null; var section = originalSections [sidx]; Element [] elements = originalElements [sidx]; for (int eidx = 0; eidx < elements.Length; eidx++){ if (elements [eidx].Matches (text)){ if (newSection == null){ newSection = new Section (section.Header, section.Footer){ FooterView = section.FooterView, HeaderView = section.HeaderView }; newSections.Add (newSection); } newSection.Add (elements [eidx]); } } } Root.Sections = newSections; ReloadData (); } public virtual void SearchButtonClicked (string text) { } class SearchDelegate : UISearchBarDelegate { DialogViewController container; public SearchDelegate (DialogViewController container) { this.container = container; } public override void OnEditingStarted (UISearchBar searchBar) { searchBar.ShowsCancelButton = true; container.StartSearch (); } public override void OnEditingStopped (UISearchBar searchBar) { searchBar.ShowsCancelButton = false; container.FinishSearch (); } public override void TextChanged (UISearchBar searchBar, string searchText) { container.PerformFilter (searchText ?? ""); } public override void CancelButtonClicked (UISearchBar searchBar) { searchBar.ShowsCancelButton = false; container.searchBar.Text = ""; container.FinishSearch (); searchBar.ResignFirstResponder (); } public override void SearchButtonClicked (UISearchBar searchBar) { container.SearchButtonClicked (searchBar.Text); } } public class Source : UITableViewSource { const float yboundary = 65; protected DialogViewController Container; protected RootElement Root; bool checkForRefresh; public Source (DialogViewController container) { this.Container = container; Root = container.root; } public override void AccessoryButtonTapped (UITableView tableView, NSIndexPath indexPath) { var section = Root.Sections [indexPath.Section]; var element = (section.Elements [indexPath.Row] as StyledStringElement); if (element != null) element.AccessoryTap (); } public override nint RowsInSection (UITableView tableview, nint section) { var s = Root.Sections[(int)section]; var count = s.Elements.Count; return count; } public override nint NumberOfSections (UITableView tableView) { return Root.Sections.Count; } public override string TitleForHeader (UITableView tableView, nint section) { return Root.Sections[(int)section].Caption; } public override string TitleForFooter (UITableView tableView, nint section) { return Root.Sections[(int)section].Footer; } public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { var section = Root.Sections [indexPath.Section]; var element = section.Elements [indexPath.Row]; return element.GetCell (tableView); } public override void WillDisplay (UITableView tableView, UITableViewCell cell, NSIndexPath indexPath) { if (Root.NeedColorUpdate){ var section = Root.Sections [indexPath.Section]; var element = section.Elements [indexPath.Row]; var colorized = element as IColorizeBackground; if (colorized != null) colorized.WillDisplay (tableView, cell, indexPath); } } public override void RowDeselected (UITableView tableView, NSIndexPath indexPath) { Container.Deselected (indexPath); } public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { var onSelection = Container.OnSelection; if (onSelection != null) onSelection (indexPath); Container.Selected (indexPath); } public override UIView GetViewForHeader (UITableView tableView, nint sectionIdx) { var section = Root.Sections[(int)sectionIdx]; return section.HeaderView; } public override nfloat GetHeightForHeader (UITableView tableView, nint sectionIdx) { var section = Root.Sections[(int)sectionIdx]; if (section.HeaderView == null) return -1; return section.HeaderView.Frame.Height; } public override UIView GetViewForFooter (UITableView tableView, nint sectionIdx) { var section = Root.Sections[(int)sectionIdx]; return section.FooterView; } public override nfloat GetHeightForFooter (UITableView tableView, nint sectionIdx) { var section = Root.Sections[(int)sectionIdx]; if (section.FooterView == null) return -1; return section.FooterView.Frame.Height; } #region Pull to Refresh support public override void Scrolled (UIScrollView scrollView) { if (!checkForRefresh) return; if (Container.reloading) return; var view = Container.refreshView; if (view == null) return; var point = Container.TableView.ContentOffset; if (view.IsFlipped && point.Y > -yboundary && point.Y < 0){ view.Flip (true); view.SetStatus (RefreshViewStatus.PullToReload); } else if (!view.IsFlipped && point.Y < -yboundary){ view.Flip (true); view.SetStatus (RefreshViewStatus.ReleaseToReload); } } public override void DraggingStarted (UIScrollView scrollView) { checkForRefresh = true; } public override void DraggingEnded (UIScrollView scrollView, bool willDecelerate) { if (Container.refreshView == null) return; checkForRefresh = false; if (Container.TableView.ContentOffset.Y > -yboundary) return; Container.TriggerRefresh (true); } #endregion } // // Performance trick, if we expose GetHeightForRow, the UITableView will // probe *every* row for its size; Avoid this by creating a separate // model that is used only when we have items that require resizing // public class SizingSource : Source { public SizingSource (DialogViewController controller) : base (controller) {} public override nfloat GetHeightForRow (UITableView tableView, NSIndexPath indexPath) { var section = Root.Sections [indexPath.Section]; var element = section.Elements [indexPath.Row]; var sizable = element as IElementSizing; if (sizable == null) return tableView.RowHeight; return sizable.GetHeight (tableView, indexPath); } } /// <summary> /// Activates a nested view controller from the DialogViewController. /// If the view controller is hosted in a UINavigationController it /// will push the result. Otherwise it will show it as a modal /// dialog /// </summary> public void ActivateController (UIViewController controller) { dirty = true; var parent = ParentViewController; var nav = parent as UINavigationController; // We can not push a nav controller into a nav controller if (nav != null && !(controller is UINavigationController)) nav.PushViewController (controller, true); else PresentModalViewController (controller, true); } /// <summary> /// Dismisses the view controller. It either pops or dismisses /// based on the kind of container we are hosted in. /// </summary> public void DeactivateController (bool animated) { var parent = ParentViewController; var nav = parent as UINavigationController; if (nav != null) nav.PopViewController(animated); else DismissModalViewController(animated); } void SetupSearch () { if (enableSearch){ searchBar = new UISearchBar (new CGRect (0, 0, tableView.Bounds.Width, 44)) { Delegate = new SearchDelegate (this) }; if (SearchPlaceholder != null) searchBar.Placeholder = this.SearchPlaceholder; tableView.TableHeaderView = searchBar; } else { // Does not work with current Monotouch, will work with 3.0 // tableView.TableHeaderView = null; } } public virtual void Deselected (NSIndexPath indexPath) { var section = root.Sections [indexPath.Section]; var element = section.Elements [indexPath.Row]; element.Deselected (this, tableView, indexPath); } public virtual void Selected (NSIndexPath indexPath) { var section = root.Sections [indexPath.Section]; var element = section.Elements [indexPath.Row]; element.Selected (this, tableView, indexPath); } public virtual UITableView MakeTableView (CGRect bounds, UITableViewStyle style) { return new UITableView (bounds, style); } public override void LoadView () { tableView = MakeTableView (UIScreen.MainScreen.Bounds, Style); tableView.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleTopMargin; tableView.AutosizesSubviews = true; if (root != null) root.Prepare (); UpdateSource (); View = tableView; SetupSearch (); ConfigureTableView (); if (root == null) return; root.TableView = tableView; } void ConfigureTableView () { if (refreshRequested != null){ // The dimensions should be large enough so that even if the user scrolls, we render the // whole are with the background color. var bounds = View.Bounds; refreshView = MakeRefreshTableHeaderView (new CGRect (0, -bounds.Height, bounds.Width, bounds.Height)); if (reloading) refreshView.SetActivity (true); TableView.AddSubview (refreshView); } } public virtual RefreshTableHeaderView MakeRefreshTableHeaderView (CGRect rect) { return new RefreshTableHeaderView (rect); } public event EventHandler ViewAppearing; public override void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); if (AutoHideSearch){ if (enableSearch){ if (TableView.ContentOffset.Y < 44) TableView.ContentOffset = new CGPoint (0, 44); } } if (root == null) return; root.Prepare (); NavigationItem.HidesBackButton = !pushing; if (root.Caption != null) NavigationItem.Title = root.Caption; if (dirty){ tableView.ReloadData (); dirty = false; } if (ViewAppearing != null) ViewAppearing (this, EventArgs.Empty); } public bool Pushing { get { return pushing; } set { pushing = value; if (NavigationItem != null) NavigationItem.HidesBackButton = !pushing; } } public virtual Source CreateSizingSource (bool unevenRows) { return unevenRows ? new SizingSource (this) : new Source (this); } Source TableSource; void UpdateSource () { if (root == null) return; TableSource = CreateSizingSource (root.UnevenRows); tableView.Source = TableSource; } public void ReloadData () { if (root == null) return; if(root.Caption != null) NavigationItem.Title = root.Caption; root.Prepare (); if (tableView != null){ UpdateSource (); tableView.ReloadData (); } dirty = false; } public event EventHandler ViewDisappearing; [Obsolete ("Use the ViewDisappearing event instead")] public event EventHandler ViewDissapearing { add { ViewDisappearing += value; } remove { ViewDisappearing -= value; } } public override void ViewWillDisappear (bool animated) { base.ViewWillDisappear (animated); if (ViewDisappearing != null) ViewDisappearing (this, EventArgs.Empty); } public DialogViewController (RootElement root) : base (UITableViewStyle.Grouped) { this.root = root; } public DialogViewController (UITableViewStyle style, RootElement root) : base (style) { Style = style; this.root = root; } /// <summary> /// Creates a new DialogViewController from a RootElement and sets the push status /// </summary> /// <param name="root"> /// The <see cref="RootElement"/> containing the information to render. /// </param> /// <param name="pushing"> /// A <see cref="System.Boolean"/> describing whether this is being pushed /// (NavigationControllers) or not. If pushing is true, then the back button /// will be shown, allowing the user to go back to the previous controller /// </param> public DialogViewController (RootElement root, bool pushing) : base (UITableViewStyle.Grouped) { this.pushing = pushing; this.root = root; } public DialogViewController (UITableViewStyle style, RootElement root, bool pushing) : base (style) { Style = style; this.pushing = pushing; this.root = root; } public DialogViewController (IntPtr handle) : base(handle) { this.root = new RootElement (""); } } }
namespace android.database { [global::MonoJavaBridge.JavaInterface(typeof(global::android.database.CrossProcessCursor_))] public interface CrossProcessCursor : Cursor { global::android.database.CursorWindow getWindow(); bool onMove(int arg0, int arg1); void fillWindow(int arg0, android.database.CursorWindow arg1); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.database.CrossProcessCursor))] public sealed partial class CrossProcessCursor_ : java.lang.Object, CrossProcessCursor { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static CrossProcessCursor_() { InitJNI(); } internal CrossProcessCursor_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _getWindow2520; global::android.database.CursorWindow android.database.CrossProcessCursor.getWindow() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._getWindow2520)) as android.database.CursorWindow; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._getWindow2520)) as android.database.CursorWindow; } internal static global::MonoJavaBridge.MethodId _onMove2521; bool android.database.CrossProcessCursor.onMove(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._onMove2521, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._onMove2521, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _fillWindow2522; void android.database.CrossProcessCursor.fillWindow(int arg0, android.database.CursorWindow arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._fillWindow2522, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._fillWindow2522, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _getShort2523; short android.database.Cursor.getShort(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallShortMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._getShort2523, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualShortMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._getShort2523, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getInt2524; int android.database.Cursor.getInt(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._getInt2524, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._getInt2524, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getLong2525; long android.database.Cursor.getLong(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._getLong2525, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._getLong2525, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getFloat2526; float android.database.Cursor.getFloat(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallFloatMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._getFloat2526, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._getFloat2526, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getDouble2527; double android.database.Cursor.getDouble(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallDoubleMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._getDouble2527, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualDoubleMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._getDouble2527, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _close2528; void android.database.Cursor.close() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._close2528); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._close2528); } internal static global::MonoJavaBridge.MethodId _getString2529; global::java.lang.String android.database.Cursor.getString(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._getString2529, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._getString2529, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _isFirst2530; bool android.database.Cursor.isFirst() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._isFirst2530); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._isFirst2530); } internal static global::MonoJavaBridge.MethodId _isClosed2531; bool android.database.Cursor.isClosed() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._isClosed2531); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._isClosed2531); } internal static global::MonoJavaBridge.MethodId _getPosition2532; int android.database.Cursor.getPosition() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._getPosition2532); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._getPosition2532); } internal static global::MonoJavaBridge.MethodId _getExtras2533; global::android.os.Bundle android.database.Cursor.getExtras() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._getExtras2533)) as android.os.Bundle; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._getExtras2533)) as android.os.Bundle; } internal static global::MonoJavaBridge.MethodId _registerContentObserver2534; void android.database.Cursor.registerContentObserver(android.database.ContentObserver arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._registerContentObserver2534, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._registerContentObserver2534, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _unregisterContentObserver2535; void android.database.Cursor.unregisterContentObserver(android.database.ContentObserver arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._unregisterContentObserver2535, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._unregisterContentObserver2535, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getCount2536; int android.database.Cursor.getCount() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._getCount2536); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._getCount2536); } internal static global::MonoJavaBridge.MethodId _move2537; bool android.database.Cursor.move(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._move2537, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._move2537, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _moveToPosition2538; bool android.database.Cursor.moveToPosition(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._moveToPosition2538, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._moveToPosition2538, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _moveToFirst2539; bool android.database.Cursor.moveToFirst() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._moveToFirst2539); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._moveToFirst2539); } internal static global::MonoJavaBridge.MethodId _moveToLast2540; bool android.database.Cursor.moveToLast() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._moveToLast2540); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._moveToLast2540); } internal static global::MonoJavaBridge.MethodId _moveToNext2541; bool android.database.Cursor.moveToNext() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._moveToNext2541); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._moveToNext2541); } internal static global::MonoJavaBridge.MethodId _moveToPrevious2542; bool android.database.Cursor.moveToPrevious() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._moveToPrevious2542); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._moveToPrevious2542); } internal static global::MonoJavaBridge.MethodId _isLast2543; bool android.database.Cursor.isLast() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._isLast2543); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._isLast2543); } internal static global::MonoJavaBridge.MethodId _isBeforeFirst2544; bool android.database.Cursor.isBeforeFirst() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._isBeforeFirst2544); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._isBeforeFirst2544); } internal static global::MonoJavaBridge.MethodId _isAfterLast2545; bool android.database.Cursor.isAfterLast() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._isAfterLast2545); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._isAfterLast2545); } internal static global::MonoJavaBridge.MethodId _getColumnIndex2546; int android.database.Cursor.getColumnIndex(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._getColumnIndex2546, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._getColumnIndex2546, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getColumnIndexOrThrow2547; int android.database.Cursor.getColumnIndexOrThrow(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._getColumnIndexOrThrow2547, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._getColumnIndexOrThrow2547, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getColumnName2548; global::java.lang.String android.database.Cursor.getColumnName(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._getColumnName2548, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._getColumnName2548, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getColumnNames2549; global::java.lang.String[] android.database.Cursor.getColumnNames() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.String>(@__env.CallObjectMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._getColumnNames2549)) as java.lang.String[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.String>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._getColumnNames2549)) as java.lang.String[]; } internal static global::MonoJavaBridge.MethodId _getColumnCount2550; int android.database.Cursor.getColumnCount() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._getColumnCount2550); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._getColumnCount2550); } internal static global::MonoJavaBridge.MethodId _getBlob2551; byte[] android.database.Cursor.getBlob(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallObjectMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._getBlob2551, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as byte[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._getBlob2551, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as byte[]; } internal static global::MonoJavaBridge.MethodId _copyStringToBuffer2552; void android.database.Cursor.copyStringToBuffer(int arg0, android.database.CharArrayBuffer arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._copyStringToBuffer2552, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._copyStringToBuffer2552, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _isNull2553; bool android.database.Cursor.isNull(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._isNull2553, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._isNull2553, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _deactivate2554; void android.database.Cursor.deactivate() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._deactivate2554); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._deactivate2554); } internal static global::MonoJavaBridge.MethodId _requery2555; bool android.database.Cursor.requery() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._requery2555); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._requery2555); } internal static global::MonoJavaBridge.MethodId _registerDataSetObserver2556; void android.database.Cursor.registerDataSetObserver(android.database.DataSetObserver arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._registerDataSetObserver2556, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._registerDataSetObserver2556, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _unregisterDataSetObserver2557; void android.database.Cursor.unregisterDataSetObserver(android.database.DataSetObserver arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._unregisterDataSetObserver2557, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._unregisterDataSetObserver2557, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setNotificationUri2558; void android.database.Cursor.setNotificationUri(android.content.ContentResolver arg0, android.net.Uri arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._setNotificationUri2558, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._setNotificationUri2558, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _getWantsAllOnMoveCalls2559; bool android.database.Cursor.getWantsAllOnMoveCalls() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._getWantsAllOnMoveCalls2559); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._getWantsAllOnMoveCalls2559); } internal static global::MonoJavaBridge.MethodId _respond2560; global::android.os.Bundle android.database.Cursor.respond(android.os.Bundle arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.database.CrossProcessCursor_._respond2560, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.os.Bundle; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.database.CrossProcessCursor_.staticClass, global::android.database.CrossProcessCursor_._respond2560, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.os.Bundle; } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.database.CrossProcessCursor_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/database/CrossProcessCursor")); global::android.database.CrossProcessCursor_._getWindow2520 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "getWindow", "()Landroid/database/CursorWindow;"); global::android.database.CrossProcessCursor_._onMove2521 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "onMove", "(II)Z"); global::android.database.CrossProcessCursor_._fillWindow2522 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "fillWindow", "(ILandroid/database/CursorWindow;)V"); global::android.database.CrossProcessCursor_._getShort2523 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "getShort", "(I)S"); global::android.database.CrossProcessCursor_._getInt2524 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "getInt", "(I)I"); global::android.database.CrossProcessCursor_._getLong2525 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "getLong", "(I)J"); global::android.database.CrossProcessCursor_._getFloat2526 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "getFloat", "(I)F"); global::android.database.CrossProcessCursor_._getDouble2527 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "getDouble", "(I)D"); global::android.database.CrossProcessCursor_._close2528 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "close", "()V"); global::android.database.CrossProcessCursor_._getString2529 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "getString", "(I)Ljava/lang/String;"); global::android.database.CrossProcessCursor_._isFirst2530 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "isFirst", "()Z"); global::android.database.CrossProcessCursor_._isClosed2531 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "isClosed", "()Z"); global::android.database.CrossProcessCursor_._getPosition2532 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "getPosition", "()I"); global::android.database.CrossProcessCursor_._getExtras2533 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "getExtras", "()Landroid/os/Bundle;"); global::android.database.CrossProcessCursor_._registerContentObserver2534 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "registerContentObserver", "(Landroid/database/ContentObserver;)V"); global::android.database.CrossProcessCursor_._unregisterContentObserver2535 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "unregisterContentObserver", "(Landroid/database/ContentObserver;)V"); global::android.database.CrossProcessCursor_._getCount2536 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "getCount", "()I"); global::android.database.CrossProcessCursor_._move2537 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "move", "(I)Z"); global::android.database.CrossProcessCursor_._moveToPosition2538 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "moveToPosition", "(I)Z"); global::android.database.CrossProcessCursor_._moveToFirst2539 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "moveToFirst", "()Z"); global::android.database.CrossProcessCursor_._moveToLast2540 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "moveToLast", "()Z"); global::android.database.CrossProcessCursor_._moveToNext2541 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "moveToNext", "()Z"); global::android.database.CrossProcessCursor_._moveToPrevious2542 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "moveToPrevious", "()Z"); global::android.database.CrossProcessCursor_._isLast2543 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "isLast", "()Z"); global::android.database.CrossProcessCursor_._isBeforeFirst2544 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "isBeforeFirst", "()Z"); global::android.database.CrossProcessCursor_._isAfterLast2545 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "isAfterLast", "()Z"); global::android.database.CrossProcessCursor_._getColumnIndex2546 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "getColumnIndex", "(Ljava/lang/String;)I"); global::android.database.CrossProcessCursor_._getColumnIndexOrThrow2547 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "getColumnIndexOrThrow", "(Ljava/lang/String;)I"); global::android.database.CrossProcessCursor_._getColumnName2548 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "getColumnName", "(I)Ljava/lang/String;"); global::android.database.CrossProcessCursor_._getColumnNames2549 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "getColumnNames", "()[Ljava/lang/String;"); global::android.database.CrossProcessCursor_._getColumnCount2550 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "getColumnCount", "()I"); global::android.database.CrossProcessCursor_._getBlob2551 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "getBlob", "(I)[B"); global::android.database.CrossProcessCursor_._copyStringToBuffer2552 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "copyStringToBuffer", "(ILandroid/database/CharArrayBuffer;)V"); global::android.database.CrossProcessCursor_._isNull2553 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "isNull", "(I)Z"); global::android.database.CrossProcessCursor_._deactivate2554 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "deactivate", "()V"); global::android.database.CrossProcessCursor_._requery2555 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "requery", "()Z"); global::android.database.CrossProcessCursor_._registerDataSetObserver2556 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "registerDataSetObserver", "(Landroid/database/DataSetObserver;)V"); global::android.database.CrossProcessCursor_._unregisterDataSetObserver2557 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "unregisterDataSetObserver", "(Landroid/database/DataSetObserver;)V"); global::android.database.CrossProcessCursor_._setNotificationUri2558 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "setNotificationUri", "(Landroid/content/ContentResolver;Landroid/net/Uri;)V"); global::android.database.CrossProcessCursor_._getWantsAllOnMoveCalls2559 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "getWantsAllOnMoveCalls", "()Z"); global::android.database.CrossProcessCursor_._respond2560 = @__env.GetMethodIDNoThrow(global::android.database.CrossProcessCursor_.staticClass, "respond", "(Landroid/os/Bundle;)Landroid/os/Bundle;"); } } }
#region File Description //----------------------------------------------------------------------------- // SwordSlash.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; #endregion namespace NinjAcademy { /// <summary> /// Used to represent sword slashes on the screen during the game. This component will take care of enabling and /// disabling itself. /// </summary> class SwordSlash : TexturedDrawableGameComponent { #region Private Sub-Types enum State { Static, Appearing, Fading } #endregion #region Fields/Properties readonly Vector2 textureOrigin = new Vector2(6, 75); Vector2 source; State state = State.Appearing; TimeSpan fadeDuration = TimeSpan.FromMilliseconds(500); TimeSpan growthDuration = TimeSpan.FromMilliseconds(100); TimeSpan timer = TimeSpan.Zero; float desiredScale; float alpha = 1; /// <summary> /// Rotation in radians to use when rendering the sword slash. /// </summary> public float Rotation { get; set; } Vector2 scaleVector = new Vector2(1, 1); /// <summary> /// Scale factor for the sword slash. Only the slash's length is scaled. /// </summary> public float Stretch { get { return scaleVector.Y; } set { scaleVector.Y = value; } } #endregion #region Initialization /// <summary> /// Creates a new sword slash instance. /// </summary> /// <param name="game">Associated game object.</param> /// <param name="gameScreen">Screen where the element will appear.</param> /// <param name="texture">Texture asset which represents the sword slash.</param> public SwordSlash(Game game, GameScreen gameScreen, Texture2D texture) : base(game, gameScreen, texture) { } #endregion #region Update /// <summary> /// Updates the sword slash's appearance. /// </summary> /// <param name="gameTime">Game time information.</param> public override void Update(GameTime gameTime) { base.Update(gameTime); timer += gameTime.ElapsedGameTime; switch (state) { case State.Static: // No update required in this case break; case State.Appearing: // Cause the slash to grow Stretch = (float)(desiredScale * timer.TotalMilliseconds / growthDuration.TotalMilliseconds); if (timer >= growthDuration) { Fade(fadeDuration); } break; case State.Fading: // Cause the slash to fade, and ultimately vanish alpha = (float)(1 - timer.TotalMilliseconds / fadeDuration.TotalMilliseconds); if (timer >= fadeDuration) { Enabled = false; Visible = false; } break; default: break; } } #endregion #region Rendering /// <summary> /// Renders the component. /// </summary> /// <param name="gameTime">Game time information.</param> public override void Draw(GameTime gameTime) { spriteBatch.Begin(); spriteBatch.Draw(texture, source, null, Color.White * alpha, Rotation, textureOrigin, scaleVector, SpriteEffects.None, 0); spriteBatch.End(); } #endregion #region Public Methods /// <summary> /// Readies the sword slash to be displayed by initializing it. This causes the slash component to enable /// itself. /// </summary> public void Reset() { // Make the slash active and visible alpha = 1; Enabled = true; Visible = true; } /// <summary> /// Cause the sword slash to fade over the course of a specified time span. The component will become inactive /// after the specified time span. /// </summary> /// <param name="fadeDuration">The time it should take the sword slash to fully disappear.</param> public void Fade(TimeSpan fadeDuration) { timer = TimeSpan.Zero; this.fadeDuration = fadeDuration; state = State.Fading; } /// <summary> /// Positions the slash so that it begins and ends at specified points. The slash will remain as specified /// until changed. /// </summary> /// <param name="source">The slash's origin.</param> /// <param name="destination">The slash's endpoint.</param> public void PositionSlash(Vector2 source, Vector2 destination) { state = State.Static; this.source = source; InitializeSlashForCoordinates(source, destination); Stretch = desiredScale; } /// <summary> /// Displays a sword slash on the screen. The slash will expand and then fade over a specified periods of time. /// </summary> /// <param name="source">The slash's origin.</param> /// <param name="destination">The slash's endpoint.</param> /// <param name="growthDuration">The amount of time it should take the slash to stretch from the origin to the /// destination.</param> /// <param name="fadeDuration">Amount of time it should take the slash to fade after reaching its /// full size.</param> /// <remarks>Once the slash disappears, it will disable itself.</remarks> public void Slash(Vector2 source, Vector2 destination, TimeSpan growthDuration, TimeSpan fadeDuration) { this.source = source; this.fadeDuration = fadeDuration; this.growthDuration = growthDuration; state = State.Appearing; Stretch = 0; InitializeSlashForCoordinates(source, destination); // Initialize the timer to use while the sword slash appears timer = TimeSpan.Zero; } #endregion #region Private Methods /// <summary> /// Initializes the component's members for displaying a sword slash between two specified positions. /// </summary> /// <param name="source">The slash's origin.</param> /// <param name="destination">The slash's endpoint.</param> public void InitializeSlashForCoordinates(Vector2 source, Vector2 destination) { // Find the scale required to properly display the slash desiredScale = (source - destination).Length() / Bounds.Height(); // Calculate the required rotation for the sword slash (flip the Y as the screen's Y-axis is flipped) Vector2 desiredDirectionUnitVector = destination - source; desiredDirectionUnitVector.Y = -desiredDirectionUnitVector.Y; desiredDirectionUnitVector.Normalize(); Rotation = (float)Math.Acos(Vector2.Dot(desiredDirectionUnitVector, Vector2.UnitY)); if (desiredDirectionUnitVector.X < 0) { Rotation = -Rotation; } } #endregion } }
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://github.com/jskeet/dotnet-protobufs/ // Original C++/Java/Python code: // http://code.google.com/p/protobuf/ // // 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 Google Inc. 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 COPYRIGHT HOLDERS AND CONTRIBUTORS // "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 COPYRIGHT // OWNER OR 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. #endregion using System.Text; using Google.ProtocolBuffers.Descriptors; using Google.ProtocolBuffers.TestProtos; using NUnit.Framework; namespace Google.ProtocolBuffers { /// <summary> /// Tests for descriptors. (Not in its own namespace or broken up into individual classes as the /// size doesn't warrant it. On the other hand, this makes me feel a bit dirty...) /// </summary> [TestFixture] public class DescriptorsTest { [Test] public void FileDescriptor() { FileDescriptor file = UnitTestProtoFile.Descriptor; Assert.AreEqual("google/protobuf/unittest.proto", file.Name); Assert.AreEqual("protobuf_unittest", file.Package); Assert.AreEqual("UnittestProto", file.Options.JavaOuterClassname); Assert.AreEqual("google/protobuf/unittest.proto", file.Proto.Name); // TODO(jonskeet): Either change to expect 2 dependencies, or don't emit them. // Assert.AreEqual(2, file.Dependencies.Count); Assert.AreEqual(UnitTestImportProtoFile.Descriptor, file.Dependencies[1]); MessageDescriptor messageType = TestAllTypes.Descriptor; Assert.AreEqual(messageType, file.MessageTypes[0]); Assert.AreEqual(messageType, file.FindTypeByName<MessageDescriptor>("TestAllTypes")); Assert.IsNull(file.FindTypeByName<MessageDescriptor>("NoSuchType")); Assert.IsNull(file.FindTypeByName<MessageDescriptor>("protobuf_unittest.TestAllTypes")); for (int i = 0; i < file.MessageTypes.Count; i++) { Assert.AreEqual(i, file.MessageTypes[i].Index); } Assert.AreEqual(file.EnumTypes[0], file.FindTypeByName<EnumDescriptor>("ForeignEnum")); Assert.IsNull(file.FindTypeByName<EnumDescriptor>("NoSuchType")); Assert.IsNull(file.FindTypeByName<EnumDescriptor>("protobuf_unittest.ForeignEnum")); Assert.AreEqual(1, UnitTestImportProtoFile.Descriptor.EnumTypes.Count); Assert.AreEqual("ImportEnum", UnitTestImportProtoFile.Descriptor.EnumTypes[0].Name); for (int i = 0; i < file.EnumTypes.Count; i++) { Assert.AreEqual(i, file.EnumTypes[i].Index); } ServiceDescriptor service = TestService.Descriptor; Assert.AreEqual(service, file.Services[0]); Assert.AreEqual(service, file.FindTypeByName<ServiceDescriptor>("TestService")); Assert.IsNull(file.FindTypeByName<ServiceDescriptor>("NoSuchType")); Assert.IsNull(file.FindTypeByName<ServiceDescriptor>("protobuf_unittest.TestService")); Assert.AreEqual(0, UnitTestImportProtoFile.Descriptor.Services.Count); for (int i = 0; i < file.Services.Count; i++) { Assert.AreEqual(i, file.Services[i].Index); } FieldDescriptor extension = UnitTestProtoFile.OptionalInt32Extension.Descriptor; Assert.AreEqual(extension, file.Extensions[0]); Assert.AreEqual(extension, file.FindTypeByName<FieldDescriptor>("optional_int32_extension")); Assert.IsNull(file.FindTypeByName<FieldDescriptor>("no_such_ext")); Assert.IsNull(file.FindTypeByName<FieldDescriptor>("protobuf_unittest.optional_int32_extension")); Assert.AreEqual(0, UnitTestImportProtoFile.Descriptor.Extensions.Count); for (int i = 0; i < file.Extensions.Count; i++) { Assert.AreEqual(i, file.Extensions[i].Index); } } [Test] public void MessageDescriptor() { MessageDescriptor messageType = TestAllTypes.Descriptor; MessageDescriptor nestedType = TestAllTypes.Types.NestedMessage.Descriptor; Assert.AreEqual("TestAllTypes", messageType.Name); Assert.AreEqual("protobuf_unittest.TestAllTypes", messageType.FullName); Assert.AreEqual(UnitTestProtoFile.Descriptor, messageType.File); Assert.IsNull(messageType.ContainingType); Assert.AreEqual(DescriptorProtos.MessageOptions.DefaultInstance, messageType.Options); Assert.AreEqual("TestAllTypes", messageType.Proto.Name); Assert.AreEqual("NestedMessage", nestedType.Name); Assert.AreEqual("protobuf_unittest.TestAllTypes.NestedMessage", nestedType.FullName); Assert.AreEqual(UnitTestProtoFile.Descriptor, nestedType.File); Assert.AreEqual(messageType, nestedType.ContainingType); FieldDescriptor field = messageType.Fields[0]; Assert.AreEqual("optional_int32", field.Name); Assert.AreEqual(field, messageType.FindDescriptor<FieldDescriptor>("optional_int32")); Assert.IsNull(messageType.FindDescriptor<FieldDescriptor>("no_such_field")); Assert.AreEqual(field, messageType.FindFieldByNumber(1)); Assert.IsNull(messageType.FindFieldByNumber(571283)); for (int i = 0; i < messageType.Fields.Count; i++) { Assert.AreEqual(i, messageType.Fields[i].Index); } Assert.AreEqual(nestedType, messageType.NestedTypes[0]); Assert.AreEqual(nestedType, messageType.FindDescriptor<MessageDescriptor>("NestedMessage")); Assert.IsNull(messageType.FindDescriptor<MessageDescriptor>("NoSuchType")); for (int i = 0; i < messageType.NestedTypes.Count; i++) { Assert.AreEqual(i, messageType.NestedTypes[i].Index); } Assert.AreEqual(messageType.EnumTypes[0], messageType.FindDescriptor<EnumDescriptor>("NestedEnum")); Assert.IsNull(messageType.FindDescriptor<EnumDescriptor>("NoSuchType")); for (int i = 0; i < messageType.EnumTypes.Count; i++) { Assert.AreEqual(i, messageType.EnumTypes[i].Index); } } [Test] public void FieldDescriptor() { MessageDescriptor messageType = TestAllTypes.Descriptor; FieldDescriptor primitiveField = messageType.FindDescriptor<FieldDescriptor>("optional_int32"); FieldDescriptor enumField = messageType.FindDescriptor<FieldDescriptor>("optional_nested_enum"); FieldDescriptor messageField = messageType.FindDescriptor<FieldDescriptor>("optional_foreign_message"); FieldDescriptor cordField = messageType.FindDescriptor<FieldDescriptor>("optional_cord"); FieldDescriptor extension = UnitTestProtoFile.OptionalInt32Extension.Descriptor; FieldDescriptor nestedExtension = TestRequired.Single.Descriptor; Assert.AreEqual("optional_int32", primitiveField.Name); Assert.AreEqual("protobuf_unittest.TestAllTypes.optional_int32", primitiveField.FullName); Assert.AreEqual(1, primitiveField.FieldNumber); Assert.AreEqual(messageType, primitiveField.ContainingType); Assert.AreEqual(UnitTestProtoFile.Descriptor, primitiveField.File); Assert.AreEqual(FieldType.Int32, primitiveField.FieldType); Assert.AreEqual(MappedType.Int32, primitiveField.MappedType); Assert.AreEqual(DescriptorProtos.FieldOptions.DefaultInstance, primitiveField.Options); Assert.IsFalse(primitiveField.IsExtension); Assert.AreEqual("optional_int32", primitiveField.Proto.Name); Assert.AreEqual("optional_nested_enum", enumField.Name); Assert.AreEqual(FieldType.Enum, enumField.FieldType); Assert.AreEqual(MappedType.Enum, enumField.MappedType); // Assert.AreEqual(TestAllTypes.Types.NestedEnum.Descriptor, enumField.EnumType); Assert.AreEqual("optional_foreign_message", messageField.Name); Assert.AreEqual(FieldType.Message, messageField.FieldType); Assert.AreEqual(MappedType.Message, messageField.MappedType); Assert.AreEqual(ForeignMessage.Descriptor, messageField.MessageType); Assert.AreEqual("optional_cord", cordField.Name); Assert.AreEqual(FieldType.String, cordField.FieldType); Assert.AreEqual(MappedType.String, cordField.MappedType); Assert.AreEqual(DescriptorProtos.FieldOptions.Types.CType.CORD, cordField.Options.Ctype); Assert.AreEqual("optional_int32_extension", extension.Name); Assert.AreEqual("protobuf_unittest.optional_int32_extension", extension.FullName); Assert.AreEqual(1, extension.FieldNumber); Assert.AreEqual(TestAllExtensions.Descriptor, extension.ContainingType); Assert.AreEqual(UnitTestProtoFile.Descriptor, extension.File); Assert.AreEqual(FieldType.Int32, extension.FieldType); Assert.AreEqual(MappedType.Int32, extension.MappedType); Assert.AreEqual(DescriptorProtos.FieldOptions.DefaultInstance, extension.Options); Assert.IsTrue(extension.IsExtension); Assert.AreEqual(null, extension.ExtensionScope); Assert.AreEqual("optional_int32_extension", extension.Proto.Name); Assert.AreEqual("single", nestedExtension.Name); Assert.AreEqual("protobuf_unittest.TestRequired.single", nestedExtension.FullName); Assert.AreEqual(TestRequired.Descriptor, nestedExtension.ExtensionScope); } [Test] public void FieldDescriptorLabel() { FieldDescriptor requiredField = TestRequired.Descriptor.FindDescriptor<FieldDescriptor>("a"); FieldDescriptor optionalField = TestAllTypes.Descriptor.FindDescriptor<FieldDescriptor>("optional_int32"); FieldDescriptor repeatedField = TestAllTypes.Descriptor.FindDescriptor<FieldDescriptor>("repeated_int32"); Assert.IsTrue(requiredField.IsRequired); Assert.IsFalse(requiredField.IsRepeated); Assert.IsFalse(optionalField.IsRequired); Assert.IsFalse(optionalField.IsRepeated); Assert.IsFalse(repeatedField.IsRequired); Assert.IsTrue(repeatedField.IsRepeated); } [Test] public void FieldDescriptorDefault() { MessageDescriptor d = TestAllTypes.Descriptor; Assert.IsFalse(d.FindDescriptor<FieldDescriptor>("optional_int32").HasDefaultValue); Assert.AreEqual(0, d.FindDescriptor<FieldDescriptor>("optional_int32").DefaultValue); Assert.IsTrue(d.FindDescriptor<FieldDescriptor>("default_int32").HasDefaultValue); Assert.AreEqual(41, d.FindDescriptor<FieldDescriptor>("default_int32").DefaultValue); d = TestExtremeDefaultValues.Descriptor; Assert.AreEqual(ByteString.CopyFrom("\u0000\u0001\u0007\b\f\n\r\t\u000b\\\'\"\u00fe", Encoding.GetEncoding(28591)), d.FindDescriptor<FieldDescriptor>("escaped_bytes").DefaultValue); Assert.AreEqual(uint.MaxValue, d.FindDescriptor<FieldDescriptor>("large_uint32").DefaultValue); Assert.AreEqual(ulong.MaxValue, d.FindDescriptor<FieldDescriptor>("large_uint64").DefaultValue); } [Test] public void EnumDescriptor() { // Note: this test is a bit different to the Java version because there's no static way of getting to the descriptor EnumDescriptor enumType = UnitTestProtoFile.Descriptor.FindTypeByName<EnumDescriptor>("ForeignEnum"); EnumDescriptor nestedType = TestAllTypes.Descriptor.FindDescriptor<EnumDescriptor>("NestedEnum"); Assert.AreEqual("ForeignEnum", enumType.Name); Assert.AreEqual("protobuf_unittest.ForeignEnum", enumType.FullName); Assert.AreEqual(UnitTestProtoFile.Descriptor, enumType.File); Assert.IsNull(enumType.ContainingType); Assert.AreEqual(DescriptorProtos.EnumOptions.DefaultInstance, enumType.Options); Assert.AreEqual("NestedEnum", nestedType.Name); Assert.AreEqual("protobuf_unittest.TestAllTypes.NestedEnum", nestedType.FullName); Assert.AreEqual(UnitTestProtoFile.Descriptor, nestedType.File); Assert.AreEqual(TestAllTypes.Descriptor, nestedType.ContainingType); EnumValueDescriptor value = enumType.FindValueByName("FOREIGN_FOO"); Assert.AreEqual(value, enumType.Values[0]); Assert.AreEqual("FOREIGN_FOO", value.Name); Assert.AreEqual(4, value.Number); Assert.AreEqual((int) ForeignEnum.FOREIGN_FOO, value.Number); Assert.AreEqual(value, enumType.FindValueByNumber(4)); Assert.IsNull(enumType.FindValueByName("NO_SUCH_VALUE")); for (int i = 0; i < enumType.Values.Count; i++) { Assert.AreEqual(i, enumType.Values[i].Index); } } [Test] public void ServiceDescriptor() { ServiceDescriptor service = TestService.Descriptor; Assert.AreEqual("TestService", service.Name); Assert.AreEqual("protobuf_unittest.TestService", service.FullName); Assert.AreEqual(UnitTestProtoFile.Descriptor, service.File); Assert.AreEqual(2, service.Methods.Count); MethodDescriptor fooMethod = service.Methods[0]; Assert.AreEqual("Foo", fooMethod.Name); Assert.AreEqual(FooRequest.Descriptor, fooMethod.InputType); Assert.AreEqual(FooResponse.Descriptor, fooMethod.OutputType); Assert.AreEqual(fooMethod, service.FindMethodByName("Foo")); MethodDescriptor barMethod = service.Methods[1]; Assert.AreEqual("Bar", barMethod.Name); Assert.AreEqual(BarRequest.Descriptor, barMethod.InputType); Assert.AreEqual(BarResponse.Descriptor, barMethod.OutputType); Assert.AreEqual(barMethod, service.FindMethodByName("Bar")); Assert.IsNull(service.FindMethodByName("NoSuchMethod")); for (int i = 0; i < service.Methods.Count; i++) { Assert.AreEqual(i, service.Methods[i].Index); } } [Test] public void CustomOptions() { MessageDescriptor descriptor = TestMessageWithCustomOptions.Descriptor; Assert.IsTrue(descriptor.Options.HasExtension(UnitTestCustomOptionsProtoFile.MessageOpt1)); Assert.AreEqual(-56, descriptor.Options.GetExtension(UnitTestCustomOptionsProtoFile.MessageOpt1)); FieldDescriptor field = descriptor.FindFieldByName("field1"); Assert.IsNotNull(field); Assert.IsTrue(field.Options.HasExtension(UnitTestCustomOptionsProtoFile.FieldOpt1)); Assert.AreEqual(8765432109L, field.Options.GetExtension(UnitTestCustomOptionsProtoFile.FieldOpt1)); // TODO: Write out enum descriptors /* EnumDescriptor enumType = TestMessageWithCustomOptions.Types. UnittestCustomOptions.TestMessageWithCustomOptions.AnEnum.getDescriptor(); Assert.IsTrue( enumType.getOptions().hasExtension(UnittestCustomOptions.enumOpt1)); Assert.AreEqual(Integer.valueOf(-789), enumType.getOptions().getExtension(UnittestCustomOptions.enumOpt1)); */ ServiceDescriptor service = TestServiceWithCustomOptions.Descriptor; Assert.IsTrue(service.Options.HasExtension(UnitTestCustomOptionsProtoFile.ServiceOpt1)); Assert.AreEqual(-9876543210L, service.Options.GetExtension(UnitTestCustomOptionsProtoFile.ServiceOpt1)); MethodDescriptor method = service.FindMethodByName("Foo"); Assert.IsNotNull(method); Assert.IsTrue(method.Options.HasExtension(UnitTestCustomOptionsProtoFile.MethodOpt1)); Assert.AreEqual(MethodOpt1.METHODOPT1_VAL2, method.Options.GetExtension(UnitTestCustomOptionsProtoFile.MethodOpt1)); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using GammaInput; [RequireComponent(typeof(Camera))] public class MouseInputPointer : InputPointer { #region MouseInputHandling protected override void OnEnable () { base.OnEnable (); MouseInput.OnButtonDown += HandleOnButtonDown; MouseInput.OnButton += HandleOnButton; MouseInput.OnButtonUp += HandleOnButtonUp; MouseInput.OnClick += HandleOnClick; } protected override void OnDisable () { base.OnDisable (); MouseInput.OnButtonDown -= HandleOnButtonDown; MouseInput.OnButton -= HandleOnButton; MouseInput.OnButtonUp -= HandleOnButtonUp; MouseInput.OnClick -= HandleOnClick; } void HandleOnButtonDown (int buttonIndex, MouseInputParameters inputParameters, MouseInput sender) { if(isEventMaster){ (activePointers[0] as MouseInputPointer).PointerInputDown(buttonIndex, inputParameters, sender, 0, false); } } void HandleOnButton (int buttonIndex, MouseInputParameters inputParameters, MouseInput sender) { if(isEventMaster){ (activePointers[0] as MouseInputPointer).PointerInput(buttonIndex, inputParameters, sender, 0, false); } } void HandleOnButtonUp (int buttonIndex, MouseInputParameters inputParameters, MouseInput sender) { if(isEventMaster){ (activePointers[0] as MouseInputPointer).PointerInputUp(buttonIndex, inputParameters, sender, 0, false); } } void HandleOnClick (int buttonIndex, MouseInputParameters inputParameters, MouseInput sender) { if(isEventMaster){ (activePointers[0] as MouseInputPointer).PointerInputTimeClick(buttonIndex, inputParameters, sender, 0, false); } } #endregion #region InputEvents bool timeClick = false; protected override void PointerInputDown (int inputIndex, InputParameters inputParams, BaseInput input, int raydepth, bool behindGui) { //Handle Raycast for Input Ray inputRay = GetComponent<Camera>().ScreenPointToRay(inputParams.position); if(raycastAll){ RaycastHit[] raycastHits = Physics.RaycastAll(inputRay, rayDistance, mask); foreach(var hit in raycastHits){ InputPointerParameters ipp = new InputPointerParameters(hit, raydepth, this, behindGui); ipp.SetInput(input, inputParams, inputRay); AddSelected(inputIndex, ipp); InvokeInputPointerDown(inputIndex, ipp); if(isGUIPointer){ behindGui = true; } raydepth++; } }else{ RaycastHit hit; if(Physics.Raycast(inputRay, out hit, rayDistance, mask)){ InputPointerParameters ipp = new InputPointerParameters(hit, raydepth, this, behindGui); ipp.SetInput(input, inputParams, inputRay); AddSelected(inputIndex, ipp); InvokeInputPointerDown(inputIndex, ipp); if(isGUIPointer){ behindGui = true; } raydepth++; } } timeClick = false; base.PointerInputDown (inputIndex, inputParams, input, raydepth, behindGui); } protected override void PointerInput (int inputIndex, InputParameters inputParams, BaseInput input, int raydepth, bool behindGui) { Ray inputRay = GetComponent<Camera>().ScreenPointToRay(inputParams.position); if(raycastAll){ RaycastHit[] raycastHits = Physics.RaycastAll(inputRay, rayDistance, mask); foreach(var hit in raycastHits){ var ipp = new InputPointerParameters(hit, raydepth, this, behindGui); ipp.SetInput(input, inputParams, inputRay); InvokeInputPointer(inputIndex, ipp); if(isGUIPointer){ behindGui = true; } raydepth++; } }else{ RaycastHit hit; if(Physics.Raycast(inputRay, out hit, rayDistance, mask)){ IsSelected(inputIndex, hit); var ipp = new InputPointerParameters(hit, raydepth, this, behindGui); ipp.SetInput(input, inputParams, inputRay); InvokeInputPointer(inputIndex, ipp); if(isGUIPointer){ behindGui = true; } raydepth++; } } timeClick = false; base.PointerInput (inputIndex, inputParams, input, raydepth, behindGui); } protected override void PointerInputTimeClick (int inputIndex, InputParameters inputParams, BaseInput input, int raydepth, bool behindGui) { timeClick = true; base.PointerInputTimeClick (inputIndex, inputParams, input, raydepth, behindGui); } protected override void PointerInputUp (int inputIndex, InputParameters inputParams, BaseInput input, int raydepth, bool behindGui) { Ray inputRay = GetComponent<Camera>().ScreenPointToRay(inputParams.position); if(raycastAll){ RaycastHit[] raycastHits = Physics.RaycastAll(inputRay, rayDistance, mask); foreach(var hit in raycastHits){ var ipp = new InputPointerParameters(hit, raydepth, this, behindGui); ipp.SetInput(input, inputParams, inputRay); if(IsSelected(inputIndex, hit)){ ipp.inputTimedClick = timeClick; InvokePointerClicked(inputIndex, ipp); RemoveSelected(inputIndex, hit); } InvokeInputPointerUp(inputIndex, ipp); if(isGUIPointer){ behindGui = true; } raydepth++; } foreach(var remainingpp in GetSelected(inputIndex)) { var ipp = new InputPointerParameters(remainingpp.target, this); ipp.SetInput(input, inputParams, inputRay); InvokeInputPointerUpExternal(inputIndex, ipp); } }else{ RaycastHit hit; if(Physics.Raycast(inputRay, out hit, rayDistance, mask)){ var ipp = new InputPointerParameters(hit, raydepth, this, behindGui); ipp.SetInput(input, inputParams, inputRay); InvokeInputPointerUp(inputIndex, ipp); if(IsSelected(inputIndex, hit)){ ipp.inputTimedClick = timeClick; InvokePointerClicked(inputIndex, ipp); RemoveSelected(inputIndex, hit); } if(isGUIPointer){ behindGui = true; } raydepth++; } foreach(var remainingpp in GetSelected(inputIndex)) { var ipp = new InputPointerParameters(remainingpp.target, this); ipp.SetInput(input, inputParams, inputRay); InvokeInputPointerUpExternal(inputIndex, ipp); } } ClearSelected(inputIndex); base.PointerInputUp (inputIndex, inputParams, input, raydepth, behindGui); } #endregion protected override void PointerUpdate (int raydepth, bool behindGui) { if(raycastAll){ RaycastAll(ref raydepth, ref behindGui); }else{ RaycastFirst(ref raydepth, ref behindGui); } base.PointerUpdate (raydepth, behindGui); } private void RaycastAll(ref int raydepth, ref bool behindGui) { Ray pointerRay = GetComponent<Camera>().ScreenPointToRay(MouseInput.position); InvokeInputRayUpdate(0, pointerRay); RaycastHit[] raycastHits = Physics.RaycastAll(pointerRay, rayDistance, mask.value); List<RaycastHit> tempActives = new List<RaycastHit>(); foreach(var hit in raycastHits){ PointerParameters pp; if(!IsActive(hit, out pp)){ pp = new PointerParameters(hit, raydepth, this, behindGui); AddActive(pp); InvokePointerEnter(0, new BasePointerParameters(hit, raydepth, this, behindGui)); }else{ var npp = new BasePointerParameters(hit, raydepth, this, behindGui); InvokePointerOver(0, npp); } tempActives.Add(hit); //Raise raycounter raydepth ++; } //If we hit something and we are a GUIpointer then set behindGui true if(tempActives.Count > 0 && isGUIPointer){ behindGui = true; } List<PointerParameters> leftTargets = RemoveActivesExcept(tempActives); foreach(var tpp in leftTargets){ InvokePointerExit(0, new BasePointerParameters(tpp.target, this)); } } private void RaycastFirst(ref int raydepth, ref bool behindGui) { Ray pointerRay = GetComponent<Camera>().ScreenPointToRay(MouseInput.position); InvokeInputRayUpdate(0, pointerRay); RaycastHit hit; if(Physics.Raycast(pointerRay, out hit, rayDistance, mask.value)){ // Something hit, handle Enter and Over events PointerParameters pp; if(!IsActive(hit, out pp)){ if(HasActives()){ InvokePointerExit(0, new BasePointerParameters(activeTarget[0][0].target, this)); ClearActives(); } pp = new PointerParameters(hit, raydepth, this, behindGui); AddActive(pp); InvokePointerEnter(0, new BasePointerParameters(hit, raydepth, this, behindGui)); }else{ var npp = new BasePointerParameters(hit, raydepth, this, behindGui); InvokePointerOver(0, npp); } raydepth ++; if(isGUIPointer){ behindGui = true; } }else{ // Nothing hit, report Exit event if active objects if(HasActives()){ InvokePointerExit(0, new BasePointerParameters(activeTarget[0][0].target, this)); ClearActives(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Baseline.Dates; using Marten.Events.Projections; using Marten.Events.Projections.Async; using Marten.Storage; using Marten.Testing.CodeTracker; using Marten.Testing.Events.Projections; using Marten.Testing.Harness; using Marten.Util; using Shouldly; using Xunit; using Xunit.Abstractions; using ProjectStarted = Marten.Testing.CodeTracker.ProjectStarted; namespace Marten.Testing.AsyncDaemon { [Collection("daemon")] public class async_daemon_end_to_end: OneOffConfigurationsContext, IClassFixture<AsyncDaemonTestHelper> { public async_daemon_end_to_end(AsyncDaemonTestHelper testHelper, ITestOutputHelper output) : base("daemon") { _testHelper = testHelper; _logger = new TracingLogger(output.WriteLine); } // public async_daemon_end_to_end() // { // _fixture = new AsyncDaemonFixture(); // _logger = new ConsoleDaemonLogger(); // } private readonly AsyncDaemonTestHelper _testHelper; private readonly IDaemonLogger _logger; [Fact] public async Task do_a_complete_rebuild_of_the_active_projects_from_scratch_on_other_schema_single_event() { _testHelper.LoadSingleProject(); StoreOptions(_ => { _.Events.AsyncProjections.AggregateStreamsWith<ActiveProject>(); _.Events.DatabaseSchemaName = "events"; }); await _testHelper.PublishAllProjectEventsAsync(theStore, true); // SAMPLE: rebuild-single-projection using (var daemon = theStore.BuildProjectionDaemon(logger: _logger, settings: new DaemonSettings { LeadingEdgeBuffer = 0.Seconds() })) { await daemon.Rebuild<ActiveProject>().ConfigureAwait(false); } // ENDSAMPLE _testHelper.CompareActiveProjects(theStore); } [Fact] public async Task start_and_stop_a_projection() { _testHelper.LoadSingleProject(); StoreOptions(_ => { _.Events.AsyncProjections.AggregateStreamsWith<ActiveProject>(); _.Events.DatabaseSchemaName = "events"; }); await _testHelper.PublishAllProjectEventsAsync(theStore, true); // Really just kind of a smoke test here using (var daemon = theStore.BuildProjectionDaemon(logger: _logger, settings: new DaemonSettings { LeadingEdgeBuffer = 0.Seconds() })) { daemon.Start<ActiveProject>(DaemonLifecycle.Continuous); await Task.Delay(200); await daemon.Stop<ActiveProject>().ConfigureAwait(false); daemon.Start<ActiveProject>(DaemonLifecycle.StopAtEndOfEventData); } } //[Fact] Not super duper reliable when running back to back public async Task do_a_complete_rebuild_of_the_active_projects_from_scratch_twice_on_other_schema() { _testHelper.LoadAllProjects(); StoreOptions(_ => { _.Events.AsyncProjections.AggregateStreamsWith<ActiveProject>(); _.Events.DatabaseSchemaName = "events"; }); await _testHelper.PublishAllProjectEventsAsync(theStore, true); using (var daemon = theStore.BuildProjectionDaemon(logger: _logger, settings: new DaemonSettings { LeadingEdgeBuffer = 0.Seconds() })) { await daemon.RebuildAll().ConfigureAwait(false); await daemon.RebuildAll().ConfigureAwait(false); } _testHelper.CompareActiveProjects(theStore); } [Fact] public async Task do_a_complete_rebuild_of_the_project_count_with_seq_id_gap_at_101() { _testHelper.LoadTwoProjectsWithOneEventEach(); StoreOptions(_ => { _.Events.AddEventType(typeof(ProjectStarted)); _.Events.AsyncProjections.Add(new ProjectCountProjection()); }); theStore.Schema.ApplyAllConfiguredChangesToDatabase(); _testHelper.PublishAllProjectEvents(theStore, false); // Increment seq_id so events have a respective 1 and 102 seq_id using (var conn = theStore.Tenancy.Default.OpenConnection()) { var command = conn.Connection.CreateCommand(); command.CommandText = $"UPDATE {SchemaName}.mt_events SET seq_id = 102 WHERE seq_id = 2"; command.CommandType = System.Data.CommandType.Text; conn.Execute(command); } using (var daemon = theStore.BuildProjectionDaemon( logger: _logger, viewTypes: new Type[] { typeof(ProjectCountProjection) }, settings: new DaemonSettings { LeadingEdgeBuffer = 0.Seconds() })) { await daemon.Rebuild(typeof(ProjectCountProjection)).ConfigureAwait(false); } using (var session = theStore.LightweightSession()) { session.Query<ProjectCountProjection>().Count().ShouldBe(2); } } [Fact] public async Task use_projection_with_custom_projectionKey_name() { _testHelper.LoadTwoProjectsWithOneEventEach(); var projection = new ProjectionWithCustomProjectionKeyName(); StoreOptions(_ => { _.Events.AddEventType(typeof(ProjectStarted)); _.Events.AsyncProjections.Add(projection); _.Events.DatabaseSchemaName = "events"; }); theStore.Schema.ApplyAllConfiguredChangesToDatabase(); _testHelper.PublishAllProjectEvents(theStore, false); using (var daemon = theStore.BuildProjectionDaemon( logger: _logger, viewTypes: new[] { typeof(ProjectionWithCustomProjectionKeyName) }, settings: new DaemonSettings { LeadingEdgeBuffer = 0.Seconds() })) { await daemon.Rebuild<ProjectionWithCustomProjectionKeyName>(); } projection.Observed.Count.ShouldBe(2); using (var conn = theStore.Tenancy.Default.OpenConnection()) { var command = conn.Connection.CreateCommand(); command.Sql($"select last_seq_id from {theStore.Events.DatabaseSchemaName}.mt_event_progression where name = :name") .With("name", projection.GetEventProgressionName()); using (var reader = await command.ExecuteReaderAsync().ConfigureAwait(false)) { var any = await reader.ReadAsync().ConfigureAwait(false); if (!any) { throw new Exception("No projection found"); } var lastEncountered = await reader.GetFieldValueAsync<long>(0); lastEncountered.ShouldBe(2); } } } [Fact] public async Task custom_projection_with_customKeyName_can_fetch_current_state() { _testHelper.LoadTwoProjectsWithOneEventEach(); var projection = new ProjectionWithCustomProjectionKeyName(); StoreOptions(_ => { _.Events.AddEventType(typeof(ProjectStarted)); _.Events.AsyncProjections.Add(projection); _.Events.DatabaseSchemaName = "events"; }); theStore.Schema.ApplyAllConfiguredChangesToDatabase(); _testHelper.PublishAllProjectEvents(theStore, false); using (var conn = theStore.Tenancy.Default.OpenConnection()) { var command = conn.Connection.CreateCommand(); command.Sql($"insert into {theStore.Events.DatabaseSchemaName}.mt_event_progression (last_seq_id, name) values (:seq, :name)") .With("seq", 1) .With("name", projection.GetEventProgressionName()) ; await command.ExecuteNonQueryAsync().ConfigureAwait(false); } using (var daemon = theStore.BuildProjectionDaemon( logger: _logger, viewTypes: new[] { typeof(ProjectionWithCustomProjectionKeyName) }, settings: new DaemonSettings { LeadingEdgeBuffer = 0.Seconds() })) { daemon.Start<ProjectionWithCustomProjectionKeyName>(DaemonLifecycle.StopAtEndOfEventData); await daemon.WaitForNonStaleResultsOf<ProjectionWithCustomProjectionKeyName>(); } projection.Observed.ShouldHaveSingleItem().ShouldBe(2); } [Fact] public async Task rebuild_all_should_recreate_inline_projection() { StoreOptions(_ => { _.AutoCreateSchemaObjects = AutoCreate.All; _.Events.InlineProjections.AggregateStreamsWith<Project>(); }); var projectId = Guid.NewGuid(); theSession.Events.Append(projectId, new Events.Projections.ProjectStarted { Id = projectId, Name = "Marten"}); await theSession.SaveChangesAsync(); theSession.Query<Project>().SingleOrDefault(x=>x.Id == projectId).ShouldNotBeNull(); theSession.Delete<Project>(projectId); await theSession.SaveChangesAsync(); theSession.Query<Project>().SingleOrDefault(x=>x.Id == projectId).ShouldBeNull(); using (var daemon = theSession.DocumentStore.BuildProjectionDaemon(new[] {typeof(Project)}, settings: new DaemonSettings { LeadingEdgeBuffer = 0.Seconds() })) { await daemon.RebuildAll(); } theSession.Query<Project>().SingleOrDefault(x=>x.Id == projectId).ShouldNotBeNull(); } public class ProjectCountProjection: IProjection { public Guid Id { get; set; } private IDocumentSession _session; public Type[] Consumes { get; } = new Type[] { typeof(ProjectStarted) }; public Type Produces { get; } = typeof(ProjectCountProjection); public AsyncOptions AsyncOptions { get; } = new AsyncOptions(); public void Apply(IDocumentSession session, EventPage page) { } public Task ApplyAsync(IDocumentSession session, EventPage page, CancellationToken token) { _session = session; var projectEvents = page.Events.OrderBy(s => s.Sequence).Select(s => s.Data).OfType<ProjectStarted>(); foreach (var e in projectEvents) { Apply(e); } return Task.CompletedTask; } public void EnsureStorageExists(ITenant tenant) { } public int ProjectCount { get; set; } public void Apply(ProjectStarted @event) { var model = new ProjectCountProjection(); model.ProjectCount++; _session.Store(model); } } public class ProjectionWithCustomProjectionKeyName: IProjection, IHasCustomEventProgressionName { public Guid Id { get; set; } public Type[] Consumes { get; } = { typeof(ProjectStarted) }; public AsyncOptions AsyncOptions { get; } = new AsyncOptions(); public void Apply(IDocumentSession session, EventPage page) { } public Task ApplyAsync(IDocumentSession session, EventPage page, CancellationToken token) { foreach (var pageEvent in page.Events) { Observed.Add(pageEvent.Sequence); } return Task.CompletedTask; } public void EnsureStorageExists(ITenant tenant) { } public string Name => "Custom_projection_key_name"; public List<long> Observed { get; } = new List<long>(); } public class OccasionalErroringProjection: IProjection { private readonly Random _random = new Random(5); private bool _failed; public Type[] Consumes { get; } = new Type[] { typeof(ProjectStarted), typeof(IssueCreated), typeof(IssueClosed), typeof(Commit) }; public Type Produces { get; } = typeof(FakeThing); public AsyncOptions AsyncOptions { get; } = new AsyncOptions(); public void Apply(IDocumentSession session, EventPage page) { } public Task ApplyAsync(IDocumentSession session, EventPage page, CancellationToken token) { if (!_failed && _random.Next(0, 10) == 9) { _failed = true; throw new DivideByZeroException(); } _failed = false; return Task.CompletedTask; } public void EnsureStorageExists(ITenant tenant) { } } public class FakeThing { public Guid Id; } } }
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" using System; using System.Drawing; using System.Windows.Forms; using HtmlRenderer.Dom; using HtmlRenderer.Entities; using HtmlRenderer.Utils; namespace HtmlRenderer.Handlers { /// <summary> /// Handler for text selection in the html. /// </summary> internal sealed class SelectionHandler : IDisposable { #region Fields and Consts /// <summary> /// the root of the handled html tree /// </summary> private readonly CssBox _root; /// <summary> /// handler for showing context menu on right click /// </summary> private readonly ContextMenuHandler _contextMenuHandler; /// <summary> /// the mouse location when selection started used to ignore small selections /// </summary> private Point _selectionStartPoint; /// <summary> /// the starting word of html selection<br/> /// where the user started the selection, if the selection is backwards then it will be the last selected word. /// </summary> private CssRect _selectionStart; /// <summary> /// the ending word of html selection<br/> /// where the user ended the selection, if the selection is backwards then it will be the first selected word. /// </summary> private CssRect _selectionEnd; /// <summary> /// the selection start index if the first selected word is partially selected (-1 if not selected or fully selected) /// </summary> private int _selectionStartIndex = -1; /// <summary> /// the selection end index if the last selected word is partially selected (-1 if not selected or fully selected) /// </summary> private int _selectionEndIndex = -1; /// <summary> /// the selection start offset if the first selected word is partially selected (-1 if not selected or fully selected) /// </summary> private float _selectionStartOffset = -1; /// <summary> /// the selection end offset if the last selected word is partially selected (-1 if not selected or fully selected) /// </summary> private float _selectionEndOffset = -1; /// <summary> /// is the selection goes backward in the html, the starting word comes after the ending word in DFS traversing.<br/> /// </summary> private bool _backwardSelection; /// <summary> /// used to ignore mouse up after selection /// </summary> private bool _inSelection; /// <summary> /// current selection process is after double click (full word selection) /// </summary> private bool _isDoubleClickSelect; /// <summary> /// used to know if selection is in the control or started outside so it needs to be ignored /// </summary> private bool _mouseDownInControl; /// <summary> /// used to handle drag & drop /// </summary> private bool _mouseDownOnSelectedWord; /// <summary> /// is the cursor on the control has been changed by the selection handler /// </summary> private bool _cursorChanged; /// <summary> /// used to know if double click selection is requested /// </summary> private DateTime _lastMouseDown; /// <summary> /// used to know if drag & drop was already started not to execute the same operation over /// </summary> private DataObject _dragDropData; #endregion /// <summary> /// Init. /// </summary> /// <param name="root">the root of the handled html tree</param> public SelectionHandler(CssBox root) { ArgChecker.AssertArgNotNull(root, "root"); _root = root; _contextMenuHandler = new ContextMenuHandler(this, root.HtmlContainer); } /// <summary> /// Select all the words in the html. /// </summary> /// <param name="control">the control hosting the html to invalidate</param> public void SelectAll(Control control) { if (_root.HtmlContainer.IsSelectionEnabled) { ClearSelection(); SelectAllWords(_root); control.Invalidate(); } } /// <summary> /// Select the word at the given location if found. /// </summary> /// <param name="control">the control hosting the html to invalidate</param> /// <param name="loc">the location to select word at</param> public void SelectWord(Control control, Point loc) { if (_root.HtmlContainer.IsSelectionEnabled) { var word = DomUtils.GetCssBoxWord(_root, loc); if (word != null) { word.Selection = this; _selectionStartPoint = loc; _selectionStart = _selectionEnd = word; control.Invalidate(); } } } /// <summary> /// Handle mouse down to handle selection. /// </summary> /// <param name="parent">the control hosting the html to invalidate</param> /// <param name="loc">the location of the mouse on the html</param> /// <param name="isMouseInContainer"> </param> public void HandleMouseDown(Control parent, Point loc, bool isMouseInContainer) { bool clear = !isMouseInContainer; if(isMouseInContainer) { _mouseDownInControl = true; _isDoubleClickSelect = (DateTime.Now - _lastMouseDown).TotalMilliseconds < 400; _lastMouseDown = DateTime.Now; _mouseDownOnSelectedWord = false; if (_root.HtmlContainer.IsSelectionEnabled && (Control.MouseButtons & MouseButtons.Left) != 0) { var word = DomUtils.GetCssBoxWord(_root, loc); if (word != null && word.Selected) { _mouseDownOnSelectedWord = true; } else { clear = true; } } else if ((Control.MouseButtons & MouseButtons.Right) != 0) { var rect = DomUtils.GetCssBoxWord(_root, loc); var link = DomUtils.GetLinkBox(_root, loc); if(_root.HtmlContainer.IsContextMenuEnabled) { _contextMenuHandler.ShowContextMenu(parent, rect, link); } clear = rect == null || !rect.Selected; } } if (clear) { ClearSelection(); parent.Invalidate(); } } /// <summary> /// Handle mouse up to handle selection and link click. /// </summary> /// <param name="parent">the control hosting the html to invalidate</param> /// <param name="button">the mouse button that has been released</param> /// <returns>is the mouse up should be ignored</returns> public bool HandleMouseUp(Control parent, MouseButtons button) { bool ignore = false; _mouseDownInControl = false; if (_root.HtmlContainer.IsSelectionEnabled) { ignore = _inSelection; if (!_inSelection && (button & MouseButtons.Left) != 0 && _mouseDownOnSelectedWord) { ClearSelection(); parent.Invalidate(); } _mouseDownOnSelectedWord = false; _inSelection = false; } ignore = ignore || (DateTime.Now - _lastMouseDown > TimeSpan.FromSeconds(1)); return ignore; } /// <summary> /// Handle mouse move to handle hover cursor and text selection. /// </summary> /// <param name="parent">the control hosting the html to set cursor and invalidate</param> /// <param name="loc">the location of the mouse on the html</param> public void HandleMouseMove(Control parent, Point loc) { if (_root.HtmlContainer.IsSelectionEnabled && _mouseDownInControl && (Control.MouseButtons & MouseButtons.Left) != 0) { if (_mouseDownOnSelectedWord) { // make sure not to start drag-drop on click but when it actually moves as it fucks mouse-up if ((DateTime.Now - _lastMouseDown).TotalMilliseconds > 200) StartDragDrop(parent); } else { HandleSelection(parent, loc, !_isDoubleClickSelect); _inSelection = _selectionStart != null && _selectionEnd != null && (_selectionStart != _selectionEnd || _selectionStartIndex != _selectionEndIndex); } } else { // Handle mouse hover over the html to change the cursor depending if hovering word, link of other. var link = DomUtils.GetLinkBox(_root, loc); if (link != null) { _cursorChanged = true; parent.Cursor = Cursors.Hand; } else if (_root.HtmlContainer.IsSelectionEnabled) { var word = DomUtils.GetCssBoxWord(_root, loc); _cursorChanged = word != null && !word.IsImage && !( word.Selected && ( word.SelectedStartIndex < 0 || word.Left + word.SelectedStartOffset <= loc.X ) && ( word.SelectedEndOffset < 0 || word.Left + word.SelectedEndOffset >= loc.X ) ); parent.Cursor = _cursorChanged ? Cursors.IBeam : Cursors.Default; } else if(_cursorChanged) { parent.Cursor = Cursors.Default; } } } /// <summary> /// On mouse leave change the cursor back to default. /// </summary> /// <param name="parent">the control hosting the html to set cursor and invalidate</param> public void HandleMouseLeave(Control parent) { if(_cursorChanged) { _cursorChanged = false; parent.Cursor = Cursors.Default; } } /// <summary> /// Copy the currently selected html segment to clipboard.<br/> /// Copy rich html text and plain text. /// </summary> public void CopySelectedHtml() { if(_root.HtmlContainer.IsSelectionEnabled) { var html = DomUtils.GenerateHtml(_root, HtmlGenerationStyle.Inline, true); var plainText = DomUtils.GetSelectedPlainText(_root); if (!string.IsNullOrEmpty(plainText)) HtmlClipboardUtils.CopyToClipboard(html, plainText); } } /// <summary> /// Get the currently selected text segment in the html.<br/> /// </summary> public string GetSelectedText() { return _root.HtmlContainer.IsSelectionEnabled ? DomUtils.GetSelectedPlainText(_root) : null; } /// <summary> /// Copy the currently selected html segment with style.<br/> /// </summary> public string GetSelectedHtml() { return _root.HtmlContainer.IsSelectionEnabled ? DomUtils.GenerateHtml(_root, HtmlGenerationStyle.Inline, true) : null; } /// <summary> /// The selection start index if the first selected word is partially selected (-1 if not selected or fully selected)<br/> /// if the given word is not starting or ending selection word -1 is returned as full word selection is in place. /// </summary> /// <remarks> /// Handles backward selecting by returning the selection end data instead of start. /// </remarks> /// <param name="word">the word to return the selection start index for</param> /// <returns>data value or -1 if not applicable</returns> public int GetSelectingStartIndex(CssRect word) { return word == (_backwardSelection ? _selectionEnd : _selectionStart) ? (_backwardSelection ? _selectionEndIndex : _selectionStartIndex) : -1; } /// <summary> /// The selection end index if the last selected word is partially selected (-1 if not selected or fully selected)<br/> /// if the given word is not starting or ending selection word -1 is returned as full word selection is in place. /// </summary> /// <remarks> /// Handles backward selecting by returning the selection end data instead of start. /// </remarks> /// <param name="word">the word to return the selection end index for</param> public int GetSelectedEndIndexOffset(CssRect word) { return word == (_backwardSelection ? _selectionStart : _selectionEnd) ? (_backwardSelection ? _selectionStartIndex : _selectionEndIndex) : -1; } /// <summary> /// The selection start offset if the first selected word is partially selected (-1 if not selected or fully selected)<br/> /// if the given word is not starting or ending selection word -1 is returned as full word selection is in place. /// </summary> /// <remarks> /// Handles backward selecting by returning the selection end data instead of start. /// </remarks> /// <param name="word">the word to return the selection start offset for</param> public float GetSelectedStartOffset(CssRect word) { return word == (_backwardSelection ? _selectionEnd : _selectionStart) ? (_backwardSelection ? _selectionEndOffset : _selectionStartOffset) : -1; } /// <summary> /// The selection end offset if the last selected word is partially selected (-1 if not selected or fully selected)<br/> /// if the given word is not starting or ending selection word -1 is returned as full word selection is in place. /// </summary> /// <remarks> /// Handles backward selecting by returning the selection end data instead of start. /// </remarks> /// <param name="word">the word to return the selection end offset for</param> public float GetSelectedEndOffset(CssRect word) { return word == (_backwardSelection ? _selectionStart : _selectionEnd) ? (_backwardSelection ? _selectionStartOffset : _selectionEndOffset) : -1; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> /// <filterpriority>2</filterpriority> public void Dispose() { _contextMenuHandler.Dispose(); } #region Private methods /// <summary> /// Handle html text selection by mouse move over the html with left mouse button pressed.<br/> /// Calculate the words in the selected range and set their selected property. /// </summary> /// <param name="control">the control hosting the html to invalidate</param> /// <param name="loc">the mouse location</param> /// <param name="allowPartialSelect">true - partial word selection allowed, false - only full words selection</param> private void HandleSelection(Control control, Point loc, bool allowPartialSelect) { // get the line under the mouse or nearest from the top var lineBox = DomUtils.GetCssLineBox(_root, loc); if (lineBox != null) { // get the word under the mouse var word = DomUtils.GetCssBoxWord(lineBox, loc); // if no word found under the mouse use the last or the first word in the line if (word == null && lineBox.Words.Count > 0) { if (loc.Y > lineBox.LineBottom) { // under the line word = lineBox.Words[lineBox.Words.Count - 1]; } else if (loc.X < lineBox.Words[0].Left) { // before the line word = lineBox.Words[0]; } else if (loc.X > lineBox.Words[lineBox.Words.Count - 1].Right) { // at the end of the line word = lineBox.Words[lineBox.Words.Count - 1]; } } // if there is matching word if (word != null) { if (_selectionStart == null) { // on start set the selection start word _selectionStartPoint = loc; _selectionStart = word; if (allowPartialSelect) CalculateWordCharIndexAndOffset(control, word, loc, true); } // always set selection end word _selectionEnd = word; if (allowPartialSelect) CalculateWordCharIndexAndOffset(control, word, loc, false); ClearSelection(_root); if (CheckNonEmptySelection(loc, allowPartialSelect)) { CheckSelectionDirection(); SelectWordsInRange(_root, _backwardSelection ? _selectionEnd : _selectionStart, _backwardSelection ? _selectionStart : _selectionEnd); } else { _selectionEnd = null; } _cursorChanged = true; control.Cursor = Cursors.IBeam; control.Invalidate(); } } } /// <summary> /// Clear the current selection. /// </summary> private void ClearSelection() { // clear drag and drop _dragDropData = null; ClearSelection(_root); _selectionStartOffset = -1; _selectionStartIndex = -1; _selectionEndOffset = -1; _selectionEndIndex = -1; _selectionStartPoint = Point.Empty; _selectionStart = null; _selectionEnd = null; } /// <summary> /// Clear the selection from all the words in the css box recursively. /// </summary> /// <param name="box">the css box to selectionStart clear at</param> private static void ClearSelection(CssBox box) { foreach (var word in box.Words) { word.Selection = null; } foreach (var childBox in box.Boxes) { ClearSelection(childBox); } } /// <summary> /// Start drag & drop operation on the currently selected html segment. /// </summary> /// <param name="control">the control to start the drag & drop on</param> private void StartDragDrop(Control control) { if (_dragDropData == null) { var html = DomUtils.GenerateHtml(_root, HtmlGenerationStyle.Inline, true); var plainText = DomUtils.GetSelectedPlainText(_root); _dragDropData = HtmlClipboardUtils.GetDataObject(html, plainText); } control.DoDragDrop(_dragDropData, DragDropEffects.Copy); } /// <summary> /// Select all the words that are under <paramref name="box"/> DOM hierarchy.<br/> /// </summary> /// <param name="box">the box to start select all at</param> public void SelectAllWords(CssBox box) { foreach (var word in box.Words) { word.Selection = this; } foreach (var childBox in box.Boxes) { SelectAllWords(childBox); } } /// <summary> /// Check if the current selection is non empty, has some selection data. /// </summary> /// <param name="loc"></param> /// <param name="allowPartialSelect">true - partial word selection allowed, false - only full words selection</param> /// <returns>true - is non empty selection, false - empty selection</returns> private bool CheckNonEmptySelection(Point loc, bool allowPartialSelect) { // full word selection is never empty if (!allowPartialSelect) return true; // if end selection location is near starting location then the selection is empty if (Math.Abs(_selectionStartPoint.X - loc.X) <= 1 && Math.Abs(_selectionStartPoint.Y - loc.Y) < 5) return false; // selection is empty if on same word and same index return _selectionStart != _selectionEnd || _selectionStartIndex != _selectionEndIndex; } /// <summary> /// Select all the words that are between <paramref name="selectionStart"/> word and <paramref name="selectionEnd"/> word in the DOM hierarchy.<br/> /// </summary> /// <param name="root">the root of the DOM sub-tree the selection is in</param> /// <param name="selectionStart">selection start word limit</param> /// <param name="selectionEnd">selection end word limit</param> private void SelectWordsInRange(CssBox root, CssRect selectionStart, CssRect selectionEnd) { bool inSelection = false; SelectWordsInRange(root, selectionStart, selectionEnd, ref inSelection); } /// <summary> /// Select all the words that are between <paramref name="selectionStart"/> word and <paramref name="selectionEnd"/> word in the DOM hierarchy. /// </summary> /// <param name="box">the current traversal node</param> /// <param name="selectionStart">selection start word limit</param> /// <param name="selectionEnd">selection end word limit</param> /// <param name="inSelection">used to know the traversal is currently in selected range</param> /// <returns></returns> private bool SelectWordsInRange(CssBox box, CssRect selectionStart, CssRect selectionEnd, ref bool inSelection) { foreach (var boxWord in box.Words) { if (!inSelection && boxWord == selectionStart) { inSelection = true; } if (inSelection) { boxWord.Selection = this; if (selectionStart == selectionEnd || boxWord == selectionEnd) { return true; } } } foreach (var childBox in box.Boxes) { if (SelectWordsInRange(childBox, selectionStart, selectionEnd, ref inSelection)) { return true; } } return false; } /// <summary> /// Calculate the character index and offset by characters for the given word and given offset.<br/> /// <seealso cref="CalculateWordCharIndexAndOffset(Control, CssRect, Point, bool, out int, out float)"/>. /// </summary> /// <param name="control">used to create graphics to measure string</param> /// <param name="word">the word to calculate its index and offset</param> /// <param name="loc">the location to calculate for</param> /// <param name="selectionStart">to set the starting or ending char and offset data</param> private void CalculateWordCharIndexAndOffset(Control control, CssRect word, Point loc, bool selectionStart) { int selectionIndex; float selectionOffset; CalculateWordCharIndexAndOffset(control, word, loc, selectionStart, out selectionIndex, out selectionOffset); if(selectionStart) { _selectionStartIndex = selectionIndex; _selectionStartOffset = selectionOffset; } else { _selectionEndIndex = selectionIndex; _selectionEndOffset = selectionOffset; } } /// <summary> /// Calculate the character index and offset by characters for the given word and given offset.<br/> /// If the location is below the word line then set the selection to the end.<br/> /// If the location is to the right of the word then set the selection to the end.<br/> /// If the offset is to the left of the word set the selection to the beginning.<br/> /// Otherwise calculate the width of each substring to find the char the location is on. /// </summary> /// <param name="control">used to create graphics to measure string</param> /// <param name="word">the word to calculate its index and offset</param> /// <param name="loc">the location to calculate for</param> /// <param name="selectionIndex">return the index of the char under the location</param> /// <param name="selectionOffset">return the offset of the char under the location</param> /// <param name="inclusive">is to include the first character in the calculation</param> private static void CalculateWordCharIndexAndOffset(Control control, CssRect word, Point loc, bool inclusive, out int selectionIndex, out float selectionOffset) { selectionIndex = 0; selectionOffset = 0f; var offset = loc.X - word.Left; if (word.Text == null) { // not a text word - set full selection selectionIndex = -1; selectionOffset = -1; } else if (offset > word.Width - word.OwnerBox.ActualWordSpacing || loc.Y > DomUtils.GetCssLineBoxByWord(word).LineBottom) { // mouse under the line, to the right of the word - set to the end of the word selectionIndex = word.Text.Length; selectionOffset = word.Width; } else if (offset > 0) { // calculate partial word selection var font = word.OwnerBox.ActualFont; using (var g = new WinGraphics(control.CreateGraphics(),false)) { int charFit; int charFitWidth; var maxWidth = offset + ( inclusive ? 0 : 1.5f*word.LeftGlyphPadding ); g.MeasureString(word.Text, font, maxWidth, out charFit, out charFitWidth); selectionIndex = charFit; selectionOffset = charFitWidth; } } } /// <summary> /// Check if the selection direction is forward or backward.<br/> /// Is the selection start word is before the selection end word in DFS traversal. /// </summary> private void CheckSelectionDirection() { if (_selectionStart == _selectionEnd) { _backwardSelection = _selectionStartIndex > _selectionEndIndex; } else if (DomUtils.GetCssLineBoxByWord(_selectionStart) == DomUtils.GetCssLineBoxByWord(_selectionEnd)) { _backwardSelection = _selectionStart.Left > _selectionEnd.Left; } else { _backwardSelection = _selectionStart.Top >= _selectionEnd.Bottom; } } #endregion } }
using System.IO; using Kitware.VTK; using System; // input file is C:\VTK\Graphics\Testing\Tcl\fieldToRGrid.tcl // output file is AVfieldToRGrid.cs /// <summary> /// The testing class derived from AVfieldToRGrid /// </summary> public class AVfieldToRGridClass { /// <summary> /// The main entry method called by the CSharp driver /// </summary> /// <param name="argv"></param> public static void AVfieldToRGrid(String [] argv) { //Prefix Content is: "" //# Generate a rectilinear grid from a field.[] //#[] // get the interactor ui[] // Create a reader and write out the field[] reader = new vtkDataSetReader(); reader.SetFileName((string)"" + (VTK_DATA_ROOT.ToString()) + "/Data/RectGrid2.vtk"); ds2do = new vtkDataSetToDataObjectFilter(); ds2do.SetInputConnection((vtkAlgorithmOutput)reader.GetOutputPort()); try { channel = new StreamWriter("RGridField.vtk"); tryCatchError = "NOERROR"; } catch(Exception) {tryCatchError = "ERROR";} if(tryCatchError.Equals("NOERROR")) { channel.Close(); writer = new vtkDataObjectWriter(); writer.SetInputConnection((vtkAlgorithmOutput)ds2do.GetOutputPort()); writer.SetFileName((string)"RGridField.vtk"); writer.Write(); // Read the field[] //[] dor = new vtkDataObjectReader(); dor.SetFileName((string)"RGridField.vtk"); do2ds = new vtkDataObjectToDataSetFilter(); do2ds.SetInputConnection((vtkAlgorithmOutput)dor.GetOutputPort()); do2ds.SetDataSetTypeToRectilinearGrid(); do2ds.SetDimensionsComponent((string)"Dimensions",(int)0); do2ds.SetPointComponent((int)0,(string)"XCoordinates",(int)0); do2ds.SetPointComponent((int)1,(string)"YCoordinates",(int)0); do2ds.SetPointComponent((int)2,(string)"ZCoordinates",(int)0); fd2ad = new vtkFieldDataToAttributeDataFilter(); fd2ad.SetInput((vtkDataObject)do2ds.GetRectilinearGridOutput()); fd2ad.SetInputFieldToDataObjectField(); fd2ad.SetOutputAttributeDataToPointData(); fd2ad.SetVectorComponent((int)0,(string)"vectors",(int)0); fd2ad.SetVectorComponent((int)1,(string)"vectors",(int)1); fd2ad.SetVectorComponent((int)2,(string)"vectors",(int)2); fd2ad.SetScalarComponent((int)0,(string)"scalars",(int)0); fd2ad.Update(); // create pipeline[] //[] plane = new vtkRectilinearGridGeometryFilter(); plane.SetInput((vtkDataObject)fd2ad.GetRectilinearGridOutput()); plane.SetExtent((int)0,(int)100,(int)0,(int)100,(int)15,(int)15); warper = new vtkWarpVector(); warper.SetInputConnection((vtkAlgorithmOutput)plane.GetOutputPort()); warper.SetScaleFactor((double)0.05); planeMapper = new vtkDataSetMapper(); planeMapper.SetInputConnection((vtkAlgorithmOutput)warper.GetOutputPort()); planeMapper.SetScalarRange((double)0.197813,(double)0.710419); planeActor = new vtkActor(); planeActor.SetMapper((vtkMapper)planeMapper); cutPlane = new vtkPlane(); cutPlane.SetOrigin(fd2ad.GetOutput().GetCenter()[0],fd2ad.GetOutput().GetCenter()[1],fd2ad.GetOutput().GetCenter()[2]); cutPlane.SetNormal((double)1,(double)0,(double)0); planeCut = new vtkCutter(); planeCut.SetInput((vtkDataObject)fd2ad.GetRectilinearGridOutput()); planeCut.SetCutFunction((vtkImplicitFunction)cutPlane); cutMapper = new vtkDataSetMapper(); cutMapper.SetInputConnection((vtkAlgorithmOutput)planeCut.GetOutputPort()); cutMapper.SetScalarRange( (double)((vtkDataSet)fd2ad.GetOutput()).GetPointData().GetScalars().GetRange()[0], (double)((vtkDataSet)fd2ad.GetOutput()).GetPointData().GetScalars().GetRange()[1]); cutActor = new vtkActor(); cutActor.SetMapper((vtkMapper)cutMapper); iso = new vtkContourFilter(); iso.SetInput((vtkDataObject)fd2ad.GetRectilinearGridOutput()); iso.SetValue((int)0,(double)0.7); normals = new vtkPolyDataNormals(); normals.SetInputConnection((vtkAlgorithmOutput)iso.GetOutputPort()); normals.SetFeatureAngle((double)45); isoMapper = vtkPolyDataMapper.New(); isoMapper.SetInputConnection((vtkAlgorithmOutput)normals.GetOutputPort()); isoMapper.ScalarVisibilityOff(); isoActor = new vtkActor(); isoActor.SetMapper((vtkMapper)isoMapper); isoActor.GetProperty().SetColor((double) 1.0000, 0.8941, 0.7686 ); isoActor.GetProperty().SetRepresentationToWireframe(); streamer = new vtkStreamLine(); streamer.SetInputConnection((vtkAlgorithmOutput)fd2ad.GetOutputPort()); streamer.SetStartPosition((double)-1.2,(double)-0.1,(double)1.3); streamer.SetMaximumPropagationTime((double)500); streamer.SetStepLength((double)0.05); streamer.SetIntegrationStepLength((double)0.05); streamer.SetIntegrationDirectionToIntegrateBothDirections(); streamTube = new vtkTubeFilter(); streamTube.SetInputConnection((vtkAlgorithmOutput)streamer.GetOutputPort()); streamTube.SetRadius((double)0.025); streamTube.SetNumberOfSides((int)6); streamTube.SetVaryRadiusToVaryRadiusByVector(); mapStreamTube = vtkPolyDataMapper.New(); mapStreamTube.SetInputConnection((vtkAlgorithmOutput)streamTube.GetOutputPort()); mapStreamTube.SetScalarRange( (double)((vtkDataSet)fd2ad.GetOutput()).GetPointData().GetScalars().GetRange()[0], (double)((vtkDataSet)fd2ad.GetOutput()).GetPointData().GetScalars().GetRange()[1]); streamTubeActor = new vtkActor(); streamTubeActor.SetMapper((vtkMapper)mapStreamTube); streamTubeActor.GetProperty().BackfaceCullingOn(); outline = new vtkOutlineFilter(); outline.SetInput((vtkDataObject)fd2ad.GetRectilinearGridOutput()); outlineMapper = vtkPolyDataMapper.New(); outlineMapper.SetInputConnection((vtkAlgorithmOutput)outline.GetOutputPort()); outlineActor = new vtkActor(); outlineActor.SetMapper((vtkMapper)outlineMapper); outlineActor.GetProperty().SetColor((double) 0.0000, 0.0000, 0.0000 ); // Graphics stuff[] // Create the RenderWindow, Renderer and both Actors[] //[] ren1 = vtkRenderer.New(); renWin = vtkRenderWindow.New(); renWin.AddRenderer((vtkRenderer)ren1); iren = new vtkRenderWindowInteractor(); iren.SetRenderWindow((vtkRenderWindow)renWin); // Add the actors to the renderer, set the background and size[] //[] ren1.AddActor((vtkProp)outlineActor); ren1.AddActor((vtkProp)planeActor); ren1.AddActor((vtkProp)cutActor); ren1.AddActor((vtkProp)isoActor); ren1.AddActor((vtkProp)streamTubeActor); ren1.SetBackground((double)1,(double)1,(double)1); renWin.SetSize((int)300,(int)300); ren1.GetActiveCamera().SetPosition((double)0.0390893,(double)0.184813,(double)-3.94026); ren1.GetActiveCamera().SetFocalPoint((double)-0.00578326,(double)0,(double)0.701967); ren1.GetActiveCamera().SetViewAngle((double)30); ren1.GetActiveCamera().SetViewUp((double)0.00850257,(double)0.999169,(double)0.0398605); ren1.GetActiveCamera().SetClippingRange((double)3.08127,(double)6.62716); iren.Initialize(); // render the image[] //[] File.Delete("RGridField.vtk"); } // prevent the tk window from showing up then start the event loop[] //deleteAllVTKObjects(); } static string VTK_DATA_ROOT; static int threshold; static vtkDataSetReader reader; static vtkDataSetToDataObjectFilter ds2do; static string tryCatchError; static StreamWriter channel; static vtkDataObjectWriter writer; static vtkDataObjectReader dor; static vtkDataObjectToDataSetFilter do2ds; static vtkFieldDataToAttributeDataFilter fd2ad; static vtkRectilinearGridGeometryFilter plane; static vtkWarpVector warper; static vtkDataSetMapper planeMapper; static vtkActor planeActor; static vtkPlane cutPlane; static vtkCutter planeCut; static vtkDataSetMapper cutMapper; static vtkActor cutActor; static vtkContourFilter iso; static vtkPolyDataNormals normals; static vtkPolyDataMapper isoMapper; static vtkActor isoActor; static vtkStreamLine streamer; static vtkTubeFilter streamTube; static vtkPolyDataMapper mapStreamTube; static vtkActor streamTubeActor; static vtkOutlineFilter outline; static vtkPolyDataMapper outlineMapper; static vtkActor outlineActor; static vtkRenderer ren1; static vtkRenderWindow renWin; static vtkRenderWindowInteractor iren; ///<summary> A Get Method for Static Variables </summary> public static string GetVTK_DATA_ROOT() { return VTK_DATA_ROOT; } ///<summary> A Set Method for Static Variables </summary> public static void SetVTK_DATA_ROOT(string toSet) { VTK_DATA_ROOT = toSet; } ///<summary> A Get Method for Static Variables </summary> public static int Getthreshold() { return threshold; } ///<summary> A Set Method for Static Variables </summary> public static void Setthreshold(int toSet) { threshold = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkDataSetReader Getreader() { return reader; } ///<summary> A Set Method for Static Variables </summary> public static void Setreader(vtkDataSetReader toSet) { reader = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkDataSetToDataObjectFilter Getds2do() { return ds2do; } ///<summary> A Set Method for Static Variables </summary> public static void Setds2do(vtkDataSetToDataObjectFilter toSet) { ds2do = toSet; } ///<summary> A Get Method for Static Variables </summary> public static string GettryCatchError() { return tryCatchError; } ///<summary> A Set Method for Static Variables </summary> public static void SettryCatchError(string toSet) { tryCatchError = toSet; } ///<summary> A Get Method for Static Variables </summary> public static StreamWriter Getchannel() { return channel; } ///<summary> A Set Method for Static Variables </summary> public static void Setchannel(StreamWriter toSet) { channel = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkDataObjectWriter Getwriter() { return writer; } ///<summary> A Set Method for Static Variables </summary> public static void Setwriter(vtkDataObjectWriter toSet) { writer = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkDataObjectReader Getdor() { return dor; } ///<summary> A Set Method for Static Variables </summary> public static void Setdor(vtkDataObjectReader toSet) { dor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkDataObjectToDataSetFilter Getdo2ds() { return do2ds; } ///<summary> A Set Method for Static Variables </summary> public static void Setdo2ds(vtkDataObjectToDataSetFilter toSet) { do2ds = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkFieldDataToAttributeDataFilter Getfd2ad() { return fd2ad; } ///<summary> A Set Method for Static Variables </summary> public static void Setfd2ad(vtkFieldDataToAttributeDataFilter toSet) { fd2ad = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRectilinearGridGeometryFilter Getplane() { return plane; } ///<summary> A Set Method for Static Variables </summary> public static void Setplane(vtkRectilinearGridGeometryFilter toSet) { plane = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkWarpVector Getwarper() { return warper; } ///<summary> A Set Method for Static Variables </summary> public static void Setwarper(vtkWarpVector toSet) { warper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkDataSetMapper GetplaneMapper() { return planeMapper; } ///<summary> A Set Method for Static Variables </summary> public static void SetplaneMapper(vtkDataSetMapper toSet) { planeMapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetplaneActor() { return planeActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetplaneActor(vtkActor toSet) { planeActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPlane GetcutPlane() { return cutPlane; } ///<summary> A Set Method for Static Variables </summary> public static void SetcutPlane(vtkPlane toSet) { cutPlane = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkCutter GetplaneCut() { return planeCut; } ///<summary> A Set Method for Static Variables </summary> public static void SetplaneCut(vtkCutter toSet) { planeCut = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkDataSetMapper GetcutMapper() { return cutMapper; } ///<summary> A Set Method for Static Variables </summary> public static void SetcutMapper(vtkDataSetMapper toSet) { cutMapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetcutActor() { return cutActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetcutActor(vtkActor toSet) { cutActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkContourFilter Getiso() { return iso; } ///<summary> A Set Method for Static Variables </summary> public static void Setiso(vtkContourFilter toSet) { iso = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataNormals Getnormals() { return normals; } ///<summary> A Set Method for Static Variables </summary> public static void Setnormals(vtkPolyDataNormals toSet) { normals = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetisoMapper() { return isoMapper; } ///<summary> A Set Method for Static Variables </summary> public static void SetisoMapper(vtkPolyDataMapper toSet) { isoMapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetisoActor() { return isoActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetisoActor(vtkActor toSet) { isoActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkStreamLine Getstreamer() { return streamer; } ///<summary> A Set Method for Static Variables </summary> public static void Setstreamer(vtkStreamLine toSet) { streamer = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkTubeFilter GetstreamTube() { return streamTube; } ///<summary> A Set Method for Static Variables </summary> public static void SetstreamTube(vtkTubeFilter toSet) { streamTube = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetmapStreamTube() { return mapStreamTube; } ///<summary> A Set Method for Static Variables </summary> public static void SetmapStreamTube(vtkPolyDataMapper toSet) { mapStreamTube = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetstreamTubeActor() { return streamTubeActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetstreamTubeActor(vtkActor toSet) { streamTubeActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkOutlineFilter Getoutline() { return outline; } ///<summary> A Set Method for Static Variables </summary> public static void Setoutline(vtkOutlineFilter toSet) { outline = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyDataMapper GetoutlineMapper() { return outlineMapper; } ///<summary> A Set Method for Static Variables </summary> public static void SetoutlineMapper(vtkPolyDataMapper toSet) { outlineMapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetoutlineActor() { return outlineActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetoutlineActor(vtkActor toSet) { outlineActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderer Getren1() { return ren1; } ///<summary> A Set Method for Static Variables </summary> public static void Setren1(vtkRenderer toSet) { ren1 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderWindow GetrenWin() { return renWin; } ///<summary> A Set Method for Static Variables </summary> public static void SetrenWin(vtkRenderWindow toSet) { renWin = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderWindowInteractor Getiren() { return iren; } ///<summary> A Set Method for Static Variables </summary> public static void Setiren(vtkRenderWindowInteractor toSet) { iren = toSet; } ///<summary>Deletes all static objects created</summary> public static void deleteAllVTKObjects() { //clean up vtk objects if(reader!= null){reader.Dispose();} if(ds2do!= null){ds2do.Dispose();} if(writer!= null){writer.Dispose();} if(dor!= null){dor.Dispose();} if(do2ds!= null){do2ds.Dispose();} if(fd2ad!= null){fd2ad.Dispose();} if(plane!= null){plane.Dispose();} if(warper!= null){warper.Dispose();} if(planeMapper!= null){planeMapper.Dispose();} if(planeActor!= null){planeActor.Dispose();} if(cutPlane!= null){cutPlane.Dispose();} if(planeCut!= null){planeCut.Dispose();} if(cutMapper!= null){cutMapper.Dispose();} if(cutActor!= null){cutActor.Dispose();} if(iso!= null){iso.Dispose();} if(normals!= null){normals.Dispose();} if(isoMapper!= null){isoMapper.Dispose();} if(isoActor!= null){isoActor.Dispose();} if(streamer!= null){streamer.Dispose();} if(streamTube!= null){streamTube.Dispose();} if(mapStreamTube!= null){mapStreamTube.Dispose();} if(streamTubeActor!= null){streamTubeActor.Dispose();} if(outline!= null){outline.Dispose();} if(outlineMapper!= null){outlineMapper.Dispose();} if(outlineActor!= null){outlineActor.Dispose();} if(ren1!= null){ren1.Dispose();} if(renWin!= null){renWin.Dispose();} if(iren!= null){iren.Dispose();} } } //--- end of script --//
using System; using System.Collections.Generic; using System.Text; using System.Linq; namespace Deduplication { class Block { private readonly string buffer; private readonly int bufferHash; private int referenceCount; public Block(string str) { this.buffer = str; this.bufferHash = str.GetHashCode(); this.referenceCount = 0; } public Block Reference() { ++this.referenceCount; return this; } public bool Free() { --this.referenceCount; return this.referenceCount == 0; } public Block Copy() { return new Block(this.buffer); } public override int GetHashCode() { return this.bufferHash; } public override bool Equals(object obj) { var other = obj as Block; if (this.bufferHash != other.bufferHash) { return false; } return this.buffer == other.buffer; } } class File { private readonly List<Block> blocks; public File() { this.blocks = new List<Block>(); } public void Append(Block[] blocks) { foreach (var b in blocks) { this.blocks.Add(b.Reference()); } } public int Size() { return this.blocks.Count; } public int Remove() { int freed = 0; foreach (var b in this.blocks) { if (b.Free()) { ++freed; } } return freed; } public List<Block> GetBlocks() { return this.blocks; } } class Filesystem { private const int BLOCK_SIZE = 256; private readonly Dictionary<string, File> files; private int allocatedBlocksCount; public Filesystem() { this.files = new Dictionary<string, File>(); this.allocatedBlocksCount = 0; } public void Append(string filename, string content) { var blocks = Filesystem.SplitBlocks(content); File file; if (!this.files.TryGetValue(filename, out file)) { file = new File(); this.files[filename] = file; } file.Append(blocks); this.allocatedBlocksCount += blocks.Length; } private static Block[] SplitBlocks(string content) { var blocks = new Block[content.Length / Filesystem.BLOCK_SIZE]; for (int i = 0, j = 0; j < blocks.Length; i += Filesystem.BLOCK_SIZE, ++j) { blocks[j] = new Block(content.Substring(i, Filesystem.BLOCK_SIZE)); } return blocks; } public void Remove(string filename) { File file; if(this.files.TryGetValue(filename, out file)) { this.allocatedBlocksCount -= file.Remove(); this.files.Remove(filename); } } public void Copy(string source, string destination) { File sourceFile; File destinationFile; this.PreCopy(source, destination, out sourceFile, out destinationFile); var blocks = sourceFile.GetBlocks() .Select(b => b.Copy()) .ToArray(); destinationFile.Append(blocks); this.allocatedBlocksCount += blocks.Length; } public void CoW(string source, string destination) { File sourceFile; File destinationFile; this.PreCopy(source, destination, out sourceFile, out destinationFile); var blocks = sourceFile.GetBlocks() .ToArray(); destinationFile.Append(blocks); } private void PreCopy(string sourceFilename, string destinationFilename, out File sourceFile, out File destinationFile) { if (!this.files.TryGetValue(sourceFilename, out sourceFile)) { sourceFile = new File(); this.files[sourceFilename] = sourceFile; } if (this.files.TryGetValue(destinationFilename, out destinationFile)) { destinationFile.Remove(); } destinationFile = new File(); this.files[destinationFilename] = destinationFile; } public void Dedup() { var dedup = new Dictionary<Block, Block>(); // C# HashSet is stupid foreach (var kvp in this.files) { var file = kvp.Value; var blocks = file.GetBlocks(); for(int i = 0; i < blocks.Count; ++i) { Block prevBlock; if(dedup.TryGetValue(blocks[i], out prevBlock)) { blocks[i].Free(); blocks[i] = prevBlock.Reference(); --this.allocatedBlocksCount; } else { dedup[blocks[i]] = blocks[i]; } } } } public int Usage() { return this.allocatedBlocksCount; } public int Size(string filename) { File file; if (!this.files.TryGetValue(filename, out file)) { return 0; } return file.Size(); } } class Program { static void Main() { var fs = new Filesystem(); var output = new StringBuilder(); while (true) { var line = Console.ReadLine(); if (line == "exit") { break; } var strs = line.Split(' '); if (strs[0] == "append") { fs.Append(strs[1], strs[2]); } else if (strs[0] == "copy") { fs.Copy(strs[1], strs[2]); } else if (strs[0] == "cow") { fs.CoW(strs[1], strs[2]); } else if (strs[0] == "remove") { fs.Remove(strs[1]); } else if (strs[0] == "dedup") { fs.Dedup(); } else if (strs[0] == "usage") { var usage = fs.Usage(); output.AppendLine(string.Format("{0} blocks are currently in use.", usage)); } else if (strs[0] == "size") { var size = fs.Size(strs[1]); output.AppendLine(string.Format("{0} is {1} blocks large.", strs[1], size)); } else { throw new NotSupportedException("No such command " + line); } } Console.WriteLine(output.ToString().Trim()); } } }
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "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 COPYRIGHT HOLDER OR * 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.Text; using XenAdmin.Core; namespace XenAdmin.Wlb { public class WlbScheduledTask : WlbConfigurationBase { private const string KEY_TASK_NAME = "TaskName"; private const string KEY_TASK_DESCRIPTION = "TaskDescription"; private const string KEY_TASK_ENABLED = "TaskEnabled"; private const string KEY_TASK_OWNER = "TaskOwner"; private const string KEY_TASK_LAST_RUN_RESULT = "TaskLastRunResult"; private const string KEY_TASK_LAST_TOUCHED_BY = "TaskLastTouchedBy"; private const string KEY_TASK_LAST_TOUCHED = "TaskLastTouched"; private const string KEY_TRIGGER_TYPE = "TriggerType"; private const string KEY_TRIGGER_DAYS_OF_WEEK = "TriggerDaysOfWeek"; private const string KEY_TRIGGER_EXECUTE_TIME = "TriggerExecuteTime"; private const string KEY_TRIGGER_LAST_RUN = "TriggerLastRun"; private const string KEY_TRIGGER_ENABLED_DATE = "TriggerEndabledDate"; private const string KEY_TRIGGER_DISABLED_DATE = "TriggerDisabledDate"; private const string KEY_DELETE_TASK = "TaskDelete"; private const string KEY_ACTION_TYPE = "ActionType"; /// <summary> /// Public enumeration describing the interval period of a WlbTaskTrigger /// </summary> public enum WlbTaskTriggerType : int { /// <summary> /// A single-shot trigger /// </summary> Once = 0, /// <summary> /// A trigger that occurs every day at a particular time /// </summary> Daily = 1, /// <summary> /// A trigger that occurs every week on a set of days at a particulat time /// </summary> Weekly = 2, /// <summary> /// A trigger that occurs once every month on a given date /// </summary> Monthly = 3 } public enum WlbTaskActionType : int { Unknown = 0, SetOptimizationMode = 1, ReportSubscription = 2 } /// <summary> /// Public enumeration of the days on which a weekly WlbTaskTrigger will execute /// </summary> [FlagsAttribute] public enum WlbTaskDaysOfWeek { /// <summary> /// None /// </summary> None = 0, /// <summary> /// Sunday /// </summary> Sunday = 1, /// <summary> /// Monday /// </summary> Monday = 2, /// <summary> /// Tuesday /// </summary> Tuesday = 4, /// <summary> /// Wednesday /// </summary> Wednesday = 8, /// <summary> /// Thursday /// </summary> Thursday = 16, /// <summary> /// Friday /// </summary> Friday = 32, /// <summary> /// Saturday /// </summary> Saturday = 64, /// <summary> /// All weekdays /// </summary> Weekends = Sunday | Saturday, /// <summary> /// Only weekend days /// </summary> Weekdays = Monday | Tuesday | Wednesday | Thursday | Friday, /// <summary> /// All days /// </summary> All = Weekdays | Weekends } public static string DaysOfWeekL10N(WlbTaskDaysOfWeek days) { switch (days) { case WlbTaskDaysOfWeek.Sunday: return Messages.SUNDAY_LONG; case WlbTaskDaysOfWeek.Monday: return Messages.MONDAY_LONG; case WlbTaskDaysOfWeek.Tuesday: return Messages.TUESDAY_LONG; case WlbTaskDaysOfWeek.Wednesday: return Messages.WEDNESDAY_LONG; case WlbTaskDaysOfWeek.Thursday: return Messages.THURSDAY_LONG; case WlbTaskDaysOfWeek.Friday: return Messages.FRIDAY_LONG; case WlbTaskDaysOfWeek.Saturday: return Messages.SATURDAY_LONG; case WlbTaskDaysOfWeek.Weekdays: return Messages.WLB_DAY_WEEKDAYS; case WlbTaskDaysOfWeek.Weekends: return Messages.WLB_DAY_WEEKENDS; case WlbTaskDaysOfWeek.All: return Messages.WLB_DAY_ALL; default: return ""; } } public static WlbPoolPerformanceMode GetTaskOptMode(WlbScheduledTask task) { WlbPoolPerformanceMode mode = WlbPoolPerformanceMode.MaximizePerformance; if (task.TaskParameters["OptMode"] == "0") { mode = WlbPoolPerformanceMode.MaximizePerformance; } else { mode = WlbPoolPerformanceMode.MaximizeDensity; } return mode; } public static string GetTaskExecuteTime(DateTime TaskExecuteTime) { return HelpersGUI.DateTimeToString(TaskExecuteTime, Messages.DATEFORMAT_HM, true); } /// <summary> /// Returns the offset minutes between Utc and local time /// Add this to local time to get UTC /// Subtract from UTC to get local time /// </summary> /// <returns>(double) number of minutes between Utc and Local time</returns> private static double LocalOffsetMinutes() { TimeSpan difference = DateTime.UtcNow.Subtract(DateTime.Now); return difference.TotalMinutes; } /// <summary> /// Accepts a client's local time DayOfWeek and ExecuteTime of a scheduled task /// and returns the DaysOfWeek and ExecuteTime adjusted to UTC time /// </summary> /// <param name="LocalDaysOfWeek">Task's DaysOfWeek value in local time</param> /// <param name="LocalExecuteTime">Task's ExecuteTime in local time</param> /// <param name="UtcDaysOfWeek">(Output) Task's DaysOfWeek value adjusted to UTC</param> /// <param name="UtcExecuteTime">(Output) Task's ExecuteTime value adjusted to UTC</param> public static void GetUTCTaskTimes(WlbScheduledTask.WlbTaskDaysOfWeek LocalDaysOfWeek, DateTime LocalExecuteTime, out WlbScheduledTask.WlbTaskDaysOfWeek UtcDaysOfWeek, out DateTime UtcExecuteTime) { UtcDaysOfWeek = LocalDaysOfWeek; UtcExecuteTime = LocalExecuteTime.AddMinutes(LocalOffsetMinutes()); if (DateTime.Compare(LocalExecuteTime.Date, UtcExecuteTime.Date) < 0) { UtcDaysOfWeek = WlbScheduledTask.NextDay(LocalDaysOfWeek); } else if (DateTime.Compare(LocalExecuteTime.Date, UtcExecuteTime.Date) > 0) { UtcDaysOfWeek = WlbScheduledTask.PreviousDay(LocalDaysOfWeek); } } /// <summary> /// Accepts UTC DayOfWeek and ExecuteTime of a scheduled task /// and returns the DaysOfWeek and ExecuteTime adjusted to client's local time /// </summary> /// <param name="UtcDaysOfWeek">Task's DaysOfWeek value in UTC</param> /// <param name="UtcExecuteTime">Task's ExecuteTime in UTC</param> /// <param name="LocalDaysOfWeek">(Output) Task's DaysOfWeek value adjusted to local time</param> /// <param name="LocalExecuteTime">(Output) Task's ExecuteTime value adjusted to local time</param> public static void GetLocalTaskTimes(WlbScheduledTask.WlbTaskDaysOfWeek UtcDaysOfWeek, DateTime UtcExecuteTime, out WlbScheduledTask.WlbTaskDaysOfWeek LocalDaysOfWeek, out DateTime LocalExecuteTime) { LocalDaysOfWeek = UtcDaysOfWeek; LocalExecuteTime = UtcExecuteTime.AddMinutes(LocalOffsetMinutes() * -1); if (UtcDaysOfWeek != WlbTaskDaysOfWeek.None && UtcDaysOfWeek != WlbTaskDaysOfWeek.All && UtcDaysOfWeek != WlbTaskDaysOfWeek.Weekdays && UtcDaysOfWeek != WlbTaskDaysOfWeek.Weekends) { if (DateTime.Compare(UtcExecuteTime.Date, LocalExecuteTime.Date) < 0) { LocalDaysOfWeek = WlbScheduledTask.NextDay(UtcDaysOfWeek); } else if (DateTime.Compare(UtcExecuteTime.Date, LocalExecuteTime.Date) > 0) { LocalDaysOfWeek = WlbScheduledTask.PreviousDay(UtcDaysOfWeek); } } } public static WlbTaskDaysOfWeek NextDay(WlbTaskDaysOfWeek daysOfWeek) { // Doing some hackery here to shift days in the enumeration switch (daysOfWeek) { case WlbTaskDaysOfWeek.Saturday: { return WlbTaskDaysOfWeek.Sunday; } case WlbTaskDaysOfWeek.Weekends: { return (WlbTaskDaysOfWeek.Sunday | WlbTaskDaysOfWeek.Monday); } case WlbTaskDaysOfWeek.Weekdays: { return (WlbTaskDaysOfWeek.Tuesday | WlbTaskDaysOfWeek.Wednesday | WlbTaskDaysOfWeek.Thursday | WlbTaskDaysOfWeek.Friday | WlbTaskDaysOfWeek.Saturday); } case WlbTaskDaysOfWeek.All: { return daysOfWeek; } // single days, Sunday through Friday, which can easily be // shifted back by one. This also handles None (0). default: { //do the circular shift of rightmost 7 bits, discard the rest int tempDays = (int)daysOfWeek; tempDays = (tempDays << 1 | tempDays >> 6) & 0x0000007F; return (WlbTaskDaysOfWeek)tempDays; //return (WlbTaskDaysOfWeek)(((int)daysOfWeek) * 2); } } } public static WlbTaskDaysOfWeek PreviousDay(WlbTaskDaysOfWeek daysOfWeek) { // Doing some hackery here to shift days in the enumeration switch (daysOfWeek) { case WlbTaskDaysOfWeek.Sunday: { return WlbTaskDaysOfWeek.Saturday; } case WlbTaskDaysOfWeek.Weekends: { return (WlbTaskDaysOfWeek.Friday | WlbTaskDaysOfWeek.Saturday); } case WlbTaskDaysOfWeek.Weekdays: { return (WlbTaskDaysOfWeek.Sunday | WlbTaskDaysOfWeek.Monday | WlbTaskDaysOfWeek.Tuesday | WlbTaskDaysOfWeek.Wednesday | WlbTaskDaysOfWeek.Thursday); } case WlbTaskDaysOfWeek.All: { return daysOfWeek; } // single days, monday through saturday, which can easily be // shifted back by one. This also handles None (0). default: { //do the circular shift of rightmost 7 bits, discard the rest int tempDays = (int)daysOfWeek; tempDays = (tempDays >> 1 | tempDays << 6) & 0x0000007F; return (WlbTaskDaysOfWeek)tempDays; //return (WlbTaskDaysOfWeek)(((int)daysOfWeek) / 2); } } } public static WlbScheduledTask.WlbTaskDaysOfWeek ConvertToWlbTaskDayOfWeek(DayOfWeek dayOfWeek) { return (WlbScheduledTask.WlbTaskDaysOfWeek)(Math.Pow(2,(int)dayOfWeek) % 127); } public static DayOfWeek ConvertFromWlbTaskDayOfWeek(WlbScheduledTask.WlbTaskDaysOfWeek wlbDayOfWeek) { return (DayOfWeek)(Math.Log((int)wlbDayOfWeek, 2)); } public WlbScheduledTask(string TaskId) { base.Configuration = new Dictionary<string, string>(); base.ItemId = TaskId; //Define the key base base.KeyBase = WlbConfigurationKeyBase.schedTask; //Define the known keys WlbConfigurationKeys = new List<string>(new string[] { KEY_TASK_NAME, KEY_TASK_DESCRIPTION, KEY_TASK_ENABLED, KEY_TASK_OWNER, KEY_TASK_LAST_RUN_RESULT, KEY_TASK_LAST_TOUCHED_BY, KEY_TASK_LAST_TOUCHED, KEY_TRIGGER_TYPE, KEY_TRIGGER_DAYS_OF_WEEK, KEY_TRIGGER_EXECUTE_TIME, KEY_TRIGGER_LAST_RUN, KEY_TRIGGER_ENABLED_DATE, KEY_TRIGGER_DISABLED_DATE, KEY_DELETE_TASK, KEY_ACTION_TYPE }); } public bool DeleteTask { get { return GetConfigValueBool(BuildComplexKey(KEY_DELETE_TASK)); } set { SetConfigValueBool(BuildComplexKey(KEY_DELETE_TASK), value, true); } } public string Name { get { return GetConfigValueString(BuildComplexKey(KEY_TASK_NAME)); } set { SetConfigValueString(BuildComplexKey(KEY_TASK_NAME), value, true); } } public string Description { get { return GetConfigValueString(BuildComplexKey(KEY_TASK_DESCRIPTION)); } set { SetConfigValueString(BuildComplexKey(KEY_TASK_DESCRIPTION), value, true); } } public bool Enabled { get { return GetConfigValueBool(BuildComplexKey(KEY_TASK_ENABLED)); } set { SetConfigValueBool(BuildComplexKey(KEY_TASK_ENABLED), value, true); } } public string Owner { get { return GetConfigValueString(BuildComplexKey(KEY_TASK_OWNER)); } set { SetConfigValueString(BuildComplexKey(KEY_TASK_OWNER), value, true); } } public bool LastRunResult { get { return GetConfigValueBool(BuildComplexKey(KEY_TASK_LAST_RUN_RESULT)); } set { SetConfigValueBool(BuildComplexKey(KEY_TASK_LAST_RUN_RESULT), value, true); } } public string LastTouchedBy { get { return GetConfigValueString(BuildComplexKey(KEY_TASK_LAST_TOUCHED_BY)); } set { SetConfigValueString(BuildComplexKey(KEY_TASK_LAST_TOUCHED_BY), value, true); } } public DateTime LastTouched { get { return GetConfigValueUTCDateTime(BuildComplexKey(KEY_TASK_LAST_TOUCHED)); } set { SetConfigValueUTCDateTime(BuildComplexKey(KEY_TASK_LAST_TOUCHED), value, true); } } public WlbTaskTriggerType TriggerInterval { get { return (WlbTaskTriggerType)GetConfigValueInt(BuildComplexKey(KEY_TRIGGER_TYPE)); } set { SetConfigValueInt(BuildComplexKey(KEY_TRIGGER_TYPE), (int)value, true); } } public WlbTaskDaysOfWeek DaysOfWeek { get { return (WlbTaskDaysOfWeek)GetConfigValueInt(BuildComplexKey(KEY_TRIGGER_DAYS_OF_WEEK)); } set { SetConfigValueInt(BuildComplexKey(KEY_TRIGGER_DAYS_OF_WEEK), (int)value, true); } } public DateTime ExecuteTime { get { return GetConfigValueUTCDateTime(BuildComplexKey(KEY_TRIGGER_EXECUTE_TIME)); } set { SetConfigValueUTCDateTime(BuildComplexKey(KEY_TRIGGER_EXECUTE_TIME), value, true); } } public DateTime LastRunDate { get { return GetConfigValueUTCDateTime(BuildComplexKey(KEY_TRIGGER_LAST_RUN)); } set { SetConfigValueUTCDateTime(BuildComplexKey(KEY_TRIGGER_LAST_RUN), value, true); } } public DateTime EnableDate { get { return GetConfigValueUTCDateTime(BuildComplexKey(KEY_TRIGGER_ENABLED_DATE)); } set { SetConfigValueUTCDateTime(BuildComplexKey(KEY_TRIGGER_ENABLED_DATE), value, true); } } public DateTime DisableTime { get { return GetConfigValueUTCDateTime(BuildComplexKey(KEY_TRIGGER_DISABLED_DATE)); } set { SetConfigValueUTCDateTime(BuildComplexKey(KEY_TRIGGER_DISABLED_DATE), value, true); } } public WlbTaskActionType ActionType { get { return (WlbTaskActionType)GetConfigValueInt(BuildComplexKey(KEY_ACTION_TYPE)); } set { SetConfigValueInt(BuildComplexKey(KEY_ACTION_TYPE), (int)value, true); } } public Dictionary<string, string> TaskParameters { get { return GetOtherParameters(); } set { SetOtherParameters(value); } } public void AddTaskParameter(string key, string value) { SetOtherParameter(key, value); } public int TaskId { get { int taskId = 0; Int32.TryParse(ItemId, out taskId); return taskId; } } public WlbScheduledTask Clone() { WlbScheduledTask newTask = new WlbScheduledTask(this.TaskId.ToString()); newTask.ActionType = this.ActionType; newTask.DaysOfWeek = this.DaysOfWeek; newTask.DeleteTask = this.DeleteTask; newTask.Description = this.Description; newTask.DisableTime = this.DisableTime; newTask.Enabled = this.Enabled; newTask.EnableDate = this.EnableDate; newTask.ExecuteTime = this.ExecuteTime; newTask.LastRunDate = this.LastRunDate; newTask.LastRunResult = this.LastRunResult; newTask.LastTouched = this.LastTouched; newTask.LastTouchedBy = this.LastTouchedBy; newTask.Name = this.Name; newTask.Owner = this.Owner; newTask.TaskParameters = this.TaskParameters; newTask.TriggerInterval = this.TriggerInterval; return newTask; } } public class WlbScheduledTasks { private Dictionary<string, WlbScheduledTask> _tasks = new Dictionary<string, WlbScheduledTask>(); public WlbScheduledTasks() { ;} /// <summary> /// Exposes the actual list of WlbScheduledTasks /// </summary> public Dictionary<string, WlbScheduledTask> TaskList { set { _tasks = value; } get { return _tasks; } } /// <summary> /// Exposes a sorted version of the WlbScheduledTasks collection /// </summary> public SortedDictionary<int, WlbScheduledTask> SortedTaskList { get { SortedDictionary<int, WlbScheduledTask> sortedTasks = new SortedDictionary<int, WlbScheduledTask>(); foreach (WlbScheduledTask task in _tasks.Values) { if (!task.DeleteTask) { WlbScheduledTask.WlbTaskDaysOfWeek localDaysOfWeek; DateTime localExecuteTime; WlbScheduledTask.GetLocalTaskTimes((task.DaysOfWeek), task.ExecuteTime, out localDaysOfWeek, out localExecuteTime); int sortKey = GetSortKey(localDaysOfWeek, localExecuteTime); //if the task is disabled, bump the sort key to prevent conficts // with any new tasks. This could start to get wierd after 100 duplicate // disabled tasks, but then it will be the user's problem. if (!task.Enabled) { sortKey += 1; while (sortedTasks.ContainsKey(sortKey)) { sortKey += 1; } } WlbScheduledTask virtualTask = task.Clone(); virtualTask.DaysOfWeek = task.DaysOfWeek; if (!sortedTasks.ContainsKey(sortKey)) { sortedTasks.Add(sortKey, virtualTask); } } } return sortedTasks; } } /// <summary> /// Exposes a virtual representation of the WlbScheduledTasks collection, in which aggregate days /// are separated into individual days. The entire list is also presorted chronologically. /// </summary> public SortedDictionary<int, WlbScheduledTask> VirtualTaskList { get { SortedDictionary<int, WlbScheduledTask> virtualTasks = new SortedDictionary<int, WlbScheduledTask>(); foreach (WlbScheduledTask task in _tasks.Values) { if (!task.DeleteTask) { foreach (WlbScheduledTask.WlbTaskDaysOfWeek dayValue in Enum.GetValues(typeof(WlbScheduledTask.WlbTaskDaysOfWeek))) { if (dayValue != WlbScheduledTask.WlbTaskDaysOfWeek.None && dayValue != WlbScheduledTask.WlbTaskDaysOfWeek.All && dayValue != WlbScheduledTask.WlbTaskDaysOfWeek.Weekdays && dayValue != WlbScheduledTask.WlbTaskDaysOfWeek.Weekends && ((task.DaysOfWeek & dayValue) == dayValue)) { DateTime localExecuteTime; WlbScheduledTask.WlbTaskDaysOfWeek localDaysOfWeek; WlbScheduledTask.GetLocalTaskTimes((task.DaysOfWeek & dayValue), task.ExecuteTime, out localDaysOfWeek, out localExecuteTime); int sortKey = GetSortKey(localDaysOfWeek, localExecuteTime); //if the task is disabled, bump the sort key to prevent conficts // with any new tasks. This could start to get wierd after 100 duplicate // disabled tasks, but then it will be the user's problem. if (!task.Enabled) { sortKey += 1; while (virtualTasks.ContainsKey(sortKey)) { sortKey += 1; } } WlbScheduledTask virtualTask = task.Clone(); virtualTask.DaysOfWeek = dayValue; if (!virtualTasks.ContainsKey(sortKey)) { virtualTasks.Add(sortKey, virtualTask); } } } } } return virtualTasks; } } /// <summary> /// Creates an artificial sort key that is used to sort the presentation of scheduled tasks. /// </summary> /// <param name="localDaysOfWeek">WlbScheduledTask.DaysOfWeek enumeration of the task denoting on which days it will execute</param> /// <param name="localExecuteTime">DateTime execute time of the task denoting on when the task </param> /// <returns></returns> private static int GetSortKey(WlbScheduledTask.WlbTaskDaysOfWeek localDaysOfWeek, DateTime localExecuteTime) { int sortKey; //The day of week is the primary sort item switch(localDaysOfWeek) { //Put ALL tasks at the front of the list case WlbScheduledTask.WlbTaskDaysOfWeek.All: { sortKey = 0; break; } //Next are WEEKDAY tasks case WlbScheduledTask.WlbTaskDaysOfWeek.Weekdays: { sortKey = 200000; break; } //Next are WEEKEND tasks case WlbScheduledTask.WlbTaskDaysOfWeek.Weekends: { sortKey = 400000; break; } //Finally, single-day tasks default: { sortKey = (int)localDaysOfWeek * 1000000; break; } } //Add the execute time of day as a secondary sort item //Multiply it by 100 to allow room for disabled tasks sortKey += (int)localExecuteTime.TimeOfDay.TotalMinutes * 100; return sortKey; } public WlbScheduledTasks(Dictionary<string,string> Configuration) { foreach (string key in Configuration.Keys) { if (key.StartsWith("schedTask_")) { string[] keyElements = key.Split('_'); string taskId = keyElements[1]; if (!_tasks.ContainsKey(taskId)) { _tasks.Add(taskId, new WlbScheduledTask(taskId)); _tasks[taskId].AddParameter(key, Configuration[key]); } else { _tasks[taskId].AddParameter(key, Configuration[key]); } } } } public Dictionary<string, string> ToDictionary() { Dictionary<string, string> collectionDictionary = null; foreach (WlbScheduledTask scheduleTask in _tasks.Values) { Dictionary<string, string> taskDictionary = scheduleTask.ToDictionary(); foreach (string key in taskDictionary.Keys) { if (null == collectionDictionary) { collectionDictionary = new Dictionary<string, string>(); } collectionDictionary.Add(key, taskDictionary[key]); } foreach (string key in scheduleTask.TaskParameters.Keys) { string complexKey = string.Format("{0}_{1}_{2}", scheduleTask.KeyBase, scheduleTask.TaskId.ToString(), key); if (collectionDictionary.ContainsKey(complexKey)) { collectionDictionary[complexKey] = scheduleTask.TaskParameters[key]; } else { collectionDictionary.Add(complexKey, scheduleTask.TaskParameters[key]); } } } return collectionDictionary; } public WlbScheduledTask GetNextExecutingTask() { WlbScheduledTask firstTask = null; int currentTimeSortKey = GetSortKey(WlbScheduledTask.ConvertToWlbTaskDayOfWeek(DateTime.Now.DayOfWeek), DateTime.Now); foreach (int key in this.VirtualTaskList.Keys) { //only consider Enabled tasks if (this.VirtualTaskList[key].Enabled) { if (null == firstTask) { firstTask = this.VirtualTaskList[key]; } if (key > currentTimeSortKey) { return this.VirtualTaskList[key]; } } } //we are still here, so we have not found the next task. this means that we // need to account for week wrapping. This shoudl be the first task of the Virtual // Task List return firstTask; } public WlbScheduledTask GetLastExecutingTask() { int[] taskKeys = new int[this.VirtualTaskList.Keys.Count]; this.VirtualTaskList.Keys.CopyTo(taskKeys,0); WlbScheduledTask lastTask = this.VirtualTaskList[taskKeys[taskKeys.Length-1]]; int currentTimeSortKey = GetSortKey(WlbScheduledTask.ConvertToWlbTaskDayOfWeek(DateTime.Now.DayOfWeek), DateTime.Now); for (int i = taskKeys.Length-1; i>=0; i--) { //Only consider Enabled tasks if (this.VirtualTaskList[taskKeys[i]].Enabled) { if (taskKeys[i] < currentTimeSortKey) { return this.VirtualTaskList[taskKeys[i]]; } } } //we are still here, so we have not found the previous task. this means that we // need to account for week wrapping. This should be the last task of the Virtual // Task List return lastTask; } public WlbPoolPerformanceMode GetCurrentScheduledPerformanceMode() { WlbScheduledTask lastTask = GetLastExecutingTask(); return (WlbPoolPerformanceMode)int.Parse(lastTask.TaskParameters["OptMode"]); } } }
using System; using NUnit.Framework; using Shouldly; using StructureMap.Testing.Widget; namespace StructureMap.Testing.Configuration.DSL { [TestFixture] public class AddInstanceTester { #region Setup/Teardown [SetUp] public void SetUp() { container = new Container(registry => { registry.Scan(x => x.AssemblyContainingType<ColorWidget>()); // Add an instance with properties registry.For<IWidget>() .Add<ColorWidget>() .Named("DarkGreen") .Ctor<string>("color").Is("DarkGreen"); // Add an instance by specifying the ConcreteKey registry.For<IWidget>() .Add<ColorWidget>() .Named("Purple") .Ctor<string>("color").Is("Purple"); registry.For<IWidget>().Add<AWidget>(); }); } #endregion private IContainer container; [Test] public void AddAnInstanceWithANameAndAPropertySpecifyingConcreteKey() { var widget = (ColorWidget) container.GetInstance<IWidget>("Purple"); widget.Color.ShouldBe("Purple"); } [Test] public void AddAnInstanceWithANameAndAPropertySpecifyingConcreteType() { var widget = (ColorWidget) container.GetInstance<IWidget>("DarkGreen"); widget.Color.ShouldBe("DarkGreen"); } [Test] public void AddInstanceAndOverrideTheConcreteTypeForADependency() { IContainer container = new Container(x => { x.For<Rule>().Add<WidgetRule>() .Named("AWidgetRule") .Ctor<IWidget>().IsSpecial(i => i.Type<AWidget>()); }); container.GetInstance<Rule>("AWidgetRule") .IsType<WidgetRule>() .Widget.IsType<AWidget>(); } // SAMPLE: named-instance [Test] public void SimpleCaseWithNamedInstance() { container = new Container(x => { x.For<IWidget>().Add<AWidget>().Named("MyInstance"); }); // retrieve an instance by name var widget = (AWidget) container.GetInstance<IWidget>("MyInstance"); widget.ShouldNotBeNull(); } // ENDSAMPLE [Test] public void SpecifyANewInstanceOverrideADependencyWithANamedInstance() { container = new Container(registry => { registry.For<Rule>().Add<ARule>().Named("Alias"); // Add an instance by specifying the ConcreteKey registry.For<IWidget>() .Add<ColorWidget>() .Named("Purple") .Ctor<string>("color").Is("Purple"); // Specify a new Instance, override a dependency with a named instance registry.For<Rule>().Add<WidgetRule>().Named("RuleThatUsesMyInstance") .Ctor<IWidget>("widget").IsSpecial(x => x.TheInstanceNamed("Purple")); }); container.GetInstance<Rule>("Alias").ShouldBeOfType<ARule>(); var rule = (WidgetRule) container.GetInstance<Rule>("RuleThatUsesMyInstance"); rule.Widget.As<ColorWidget>().Color.ShouldBe("Purple"); } [Test] public void SpecifyANewInstanceWithADependency() { // Specify a new Instance, create an instance for a dependency on the fly var instanceKey = "OrangeWidgetRule"; var theContainer = new Container(registry => { registry.For<Rule>().Add<WidgetRule>().Named(instanceKey) .Ctor<IWidget>().IsSpecial( i => i.Type<ColorWidget>().Ctor<string>("color").Is("Orange").Named("Orange")); }); theContainer.GetInstance<Rule>(instanceKey).As<WidgetRule>() .Widget.As<ColorWidget>() .Color.ShouldBe("Orange"); } [Test] public void UseAPreBuiltObjectWithAName() { // Return the specific instance when an IWidget named "Julia" is requested var julia = new CloneableWidget("Julia"); container = new Container(x => x.For<IWidget>().Add(julia).Named("Julia")); var widget1 = (CloneableWidget) container.GetInstance<IWidget>("Julia"); var widget2 = (CloneableWidget) container.GetInstance<IWidget>("Julia"); var widget3 = (CloneableWidget) container.GetInstance<IWidget>("Julia"); julia.ShouldBeTheSameAs(widget1); julia.ShouldBeTheSameAs(widget2); julia.ShouldBeTheSameAs(widget3); } } public class WidgetRule : Rule { private readonly IWidget _widget; public WidgetRule(IWidget widget) { _widget = widget; } public IWidget Widget { get { return _widget; } } public override bool Equals(object obj) { if (this == obj) return true; var widgetRule = obj as WidgetRule; if (widgetRule == null) return false; return Equals(_widget, widgetRule._widget); } public override int GetHashCode() { return _widget != null ? _widget.GetHashCode() : 0; } } public class WidgetThing : IWidget { #region IWidget Members public void DoSomething() { throw new NotImplementedException(); } #endregion } [Serializable] public class CloneableWidget : IWidget, ICloneable { private readonly string _name; public CloneableWidget(string name) { _name = name; } public string Name { get { return _name; } } #region ICloneable Members public object Clone() { return MemberwiseClone(); } #endregion #region IWidget Members public void DoSomething() { throw new NotImplementedException(); } #endregion } public class ARule : Rule { } }
using OpenKh.Command.ImgTool.Utils; using OpenKh.Common; using OpenKh.Imaging; using OpenKh.Kh2; using OpenKh.Kh2.Utils; using OpenKh.Tools.Common; using OpenKh.Tools.Common.Imaging; using OpenKh.Tools.Common.Wpf; using OpenKh.Tools.ImageViewer.Services; using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Windows; using Xe.Tools; using Xe.Tools.Wpf.Commands; using Xe.Tools.Wpf.Dialogs; namespace OpenKh.Tools.ImageViewer.ViewModels { public class ImageViewerViewModel : BaseNotifyPropertyChanged { private const int ZoomLevelFit = -1; private static readonly IImageFormatService _imageFormatService = new ImageFormatService(); private static readonly List<FileDialogFilter> OpenFilters = FileDialogFilterComposer .Compose() .AddExtensions("All supported images", GetAllSupportedExtensions()) .Concat(_imageFormatService.Formats.Select(x => FileDialogFilter.ByExtensions($"{x.Name} image", x.Extension))) .ToList() .AddAllFiles(); private static readonly List<FileDialogFilter> ExportToContainerFilters = FileDialogFilterComposer .Compose() .AddExtensions("All supported images for export", GetAllSupportedExtensions(x => x.IsCreationSupported && x.IsContainer)) .Concat(_imageFormatService.Formats.Where(x => x.IsCreationSupported && x.IsContainer).Select(x => FileDialogFilter.ByExtensions($"{x.Name} image", x.Extension))) .ToList() .AddAllFiles(); private static readonly List<FileDialogFilter> ExportToSingleImageFilters = FileDialogFilterComposer .Compose() .AddExtensions("All supported images for export", GetAllSupportedExtensions(x => x.IsCreationSupported)) .Concat(_imageFormatService.Formats.Where(x => x.IsCreationSupported).Select(x => FileDialogFilter.ByExtensions($"{x.Name} image", x.Extension))) .ToList() .AddAllFiles(); private static string ApplicationName = Utilities.GetApplicationName(); private Window Window => Application.Current.Windows.OfType<Window>().FirstOrDefault(x => x.IsActive); public string Title { get { var fileName = IsTool ? _toolInvokeDesc.Title : (Path.GetFileName(FileName) ?? "untitled"); return $"{fileName} | {ApplicationName}"; } } public bool IsTool => _toolInvokeDesc != null; public ImageViewerViewModel() { OpenCommand = new RelayCommand(x => { FileDialog.OnOpen(fileName => { LoadImage(fileName); }, OpenFilters); }, x => !IsTool); SaveCommand = new RelayCommand(x => { if (IsTool) { // Clear current bar entry content before saving. _toolInvokeDesc.SelectedEntry.Stream.SetLength(0); Save(_toolInvokeDesc.SelectedEntry.Stream); } else if (!string.IsNullOrEmpty(FileName)) { using (var stream = File.Open(FileName, FileMode.Create)) { Save(stream); } } else { SaveAsCommand.Execute(x); } }, x => ImageFormat != null); SaveAsCommand = new RelayCommand(x => { var filter = new List<FileDialogFilter>().AddExtensions($"{ImageFormat.Name} format", ImageFormat.Extension); FileDialog.OnSave(fileName => { using (var stream = File.Open(fileName, FileMode.Create)) { Save(stream); } }, filter); }, x => ImageFormat != null && !IsTool); ExitCommand = new RelayCommand(x => { Window.Close(); }, x => true); AboutCommand = new RelayCommand(x => { new AboutDialog(Assembly.GetExecutingAssembly()).ShowDialog(); }, x => true); ExportCurrentCommand = new RelayCommand(x => { var singleImage = Image?.Source; if (singleImage != null) { FileDialog.OnSave(fileName => { var imageFormat = _imageFormatService.GetFormatByFileName(fileName); if (imageFormat == null) { var extension = Path.GetExtension(fileName); MessageBox.Show($"The format with extension {extension} is not supported for export.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } File.OpenWrite(fileName).Using( stream => { if (imageFormat.IsContainer) { imageFormat.As<IImageMultiple>().Write( stream, new ImageFormatService.ImageContainer(new IImageRead[] { singleImage }) ); } else { imageFormat.As<IImageSingle>().Write( stream, singleImage ); } } ); }, ExportToSingleImageFilters); } }, x => true); ExportAllCommand = new RelayCommand(x => { var multiImages = GetImagesForExport(); if (multiImages.Any()) { FileDialog.OnSave(fileName => { var imageFormat = _imageFormatService.GetFormatByFileName(fileName); if (imageFormat == null) { var extension = Path.GetExtension(fileName); MessageBox.Show($"The format with extension {extension} is not supported for export.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } var imageContainer = new ImageFormatService.ImageContainer(multiImages); File.OpenWrite(fileName).Using(stream => imageFormat.As<IImageMultiple>().Write(stream, imageContainer)); }, ExportToContainerFilters); } }, x => true); ImportCommand = new RelayCommand( parameter => { AddImage(Enum.Parse<AddPosition>($"{parameter}")); }, x => IsMultipleImageFormat ); CreateNewImgzCommand = new RelayCommand( x => { if (IsSingleImageFormat || IsMultipleImageFormat) { if (MessageBoxResult.OK != MessageBox.Show("This will discard all of existing images.", null, MessageBoxButton.OKCancel, MessageBoxImage.Exclamation)) { return; } } FileName = null; EditImageList( currentImageList => { var newImage = CreateDummyImage(); return new EditResult { imageList = new IImageRead[] { newImage }, selection = newImage, }; } ); } ); ConvertToImgzCommand = new RelayCommand( x => { FileName = null; EditImageList( currentImageList => { return new EditResult { imageList = new IImageRead[] { Image.Source }, selection = Image.Source }; } ); }, x => IsSingleImageFormat ); InsertEmptyImageCommand = new RelayCommand( x => { AddEmptyImage(AddPosition.BeforeCurrent); }, x => IsMultipleImageFormat ); RemoveImageCommand = new RelayCommand( x => { EditImageList( currentImageList => { return new EditResult { imageList = currentImageList.Except(new IImageRead[] { Image?.Source }) }; } ); }, x => IsMultipleImageFormat && ImageContainer.Count >= 1 ); ConvertBitsPerPixelCommand = new RelayCommand( parameter => { try { EditImageList( currentImageList => { var sourceImage = Image.Source; var bpp = Convert.ToInt32(parameter); var newImage = ImgdBitmapUtil.ToImgd( sourceImage.CreateBitmap(), bpp, QuantizerFactory.MakeFrom( bpp, UsePngquant ?? false ) ); return new EditResult { imageList = currentImageList .Select(it => ReferenceEquals(it, sourceImage) ? newImage : it), selection = newImage, }; } ); } catch (Exception ex) { MessageBox.Show($"{ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } }, x => IsMultipleImageFormat && ImageContainer.Count >= 1 ); CheckQuant = new RelayCommand(x => { if (UsePngquant == true) { if (!File.Exists("pngquant.exe")) { UsePngquant = false; string _msg = "PNGQuant was not located in OpenKH's root folder.\n" + "Please acquire PNGQuant from the link below and\n" + "place it in the same folder as this viewer."; new MessageDialog(_msg, "https://pngquant.org/pngquant-windows.zip").ShowDialog(); OnPropertyChanged(nameof(UsePngquant)); } } }); ZoomLevel = ZoomLevelFit; } public bool IsMultipleImageFormat => _imageFormat != null ? _imageFormat.IsContainer : false; public bool IsSingleImageFormat => _imageFormat != null ? !_imageFormat.IsContainer : false; public bool? UsePngquant { get; set; } public ImageViewerViewModel(Stream stream) : this() { LoadImage(stream); } private string _fileName; private IImageFormat _imageFormat; private IImageContainer _imageContainer; private double _zoomLevel; private bool _zoomFit; private ImageViewModel _imageViewModel; private ImageContainerViewModel _imageContainerItems; private ToolInvokeDesc _toolInvokeDesc; public string FileName { get => _fileName; set { _fileName = value; OnPropertyChanged(nameof(Title)); } } public RelayCommand OpenCommand { get; set; } public RelayCommand CheckQuant { get; set; } public RelayCommand SaveCommand { get; set; } public RelayCommand SaveAsCommand { get; set; } public RelayCommand ExitCommand { get; set; } public RelayCommand AboutCommand { get; set; } public RelayCommand ExportCurrentCommand { get; set; } public RelayCommand ExportAllCommand { get; set; } public RelayCommand ImportCommand { get; set; } public RelayCommand CreateNewImgzCommand { get; } public RelayCommand ConvertToImgzCommand { get; private set; } public RelayCommand InsertEmptyImageCommand { get; private set; } public RelayCommand RemoveImageCommand { get; private set; } public RelayCommand ConvertBitsPerPixelCommand { get; private set; } public IEnumerable<KeyValuePair<string, double>> ZoomLevels { get; } = new double[] { 0.25, 0.33, 0.5, 0.75, 1, 1.25, 1.50, 1.75, 2, 2.5, 3, 4, 6, 8, 12, 16, 1 } .Select(x => new KeyValuePair<string, double>($"{x * 100.0}%", x)) .Concat(new KeyValuePair<string, double>[] { new KeyValuePair<string, double>("Fit", ZoomLevelFit) }) .ToArray(); private IImageFormat ImageFormat { get => _imageFormat; set { _imageFormat = value; OnPropertyChanged(nameof(ImageType)); OnPropertyChanged(nameof(ImageMultiple)); OnPropertyChanged(nameof(ImageSelectionVisibility)); OnPropertyChanged(nameof(SaveCommand)); OnPropertyChanged(nameof(SaveAsCommand)); } } private IImageContainer ImageContainer { get => _imageContainer; set { _imageContainer = value; ImageContainerItems = new ImageContainerViewModel(_imageContainer); } } public ImageViewModel Image { get => _imageViewModel; set { _imageViewModel = value; OnPropertyChanged(); OnPropertyChanged(nameof(ImageZoomWidth)); OnPropertyChanged(nameof(ImageZoomHeight)); } } public ImageContainerViewModel ImageContainerItems { get => _imageContainerItems; set { _imageContainerItems = value; OnPropertyChanged(); } } public string ImageType => _imageFormat?.Name ?? "Unknown"; public string ImageMultiple => _imageFormat != null ? _imageFormat.IsContainer ? "Multiple" : "Single" : null; public Visibility ImageSelectionVisibility => (_imageFormat?.IsContainer ?? false) ? Visibility.Visible : Visibility.Collapsed; public double ZoomLevel { get => _zoomLevel; set { _zoomLevel = value; ZoomFit = _zoomLevel <= 0; OnPropertyChanged(); OnPropertyChanged(nameof(ImageZoomWidth)); OnPropertyChanged(nameof(ImageZoomHeight)); } } public bool ZoomFit { get => _zoomFit; set { _zoomFit = value; OnPropertyChanged(); OnPropertyChanged(nameof(ImageFitVisibility)); OnPropertyChanged(nameof(ImageCustomZoomVisibility)); } } public double ImageZoomWidth => (Image?.Width * ZoomLevel) ?? 0; public double ImageZoomHeight => (Image?.Height * ZoomLevel) ?? 0; public Visibility ImageFitVisibility => ZoomFit ? Visibility.Visible : Visibility.Collapsed; public Visibility ImageCustomZoomVisibility => ZoomFit ? Visibility.Collapsed : Visibility.Visible; public void LoadImage(ToolInvokeDesc toolInvokeDesc) { _toolInvokeDesc = toolInvokeDesc; LoadImage(_toolInvokeDesc.SelectedEntry.Stream); } public void LoadImage(string fileName) { using (var stream = File.OpenRead(fileName)) { LoadImage(stream); FileName = fileName; } } private void LoadImage(Stream stream) { var imageFormat = _imageFormatService.GetFormatByContent(stream); if (imageFormat == null) throw new Exception("Image format not found for the given stream."); ImageFormat = imageFormat; if (ImageFormat.IsContainer) { ImageContainer = _imageFormat.As<IImageMultiple>().Read(stream); Image = ImageContainerItems.First(); } else { Image = new ImageViewModel(_imageFormat.As<IImageSingle>().Read(stream)); } } private IImageRead CreateDummyImage() => Imgd.Create( new System.Drawing.Size(128, 128), PixelFormat.Indexed8, new byte[128 * 128], Enumerable.Repeat((byte)0x80, 4 * 256).ToArray(), // gray color palette false ); class EditResult { internal IEnumerable<IImageRead> imageList; internal IImageRead selection; } private void EditImageList(Func<List<IImageRead>, EditResult> editor) { var currentImageList = (ImageContainer?.Images.ToList()) ?? new List<IImageRead>(); var currentIndex = currentImageList.IndexOf(Image?.Source); var editResult = editor(currentImageList); ImageContainer = new ImageFormatService.ImageContainer(editResult.imageList); if (ImageContainerItems.Any()) { if (editResult.selection != null) { Image = ImageContainerItems .FirstOrDefault(it => ReferenceEquals(editResult.selection, it.Source)); } else { Image = ImageContainerItems .Skip(currentIndex) .FirstOrDefault() ?? ImageContainerItems.Last(); } } else { Image = null; } ImageFormat = _imageFormatService.Formats.Single(it => it.Name == "IMGZ"); } enum AddPosition { BeforeCurrent, ReplaceCurrent, AfterCurrent, Last, } private void AddEmptyImage(AddPosition addPosition) { EditImageList( imageList => { var incomingImages = new IImageRead[] { CreateDummyImage() }; var position = Math.Max(0, imageList.IndexOf(Image?.Source)); switch (addPosition) { case AddPosition.BeforeCurrent: imageList.InsertRange(position, incomingImages); break; case AddPosition.AfterCurrent: imageList.InsertRange(position + 1, incomingImages); break; case AddPosition.Last: default: imageList.AddRange(incomingImages); break; } return new EditResult { imageList = imageList, selection = incomingImages.LastOrDefault(), }; } ); } private void AddImage(AddPosition addPosition) { FileDialog.OnOpen(fileName => { using (var stream = File.OpenRead(fileName)) { var imageFormat = _imageFormatService.GetFormatByContent(stream); if (imageFormat == null) throw new Exception("Image format not found for the given stream."); var incomingImages = imageFormat.IsContainer ? imageFormat.As<IImageMultiple>().Read(stream).Images : new IImageRead[] { imageFormat.As<IImageSingle>().Read(stream) }; EditImageList( imageList => { var position = Math.Max(0, imageList.IndexOf(Image?.Source)); var selectedImage = Image?.Source; switch (addPosition) { case AddPosition.BeforeCurrent: case AddPosition.ReplaceCurrent: imageList.InsertRange(position, incomingImages); break; case AddPosition.AfterCurrent: imageList.InsertRange(position + 1, incomingImages); break; case AddPosition.Last: default: imageList.AddRange(incomingImages); break; } if (addPosition == AddPosition.ReplaceCurrent) { imageList.Remove(selectedImage); } return new EditResult { imageList = imageList, selection = incomingImages.LastOrDefault(), }; } ); } }, OpenFilters); } public void Save(Stream stream) => Save(stream, ImageFormat); public void Save(Stream stream, IImageFormat imageFormat) { if (imageFormat.IsContainer) { imageFormat.As<IImageMultiple>().Write(stream, ImageContainer); } else { imageFormat.As<IImageSingle>().Write(stream, Image.Source); } } private static string GetAllSupportedExtensions(Func<IImageFormat, bool> filter = null) { filter = filter ?? (it => true); var extensions = _imageFormatService.Formats.Where(filter).Select(x => $"*.{x.Extension}"); return string.Join(";", extensions).Substring(2); } class RunCmd { private Process p; public string App => p.StartInfo.FileName; public int ExitCode => p.ExitCode; public RunCmd(string app, string arg) { var psi = new ProcessStartInfo(app, arg) { UseShellExecute = false, CreateNoWindow = true, }; var p = Process.Start(psi); p.WaitForExit(); this.p = p; } } private IEnumerable<IImageRead> GetImagesForExport() { if (ImageContainer != null) { // currently container (multiple images) format return ImageContainer.Images.ToArray(); } if (Image?.Source != null) { // currently single image format return new IImageRead[] { Image.Source }; } // no image loaded return new IImageRead[0]; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Security.AccessControl; using System.Security.Principal; using System.Text; using SIL.IO; using SIL.PlatformUtilities; using SIL.Threading; using SIL.WritingSystems.Migration; namespace SIL.WritingSystems { ///<summary> /// A system wide writing system repository. ///</summary> public class GlobalWritingSystemRepository : GlobalWritingSystemRepository<WritingSystemDefinition> { ///<summary> /// Initializes the global writing system repository. Migrates any ldml files if required, /// notifying of any changes of writing system id that occured during migration. ///</summary> public static GlobalWritingSystemRepository Initialize(Action<int, IEnumerable<LdmlMigrationInfo>> migrationHandler = null) { return InitializeWithBasePath(DefaultBasePath, migrationHandler); } ///<summary> /// This initializer is intended for tests as it allows setting of the basePath explicitly. ///</summary> internal static GlobalWritingSystemRepository InitializeWithBasePath(string basePath, Action<int, IEnumerable<LdmlMigrationInfo>> migrationHandler) { var migrator = new GlobalWritingSystemRepositoryMigrator(basePath, migrationHandler); if (migrator.NeedsMigration()) migrator.Migrate(); var globalRepo = new GlobalWritingSystemRepository(basePath); migrator.ResetRemovedProperties(globalRepo); return globalRepo; } protected internal GlobalWritingSystemRepository(string basePath) : base(basePath) { } protected override IWritingSystemFactory<WritingSystemDefinition> CreateWritingSystemFactory() { return new SldrWritingSystemFactory(); } } ///<summary> /// A system wide writing system repository. ///</summary> public abstract class GlobalWritingSystemRepository<T> : WritingSystemRepositoryBase<T>, IDisposable where T : WritingSystemDefinition { private const string Extension = ".ldml"; private readonly string _path; private readonly GlobalMutex _mutex; private readonly Dictionary<string, Tuple<DateTime, long>> _lastFileStats; private readonly HashSet<string> _addedWritingSystems; private static string _defaultBasePath; protected internal GlobalWritingSystemRepository(string basePath) { _lastFileStats = new Dictionary<string, Tuple<DateTime, long>>(StringComparer.OrdinalIgnoreCase); _addedWritingSystems = new HashSet<string>(StringComparer.OrdinalIgnoreCase); _path = CurrentVersionPath(basePath); if (!Directory.Exists(_path)) CreateGlobalWritingSystemRepositoryDirectory(_path); _mutex = new GlobalMutex(_path.Replace('\\', '_').Replace('/', '_')); _mutex.Initialize(); } private void UpdateDefinitions() { var ldmlDataMapper = new LdmlDataMapper(WritingSystemFactory); var removedIds = new HashSet<string>(WritingSystems.Keys); foreach (var file in Directory.GetFiles(PathToWritingSystems, $"*{Extension}").OrderBy(filename => filename)) { var fi = new FileInfo(file); string id = Path.GetFileNameWithoutExtension(file); Debug.Assert(id != null); T ws; if (WritingSystems.TryGetValue(id, out ws)) { // existing writing system // preserve this repo's changes if (!ws.IsChanged) { // for performance purposes, we check the last modified timestamp and file size to see if the file has changed // hopefully that is good enough for our purposes here if (_lastFileStats[id].Item1 != fi.LastWriteTime || _lastFileStats[id].Item2 != fi.Length) { var errorEncountered = false; // modified writing system if (!_addedWritingSystems.Contains(id)) { ldmlDataMapper.Read(file, ws, e => { errorEncountered = true; }); if (string.IsNullOrEmpty(ws.Id)) ws.Id = ws.LanguageTag; ws.AcceptChanges(); } // if an error was encountered in reading the file above, the file will have been moved _lastFileStats[id] = Tuple.Create( errorEncountered ? DateTime.MinValue : fi.LastWriteTime, errorEncountered ? 0 : fi.Length); } } removedIds.Remove(id); } else { // new writing system ws = WritingSystemFactory.Create(); var errorEncountered = false; ldmlDataMapper.Read(file, ws, e => { errorEncountered = true; }); ws.Id = ws.LanguageTag; ws.AcceptChanges(); WritingSystems[id] = ws; // if an error was encountered in reading the file above, the file will have been moved _lastFileStats[id] = Tuple.Create( errorEncountered ? DateTime.MinValue : fi.LastWriteTime, errorEncountered ? 0 : fi.Length); } } foreach (string id in removedIds) { // preserve this repo's changes if (!WritingSystems[id].IsChanged && !_addedWritingSystems.Contains(id)) base.Remove(id); } } ///<summary> /// The DefaultBasePath is %CommonApplicationData%\SIL\WritingSystemRepository /// On Windows 7 this is \ProgramData\SIL\WritingSystemRepository\ /// On Linux this must be in ~/.local/share so that it may be edited ///</summary> public static string DefaultBasePath { get { // This allows unit tests to set the _defaultBasePath (through reflection) if (string.IsNullOrEmpty(_defaultBasePath)) { string basePath = Platform.IsLinux ? Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) : Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); _defaultBasePath = Path.Combine(basePath, "SIL", "WritingSystemRepository"); } return _defaultBasePath; } } ///<summary> /// The CurrentVersionPath is %CommonApplicationData%\SIL\WritingSystemRepository\[CurrentLdmlVersion] /// e.g. On Windows 7 this is \ProgramData\SIL\WritingSystemRepository\1 ///</summary> public static string CurrentVersionPath(string basePath) { return Path.Combine(basePath, LdmlDataMapper.CurrentLdmlLibraryVersion.ToString(CultureInfo.InvariantCulture)); } public static void CreateGlobalWritingSystemRepositoryDirectory(string path) { DirectoryInfo di = Directory.CreateDirectory(path); if (!Platform.IsLinux && !path.StartsWith(Path.GetTempPath())) { // NOTE: GetAccessControl/ModifyAccessRule/SetAccessControl is not implemented in Mono DirectorySecurity ds = di.GetAccessControl(); var sid = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null); AccessRule rule = new FileSystemAccessRule(sid, FileSystemRights.Write | FileSystemRights.ReadAndExecute | FileSystemRights.Modify, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow); bool modified; ds.ModifyAccessRule(AccessControlModification.Add, rule, out modified); di.SetAccessControl(ds); } } public string PathToWritingSystems { get { return _path; } } /// <summary> /// Adds the writing system to the store or updates the store information about /// an already-existing writing system. Set should be called when there is a change /// that updates the IETF language tag information. /// </summary> public override void Set(T ws) { using (_mutex.Lock()) { UpdateDefinitions(); string oldStoreId = ws.Id; var isNewWs = WritingSystems.Count(kvp => kvp.Value.Id == ws.Id) == 0; base.Set(ws); //Renaming the file here is a bit ugly as the content has not yet been updated. Thus there //may be a mismatch between the filename and the contained rfc5646 tag. Doing it here however //helps us avoid having to deal with situations where a writing system id is changed to be //identical with the old id of another writing system. This could otherwise lead to dataloss. //The inconsistency is resolved on Save() if (oldStoreId != ws.Id && File.Exists(GetFilePathFromLanguageTag(oldStoreId))) File.Move(GetFilePathFromLanguageTag(oldStoreId), GetFilePathFromLanguageTag(ws.Id)); else if (isNewWs && !ws.IsChanged && !_addedWritingSystems.Contains(ws.Id)) _addedWritingSystems.Add(ws.Id); } } /// <summary> /// Gets the writing system object for the given Store ID /// </summary> public override T Get(string id) { using (_mutex.Lock()) { UpdateDefinitions(); return base.Get(id); } } /// <summary> /// This method will save the global store file in a temporary location while doing the base /// Replace (Remove/Set). This will leave the old file content available during the Save method so that /// it will round trip correctly. /// </summary> public override void Replace(string languageTag, T newWs) { using (new WsStasher(Path.Combine(PathToWritingSystems, languageTag + Extension))) { base.Replace(languageTag, newWs); } } /// <summary> /// Returns true if a writing system with the given Store ID exists in the store /// </summary> public override bool Contains(string id) { using (_mutex.Lock()) { UpdateDefinitions(); return base.Contains(id); } } /// <summary> /// Gives the total number of writing systems in the store /// </summary> public override int Count { get { using (_mutex.Lock()) { UpdateDefinitions(); return base.Count; } } } /// <summary> /// This is a new required interface member. We don't use it, and I hope we don't use anything which uses it! /// </summary> /// <param name="wsToConflate"></param> /// <param name="wsToConflateWith"></param> public override void Conflate(string wsToConflate, string wsToConflateWith) { using (_mutex.Lock()) { UpdateDefinitions(); base.Conflate(wsToConflate, wsToConflateWith); } } /// <summary> /// Removes the writing system with the specified Store ID from the store. /// </summary> public override void Remove(string id) { using (_mutex.Lock()) { UpdateDefinitions(); base.Remove(id); if (_addedWritingSystems.Contains(id)) _addedWritingSystems.Remove(id); } } /// <summary> /// Returns a list of all writing system definitions in the store. /// </summary> public override IEnumerable<T> AllWritingSystems { get { using (_mutex.Lock()) { UpdateDefinitions(); return base.AllWritingSystems; } } } /// <summary> /// This is used by the orphan finder, which we don't use (yet). It tells whether, typically in the scope of some /// current change log, a writing system ID has changed to something else...call WritingSystemIdHasChangedTo /// to find out what. /// </summary> public override bool WritingSystemIdHasChanged(string id) { throw new NotImplementedException(); } /// <summary> /// This is used by the orphan finder, which we don't use (yet). It tells what, typically in the scope of some /// current change log, a writing system ID has changed to. /// </summary> public override string WritingSystemIdHasChangedTo(string id) { throw new NotImplementedException(); } protected override void RemoveDefinition(T ws) { string file = GetFilePathFromLanguageTag(ws.Id); if (File.Exists(file)) File.Delete(file); base.RemoveDefinition(ws); if (_addedWritingSystems.Contains(ws.Id)) _addedWritingSystems.Remove(ws.Id); } private void SaveDefinition(T ws) { base.Set(ws); string writingSystemFilePath = GetFilePathFromLanguageTag(ws.Id); if (!File.Exists(writingSystemFilePath) && !string.IsNullOrEmpty(ws.Template)) { // this is a new writing system that was generated from a template, so copy the template over before saving File.Copy(ws.Template, writingSystemFilePath); ws.Template = null; } if (!ws.IsChanged && File.Exists(writingSystemFilePath) && !_addedWritingSystems.Contains(ws.Id)) return; // no need to save (better to preserve the modified date) if (ws.IsChanged) ws.DateModified = DateTime.UtcNow; MemoryStream oldData = GetDataToMergeWithInSave(writingSystemFilePath); if (File.Exists(writingSystemFilePath)) { File.Delete(writingSystemFilePath); } var ldmlDataMapper = new LdmlDataMapper(WritingSystemFactory); try { // Provides FW on Linux multi-user access. Overrides the system // umask and creates the files with the permissions "775". // The "fieldworks" group was created outside the app during // configuration of the package which allows group access. using (new FileModeOverride()) { ldmlDataMapper.Write(writingSystemFilePath, ws, oldData); } var fi = new FileInfo(writingSystemFilePath); _lastFileStats[ws.Id] = Tuple.Create(fi.LastWriteTime, fi.Length); } catch (UnauthorizedAccessException) { // If we can't save the changes, too bad. Inability to save locally is typically caught // when we go to open the modify dialog. If we can't make the global store consistent, // as we well may not be able to in a client-server mode, too bad. } ws.AcceptChanges(); } /// <summary> /// Writes the store to a persistable medium, if applicable. /// </summary> public override void Save() { using (_mutex.Lock()) { UpdateDefinitions(); //delete anything we're going to delete first, to prevent losing //a WS we want by having it deleted by an old WS we don't want //(but which has the same identifier) foreach (string id in AllWritingSystems.Where(ws => ws.MarkedForDeletion).Select(ws => ws.Id).ToArray()) base.Remove(id); // make a copy and then go through that list - SaveDefinition calls Set which // may delete and then insert the same writing system - which would change WritingSystemDefinitions // and not be allowed in a foreach loop foreach (T ws in AllWritingSystems.Where(CanSet).ToArray()) SaveDefinition(ws); _addedWritingSystems.Clear(); } } /// <summary> /// Since the current implementation of Save does nothing, it's always possible. /// </summary> public override bool CanSave(T ws) { using (_mutex.Lock()) { string filePath = GetFilePathFromLanguageTag(ws.Id); if (File.Exists(filePath)) { try { using (FileStream stream = File.Open(filePath, FileMode.Open)) stream.Close(); // don't really want to change anything } catch (UnauthorizedAccessException) { return false; } } else if (Directory.Exists(PathToWritingSystems)) { try { // See whether we're allowed to create the file (but if so, get rid of it). // Pathologically we might have create but not delete permission...if so, // we'll create an empty file and report we can't save. I don't see how to // do better. using (FileStream stream = File.Create(filePath)) stream.Close(); File.Delete(filePath); } catch (UnauthorizedAccessException) { return false; } } else { try { Directory.CreateDirectory(PathToWritingSystems); // Don't try to clean it up again. This is a vanishingly rare case, // I don't think it's even possible to create a writing system store without // the directory existing. } catch (UnauthorizedAccessException) { return false; } } return true; } } /// <summary> /// Gets the specified writing system if it exists. /// </summary> /// <param name="id">The identifier.</param> /// <param name="ws">The writing system.</param> /// <returns></returns> public override bool TryGet(string id, out T ws) { using (_mutex.Lock()) { UpdateDefinitions(); return WritingSystems.TryGetValue(id, out ws); } } ///<summary> /// Returns the full path to the underlying store for this writing system. ///</summary> public string GetFilePathFromLanguageTag(string langTag) { return Path.Combine(PathToWritingSystems, GetFileNameFromLanguageTag(langTag)); } /// <summary> /// Gets the file name from the specified identifier. /// </summary> protected static string GetFileNameFromLanguageTag(string langTag) { return langTag + Extension; } ~GlobalWritingSystemRepository() { Dispose(false); // The base class finalizer is called automatically. } public bool IsDisposed { get; private set; } public void CheckDisposed() { if (IsDisposed) throw new ObjectDisposedException(String.Format("'{0}' in use after being disposed.", GetType().Name)); } public void Dispose() { Dispose(true); // This object will be cleaned up by the Dispose method. // Therefore, you should call GC.SupressFinalize to // take this object off the finalization queue // and prevent finalization code for this object // from executing a second time. GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { Debug.WriteLineIf(!disposing, "****** Missing Dispose() call for " + GetType().Name + ". ****** "); // Must not be run more than once. if (IsDisposed) return; if (disposing) _mutex.Dispose(); IsDisposed = true; } private class WsStasher : IDisposable { private string _wsFile; private const string _localrepoupdate = ".localrepoupdate"; public WsStasher(string wsFile) { _wsFile = wsFile; RobustFile.Copy(wsFile, wsFile + _localrepoupdate); } public void Dispose() { RobustFile.Move($"{_wsFile}{_localrepoupdate}", _wsFile); } } } }
using BeardedManStudios.Forge.Networking.Frame; using BeardedManStudios.Forge.Networking.Unity; using System; using UnityEngine; namespace BeardedManStudios.Forge.Networking.Generated { [GeneratedInterpol("{\"inter\":[0,0,0,0,0,0,0,0,0.15,0,0,0]")] public partial class TestNetworkObject : NetworkObject { public const int IDENTITY = 5; private byte[] _dirtyFields = new byte[2]; #pragma warning disable 0067 public event FieldChangedEvent fieldAltered; #pragma warning restore 0067 private byte _fieldByte; public event FieldEvent<byte> fieldByteChanged; public Interpolated<byte> fieldByteInterpolation = new Interpolated<byte>() { LerpT = 0f, Enabled = false }; public byte fieldByte { get { return _fieldByte; } set { // Don't do anything if the value is the same if (_fieldByte == value) return; // Mark the field as dirty for the network to transmit _dirtyFields[0] |= 0x1; _fieldByte = value; hasDirtyFields = true; } } public void SetfieldByteDirty() { _dirtyFields[0] |= 0x1; hasDirtyFields = true; } private void RunChange_fieldByte(ulong timestep) { if (fieldByteChanged != null) fieldByteChanged(_fieldByte, timestep); if (fieldAltered != null) fieldAltered("fieldByte", _fieldByte, timestep); } private char _fieldChar; public event FieldEvent<char> fieldCharChanged; public Interpolated<char> fieldCharInterpolation = new Interpolated<char>() { LerpT = 0f, Enabled = false }; public char fieldChar { get { return _fieldChar; } set { // Don't do anything if the value is the same if (_fieldChar == value) return; // Mark the field as dirty for the network to transmit _dirtyFields[0] |= 0x2; _fieldChar = value; hasDirtyFields = true; } } public void SetfieldCharDirty() { _dirtyFields[0] |= 0x2; hasDirtyFields = true; } private void RunChange_fieldChar(ulong timestep) { if (fieldCharChanged != null) fieldCharChanged(_fieldChar, timestep); if (fieldAltered != null) fieldAltered("fieldChar", _fieldChar, timestep); } private short _fieldShort; public event FieldEvent<short> fieldShortChanged; public Interpolated<short> fieldShortInterpolation = new Interpolated<short>() { LerpT = 0f, Enabled = false }; public short fieldShort { get { return _fieldShort; } set { // Don't do anything if the value is the same if (_fieldShort == value) return; // Mark the field as dirty for the network to transmit _dirtyFields[0] |= 0x4; _fieldShort = value; hasDirtyFields = true; } } public void SetfieldShortDirty() { _dirtyFields[0] |= 0x4; hasDirtyFields = true; } private void RunChange_fieldShort(ulong timestep) { if (fieldShortChanged != null) fieldShortChanged(_fieldShort, timestep); if (fieldAltered != null) fieldAltered("fieldShort", _fieldShort, timestep); } private ushort _fieldUShort; public event FieldEvent<ushort> fieldUShortChanged; public Interpolated<ushort> fieldUShortInterpolation = new Interpolated<ushort>() { LerpT = 0f, Enabled = false }; public ushort fieldUShort { get { return _fieldUShort; } set { // Don't do anything if the value is the same if (_fieldUShort == value) return; // Mark the field as dirty for the network to transmit _dirtyFields[0] |= 0x8; _fieldUShort = value; hasDirtyFields = true; } } public void SetfieldUShortDirty() { _dirtyFields[0] |= 0x8; hasDirtyFields = true; } private void RunChange_fieldUShort(ulong timestep) { if (fieldUShortChanged != null) fieldUShortChanged(_fieldUShort, timestep); if (fieldAltered != null) fieldAltered("fieldUShort", _fieldUShort, timestep); } private bool _fieldBool; public event FieldEvent<bool> fieldBoolChanged; public Interpolated<bool> fieldBoolInterpolation = new Interpolated<bool>() { LerpT = 0f, Enabled = false }; public bool fieldBool { get { return _fieldBool; } set { // Don't do anything if the value is the same if (_fieldBool == value) return; // Mark the field as dirty for the network to transmit _dirtyFields[0] |= 0x10; _fieldBool = value; hasDirtyFields = true; } } public void SetfieldBoolDirty() { _dirtyFields[0] |= 0x10; hasDirtyFields = true; } private void RunChange_fieldBool(ulong timestep) { if (fieldBoolChanged != null) fieldBoolChanged(_fieldBool, timestep); if (fieldAltered != null) fieldAltered("fieldBool", _fieldBool, timestep); } private int _fieldInt; public event FieldEvent<int> fieldIntChanged; public Interpolated<int> fieldIntInterpolation = new Interpolated<int>() { LerpT = 0f, Enabled = false }; public int fieldInt { get { return _fieldInt; } set { // Don't do anything if the value is the same if (_fieldInt == value) return; // Mark the field as dirty for the network to transmit _dirtyFields[0] |= 0x20; _fieldInt = value; hasDirtyFields = true; } } public void SetfieldIntDirty() { _dirtyFields[0] |= 0x20; hasDirtyFields = true; } private void RunChange_fieldInt(ulong timestep) { if (fieldIntChanged != null) fieldIntChanged(_fieldInt, timestep); if (fieldAltered != null) fieldAltered("fieldInt", _fieldInt, timestep); } private uint _fieldUInt; public event FieldEvent<uint> fieldUIntChanged; public Interpolated<uint> fieldUIntInterpolation = new Interpolated<uint>() { LerpT = 0f, Enabled = false }; public uint fieldUInt { get { return _fieldUInt; } set { // Don't do anything if the value is the same if (_fieldUInt == value) return; // Mark the field as dirty for the network to transmit _dirtyFields[0] |= 0x40; _fieldUInt = value; hasDirtyFields = true; } } public void SetfieldUIntDirty() { _dirtyFields[0] |= 0x40; hasDirtyFields = true; } private void RunChange_fieldUInt(ulong timestep) { if (fieldUIntChanged != null) fieldUIntChanged(_fieldUInt, timestep); if (fieldAltered != null) fieldAltered("fieldUInt", _fieldUInt, timestep); } private float _fieldFloat; public event FieldEvent<float> fieldFloatChanged; public InterpolateFloat fieldFloatInterpolation = new InterpolateFloat() { LerpT = 0f, Enabled = false }; public float fieldFloat { get { return _fieldFloat; } set { // Don't do anything if the value is the same if (_fieldFloat == value) return; // Mark the field as dirty for the network to transmit _dirtyFields[0] |= 0x80; _fieldFloat = value; hasDirtyFields = true; } } public void SetfieldFloatDirty() { _dirtyFields[0] |= 0x80; hasDirtyFields = true; } private void RunChange_fieldFloat(ulong timestep) { if (fieldFloatChanged != null) fieldFloatChanged(_fieldFloat, timestep); if (fieldAltered != null) fieldAltered("fieldFloat", _fieldFloat, timestep); } private float _fieldFloatInterpolate; public event FieldEvent<float> fieldFloatInterpolateChanged; public InterpolateFloat fieldFloatInterpolateInterpolation = new InterpolateFloat() { LerpT = 0.15f, Enabled = true }; public float fieldFloatInterpolate { get { return _fieldFloatInterpolate; } set { // Don't do anything if the value is the same if (_fieldFloatInterpolate == value) return; // Mark the field as dirty for the network to transmit _dirtyFields[1] |= 0x1; _fieldFloatInterpolate = value; hasDirtyFields = true; } } public void SetfieldFloatInterpolateDirty() { _dirtyFields[1] |= 0x1; hasDirtyFields = true; } private void RunChange_fieldFloatInterpolate(ulong timestep) { if (fieldFloatInterpolateChanged != null) fieldFloatInterpolateChanged(_fieldFloatInterpolate, timestep); if (fieldAltered != null) fieldAltered("fieldFloatInterpolate", _fieldFloatInterpolate, timestep); } private long _fieldLong; public event FieldEvent<long> fieldLongChanged; public Interpolated<long> fieldLongInterpolation = new Interpolated<long>() { LerpT = 0f, Enabled = false }; public long fieldLong { get { return _fieldLong; } set { // Don't do anything if the value is the same if (_fieldLong == value) return; // Mark the field as dirty for the network to transmit _dirtyFields[1] |= 0x2; _fieldLong = value; hasDirtyFields = true; } } public void SetfieldLongDirty() { _dirtyFields[1] |= 0x2; hasDirtyFields = true; } private void RunChange_fieldLong(ulong timestep) { if (fieldLongChanged != null) fieldLongChanged(_fieldLong, timestep); if (fieldAltered != null) fieldAltered("fieldLong", _fieldLong, timestep); } private ulong _fieldULong; public event FieldEvent<ulong> fieldULongChanged; public Interpolated<ulong> fieldULongInterpolation = new Interpolated<ulong>() { LerpT = 0f, Enabled = false }; public ulong fieldULong { get { return _fieldULong; } set { // Don't do anything if the value is the same if (_fieldULong == value) return; // Mark the field as dirty for the network to transmit _dirtyFields[1] |= 0x4; _fieldULong = value; hasDirtyFields = true; } } public void SetfieldULongDirty() { _dirtyFields[1] |= 0x4; hasDirtyFields = true; } private void RunChange_fieldULong(ulong timestep) { if (fieldULongChanged != null) fieldULongChanged(_fieldULong, timestep); if (fieldAltered != null) fieldAltered("fieldULong", _fieldULong, timestep); } private double _fieldDouble; public event FieldEvent<double> fieldDoubleChanged; public Interpolated<double> fieldDoubleInterpolation = new Interpolated<double>() { LerpT = 0f, Enabled = false }; public double fieldDouble { get { return _fieldDouble; } set { // Don't do anything if the value is the same if (_fieldDouble == value) return; // Mark the field as dirty for the network to transmit _dirtyFields[1] |= 0x8; _fieldDouble = value; hasDirtyFields = true; } } public void SetfieldDoubleDirty() { _dirtyFields[1] |= 0x8; hasDirtyFields = true; } private void RunChange_fieldDouble(ulong timestep) { if (fieldDoubleChanged != null) fieldDoubleChanged(_fieldDouble, timestep); if (fieldAltered != null) fieldAltered("fieldDouble", _fieldDouble, timestep); } protected override void OwnershipChanged() { base.OwnershipChanged(); SnapInterpolations(); } public void SnapInterpolations() { fieldByteInterpolation.current = fieldByteInterpolation.target; fieldCharInterpolation.current = fieldCharInterpolation.target; fieldShortInterpolation.current = fieldShortInterpolation.target; fieldUShortInterpolation.current = fieldUShortInterpolation.target; fieldBoolInterpolation.current = fieldBoolInterpolation.target; fieldIntInterpolation.current = fieldIntInterpolation.target; fieldUIntInterpolation.current = fieldUIntInterpolation.target; fieldFloatInterpolation.current = fieldFloatInterpolation.target; fieldFloatInterpolateInterpolation.current = fieldFloatInterpolateInterpolation.target; fieldLongInterpolation.current = fieldLongInterpolation.target; fieldULongInterpolation.current = fieldULongInterpolation.target; fieldDoubleInterpolation.current = fieldDoubleInterpolation.target; } public override int UniqueIdentity { get { return IDENTITY; } } protected override BMSByte WritePayload(BMSByte data) { UnityObjectMapper.Instance.MapBytes(data, _fieldByte); UnityObjectMapper.Instance.MapBytes(data, _fieldChar); UnityObjectMapper.Instance.MapBytes(data, _fieldShort); UnityObjectMapper.Instance.MapBytes(data, _fieldUShort); UnityObjectMapper.Instance.MapBytes(data, _fieldBool); UnityObjectMapper.Instance.MapBytes(data, _fieldInt); UnityObjectMapper.Instance.MapBytes(data, _fieldUInt); UnityObjectMapper.Instance.MapBytes(data, _fieldFloat); UnityObjectMapper.Instance.MapBytes(data, _fieldFloatInterpolate); UnityObjectMapper.Instance.MapBytes(data, _fieldLong); UnityObjectMapper.Instance.MapBytes(data, _fieldULong); UnityObjectMapper.Instance.MapBytes(data, _fieldDouble); return data; } protected override void ReadPayload(BMSByte payload, ulong timestep) { _fieldByte = UnityObjectMapper.Instance.Map<byte>(payload); fieldByteInterpolation.current = _fieldByte; fieldByteInterpolation.target = _fieldByte; RunChange_fieldByte(timestep); _fieldChar = UnityObjectMapper.Instance.Map<char>(payload); fieldCharInterpolation.current = _fieldChar; fieldCharInterpolation.target = _fieldChar; RunChange_fieldChar(timestep); _fieldShort = UnityObjectMapper.Instance.Map<short>(payload); fieldShortInterpolation.current = _fieldShort; fieldShortInterpolation.target = _fieldShort; RunChange_fieldShort(timestep); _fieldUShort = UnityObjectMapper.Instance.Map<ushort>(payload); fieldUShortInterpolation.current = _fieldUShort; fieldUShortInterpolation.target = _fieldUShort; RunChange_fieldUShort(timestep); _fieldBool = UnityObjectMapper.Instance.Map<bool>(payload); fieldBoolInterpolation.current = _fieldBool; fieldBoolInterpolation.target = _fieldBool; RunChange_fieldBool(timestep); _fieldInt = UnityObjectMapper.Instance.Map<int>(payload); fieldIntInterpolation.current = _fieldInt; fieldIntInterpolation.target = _fieldInt; RunChange_fieldInt(timestep); _fieldUInt = UnityObjectMapper.Instance.Map<uint>(payload); fieldUIntInterpolation.current = _fieldUInt; fieldUIntInterpolation.target = _fieldUInt; RunChange_fieldUInt(timestep); _fieldFloat = UnityObjectMapper.Instance.Map<float>(payload); fieldFloatInterpolation.current = _fieldFloat; fieldFloatInterpolation.target = _fieldFloat; RunChange_fieldFloat(timestep); _fieldFloatInterpolate = UnityObjectMapper.Instance.Map<float>(payload); fieldFloatInterpolateInterpolation.current = _fieldFloatInterpolate; fieldFloatInterpolateInterpolation.target = _fieldFloatInterpolate; RunChange_fieldFloatInterpolate(timestep); _fieldLong = UnityObjectMapper.Instance.Map<long>(payload); fieldLongInterpolation.current = _fieldLong; fieldLongInterpolation.target = _fieldLong; RunChange_fieldLong(timestep); _fieldULong = UnityObjectMapper.Instance.Map<ulong>(payload); fieldULongInterpolation.current = _fieldULong; fieldULongInterpolation.target = _fieldULong; RunChange_fieldULong(timestep); _fieldDouble = UnityObjectMapper.Instance.Map<double>(payload); fieldDoubleInterpolation.current = _fieldDouble; fieldDoubleInterpolation.target = _fieldDouble; RunChange_fieldDouble(timestep); } protected override BMSByte SerializeDirtyFields() { dirtyFieldsData.Clear(); dirtyFieldsData.Append(_dirtyFields); if ((0x1 & _dirtyFields[0]) != 0) UnityObjectMapper.Instance.MapBytes(dirtyFieldsData, _fieldByte); if ((0x2 & _dirtyFields[0]) != 0) UnityObjectMapper.Instance.MapBytes(dirtyFieldsData, _fieldChar); if ((0x4 & _dirtyFields[0]) != 0) UnityObjectMapper.Instance.MapBytes(dirtyFieldsData, _fieldShort); if ((0x8 & _dirtyFields[0]) != 0) UnityObjectMapper.Instance.MapBytes(dirtyFieldsData, _fieldUShort); if ((0x10 & _dirtyFields[0]) != 0) UnityObjectMapper.Instance.MapBytes(dirtyFieldsData, _fieldBool); if ((0x20 & _dirtyFields[0]) != 0) UnityObjectMapper.Instance.MapBytes(dirtyFieldsData, _fieldInt); if ((0x40 & _dirtyFields[0]) != 0) UnityObjectMapper.Instance.MapBytes(dirtyFieldsData, _fieldUInt); if ((0x80 & _dirtyFields[0]) != 0) UnityObjectMapper.Instance.MapBytes(dirtyFieldsData, _fieldFloat); if ((0x1 & _dirtyFields[1]) != 0) UnityObjectMapper.Instance.MapBytes(dirtyFieldsData, _fieldFloatInterpolate); if ((0x2 & _dirtyFields[1]) != 0) UnityObjectMapper.Instance.MapBytes(dirtyFieldsData, _fieldLong); if ((0x4 & _dirtyFields[1]) != 0) UnityObjectMapper.Instance.MapBytes(dirtyFieldsData, _fieldULong); if ((0x8 & _dirtyFields[1]) != 0) UnityObjectMapper.Instance.MapBytes(dirtyFieldsData, _fieldDouble); return dirtyFieldsData; } protected override void ReadDirtyFields(BMSByte data, ulong timestep) { if (readDirtyFlags == null) Initialize(); Buffer.BlockCopy(data.byteArr, data.StartIndex(), readDirtyFlags, 0, readDirtyFlags.Length); data.MoveStartIndex(readDirtyFlags.Length); if ((0x1 & readDirtyFlags[0]) != 0) { if (fieldByteInterpolation.Enabled) { fieldByteInterpolation.target = UnityObjectMapper.Instance.Map<byte>(data); fieldByteInterpolation.Timestep = timestep; } else { _fieldByte = UnityObjectMapper.Instance.Map<byte>(data); RunChange_fieldByte(timestep); } } if ((0x2 & readDirtyFlags[0]) != 0) { if (fieldCharInterpolation.Enabled) { fieldCharInterpolation.target = UnityObjectMapper.Instance.Map<char>(data); fieldCharInterpolation.Timestep = timestep; } else { _fieldChar = UnityObjectMapper.Instance.Map<char>(data); RunChange_fieldChar(timestep); } } if ((0x4 & readDirtyFlags[0]) != 0) { if (fieldShortInterpolation.Enabled) { fieldShortInterpolation.target = UnityObjectMapper.Instance.Map<short>(data); fieldShortInterpolation.Timestep = timestep; } else { _fieldShort = UnityObjectMapper.Instance.Map<short>(data); RunChange_fieldShort(timestep); } } if ((0x8 & readDirtyFlags[0]) != 0) { if (fieldUShortInterpolation.Enabled) { fieldUShortInterpolation.target = UnityObjectMapper.Instance.Map<ushort>(data); fieldUShortInterpolation.Timestep = timestep; } else { _fieldUShort = UnityObjectMapper.Instance.Map<ushort>(data); RunChange_fieldUShort(timestep); } } if ((0x10 & readDirtyFlags[0]) != 0) { if (fieldBoolInterpolation.Enabled) { fieldBoolInterpolation.target = UnityObjectMapper.Instance.Map<bool>(data); fieldBoolInterpolation.Timestep = timestep; } else { _fieldBool = UnityObjectMapper.Instance.Map<bool>(data); RunChange_fieldBool(timestep); } } if ((0x20 & readDirtyFlags[0]) != 0) { if (fieldIntInterpolation.Enabled) { fieldIntInterpolation.target = UnityObjectMapper.Instance.Map<int>(data); fieldIntInterpolation.Timestep = timestep; } else { _fieldInt = UnityObjectMapper.Instance.Map<int>(data); RunChange_fieldInt(timestep); } } if ((0x40 & readDirtyFlags[0]) != 0) { if (fieldUIntInterpolation.Enabled) { fieldUIntInterpolation.target = UnityObjectMapper.Instance.Map<uint>(data); fieldUIntInterpolation.Timestep = timestep; } else { _fieldUInt = UnityObjectMapper.Instance.Map<uint>(data); RunChange_fieldUInt(timestep); } } if ((0x80 & readDirtyFlags[0]) != 0) { if (fieldFloatInterpolation.Enabled) { fieldFloatInterpolation.target = UnityObjectMapper.Instance.Map<float>(data); fieldFloatInterpolation.Timestep = timestep; } else { _fieldFloat = UnityObjectMapper.Instance.Map<float>(data); RunChange_fieldFloat(timestep); } } if ((0x1 & readDirtyFlags[1]) != 0) { if (fieldFloatInterpolateInterpolation.Enabled) { fieldFloatInterpolateInterpolation.target = UnityObjectMapper.Instance.Map<float>(data); fieldFloatInterpolateInterpolation.Timestep = timestep; } else { _fieldFloatInterpolate = UnityObjectMapper.Instance.Map<float>(data); RunChange_fieldFloatInterpolate(timestep); } } if ((0x2 & readDirtyFlags[1]) != 0) { if (fieldLongInterpolation.Enabled) { fieldLongInterpolation.target = UnityObjectMapper.Instance.Map<long>(data); fieldLongInterpolation.Timestep = timestep; } else { _fieldLong = UnityObjectMapper.Instance.Map<long>(data); RunChange_fieldLong(timestep); } } if ((0x4 & readDirtyFlags[1]) != 0) { if (fieldULongInterpolation.Enabled) { fieldULongInterpolation.target = UnityObjectMapper.Instance.Map<ulong>(data); fieldULongInterpolation.Timestep = timestep; } else { _fieldULong = UnityObjectMapper.Instance.Map<ulong>(data); RunChange_fieldULong(timestep); } } if ((0x8 & readDirtyFlags[1]) != 0) { if (fieldDoubleInterpolation.Enabled) { fieldDoubleInterpolation.target = UnityObjectMapper.Instance.Map<double>(data); fieldDoubleInterpolation.Timestep = timestep; } else { _fieldDouble = UnityObjectMapper.Instance.Map<double>(data); RunChange_fieldDouble(timestep); } } } public override void InterpolateUpdate() { if (IsOwner) return; if (fieldByteInterpolation.Enabled && !fieldByteInterpolation.current.UnityNear(fieldByteInterpolation.target, 0.0015f)) { _fieldByte = (byte)fieldByteInterpolation.Interpolate(); RunChange_fieldByte(fieldByteInterpolation.Timestep); } if (fieldCharInterpolation.Enabled && !fieldCharInterpolation.current.UnityNear(fieldCharInterpolation.target, 0.0015f)) { _fieldChar = (char)fieldCharInterpolation.Interpolate(); RunChange_fieldChar(fieldCharInterpolation.Timestep); } if (fieldShortInterpolation.Enabled && !fieldShortInterpolation.current.UnityNear(fieldShortInterpolation.target, 0.0015f)) { _fieldShort = (short)fieldShortInterpolation.Interpolate(); RunChange_fieldShort(fieldShortInterpolation.Timestep); } if (fieldUShortInterpolation.Enabled && !fieldUShortInterpolation.current.UnityNear(fieldUShortInterpolation.target, 0.0015f)) { _fieldUShort = (ushort)fieldUShortInterpolation.Interpolate(); RunChange_fieldUShort(fieldUShortInterpolation.Timestep); } if (fieldBoolInterpolation.Enabled && !fieldBoolInterpolation.current.UnityNear(fieldBoolInterpolation.target, 0.0015f)) { _fieldBool = (bool)fieldBoolInterpolation.Interpolate(); RunChange_fieldBool(fieldBoolInterpolation.Timestep); } if (fieldIntInterpolation.Enabled && !fieldIntInterpolation.current.UnityNear(fieldIntInterpolation.target, 0.0015f)) { _fieldInt = (int)fieldIntInterpolation.Interpolate(); RunChange_fieldInt(fieldIntInterpolation.Timestep); } if (fieldUIntInterpolation.Enabled && !fieldUIntInterpolation.current.UnityNear(fieldUIntInterpolation.target, 0.0015f)) { _fieldUInt = (uint)fieldUIntInterpolation.Interpolate(); RunChange_fieldUInt(fieldUIntInterpolation.Timestep); } if (fieldFloatInterpolation.Enabled && !fieldFloatInterpolation.current.UnityNear(fieldFloatInterpolation.target, 0.0015f)) { _fieldFloat = (float)fieldFloatInterpolation.Interpolate(); RunChange_fieldFloat(fieldFloatInterpolation.Timestep); } if (fieldFloatInterpolateInterpolation.Enabled && !fieldFloatInterpolateInterpolation.current.UnityNear(fieldFloatInterpolateInterpolation.target, 0.0015f)) { _fieldFloatInterpolate = (float)fieldFloatInterpolateInterpolation.Interpolate(); RunChange_fieldFloatInterpolate(fieldFloatInterpolateInterpolation.Timestep); } if (fieldLongInterpolation.Enabled && !fieldLongInterpolation.current.UnityNear(fieldLongInterpolation.target, 0.0015f)) { _fieldLong = (long)fieldLongInterpolation.Interpolate(); RunChange_fieldLong(fieldLongInterpolation.Timestep); } if (fieldULongInterpolation.Enabled && !fieldULongInterpolation.current.UnityNear(fieldULongInterpolation.target, 0.0015f)) { _fieldULong = (ulong)fieldULongInterpolation.Interpolate(); RunChange_fieldULong(fieldULongInterpolation.Timestep); } if (fieldDoubleInterpolation.Enabled && !fieldDoubleInterpolation.current.UnityNear(fieldDoubleInterpolation.target, 0.0015f)) { _fieldDouble = (double)fieldDoubleInterpolation.Interpolate(); RunChange_fieldDouble(fieldDoubleInterpolation.Timestep); } } private void Initialize() { if (readDirtyFlags == null) readDirtyFlags = new byte[2]; } public TestNetworkObject() : base() { Initialize(); } public TestNetworkObject(NetWorker networker, INetworkBehavior networkBehavior = null, int createCode = 0, byte[] metadata = null) : base(networker, networkBehavior, createCode, metadata) { Initialize(); } public TestNetworkObject(NetWorker networker, uint serverId, FrameStream frame) : base(networker, serverId, frame) { Initialize(); } // DO NOT TOUCH, THIS GETS GENERATED PLEASE EXTEND THIS CLASS IF YOU WISH TO HAVE CUSTOM CODE ADDITIONS } }
#region License /* * All content copyright Terracotta, Inc., unless otherwise indicated. All rights 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 using System; using System.Data; using Quartz.Spi; using Quartz.Util; namespace Quartz.Impl.AdoJobStore { /// <summary> /// A base implementation of <see cref="ITriggerPersistenceDelegate" /> that persists /// trigger fields in the "QRTZ_SIMPROP_TRIGGERS" table. This allows extending /// concrete classes to simply implement a couple methods that do the work of /// getting/setting the trigger's fields, and creating the <see cref="IScheduleBuilder" /> /// for the particular type of trigger. /// </summary> /// <seealso cref="CalendarIntervalTriggerPersistenceDelegate" /> /// <author>jhouse</author> /// <author>Marko Lahma (.NET)</author> public abstract class SimplePropertiesTriggerPersistenceDelegateSupport : ITriggerPersistenceDelegate { protected const string TableSimplePropertiesTriggers = "SIMPROP_TRIGGERS"; protected const string ColumnStrProp1 = "STR_PROP_1"; protected const string ColumnStrProp2 = "STR_PROP_2"; protected const string ColumnStrProp3 = "STR_PROP_3"; protected const string ColumnIntProp1 = "INT_PROP_1"; protected const string ColumnIntProp2 = "INT_PROP_2"; protected const string ColumnLongProp1 = "LONG_PROP_1"; protected const string ColumnLongProp2 = "LONG_PROP_2"; protected const string ColumnDecProp1 = "DEC_PROP_1"; protected const string ColumnDecProp2 = "DEC_PROP_2"; protected const string ColumnBoolProp1 = "BOOL_PROP_1"; protected const string ColumnBoolProp2 = "BOOL_PROP_2"; protected const string SelectSimplePropsTrigger = "SELECT *" + " FROM " + StdAdoConstants.TablePrefixSubst + TableSimplePropertiesTriggers + " WHERE " + AdoConstants.ColumnSchedulerName + " = " + StdAdoConstants.SchedulerNameSubst + " AND " + AdoConstants.ColumnTriggerName + " = @triggerName AND " + AdoConstants.ColumnTriggerGroup + " = @triggerGroup"; protected const string DeleteSimplePropsTrigger = "DELETE FROM " + StdAdoConstants.TablePrefixSubst + TableSimplePropertiesTriggers + " WHERE " + AdoConstants.ColumnSchedulerName + " = " + StdAdoConstants.SchedulerNameSubst + " AND " + AdoConstants.ColumnTriggerName + " = @triggerName AND " + AdoConstants.ColumnTriggerGroup + " = @triggerGroup"; protected const string InsertSimplePropsTrigger = "INSERT INTO " + StdAdoConstants.TablePrefixSubst + TableSimplePropertiesTriggers + " (" + AdoConstants.ColumnSchedulerName + ", " + AdoConstants.ColumnTriggerName + ", " + AdoConstants.ColumnTriggerGroup + ", " + ColumnStrProp1 + ", " + ColumnStrProp2 + ", " + ColumnStrProp3 + ", " + ColumnIntProp1 + ", " + ColumnIntProp2 + ", " + ColumnLongProp1 + ", " + ColumnLongProp2 + ", " + ColumnDecProp1 + ", " + ColumnDecProp2 + ", " + ColumnBoolProp1 + ", " + ColumnBoolProp2 + ") " + " VALUES(" + StdAdoConstants.SchedulerNameSubst + ", @triggerName, @triggerGroup, @string1, @string2, @string3, @int1, @int2, @long1, @long2, @decimal1, @decimal2, @boolean1, @boolean2)"; protected const string UpdateSimplePropsTrigger = "UPDATE " + StdAdoConstants.TablePrefixSubst + TableSimplePropertiesTriggers + " SET " + ColumnStrProp1 + " = @string1, " + ColumnStrProp2 + " = @string2, " + ColumnStrProp3 + " = @string3, " + ColumnIntProp1 + " = @int1, " + ColumnIntProp2 + " = @int2, " + ColumnLongProp1 + " = @long1, " + ColumnLongProp2 + " = @long2, " + ColumnDecProp1 + " = @decimal1, " + ColumnDecProp2 + " = @decimal2, " + ColumnBoolProp1 + " = @boolean1, " + ColumnBoolProp2 + " = @boolean2 WHERE " + AdoConstants.ColumnSchedulerName + " = " + StdAdoConstants.SchedulerNameSubst + " AND " + AdoConstants.ColumnTriggerName + " = @triggerName AND " + AdoConstants.ColumnTriggerGroup + " = @triggerGroup"; public void Initialize(string tablePrefix, string schedName, IDbAccessor dbAccessor) { TablePrefix = tablePrefix; DbAccessor = dbAccessor; SchedNameLiteral = "'" + schedName + "'"; } /// <summary> /// Returns whether the trigger type can be handled by delegate. /// </summary> public abstract bool CanHandleTriggerType(IOperableTrigger trigger); /// <summary> /// Returns database discriminator value for trigger type. /// </summary> public abstract string GetHandledTriggerTypeDiscriminator(); protected abstract SimplePropertiesTriggerProperties GetTriggerProperties(IOperableTrigger trigger); protected abstract TriggerPropertyBundle GetTriggerPropertyBundle(SimplePropertiesTriggerProperties properties); protected string TablePrefix { get; private set; } protected string SchedNameLiteral { get; private set; } protected IDbAccessor DbAccessor { get; private set; } public int DeleteExtendedTriggerProperties(ConnectionAndTransactionHolder conn, TriggerKey triggerKey) { using (IDbCommand cmd = DbAccessor.PrepareCommand(conn, AdoJobStoreUtil.ReplaceTablePrefix(DeleteSimplePropsTrigger, TablePrefix, SchedNameLiteral))) { DbAccessor.AddCommandParameter(cmd, "triggerName", triggerKey.Name); DbAccessor.AddCommandParameter(cmd, "triggerGroup", triggerKey.Group); return cmd.ExecuteNonQuery(); } } public int InsertExtendedTriggerProperties(ConnectionAndTransactionHolder conn, IOperableTrigger trigger, string state, IJobDetail jobDetail) { SimplePropertiesTriggerProperties properties = GetTriggerProperties(trigger); using (IDbCommand cmd = DbAccessor.PrepareCommand(conn, AdoJobStoreUtil.ReplaceTablePrefix(InsertSimplePropsTrigger, TablePrefix, SchedNameLiteral))) { DbAccessor.AddCommandParameter(cmd, "triggerName", trigger.Key.Name); DbAccessor.AddCommandParameter(cmd, "triggerGroup", trigger.Key.Group); DbAccessor.AddCommandParameter(cmd, "string1", properties.String1); DbAccessor.AddCommandParameter(cmd, "string2", properties.String2); DbAccessor.AddCommandParameter(cmd, "string3", properties.String3); DbAccessor.AddCommandParameter(cmd, "int1", properties.Int1); DbAccessor.AddCommandParameter(cmd, "int2", properties.Int2); DbAccessor.AddCommandParameter(cmd, "long1", properties.Long1); DbAccessor.AddCommandParameter(cmd, "long2", properties.Long2); DbAccessor.AddCommandParameter(cmd, "decimal1", properties.Decimal1); DbAccessor.AddCommandParameter(cmd, "decimal2", properties.Decimal2); DbAccessor.AddCommandParameter(cmd, "boolean1", DbAccessor.GetDbBooleanValue(properties.Boolean1)); DbAccessor.AddCommandParameter(cmd, "boolean2", DbAccessor.GetDbBooleanValue(properties.Boolean2)); return cmd.ExecuteNonQuery(); } } public TriggerPropertyBundle LoadExtendedTriggerProperties(ConnectionAndTransactionHolder conn, TriggerKey triggerKey) { using (IDbCommand cmd = DbAccessor.PrepareCommand(conn, AdoJobStoreUtil.ReplaceTablePrefix(SelectSimplePropsTrigger, TablePrefix, SchedNameLiteral))) { DbAccessor.AddCommandParameter(cmd, "triggerName", triggerKey.Name); DbAccessor.AddCommandParameter(cmd, "triggerGroup", triggerKey.Group); using (IDataReader rs = cmd.ExecuteReader()) { if (rs.Read()) { SimplePropertiesTriggerProperties properties = new SimplePropertiesTriggerProperties(); properties.String1 = rs.GetString(ColumnStrProp1); properties.String2 = rs.GetString(ColumnStrProp2); properties.String3 = rs.GetString(ColumnStrProp3); properties.Int1 = rs.GetInt32(ColumnIntProp1); properties.Int2 = rs.GetInt32(ColumnIntProp2); properties.Long1 = rs.GetInt32(ColumnLongProp1); properties.Long2 = rs.GetInt32(ColumnLongProp2); properties.Decimal1 = rs.GetDecimal(ColumnDecProp1); properties.Decimal2 = rs.GetDecimal(ColumnDecProp2); properties.Boolean1 = DbAccessor.GetBooleanFromDbValue(rs[ColumnBoolProp1]); properties.Boolean2 = DbAccessor.GetBooleanFromDbValue(rs[ColumnBoolProp2]); return GetTriggerPropertyBundle(properties); } } } throw new InvalidOperationException("No record found for selection of Trigger with key: '" + triggerKey + "' and statement: " + AdoJobStoreUtil.ReplaceTablePrefix(StdAdoConstants.SqlSelectSimpleTrigger, TablePrefix, SchedNameLiteral)); } public int UpdateExtendedTriggerProperties(ConnectionAndTransactionHolder conn, IOperableTrigger trigger, string state, IJobDetail jobDetail) { SimplePropertiesTriggerProperties properties = GetTriggerProperties(trigger); using (IDbCommand cmd = DbAccessor.PrepareCommand(conn, AdoJobStoreUtil.ReplaceTablePrefix(UpdateSimplePropsTrigger, TablePrefix, SchedNameLiteral))) { DbAccessor.AddCommandParameter(cmd, "string1", properties.String1); DbAccessor.AddCommandParameter(cmd, "string2", properties.String2); DbAccessor.AddCommandParameter(cmd, "string3", properties.String3); DbAccessor.AddCommandParameter(cmd, "int1", properties.Int1); DbAccessor.AddCommandParameter(cmd, "int2", properties.Int2); DbAccessor.AddCommandParameter(cmd, "long1", properties.Long1); DbAccessor.AddCommandParameter(cmd, "long2", properties.Long2); DbAccessor.AddCommandParameter(cmd, "decimal1", properties.Decimal1); DbAccessor.AddCommandParameter(cmd, "decimal2", properties.Decimal2); DbAccessor.AddCommandParameter(cmd, "boolean1", DbAccessor.GetDbBooleanValue(properties.Boolean1)); DbAccessor.AddCommandParameter(cmd, "boolean2", DbAccessor.GetDbBooleanValue(properties.Boolean2)); DbAccessor.AddCommandParameter(cmd, "triggerName", trigger.Key.Name); DbAccessor.AddCommandParameter(cmd, "triggerGroup", trigger.Key.Group); return cmd.ExecuteNonQuery(); } } } }
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 MyCsomAppWeb { 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 registerd for this app</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 app event /// </summary> /// <param name="properties">Properties of an app 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 registerd for this app</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 registerd for this app</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 app. 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 app 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 app 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 app 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 app. /// </summary> /// <returns>True if this is a high trust app.</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 app 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 } }
//------------------------------------------------------------------------------- // <copyright file="Transition.cs" company="Appccelerate"> // Copyright (c) 2008-2015 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> //------------------------------------------------------------------------------- namespace Appccelerate.StateMachine.Machine.Transitions { using System; using System.Collections.Generic; using System.Globalization; using Appccelerate.StateMachine.Machine.ActionHolders; using Appccelerate.StateMachine.Machine.GuardHolders; public class Transition<TState, TEvent> : ITransition<TState, TEvent> where TState : IComparable where TEvent : IComparable { private readonly List<IActionHolder> actions; private readonly IExtensionHost<TState, TEvent> extensionHost; private readonly IStateMachineInformation<TState, TEvent> stateMachineInformation; public Transition(IStateMachineInformation<TState, TEvent> stateMachineInformation, IExtensionHost<TState, TEvent> extensionHost) { this.stateMachineInformation = stateMachineInformation; this.extensionHost = extensionHost; this.actions = new List<IActionHolder>(); } public IState<TState, TEvent> Source { get; set; } public IState<TState, TEvent> Target { get; set; } public IGuardHolder Guard { get; set; } public ICollection<IActionHolder> Actions { get { return this.actions; } } private bool IsInternalTransition { get { return this.Target == null; } } public ITransitionResult<TState, TEvent> Fire(ITransitionContext<TState, TEvent> context) { Ensure.ArgumentNotNull(context, "context"); if (!this.ShouldFire(context)) { this.extensionHost.ForEach(extension => extension.SkippedTransition( this.stateMachineInformation, this, context)); return TransitionResult<TState, TEvent>.NotFired; } context.OnTransitionBegin(); this.extensionHost.ForEach(extension => extension.ExecutingTransition( this.stateMachineInformation, this, context)); IState<TState, TEvent> newState = context.State; if (!this.IsInternalTransition) { this.UnwindSubStates(context); this.Fire(this.Source, this.Target, context); newState = this.Target.EnterByHistory(context); } else { this.PerformActions(context); } this.extensionHost.ForEach(extension => extension.ExecutedTransition( this.stateMachineInformation, this, context)); return new TransitionResult<TState, TEvent>(true, newState); } public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "Transition from state {0} to state {1}.", this.Source, this.Target); } private static void HandleException(Exception exception, ITransitionContext<TState, TEvent> context) { context.OnExceptionThrown(exception); } /// <summary> /// Recursively traverses the state hierarchy, exiting states along /// the way, performing the action, and entering states to the target. /// </summary> /// <remarks> /// There exist the following transition scenarios: /// 0. there is no target state (internal transition) /// --> handled outside this method. /// 1. The source and target state are the same (self transition) /// --> perform the transition directly: /// Exit source state, perform transition actions and enter target state /// 2. The target state is a direct or indirect sub-state of the source state /// --> perform the transition actions, then traverse the hierarchy /// from the source state down to the target state, /// entering each state along the way. /// No state is exited. /// 3. The source state is a sub-state of the target state /// --> traverse the hierarchy from the source up to the target, /// exiting each state along the way. /// Then perform transition actions. /// Finally enter the target state. /// 4. The source and target state share the same super-state /// 5. All other scenarios: /// a. The source and target states reside at the same level in the hierarchy /// but do not share the same direct super-state /// --> exit the source state, move up the hierarchy on both sides and enter the target state /// b. The source state is lower in the hierarchy than the target state /// --> exit the source state and move up the hierarchy on the source state side /// c. The target state is lower in the hierarchy than the source state /// --> move up the hierarchy on the target state side, afterward enter target state /// </remarks> /// <param name="source">The source state.</param> /// <param name="target">The target state.</param> /// <param name="context">The event context.</param> private void Fire(IState<TState, TEvent> source, IState<TState, TEvent> target, ITransitionContext<TState, TEvent> context) { if (source == this.Target) { // Handles 1. // Handles 3. after traversing from the source to the target. source.Exit(context); this.PerformActions(context); this.Target.Entry(context); } else if (source == target) { // Handles 2. after traversing from the target to the source. this.PerformActions(context); } else if (source.SuperState == target.SuperState) { //// Handles 4. //// Handles 5a. after traversing the hierarchy until a common ancestor if found. source.Exit(context); this.PerformActions(context); target.Entry(context); } else { // traverses the hierarchy until one of the above scenarios is met. // Handles 3. // Handles 5b. if (source.Level > target.Level) { source.Exit(context); this.Fire(source.SuperState, target, context); } else if (source.Level < target.Level) { // Handles 2. // Handles 5c. this.Fire(source, target.SuperState, context); target.Entry(context); } else { // Handles 5a. source.Exit(context); this.Fire(source.SuperState, target.SuperState, context); target.Entry(context); } } } private bool ShouldFire(ITransitionContext<TState, TEvent> context) { try { return this.Guard == null || this.Guard.Execute(context.EventArgument); } catch (Exception exception) { this.extensionHost.ForEach(extention => extention.HandlingGuardException(this.stateMachineInformation, this, context, ref exception)); HandleException(exception, context); this.extensionHost.ForEach(extention => extention.HandledGuardException(this.stateMachineInformation, this, context, exception)); return false; } } private void PerformActions(ITransitionContext<TState, TEvent> context) { foreach (IActionHolder action in this.actions) { try { action.Execute(context.EventArgument); } catch (Exception exception) { this.extensionHost.ForEach(extension => extension.HandlingTransitionException(this.stateMachineInformation, this, context, ref exception)); HandleException(exception, context); this.extensionHost.ForEach(extension => extension.HandledTransitionException(this.stateMachineInformation, this, context, exception)); } } } private void UnwindSubStates(ITransitionContext<TState, TEvent> context) { for (IState<TState, TEvent> o = context.State; o != this.Source; o = o.SuperState) { o.Exit(context); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.MirrorPolymorphic { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Models; /// <summary> /// Some cool documentation. /// </summary> public partial class PolymorphicAnimalStore : ServiceClient<PolymorphicAnimalStore>, IPolymorphicAnimalStore { /// <summary> /// The base URI of the service. /// </summary> public Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Initializes a new instance of the PolymorphicAnimalStore class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public PolymorphicAnimalStore(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the PolymorphicAnimalStore class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public PolymorphicAnimalStore(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the PolymorphicAnimalStore class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public PolymorphicAnimalStore(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the PolymorphicAnimalStore class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public PolymorphicAnimalStore(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// An optional partial-method to perform custom initialization. ///</summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.BaseUri = new Uri("https://management.azure.com/"); SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new PolymorphicSerializeJsonConverter<Animal>("dtype")); DeserializationSettings.Converters.Add(new PolymorphicDeserializeJsonConverter<Animal>("dtype")); CustomInitialize(); } /// <summary> /// Product Types /// </summary> /// The Products endpoint returns information about the Uber products offered /// at a given location. The response includes the display name and other /// details about each product, and lists the products in the proper display /// order. /// <param name='animalCreateOrUpdateParameter'> /// An Animal /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<Animal>> CreateOrUpdatePolymorphicAnimalsWithHttpMessagesAsync(Animal animalCreateOrUpdateParameter = default(Animal), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("animalCreateOrUpdateParameter", animalCreateOrUpdateParameter); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdatePolymorphicAnimals", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "getpolymorphicAnimals").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = SafeJsonConvert.SerializeObject(animalCreateOrUpdateParameter, this.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Error2Exception(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error2 _errorBody = SafeJsonConvert.DeserializeObject<Error2>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<Animal>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Animal>(_responseContent, this.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
/* **************************************************************************** * * 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.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ namespace System.Management.Automation.Interpreter { internal abstract class NumericConvertInstruction : Instruction { internal readonly TypeCode _from, _to; protected NumericConvertInstruction(TypeCode from, TypeCode to) { _from = from; _to = to; } public override int ConsumedStack { get { return 1; } } public override int ProducedStack { get { return 1; } } public override string ToString() { return InstructionName + "(" + _from + "->" + _to + ")"; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] internal sealed class Unchecked : NumericConvertInstruction { public override string InstructionName { get { return "UncheckedConvert"; } } public Unchecked(TypeCode from, TypeCode to) : base(from, to) { } public override int Run(InterpretedFrame frame) { frame.Push(Convert(frame.Pop())); return +1; } private object Convert(object obj) { switch (_from) { case TypeCode.Byte: return ConvertInt32((byte)obj); case TypeCode.SByte: return ConvertInt32((sbyte)obj); case TypeCode.Int16: return ConvertInt32((Int16)obj); case TypeCode.Char: return ConvertInt32((char)obj); case TypeCode.Int32: return ConvertInt32((Int32)obj); case TypeCode.Int64: return ConvertInt64((Int64)obj); case TypeCode.UInt16: return ConvertInt32((UInt16)obj); case TypeCode.UInt32: return ConvertInt64((UInt32)obj); case TypeCode.UInt64: return ConvertUInt64((UInt64)obj); case TypeCode.Single: return ConvertDouble((Single)obj); case TypeCode.Double: return ConvertDouble((double)obj); default: throw Assert.Unreachable; } } private object ConvertInt32(int obj) { unchecked { switch (_to) { case TypeCode.Byte: return (byte)obj; case TypeCode.SByte: return (sbyte)obj; case TypeCode.Int16: return (Int16)obj; case TypeCode.Char: return (char)obj; case TypeCode.Int32: return (Int32)obj; case TypeCode.Int64: return (Int64)obj; case TypeCode.UInt16: return (UInt16)obj; case TypeCode.UInt32: return (UInt32)obj; case TypeCode.UInt64: return (UInt64)obj; case TypeCode.Single: return (Single)obj; case TypeCode.Double: return (double)obj; default: throw Assert.Unreachable; } } } private object ConvertInt64(Int64 obj) { unchecked { switch (_to) { case TypeCode.Byte: return (byte)obj; case TypeCode.SByte: return (sbyte)obj; case TypeCode.Int16: return (Int16)obj; case TypeCode.Char: return (char)obj; case TypeCode.Int32: return (Int32)obj; case TypeCode.Int64: return (Int64)obj; case TypeCode.UInt16: return (UInt16)obj; case TypeCode.UInt32: return (UInt32)obj; case TypeCode.UInt64: return (UInt64)obj; case TypeCode.Single: return (Single)obj; case TypeCode.Double: return (double)obj; default: throw Assert.Unreachable; } } } private object ConvertUInt64(UInt64 obj) { unchecked { switch (_to) { case TypeCode.Byte: return (byte)obj; case TypeCode.SByte: return (sbyte)obj; case TypeCode.Int16: return (Int16)obj; case TypeCode.Char: return (char)obj; case TypeCode.Int32: return (Int32)obj; case TypeCode.Int64: return (Int64)obj; case TypeCode.UInt16: return (UInt16)obj; case TypeCode.UInt32: return (UInt32)obj; case TypeCode.UInt64: return (UInt64)obj; case TypeCode.Single: return (Single)obj; case TypeCode.Double: return (double)obj; default: throw Assert.Unreachable; } } } private object ConvertDouble(double obj) { unchecked { switch (_to) { case TypeCode.Byte: return (byte)obj; case TypeCode.SByte: return (sbyte)obj; case TypeCode.Int16: return (Int16)obj; case TypeCode.Char: return (char)obj; case TypeCode.Int32: return (Int32)obj; case TypeCode.Int64: return (Int64)obj; case TypeCode.UInt16: return (UInt16)obj; case TypeCode.UInt32: return (UInt32)obj; case TypeCode.UInt64: return (UInt64)obj; case TypeCode.Single: return (Single)obj; case TypeCode.Double: return (double)obj; default: throw Assert.Unreachable; } } } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] internal sealed class Checked : NumericConvertInstruction { public override string InstructionName { get { return "CheckedConvert"; } } public Checked(TypeCode from, TypeCode to) : base(from, to) { } public override int Run(InterpretedFrame frame) { frame.Push(Convert(frame.Pop())); return +1; } private object Convert(object obj) { switch (_from) { case TypeCode.Byte: return ConvertInt32((byte)obj); case TypeCode.SByte: return ConvertInt32((sbyte)obj); case TypeCode.Int16: return ConvertInt32((Int16)obj); case TypeCode.Char: return ConvertInt32((char)obj); case TypeCode.Int32: return ConvertInt32((Int32)obj); case TypeCode.Int64: return ConvertInt64((Int64)obj); case TypeCode.UInt16: return ConvertInt32((UInt16)obj); case TypeCode.UInt32: return ConvertInt64((UInt32)obj); case TypeCode.UInt64: return ConvertUInt64((UInt64)obj); case TypeCode.Single: return ConvertDouble((Single)obj); case TypeCode.Double: return ConvertDouble((double)obj); default: throw Assert.Unreachable; } } private object ConvertInt32(int obj) { checked { switch (_to) { case TypeCode.Byte: return (byte)obj; case TypeCode.SByte: return (sbyte)obj; case TypeCode.Int16: return (Int16)obj; case TypeCode.Char: return (char)obj; case TypeCode.Int32: return (Int32)obj; case TypeCode.Int64: return (Int64)obj; case TypeCode.UInt16: return (UInt16)obj; case TypeCode.UInt32: return (UInt32)obj; case TypeCode.UInt64: return (UInt64)obj; case TypeCode.Single: return (Single)obj; case TypeCode.Double: return (double)obj; default: throw Assert.Unreachable; } } } private object ConvertInt64(Int64 obj) { checked { switch (_to) { case TypeCode.Byte: return (byte)obj; case TypeCode.SByte: return (sbyte)obj; case TypeCode.Int16: return (Int16)obj; case TypeCode.Char: return (char)obj; case TypeCode.Int32: return (Int32)obj; case TypeCode.Int64: return (Int64)obj; case TypeCode.UInt16: return (UInt16)obj; case TypeCode.UInt32: return (UInt32)obj; case TypeCode.UInt64: return (UInt64)obj; case TypeCode.Single: return (Single)obj; case TypeCode.Double: return (double)obj; default: throw Assert.Unreachable; } } } private object ConvertUInt64(UInt64 obj) { checked { switch (_to) { case TypeCode.Byte: return (byte)obj; case TypeCode.SByte: return (sbyte)obj; case TypeCode.Int16: return (Int16)obj; case TypeCode.Char: return (char)obj; case TypeCode.Int32: return (Int32)obj; case TypeCode.Int64: return (Int64)obj; case TypeCode.UInt16: return (UInt16)obj; case TypeCode.UInt32: return (UInt32)obj; case TypeCode.UInt64: return (UInt64)obj; case TypeCode.Single: return (Single)obj; case TypeCode.Double: return (double)obj; default: throw Assert.Unreachable; } } } private object ConvertDouble(double obj) { checked { switch (_to) { case TypeCode.Byte: return (byte)obj; case TypeCode.SByte: return (sbyte)obj; case TypeCode.Int16: return (Int16)obj; case TypeCode.Char: return (char)obj; case TypeCode.Int32: return (Int32)obj; case TypeCode.Int64: return (Int64)obj; case TypeCode.UInt16: return (UInt16)obj; case TypeCode.UInt32: return (UInt32)obj; case TypeCode.UInt64: return (UInt64)obj; case TypeCode.Single: return (Single)obj; case TypeCode.Double: return (double)obj; default: throw Assert.Unreachable; } } } } } }
// UrlRewriter - A .NET URL Rewriter module // Version 2.0 // // Copyright 2011 Intelligencia // Copyright 2011 Seth Yates // using System; using System.Collections.Generic; using System.Configuration; using System.Xml; using System.Collections.Specialized; using System.Reflection; using Intelligencia.UrlRewriter.Parsers; using Intelligencia.UrlRewriter.Transforms; using Intelligencia.UrlRewriter.Utilities; using Intelligencia.UrlRewriter.Logging; using System.Web; using System.IO; using System.Web.Caching; namespace Intelligencia.UrlRewriter.Configuration { /// <summary> /// Configuration for the URL rewriter. /// </summary> public class RewriterConfiguration : IRewriterConfiguration { private IConfigurationManager _configurationManager; private IRewriteLogger _logger = new NullLogger(); private IDictionary<int, IRewriteErrorHandler> _errorHandlers = new Dictionary<int, IRewriteErrorHandler>(); private IList<IRewriteAction> _rules = new List<IRewriteAction>(); private ActionParserFactory _actionParserFactory; private ConditionParserPipeline _conditionParserPipeline; private TransformFactory _transformFactory; private StringCollection _defaultDocuments; private string _xPoweredBy; /// <summary> /// Default constructor. /// </summary> internal RewriterConfiguration() : this(new ConfigurationManagerFacade()) { } /// <summary> /// Constructor. /// </summary> /// <param name="configurationManager">The configuration manager instance</param> internal RewriterConfiguration(IConfigurationManager configurationManager) { if (configurationManager == null) { throw new ArgumentNullException("configurationManager"); } _configurationManager = configurationManager; _xPoweredBy = MessageProvider.FormatString(Message.ProductName, Assembly.GetExecutingAssembly().GetName().Version.ToString(3)); _actionParserFactory = new ActionParserFactory(); _actionParserFactory.AddParser(new IfConditionActionParser()); _actionParserFactory.AddParser(new UnlessConditionActionParser()); _actionParserFactory.AddParser(new AddHeaderActionParser()); _actionParserFactory.AddParser(new SetCookieActionParser()); _actionParserFactory.AddParser(new SetPropertyActionParser()); _actionParserFactory.AddParser(new SetAppSettingPropertyActionParser()); _actionParserFactory.AddParser(new RewriteActionParser()); _actionParserFactory.AddParser(new RedirectActionParser()); _actionParserFactory.AddParser(new SetStatusActionParser()); _actionParserFactory.AddParser(new ForbiddenActionParser()); _actionParserFactory.AddParser(new GoneActionParser()); _actionParserFactory.AddParser(new NotAllowedActionParser()); _actionParserFactory.AddParser(new NotFoundActionParser()); _actionParserFactory.AddParser(new NotImplementedActionParser()); _conditionParserPipeline = new ConditionParserPipeline(); _conditionParserPipeline.AddParser(new AddressConditionParser()); _conditionParserPipeline.AddParser(new HeaderMatchConditionParser()); _conditionParserPipeline.AddParser(new MethodConditionParser()); _conditionParserPipeline.AddParser(new PropertyMatchConditionParser()); _conditionParserPipeline.AddParser(new ExistsConditionParser()); _conditionParserPipeline.AddParser(new UrlMatchConditionParser()); _transformFactory = new TransformFactory(); _transformFactory.AddTransform(new DecodeTransform()); _transformFactory.AddTransform(new EncodeTransform()); _transformFactory.AddTransform(new LowerTransform()); _transformFactory.AddTransform(new UpperTransform()); _transformFactory.AddTransform(new Base64Transform()); _transformFactory.AddTransform(new Base64DecodeTransform()); _defaultDocuments = new StringCollection(); //LoadFromConfig(); } /// <summary> /// The rules. /// </summary> public IList<IRewriteAction> Rules { get { return _rules; } } /// <summary> /// The action parser factory. /// </summary> public ActionParserFactory ActionParserFactory { get { return _actionParserFactory; } } /// <summary> /// The transform factory. /// </summary> public TransformFactory TransformFactory { get { return _transformFactory; } } /// <summary> /// The condition parser pipeline. /// </summary> public ConditionParserPipeline ConditionParserPipeline { get { return _conditionParserPipeline; } } /// <summary> /// Dictionary of error handlers. /// </summary> public IDictionary<int, IRewriteErrorHandler> ErrorHandlers { get { return _errorHandlers; } } /// <summary> /// Logger to use for logging information. /// </summary> public IRewriteLogger Logger { get { return _logger; } set { _logger = value; } } /// <summary> /// Collection of default document names to use if the result of a rewriting /// is a directory name. /// </summary> public StringCollection DefaultDocuments { get { return _defaultDocuments; } } /// <summary> /// Additional X-Powered-By header. /// </summary> public string XPoweredBy { get { return _xPoweredBy; } } /// <summary> /// The configuration manager instance. /// </summary> public IConfigurationManager ConfigurationManager { get { return _configurationManager; } } /// <summary> /// Loads the rewriter configuration from the web.config file. /// </summary> private void LoadFromConfig() { XmlNode section = _configurationManager.GetSection(Constants.RewriterNode) as XmlNode; if (section == null) { throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.MissingConfigFileSection, Constants.RewriterNode), section); } RewriterConfigurationReader.Read(this, section); } //Add Code in 2014-04-15 16:44 private static string _cacheName = typeof(RewriterConfiguration).AssemblyQualifiedName; private static object SyncObject = new object(); /// <summary> /// Create a RewriterConfiguration Instance /// </summary> /// <returns></returns> public static RewriterConfiguration Create() { return new RewriterConfiguration(); } /// <summary> /// Current Configuration for the URL rewriter. /// </summary> public static RewriterConfiguration Current { get { RewriterConfiguration configuration = HttpRuntime.Cache.Get(_cacheName) as RewriterConfiguration; if (configuration == null) { lock (SyncObject) { configuration = HttpRuntime.Cache.Get(_cacheName) as RewriterConfiguration; if (configuration == null) { configuration = Load(); } } } return configuration; } } /// <summary> /// Load RewriterConfiguration Instance /// </summary> /// <returns></returns> public static RewriterConfiguration Load() { XmlNode section = System.Configuration.ConfigurationManager.GetSection(Constants.RewriterNode) as XmlNode; RewriterConfiguration configuration = null; XmlNode namedItem = section.Attributes.GetNamedItem(Constants.AttrFile); if (namedItem != null) { string filename = HttpContext.Current.Server.MapPath(namedItem.Value); configuration = LoadFromFile(filename); if (configuration != null) { CacheDependency dependencies = new CacheDependency(filename); HttpRuntime.Cache.Add(_cacheName, configuration, dependencies, DateTime.Now.AddHours(1.0), TimeSpan.Zero, CacheItemPriority.Normal, null); } } if (configuration == null) { configuration = LoadFromNode(section); HttpRuntime.Cache.Add(_cacheName, configuration, null, DateTime.Now.AddHours(1.0), TimeSpan.Zero, CacheItemPriority.Normal, null); } return configuration; } /// <summary> /// Load RewriterConfiguration Instance to File /// </summary> /// <param name="filename">Config File Path</param> /// <returns></returns> public static RewriterConfiguration LoadFromFile(string filename) { if (File.Exists(filename)) { XmlDocument document = new XmlDocument(); document.Load(filename); return LoadFromNode(document.DocumentElement); } return null; } /// <summary> /// Load RewriterConfiguration Instance to XmlNode /// </summary> /// <param name="node">XmlNode</param> /// <returns></returns> public static RewriterConfiguration LoadFromNode(XmlNode node) { RewriterConfiguration configuration = RewriterConfigurationReader.Read(node); //HttpRuntime.Cache.Add(_cacheName, configuration, null, DateTime.Now.AddHours(1.0), TimeSpan.Zero, CacheItemPriority.Normal, null); return configuration; } } }
/* Copyright 2012 Michael Edwards 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. */ //-CRE- using Castle.MicroKernel.Registration; using Glass.Mapper.Configuration; using Glass.Mapper.Pipelines.ObjectConstruction; using Glass.Mapper.Umb.CastleWindsor.Pipelines.ObjectConstruction; using NSubstitute; using NUnit.Framework; namespace Glass.Mapper.Umb.CastleWindsor.Tests.Pipelines.ObjectConstruction { [TestFixture] public class WindsorConstructionFixture { [Test] public void Execute_RequestInstanceOfClass_ReturnsInstance() { //Assign var task = new WindsorConstruction(); var resolver = DependencyResolver.CreateStandardResolver(); resolver.Container.Register( Component.For<Mapper.Config>().Instance(new Mapper.Config()) ); var context = Context.Create(resolver); var typeConfig = Substitute.For<AbstractTypeConfiguration>(); typeConfig.Type = typeof (StubClass); var typeCreationContext = Substitute.For<AbstractTypeCreationContext>(); var service = Substitute.For<AbstractService>(); var args = new ObjectConstructionArgs(context, typeCreationContext, typeConfig , service); Assert.IsNull(args.Result); //Act task.Execute(args); //Assert Assert.IsNotNull(args.Result); Assert.IsTrue(args.Result is StubClass); } [Test] public void Execute_ResultAlreadySet_NoInstanceCreated() { //Assign var task = new WindsorConstruction(); var resolver = DependencyResolver.CreateStandardResolver(); resolver.Container.Register( Component.For<Mapper.Config>().Instance(new Mapper.Config()) ); var context = Context.Create(resolver); var typeConfig = Substitute.For<AbstractTypeConfiguration>(); typeConfig.Type = typeof(StubClass); var args = new ObjectConstructionArgs(context, null, typeConfig , null); var result = new StubClass2(); args.Result = result; Assert.IsNotNull(args.Result); //Act task.Execute(args); //Assert Assert.IsNotNull(args.Result); Assert.IsTrue(args.Result is StubClass2); Assert.AreEqual(result, args.Result); } [Test] public void Execute_RequestInstanceOfInterface_ReturnsNullInterfaceNotSupported() { //Assign var task = new WindsorConstruction(); var resolver = DependencyResolver.CreateStandardResolver(); resolver.Container.Register( Component.For<Mapper.Config>().Instance(new Mapper.Config()) ); var context = Context.Create(resolver); var typeConfig = Substitute.For<AbstractTypeConfiguration>(); typeConfig.Type = typeof(StubInterface); var typeCreationContext = Substitute.For<AbstractTypeCreationContext>(); var args = new ObjectConstructionArgs(context, typeCreationContext, typeConfig , null); Assert.IsNull(args.Result); //Act task.Execute(args); //Assert Assert.IsNull(args.Result); } [Test] public void Execute_RequestInstanceOfClassWithService_ReturnsInstanceWithService() { //Assign var task = new WindsorConstruction(); var resolver = DependencyResolver.CreateStandardResolver(); resolver.Container.Register( Component.For<Mapper.Config>().Instance(new Mapper.Config()) ); var context = Context.Create(resolver); resolver.Container.Register( Component.For<StubServiceInterface>().ImplementedBy<StubService>().LifestyleTransient() ); var typeConfig = Substitute.For<AbstractTypeConfiguration>(); typeConfig.Type = typeof(StubClassWithService); var typeCreationContext = Substitute.For<AbstractTypeCreationContext>(); var service = Substitute.For<AbstractService>(); var args = new ObjectConstructionArgs(context, typeCreationContext, typeConfig , service); Assert.IsNull(args.Result); //Act task.Execute(args); //Assert Assert.IsNotNull(args.Result); Assert.IsTrue(args.Result is StubClassWithService); var stub = args.Result as StubClassWithService; Assert.IsNotNull(stub.Service); Assert.IsTrue(stub.Service is StubService); } [Test] public void Execute_RequestInstanceOfClassWithParameters_NoInstanceReturnedDoesntHandle() { //Assign var task = new WindsorConstruction(); var resolver = DependencyResolver.CreateStandardResolver(); resolver.Container.Register( Component.For<Mapper.Config>().Instance(new Mapper.Config()) ); var context = Context.Create(resolver); var typeConfig = Substitute.For<AbstractTypeConfiguration>(); typeConfig.Type = typeof(StubClassWithParameters); string param1 = "test param1"; int param2 = 450; double param3 = 489; string param4 = "param4 test"; var typeCreationContext = Substitute.For<AbstractTypeCreationContext>(); typeCreationContext.ConstructorParameters = new object[]{param1, param2, param3, param4}; var args = new ObjectConstructionArgs(context, typeCreationContext, typeConfig , null); Assert.IsNull(args.Result); //Act task.Execute(args); //Assert Assert.IsNull(args.Result); } #region Stubs public class StubClass { } public class StubClass2 { } public interface StubInterface { } public interface StubServiceInterface { } public class StubService: StubServiceInterface { } public class StubClassWithService { public StubServiceInterface Service { get; set; } public StubClassWithService(StubServiceInterface service) { Service = service; } } public class StubClassWithParameters { public string Param1 { get; set; } public int Param2 { get; set; } public double Param3 { get; set; } public string Param4 { get; set; } public StubClassWithParameters( string param1, int param2, double param3, string param4 ) { Param1 = param1; Param2 = param2; Param3 = param3; Param4 = param4; } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Reflection; using System.Text; using System.Collections; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Diagnostics.Contracts; namespace System { [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public abstract class Enum : ValueType, IComparable, IFormattable, IConvertible { #region Private Static Data Members private static readonly char [] enumSeperatorCharArray = new char [] {','}; private const String enumSeperator = ", "; #endregion #region Private Static Methods [System.Security.SecuritySafeCritical] // auto-generated private static ValuesAndNames GetCachedValuesAndNames(RuntimeType enumType, bool getNames) { ValuesAndNames entry = enumType.GenericCache as ValuesAndNames; if (entry == null || (getNames && entry.Names == null)) { ulong[] values = null; String[] names = null; GetEnumValuesAndNames( enumType.GetTypeHandleInternal(), JitHelpers.GetObjectHandleOnStack(ref values), JitHelpers.GetObjectHandleOnStack(ref names), getNames); entry = new ValuesAndNames(values, names); enumType.GenericCache = entry; } return entry; } private static String InternalFormattedHexString(Object value) { TypeCode typeCode = Convert.GetTypeCode(value); switch (typeCode) { case TypeCode.SByte : { Byte result = (byte)(sbyte)value; return result.ToString("X2", null); } case TypeCode.Byte : { Byte result = (byte)value; return result.ToString("X2", null); } case TypeCode.Boolean: { // direct cast from bool to byte is not allowed Byte result = Convert.ToByte((bool)value); return result.ToString("X2", null); } case TypeCode.Int16: { UInt16 result = (UInt16)(Int16)value; return result.ToString("X4", null); } case TypeCode.UInt16 : { UInt16 result = (UInt16)value; return result.ToString("X4", null); } case TypeCode.Char: { UInt16 result = (UInt16)(Char)value; return result.ToString("X4", null); } case TypeCode.UInt32: { UInt32 result = (UInt32)value; return result.ToString("X8", null); } case TypeCode.Int32 : { UInt32 result = (UInt32)(int)value; return result.ToString("X8", null); } case TypeCode.UInt64 : { UInt64 result = (UInt64)value; return result.ToString("X16", null); } case TypeCode.Int64 : { UInt64 result = (UInt64)(Int64)value; return result.ToString("X16", null); } // All unsigned types will be directly cast default : Contract.Assert(false, "Invalid Object type in Format"); throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType")); } } private static String InternalFormat(RuntimeType eT, Object value) { Contract.Requires(eT != null); Contract.Requires(value != null); if (!eT.IsDefined(typeof(System.FlagsAttribute), false)) // Not marked with Flags attribute { // Try to see if its one of the enum values, then we return a String back else the value String retval = GetName(eT, value); if (retval == null) return value.ToString(); else return retval; } else // These are flags OR'ed together (We treat everything as unsigned types) { return InternalFlagsFormat(eT, value); } } private static String InternalFlagsFormat(RuntimeType eT, Object value) { Contract.Requires(eT != null); Contract.Requires(value != null); ulong result = ToUInt64(value); // These values are sorted by value. Don't change this ValuesAndNames entry = GetCachedValuesAndNames(eT, true); String[] names = entry.Names; ulong[] values = entry.Values; Contract.Assert(names.Length == values.Length); int index = values.Length - 1; StringBuilder retval = new StringBuilder(); bool firstTime = true; ulong saveResult = result; // We will not optimize this code further to keep it maintainable. There are some boundary checks that can be applied // to minimize the comparsions required. This code works the same for the best/worst case. In general the number of // items in an enum are sufficiently small and not worth the optimization. while (index >= 0) { if ((index == 0) && (values[index] == 0)) break; if ((result & values[index]) == values[index]) { result -= values[index]; if (!firstTime) retval.Insert(0, enumSeperator); retval.Insert(0, names[index]); firstTime = false; } index--; } // We were unable to represent this number as a bitwise or of valid flags if (result != 0) return value.ToString(); // For the case when we have zero if (saveResult==0) { if (values.Length > 0 && values[0] == 0) return names[0]; // Zero was one of the enum values. else return "0"; } else return retval.ToString(); // Return the string representation } internal static ulong ToUInt64(Object value) { // Helper function to silently convert the value to UInt64 from the other base types for enum without throwing an exception. // This is need since the Convert functions do overflow checks. TypeCode typeCode = Convert.GetTypeCode(value); ulong result; switch(typeCode) { case TypeCode.SByte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: result = (UInt64)Convert.ToInt64(value, CultureInfo.InvariantCulture); break; case TypeCode.Byte: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: case TypeCode.Boolean: case TypeCode.Char: result = Convert.ToUInt64(value, CultureInfo.InvariantCulture); break; default: // All unsigned types will be directly cast Contract.Assert(false, "Invalid Object type in ToUInt64"); throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType")); } return result; } [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int InternalCompareTo(Object o1, Object o2); [System.Security.SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern RuntimeType InternalGetUnderlyingType(RuntimeType enumType); [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [System.Security.SuppressUnmanagedCodeSecurity] private static extern void GetEnumValuesAndNames(RuntimeTypeHandle enumType, ObjectHandleOnStack values, ObjectHandleOnStack names, bool getNames); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern Object InternalBoxEnum(RuntimeType enumType, long value); #endregion #region Public Static Methods private enum ParseFailureKind { None = 0, Argument = 1, ArgumentNull = 2, ArgumentWithParameter = 3, UnhandledException = 4 } // This will store the result of the parsing. private struct EnumResult { internal object parsedEnum; internal bool canThrow; internal ParseFailureKind m_failure; internal string m_failureMessageID; internal string m_failureParameter; internal object m_failureMessageFormatArgument; internal Exception m_innerException; internal void Init(bool canMethodThrow) { parsedEnum = 0; canThrow = canMethodThrow; } internal void SetFailure(Exception unhandledException) { m_failure = ParseFailureKind.UnhandledException; m_innerException = unhandledException; } internal void SetFailure(ParseFailureKind failure, string failureParameter) { m_failure = failure; m_failureParameter = failureParameter; if (canThrow) throw GetEnumParseException(); } internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument) { m_failure = failure; m_failureMessageID = failureMessageID; m_failureMessageFormatArgument = failureMessageFormatArgument; if (canThrow) throw GetEnumParseException(); } internal Exception GetEnumParseException() { switch (m_failure) { case ParseFailureKind.Argument: return new ArgumentException(Environment.GetResourceString(m_failureMessageID)); case ParseFailureKind.ArgumentNull: return new ArgumentNullException(m_failureParameter); case ParseFailureKind.ArgumentWithParameter: return new ArgumentException(Environment.GetResourceString(m_failureMessageID, m_failureMessageFormatArgument)); case ParseFailureKind.UnhandledException: return m_innerException; default: Contract.Assert(false, "Unknown EnumParseFailure: " + m_failure); return new ArgumentException(Environment.GetResourceString("Arg_EnumValueNotFound")); } } } public static bool TryParse<TEnum>(String value, out TEnum result) where TEnum : struct { return TryParse(value, false, out result); } public static bool TryParse<TEnum>(String value, bool ignoreCase, out TEnum result) where TEnum : struct { result = default(TEnum); EnumResult parseResult = new EnumResult(); parseResult.Init(false); bool retValue; if (retValue = TryParseEnum(typeof(TEnum), value, ignoreCase, ref parseResult)) result = (TEnum)parseResult.parsedEnum; return retValue; } [System.Runtime.InteropServices.ComVisible(true)] public static Object Parse(Type enumType, String value) { return Parse(enumType, value, false); } [System.Runtime.InteropServices.ComVisible(true)] public static Object Parse(Type enumType, String value, bool ignoreCase) { EnumResult parseResult = new EnumResult(); parseResult.Init(true); if (TryParseEnum(enumType, value, ignoreCase, ref parseResult)) return parseResult.parsedEnum; else throw parseResult.GetEnumParseException(); } private static bool TryParseEnum(Type enumType, String value, bool ignoreCase, ref EnumResult parseResult) { if (enumType == null) throw new ArgumentNullException("enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); if (value == null) { parseResult.SetFailure(ParseFailureKind.ArgumentNull, "value"); return false; } value = value.Trim(); if (value.Length == 0) { parseResult.SetFailure(ParseFailureKind.Argument, "Arg_MustContainEnumInfo", null); return false; } // We have 2 code paths here. One if they are values else if they are Strings. // values will have the first character as as number or a sign. ulong result = 0; if (Char.IsDigit(value[0]) || value[0] == '-' || value[0] == '+') { Type underlyingType = GetUnderlyingType(enumType); Object temp; try { temp = Convert.ChangeType(value, underlyingType, CultureInfo.InvariantCulture); parseResult.parsedEnum = ToObject(enumType, temp); return true; } catch (FormatException) { // We need to Parse this as a String instead. There are cases // when you tlbimp enums that can have values of the form "3D". // Don't fix this code. } catch (Exception ex) { if (parseResult.canThrow) throw; else { parseResult.SetFailure(ex); return false; } } } String[] values = value.Split(enumSeperatorCharArray); // Find the field.Lets assume that these are always static classes because the class is // an enum. ValuesAndNames entry = GetCachedValuesAndNames(rtType, true); String[] enumNames = entry.Names; ulong[] enumValues = entry.Values; for (int i = 0; i < values.Length; i++) { values[i] = values[i].Trim(); // We need to remove whitespace characters bool success = false; for (int j = 0; j < enumNames.Length; j++) { if (ignoreCase) { if (String.Compare(enumNames[j], values[i], StringComparison.OrdinalIgnoreCase) != 0) continue; } else { if (!enumNames[j].Equals(values[i])) continue; } ulong item = enumValues[j]; result |= item; success = true; break; } if (!success) { // Not found, throw an argument exception. parseResult.SetFailure(ParseFailureKind.ArgumentWithParameter, "Arg_EnumValueNotFound", value); return false; } } try { parseResult.parsedEnum = ToObject(enumType, result); return true; } catch (Exception ex) { if (parseResult.canThrow) throw; else { parseResult.SetFailure(ex); return false; } } } [System.Runtime.InteropServices.ComVisible(true)] public static Type GetUnderlyingType(Type enumType) { if (enumType == null) throw new ArgumentNullException("enumType"); Contract.Ensures(Contract.Result<Type>() != null); Contract.EndContractBlock(); return enumType.GetEnumUnderlyingType(); } [System.Runtime.InteropServices.ComVisible(true)] public static Array GetValues(Type enumType) { if (enumType == null) throw new ArgumentNullException("enumType"); Contract.Ensures(Contract.Result<Array>() != null); Contract.EndContractBlock(); return enumType.GetEnumValues(); } internal static ulong[] InternalGetValues(RuntimeType enumType) { // Get all of the values return GetCachedValuesAndNames(enumType, false).Values; } [System.Runtime.InteropServices.ComVisible(true)] public static String GetName(Type enumType, Object value) { if (enumType == null) throw new ArgumentNullException("enumType"); Contract.EndContractBlock(); return enumType.GetEnumName(value); } [System.Runtime.InteropServices.ComVisible(true)] public static String[] GetNames(Type enumType) { if (enumType == null) throw new ArgumentNullException("enumType"); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); return enumType.GetEnumNames(); } internal static String[] InternalGetNames(RuntimeType enumType) { // Get all of the names return GetCachedValuesAndNames(enumType, true).Names; } [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, Object value) { if (value == null) throw new ArgumentNullException("value"); Contract.EndContractBlock(); // Delegate rest of error checking to the other functions TypeCode typeCode = Convert.GetTypeCode(value); // NetCF doesn't support char and boolean conversion if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8 && ((typeCode == TypeCode.Boolean) || (typeCode == TypeCode.Char))) { throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnumBaseTypeOrEnum"), "value"); } switch (typeCode) { case TypeCode.Int32 : return ToObject(enumType, (int)value); case TypeCode.SByte : return ToObject(enumType, (sbyte)value); case TypeCode.Int16 : return ToObject(enumType, (short)value); case TypeCode.Int64 : return ToObject(enumType, (long)value); case TypeCode.UInt32 : return ToObject(enumType, (uint)value); case TypeCode.Byte : return ToObject(enumType, (byte)value); case TypeCode.UInt16 : return ToObject(enumType, (ushort)value); case TypeCode.UInt64 : return ToObject(enumType, (ulong)value); case TypeCode.Char: return ToObject(enumType, (char)value); case TypeCode.Boolean: return ToObject(enumType, (bool)value); default: // All unsigned types will be directly cast throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnumBaseTypeOrEnum"), "value"); } } [Pure] [System.Runtime.InteropServices.ComVisible(true)] public static bool IsDefined(Type enumType, Object value) { if (enumType == null) throw new ArgumentNullException("enumType"); Contract.EndContractBlock(); return enumType.IsEnumDefined(value); } [System.Runtime.InteropServices.ComVisible(true)] public static String Format(Type enumType, Object value, String format) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); if (value == null) throw new ArgumentNullException("value"); if (format == null) throw new ArgumentNullException("format"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); // Check if both of them are of the same type Type valueType = value.GetType(); Type underlyingType = GetUnderlyingType(enumType); // If the value is an Enum then we need to extract the underlying value from it if (valueType.IsEnum) { Type valueUnderlyingType = GetUnderlyingType(valueType); if (!valueType.IsEquivalentTo(enumType)) throw new ArgumentException(Environment.GetResourceString("Arg_EnumAndObjectMustBeSameType", valueType.ToString(), enumType.ToString())); valueType = valueUnderlyingType; value = ((Enum)value).GetValue(); } // The value must be of the same type as the Underlying type of the Enum else if (valueType != underlyingType) { throw new ArgumentException(Environment.GetResourceString("Arg_EnumFormatUnderlyingTypeAndObjectMustBeSameType", valueType.ToString(), underlyingType.ToString())); } if( format.Length != 1) { // all acceptable format string are of length 1 throw new FormatException(Environment.GetResourceString("Format_InvalidEnumFormatSpecification")); } char formatCh = format[0]; if (formatCh == 'D' || formatCh == 'd') { return value.ToString(); } if (formatCh == 'X' || formatCh == 'x') { // Retrieve the value from the field. return InternalFormattedHexString(value); } if (formatCh == 'G' || formatCh == 'g') { return InternalFormat(rtType, value); } if (formatCh == 'F' || formatCh == 'f') { return InternalFlagsFormat(rtType, value); } throw new FormatException(Environment.GetResourceString("Format_InvalidEnumFormatSpecification")); } #endregion #region Definitions private class ValuesAndNames { // Each entry contains a list of sorted pair of enum field names and values, sorted by values public ValuesAndNames(ulong[] values, String[] names) { this.Values = values; this.Names = names; } public ulong[] Values; public String[] Names; } #endregion #region Private Methods [System.Security.SecuritySafeCritical] internal unsafe Object GetValue() { fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data) { switch (InternalGetCorElementType()) { case CorElementType.I1: return *(sbyte*)pValue; case CorElementType.U1: return *(byte*)pValue; case CorElementType.Boolean: return *(bool*)pValue; case CorElementType.I2: return *(short*)pValue; case CorElementType.U2: return *(ushort*)pValue; case CorElementType.Char: return *(char*)pValue; case CorElementType.I4: return *(int*)pValue; case CorElementType.U4: return *(uint*)pValue; case CorElementType.R4: return *(float*)pValue; case CorElementType.I8: return *(long*)pValue; case CorElementType.U8: return *(ulong*)pValue; case CorElementType.R8: return *(double*)pValue; case CorElementType.I: return *(IntPtr*)pValue; case CorElementType.U: return *(UIntPtr*)pValue; default: Contract.Assert(false, "Invalid primitive type"); return null; } } } [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern bool InternalHasFlag(Enum flags); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern CorElementType InternalGetCorElementType(); #endregion #region Object Overrides [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern override bool Equals(Object obj); [System.Security.SecuritySafeCritical] public override unsafe int GetHashCode() { // Avoid boxing by inlining GetValue() // return GetValue().GetHashCode(); fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data) { switch (InternalGetCorElementType()) { case CorElementType.I1: return (*(sbyte*)pValue).GetHashCode(); case CorElementType.U1: return (*(byte*)pValue).GetHashCode(); case CorElementType.Boolean: return (*(bool*)pValue).GetHashCode(); case CorElementType.I2: return (*(short*)pValue).GetHashCode(); case CorElementType.U2: return (*(ushort*)pValue).GetHashCode(); case CorElementType.Char: return (*(char*)pValue).GetHashCode(); case CorElementType.I4: return (*(int*)pValue).GetHashCode(); case CorElementType.U4: return (*(uint*)pValue).GetHashCode(); case CorElementType.R4: return (*(float*)pValue).GetHashCode(); case CorElementType.I8: return (*(long*)pValue).GetHashCode(); case CorElementType.U8: return (*(ulong*)pValue).GetHashCode(); case CorElementType.R8: return (*(double*)pValue).GetHashCode(); case CorElementType.I: return (*(IntPtr*)pValue).GetHashCode(); case CorElementType.U: return (*(UIntPtr*)pValue).GetHashCode(); default: Contract.Assert(false, "Invalid primitive type"); return 0; } } } public override String ToString() { // Returns the value in a human readable format. For PASCAL style enums who's value maps directly the name of the field is returned. // For PASCAL style enums who's values do not map directly the decimal value of the field is returned. // For BitFlags (indicated by the Flags custom attribute): If for each bit that is set in the value there is a corresponding constant //(a pure power of 2), then the OR string (ie "Red | Yellow") is returned. Otherwise, if the value is zero or if you can't create a string that consists of // pure powers of 2 OR-ed together, you return a hex value return Enum.InternalFormat((RuntimeType)GetType(), GetValue()); } #endregion #region IFormattable [Obsolete("The provider argument is not used. Please use ToString(String).")] public String ToString(String format, IFormatProvider provider) { return ToString(format); } #endregion #region IComparable [System.Security.SecuritySafeCritical] // auto-generated public int CompareTo(Object target) { const int retIncompatibleMethodTables = 2; // indicates that the method tables did not match const int retInvalidEnumType = 3; // indicates that the enum was of an unknown/unsupported unerlying type if (this == null) throw new NullReferenceException(); Contract.EndContractBlock(); int ret = InternalCompareTo(this, target); if (ret < retIncompatibleMethodTables) { // -1, 0 and 1 are the normal return codes return ret; } else if (ret == retIncompatibleMethodTables) { Type thisType = this.GetType(); Type targetType = target.GetType(); throw new ArgumentException(Environment.GetResourceString("Arg_EnumAndObjectMustBeSameType", targetType.ToString(), thisType.ToString())); } else { // assert valid return code (3) Contract.Assert(ret == retInvalidEnumType, "Enum.InternalCompareTo return code was invalid"); throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType")); } } #endregion #region Public Methods public String ToString(String format) { if (format == null || format.Length == 0) format = "G"; if (String.Compare(format, "G", StringComparison.OrdinalIgnoreCase) == 0) return ToString(); if (String.Compare(format, "D", StringComparison.OrdinalIgnoreCase) == 0) return GetValue().ToString(); if (String.Compare(format, "X", StringComparison.OrdinalIgnoreCase) == 0) return InternalFormattedHexString(GetValue()); if (String.Compare(format, "F", StringComparison.OrdinalIgnoreCase) == 0) return InternalFlagsFormat((RuntimeType)GetType(), GetValue()); throw new FormatException(Environment.GetResourceString("Format_InvalidEnumFormatSpecification")); } [Obsolete("The provider argument is not used. Please use ToString().")] public String ToString(IFormatProvider provider) { return ToString(); } [System.Security.SecuritySafeCritical] public Boolean HasFlag(Enum flag) { if (flag == null) throw new ArgumentNullException("flag"); Contract.EndContractBlock(); if (!this.GetType().IsEquivalentTo(flag.GetType())) { throw new ArgumentException(Environment.GetResourceString("Argument_EnumTypeDoesNotMatch", flag.GetType(), this.GetType())); } return InternalHasFlag(flag); } #endregion #region IConvertable public TypeCode GetTypeCode() { Type enumType = this.GetType(); Type underlyingType = GetUnderlyingType(enumType); if (underlyingType == typeof(Int32)) { return TypeCode.Int32; } if (underlyingType == typeof(sbyte)) { return TypeCode.SByte; } if (underlyingType == typeof(Int16)) { return TypeCode.Int16; } if (underlyingType == typeof(Int64)) { return TypeCode.Int64; } if (underlyingType == typeof(UInt32)) { return TypeCode.UInt32; } if (underlyingType == typeof(byte)) { return TypeCode.Byte; } if (underlyingType == typeof(UInt16)) { return TypeCode.UInt16; } if (underlyingType == typeof(UInt64)) { return TypeCode.UInt64; } if (underlyingType == typeof(Boolean)) { return TypeCode.Boolean; } if (underlyingType == typeof(Char)) { return TypeCode.Char; } Contract.Assert(false, "Unknown underlying type."); throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType")); } /// <internalonly/> bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(GetValue(), CultureInfo.CurrentCulture); } /// <internalonly/> DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Enum", "DateTime")); } /// <internalonly/> Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } #endregion #region ToObject [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, sbyte value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, short value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, int value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, byte value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, ushort value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, uint value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, long value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(true)] public static Object ToObject(Type enumType, ulong value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, unchecked((long)value)); } [System.Security.SecuritySafeCritical] // auto-generated private static Object ToObject(Type enumType, char value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, value); } [System.Security.SecuritySafeCritical] // auto-generated private static Object ToObject(Type enumType, bool value) { if (enumType == null) throw new ArgumentNullException("enumType"); if (!enumType.IsEnum) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType"); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "enumType"); return InternalBoxEnum(rtType, value ? 1 : 0); } #endregion } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; #if UNIX using System.Globalization; using System.Management.Automation; using System.Runtime.InteropServices; #else using System.Management.Automation; using System.Management.Automation.Internal; #endif #endregion namespace Microsoft.PowerShell.Commands { /// <summary>Removes the Zone.Identifier stream from a file.</summary> [Cmdlet(VerbsSecurity.Unblock, "File", DefaultParameterSetName = "ByPath", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097033")] public sealed class UnblockFileCommand : PSCmdlet { #if UNIX private const string MacBlockAttribute = "com.apple.quarantine"; private const int RemovexattrFollowSymLink = 0; #endif /// <summary> /// The path of the file to unblock. /// </summary> [Parameter(Mandatory = true, Position = 0, ParameterSetName = "ByPath")] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] Path { get { return _paths; } set { _paths = value; } } /// <summary> /// The literal path of the file to unblock. /// </summary> [Parameter(Mandatory = true, ParameterSetName = "ByLiteralPath", ValueFromPipelineByPropertyName = true)] [Alias("PSPath", "LP")] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] LiteralPath { get { return _paths; } set { _paths = value; } } private string[] _paths; /// <summary> /// Generate the type(s) /// </summary> protected override void ProcessRecord() { List<string> pathsToProcess = new(); ProviderInfo provider = null; if (string.Equals(this.ParameterSetName, "ByLiteralPath", StringComparison.OrdinalIgnoreCase)) { foreach (string path in _paths) { string newPath = Context.SessionState.Path.GetUnresolvedProviderPathFromPSPath(path); if (IsValidFileForUnblocking(newPath)) { pathsToProcess.Add(newPath); } } } else { // Resolve paths foreach (string path in _paths) { try { Collection<string> newPaths = Context.SessionState.Path.GetResolvedProviderPathFromPSPath(path, out provider); foreach (string currentFilepath in newPaths) { if (IsValidFileForUnblocking(currentFilepath)) { pathsToProcess.Add(currentFilepath); } } } catch (ItemNotFoundException e) { if (!WildcardPattern.ContainsWildcardCharacters(path)) { ErrorRecord errorRecord = new(e, "FileNotFound", ErrorCategory.ObjectNotFound, path); WriteError(errorRecord); } } } } #if !UNIX // Unblock files foreach (string path in pathsToProcess) { if (ShouldProcess(path)) { try { AlternateDataStreamUtilities.DeleteFileStream(path, "Zone.Identifier"); } catch (Exception e) { WriteError(new ErrorRecord(exception: e, errorId: "RemoveItemUnableToAccessFile", ErrorCategory.ResourceUnavailable, targetObject: path)); } } } #else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { string errorMessage = UnblockFileStrings.LinuxNotSupported; Exception e = new PlatformNotSupportedException(errorMessage); ThrowTerminatingError(new ErrorRecord(exception: e, errorId: "LinuxNotSupported", ErrorCategory.NotImplemented, targetObject: null)); return; } foreach (string path in pathsToProcess) { if (IsBlocked(path)) { UInt32 result = RemoveXattr(path, MacBlockAttribute, RemovexattrFollowSymLink); if (result != 0) { string errorMessage = string.Format(CultureInfo.CurrentUICulture, UnblockFileStrings.UnblockError, path); Exception e = new InvalidOperationException(errorMessage); WriteError(new ErrorRecord(exception: e, errorId: "UnblockError", ErrorCategory.InvalidResult, targetObject: path)); } } } #endif } /// <summary> /// IsValidFileForUnblocking is a helper method used to validate if /// the supplied file path has to be considered for unblocking. /// </summary> /// <param name="resolvedpath">File or directory path.</param> /// <returns>True is the supplied path is a /// valid file path or else false is returned. /// If the supplied path is a directory path then false is returned.</returns> private bool IsValidFileForUnblocking(string resolvedpath) { bool isValidUnblockableFile = false; // Bug 501423 : silently ignore folders given that folders cannot have // alternate data streams attached to them (i.e. they're already unblocked). if (!System.IO.Directory.Exists(resolvedpath)) { if (!System.IO.File.Exists(resolvedpath)) { ErrorRecord errorRecord = new( new System.IO.FileNotFoundException(resolvedpath), "FileNotFound", ErrorCategory.ObjectNotFound, resolvedpath); WriteError(errorRecord); } else { isValidUnblockableFile = true; } } return isValidUnblockableFile; } #if UNIX private static bool IsBlocked(string path) { const uint valueSize = 1024; IntPtr value = Marshal.AllocHGlobal((int)valueSize); try { var resultSize = GetXattr(path, MacBlockAttribute, value, valueSize, 0, RemovexattrFollowSymLink); return resultSize != -1; } finally { Marshal.FreeHGlobal(value); } } // Ansi means UTF8 on Unix // https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/RemoveXattr.2.html [DllImport("libc", SetLastError = true, EntryPoint = "removexattr", CharSet = CharSet.Ansi)] private static extern UInt32 RemoveXattr(string path, string name, int options); [DllImport("libc", EntryPoint = "getxattr", CharSet = CharSet.Ansi)] private static extern long GetXattr( [MarshalAs(UnmanagedType.LPStr)] string path, [MarshalAs(UnmanagedType.LPStr)] string name, IntPtr value, ulong size, uint position, int options); #endif } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System; #if UNITY_EDITOR using UnityEditor; using Uni2DTextureImporterSettingsPair = System.Collections.Generic.KeyValuePair<UnityEngine.Texture2D, UnityEditor.TextureImporterSettings>; #endif // Animation clip [Serializable] [AddComponentMenu( "Uni2D/Sprite/Uni2DAnimationClip" )] public class Uni2DAnimationClip : MonoBehaviour { #if UNITY_EDITOR public enum AnimationClipRegeneration { RegenerateNothing, RegenerateAnimationClipOnly, RegenerateAlsoAtlasIfNeeded, RegenerateAll } #endif /// Wrap mode for the clip public enum WrapMode { // Loop Loop, // Play forward then backward infinitely PingPong, // Play once and reset the sprite to the main frame (the sprite without animation) Once, // Play once and stop but don't reset ClampForever }; private const string mc_oProgressBarTitle = "Uni2D Animation Clip"; // Default frame rate public const float defaultFrameRate = 12.0f; ///// Clip settings ///// // Frame rate public float frameRate = defaultFrameRate; // Wrap mode public WrapMode wrapMode; // Frames public List<Uni2DAnimationFrame> frames = new List<Uni2DAnimationFrame>( ); // Global atlas public Uni2DTextureAtlas globalAtlas = null; // Frame index by name private Dictionary<string, int> m_oFrameIndexByName; // Disables unused var warnings because these members are only unused in edit mode // but can't be removed since they're serialized... #pragma warning disable 414 ///// Inspector settings ///// // Frame rate [HideInInspector] [SerializeField] private float m_fSavedFrameRate = defaultFrameRate; // Wrap mode [HideInInspector] [SerializeField] private WrapMode m_eSavedWrapMode; // Frames [HideInInspector] [SerializeField] private List<Uni2DAnimationFrame> m_oSavedFrames = new List<Uni2DAnimationFrame>( ); // Global atlas [HideInInspector] [SerializeField] private Uni2DTextureAtlas m_rSavedGlobalAtlas = null; #pragma warning restore 414 // Unused var warnings restored // Frame count public int FrameCount { get { return frames.Count; } } // Try Get Frame Index By Name public bool TryGetFrameIndex(string a_oFrameName, out int a_iFrameIndex) { Dictionary<string, int> rFrameIndexByName = GetFrameIndexByName(); return rFrameIndexByName.TryGetValue(a_oFrameName, out a_iFrameIndex); } #if UNITY_EDITOR // Unapplied Settings? (inspector) public bool UnappliedSettings { get { if( m_eSavedWrapMode != wrapMode || m_fSavedFrameRate != frameRate || m_rSavedGlobalAtlas != globalAtlas || ( globalAtlas != null && globalAtlas.UnappliedSettings ) ) { return true; } else { return this.FramesAreDifferents( ); // Are settings inspector settings different from object ones? } } } // Frames are differents private bool FramesAreDifferents( ) { if( frames != null && m_oSavedFrames != null ) { if( frames.Count != m_oSavedFrames.Count ) { return true; } else { int iFrameIndex = 0; foreach( Uni2DAnimationFrame rFrame in frames ) { if( rFrame.IsDifferentFrom( m_oSavedFrames[ iFrameIndex ] ) ) { return true; } ++iFrameIndex; } } return false; } return frames != m_oSavedFrames; } // Copy clips private void CopyFrames( List<Uni2DAnimationFrame> a_rFramesSource, List<Uni2DAnimationFrame> a_rFramesDestination ) { // Update asset table Uni2DEditorAssetTable rAssetTable = Uni2DEditorAssetTable.Instance; string rClipGUID = Uni2DEditorUtils.GetUnityAssetGUID( this ); foreach( Uni2DAnimationFrame rOldFrame in a_rFramesDestination ) { string oTextureGUID = rOldFrame.textureContainer != null ? rOldFrame.textureContainer.GUID : null; if( !string.IsNullOrEmpty( oTextureGUID ) ) { rAssetTable.RemoveClipUsingTexture( rClipGUID, oTextureGUID ); } } a_rFramesDestination.Clear( ); foreach( Uni2DAnimationFrame rFrameSource in a_rFramesSource ) { a_rFramesDestination.Add( new Uni2DAnimationFrame( rFrameSource ) ); string oTextureGUID = rFrameSource.textureContainer != null ? rFrameSource.textureContainer.GUID : null; if( !string.IsNullOrEmpty( oTextureGUID ) ) { rAssetTable.AddClipUsingTexture( rClipGUID, oTextureGUID ); } } rAssetTable.Save( ); } public void SwapFrames( int a_iFrameIndexA, int a_iFrameIndexB ) { int iFrameCount = frames.Count; if( a_iFrameIndexA != a_iFrameIndexB && 0 <= a_iFrameIndexA && 0 <= a_iFrameIndexB && a_iFrameIndexA < iFrameCount && a_iFrameIndexB < iFrameCount ) { // Swap frames Uni2DAnimationFrame rTmp = frames[ a_iFrameIndexA ]; frames[ a_iFrameIndexA ] = frames[ a_iFrameIndexB ]; frames[ a_iFrameIndexB ] = rTmp; } } // On textures change public void OnTexturesChange( ICollection<string> a_rTextureGUIDs ) { List<Uni2DAnimationFrame> oFramesToUpdate = new List<Uni2DAnimationFrame>( ); foreach( Uni2DAnimationFrame rFrame in frames ) { if( a_rTextureGUIDs.Contains( rFrame.textureContainer.GUID ) ) { oFramesToUpdate.Add( rFrame ); } } GenerateTextureFramesInfos( oFramesToUpdate ); CopyFrames( frames, m_oSavedFrames ); EditorUtility.SetDirty( this ); AssetDatabase.SaveAssets( ); } // Apply settings from inspector public void ApplySettings( AnimationClipRegeneration a_eRegeneration = AnimationClipRegeneration.RegenerateAlsoAtlasIfNeeded ) { m_eSavedWrapMode = wrapMode; m_fSavedFrameRate = frameRate; m_rSavedGlobalAtlas = globalAtlas; if( a_eRegeneration != AnimationClipRegeneration.RegenerateNothing ) { Generate( a_eRegeneration ); // Generate frames infos (and atlas if needed/asked) CopyFrames( frames, m_oSavedFrames ); // frames -> m_oFrames (apply) } EditorUtility.SetDirty( this ); AssetDatabase.SaveAssets( ); } // Revert settings public void RevertSettings( ) { wrapMode = m_eSavedWrapMode; frameRate = m_fSavedFrameRate; globalAtlas = m_rSavedGlobalAtlas; if( globalAtlas != null ) { globalAtlas.RevertSettings( ); } CopyFrames( m_oSavedFrames, frames ); // m_oFrames -> frames (revert) EditorUtility.SetDirty( this ); AssetDatabase.SaveAssets( ); } // Generate private void Generate( AnimationClipRegeneration a_eRegeneration ) { GenerateAllFramesInfos( ); GenerateAtlas( a_eRegeneration ); } // Generate atlas private void GenerateAtlas( AnimationClipRegeneration a_eRegeneration ) { int iFrameCount = this.FrameCount; if( globalAtlas != null ) // global atlas { string[ ] oTextureGUIDs = this.GetAllFramesTextureGUIDs( ); if( a_eRegeneration == AnimationClipRegeneration.RegenerateAll || ( a_eRegeneration == AnimationClipRegeneration.RegenerateAlsoAtlasIfNeeded && ( globalAtlas.UnappliedSettings || globalAtlas.Contains( oTextureGUIDs ) == false ) ) ) { globalAtlas.ApplySettings( ); } globalAtlas.AddTextures( oTextureGUIDs ); } else // Atlas per frame { HashSet<Uni2DTextureAtlas> oFrameAtlases = new HashSet<Uni2DTextureAtlas>( ); for( int iFrameIndex = 0; iFrameIndex < iFrameCount; ++iFrameIndex ) { Uni2DAnimationFrame rFrame = frames[ iFrameIndex ]; Uni2DTextureAtlas rFrameAtlas = rFrame.atlas; if( rFrameAtlas != null ) { string oFrameTextureGUID = rFrame.textureContainer != null ? rFrame.textureContainer.GUID : null; if( a_eRegeneration == AnimationClipRegeneration.RegenerateAll || ( a_eRegeneration == AnimationClipRegeneration.RegenerateAlsoAtlasIfNeeded && ( rFrameAtlas.UnappliedSettings || rFrameAtlas.Contains( oFrameTextureGUID ) == false ) ) ) { oFrameAtlases.Add( rFrameAtlas ); } rFrameAtlas.AddTextures( new string[ 1 ]{ oFrameTextureGUID } ); } } // Regenerate atlases foreach( Uni2DTextureAtlas rFrameAtlas in oFrameAtlases ) { rFrameAtlas.ApplySettings( ); } } } // Generate all frames infos private void GenerateAllFramesInfos( ) { this.GenerateTextureFramesInfos( frames ); } // Update all frames infos about given textures private void GenerateTextureFramesInfos( ICollection<Uni2DAnimationFrame> a_rFramesToGenerate ) { Uni2DAssetPostprocessor.Enabled = false; EditorUtility.DisplayProgressBar( mc_oProgressBarTitle, "Reading texture settings...", 0.0f ); int iFrameCount = a_rFramesToGenerate.Count; int iFrameIndex = 0; Texture2D[ ] oFrameTextures = new Texture2D[ iFrameCount ]; foreach( Uni2DAnimationFrame rFrame in a_rFramesToGenerate ) { oFrameTextures[ iFrameIndex++ ] = rFrame.textureContainer.Texture; } // Prepare textures List<Uni2DTextureImporterSettingsPair> oImporterSettingsPair = Uni2DEditorSpriteBuilderUtils.TexturesProcessingBegin( oFrameTextures ); try { iFrameIndex = 1; float fInvCount = 1.0f / (float) iFrameCount; foreach( Uni2DAnimationFrame rFrame in a_rFramesToGenerate ) { EditorUtility.DisplayProgressBar( mc_oProgressBarTitle, "Generating frame #" + iFrameIndex + " out of " + iFrameCount, iFrameIndex * fInvCount ); rFrame.GenerateInfos( ); ++iFrameIndex; } // Restore Texture import settings EditorUtility.DisplayProgressBar( mc_oProgressBarTitle, "Restoring texture settings...", 1.0f ); } finally { Uni2DEditorSpriteBuilderUtils.TexturesProcessingEnd( oImporterSettingsPair ); EditorUtility.ClearProgressBar( ); Uni2DAssetPostprocessor.Enabled = true; } } // Get Textures private List<Texture2D> GetAllFramesTextures( ) { // Get textures List<Texture2D> rTextures = new List<Texture2D>( this.FrameCount ); foreach(Uni2DAnimationFrame rFrame in frames ) { rTextures.Add( rFrame.textureContainer ); } return rTextures; } public string[ ] GetAllFramesTextureGUIDs( ) { HashSet<string> oUniqueTextureGUIDs = new HashSet<string>( ); foreach( Uni2DAnimationFrame rFrame in frames ) { Texture2DContainer rTextureContainer = rFrame.textureContainer; if( rTextureContainer != null && !string.IsNullOrEmpty( rTextureContainer.GUID ) ) { oUniqueTextureGUIDs.Add( rTextureContainer.GUID ); } } string[ ] oTextureGUIDs = new string[ oUniqueTextureGUIDs.Count ]; oUniqueTextureGUIDs.CopyTo( oTextureGUIDs ); return oTextureGUIDs; } public bool AreClipAndAtlasSynced( ) { if( m_rSavedGlobalAtlas != null ) { foreach( Uni2DAnimationFrame rFrame in frames ) { Texture2D rFrameTexture = rFrame.textureContainer; if( rFrame.atlas != globalAtlas || ( rFrameTexture != null && globalAtlas.Contains( rFrameTexture ) == false ) ) { return false; } } } else { foreach( Uni2DAnimationFrame rFrame in frames ) { Texture2D rFrameTexture = rFrame.textureContainer; if( rFrameTexture != null && rFrame.atlas != null && rFrame.atlas.Contains( rFrameTexture ) == false ) { return false; } } } return true; } #endif // Get Frame Index By Name private Dictionary<string, int> GetFrameIndexByName() { if(m_oFrameIndexByName == null) { BuildFrameIndexByName(); } return m_oFrameIndexByName; } // Build Frame Index By Name private void BuildFrameIndexByName() { m_oFrameIndexByName = new Dictionary<string, int>(); int iFrameIndex = 0; foreach(Uni2DAnimationFrame rFrame in frames) { if(rFrame != null) { if(m_oFrameIndexByName.ContainsKey(rFrame.name) == false) { m_oFrameIndexByName.Add(rFrame.name, iFrameIndex); } } iFrameIndex++; } } }
/* * 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 OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System; using System.Runtime.Serialization; namespace OpenSim.Region.ScriptEngine.Shared { [Serializable] public class EventAbortException : Exception { public EventAbortException() { } protected EventAbortException( SerializationInfo info, StreamingContext context) { } } [Serializable] public class SelfDeleteException : Exception { public SelfDeleteException() { } protected SelfDeleteException( SerializationInfo info, StreamingContext context) { } } [Serializable] public class ScriptDeleteException : Exception { public ScriptDeleteException() { } protected ScriptDeleteException( SerializationInfo info, StreamingContext context) { } } /// <summary> /// Used to signal when the script is stopping in co-operation with the script engine /// (instead of through Thread.Abort()). /// </summary> [Serializable] public class ScriptCoopStopException : Exception { public ScriptCoopStopException() { } protected ScriptCoopStopException( SerializationInfo info, StreamingContext context) { } } public class DetectParams { public const int AGENT = 1; public const int ACTIVE = 2; public const int PASSIVE = 4; public const int SCRIPTED = 8; public const int OS_NPC = 0x01000000; public DetectParams() { Key = UUID.Zero; OffsetPos = new LSL_Types.Vector3(); LinkNum = 0; Group = UUID.Zero; Name = String.Empty; Owner = UUID.Zero; Position = new LSL_Types.Vector3(); Rotation = new LSL_Types.Quaternion(); Type = 0; Velocity = new LSL_Types.Vector3(); initializeSurfaceTouch(); } public UUID Key; public LSL_Types.Vector3 OffsetPos; public int LinkNum; public UUID Group; public string Name; public UUID Owner; public LSL_Types.Vector3 Position; public LSL_Types.Quaternion Rotation; public int Type; public LSL_Types.Vector3 Velocity; private LSL_Types.Vector3 touchST; public LSL_Types.Vector3 TouchST { get { return touchST; } } private LSL_Types.Vector3 touchNormal; public LSL_Types.Vector3 TouchNormal { get { return touchNormal; } } private LSL_Types.Vector3 touchBinormal; public LSL_Types.Vector3 TouchBinormal { get { return touchBinormal; } } private LSL_Types.Vector3 touchPos; public LSL_Types.Vector3 TouchPos { get { return touchPos; } } private LSL_Types.Vector3 touchUV; public LSL_Types.Vector3 TouchUV { get { return touchUV; } } private int touchFace; public int TouchFace { get { return touchFace; } } // This can be done in two places including the constructor // so be carefull what gets added here private void initializeSurfaceTouch() { touchST = new LSL_Types.Vector3(-1.0, -1.0, 0.0); touchNormal = new LSL_Types.Vector3(); touchBinormal = new LSL_Types.Vector3(); touchPos = new LSL_Types.Vector3(); touchUV = new LSL_Types.Vector3(-1.0, -1.0, 0.0); touchFace = -1; } /* * Set up the surface touch detected values */ public SurfaceTouchEventArgs SurfaceTouchArgs { set { if (value == null) { // Initialise to defaults if no value initializeSurfaceTouch(); } else { // Set the values from the touch data provided by the client touchST = new LSL_Types.Vector3(value.STCoord); touchUV = new LSL_Types.Vector3(value.UVCoord); touchNormal = new LSL_Types.Vector3(value.Normal); touchBinormal = new LSL_Types.Vector3(value.Binormal); touchPos = new LSL_Types.Vector3(value.Position); touchFace = value.FaceIndex; } } } public void Populate(Scene scene) { SceneObjectPart part = scene.GetSceneObjectPart(Key); if (part == null) // Avatar, maybe? { ScenePresence presence = scene.GetScenePresence(Key); if (presence == null) return; Name = presence.Firstname + " " + presence.Lastname; Owner = Key; Position = new LSL_Types.Vector3(presence.AbsolutePosition); Rotation = new LSL_Types.Quaternion( presence.Rotation.X, presence.Rotation.Y, presence.Rotation.Z, presence.Rotation.W); Velocity = new LSL_Types.Vector3(presence.Velocity); if (presence.PresenceType != PresenceType.Npc) { Type = AGENT; } else { Type = OS_NPC; INPCModule npcModule = scene.RequestModuleInterface<INPCModule>(); INPC npcData = npcModule.GetNPC(presence.UUID, presence.Scene); if (npcData.SenseAsAgent) { Type |= AGENT; } } if (presence.Velocity != Vector3.Zero) Type |= ACTIVE; Group = presence.ControllingClient.ActiveGroupId; return; } part = part.ParentGroup.RootPart; // We detect objects only LinkNum = 0; // Not relevant Group = part.GroupID; Name = part.Name; Owner = part.OwnerID; if (part.Velocity == Vector3.Zero) Type = PASSIVE; else Type = ACTIVE; foreach (SceneObjectPart p in part.ParentGroup.Parts) { if (p.Inventory.ContainsScripts()) { Type |= SCRIPTED; // Scripted break; } } Position = new LSL_Types.Vector3(part.AbsolutePosition); Quaternion wr = part.ParentGroup.GroupRotation; Rotation = new LSL_Types.Quaternion(wr.X, wr.Y, wr.Z, wr.W); Velocity = new LSL_Types.Vector3(part.Velocity); } } /// <summary> /// Holds all the data required to execute a scripting event. /// </summary> public class EventParams { public EventParams(string eventName, Object[] eventParams, DetectParams[] detectParams) { EventName = eventName; Params = eventParams; DetectParams = detectParams; } public string EventName; public Object[] Params; public DetectParams[] DetectParams; } }