context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
namespace BooCompiler.Tests
{
using NUnit.Framework;
[TestFixture]
public class CallablesIntegrationTestFixture : AbstractCompilerTestCase
{
[Test]
public void byref_1()
{
RunCompilerTestCase(@"byref-1.boo");
}
[Category("FailsOnMono")][Test]
public void byref_10()
{
RunCompilerTestCase(@"byref-10.boo");
}
[Test]
public void byref_11()
{
RunCompilerTestCase(@"byref-11.boo");
}
[Test]
public void byref_12()
{
RunCompilerTestCase(@"byref-12.boo");
}
[Test]
public void byref_13()
{
RunCompilerTestCase(@"byref-13.boo");
}
[Test]
public void byref_14()
{
RunCompilerTestCase(@"byref-14.boo");
}
[Test]
public void byref_2()
{
RunCompilerTestCase(@"byref-2.boo");
}
[Test]
public void byref_3()
{
RunCompilerTestCase(@"byref-3.boo");
}
[Test]
public void byref_4()
{
RunCompilerTestCase(@"byref-4.boo");
}
[Test]
public void byref_5()
{
RunCompilerTestCase(@"byref-5.boo");
}
[Test]
public void byref_6()
{
RunCompilerTestCase(@"byref-6.boo");
}
[Test]
public void byref_7()
{
RunCompilerTestCase(@"byref-7.boo");
}
[Test]
public void byref_8()
{
RunCompilerTestCase(@"byref-8.boo");
}
[Test]
public void byref_9()
{
RunCompilerTestCase(@"byref-9.boo");
}
[Test]
public void callables_1()
{
RunCompilerTestCase(@"callables-1.boo");
}
[Test]
public void callables_10()
{
RunCompilerTestCase(@"callables-10.boo");
}
[Test]
public void callables_11()
{
RunCompilerTestCase(@"callables-11.boo");
}
[Test]
public void callables_12()
{
RunCompilerTestCase(@"callables-12.boo");
}
[Test]
public void callables_13()
{
RunCompilerTestCase(@"callables-13.boo");
}
[Test]
public void callables_14()
{
RunCompilerTestCase(@"callables-14.boo");
}
[Test]
public void callables_15()
{
RunCompilerTestCase(@"callables-15.boo");
}
[Category("FailsOnMono4")][Test]
public void callables_16()
{
RunCompilerTestCase(@"callables-16.boo");
}
[Test]
public void callables_17()
{
RunCompilerTestCase(@"callables-17.boo");
}
[Test]
public void callables_18()
{
RunCompilerTestCase(@"callables-18.boo");
}
[Test]
public void callables_19()
{
RunCompilerTestCase(@"callables-19.boo");
}
[Test]
public void callables_2()
{
RunCompilerTestCase(@"callables-2.boo");
}
[Test]
public void callables_20()
{
RunCompilerTestCase(@"callables-20.boo");
}
[Test]
public void callables_21()
{
RunCompilerTestCase(@"callables-21.boo");
}
[Test]
public void callables_22()
{
RunCompilerTestCase(@"callables-22.boo");
}
[Test]
public void callables_23()
{
RunCompilerTestCase(@"callables-23.boo");
}
[Test]
public void callables_24()
{
RunCompilerTestCase(@"callables-24.boo");
}
[Test]
public void callables_25()
{
RunCompilerTestCase(@"callables-25.boo");
}
[Test]
public void callables_26()
{
RunCompilerTestCase(@"callables-26.boo");
}
[Test]
public void callables_27()
{
RunCompilerTestCase(@"callables-27.boo");
}
[Test]
public void callables_28()
{
RunCompilerTestCase(@"callables-28.boo");
}
[Test]
public void callables_29()
{
RunCompilerTestCase(@"callables-29.boo");
}
[Test]
public void callables_3()
{
RunCompilerTestCase(@"callables-3.boo");
}
[Test]
public void callables_30()
{
RunCompilerTestCase(@"callables-30.boo");
}
[Test]
public void callables_31()
{
RunCompilerTestCase(@"callables-31.boo");
}
[Test]
public void callables_32()
{
RunCompilerTestCase(@"callables-32.boo");
}
[Test]
public void callables_33()
{
RunCompilerTestCase(@"callables-33.boo");
}
[Test]
public void callables_34()
{
RunCompilerTestCase(@"callables-34.boo");
}
[Test]
public void callables_35()
{
RunCompilerTestCase(@"callables-35.boo");
}
[Test]
public void callables_36()
{
RunCompilerTestCase(@"callables-36.boo");
}
[Test]
public void callables_37()
{
RunCompilerTestCase(@"callables-37.boo");
}
[Test]
public void callables_38()
{
RunCompilerTestCase(@"callables-38.boo");
}
[Category("FailsOnMono4")][Test]
public void callables_39()
{
RunCompilerTestCase(@"callables-39.boo");
}
[Test]
public void callables_4()
{
RunCompilerTestCase(@"callables-4.boo");
}
[Test]
public void callables_40()
{
RunCompilerTestCase(@"callables-40.boo");
}
[Category("FailsOnMono4")][Test]
public void callables_41()
{
RunCompilerTestCase(@"callables-41.boo");
}
[Test]
public void callables_42()
{
RunCompilerTestCase(@"callables-42.boo");
}
[Category("FailsOnMono4")][Test]
public void callables_43()
{
RunCompilerTestCase(@"callables-43.boo");
}
[Test]
public void callables_44()
{
RunCompilerTestCase(@"callables-44.boo");
}
[Test]
public void callables_45()
{
RunCompilerTestCase(@"callables-45.boo");
}
[Test]
public void callables_46()
{
RunCompilerTestCase(@"callables-46.boo");
}
[Test]
public void callables_47()
{
RunCompilerTestCase(@"callables-47.boo");
}
[Test]
public void callables_48()
{
RunCompilerTestCase(@"callables-48.boo");
}
[Test]
public void callables_49()
{
RunCompilerTestCase(@"callables-49.boo");
}
[Test]
public void callables_5()
{
RunCompilerTestCase(@"callables-5.boo");
}
[Test]
public void callables_50()
{
RunCompilerTestCase(@"callables-50.boo");
}
[Test]
public void callables_6()
{
RunCompilerTestCase(@"callables-6.boo");
}
[Test]
public void callables_7()
{
RunCompilerTestCase(@"callables-7.boo");
}
[Test]
public void callables_8()
{
RunCompilerTestCase(@"callables-8.boo");
}
[Test]
public void callables_9()
{
RunCompilerTestCase(@"callables-9.boo");
}
[Test]
public void callables_as_ternary_operands()
{
RunCompilerTestCase(@"callables-as-ternary-operands.boo");
}
[Test]
public void callables_as_ternay_operands_invocation()
{
RunCompilerTestCase(@"callables-as-ternay-operands-invocation.boo");
}
[Test]
public void delegates_1()
{
RunCompilerTestCase(@"delegates-1.boo");
}
[Test]
public void delegates_10()
{
RunCompilerTestCase(@"delegates-10.boo");
}
[Test]
public void delegates_11()
{
RunCompilerTestCase(@"delegates-11.boo");
}
[Test]
public void delegates_12()
{
RunCompilerTestCase(@"delegates-12.boo");
}
[Test]
public void delegates_13()
{
RunCompilerTestCase(@"delegates-13.boo");
}
[Test]
public void delegates_14()
{
RunCompilerTestCase(@"delegates-14.boo");
}
[Test]
public void delegates_15()
{
RunCompilerTestCase(@"delegates-15.boo");
}
[Test]
public void delegates_16()
{
RunCompilerTestCase(@"delegates-16.boo");
}
[Test]
public void delegates_17()
{
RunCompilerTestCase(@"delegates-17.boo");
}
[Test]
public void delegates_18()
{
RunCompilerTestCase(@"delegates-18.boo");
}
[Test]
public void delegates_2()
{
RunCompilerTestCase(@"delegates-2.boo");
}
[Test]
public void delegates_3()
{
RunCompilerTestCase(@"delegates-3.boo");
}
[Test]
public void delegates_4()
{
RunCompilerTestCase(@"delegates-4.boo");
}
[Test]
public void delegates_5()
{
RunCompilerTestCase(@"delegates-5.boo");
}
[Test]
public void delegates_6()
{
RunCompilerTestCase(@"delegates-6.boo");
}
[Test]
public void delegates_7()
{
RunCompilerTestCase(@"delegates-7.boo");
}
[Test]
public void delegates_8()
{
RunCompilerTestCase(@"delegates-8.boo");
}
[Test]
public void delegates_9()
{
RunCompilerTestCase(@"delegates-9.boo");
}
[Test]
public void generic_dict_of_anonymous_callable()
{
RunCompilerTestCase(@"generic-dict-of-anonymous-callable.boo");
}
[Test]
public void method_as_macro_1()
{
RunCompilerTestCase(@"method-as-macro-1.boo");
}
[Test]
public void method_as_macro_2()
{
RunCompilerTestCase(@"method-as-macro-2.boo");
}
[Test]
public void method_as_macro_3()
{
RunCompilerTestCase(@"method-as-macro-3.boo");
}
[Test]
public void method_invocations_1()
{
RunCompilerTestCase(@"method-invocations-1.boo");
}
[Test]
public void out_1()
{
RunCompilerTestCase(@"out-1.boo");
}
[Test]
public void out_2()
{
RunCompilerTestCase(@"out-2.boo");
}
[Test]
public void out_3()
{
RunCompilerTestCase(@"out-3.boo");
}
[Test]
public void overload_resolution_1()
{
RunCompilerTestCase(@"overload-resolution-1.boo");
}
[Test]
public void overload_resolution_2()
{
RunCompilerTestCase(@"overload-resolution-2.boo");
}
[Test]
public void params_1()
{
RunCompilerTestCase(@"params-1.boo");
}
[Test]
public void params_2()
{
RunCompilerTestCase(@"params-2.boo");
}
[Test]
public void params_3()
{
RunCompilerTestCase(@"params-3.boo");
}
[Test]
public void params_4()
{
RunCompilerTestCase(@"params-4.boo");
}
[Test]
public void params_5()
{
RunCompilerTestCase(@"params-5.boo");
}
[Test]
public void params_6()
{
RunCompilerTestCase(@"params-6.boo");
}
[Category("FailsOnMono4")][Test]
public void params_7()
{
RunCompilerTestCase(@"params-7.boo");
}
[Test]
public void params_8()
{
RunCompilerTestCase(@"params-8.boo");
}
override protected string GetRelativeTestCasesPath()
{
return "integration/callables";
}
}
}
| |
#pragma warning disable
// Copyright (c) Microsoft Corporation. All rights reserved.
/*============================================================
** Class: BigRational
**
** Purpose:
** --------
** This class is used to represent an arbitrary precision
** BigRational number
**
** A rational number (commonly called a fraction) is a ratio
** between two integers. For example (3/6) = (2/4) = (1/2)
**
** Arithmetic
** ----------
** a/b = c/d, iff ad = bc
** a/b + c/d == (ad + bc)/bd
** a/b - c/d == (ad - bc)/bd
** a/b % c/d == (ad % bc)/bd
** a/b * c/d == (ac)/(bd)
** a/b / c/d == (ad)/(bc)
** -(a/b) == (-a)/b
** (a/b)^(-1) == b/a, if a != 0
**
** Reduction Algorithm
** ------------------------
** Euclid's algorithm is used to simplify the fraction.
** Calculating the greatest common divisor of two n-digit
** numbers can be found in
**
** O(n(log n)^5 (log log n)) steps as n -> +infinity
============================================================*/
namespace Numerics {
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
[Serializable]
[ComVisible(false)]
public struct BigRational : IComparable, IComparable<BigRational>, IDeserializationCallback, IEquatable<BigRational>, ISerializable {
// ---- SECTION: members supporting exposed properties -------------*
private BigInteger m_numerator;
private BigInteger m_denominator;
private static readonly BigRational s_brZero = new BigRational(BigInteger.Zero);
private static readonly BigRational s_brOne = new BigRational(BigInteger.One);
private static readonly BigRational s_brMinusOne = new BigRational(BigInteger.MinusOne);
// ---- SECTION: members for internal support ---------*
#region Members for Internal Support
[StructLayout(LayoutKind.Explicit)]
internal struct DoubleUlong {
[FieldOffset(0)]
public double dbl;
[FieldOffset(0)]
public ulong uu;
}
private const int DoubleMaxScale = 308;
private static readonly BigInteger s_bnDoublePrecision = BigInteger.Pow(10, DoubleMaxScale);
private static readonly BigInteger s_bnDoubleMaxValue = (BigInteger) Double.MaxValue;
private static readonly BigInteger s_bnDoubleMinValue = (BigInteger) Double.MinValue;
[StructLayout(LayoutKind.Explicit)]
internal struct DecimalUInt32 {
[FieldOffset(0)]
public Decimal dec;
[FieldOffset(0)]
public int flags;
}
private const int DecimalScaleMask = 0x00FF0000;
private const int DecimalSignMask = unchecked((int)0x80000000);
private const int DecimalMaxScale = 28;
private static readonly BigInteger s_bnDecimalPrecision = BigInteger.Pow(10, DecimalMaxScale);
private static readonly BigInteger s_bnDecimalMaxValue = (BigInteger) Decimal.MaxValue;
private static readonly BigInteger s_bnDecimalMinValue = (BigInteger) Decimal.MinValue;
private const String c_solidus = @"/";
#endregion Members for Internal Support
// ---- SECTION: public properties --------------*
#region Public Properties
public static BigRational Zero {
get {
return s_brZero;
}
}
public static BigRational One {
get {
return s_brOne;
}
}
public static BigRational MinusOne {
get {
return s_brMinusOne;
}
}
public Int32 Sign {
get {
return m_numerator.Sign;
}
}
public BigInteger Numerator {
get {
return m_numerator;
}
}
public BigInteger Denominator {
get {
return m_denominator;
}
}
#endregion Public Properties
// ---- SECTION: public instance methods --------------*
#region Public Instance Methods
// GetWholePart() and GetFractionPart()
//
// BigRational == Whole, Fraction
// 0/2 == 0, 0/2
// 1/2 == 0, 1/2
// -1/2 == 0, -1/2
// 1/1 == 1, 0/1
// -1/1 == -1, 0/1
// -3/2 == -1, -1/2
// 3/2 == 1, 1/2
public BigInteger GetWholePart() {
return BigInteger.Divide(m_numerator, m_denominator);
}
public BigRational GetFractionPart() {
return new BigRational(BigInteger.Remainder(m_numerator, m_denominator), m_denominator);
}
public override bool Equals(Object obj) {
if (obj == null)
return false;
if (!(obj is BigRational))
return false;
return this.Equals((BigRational)obj);
}
public override int GetHashCode() {
return (m_numerator / Denominator).GetHashCode();
}
// IComparable
int IComparable.CompareTo(Object obj) {
if (obj == null)
return 1;
if (!(obj is BigRational))
throw new ArgumentException("Argument must be of type BigRational", "obj");
return Compare(this, (BigRational)obj);
}
// IComparable<BigRational>
public int CompareTo(BigRational other) {
return Compare(this, other);
}
// Object.ToString
public override String ToString() {
StringBuilder ret = new StringBuilder();
ret.Append(m_numerator.ToString("R", CultureInfo.InvariantCulture));
ret.Append(c_solidus);
ret.Append(Denominator.ToString("R", CultureInfo.InvariantCulture));
return ret.ToString();
}
// IEquatable<BigRational>
// a/b = c/d, iff ad = bc
public Boolean Equals(BigRational other) {
if (this.Denominator == other.Denominator) {
return m_numerator == other.m_numerator;
}
else {
return (m_numerator * other.Denominator) == (Denominator * other.m_numerator);
}
}
#endregion Public Instance Methods
// -------- SECTION: constructors -----------------*
#region Constructors
public BigRational(BigInteger numerator) {
m_numerator = numerator;
m_denominator = BigInteger.One;
}
// BigRational(Double)
public BigRational(Double value) {
if (Double.IsNaN(value)) {
throw new ArgumentException("Argument is not a number", "value");
}
else if (Double.IsInfinity(value)) {
throw new ArgumentException("Argument is infinity", "value");
}
bool isFinite;
int sign;
int exponent;
ulong significand;
SplitDoubleIntoParts(value, out sign, out exponent, out significand, out isFinite);
if (significand == 0) {
this = BigRational.Zero;
return;
}
m_numerator = significand;
m_denominator = 1 << 52;
if (exponent > 0) {
m_numerator = BigInteger.Pow(m_numerator, exponent);
}
else if (exponent < 0) {
m_denominator = BigInteger.Pow(m_denominator, -exponent);
}
if (sign < 0) {
m_numerator = BigInteger.Negate(m_numerator);
}
Simplify();
}
// BigRational(Decimal) -
//
// The Decimal type represents floating point numbers exactly, with no rounding error.
// Values such as "0.1" in Decimal are actually representable, and convert cleanly
// to BigRational as "11/10"
public BigRational(Decimal value) {
int[] bits = Decimal.GetBits(value);
if (bits == null || bits.Length != 4 || (bits[3] & ~(DecimalSignMask | DecimalScaleMask)) != 0 || (bits[3] & DecimalScaleMask) > (28 << 16)) {
throw new ArgumentException("invalid Decimal", "value");
}
if (value == Decimal.Zero) {
this = BigRational.Zero;
return;
}
// build up the numerator
ulong ul = (((ulong)(uint)bits[2]) << 32) | ((ulong)(uint)bits[1]); // (hi << 32) | (mid)
m_numerator = (new BigInteger(ul) << 32) | (uint)bits[0]; // (hiMid << 32) | (low)
bool isNegative = (bits[3] & DecimalSignMask) != 0;
if (isNegative) {
m_numerator = BigInteger.Negate(m_numerator);
}
// build up the denominator
int scale = (bits[3] & DecimalScaleMask) >> 16; // 0-28, power of 10 to divide numerator by
m_denominator = BigInteger.Pow(10, scale);
Simplify();
}
public BigRational(BigInteger numerator, BigInteger denominator) {
if (denominator.Sign == 0) {
throw new DivideByZeroException();
}
else if (numerator.Sign == 0) {
// 0/m -> 0/1
m_numerator = BigInteger.Zero;
m_denominator = BigInteger.One;
}
else if (denominator.Sign < 0) {
m_numerator = BigInteger.Negate(numerator);
m_denominator = BigInteger.Negate(denominator);
}
else {
m_numerator = numerator;
m_denominator = denominator;
}
Simplify();
}
public BigRational(BigInteger whole, BigInteger numerator, BigInteger denominator) {
if (denominator.Sign == 0) {
throw new DivideByZeroException();
}
else if (numerator.Sign == 0 && whole.Sign == 0) {
m_numerator = BigInteger.Zero;
m_denominator = BigInteger.One;
}
else if (denominator.Sign < 0) {
m_denominator = BigInteger.Negate(denominator);
m_numerator = (BigInteger.Negate(whole) * m_denominator) + BigInteger.Negate(numerator);
}
else {
m_denominator = denominator;
m_numerator = (whole * denominator) + numerator;
}
Simplify();
}
#endregion Constructors
// -------- SECTION: public static methods -----------------*
#region Public Static Methods
public static BigRational Abs(BigRational r) {
return (r.m_numerator.Sign < 0 ? new BigRational(BigInteger.Abs(r.m_numerator), r.Denominator) : r);
}
public static BigRational Negate(BigRational r) {
return new BigRational(BigInteger.Negate(r.m_numerator), r.Denominator);
}
public static BigRational Invert(BigRational r) {
return new BigRational(r.Denominator, r.m_numerator);
}
public static BigRational Add(BigRational x, BigRational y) {
return x + y;
}
public static BigRational Subtract(BigRational x, BigRational y) {
return x - y;
}
public static BigRational Multiply(BigRational x, BigRational y) {
return x * y;
}
public static BigRational Divide(BigRational dividend, BigRational divisor) {
return dividend / divisor;
}
public static BigRational Remainder(BigRational dividend, BigRational divisor) {
return dividend % divisor;
}
public static BigRational DivRem(BigRational dividend, BigRational divisor, out BigRational remainder) {
// a/b / c/d == (ad)/(bc)
// a/b % c/d == (ad % bc)/bd
// (ad) and (bc) need to be calculated for both the division and the remainder operations.
BigInteger ad = dividend.m_numerator * divisor.Denominator;
BigInteger bc = dividend.Denominator * divisor.m_numerator;
BigInteger bd = dividend.Denominator * divisor.Denominator;
remainder = new BigRational(ad % bc, bd);
return new BigRational(ad, bc);
}
public static BigRational Pow(BigRational baseValue, BigInteger exponent) {
if (exponent.Sign == 0) {
// 0^0 -> 1
// n^0 -> 1
return BigRational.One;
}
else if (exponent.Sign < 0) {
if (baseValue == BigRational.Zero) {
throw new ArgumentException("cannot raise zero to a negative power", "baseValue");
}
// n^(-e) -> (1/n)^e
baseValue = BigRational.Invert(baseValue);
exponent = BigInteger.Negate(exponent);
}
BigRational result = baseValue;
while (exponent > BigInteger.One) {
result = result * baseValue;
exponent--;
}
return result;
}
// Least Common Denominator (LCD)
//
// The LCD is the least common multiple of the two denominators. For instance, the LCD of
// {1/2, 1/4} is 4 because the least common multiple of 2 and 4 is 4. Likewise, the LCD
// of {1/2, 1/3} is 6.
//
// To find the LCD:
//
// 1) Find the Greatest Common Divisor (GCD) of the denominators
// 2) Multiply the denominators together
// 3) Divide the product of the denominators by the GCD
public static BigInteger LeastCommonDenominator(BigRational x, BigRational y) {
// LCD( a/b, c/d ) == (bd) / gcd(b,d)
return (x.Denominator * y.Denominator) / BigInteger.GreatestCommonDivisor(x.Denominator, y.Denominator);
}
public static int Compare(BigRational r1, BigRational r2) {
// a/b = c/d, iff ad = bc
return BigInteger.Compare(r1.m_numerator * r2.Denominator, r2.m_numerator * r1.Denominator);
}
#endregion Public Static Methods
#region Operator Overloads
public static bool operator ==(BigRational x, BigRational y) {
return Compare(x, y) == 0;
}
public static bool operator !=(BigRational x, BigRational y) {
return Compare(x, y) != 0;
}
public static bool operator <(BigRational x, BigRational y) {
return Compare(x, y) < 0;
}
public static bool operator <=(BigRational x, BigRational y) {
return Compare(x, y) <= 0;
}
public static bool operator >(BigRational x, BigRational y) {
return Compare(x, y) > 0;
}
public static bool operator >=(BigRational x, BigRational y) {
return Compare(x, y) >= 0;
}
public static BigRational operator +(BigRational r) {
return r;
}
public static BigRational operator -(BigRational r) {
return new BigRational(-r.m_numerator, r.Denominator);
}
public static BigRational operator ++ (BigRational r) {
return r + BigRational.One;
}
public static BigRational operator -- (BigRational r) {
return r - BigRational.One;
}
public static BigRational operator +(BigRational r1, BigRational r2) {
// a/b + c/d == (ad + bc)/bd
return new BigRational((r1.m_numerator * r2.Denominator) + (r1.Denominator * r2.m_numerator), (r1.Denominator * r2.Denominator));
}
public static BigRational operator -(BigRational r1, BigRational r2) {
// a/b - c/d == (ad - bc)/bd
return new BigRational((r1.m_numerator * r2.Denominator) - (r1.Denominator * r2.m_numerator), (r1.Denominator * r2.Denominator));
}
public static BigRational operator *(BigRational r1, BigRational r2) {
// a/b * c/d == (ac)/(bd)
return new BigRational((r1.m_numerator * r2.m_numerator), (r1.Denominator * r2.Denominator));
}
public static BigRational operator /(BigRational r1, BigRational r2) {
// a/b / c/d == (ad)/(bc)
return new BigRational((r1.m_numerator * r2.Denominator), (r1.Denominator * r2.m_numerator));
}
public static BigRational operator %(BigRational r1, BigRational r2) {
// a/b % c/d == (ad % bc)/bd
return new BigRational((r1.m_numerator * r2.Denominator) % (r1.Denominator * r2.m_numerator), (r1.Denominator * r2.Denominator));
}
#endregion Operator Overloads
// ----- SECTION: explicit conversions from BigRational to numeric base types ----------------*
#region explicit conversions from BigRational
[CLSCompliant(false)]
public static explicit operator SByte(BigRational value) {
return (SByte)(BigInteger.Divide(value.m_numerator, value.m_denominator));
}
[CLSCompliant(false)]
public static explicit operator UInt16(BigRational value) {
return (UInt16)(BigInteger.Divide(value.m_numerator, value.m_denominator));
}
[CLSCompliant(false)]
public static explicit operator UInt32(BigRational value) {
return (UInt32)(BigInteger.Divide(value.m_numerator, value.m_denominator));
}
[CLSCompliant(false)]
public static explicit operator UInt64(BigRational value) {
return (UInt64)(BigInteger.Divide(value.m_numerator, value.m_denominator));
}
public static explicit operator Byte(BigRational value) {
return (Byte)(BigInteger.Divide(value.m_numerator, value.m_denominator));
}
public static explicit operator Int16(BigRational value) {
return (Int16)(BigInteger.Divide(value.m_numerator, value.m_denominator));
}
public static explicit operator Int32(BigRational value) {
return (Int32)(BigInteger.Divide(value.m_numerator, value.m_denominator));
}
public static explicit operator Int64(BigRational value) {
return (Int64)(BigInteger.Divide(value.m_numerator, value.m_denominator));
}
public static explicit operator BigInteger(BigRational value) {
return BigInteger.Divide(value.m_numerator, value.m_denominator);
}
public static explicit operator Single(BigRational value) {
// The Single value type represents a single-precision 32-bit number with
// values ranging from negative 3.402823e38 to positive 3.402823e38
// values that do not fit into this range are returned as Infinity
return (Single)((Double)value);
}
public static explicit operator Double(BigRational value) {
// The Double value type represents a double-precision 64-bit number with
// values ranging from -1.79769313486232e308 to +1.79769313486232e308
// values that do not fit into this range are returned as +/-Infinity
if (SafeCastToDouble(value.m_numerator) && SafeCastToDouble(value.m_denominator)) {
return (Double) value.m_numerator / (Double) value.m_denominator;
}
// scale the numerator to preseve the fraction part through the integer division
BigInteger denormalized = (value.m_numerator * s_bnDoublePrecision) / value.m_denominator;
if (denormalized.IsZero)
return (value.Sign < 0) ? BitConverter.Int64BitsToDouble(unchecked((long)0x8000000000000000)) : 0d; // underflow to -+0
Double result = 0;
bool isDouble = false;
int scale = DoubleMaxScale;
while (scale > 0) {
if (!isDouble) {
if (SafeCastToDouble(denormalized)) {
result = (Double) denormalized;
isDouble = true;
}
else {
denormalized = denormalized / 10;
}
}
result = result / 10;
scale--;
}
if (!isDouble)
return (value.Sign < 0) ? Double.NegativeInfinity : Double.PositiveInfinity;
else
return result;
}
public static explicit operator Decimal(BigRational value) {
// The Decimal value type represents decimal numbers ranging
// from +79,228,162,514,264,337,593,543,950,335 to -79,228,162,514,264,337,593,543,950,335
// the binary representation of a Decimal value is of the form, ((-2^96 to 2^96) / 10^(0 to 28))
if (SafeCastToDecimal(value.m_numerator) && SafeCastToDecimal(value.m_denominator)) {
return (Decimal) value.m_numerator / (Decimal) value.m_denominator;
}
// scale the numerator to preseve the fraction part through the integer division
BigInteger denormalized = (value.m_numerator * s_bnDecimalPrecision) / value.m_denominator;
if (denormalized.IsZero) {
return Decimal.Zero; // underflow - fraction is too small to fit in a decimal
}
for (int scale = DecimalMaxScale; scale >= 0; scale--) {
if (!SafeCastToDecimal(denormalized)) {
denormalized = denormalized / 10;
}
else {
DecimalUInt32 dec = new DecimalUInt32();
dec.dec = (Decimal) denormalized;
dec.flags = (dec.flags & ~DecimalScaleMask) | (scale << 16);
return dec.dec;
}
}
throw new OverflowException("Value was either too large or too small for a Decimal.");
}
#endregion explicit conversions from BigRational
// ----- SECTION: implicit conversions from numeric base types to BigRational ----------------*
#region implicit conversions to BigRational
[CLSCompliant(false)]
public static implicit operator BigRational(SByte value) {
return new BigRational((BigInteger)value);
}
[CLSCompliant(false)]
public static implicit operator BigRational(UInt16 value) {
return new BigRational((BigInteger)value);
}
[CLSCompliant(false)]
public static implicit operator BigRational(UInt32 value) {
return new BigRational((BigInteger)value);
}
[CLSCompliant(false)]
public static implicit operator BigRational(UInt64 value) {
return new BigRational((BigInteger)value);
}
public static implicit operator BigRational(Byte value) {
return new BigRational((BigInteger)value);
}
public static implicit operator BigRational(Int16 value) {
return new BigRational((BigInteger)value);
}
public static implicit operator BigRational(Int32 value) {
return new BigRational((BigInteger)value);
}
public static implicit operator BigRational(Int64 value) {
return new BigRational((BigInteger)value);
}
public static implicit operator BigRational(BigInteger value) {
return new BigRational(value);
}
public static implicit operator BigRational(Single value) {
return new BigRational((Double)value);
}
public static implicit operator BigRational(Double value) {
return new BigRational(value);
}
public static implicit operator BigRational(Decimal value) {
return new BigRational(value);
}
#endregion implicit conversions to BigRational
// ----- SECTION: private serialization instance methods ----------------*
#region serialization
void IDeserializationCallback.OnDeserialization(Object sender) {
try {
// verify that the deserialized number is well formed
if (m_denominator.Sign == 0 || m_numerator.Sign == 0) {
// n/0 -> 0/1
// 0/m -> 0/1
m_numerator = BigInteger.Zero;
m_denominator = BigInteger.One;
}
else if (m_denominator.Sign < 0) {
m_numerator = BigInteger.Negate(m_numerator);
m_denominator = BigInteger.Negate(m_denominator);
}
Simplify();
}
catch (ArgumentException e) {
throw new SerializationException("invalid serialization data", e);
}
}
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
if (info == null) {
throw new ArgumentNullException("info");
}
info.AddValue("Numerator", m_numerator);
info.AddValue("Denominator", m_denominator);
}
BigRational(SerializationInfo info, StreamingContext context) {
if (info == null) {
throw new ArgumentNullException("info");
}
m_numerator = (BigInteger)info.GetValue("Numerator", typeof(BigInteger));
m_denominator = (BigInteger)info.GetValue("Denominator", typeof(BigInteger));
}
#endregion serialization
// ----- SECTION: private instance utility methods ----------------*
#region instance helper methods
private void Simplify() {
// * if the numerator is {0, +1, -1} then the fraction is already reduced
// * if the denominator is {+1} then the fraction is already reduced
if (m_numerator == BigInteger.Zero) {
m_denominator = BigInteger.One;
}
BigInteger gcd = BigInteger.GreatestCommonDivisor(m_numerator, m_denominator);
if(gcd > BigInteger.One) {
m_numerator = m_numerator / gcd;
m_denominator = Denominator / gcd;
}
}
#endregion instance helper methods
// ----- SECTION: private static utility methods -----------------*
#region static helper methods
private static bool SafeCastToDouble(BigInteger value) {
return s_bnDoubleMinValue <= value && value <= s_bnDoubleMaxValue;
}
private static bool SafeCastToDecimal(BigInteger value) {
return s_bnDecimalMinValue <= value && value <= s_bnDecimalMaxValue;
}
private static void SplitDoubleIntoParts(double dbl, out int sign, out int exp, out ulong man, out bool isFinite) {
DoubleUlong du;
du.uu = 0;
du.dbl = dbl;
sign = 1 - ((int)(du.uu >> 62) & 2);
man = du.uu & 0x000FFFFFFFFFFFFF;
exp = (int)(du.uu >> 52) & 0x7FF;
if (exp == 0) {
// Denormalized number.
isFinite = true;
if (man != 0)
exp = -1074;
}
else if (exp == 0x7FF) {
// NaN or Infinite.
isFinite = false;
exp = Int32.MaxValue;
}
else {
isFinite = true;
man |= 0x0010000000000000; // mask in the implied leading 53rd significand bit
exp -= 1075;
}
}
private static double GetDoubleFromParts(int sign, int exp, ulong man) {
DoubleUlong du;
du.dbl = 0;
if (man == 0) {
du.uu = 0;
}
else {
// Normalize so that 0x0010 0000 0000 0000 is the highest bit set
int cbitShift = CbitHighZero(man) - 11;
if (cbitShift < 0)
man >>= -cbitShift;
else
man <<= cbitShift;
// Move the point to just behind the leading 1: 0x001.0 0000 0000 0000
// (52 bits) and skew the exponent (by 0x3FF == 1023)
exp += 1075;
if (exp >= 0x7FF) {
// Infinity
du.uu = 0x7FF0000000000000;
}
else if (exp <= 0) {
// Denormalized
exp--;
if (exp < -52) {
// Underflow to zero
du.uu = 0;
}
else {
du.uu = man >> -exp;
}
}
else {
// Mask off the implicit high bit
du.uu = (man & 0x000FFFFFFFFFFFFF) | ((ulong) exp << 52);
}
}
if (sign < 0) {
du.uu |= 0x8000000000000000;
}
return du.dbl;
}
private static int CbitHighZero(ulong uu) {
if ((uu & 0xFFFFFFFF00000000) == 0)
return 32 + CbitHighZero((uint) uu);
return CbitHighZero((uint) (uu >> 32));
}
private static int CbitHighZero(uint u) {
if (u == 0)
return 32;
int cbit = 0;
if ((u & 0xFFFF0000) == 0) {
cbit += 16;
u <<= 16;
}
if ((u & 0xFF000000) == 0) {
cbit += 8;
u <<= 8;
}
if ((u & 0xF0000000) == 0) {
cbit += 4;
u <<= 4;
}
if ((u & 0xC0000000) == 0) {
cbit += 2;
u <<= 2;
}
if ((u & 0x80000000) == 0)
cbit += 1;
return cbit;
}
#endregion static helper methods
} // BigRational
} // namespace Numerics
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
namespace OpenSim.Groups
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "GroupsModule")]
public class GroupsModule : ISharedRegionModule, IGroupsModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private ThreadedClasses.RwLockedList<Scene> m_sceneList = new ThreadedClasses.RwLockedList<Scene>();
private IMessageTransferModule m_msgTransferModule = null;
private IGroupsServicesConnector m_groupData = null;
private IUserManagement m_UserManagement;
// Configuration settings
private bool m_groupsEnabled = false;
private bool m_groupNoticesEnabled = true;
private bool m_debugEnabled = false;
private int m_levelGroupCreate = 0;
#region Region Module interfaceBase Members
public void Initialise(IConfigSource config)
{
IConfig groupsConfig = config.Configs["Groups"];
if (groupsConfig == null)
{
// Do not run this module by default.
return;
}
else
{
m_groupsEnabled = groupsConfig.GetBoolean("Enabled", false);
if (!m_groupsEnabled)
{
return;
}
if (groupsConfig.GetString("Module", "Default") != Name)
{
m_groupsEnabled = false;
return;
}
m_log.InfoFormat("[Groups]: Initializing {0}", this.Name);
m_groupNoticesEnabled = groupsConfig.GetBoolean("NoticesEnabled", true);
m_debugEnabled = groupsConfig.GetBoolean("DebugEnabled", false);
m_levelGroupCreate = groupsConfig.GetInt("LevelGroupCreate", 0);
}
}
public void AddRegion(Scene scene)
{
if (m_groupsEnabled)
{
scene.RegisterModuleInterface<IGroupsModule>(this);
scene.AddCommand(
"Debug",
this,
"debug groups verbose",
"debug groups verbose <true|false>",
"This setting turns on very verbose groups debugging",
HandleDebugGroupsVerbose);
}
}
private void HandleDebugGroupsVerbose(object modules, string[] args)
{
if (args.Length < 4)
{
MainConsole.Instance.Output("Usage: debug groups verbose <true|false>");
return;
}
bool verbose = false;
if (!bool.TryParse(args[3], out verbose))
{
MainConsole.Instance.Output("Usage: debug groups verbose <true|false>");
return;
}
m_debugEnabled = verbose;
MainConsole.Instance.OutputFormat("{0} verbose logging set to {1}", Name, m_debugEnabled);
}
public void RegionLoaded(Scene scene)
{
if (!m_groupsEnabled)
return;
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
scene.EventManager.OnNewClient += OnNewClient;
scene.EventManager.OnMakeRootAgent += OnMakeRoot;
scene.EventManager.OnMakeChildAgent += OnMakeChild;
scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage;
// The InstantMessageModule itself doesn't do this,
// so lets see if things explode if we don't do it
// scene.EventManager.OnClientClosed += OnClientClosed;
if (m_groupData == null)
{
m_groupData = scene.RequestModuleInterface<IGroupsServicesConnector>();
// No Groups Service Connector, then nothing works...
if (m_groupData == null)
{
m_groupsEnabled = false;
m_log.Error("[Groups]: Could not get IGroupsServicesConnector");
RemoveRegion(scene);
return;
}
}
if (m_msgTransferModule == null)
{
m_msgTransferModule = scene.RequestModuleInterface<IMessageTransferModule>();
// No message transfer module, no notices, group invites, rejects, ejects, etc
if (m_msgTransferModule == null)
{
m_log.Warn("[Groups]: Could not get MessageTransferModule");
}
}
if (m_UserManagement == null)
{
m_UserManagement = scene.RequestModuleInterface<IUserManagement>();
if (m_UserManagement == null)
m_log.Warn("[Groups]: Could not get UserManagementModule");
}
m_sceneList.Add(scene);
}
public void RemoveRegion(Scene scene)
{
if (!m_groupsEnabled)
return;
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
scene.EventManager.OnNewClient -= OnNewClient;
scene.EventManager.OnMakeRootAgent -= OnMakeRoot;
scene.EventManager.OnMakeChildAgent -= OnMakeChild;
scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage;
m_sceneList.Remove(scene);
}
public void Close()
{
if (!m_groupsEnabled)
return;
if (m_debugEnabled) m_log.Debug("[Groups]: Shutting down Groups module.");
}
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "Groups Module V2"; }
}
public void PostInitialise()
{
// NoOp
}
#endregion
#region EventHandlers
private void OnNewClient(IClientAPI client)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
client.OnAgentDataUpdateRequest += OnAgentDataUpdateRequest;
client.OnRequestAvatarProperties += OnRequestAvatarProperties;
}
private void OnMakeRoot(ScenePresence sp)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
sp.ControllingClient.OnUUIDGroupNameRequest += HandleUUIDGroupNameRequest;
// Used for Notices and Group Invites/Accept/Reject
sp.ControllingClient.OnInstantMessage += OnInstantMessage;
// Send client their groups information.
SendAgentGroupDataUpdate(sp.ControllingClient, sp.UUID);
}
private void OnMakeChild(ScenePresence sp)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
sp.ControllingClient.OnUUIDGroupNameRequest -= HandleUUIDGroupNameRequest;
// Used for Notices and Group Invites/Accept/Reject
sp.ControllingClient.OnInstantMessage -= OnInstantMessage;
}
private void OnRequestAvatarProperties(IClientAPI remoteClient, UUID avatarID)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
//GroupMembershipData[] avatarGroups = m_groupData.GetAgentGroupMemberships(GetRequestingAgentID(remoteClient), avatarID).ToArray();
GroupMembershipData[] avatarGroups = GetProfileListedGroupMemberships(remoteClient, avatarID);
remoteClient.SendAvatarGroupsReply(avatarID, avatarGroups);
}
/*
* This becomes very problematic in a shared module. In a shared module you may have more then one
* reference to IClientAPI's, one for 0 or 1 root connections, and 0 or more child connections.
* The OnClientClosed event does not provide anything to indicate which one of those should be closed
* nor does it provide what scene it was from so that the specific reference can be looked up.
* The InstantMessageModule.cs does not currently worry about unregistering the handles,
* and it should be an issue, since it's the client that references us not the other way around
* , so as long as we don't keep a reference to the client laying around, the client can still be GC'ed
private void OnClientClosed(UUID AgentId)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
lock (m_ActiveClients)
{
if (m_ActiveClients.ContainsKey(AgentId))
{
IClientAPI client = m_ActiveClients[AgentId];
client.OnUUIDGroupNameRequest -= HandleUUIDGroupNameRequest;
client.OnAgentDataUpdateRequest -= OnAgentDataUpdateRequest;
client.OnDirFindQuery -= OnDirFindQuery;
client.OnInstantMessage -= OnInstantMessage;
m_ActiveClients.Remove(AgentId);
}
else
{
if (m_debugEnabled) m_log.WarnFormat("[Groups]: Client closed that wasn't registered here.");
}
}
}
*/
private void OnAgentDataUpdateRequest(IClientAPI remoteClient, UUID dataForAgentID, UUID sessionID)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
UUID activeGroupID = UUID.Zero;
string activeGroupTitle = string.Empty;
string activeGroupName = string.Empty;
ulong activeGroupPowers = (ulong)GroupPowers.None;
GroupMembershipData membership = m_groupData.GetAgentActiveMembership(GetRequestingAgentIDStr(remoteClient), dataForAgentID.ToString());
if (membership != null)
{
activeGroupID = membership.GroupID;
activeGroupTitle = membership.GroupTitle;
activeGroupPowers = membership.GroupPowers;
}
SendAgentDataUpdate(remoteClient, dataForAgentID, activeGroupID, activeGroupName, activeGroupPowers, activeGroupTitle);
SendScenePresenceUpdate(dataForAgentID, activeGroupTitle);
}
private void HandleUUIDGroupNameRequest(UUID GroupID, IClientAPI remoteClient)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
string GroupName;
GroupRecord group = m_groupData.GetGroupRecord(GetRequestingAgentIDStr(remoteClient), GroupID, null);
if (group != null)
{
GroupName = group.GroupName;
}
else
{
GroupName = "Unknown";
}
remoteClient.SendGroupNameReply(GroupID, GroupName);
}
private void OnInstantMessage(IClientAPI remoteClient, GridInstantMessage im)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
//m_log.DebugFormat("[Groups]: IM From {0} to {1} msg {2} type {3}", im.fromAgentID, im.toAgentID, im.message, (InstantMessageDialog)im.dialog);
// Group invitations
if ((im.dialog == (byte)InstantMessageDialog.GroupInvitationAccept) || (im.dialog == (byte)InstantMessageDialog.GroupInvitationDecline))
{
UUID inviteID = new UUID(im.imSessionID);
GroupInviteInfo inviteInfo = m_groupData.GetAgentToGroupInvite(GetRequestingAgentIDStr(remoteClient), inviteID);
if (inviteInfo == null)
{
if (m_debugEnabled) m_log.WarnFormat("[Groups]: Received an Invite IM for an invite that does not exist {0}.", inviteID);
return;
}
//m_log.DebugFormat("[XXX]: Invite is for Agent {0} to Group {1}.", inviteInfo.AgentID, inviteInfo.GroupID);
UUID fromAgentID = new UUID(im.fromAgentID);
UUID invitee = UUID.Zero;
string tmp = string.Empty;
Util.ParseUniversalUserIdentifier(inviteInfo.AgentID, out invitee, out tmp, out tmp, out tmp, out tmp);
if ((inviteInfo != null) && (fromAgentID == invitee))
{
// Accept
if (im.dialog == (byte)InstantMessageDialog.GroupInvitationAccept)
{
//m_log.DebugFormat("[XXX]: Received an accept invite notice.");
// and the sessionid is the role
string reason = string.Empty;
if (!m_groupData.AddAgentToGroup(GetRequestingAgentIDStr(remoteClient), invitee.ToString(), inviteInfo.GroupID, inviteInfo.RoleID, string.Empty, out reason))
remoteClient.SendAgentAlertMessage("Unable to add you to the group: " + reason, false);
else
{
GridInstantMessage msg = new GridInstantMessage();
msg.imSessionID = UUID.Zero.Guid;
msg.fromAgentID = UUID.Zero.Guid;
msg.toAgentID = invitee.Guid;
msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
msg.fromAgentName = "Groups";
msg.message = string.Format("You have been added to the group.");
msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.MessageBox;
msg.fromGroup = false;
msg.offline = (byte)0;
msg.ParentEstateID = 0;
msg.Position = Vector3.Zero;
msg.RegionID = UUID.Zero.Guid;
msg.binaryBucket = new byte[0];
OutgoingInstantMessage(msg, invitee);
UpdateAllClientsWithGroupInfo(invitee);
}
m_groupData.RemoveAgentToGroupInvite(GetRequestingAgentIDStr(remoteClient), inviteID);
}
// Reject
if (im.dialog == (byte)InstantMessageDialog.GroupInvitationDecline)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: Received a reject invite notice.");
m_groupData.RemoveAgentToGroupInvite(GetRequestingAgentIDStr(remoteClient), inviteID);
m_groupData.RemoveAgentFromGroup(GetRequestingAgentIDStr(remoteClient), inviteInfo.AgentID, inviteInfo.GroupID);
}
}
}
// Group notices
if ((im.dialog == (byte)InstantMessageDialog.GroupNotice))
{
if (!m_groupNoticesEnabled)
{
return;
}
UUID GroupID = new UUID(im.toAgentID);
if (m_groupData.GetGroupRecord(GetRequestingAgentIDStr(remoteClient), GroupID, null) != null)
{
UUID NoticeID = UUID.Random();
string Subject = im.message.Substring(0, im.message.IndexOf('|'));
string Message = im.message.Substring(Subject.Length + 1);
InventoryItemBase item = null;
bool hasAttachment = false;
if (im.binaryBucket.Length >= 1 && im.binaryBucket[0] > 0)
{
hasAttachment = true;
string binBucket = OpenMetaverse.Utils.BytesToString(im.binaryBucket);
binBucket = binBucket.Remove(0, 14).Trim();
OSD binBucketOSD = OSDParser.DeserializeLLSDXml(binBucket);
if (binBucketOSD is OSDMap)
{
OSDMap binBucketMap = (OSDMap)binBucketOSD;
UUID itemID = binBucketMap["item_id"].AsUUID();
UUID ownerID = binBucketMap["owner_id"].AsUUID();
item = new InventoryItemBase(itemID, ownerID);
item = m_sceneList[0].InventoryService.GetItem(item);
}
else
m_log.DebugFormat("[Groups]: Received OSD with unexpected type: {0}", binBucketOSD.GetType());
}
if (m_groupData.AddGroupNotice(GetRequestingAgentIDStr(remoteClient), GroupID, NoticeID, im.fromAgentName, Subject, Message,
hasAttachment,
(byte)(item == null ? 0 : item.AssetType),
item == null ? null : item.Name,
item == null ? UUID.Zero : item.ID,
item == null ? UUID.Zero.ToString() : item.Owner.ToString()))
{
if (OnNewGroupNotice != null)
{
OnNewGroupNotice(GroupID, NoticeID);
}
// Send notice out to everyone that wants notices
foreach (GroupMembersData member in m_groupData.GetGroupMembers(GetRequestingAgentIDStr(remoteClient), GroupID))
{
if (member.AcceptNotices)
{
// Build notice IIM, one of reach, because the sending may be async
GridInstantMessage msg = CreateGroupNoticeIM(UUID.Zero, NoticeID, (byte)OpenMetaverse.InstantMessageDialog.GroupNotice);
msg.toAgentID = member.AgentID.Guid;
OutgoingInstantMessage(msg, member.AgentID);
}
}
}
}
}
if (im.dialog == (byte)InstantMessageDialog.GroupNoticeInventoryAccepted)
{
if (im.binaryBucket.Length < 16) // Invalid
return;
//// 16 bytes are the UUID. Maybe.
// UUID folderID = new UUID(im.binaryBucket, 0);
UUID noticeID = new UUID(im.imSessionID);
GroupNoticeInfo notice = m_groupData.GetGroupNotice(remoteClient.AgentId.ToString(), noticeID);
if (notice != null)
{
UUID giver = new UUID(im.toAgentID);
string tmp = string.Empty;
Util.ParseUniversalUserIdentifier(notice.noticeData.AttachmentOwnerID, out giver, out tmp, out tmp, out tmp, out tmp);
m_log.DebugFormat("[Groups]: Giving inventory from {0} to {1}", giver, remoteClient.AgentId);
string message;
InventoryItemBase itemCopy = ((Scene)(remoteClient.Scene)).GiveInventoryItem(remoteClient.AgentId,
giver, notice.noticeData.AttachmentItemID, out message);
if (itemCopy == null)
{
remoteClient.SendAgentAlertMessage(message, false);
return;
}
remoteClient.SendInventoryItemCreateUpdate(itemCopy, 0);
}
}
// Interop, received special 210 code for ejecting a group member
// this only works within the comms servers domain, and won't work hypergrid
// TODO:FIXME: Use a presense server of some kind to find out where the
// client actually is, and try contacting that region directly to notify them,
// or provide the notification via xmlrpc update queue
if ((im.dialog == 210))
{
// This is sent from the region that the ejectee was ejected from
// if it's being delivered here, then the ejectee is here
// so we need to send local updates to the agent.
UUID ejecteeID = new UUID(im.toAgentID);
im.dialog = (byte)InstantMessageDialog.MessageFromAgent;
OutgoingInstantMessage(im, ejecteeID);
IClientAPI ejectee = GetActiveClient(ejecteeID);
if (ejectee != null)
{
UUID groupID = new UUID(im.imSessionID);
ejectee.SendAgentDropGroup(groupID);
}
}
}
private void OnGridInstantMessage(GridInstantMessage msg)
{
if (m_debugEnabled) m_log.InfoFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// Trigger the above event handler
OnInstantMessage(null, msg);
// If a message from a group arrives here, it may need to be forwarded to a local client
if (msg.fromGroup == true)
{
switch (msg.dialog)
{
case (byte)InstantMessageDialog.GroupInvitation:
case (byte)InstantMessageDialog.GroupNotice:
UUID toAgentID = new UUID(msg.toAgentID);
IClientAPI localClient = GetActiveClient(toAgentID);
if (localClient != null)
{
localClient.SendInstantMessage(msg);
}
break;
}
}
}
#endregion
#region IGroupsModule Members
public event NewGroupNotice OnNewGroupNotice;
public GroupRecord GetGroupRecord(UUID GroupID)
{
return m_groupData.GetGroupRecord(UUID.Zero.ToString(), GroupID, null);
}
public GroupRecord GetGroupRecord(string name)
{
return m_groupData.GetGroupRecord(UUID.Zero.ToString(), UUID.Zero, name);
}
public void ActivateGroup(IClientAPI remoteClient, UUID groupID)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
m_groupData.SetAgentActiveGroup(GetRequestingAgentIDStr(remoteClient), GetRequestingAgentIDStr(remoteClient), groupID);
// Changing active group changes title, active powers, all kinds of things
// anyone who is in any region that can see this client, should probably be
// updated with new group info. At a minimum, they should get ScenePresence
// updated with new title.
UpdateAllClientsWithGroupInfo(remoteClient.AgentId);
}
/// <summary>
/// Get the Role Titles for an Agent, for a specific group
/// </summary>
public List<GroupTitlesData> GroupTitlesRequest(IClientAPI remoteClient, UUID groupID)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
List<GroupRolesData> agentRoles = m_groupData.GetAgentGroupRoles(GetRequestingAgentIDStr(remoteClient), GetRequestingAgentIDStr(remoteClient), groupID);
GroupMembershipData agentMembership = m_groupData.GetAgentGroupMembership(GetRequestingAgentIDStr(remoteClient), GetRequestingAgentIDStr(remoteClient), groupID);
List<GroupTitlesData> titles = new List<GroupTitlesData>();
foreach (GroupRolesData role in agentRoles)
{
GroupTitlesData title = new GroupTitlesData();
title.Name = role.Name;
if (agentMembership != null)
{
title.Selected = agentMembership.ActiveRole == role.RoleID;
}
title.UUID = role.RoleID;
titles.Add(title);
}
return titles;
}
public List<GroupMembersData> GroupMembersRequest(IClientAPI remoteClient, UUID groupID)
{
if (m_debugEnabled)
m_log.DebugFormat(
"[Groups]: GroupMembersRequest called for {0} from client {1}", groupID, remoteClient.Name);
List<GroupMembersData> data = m_groupData.GetGroupMembers(GetRequestingAgentIDStr(remoteClient), groupID);
if (m_debugEnabled)
{
foreach (GroupMembersData member in data)
{
m_log.DebugFormat("[Groups]: Member({0}) - IsOwner({1})", member.AgentID, member.IsOwner);
}
}
return data;
}
public List<GroupRolesData> GroupRoleDataRequest(IClientAPI remoteClient, UUID groupID)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
List<GroupRolesData> data = m_groupData.GetGroupRoles(GetRequestingAgentIDStr(remoteClient), groupID);
return data;
}
public List<GroupRoleMembersData> GroupRoleMembersRequest(IClientAPI remoteClient, UUID groupID)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
List<GroupRoleMembersData> data = m_groupData.GetGroupRoleMembers(GetRequestingAgentIDStr(remoteClient), groupID);
if (m_debugEnabled)
{
foreach (GroupRoleMembersData member in data)
{
m_log.DebugFormat("[Groups]: Member({0}) - Role({1})", member.MemberID, member.RoleID);
}
}
return data;
}
public GroupProfileData GroupProfileRequest(IClientAPI remoteClient, UUID groupID)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
GroupProfileData profile = new GroupProfileData();
// just to get the OwnerRole...
ExtendedGroupRecord groupInfo = m_groupData.GetGroupRecord(GetRequestingAgentIDStr(remoteClient), groupID, string.Empty);
GroupMembershipData memberInfo = m_groupData.GetAgentGroupMembership(GetRequestingAgentIDStr(remoteClient), GetRequestingAgentIDStr(remoteClient), groupID);
if (groupInfo != null)
{
profile.AllowPublish = groupInfo.AllowPublish;
profile.Charter = groupInfo.Charter;
profile.FounderID = groupInfo.FounderID;
profile.GroupID = groupID;
profile.GroupMembershipCount = groupInfo.MemberCount;
profile.GroupRolesCount = groupInfo.RoleCount;
profile.InsigniaID = groupInfo.GroupPicture;
profile.MaturePublish = groupInfo.MaturePublish;
profile.MembershipFee = groupInfo.MembershipFee;
profile.Money = 0;
profile.Name = groupInfo.GroupName;
profile.OpenEnrollment = groupInfo.OpenEnrollment;
profile.OwnerRole = groupInfo.OwnerRoleID;
profile.ShowInList = groupInfo.ShowInList;
}
if (memberInfo != null)
{
profile.MemberTitle = memberInfo.GroupTitle;
profile.PowersMask = memberInfo.GroupPowers;
}
return profile;
}
public GroupMembershipData[] GetMembershipData(UUID agentID)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
return m_groupData.GetAgentGroupMemberships(UUID.Zero.ToString(), agentID.ToString()).ToArray();
}
public GroupMembershipData[] GetMembershipData(UUID agentID, bool forceUpdate)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
return m_groupData.GetAgentGroupMemberships(UUID.Zero.ToString(), agentID.ToString(), forceUpdate).ToArray();
}
public GroupMembershipData GetMembershipData(UUID groupID, UUID agentID)
{
if (m_debugEnabled)
m_log.DebugFormat(
"[Groups]: {0} called with groupID={1}, agentID={2}",
System.Reflection.MethodBase.GetCurrentMethod().Name, groupID, agentID);
return m_groupData.GetAgentGroupMembership(UUID.Zero.ToString(), agentID.ToString(), groupID);
}
public void UpdateGroupInfo(IClientAPI remoteClient, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// Note: Permissions checking for modification rights is handled by the Groups Server/Service
string reason = string.Empty;
if (!m_groupData.UpdateGroup(GetRequestingAgentIDStr(remoteClient), groupID, charter, showInList, insigniaID, membershipFee,
openEnrollment, allowPublish, maturePublish, out reason))
remoteClient.SendAgentAlertMessage(reason, false);
}
public void SetGroupAcceptNotices(IClientAPI remoteClient, UUID groupID, bool acceptNotices, bool listInProfile)
{
// Note: Permissions checking for modification rights is handled by the Groups Server/Service
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
m_groupData.UpdateMembership(GetRequestingAgentIDStr(remoteClient), GetRequestingAgentIDStr(remoteClient), groupID, acceptNotices, listInProfile);
}
public UUID CreateGroup(IClientAPI remoteClient, string name, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called in {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, remoteClient.Scene.RegionInfo.RegionName);
if (m_groupData.GetGroupRecord(GetRequestingAgentIDStr(remoteClient), UUID.Zero, name) != null)
{
remoteClient.SendCreateGroupReply(UUID.Zero, false, "A group with the same name already exists.");
return UUID.Zero;
}
// check user level
ScenePresence avatar = null;
Scene scene = (Scene)remoteClient.Scene;
scene.TryGetScenePresence(remoteClient.AgentId, out avatar);
if (avatar != null)
{
if (avatar.UserLevel < m_levelGroupCreate)
{
remoteClient.SendCreateGroupReply(UUID.Zero, false, String.Format("Insufficient permissions to create a group. Requires level {0}", m_levelGroupCreate));
return UUID.Zero;
}
}
// check funds
// is there is a money module present ?
IMoneyModule money = scene.RequestModuleInterface<IMoneyModule>();
if (money != null)
{
// do the transaction, that is if the agent has got sufficient funds
if (!money.AmountCovered(remoteClient.AgentId, money.GroupCreationCharge)) {
remoteClient.SendCreateGroupReply(UUID.Zero, false, "Insufficient funds to create a group.");
return UUID.Zero;
}
}
string reason = string.Empty;
UUID groupID = m_groupData.CreateGroup(remoteClient.AgentId, name, charter, showInList, insigniaID, membershipFee, openEnrollment,
allowPublish, maturePublish, remoteClient.AgentId, out reason);
if (groupID != UUID.Zero)
{
if (money != null)
money.ApplyCharge(remoteClient.AgentId, money.GroupCreationCharge, MoneyTransactionType.GroupCreate);
remoteClient.SendCreateGroupReply(groupID, true, "Group created successfullly");
// Update the founder with new group information.
SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient));
}
else
remoteClient.SendCreateGroupReply(groupID, false, reason);
return groupID;
}
public GroupNoticeData[] GroupNoticesListRequest(IClientAPI remoteClient, UUID groupID)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// ToDo: check if agent is a member of group and is allowed to see notices?
List<ExtendedGroupNoticeData> notices = m_groupData.GetGroupNotices(GetRequestingAgentIDStr(remoteClient), groupID);
List<GroupNoticeData> os_notices = new List<GroupNoticeData>();
foreach (ExtendedGroupNoticeData n in notices)
{
GroupNoticeData osn = n.ToGroupNoticeData();
os_notices.Add(osn);
}
return os_notices.ToArray();
}
/// <summary>
/// Get the title of the agent's current role.
/// </summary>
public string GetGroupTitle(UUID avatarID)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
GroupMembershipData membership = m_groupData.GetAgentActiveMembership(UUID.Zero.ToString(), avatarID.ToString());
if (membership != null)
{
return membership.GroupTitle;
}
return string.Empty;
}
/// <summary>
/// Change the current Active Group Role for Agent
/// </summary>
public void GroupTitleUpdate(IClientAPI remoteClient, UUID groupID, UUID titleRoleID)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
m_groupData.SetAgentActiveGroupRole(GetRequestingAgentIDStr(remoteClient), GetRequestingAgentIDStr(remoteClient), groupID, titleRoleID);
// TODO: Not sure what all is needed here, but if the active group role change is for the group
// the client currently has set active, then we need to do a scene presence update too
// if (m_groupData.GetAgentActiveMembership(GetRequestingAgentID(remoteClient)).GroupID == GroupID)
UpdateAllClientsWithGroupInfo(GetRequestingAgentID(remoteClient));
}
public void GroupRoleUpdate(IClientAPI remoteClient, UUID groupID, UUID roleID, string name, string description, string title, ulong powers, byte updateType)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// Security Checks are handled in the Groups Service.
switch ((OpenMetaverse.GroupRoleUpdate)updateType)
{
case OpenMetaverse.GroupRoleUpdate.Create:
string reason = string.Empty;
if (!m_groupData.AddGroupRole(GetRequestingAgentIDStr(remoteClient), groupID, UUID.Random(), name, description, title, powers, out reason))
remoteClient.SendAgentAlertMessage("Unable to create role: " + reason, false);
break;
case OpenMetaverse.GroupRoleUpdate.Delete:
m_groupData.RemoveGroupRole(GetRequestingAgentIDStr(remoteClient), groupID, roleID);
break;
case OpenMetaverse.GroupRoleUpdate.UpdateAll:
case OpenMetaverse.GroupRoleUpdate.UpdateData:
case OpenMetaverse.GroupRoleUpdate.UpdatePowers:
if (m_debugEnabled)
{
GroupPowers gp = (GroupPowers)powers;
m_log.DebugFormat("[Groups]: Role ({0}) updated with Powers ({1}) ({2})", name, powers.ToString(), gp.ToString());
}
m_groupData.UpdateGroupRole(GetRequestingAgentIDStr(remoteClient), groupID, roleID, name, description, title, powers);
break;
case OpenMetaverse.GroupRoleUpdate.NoUpdate:
default:
// No Op
break;
}
// TODO: This update really should send out updates for everyone in the role that just got changed.
SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient));
}
public void GroupRoleChanges(IClientAPI remoteClient, UUID groupID, UUID roleID, UUID memberID, uint changes)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// Todo: Security check
switch (changes)
{
case 0:
// Add
m_groupData.AddAgentToGroupRole(GetRequestingAgentIDStr(remoteClient), memberID.ToString(), groupID, roleID);
break;
case 1:
// Remove
m_groupData.RemoveAgentFromGroupRole(GetRequestingAgentIDStr(remoteClient), memberID.ToString(), groupID, roleID);
break;
default:
m_log.ErrorFormat("[Groups]: {0} does not understand changes == {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, changes);
break;
}
// TODO: This update really should send out updates for everyone in the role that just got changed.
SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient));
}
public void GroupNoticeRequest(IClientAPI remoteClient, UUID groupNoticeID)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called for notice {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, groupNoticeID);
GridInstantMessage msg = CreateGroupNoticeIM(remoteClient.AgentId, groupNoticeID, (byte)InstantMessageDialog.GroupNoticeRequested);
OutgoingInstantMessage(msg, GetRequestingAgentID(remoteClient));
}
public GridInstantMessage CreateGroupNoticeIM(UUID agentID, UUID groupNoticeID, byte dialog)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
GridInstantMessage msg = new GridInstantMessage();
byte[] bucket;
msg.imSessionID = groupNoticeID.Guid;
msg.toAgentID = agentID.Guid;
msg.dialog = dialog;
// msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.GroupNotice;
msg.fromGroup = true;
msg.offline = (byte)0;
msg.ParentEstateID = 0;
msg.Position = Vector3.Zero;
msg.RegionID = UUID.Zero.Guid;
GroupNoticeInfo info = m_groupData.GetGroupNotice(agentID.ToString(), groupNoticeID);
if (info != null)
{
msg.fromAgentID = info.GroupID.Guid;
msg.timestamp = info.noticeData.Timestamp;
msg.fromAgentName = info.noticeData.FromName;
msg.message = info.noticeData.Subject + "|" + info.Message;
if (info.noticeData.HasAttachment)
{
byte[] name = System.Text.Encoding.UTF8.GetBytes(info.noticeData.AttachmentName);
bucket = new byte[19 + name.Length];
bucket[0] = 1; // has attachment?
bucket[1] = info.noticeData.AttachmentType; // attachment type
name.CopyTo(bucket, 18);
}
else
{
bucket = new byte[19];
bucket[0] = 0; // Has att?
bucket[1] = 0; // type
bucket[18] = 0; // null terminated
}
info.GroupID.ToBytes(bucket, 2);
msg.binaryBucket = bucket;
}
else
{
m_log.DebugFormat("[Groups]: Group Notice {0} not found, composing empty message.", groupNoticeID);
msg.fromAgentID = UUID.Zero.Guid;
msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); ;
msg.fromAgentName = string.Empty;
msg.message = string.Empty;
msg.binaryBucket = new byte[0];
}
return msg;
}
public void SendAgentGroupDataUpdate(IClientAPI remoteClient)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// Send agent information about his groups
SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient));
}
public void JoinGroupRequest(IClientAPI remoteClient, UUID groupID)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
string reason = string.Empty;
// Should check to see if OpenEnrollment, or if there's an outstanding invitation
if (m_groupData.AddAgentToGroup(GetRequestingAgentIDStr(remoteClient), GetRequestingAgentIDStr(remoteClient), groupID, UUID.Zero, string.Empty, out reason))
{
remoteClient.SendJoinGroupReply(groupID, true);
// Should this send updates to everyone in the group?
SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient));
if (reason != string.Empty)
// A warning
remoteClient.SendAlertMessage("Warning: " + reason);
}
else
remoteClient.SendJoinGroupReply(groupID, false);
}
public void LeaveGroupRequest(IClientAPI remoteClient, UUID groupID)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
m_groupData.RemoveAgentFromGroup(GetRequestingAgentIDStr(remoteClient), GetRequestingAgentIDStr(remoteClient), groupID);
remoteClient.SendLeaveGroupReply(groupID, true);
remoteClient.SendAgentDropGroup(groupID);
// SL sends out notifcations to the group messaging session that the person has left
// Should this also update everyone who is in the group?
SendAgentGroupDataUpdate(remoteClient, GetRequestingAgentID(remoteClient));
}
public void EjectGroupMemberRequest(IClientAPI remoteClient, UUID groupID, UUID ejecteeID)
{
EjectGroupMember(remoteClient, GetRequestingAgentID(remoteClient), groupID, ejecteeID);
}
public void EjectGroupMember(IClientAPI remoteClient, UUID agentID, UUID groupID, UUID ejecteeID)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// Todo: Security check?
m_groupData.RemoveAgentFromGroup(agentID.ToString(), ejecteeID.ToString(), groupID);
string agentName;
RegionInfo regionInfo;
// remoteClient provided or just agentID?
if (remoteClient != null)
{
agentName = remoteClient.Name;
regionInfo = remoteClient.Scene.RegionInfo;
remoteClient.SendEjectGroupMemberReply(agentID, groupID, true);
}
else
{
IClientAPI client = GetActiveClient(agentID);
if (client != null)
{
agentName = client.Name;
regionInfo = client.Scene.RegionInfo;
client.SendEjectGroupMemberReply(agentID, groupID, true);
}
else
{
regionInfo = m_sceneList[0].RegionInfo;
UserAccount acc = m_sceneList[0].UserAccountService.GetUserAccount(regionInfo.ScopeID, agentID);
if (acc != null)
{
agentName = acc.FirstName + " " + acc.LastName;
}
else
{
agentName = "Unknown member";
}
}
}
GroupRecord groupInfo = m_groupData.GetGroupRecord(agentID.ToString(), groupID, null);
UserAccount account = m_sceneList[0].UserAccountService.GetUserAccount(regionInfo.ScopeID, ejecteeID);
if ((groupInfo == null) || (account == null))
{
return;
}
// Send Message to Ejectee
GridInstantMessage msg = new GridInstantMessage();
msg.imSessionID = UUID.Zero.Guid;
msg.fromAgentID = agentID.Guid;
// msg.fromAgentID = info.GroupID;
msg.toAgentID = ejecteeID.Guid;
//msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
msg.timestamp = 0;
msg.fromAgentName = agentName;
msg.message = string.Format("You have been ejected from '{1}' by {0}.", agentName, groupInfo.GroupName);
msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.MessageFromAgent;
msg.fromGroup = false;
msg.offline = (byte)0;
msg.ParentEstateID = 0;
msg.Position = Vector3.Zero;
msg.RegionID = regionInfo.RegionID.Guid;
msg.binaryBucket = new byte[0];
OutgoingInstantMessage(msg, ejecteeID);
// Message to ejector
// Interop, received special 210 code for ejecting a group member
// this only works within the comms servers domain, and won't work hypergrid
// TODO:FIXME: Use a presense server of some kind to find out where the
// client actually is, and try contacting that region directly to notify them,
// or provide the notification via xmlrpc update queue
msg = new GridInstantMessage();
msg.imSessionID = UUID.Zero.Guid;
msg.fromAgentID = agentID.Guid;
msg.toAgentID = agentID.Guid;
msg.timestamp = 0;
msg.fromAgentName = agentName;
if (account != null)
{
msg.message = string.Format("{2} has been ejected from '{1}' by {0}.", agentName, groupInfo.GroupName, account.FirstName + " " + account.LastName);
}
else
{
msg.message = string.Format("{2} has been ejected from '{1}' by {0}.", agentName, groupInfo.GroupName, "Unknown member");
}
msg.dialog = (byte)210; //interop
msg.fromGroup = false;
msg.offline = (byte)0;
msg.ParentEstateID = 0;
msg.Position = Vector3.Zero;
msg.RegionID = regionInfo.RegionID.Guid;
msg.binaryBucket = new byte[0];
OutgoingInstantMessage(msg, agentID);
// SL sends out messages to everyone in the group
// Who all should receive updates and what should they be updated with?
UpdateAllClientsWithGroupInfo(ejecteeID);
}
public void InviteGroupRequest(IClientAPI remoteClient, UUID groupID, UUID invitedAgentID, UUID roleID)
{
InviteGroup(remoteClient, GetRequestingAgentID(remoteClient), groupID, invitedAgentID, roleID);
}
public void InviteGroup(IClientAPI remoteClient, UUID agentID, UUID groupID, UUID invitedAgentID, UUID roleID)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
string agentName = m_UserManagement.GetUserName(agentID);
RegionInfo regionInfo = m_sceneList[0].RegionInfo;
GroupRecord group = m_groupData.GetGroupRecord(agentID.ToString(), groupID, null);
if (group == null)
{
m_log.DebugFormat("[Groups]: No such group {0}", groupID);
return;
}
// Todo: Security check, probably also want to send some kind of notification
UUID InviteID = UUID.Random();
if (m_groupData.AddAgentToGroupInvite(agentID.ToString(), InviteID, groupID, roleID, invitedAgentID.ToString()))
{
if (m_msgTransferModule != null)
{
Guid inviteUUID = InviteID.Guid;
GridInstantMessage msg = new GridInstantMessage();
msg.imSessionID = inviteUUID;
// msg.fromAgentID = agentID.Guid;
msg.fromAgentID = groupID.Guid;
msg.toAgentID = invitedAgentID.Guid;
//msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
msg.timestamp = 0;
msg.fromAgentName = agentName;
msg.message = string.Format("{0} has invited you to join a group called {1}. There is no cost to join this group.", agentName, group.GroupName);
msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.GroupInvitation;
msg.fromGroup = true;
msg.offline = (byte)0;
msg.ParentEstateID = 0;
msg.Position = Vector3.Zero;
msg.RegionID = regionInfo.RegionID.Guid;
msg.binaryBucket = new byte[20];
OutgoingInstantMessage(msg, invitedAgentID);
}
}
}
public List<DirGroupsReplyData> FindGroups(IClientAPI remoteClient, string query)
{
return m_groupData.FindGroups(GetRequestingAgentIDStr(remoteClient), query);
}
#endregion
#region Client/Update Tools
/// <summary>
/// Try to find an active IClientAPI reference for agentID giving preference to root connections
/// </summary>
private IClientAPI GetActiveClient(UUID agentID)
{
IClientAPI child = null;
// Try root avatar first
foreach(Scene scene in m_sceneList)
{
ScenePresence sp = scene.GetScenePresence(agentID);
if (sp != null)
{
if (!sp.IsChildAgent)
{
return sp.ControllingClient;
}
else
{
child = sp.ControllingClient;
}
}
}
// If we didn't find a root, then just return whichever child we found, or null if none
return child;
}
/// <summary>
/// Send 'remoteClient' the group membership 'data' for agent 'dataForAgentID'.
/// </summary>
private void SendGroupMembershipInfoViaCaps(IClientAPI remoteClient, UUID dataForAgentID, GroupMembershipData[] data)
{
if (m_debugEnabled) m_log.InfoFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// NPCs currently don't have a CAPs structure or event queues. There is a strong argument for conveying this information
// to them anyway since it makes writing server-side bots a lot easier, but for now we don't do anything.
if (remoteClient.SceneAgent.PresenceType == PresenceType.Npc)
return;
OSDArray AgentData = new OSDArray(1);
OSDMap AgentDataMap = new OSDMap(1);
AgentDataMap.Add("AgentID", OSD.FromUUID(dataForAgentID));
AgentData.Add(AgentDataMap);
OSDArray GroupData = new OSDArray(data.Length);
OSDArray NewGroupData = new OSDArray(data.Length);
foreach (GroupMembershipData membership in data)
{
if (GetRequestingAgentID(remoteClient) != dataForAgentID)
{
if (!membership.ListInProfile)
{
// If we're sending group info to remoteclient about another agent,
// filter out groups the other agent doesn't want to share.
continue;
}
}
OSDMap GroupDataMap = new OSDMap(6);
OSDMap NewGroupDataMap = new OSDMap(1);
GroupDataMap.Add("GroupID", OSD.FromUUID(membership.GroupID));
GroupDataMap.Add("GroupPowers", OSD.FromULong(membership.GroupPowers));
GroupDataMap.Add("AcceptNotices", OSD.FromBoolean(membership.AcceptNotices));
GroupDataMap.Add("GroupInsigniaID", OSD.FromUUID(membership.GroupPicture));
GroupDataMap.Add("Contribution", OSD.FromInteger(membership.Contribution));
GroupDataMap.Add("GroupName", OSD.FromString(membership.GroupName));
NewGroupDataMap.Add("ListInProfile", OSD.FromBoolean(membership.ListInProfile));
GroupData.Add(GroupDataMap);
NewGroupData.Add(NewGroupDataMap);
}
OSDMap llDataStruct = new OSDMap(3);
llDataStruct.Add("AgentData", AgentData);
llDataStruct.Add("GroupData", GroupData);
llDataStruct.Add("NewGroupData", NewGroupData);
if (m_debugEnabled)
{
m_log.InfoFormat("[Groups]: {0}", OSDParser.SerializeJsonString(llDataStruct));
}
IEventQueue queue = remoteClient.Scene.RequestModuleInterface<IEventQueue>();
if (queue != null)
{
queue.Enqueue(queue.BuildEvent("AgentGroupDataUpdate", llDataStruct), GetRequestingAgentID(remoteClient));
}
}
private void SendScenePresenceUpdate(UUID AgentID, string Title)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: Updating scene title for {0} with title: {1}", AgentID, Title);
m_sceneList.ForEach(delegate(Scene scene)
{
ScenePresence presence = scene.GetScenePresence(AgentID);
if (presence != null)
{
if (presence.Grouptitle != Title)
{
presence.Grouptitle = Title;
if (!presence.IsChildAgent)
presence.SendAvatarDataToAllAgents();
}
}
});
}
/// <summary>
/// Send updates to all clients who might be interested in groups data for dataForClientID
/// </summary>
private void UpdateAllClientsWithGroupInfo(UUID dataForClientID)
{
if (m_debugEnabled) m_log.InfoFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// TODO: Probably isn't nessesary to update every client in every scene.
// Need to examine client updates and do only what's nessesary.
m_sceneList.ForEach(delegate(Scene scene)
{
scene.ForEachClient(delegate(IClientAPI client) { SendAgentGroupDataUpdate(client, dataForClientID); });
});
}
/// <summary>
/// Update remoteClient with group information about dataForAgentID
/// </summary>
private void SendAgentGroupDataUpdate(IClientAPI remoteClient, UUID dataForAgentID)
{
if (m_debugEnabled) m_log.InfoFormat("[Groups]: {0} called for {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, remoteClient.Name);
// TODO: All the client update functions need to be reexamined because most do too much and send too much stuff
OnAgentDataUpdateRequest(remoteClient, dataForAgentID, UUID.Zero);
// Need to send a group membership update to the client
// UDP version doesn't seem to behave nicely. But we're going to send it out here
// with an empty group membership to hopefully remove groups being displayed due
// to the core Groups Stub
//remoteClient.SendGroupMembership(new GroupMembershipData[0]);
GroupMembershipData[] membershipArray = GetProfileListedGroupMemberships(remoteClient, dataForAgentID);
SendGroupMembershipInfoViaCaps(remoteClient, dataForAgentID, membershipArray);
//remoteClient.SendAvatarGroupsReply(dataForAgentID, membershipArray);
if (remoteClient.AgentId == dataForAgentID)
remoteClient.RefreshGroupMembership();
}
/// <summary>
/// Get a list of groups memberships for the agent that are marked "ListInProfile"
/// (unless that agent has a godLike aspect, in which case get all groups)
/// </summary>
/// <param name="dataForAgentID"></param>
/// <returns></returns>
private GroupMembershipData[] GetProfileListedGroupMemberships(IClientAPI requestingClient, UUID dataForAgentID)
{
List<GroupMembershipData> membershipData = m_groupData.GetAgentGroupMemberships(requestingClient.AgentId.ToString(), dataForAgentID.ToString());
GroupMembershipData[] membershipArray;
// cScene and property accessor 'isGod' are in support of the opertions to bypass 'hidden' group attributes for
// those with a GodLike aspect.
Scene cScene = (Scene)requestingClient.Scene;
bool isGod = cScene.Permissions.IsGod(requestingClient.AgentId);
if (isGod)
{
membershipArray = membershipData.ToArray();
}
else
{
if (requestingClient.AgentId != dataForAgentID)
{
Predicate<GroupMembershipData> showInProfile = delegate(GroupMembershipData membership)
{
return membership.ListInProfile;
};
membershipArray = membershipData.FindAll(showInProfile).ToArray();
}
else
{
membershipArray = membershipData.ToArray();
}
}
if (m_debugEnabled)
{
m_log.InfoFormat("[Groups]: Get group membership information for {0} requested by {1}", dataForAgentID, requestingClient.AgentId);
foreach (GroupMembershipData membership in membershipArray)
{
m_log.InfoFormat("[Groups]: {0} :: {1} - {2} - {3}", dataForAgentID, membership.GroupName, membership.GroupTitle, membership.GroupPowers);
}
}
return membershipArray;
}
private void SendAgentDataUpdate(IClientAPI remoteClient, UUID dataForAgentID, UUID activeGroupID, string activeGroupName, ulong activeGroupPowers, string activeGroupTitle)
{
if (m_debugEnabled) m_log.DebugFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
// TODO: All the client update functions need to be reexamined because most do too much and send too much stuff
string firstname = "Unknown", lastname = "Unknown";
string name = m_UserManagement.GetUserName(dataForAgentID);
if (!string.IsNullOrEmpty(name))
{
string[] parts = name.Split(new char[] { ' ' });
if (parts.Length >= 2)
{
firstname = parts[0];
lastname = parts[1];
}
}
remoteClient.SendAgentDataUpdate(dataForAgentID, activeGroupID, firstname,
lastname, activeGroupPowers, activeGroupName,
activeGroupTitle);
}
#endregion
#region IM Backed Processes
private void OutgoingInstantMessage(GridInstantMessage msg, UUID msgTo)
{
if (m_debugEnabled) m_log.InfoFormat("[Groups]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name);
IClientAPI localClient = GetActiveClient(msgTo);
if (localClient != null)
{
if (m_debugEnabled) m_log.InfoFormat("[Groups]: MsgTo ({0}) is local, delivering directly", localClient.Name);
localClient.SendInstantMessage(msg);
}
else if (m_msgTransferModule != null)
{
if (m_debugEnabled) m_log.InfoFormat("[Groups]: MsgTo ({0}) is not local, delivering via TransferModule", msgTo);
m_msgTransferModule.SendInstantMessage(msg, delegate(bool success) { if (m_debugEnabled) m_log.DebugFormat("[Groups]: Message Sent: {0}", success?"Succeeded":"Failed"); });
}
}
public void NotifyChange(UUID groupID)
{
// Notify all group members of a chnge in group roles and/or
// permissions
//
}
#endregion
private string GetRequestingAgentIDStr(IClientAPI client)
{
return GetRequestingAgentID(client).ToString();
}
private UUID GetRequestingAgentID(IClientAPI client)
{
UUID requestingAgentID = UUID.Zero;
if (client != null)
{
requestingAgentID = client.AgentId;
}
return requestingAgentID;
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Xunit;
namespace Peddler {
public abstract class IntegralGeneratorTests<TIntegral>
where TIntegral : struct, IEquatable<TIntegral>, IComparable<TIntegral> {
private const int numberOfAttempts = 100;
private static TIntegral minValue;
private static TIntegral maxValue;
static IntegralGeneratorTests() {
minValue = (TIntegral)
typeof(TIntegral)
.GetField("MinValue", BindingFlags.Public | BindingFlags.Static)
.GetValue(null);
maxValue = (TIntegral)
typeof(TIntegral)
.GetField("MaxValue", BindingFlags.Public | BindingFlags.Static)
.GetValue(null);
}
private static TIntegral ToIntegral(Object value) {
if (typeof(TIntegral) == typeof(TimeSpan)) {
// TimeSpan integral value is 'ticks', which isn't supported
// by Convert.ChangeType
value = new TimeSpan(
(Int64)Convert.ChangeType(value, typeof(Int64))
);
}
if (typeof(TIntegral) == typeof(DateTime)) {
// DateTime integral value is 'ticks', which isn't supported
// by Convert.ChangeType.
value = new DateTime(
(Int64)Convert.ChangeType(value, typeof(Int64)),
DateTimeKind.Unspecified
);
}
return (TIntegral)Convert.ChangeType(value, typeof(TIntegral));
}
private static TIntegral Add(TIntegral value, long amount) {
checked {
// Of all integrals, only UInt64 cannot be converted to Int64
if (typeof(TIntegral) == typeof(UInt64)) {
if (amount < 0) {
return ToIntegral(Convert.ToUInt64(value) - (UInt64)Math.Abs(amount));
} else {
return ToIntegral(Convert.ToUInt64(value) + (UInt64)amount);
}
}
if (typeof(TIntegral) == typeof(DateTime)) {
return ToIntegral(((DateTime)(object)value).Ticks + amount);
}
if (typeof(TIntegral) == typeof(TimeSpan)) {
return ToIntegral(((TimeSpan)(object)value).Ticks + amount);
}
return ToIntegral(Convert.ToInt64(value) + amount);
}
}
protected abstract IIntegralGenerator<TIntegral> CreateGenerator();
protected abstract IIntegralGenerator<TIntegral> CreateGenerator(TIntegral low);
protected abstract IIntegralGenerator<TIntegral> CreateGenerator(TIntegral low, TIntegral high);
[Fact]
public void Constructor_WithLow_CannotBeMaxIntegralValue() {
Assert.Throws<ArgumentException>(
() => this.CreateGenerator(maxValue)
);
}
public static IEnumerable<object[]> Constructor_WithLowAndHigh_LowMustBeLessThanHigh_Data {
get {
yield return new object[] { Add(minValue, 1), minValue };
yield return new object[] { maxValue, minValue };
yield return new object[] { minValue, minValue };
yield return new object[] { ToIntegral(1), ToIntegral(1) };
yield return new object[] { maxValue, maxValue };
}
}
[Theory]
[MemberData(nameof(Constructor_WithLowAndHigh_LowMustBeLessThanHigh_Data))]
public void Constructor_WithLowAndHigh_LowMustBeLessThanHigh(
TIntegral low,
TIntegral high) {
Assert.Throws<ArgumentException>(
() => this.CreateGenerator(low, high)
);
}
[Fact]
public void Next_WithDefaults_RangeIsZeroToMaxIntegralValue() {
var generator = this.CreateGenerator();
Assert.Equal(generator.Low, ToIntegral(0));
Assert.Equal(generator.High, maxValue);
for (var attempt = 0; attempt < numberOfAttempts; attempt++) {
var value = generator.Next();
AssertGreaterThanOrEqualTo(value, generator.Low);
AssertLessThan(value, generator.High);
Assert.True(generator.EqualityComparer.Equals(value, value));
}
}
public static IEnumerable<object[]> Next_WithLowDefined_RangeIsLowToMaxIntegralValue_Data {
get {
yield return new object[] { minValue };
yield return new object[] { ToIntegral(1) };
yield return new object[] { Add(maxValue, -1) };
}
}
[Theory]
[MemberData(nameof(Next_WithLowDefined_RangeIsLowToMaxIntegralValue_Data))]
public void Next_WithLowDefined_RangeIsLowToMaxIntegralValue(TIntegral low) {
var generator = this.CreateGenerator(low);
Assert.Equal(generator.Low, low);
Assert.Equal(generator.High, maxValue);
for (var attempt = 0; attempt < numberOfAttempts; attempt++) {
var value = generator.Next();
AssertGreaterThanOrEqualTo(value, low);
AssertLessThan(value, generator.High);
Assert.True(generator.EqualityComparer.Equals(value, value));
}
}
public static IEnumerable<object[]> Next_WithLowAndHighDefined_RangeIsBetweenLowAndHigh_Data {
get {
yield return new object[] { minValue, maxValue };
yield return new object[] { minValue, ToIntegral(1) };
yield return new object[] { ToIntegral(1), maxValue };
}
}
[Theory]
[MemberData(nameof(Next_WithLowAndHighDefined_RangeIsBetweenLowAndHigh_Data))]
public void Next_WithLowAndHighDefined_RangeIsBetweenLowAndHigh(
TIntegral low,
TIntegral high) {
var generator = this.CreateGenerator(low, high);
Assert.Equal(generator.Low, low);
Assert.Equal(generator.High, high);
for (var attempt = 0; attempt < numberOfAttempts; attempt++) {
var value = generator.Next();
AssertGreaterThanOrEqualTo(value, low);
AssertLessThan(value, high);
Assert.True(generator.EqualityComparer.Equals(value, value));
}
}
public static IEnumerable<object[]> NextDistinct_NeverGetSameValue_Data {
get {
yield return new object[] { minValue, maxValue };
yield return new object[] { ToIntegral(0), ToIntegral(2) };
}
}
[Theory]
[MemberData(nameof(NextDistinct_NeverGetSameValue_Data))]
public void NextDistinct_NeverGetSameValue(TIntegral low, TIntegral high) {
var generator = this.CreateGenerator(low, high);
var previousValue = generator.Next();
for (var attempt = 0; attempt < numberOfAttempts; attempt++) {
var nextValue = generator.NextDistinct(previousValue);
Assert.NotEqual(previousValue, nextValue);
Assert.False(generator.EqualityComparer.Equals(previousValue, nextValue));
previousValue = nextValue;
}
}
[Fact]
public void NextDistinct_ThrowOnConstantGenerator() {
// With these arguments, IntegralGenerator<TIntegral> can only generate '0'
var generator = this.CreateGenerator(ToIntegral(0), ToIntegral(1));
var value = generator.Next();
Assert.Throws<UnableToGenerateValueException>(
() => generator.NextDistinct(value)
);
}
[Fact]
public void NextDistinct_OtherGreaterThanRange() {
var generator = this.CreateGenerator(ToIntegral(0), ToIntegral(10));
var other = ToIntegral(20);
AssertGreaterThan(other, generator.High);
for (var attempt = 0; attempt < numberOfAttempts; attempt++) {
var value = generator.NextDistinct(other);
AssertGreaterThanOrEqualTo(value, generator.Low);
AssertLessThan(value, generator.High);
Assert.False(generator.EqualityComparer.Equals(other, value));
}
}
[Fact]
public void NextDistinct_OtherLessThanRange() {
var generator = this.CreateGenerator(ToIntegral(10), ToIntegral(20));
var other = ToIntegral(5);
AssertLessThan(other, generator.Low);
for (var attempt = 0; attempt < numberOfAttempts; attempt++) {
var value = generator.NextDistinct(other);
AssertGreaterThanOrEqualTo(value, generator.Low);
AssertLessThan(value, generator.High);
Assert.False(generator.EqualityComparer.Equals(other, value));
}
}
public static IEnumerable<object[]> NextGreaterThan_ThrowOnMaxValueOrHigher_Data {
get {
yield return new object[] { ToIntegral(0), ToIntegral(10), ToIntegral(20) };
yield return new object[] { ToIntegral(0), ToIntegral(10), ToIntegral(10) };
yield return new object[] { ToIntegral(0), ToIntegral(10), ToIntegral(9) };
yield return new object[] { ToIntegral(0), maxValue, maxValue };
}
}
[Theory]
[MemberData(nameof(NextGreaterThan_ThrowOnMaxValueOrHigher_Data))]
public void NextGreaterThan_ThrowOnMaxValueOrHigher(
TIntegral low,
TIntegral high,
TIntegral other) {
var generator = this.CreateGenerator(low, high);
Assert.Throws<UnableToGenerateValueException>(
() => generator.NextGreaterThan(other)
);
}
public static IEnumerable<object[]> NextGreaterThan_Data {
get {
yield return new object[] { minValue, maxValue, minValue };
yield return new object[] { ToIntegral(0), ToIntegral(2), ToIntegral(0) };
yield return new object[] { ToIntegral(10), ToIntegral(40), ToIntegral(5) };
}
}
[Theory]
[MemberData(nameof(NextGreaterThan_Data))]
public void NextGreaterThan(
TIntegral low,
TIntegral high,
TIntegral other) {
var generator = this.CreateGenerator(low, high);
for (var attempt = 0; attempt < numberOfAttempts; attempt++) {
var value = generator.NextGreaterThan(other);
AssertGreaterThan(value, other);
AssertGreaterThanOrEqualTo(value, generator.Low);
AssertLessThan(value, generator.High);
Assert.True(generator.Comparer.Compare(other, value) < 0);
}
}
public static IEnumerable<object[]> NextGreaterThanOrEqualTo_ThrowOnHigherThanMaxValue_Data {
get {
yield return new object[] { ToIntegral(1), ToIntegral(2), ToIntegral(10) };
yield return new object[] { ToIntegral(0), ToIntegral(10), ToIntegral(10) };
yield return new object[] { minValue, maxValue, maxValue };
}
}
[Theory]
[MemberData(nameof(NextGreaterThanOrEqualTo_ThrowOnHigherThanMaxValue_Data))]
public void NextGreaterThanOrEqualTo_ThrowOnHigherThanMaxValue(
TIntegral low,
TIntegral high,
TIntegral other) {
var generator = this.CreateGenerator(low, high);
Assert.Throws<UnableToGenerateValueException>(
() => generator.NextGreaterThanOrEqualTo(other)
);
}
public static IEnumerable<object[]> NextGreaterThanOrEqualTo_Data {
get {
yield return new object[] { ToIntegral(1), ToIntegral(2), ToIntegral(0) };
yield return new object[] { ToIntegral(0), ToIntegral(10), ToIntegral(9) };
yield return new object[] { minValue, maxValue, minValue };
yield return new object[] { ToIntegral(50), ToIntegral(100), ToIntegral(30) };
}
}
[Theory]
[MemberData(nameof(NextGreaterThanOrEqualTo_Data))]
public void NextGreaterThanOrEqualTo(
TIntegral low,
TIntegral high,
TIntegral other) {
var generator = this.CreateGenerator(low, high);
for (var attempt = 0; attempt < numberOfAttempts; attempt++) {
var value = generator.NextGreaterThanOrEqualTo(other);
AssertGreaterThanOrEqualTo(value, other);
AssertGreaterThanOrEqualTo(value, generator.Low);
AssertLessThan(value, generator.High);
Assert.True(generator.Comparer.Compare(other, value) <= 0);
}
}
public static IEnumerable<object[]> NextLessThan_ThrowOnMinValueOrLower_Data {
get {
yield return new object[] { ToIntegral(1), ToIntegral(2), ToIntegral(0) };
yield return new object[] { ToIntegral(0), ToIntegral(10), ToIntegral(0) };
yield return new object[] { minValue, maxValue, minValue };
}
}
[Theory]
[MemberData(nameof(NextLessThan_ThrowOnMinValueOrLower_Data))]
public void NextLessThan_ThrowOnMinValueOrLower(
TIntegral low,
TIntegral high,
TIntegral other) {
var generator = this.CreateGenerator(low, high);
Assert.Throws<UnableToGenerateValueException>(
() => generator.NextLessThan(other)
);
}
public static IEnumerable<object[]> NextLessThan_Data {
get {
yield return new object[] { minValue, maxValue, maxValue };
yield return new object[] { ToIntegral(0), ToIntegral(2), ToIntegral(1) };
yield return new object[] { ToIntegral(0), ToIntegral(10), ToIntegral(40) };
}
}
[Theory]
[MemberData(nameof(NextLessThan_Data))]
public void NextLessThan(
TIntegral low,
TIntegral high,
TIntegral other) {
var generator = this.CreateGenerator(low, high);
for (var attempt = 0; attempt < numberOfAttempts; attempt++) {
var value = generator.NextLessThan(other);
AssertLessThan(value, other);
AssertGreaterThanOrEqualTo(value, generator.Low);
AssertLessThan(value, generator.High);
Assert.True(generator.Comparer.Compare(other, value) > 0);
}
}
public static IEnumerable<object[]> NextLessThanOrEqualTo_ThrowOnLessThanMinValue_Data {
get {
yield return new object[] { ToIntegral(10), ToIntegral(20), ToIntegral(0) };
yield return new object[] { ToIntegral(30), ToIntegral(50), ToIntegral(10) };
yield return new object[] { Add(minValue, 1), maxValue, minValue };
}
}
[Theory]
[MemberData(nameof(NextLessThanOrEqualTo_ThrowOnLessThanMinValue_Data))]
public void NextLessThanOrEqualTo_ThrowOnLessThanMinValue(
TIntegral low,
TIntegral high,
TIntegral other) {
var generator = this.CreateGenerator(low, high);
Assert.Throws<UnableToGenerateValueException>(
() => generator.NextLessThanOrEqualTo(other)
);
}
public static IEnumerable<object[]> NextLessThanOrEqualTo_Data {
get {
yield return new object[] { ToIntegral(1), ToIntegral(2), ToIntegral(3) };
yield return new object[] { ToIntegral(0), ToIntegral(10), ToIntegral(0) };
yield return new object[] { minValue, maxValue, maxValue };
yield return new object[] { ToIntegral(0), ToIntegral(10), ToIntegral(40) };
}
}
[Theory]
[MemberData(nameof(NextLessThanOrEqualTo_Data))]
public void NextLessThanOrEqualTo(
TIntegral low,
TIntegral high,
TIntegral other) {
var generator = this.CreateGenerator(low, high);
for (var attempt = 0; attempt < numberOfAttempts; attempt++) {
var value = generator.NextLessThanOrEqualTo(other);
AssertLessThanOrEqualTo(value, other);
AssertGreaterThanOrEqualTo(value, generator.Low);
AssertLessThan(value, generator.High);
Assert.True(generator.Comparer.Compare(other, value) >= 0);
}
}
[Fact]
public async Task ThreadSafety() {
// Arrange
var zero = ToIntegral(0);
var consecutiveZeros = new ConcurrentStack<TIntegral>();
var generator = this.CreateGenerator(zero);
Action createThread =
() => this.ThreadSafetyImpl(zero, generator, consecutiveZeros);
// Act
var threads =
Enumerable
.Range(0, 10)
.Select(_ => Task.Run(createThread))
.ToArray();
await Task.WhenAll(threads);
// Assert
Assert.True(
consecutiveZeros.Count < 50,
$"System.Random is not thread safe. If one of its .Next() " +
$"implementations is called simultaneously on several " +
$"threads, it breaks and starts returning zero exclusively. " +
$"The last {consecutiveZeros.Count:N0} values were zero."
);
}
private void ThreadSafetyImpl(
TIntegral zero,
IGenerator<TIntegral> generator,
ConcurrentStack<TIntegral> consecutiveZeros) {
var count = 0;
while (count++ < 10000) {
if (generator.Next().Equals(zero)) {
consecutiveZeros.Push(zero);
} else {
consecutiveZeros.Clear();
}
}
}
private void AssertLessThan(TIntegral low, TIntegral high) {
Assert.True(
low.CompareTo(high) < 0,
String.Format(
"Expected '{0}' to be less than '{1}'.",
this.FormatValue(low),
this.FormatValue(high)
)
);
}
private void AssertLessThanOrEqualTo(TIntegral low, TIntegral high) {
Assert.True(
low.CompareTo(high) <= 0,
String.Format(
"Expected '{0}' to be less than or equal to '{1}'.",
this.FormatValue(low),
this.FormatValue(high)
)
);
}
private void AssertGreaterThan(TIntegral low, TIntegral high) {
Assert.True(
low.CompareTo(high) > 0,
String.Format(
"Expected '{0}' to be greater than '{1}'.",
this.FormatValue(low),
this.FormatValue(high)
)
);
}
private void AssertGreaterThanOrEqualTo(TIntegral low, TIntegral high) {
Assert.True(
low.CompareTo(high) >= 0,
String.Format(
"Expected '{0}' to be greater than or equal to '{1}'.",
this.FormatValue(low),
this.FormatValue(high)
)
);
}
protected virtual String FormatValue(TIntegral value) {
return $"{value:N0}";
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Xml.Linq;
using FluentAssertions;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.PlatformAbstractions;
using Microsoft.DotNet.TestFramework;
using Microsoft.DotNet.Tools.Test.Utilities;
using Xunit;
using LocalizableStrings = Microsoft.DotNet.Tools.Run.LocalizableStrings;
namespace Microsoft.DotNet.Cli.Run.Tests
{
public class GivenDotnetRunBuildsCsproj : TestBase
{
[Fact]
public void ItCanRunAMSBuildProject()
{
var testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RestoreCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("/p:SkipInvalidConfigurations=true")
.Should().Pass();
new BuildCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute()
.Should().Pass();
new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput()
.Should().Pass()
.And.HaveStdOutContaining("Hello World!");
}
[Fact]
public void ItImplicitlyRestoresAProjectWhenRunning()
{
var testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput()
.Should().Pass()
.And.HaveStdOutContaining("Hello World!");
}
[Fact]
public void ItCanRunAMultiTFMProjectWithImplicitRestore()
{
var testInstance = TestAssets.Get(
TestAssetKinds.DesktopTestProjects,
"NETFrameworkReferenceNETStandard20")
.CreateInstance()
.WithSourceFiles();
string projectDirectory = Path.Combine(testInstance.Root.FullName, "MultiTFMTestApp");
new RunCommand()
.WithWorkingDirectory(projectDirectory)
.ExecuteWithCapturedOutput("--framework netcoreapp3.0")
.Should().Pass()
.And.HaveStdOutContaining("This string came from the test library!");
}
[Fact]
public void ItDoesNotImplicitlyBuildAProjectWhenRunningWithTheNoBuildOption()
{
var testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var result = new RunCommand()
.WithWorkingDirectory(testInstance.Root.FullName)
.ExecuteWithCapturedOutput("--no-build -v:m");
result.Should().Fail();
if (!DotnetUnderTest.IsLocalized())
{
result.Should().NotHaveStdOutContaining("Restore");
}
}
[Fact]
public void ItDoesNotImplicitlyRestoreAProjectWhenRunningWithTheNoRestoreOption()
{
var testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput("--no-restore")
.Should().Fail()
.And.HaveStdOutContaining("project.assets.json");
}
[Fact]
public void ItBuildsTheProjectBeforeRunning()
{
var testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RestoreCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("/p:SkipInvalidConfigurations=true")
.Should().Pass();
new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput()
.Should().Pass()
.And.HaveStdOutContaining("Hello World!");
}
[Fact]
public void ItCanRunAMSBuildProjectWhenSpecifyingAFramework()
{
var testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RestoreCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("/p:SkipInvalidConfigurations=true")
.Should().Pass();
new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput("--framework netcoreapp3.0")
.Should().Pass()
.And.HaveStdOut("Hello World!");
}
[Fact]
public void ItRunsPortableAppsFromADifferentPathAfterBuilding()
{
var testInstance = TestAssets.Get("MSBuildTestApp")
.CreateInstance()
.WithSourceFiles()
.WithRestoreFiles();
new BuildCommand()
.WithWorkingDirectory(testInstance.Root)
.Execute()
.Should().Pass();
new RunCommand()
.WithWorkingDirectory(testInstance.Root)
.ExecuteWithCapturedOutput($"--no-build")
.Should().Pass()
.And.HaveStdOutContaining("Hello World!");
}
[Fact]
public void ItRunsPortableAppsFromADifferentPathWithoutBuilding()
{
var testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles()
.WithRestoreFiles();
var projectFile = testInstance.Root.GetFile(testAppName + ".csproj");
new RunCommand()
.WithWorkingDirectory(testInstance.Root.Parent)
.ExecuteWithCapturedOutput($"--project {projectFile.FullName}")
.Should().Pass()
.And.HaveStdOutContaining("Hello World!");
}
[Fact]
public void ItRunsPortableAppsFromADifferentPathSpecifyingOnlyTheDirectoryWithoutBuilding()
{
var testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles()
.WithRestoreFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RunCommand()
.WithWorkingDirectory(testInstance.Root.Parent)
.ExecuteWithCapturedOutput($"--project {testProjectDirectory}")
.Should().Pass()
.And.HaveStdOutContaining("Hello World!");
}
[Fact]
public void ItRunsAppWhenRestoringToSpecificPackageDirectory()
{
var rootPath = TestAssets.CreateTestDirectory().FullName;
string dir = "pkgs";
string args = $"--packages {dir}";
string newArgs = $"console -o \"{rootPath}\" --no-restore";
new NewCommandShim()
.WithWorkingDirectory(rootPath)
.Execute(newArgs)
.Should()
.Pass();
new RestoreCommand()
.WithWorkingDirectory(rootPath)
.Execute(args)
.Should()
.Pass();
new RunCommand()
.WithWorkingDirectory(rootPath)
.ExecuteWithCapturedOutput("--no-restore")
.Should().Pass()
.And.HaveStdOutContaining("Hello World");
}
[Fact]
public void ItReportsAGoodErrorWhenProjectHasMultipleFrameworks()
{
var testAppName = "MSBuildAppWithMultipleFrameworks";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles()
.WithRestoreFiles();
// use --no-build so this test can run on all platforms.
// the test app targets net451, which can't be built on non-Windows
new RunCommand()
.WithWorkingDirectory(testInstance.Root)
.ExecuteWithCapturedOutput("--no-build")
.Should().Fail()
.And.HaveStdErrContaining("--framework");
}
[Fact]
public void ItCanPassArgumentsToSubjectAppByDoubleDash()
{
const string testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles()
.WithRestoreFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput("-- foo bar baz")
.Should()
.Pass()
.And.HaveStdOutContaining("echo args:foo;bar;baz");
}
[Fact]
public void ItGivesAnErrorWhenAttemptingToUseALaunchProfileThatDoesNotExistWhenThereIsNoLaunchSettingsFile()
{
var testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RestoreCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("/p:SkipInvalidConfigurations=true")
.Should().Pass();
new BuildCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute()
.Should().Pass();
new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput("--launch-profile test")
.Should().Pass()
.And.HaveStdOutContaining("Hello World!")
.And.HaveStdErrContaining(LocalizableStrings.RunCommandExceptionCouldNotLocateALaunchSettingsFile);
}
[Fact]
public void ItUsesLaunchProfileOfTheSpecifiedName()
{
var testAppName = "AppWithLaunchSettings";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RestoreCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("/p:SkipInvalidConfigurations=true")
.Should().Pass();
new BuildCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute()
.Should().Pass();
var cmd = new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput("--launch-profile Second");
cmd.Should().Pass()
.And.HaveStdOutContaining("Second");
cmd.StdErr.Should().BeEmpty();
}
[Fact]
public void ItDefaultsToTheFirstUsableLaunchProfile()
{
var testAppName = "AppWithLaunchSettings";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
var launchSettingsPath = Path.Combine(testProjectDirectory, "Properties", "launchSettings.json");
new RestoreCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("/p:SkipInvalidConfigurations=true")
.Should().Pass();
new BuildCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute()
.Should().Pass();
var cmd = new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput();
cmd.Should().Pass()
.And.NotHaveStdOutContaining(string.Format(LocalizableStrings.UsingLaunchSettingsFromMessage, launchSettingsPath))
.And.HaveStdOutContaining("First");
cmd.StdErr.Should().BeEmpty();
}
[Fact]
public void ItPrintsUsingLaunchSettingsMessageWhenNotQuiet()
{
var testInstance = TestAssets.Get("AppWithLaunchSettings")
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
var launchSettingsPath = Path.Combine(testProjectDirectory, "Properties", "launchSettings.json");
var cmd = new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput("-v:m");
cmd.Should().Pass()
.And.HaveStdOutContaining(string.Format(LocalizableStrings.UsingLaunchSettingsFromMessage, launchSettingsPath))
.And.HaveStdOutContaining("First");
cmd.StdErr.Should().BeEmpty();
}
[Fact]
public void ItPrefersTheValueOfAppUrlFromEnvVarOverTheProp()
{
var testAppName = "AppWithApplicationUrlInLaunchSettings";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RestoreCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("/p:SkipInvalidConfigurations=true")
.Should().Pass();
new BuildCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute()
.Should().Pass();
var cmd = new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput("--launch-profile First");
cmd.Should().Pass()
.And.HaveStdOutContaining("http://localhost:12345/");
cmd.StdErr.Should().BeEmpty();
}
[Fact]
public void ItUsesTheValueOfAppUrlIfTheEnvVarIsNotSet()
{
var testAppName = "AppWithApplicationUrlInLaunchSettings";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RestoreCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("/p:SkipInvalidConfigurations=true")
.Should().Pass();
new BuildCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute()
.Should().Pass();
var cmd = new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput("--launch-profile Second");
cmd.Should().Pass()
.And.HaveStdOutContaining("http://localhost:54321/");
cmd.StdErr.Should().BeEmpty();
}
[Fact]
public void ItGivesAnErrorWhenTheLaunchProfileNotFound()
{
var testAppName = "AppWithLaunchSettings";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RestoreCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("/p:SkipInvalidConfigurations=true")
.Should().Pass();
new BuildCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute()
.Should().Pass();
new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput("--launch-profile Third")
.Should().Pass()
.And.HaveStdOutContaining("(NO MESSAGE)")
.And.HaveStdErrContaining(string.Format(LocalizableStrings.RunCommandExceptionCouldNotApplyLaunchSettings, "Third", "").Trim());
}
[Fact]
public void ItGivesAnErrorWhenTheLaunchProfileCanNotBeHandled()
{
var testAppName = "AppWithLaunchSettings";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RestoreCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("/p:SkipInvalidConfigurations=true")
.Should().Pass();
new BuildCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute()
.Should().Pass();
new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput("--launch-profile \"IIS Express\"")
.Should().Pass()
.And.HaveStdOutContaining("(NO MESSAGE)")
.And.HaveStdErrContaining(string.Format(LocalizableStrings.RunCommandExceptionCouldNotApplyLaunchSettings, "IIS Express", "").Trim());
}
[Fact]
public void ItSkipsLaunchProfilesWhenTheSwitchIsSupplied()
{
var testAppName = "AppWithLaunchSettings";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RestoreCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("/p:SkipInvalidConfigurations=true")
.Should().Pass();
new BuildCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute()
.Should().Pass();
var cmd = new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput("--no-launch-profile");
cmd.Should().Pass()
.And.HaveStdOutContaining("(NO MESSAGE)");
cmd.StdErr.Should().BeEmpty();
}
[Fact]
public void ItSkipsLaunchProfilesWhenTheSwitchIsSuppliedWithoutErrorWhenThereAreNoLaunchSettings()
{
var testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RestoreCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("/p:SkipInvalidConfigurations=true")
.Should().Pass();
new BuildCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute()
.Should().Pass();
var cmd = new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput("--no-launch-profile");
cmd.Should().Pass()
.And.HaveStdOutContaining("Hello World!");
cmd.StdErr.Should().BeEmpty();
}
[Fact]
public void ItSkipsLaunchProfilesWhenThereIsNoUsableDefault()
{
var testAppName = "AppWithLaunchSettingsNoDefault";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RestoreCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("/p:SkipInvalidConfigurations=true")
.Should().Pass();
new BuildCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute()
.Should().Pass();
var cmd = new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput();
cmd.Should().Pass()
.And.HaveStdOutContaining("(NO MESSAGE)")
.And.HaveStdErrContaining(string.Format(LocalizableStrings.RunCommandExceptionCouldNotApplyLaunchSettings, LocalizableStrings.DefaultLaunchProfileDisplayName, "").Trim());
}
[Fact]
public void ItPrintsAnErrorWhenLaunchSettingsAreCorrupted()
{
var testAppName = "AppWithCorruptedLaunchSettings";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var testProjectDirectory = testInstance.Root.FullName;
new RestoreCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute("/p:SkipInvalidConfigurations=true")
.Should().Pass();
new BuildCommand()
.WithWorkingDirectory(testProjectDirectory)
.Execute()
.Should().Pass();
var cmd = new RunCommand()
.WithWorkingDirectory(testProjectDirectory)
.ExecuteWithCapturedOutput();
cmd.Should().Pass()
.And.HaveStdOutContaining("(NO MESSAGE)")
.And.HaveStdErrContaining(string.Format(LocalizableStrings.RunCommandExceptionCouldNotApplyLaunchSettings, LocalizableStrings.DefaultLaunchProfileDisplayName, "").Trim());
}
[Fact]
public void ItRunsWithTheSpecifiedVerbosity()
{
var testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
var result = new RunCommand()
.WithWorkingDirectory( testInstance.Root.FullName)
.ExecuteWithCapturedOutput("-v:n");
result.Should().Pass()
.And.HaveStdOutContaining("Hello World!");
if (!DotnetUnderTest.IsLocalized())
{
result.Should().HaveStdOutContaining("Restore")
.And.HaveStdOutContaining("CoreCompile");
}
}
[Fact]
public void ItDoesNotShowImportantLevelMessageByDefault()
{
var testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles()
.WithProjectChanges(ProjectModification.AddDisplayMessageBeforeRestoreToProject);
var result = new RunCommand()
.WithWorkingDirectory(testInstance.Root.FullName)
.ExecuteWithCapturedOutput();
result.Should().Pass()
.And.NotHaveStdOutContaining("Important text");
}
[Fact]
public void ItShowImportantLevelMessageWhenPassInteractive()
{
var testAppName = "MSBuildTestApp";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles()
.WithProjectChanges(ProjectModification.AddDisplayMessageBeforeRestoreToProject);
var result = new RunCommand()
.WithWorkingDirectory(testInstance.Root.FullName)
.ExecuteWithCapturedOutput("--interactive");
result.Should().Pass()
.And.HaveStdOutContaining("Important text");
}
[Fact]
public void ItRunsWithDotnetWithoutApphost()
{
var testInstance = TestAssets.Get("AppOutputsExecutablePath").CreateInstance().WithSourceFiles();
var command = new RunCommand()
.WithWorkingDirectory(testInstance.Root.FullName);
command.Environment["UseAppHost"] = "false";
command.ExecuteWithCapturedOutput()
.Should()
.Pass()
.And
.HaveStdOutContaining($"dotnet{Constants.ExeSuffix}");
}
[Fact]
public void ItRunsWithApphost()
{
var testInstance = TestAssets.Get("AppOutputsExecutablePath").CreateInstance().WithSourceFiles();
var result = new RunCommand()
.WithWorkingDirectory(testInstance.Root.FullName)
.ExecuteWithCapturedOutput();
result.Should().Pass()
.And.HaveStdOutContaining($"AppOutputsExecutablePath{Constants.ExeSuffix}");
}
[Fact]
public void ItForwardsEmptyArgumentsToTheApp()
{
var testAppName = "TestAppSimple";
var testInstance = TestAssets.Get(testAppName)
.CreateInstance()
.WithSourceFiles();
new RunCommand()
.WithWorkingDirectory(testInstance.Root)
.ExecuteWithCapturedOutput("a \"\" c")
.Should()
.Pass()
.And
.HaveStdOutContaining($"0 = a{Environment.NewLine}1 = {Environment.NewLine}2 = c");
}
}
}
| |
/*
Copyright 2014 David Bordoley
Copyright 2014 Zumero, 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
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;
using System.Collections.Generic;
using System.Linq;
namespace SQLitePCL.pretty
{
/// <summary>
/// Extensions methods for <see cref="IStatement"/> result set rows.
/// </summary>
public static class ResultSet
{
/// <summary>
/// Selects the value in the first column of the result set row.
/// </summary>
/// <returns>An IEnumerable of the scalar values.</returns>
/// <param name="This">An enumerable of result set rows.</param>
public static IEnumerable<IResultSetValue> SelectScalar(this IEnumerable<IReadOnlyList<IResultSetValue>> This) =>
This.Select(x => x.First());
/// <summary>
/// Selects the value in the first column of the result set row as a <see cref="int"/>.
/// </summary>
/// <returns>An IEnumerable of the scalar values.</returns>
/// <param name="This">An enumerable of result set rows.</param>
public static IEnumerable<int> SelectScalarInt(this IEnumerable<IReadOnlyList<IResultSetValue>> This) =>
This.SelectScalar().Select(x => x.ToInt());
/// <summary>
/// Selects the value in the first column of the result set row as a <see cref="long"/>.
/// </summary>
/// <returns>An IEnumerable of the scalar values.</returns>
/// <param name="This">An enumerable of result set rows.</param>
public static IEnumerable<long> SelectScalarInt64(this IEnumerable<IReadOnlyList<IResultSetValue>> This) =>
This.SelectScalar().Select(x => x.ToInt64());
/// <summary>
/// Selects the value in the first column of the result set row as a <see cref="string"/>.
/// </summary>
/// <returns>An IEnumerable of the scalar values.</returns>
/// <param name="This">An enumerable of result set rows.</param>
public static IEnumerable<string> SelectScalarString(this IEnumerable<IReadOnlyList<IResultSetValue>> This) =>
This.SelectScalar().Select(x => x.ToString());
/// <summary>
/// Selects the value in the first column of the result set row as a <see cref="byte"/> array.
/// </summary>
/// <returns>An IEnumerable of the scalar values.</returns>
/// <param name="This">An enumerable of result set rows.</param>
public static IEnumerable<byte[]> SelectScalarBlob(this IEnumerable<IReadOnlyList<IResultSetValue>> This) =>
This.SelectScalar().Select(x => x.ToBlob());
/// <summary>
/// Selects the value in the first column of the result set row as a <see cref="double"/>.
/// </summary>
/// <returns>An IEnumerable of the scalar values.</returns>
/// <param name="This">An enumerable of result set rows.</param>
public static IEnumerable<double> SelectScalarDouble(this IEnumerable<IReadOnlyList<IResultSetValue>> This) =>
This.SelectScalar().Select(x => x.ToDouble());
/// <summary>
/// Selects the value in the first column of the result set row as a <see cref="bool"/>.
/// </summary>
/// <returns>An IEnumerable of the scalar values.</returns>
/// <param name="This">An enumerable of result set rows.</param>
public static IEnumerable<bool> SelectScalarBool(this IEnumerable<IReadOnlyList<IResultSetValue>> This) =>
This.SelectScalar().Select(x => x.ToBool());
/// <summary>
/// Selects the value in the first column of the result set row as a <see cref="float"/>.
/// </summary>
/// <returns>An IEnumerable of the scalar values.</returns>
/// <param name="This">An enumerable of result set rows.</param>
public static IEnumerable<float> SelectScalarFloat(this IEnumerable<IReadOnlyList<IResultSetValue>> This) =>
This.SelectScalar().Select(x => x.ToFloat());
/// <summary>
/// Selects the value in the first column of the result set row as a <see cref="TimeSpan"/>.
/// </summary>
/// <returns>An IEnumerable of the scalar values.</returns>
/// <param name="This">An enumerable of result set rows.</param>
public static IEnumerable<TimeSpan> SelectScalarTimeSpan(this IEnumerable<IReadOnlyList<IResultSetValue>> This) =>
This.SelectScalar().Select(x => x.ToTimeSpan());
/// <summary>
/// Selects the value in the first column of the result set row as a <see cref="DateTime"/>.
/// </summary>
/// <returns>An IEnumerable of the scalar values.</returns>
/// <param name="This">An enumerable of result set rows.</param>
public static IEnumerable<DateTime> SelectScalarDateTime(this IEnumerable<IReadOnlyList<IResultSetValue>> This) =>
This.SelectScalar().Select(x => x.ToDateTime());
/// <summary>
/// Selects the value in the first column of the result set row as a <see cref="DateTimeOffset"/>.
/// </summary>
/// <returns>An IEnumerable of the scalar values.</returns>
/// <param name="This">An enumerable of result set rows.</param>
public static IEnumerable<DateTimeOffset> SelectScalarDateTimeOffset(this IEnumerable<IReadOnlyList<IResultSetValue>> This) =>
This.SelectScalar().Select(x => x.ToDateTimeOffset());
/// <summary>
/// Selects the value in the first column of the result set row as a <see cref="uint"/>.
/// </summary>
/// <returns>An IEnumerable of the scalar values.</returns>
/// <param name="This">An enumerable of result set rows.</param>
public static IEnumerable<uint> SelectScalarUInt32(this IEnumerable<IReadOnlyList<IResultSetValue>> This) =>
This.SelectScalar().Select(x => x.ToUInt32());
/// <summary>
/// Selects the value in the first column of the result set row as a <see cref="decimal"/>.
/// </summary>
/// <returns>An IEnumerable of the scalar values.</returns>
/// <param name="This">An enumerable of result set rows.</param>
public static IEnumerable<decimal> SelectScalarDecimal(this IEnumerable<IReadOnlyList<IResultSetValue>> This) =>
This.SelectScalar().Select(x => x.ToDecimal());
/// <summary>
/// Selects the value in the first column of the result set row as a <see cref="byte"/>.
/// </summary>
/// <returns>An IEnumerable of the scalar values.</returns>
/// <param name="This">An enumerable of result set rows.</param>
public static IEnumerable<byte> SelectScalarByte(this IEnumerable<IReadOnlyList<IResultSetValue>> This) =>
This.SelectScalar().Select(x => x.ToByte());
/// <summary>
/// Selects the value in the first column of the result set row as a <see cref="UInt16"/>.
/// </summary>
/// <returns>An IEnumerable of the scalar values.</returns>
/// <param name="This">An enumerable of result set rows.</param>
public static IEnumerable<UInt16> SelectScalarUInt16(this IEnumerable<IReadOnlyList<IResultSetValue>> This) =>
This.SelectScalar().Select(x => x.ToUInt16());
/// <summary>
/// Selects the value in the first column of the result set row as a <see cref="short"/>.
/// </summary>
/// <returns>An IEnumerable of the scalar values.</returns>
/// <param name="This">An enumerable of result set rows.</param>
public static IEnumerable<short> SelectScalarShort(this IEnumerable<IReadOnlyList<IResultSetValue>> This) =>
This.SelectScalar().Select(x => x.ToShort());
/// <summary>
/// Selects the value in the first column of the result set row as a <see cref="sbyte"/>.
/// </summary>
/// <returns>An IEnumerable of the scalar values.</returns>
/// <param name="This">An enumerable of result set rows.</param>
public static IEnumerable<sbyte> SelectScalarSByte(this IEnumerable<IReadOnlyList<IResultSetValue>> This) =>
This.SelectScalar().Select(x => x.ToSByte());
/// <summary>
/// Selects the value in the first column of the result set row as a <see cref="Guid"/>.
/// </summary>
/// <returns>An IEnumerable of the scalar values.</returns>
/// <param name="This">An enumerable of result set rows.</param>
public static IEnumerable<Guid> SelectScalarGuid(this IEnumerable<IReadOnlyList<IResultSetValue>> This) =>
This.SelectScalar().Select(x => x.ToGuid());
/// <summary>
/// Selects the value in the first column of the result set row as a <see cref="Uri"/>.
/// </summary>
/// <returns>An IEnumerable of the scalar values.</returns>
/// <param name="This">An enumerable of result set rows.</param>
public static IEnumerable<Uri> SelectScalarUri(this IEnumerable<IReadOnlyList<IResultSetValue>> This) =>
This.SelectScalar().Select(x => x.ToUri());
/// <summary>
/// Returns an <see cref="IReadOnlyList<IColumnInfo>"/> of columns from a result set row.
/// </summary>
/// <param name="This">A row in the result set.</param>
/// <returns>An <see cref="IReadOnlyList<IColumnInfo>"/> of the result set columns.</returns>
public static IReadOnlyList<ColumnInfo> Columns(this IReadOnlyList<IResultSetValue> This)
{
Contract.Requires(This != null);
return new ResultSetColumnsListImpl(This);
}
private sealed class ResultSetColumnsListImpl : IReadOnlyList<ColumnInfo>
{
private readonly IReadOnlyList<IResultSetValue> rs;
internal ResultSetColumnsListImpl(IReadOnlyList<IResultSetValue> rs)
{
this.rs = rs;
}
public ColumnInfo this[int index] =>
rs[index].ColumnInfo;
public int Count =>
rs.Count;
public IEnumerator<ColumnInfo> GetEnumerator() =>
rs.Select(val => val.ColumnInfo).GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() =>
this.GetEnumerator();
}
}
}
| |
//
// Copyright (C) 2012-2014 DataStax Inc.
//
// 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 Cassandra.IntegrationTests.TestBase;
using Cassandra.IntegrationTests.TestClusterManagement;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Cassandra.IntegrationTests.Core
{
[Category("short")]
public class UdtMappingsTests : SharedClusterTest
{
/// <summary>
/// The protocol versions in which udts are supported
/// </summary>
private static readonly int[] UdtProtocolVersionSupported = new[] {3};
protected override void TestFixtureSetUp()
{
if (CassandraVersion < Version.Parse("2.1.0"))
Assert.Ignore("Requires Cassandra version >= 2.1");
base.TestFixtureSetUp();
const string cqlType1 = "CREATE TYPE phone (alias text, number text, country_code int)";
const string cqlType2 = "CREATE TYPE contact (first_name text, last_name text, birth_date timestamp, phones set<frozen<phone>>, emails set<text>)";
const string cqlTable1 = "CREATE TABLE users (id int PRIMARY KEY, main_phone frozen<phone>)";
const string cqlTable2 = "CREATE TABLE users_contacts (id int PRIMARY KEY, contacts list<frozen<contact>>)";
Session.Execute(cqlType1);
Session.Execute(cqlType2);
Session.Execute(cqlTable1);
Session.Execute(cqlTable2);
}
[Test]
public void MappingSingleExplicitTest()
{
foreach (var protocolVersion in UdtProtocolVersionSupported)
{
//Use all possible protocol versions
Cluster.MaxProtocolVersion = protocolVersion;
var localSession = GetNewSession(KeyspaceName);
localSession.UserDefinedTypes.Define(
UdtMap.For<Phone>("phone")
.Map(v => v.Alias, "alias")
.Map(v => v.CountryCode, "country_code")
.Map(v => v.Number, "number")
);
localSession.Execute("INSERT INTO users (id, main_phone) values (1, {alias: 'home phone', number: '123', country_code: 34})");
var rs = localSession.Execute("SELECT * FROM users WHERE id = 1");
var row = rs.First();
var value = row.GetValue<Phone>("main_phone");
Assert.NotNull(value);
Assert.AreEqual("home phone", value.Alias);
Assert.AreEqual("123", value.Number);
Assert.AreEqual(34, value.CountryCode);
}
}
[Test]
public void MappingSingleExplicitNullsTest()
{
foreach (var protocolVersion in UdtProtocolVersionSupported)
{
Cluster.MaxProtocolVersion = protocolVersion;
var localSession = GetNewSession(KeyspaceName);
localSession.UserDefinedTypes.Define(
UdtMap.For<Phone>("phone")
.Map(v => v.Alias, "alias")
.Map(v => v.CountryCode, "country_code")
.Map(v => v.Number, "number")
);
//Some fields are null
localSession.Execute("INSERT INTO users (id, main_phone) values (1, {alias: 'empty phone'})");
var row = localSession.Execute("SELECT * FROM users WHERE id = 1").First();
var value = row.GetValue<Phone>("main_phone");
Assert.NotNull(value);
Assert.AreEqual("empty phone", value.Alias);
//Default
Assert.IsNull(value.Number);
//Default
Assert.AreEqual(0, value.CountryCode);
//column value is null
localSession.Execute("INSERT INTO users (id, main_phone) values (2, null)");
row = localSession.Execute("SELECT * FROM users WHERE id = 2").First();
Assert.IsNull(row.GetValue<Phone>("main_phone"));
//first values are null
localSession.Execute("INSERT INTO users (id, main_phone) values (3, {country_code: 34})");
row = localSession.Execute("SELECT * FROM users WHERE id = 3").First();
Assert.IsNotNull(row.GetValue<Phone>("main_phone"));
Assert.AreEqual(34, row.GetValue<Phone>("main_phone").CountryCode);
Assert.IsNull(row.GetValue<Phone>("main_phone").Alias);
Assert.IsNull(row.GetValue<Phone>("main_phone").Number);
}
}
[Test]
public void MappingSingleImplicitTest()
{
foreach (var protocolVersion in UdtProtocolVersionSupported)
{
Cluster.MaxProtocolVersion = protocolVersion;
var localSession = GetNewSession(KeyspaceName);
localSession.UserDefinedTypes.Define(
UdtMap.For<Phone>()
);
localSession.Execute("INSERT INTO users (id, main_phone) values (1, {alias: 'home phone', number: '123', country_code: 34})");
var rs = localSession.Execute("SELECT * FROM users WHERE id = 1");
var row = rs.First();
var value = row.GetValue<Phone>("main_phone");
Assert.NotNull(value);
Assert.AreEqual("home phone", value.Alias);
Assert.AreEqual("123", value.Number);
//The property and the field names don't match
Assert.AreEqual(0, value.CountryCode);
}
}
[Test]
public void MappingNestedTypeTest()
{
foreach (var protocolVersion in UdtProtocolVersionSupported)
{
Cluster.MaxProtocolVersion = protocolVersion;
var localSession = GetNewSession(KeyspaceName);
localSession.UserDefinedTypes.Define(
UdtMap.For<Phone>(),
UdtMap.For<Contact>()
.Map(c => c.FirstName, "first_name")
.Map(c => c.LastName, "last_name")
.Map(c => c.Birth, "birth_date")
);
const string contactsJson =
"[" +
"{first_name: 'Jules', last_name: 'Winnfield', birth_date: '1950-02-03 04:05+0000', phones: {{alias: 'home', number: '123456'}}}," +
"{first_name: 'Mia', last_name: 'Wallace', phones: {{alias: 'mobile', number: '789'}, {alias: 'office', number: '123'}}}" +
"]";
localSession.Execute(String.Format("INSERT INTO users_contacts (id, contacts) values (1, {0})", contactsJson));
var rs = localSession.Execute("SELECT * FROM users_contacts WHERE id = 1");
var row = rs.First();
var contacts = row.GetValue<List<Contact>>("contacts");
Assert.NotNull(contacts);
Assert.AreEqual(2, contacts.Count);
var julesContact = contacts[0];
Assert.AreEqual("Jules", julesContact.FirstName);
Assert.AreEqual("Winnfield", julesContact.LastName);
Assert.AreEqual(new DateTimeOffset(1950, 2, 3, 4, 5, 0, 0, TimeSpan.Zero), julesContact.Birth);
Assert.IsNotNull(julesContact.Phones);
Assert.AreEqual(1, julesContact.Phones.Count());
var miaContact = contacts[1];
Assert.AreEqual("Mia", miaContact.FirstName);
Assert.AreEqual("Wallace", miaContact.LastName);
Assert.AreEqual(DateTimeOffset.MinValue, miaContact.Birth);
Assert.IsNotNull(miaContact.Phones);
Assert.AreEqual(2, miaContact.Phones.Count());
Assert.AreEqual("mobile", miaContact.Phones.First().Alias);
Assert.AreEqual("office", miaContact.Phones.Skip(1).First().Alias);
}
}
[Test]
public void MappingCaseSensitiveTest()
{
foreach (var protocolVersion in UdtProtocolVersionSupported)
{
Cluster.MaxProtocolVersion = protocolVersion;
var localSession = GetNewSession(KeyspaceName);
//Cassandra identifiers are lowercased by default
localSession.UserDefinedTypes.Define(
UdtMap.For<Phone>("phone")
.SetIgnoreCase(false)
.Map(v => v.Alias, "alias")
.Map(v => v.CountryCode, "country_code")
.Map(v => v.Number, "number")
);
localSession.Execute("INSERT INTO users (id, main_phone) values (101, {alias: 'home phone', number: '123', country_code: 34})");
var rs = localSession.Execute("SELECT * FROM users WHERE id = 101");
var row = rs.First();
var value = row.GetValue<Phone>("main_phone");
Assert.NotNull(value);
Assert.AreEqual("home phone", value.Alias);
Assert.AreEqual("123", value.Number);
Assert.AreEqual(34, value.CountryCode);
Assert.Throws<InvalidTypeException>(() => localSession.UserDefinedTypes.Define(
//The name should be forced to be case sensitive
UdtMap.For<Phone>("PhoNe")
.SetIgnoreCase(false)));
Assert.Throws<InvalidTypeException>(() => localSession.UserDefinedTypes.Define(
UdtMap.For<Phone>("phone")
.SetIgnoreCase(false)
//the field is called 'alias' it should fail
.Map(v => v.Alias, "Alias")
));
}
}
[Test]
public void MappingNotExistingFieldsTest()
{
var localSession = GetNewSession(KeyspaceName);
Assert.Throws<InvalidTypeException>(() => localSession.UserDefinedTypes.Define(
//there is no field named like this
UdtMap.For<Phone>("phone").Map(v => v.Number, "Alias_X_WTF")
));
}
[Test]
public void MappingEncodingSingleTest()
{
foreach (var protocolVersion in UdtProtocolVersionSupported)
{
//Use all possible protocol versions
Cluster.MaxProtocolVersion = protocolVersion;
var localSession = GetNewSession(KeyspaceName);
localSession.UserDefinedTypes.Define(
UdtMap.For<Phone>("phone")
.Map(v => v.Alias, "alias")
.Map(v => v.CountryCode, "country_code")
.Map(v => v.Number, "number")
);
const string insertQuery = "INSERT INTO users (id, main_phone) values (?, ?)";
//All of the fields null
var id = 201;
var phone = new Phone();
localSession.Execute(new SimpleStatement(insertQuery, id, phone));
var rs = localSession.Execute(new SimpleStatement("SELECT * FROM users WHERE id = ?", id));
Assert.AreEqual(phone, rs.First().GetValue<Phone>("main_phone"));
//Some fields null and others with value
id = 202;
phone = new Phone() {Alias = "Home phone"};
localSession.Execute(new SimpleStatement(insertQuery, id, phone));
rs = localSession.Execute(new SimpleStatement("SELECT * FROM users WHERE id = ?", id));
Assert.AreEqual(phone, rs.First().GetValue<Phone>("main_phone"));
//All fields filled in
id = 203;
phone = new Phone() { Alias = "Mobile phone", CountryCode = 54, Number = "1234567"};
localSession.Execute(new SimpleStatement(insertQuery, id, phone));
rs = localSession.Execute(new SimpleStatement("SELECT * FROM users WHERE id = ?", id));
Assert.AreEqual(phone, rs.First().GetValue<Phone>("main_phone"));
}
}
[Test]
public void MappingEncodingNestedTest()
{
foreach (var protocolVersion in UdtProtocolVersionSupported)
{
//Use all possible protocol versions
Cluster.MaxProtocolVersion = protocolVersion;
var localSession = GetNewSession(KeyspaceName);
localSession.UserDefinedTypes.Define(
UdtMap.For<Phone>(),
UdtMap.For<Contact>()
.Map(c => c.FirstName, "first_name")
.Map(c => c.LastName, "last_name")
.Map(c => c.Birth, "birth_date")
);
//All of the fields null
var id = 301;
var contacts = new List<Contact>
{
new Contact
{
FirstName = "Vincent",
LastName = "Vega",
Phones = new List<Phone>
{
new Phone {Alias = "Wat", Number = "0000000000121220000"},
new Phone {Alias = "Office", Number = "123"}
}
}
};
var insert = new SimpleStatement("INSERT INTO users_contacts (id, contacts) values (?, ?)", id, contacts);
localSession.Execute(insert);
var rs = localSession.Execute(new SimpleStatement("SELECT * FROM users_contacts WHERE id = ?", id));
Assert.AreEqual(contacts, rs.First().GetValue<List<Contact>>("contacts"));
}
}
/// <summary>
/// Checks that if no mapping defined, the driver gets out of the way.
/// </summary>
[Test]
public void NoMappingDefinedTest()
{
const string cqlType = "CREATE TYPE temp_udt (text_sample text, date_sample timestamp)";
const string cqlTable = "CREATE TABLE temp_table (id int PRIMARY KEY, sample_udt frozen<temp_udt>, sample_udt_list list<frozen<temp_udt>>)";
const string cqlInsert = "INSERT INTO temp_table (id, sample_udt, sample_udt_list) VALUES (1, {text_sample: 'one', date_sample: 1}, [{text_sample: 'first'}])";
var localSession = GetNewSession(KeyspaceName);
localSession.Execute(cqlType);
localSession.Execute(cqlTable);
localSession.Execute(cqlInsert);
var row = localSession.Execute("SELECT * from temp_table").First();
Assert.IsNotNull(row.GetValue<object>("sample_udt"));
Assert.IsInstanceOf<byte[]>(row.GetValue<object>("sample_udt"));
Assert.IsNotNull(row.GetValue<object>("sample_udt_list"));
Assert.IsInstanceOf<IEnumerable<byte[]>>(row.GetValue<object>("sample_udt_list"));
row = localSession.Execute("SELECT id, sample_udt.text_sample from temp_table").First();
Assert.AreEqual("one", row.GetValue<string>("sample_udt.text_sample"));
//Trying to encode an unmapped type should throw
var statement = new SimpleStatement("INSERT INTO temp_table (id, sample_udt) VALUES (?, ?)", 2, new DummyClass());
Assert.Throws<InvalidTypeException>(() => localSession.Execute(statement));
}
[Test]
public void MappingOnLowerProtocolVersionTest()
{
Cluster.MaxProtocolVersion = 2;
var localSession = GetNewSession(KeyspaceName);
Assert.Throws<NotSupportedException>(() => localSession.UserDefinedTypes.Define(UdtMap.For<Phone>()));
}
private class Contact
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTimeOffset Birth { get; set; }
public string NotMappedProp { get; set; }
public IEnumerable<Phone> Phones { get; set; }
public IEnumerable<string> Emails { get; set; }
public override bool Equals(object obj)
{
if (!(obj is Contact))
{
return false;
}
var value = (Contact)obj;
if (value.FirstName == this.FirstName &&
value.LastName == this.LastName &&
value.Birth == this.Birth &&
value.Birth == this.Birth)
{
CollectionAssert.AreEqual(this.Emails, value.Emails);
CollectionAssert.AreEqual(this.Phones, value.Phones);
return true;
}
return false;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
private class Phone
{
public string Alias { get; set; }
public string Number { get; set; }
public int CountryCode { get; set; }
public override bool Equals(object obj)
{
if (!(obj is Phone))
{
return false;
}
var phoneValue = (Phone)obj;
if (phoneValue.Alias == this.Alias &&
phoneValue.Number == this.Number &&
phoneValue.CountryCode == this.CountryCode)
{
return true;
}
return false;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
private class DummyClass
{
}
}
}
| |
// 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.Diagnostics;
using System.Linq;
using Microsoft.CSharp.RuntimeBinder.Errors;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal enum MemLookFlags : uint
{
None = 0,
Ctor = EXPRFLAG.EXF_CTOR,
NewObj = EXPRFLAG.EXF_NEWOBJCALL,
Operator = EXPRFLAG.EXF_OPERATOR,
Indexer = EXPRFLAG.EXF_INDEXER,
UserCallable = EXPRFLAG.EXF_USERCALLABLE,
BaseCall = EXPRFLAG.EXF_BASECALL,
// All EXF flags are < 0x01000000
MustBeInvocable = 0x20000000,
TypeVarsAllowed = 0x40000000,
ExtensionCall = 0x80000000,
All = Ctor | NewObj | Operator | Indexer | UserCallable | BaseCall | MustBeInvocable | TypeVarsAllowed | ExtensionCall
}
/////////////////////////////////////////////////////////////////////////////////
// MemberLookup class handles looking for a member within a type and its
// base types. This only handles AGGTYPESYMs and TYVARSYMs.
//
// Lookup must be called before any other methods.
internal sealed class MemberLookup
{
// The inputs to Lookup.
private CSemanticChecker _pSemanticChecker;
private SymbolLoader _pSymbolLoader;
private CType _typeSrc;
private EXPR _obj;
private CType _typeQual;
private ParentSymbol _symWhere;
private Name _name;
private int _arity;
private MemLookFlags _flags;
private CMemberLookupResults _results;
// For maintaining the type array. We throw the first 8 or so here.
private readonly List<AggregateType> _rgtypeStart;
// Results of the lookup.
private List<AggregateType> _prgtype;
private int _csym; // Number of syms found.
private readonly SymWithType _swtFirst; // The first symbol found.
private readonly List<MethPropWithType> _methPropWithTypeList; // When we look up methods, we want to keep the list of all candidate methods given a particular name.
// These are for error reporting.
private readonly SymWithType _swtAmbig; // An ambiguous symbol.
private readonly SymWithType _swtInaccess; // An inaccessible symbol.
private readonly SymWithType _swtBad; // If we're looking for a constructor or indexer, this matched on name, but isn't the right thing.
private readonly SymWithType _swtBogus; // A bogus member - such as an indexed property.
private readonly SymWithType _swtBadArity; // An symbol with the wrong arity.
private SymWithType _swtAmbigWarn; // An ambiguous symbol, but only warn.
// We have an override symbol, which we've errored on in SymbolPrepare. If we have nothing better, use this.
// This is because if we have:
//
// class C : D
// {
// public override int M() { }
// static void Main()
// {
// C c = new C();
// c.M(); <--
//
// We try to look up M, and find the M on C, but throw it out since its an override, and
// we want the virtual that it overrides. However, in this case, we'll never find that
// virtual, since it doesn't exist. We therefore want to use the override anyway, and
// continue on to give results with that.
private readonly SymWithType _swtOverride;
private bool _fMulti; // Whether symFirst is of a kind for which we collect multiples (methods and indexers).
/***************************************************************************************************
Another match was found. Increment the count of syms and add the type to our list if it's not
already there.
***************************************************************************************************/
private void RecordType(AggregateType type, Symbol sym)
{
Debug.Assert(type != null && sym != null);
if (!_prgtype.Contains(type))
{
_prgtype.Add(type);
}
// Now record the sym....
_csym++;
// If it is first, record it.
if (_swtFirst == null)
{
_swtFirst.Set(sym, type);
Debug.Assert(_csym == 1);
Debug.Assert(_prgtype[0] == type);
_fMulti = sym.IsMethodSymbol() || sym.IsPropertySymbol() && sym.AsPropertySymbol().isIndexer();
}
}
/******************************************************************************
Search just the given type (not any bases). Returns true iff it finds
something (which will have been recorded by RecordType).
pfHideByName is set to true iff something was found that hides all
members of base types (eg, a hidebyname method).
******************************************************************************/
private bool SearchSingleType(AggregateType typeCur, out bool pfHideByName)
{
bool fFoundSome = false;
pfHideByName = false;
// Make sure this type is accessible. It may not be due to private inheritance
// or friend assemblies.
bool fInaccess = !GetSemanticChecker().CheckTypeAccess(typeCur, _symWhere);
if (fInaccess && (_csym != 0 || _swtInaccess != null))
return false;
// Loop through symbols.
Symbol symCur = null;
for (symCur = GetSymbolLoader().LookupAggMember(_name, typeCur.getAggregate(), symbmask_t.MASK_ALL);
symCur != null;
symCur = GetSymbolLoader().LookupNextSym(symCur, typeCur.getAggregate(), symbmask_t.MASK_ALL))
{
// Check for arity.
switch (symCur.getKind())
{
case SYMKIND.SK_MethodSymbol:
// For non-zero arity, only methods of the correct arity are considered.
// For zero arity, don't filter out any methods since we do type argument
// inferencing.
if (_arity > 0 && symCur.AsMethodSymbol().typeVars.Count != _arity)
{
if (!_swtBadArity)
_swtBadArity.Set(symCur, typeCur);
continue;
}
break;
case SYMKIND.SK_AggregateSymbol:
// For types, always filter on arity.
if (symCur.AsAggregateSymbol().GetTypeVars().Count != _arity)
{
if (!_swtBadArity)
_swtBadArity.Set(symCur, typeCur);
continue;
}
break;
case SYMKIND.SK_TypeParameterSymbol:
if ((_flags & MemLookFlags.TypeVarsAllowed) == 0)
continue;
if (_arity > 0)
{
if (!_swtBadArity)
_swtBadArity.Set(symCur, typeCur);
continue;
}
break;
default:
// All others are only considered when arity is zero.
if (_arity > 0)
{
if (!_swtBadArity)
_swtBadArity.Set(symCur, typeCur);
continue;
}
break;
}
// Check for user callability.
if (symCur.IsOverride() && !symCur.IsHideByName())
{
if (!_swtOverride)
{
_swtOverride.Set(symCur, typeCur);
}
continue;
}
if ((_flags & MemLookFlags.UserCallable) != 0 && symCur.IsMethodOrPropertySymbol() && !symCur.AsMethodOrPropertySymbol().isUserCallable())
{
bool bIsIndexedProperty = false;
// If its an indexed property method symbol, let it through.
if (symCur.IsMethodSymbol() &&
symCur.AsMethodSymbol().isPropertyAccessor() &&
((symCur.name.Text.StartsWith("set_", StringComparison.Ordinal) && symCur.AsMethodSymbol().Params.Count > 1) ||
(symCur.name.Text.StartsWith("get_", StringComparison.Ordinal) && symCur.AsMethodSymbol().Params.Count > 0)))
{
bIsIndexedProperty = true;
}
if (!bIsIndexedProperty)
{
if (!_swtInaccess)
{
_swtInaccess.Set(symCur, typeCur);
}
continue;
}
}
if (fInaccess || !GetSemanticChecker().CheckAccess(symCur, typeCur, _symWhere, _typeQual))
{
// Not accessible so get the next sym.
if (!_swtInaccess)
{
_swtInaccess.Set(symCur, typeCur);
}
if (fInaccess)
{
return false;
}
continue;
}
// Make sure that whether we're seeing a ctor, operator, or indexer is consistent with the flags.
if (((_flags & MemLookFlags.Ctor) == 0) != (!symCur.IsMethodSymbol() || !symCur.AsMethodSymbol().IsConstructor()) ||
((_flags & MemLookFlags.Operator) == 0) != (!symCur.IsMethodSymbol() || !symCur.AsMethodSymbol().isOperator) ||
((_flags & MemLookFlags.Indexer) == 0) != (!symCur.IsPropertySymbol() || !symCur.AsPropertySymbol().isIndexer()))
{
if (!_swtBad)
{
_swtBad.Set(symCur, typeCur);
}
continue;
}
// We can't call CheckBogus on methods or indexers because if the method has the wrong
// number of parameters people don't think they should have to /r the assemblies containing
// the parameter types and they complain about the resulting CS0012 errors.
if (!symCur.IsMethodSymbol() && (_flags & MemLookFlags.Indexer) == 0 && GetSemanticChecker().CheckBogus(symCur))
{
// A bogus member - we can't use these, so only record them for error reporting.
if (!_swtBogus)
{
_swtBogus.Set(symCur, typeCur);
}
continue;
}
// if we are in a calling context then we should only find a property if it is delegate valued
if ((_flags & MemLookFlags.MustBeInvocable) != 0)
{
if ((symCur.IsFieldSymbol() && !IsDelegateType(symCur.AsFieldSymbol().GetType(), typeCur) && !IsDynamicMember(symCur)) ||
(symCur.IsPropertySymbol() && !IsDelegateType(symCur.AsPropertySymbol().RetType, typeCur) && !IsDynamicMember(symCur)))
{
if (!_swtBad)
{
_swtBad.Set(symCur, typeCur);
}
continue;
}
}
if (symCur.IsMethodOrPropertySymbol())
{
MethPropWithType mwpInsert = new MethPropWithType(symCur.AsMethodOrPropertySymbol(), typeCur);
_methPropWithTypeList.Add(mwpInsert);
}
// We have a visible symbol.
fFoundSome = true;
if (_swtFirst)
{
if (!typeCur.isInterfaceType())
{
// Non-interface case.
Debug.Assert(_fMulti || typeCur == _prgtype[0]);
if (!_fMulti)
{
if (_swtFirst.Sym.IsFieldSymbol() && symCur.IsEventSymbol()
#if !CSEE // The isEvent bit is only set on symbols which come from source...
// This is not a problem for the compiler because the field is only
// accessible in the scope in which it is declared,
// but in the EE we ignore accessibility...
&& _swtFirst.Field().isEvent
#endif
)
{
// m_swtFirst is just the field behind the event symCur so ignore symCur.
continue;
}
else if (_swtFirst.Sym.IsFieldSymbol() && symCur.IsEventSymbol())
{
// symCur is the matching event.
continue;
}
goto LAmbig;
}
if (_swtFirst.Sym.getKind() != symCur.getKind())
{
if (typeCur == _prgtype[0])
goto LAmbig;
// This one is hidden by the first one. This one also hides any more in base types.
pfHideByName = true;
continue;
}
}
// Interface case.
// m_fMulti : n n n y y y y y
// same-kind : * * * y n n n n
// fDiffHidden: * * * * y n n n
// meth : * * * * * y n * can n happen? just in case, we better handle it....
// hack : n * y * * y * n
// meth-2 : * n y * * * * *
// res : A A S R H H A A
else if (!_fMulti)
{
// Give method groups priority.
if ( /* !GetSymbolLoader().options.fLookupHack ||*/ !symCur.IsMethodSymbol())
goto LAmbig;
_swtAmbigWarn = _swtFirst;
// Erase previous results so we'll record this method as the first.
_prgtype = new List<AggregateType>();
_csym = 0;
_swtFirst.Clear();
_swtAmbig.Clear();
}
else if (_swtFirst.Sym.getKind() != symCur.getKind())
{
if (!typeCur.fDiffHidden)
{
// Give method groups priority.
if ( /*!GetSymbolLoader().options.fLookupHack ||*/ !_swtFirst.Sym.IsMethodSymbol())
goto LAmbig;
if (!_swtAmbigWarn)
_swtAmbigWarn.Set(symCur, typeCur);
}
// This one is hidden by another. This one also hides any more in base types.
pfHideByName = true;
continue;
}
}
RecordType(typeCur, symCur);
if (symCur.IsMethodOrPropertySymbol() && symCur.AsMethodOrPropertySymbol().isHideByName)
pfHideByName = true;
// We've found a symbol in this type but need to make sure there aren't any conflicting
// syms here, so keep searching the type.
}
Debug.Assert(!fInaccess || !fFoundSome);
return fFoundSome;
LAmbig:
// Ambiguous!
if (!_swtAmbig)
_swtAmbig.Set(symCur, typeCur);
pfHideByName = true;
return true;
}
private bool IsDynamicMember(Symbol sym)
{
System.Runtime.CompilerServices.DynamicAttribute da = null;
if (sym.IsFieldSymbol())
{
if (!sym.AsFieldSymbol().getType().isPredefType(PredefinedType.PT_OBJECT))
{
return false;
}
var o = sym.AsFieldSymbol().AssociatedFieldInfo.GetCustomAttributes(typeof(System.Runtime.CompilerServices.DynamicAttribute), false).ToArray();
if (o.Length == 1)
{
da = o[0] as System.Runtime.CompilerServices.DynamicAttribute;
}
}
else
{
Debug.Assert(sym.IsPropertySymbol());
if (!sym.AsPropertySymbol().getType().isPredefType(PredefinedType.PT_OBJECT))
{
return false;
}
var o = sym.AsPropertySymbol().AssociatedPropertyInfo.GetCustomAttributes(typeof(System.Runtime.CompilerServices.DynamicAttribute), false).ToArray();
if (o.Length == 1)
{
da = o[0] as System.Runtime.CompilerServices.DynamicAttribute;
}
}
if (da == null)
{
return false;
}
return (da.TransformFlags.Count == 0 || (da.TransformFlags.Count == 1 && da.TransformFlags[0]));
}
/******************************************************************************
Lookup in a class and its bases (until *ptypeEnd is hit).
ptypeEnd [in/out] - *ptypeEnd should be either null or object. If we find
something here that would hide members of object, this sets *ptypeEnd
to null.
Returns true when searching should continue to the interfaces.
******************************************************************************/
private bool LookupInClass(AggregateType typeStart, ref AggregateType ptypeEnd)
{
Debug.Assert(!_swtFirst || _fMulti);
Debug.Assert(typeStart != null && !typeStart.isInterfaceType() && (ptypeEnd == null || typeStart != ptypeEnd));
AggregateType typeEnd = ptypeEnd;
AggregateType typeCur;
// Loop through types. Loop until we hit typeEnd (object or null).
for (typeCur = typeStart; typeCur != typeEnd && typeCur != null; typeCur = typeCur.GetBaseClass())
{
Debug.Assert(!typeCur.isInterfaceType());
bool fHideByName = false;
SearchSingleType(typeCur, out fHideByName);
_flags &= ~MemLookFlags.TypeVarsAllowed;
if (_swtFirst && !_fMulti)
{
// Everything below this type and in interfaces is hidden.
return false;
}
if (fHideByName)
{
// This hides everything below it and in object, but not in the interfaces!
ptypeEnd = null;
// Return true to indicate that it's ok to search additional types.
return true;
}
if ((_flags & MemLookFlags.Ctor) != 0)
{
// If we're looking for a constructor, don't check base classes or interfaces.
return false;
}
}
Debug.Assert(typeCur == typeEnd);
return true;
}
/******************************************************************************
Returns true if searching should continue to object.
******************************************************************************/
private bool LookupInInterfaces(AggregateType typeStart, TypeArray types)
{
Debug.Assert(!_swtFirst || _fMulti);
Debug.Assert(typeStart == null || typeStart.isInterfaceType());
Debug.Assert(typeStart != null || types.Count != 0);
// Clear all the hidden flags. Anything found in a class hides any other
// kind of member in all the interfaces.
if (typeStart != null)
{
typeStart.fAllHidden = false;
typeStart.fDiffHidden = (_swtFirst != null);
}
for (int i = 0; i < types.Count; i++)
{
AggregateType type = types[i].AsAggregateType();
Debug.Assert(type.isInterfaceType());
type.fAllHidden = false;
type.fDiffHidden = !!_swtFirst;
}
bool fHideObject = false;
AggregateType typeCur = typeStart;
int itypeNext = 0;
if (typeCur == null)
{
typeCur = types[itypeNext++].AsAggregateType();
}
Debug.Assert(typeCur != null);
// Loop through the interfaces.
for (; ;)
{
Debug.Assert(typeCur != null && typeCur.isInterfaceType());
bool fHideByName = false;
if (!typeCur.fAllHidden && SearchSingleType(typeCur, out fHideByName))
{
fHideByName |= !_fMulti;
// Mark base interfaces appropriately.
TypeArray ifaces = typeCur.GetIfacesAll();
for (int i = 0; i < ifaces.Count; i++)
{
AggregateType type = ifaces[i].AsAggregateType();
Debug.Assert(type.isInterfaceType());
if (fHideByName)
type.fAllHidden = true;
type.fDiffHidden = true;
}
// If we hide all base types, that includes object!
if (fHideByName)
fHideObject = true;
}
_flags &= ~MemLookFlags.TypeVarsAllowed;
if (itypeNext >= types.Count)
return !fHideObject;
// Substitution has already been done.
typeCur = types[itypeNext++].AsAggregateType();
}
}
private SymbolLoader GetSymbolLoader() { return _pSymbolLoader; }
private CSemanticChecker GetSemanticChecker() { return _pSemanticChecker; }
private ErrorHandling GetErrorContext() { return GetSymbolLoader().GetErrorContext(); }
private void ReportBogus(SymWithType swt)
{
Debug.Assert(swt.Sym.hasBogus() && swt.Sym.checkBogus());
switch (swt.Sym.getKind())
{
case SYMKIND.SK_EventSymbol:
break;
case SYMKIND.SK_PropertySymbol:
if (swt.Prop().useMethInstead)
{
MethodSymbol meth1 = swt.Prop().methGet;
MethodSymbol meth2 = swt.Prop().methSet;
ReportBogusForEventsAndProperties(swt, meth1, meth2);
return;
}
break;
case SYMKIND.SK_MethodSymbol:
if (swt.Meth().name == GetSymbolLoader().GetNameManager().GetPredefName(PredefinedName.PN_INVOKE) && swt.Meth().getClass().IsDelegate())
{
swt.Set(swt.Meth().getClass(), swt.GetType());
}
break;
default:
break;
}
// Generic bogus error.
GetErrorContext().ErrorRef(ErrorCode.ERR_BindToBogus, swt);
}
private void ReportBogusForEventsAndProperties(SymWithType swt, MethodSymbol meth1, MethodSymbol meth2)
{
if (meth1 != null && meth2 != null)
{
GetErrorContext().Error(ErrorCode.ERR_BindToBogusProp2, swt.Sym.name, new SymWithType(meth1, swt.GetType()), new SymWithType(meth2, swt.GetType()), new ErrArgRefOnly(swt.Sym));
return;
}
if (meth1 != null || meth2 != null)
{
GetErrorContext().Error(ErrorCode.ERR_BindToBogusProp1, swt.Sym.name, new SymWithType(meth1 != null ? meth1 : meth2, swt.GetType()), new ErrArgRefOnly(swt.Sym));
return;
}
throw Error.InternalCompilerError();
}
private bool IsDelegateType(CType pSrcType, AggregateType pAggType)
{
CType pInstantiatedType = GetSymbolLoader().GetTypeManager().SubstType(pSrcType, pAggType, pAggType.GetTypeArgsAll());
return pInstantiatedType.isDelegateType();
}
/////////////////////////////////////////////////////////////////////////////////
// Public methods.
public MemberLookup()
{
_methPropWithTypeList = new List<MethPropWithType>();
_rgtypeStart = new List<AggregateType>();
_swtFirst = new SymWithType();
_swtAmbig = new SymWithType();
_swtInaccess = new SymWithType();
_swtBad = new SymWithType();
_swtBogus = new SymWithType();
_swtBadArity = new SymWithType();
_swtAmbigWarn = new SymWithType();
_swtOverride = new SymWithType();
}
/***************************************************************************************************
Lookup must be called before anything else can be called.
typeSrc - Must be an AggregateType or TypeParameterType.
obj - the expression through which the member is being accessed. This is used for accessibility
of protected members and for constructing a MEMGRP from the results of the lookup.
It is legal for obj to be an EK_CLASS, in which case it may be used for accessibility, but
will not be used for MEMGRP construction.
symWhere - the symbol from with the name is being accessed (for checking accessibility).
name - the name to look for.
arity - the number of type args specified. Only members that support this arity are found.
Note that when arity is zero, all methods are considered since we do type argument
inferencing.
flags - See MemLookFlags.
TypeVarsAllowed only applies to the most derived type (not base types).
***************************************************************************************************/
public bool Lookup(CSemanticChecker checker, CType typeSrc, EXPR obj, ParentSymbol symWhere, Name name, int arity, MemLookFlags flags)
{
Debug.Assert((flags & ~MemLookFlags.All) == 0);
Debug.Assert(obj == null || obj.type != null);
Debug.Assert(typeSrc.IsAggregateType() || typeSrc.IsTypeParameterType());
Debug.Assert(checker != null);
_prgtype = _rgtypeStart;
// Save the inputs for error handling, etc.
_pSemanticChecker = checker;
_pSymbolLoader = checker.GetSymbolLoader();
_typeSrc = typeSrc;
_obj = (obj != null && !obj.isCLASS()) ? obj : null;
_symWhere = symWhere;
_name = name;
_arity = arity;
_flags = flags;
if ((_flags & MemLookFlags.BaseCall) != 0)
_typeQual = null;
else if ((_flags & MemLookFlags.Ctor) != 0)
_typeQual = _typeSrc;
else if (obj != null)
_typeQual = (CType)obj.type;
else
_typeQual = null;
// Determine what to search.
AggregateType typeCls1 = null;
AggregateType typeIface = null;
TypeArray ifaces = BSYMMGR.EmptyTypeArray();
AggregateType typeCls2 = null;
if (typeSrc.IsTypeParameterType())
{
Debug.Assert((_flags & (MemLookFlags.Ctor | MemLookFlags.NewObj | MemLookFlags.Operator | MemLookFlags.BaseCall | MemLookFlags.TypeVarsAllowed)) == 0);
_flags &= ~MemLookFlags.TypeVarsAllowed;
ifaces = typeSrc.AsTypeParameterType().GetInterfaceBounds();
typeCls1 = typeSrc.AsTypeParameterType().GetEffectiveBaseClass();
if (ifaces.Count > 0 && typeCls1.isPredefType(PredefinedType.PT_OBJECT))
typeCls1 = null;
}
else if (!typeSrc.isInterfaceType())
{
typeCls1 = typeSrc.AsAggregateType();
if (typeCls1.IsWindowsRuntimeType())
{
ifaces = typeCls1.GetWinRTCollectionIfacesAll(GetSymbolLoader());
}
}
else
{
Debug.Assert(typeSrc.isInterfaceType());
Debug.Assert((_flags & (MemLookFlags.Ctor | MemLookFlags.NewObj | MemLookFlags.Operator | MemLookFlags.BaseCall)) == 0);
typeIface = typeSrc.AsAggregateType();
ifaces = typeIface.GetIfacesAll();
}
if (typeIface != null || ifaces.Count > 0)
typeCls2 = GetSymbolLoader().GetReqPredefType(PredefinedType.PT_OBJECT);
// Search the class first (except possibly object).
if (typeCls1 == null || LookupInClass(typeCls1, ref typeCls2))
{
// Search the interfaces.
if ((typeIface != null || ifaces.Count > 0) && LookupInInterfaces(typeIface, ifaces) && typeCls2 != null)
{
// Search object last.
Debug.Assert(typeCls2 != null && typeCls2.isPredefType(PredefinedType.PT_OBJECT));
AggregateType result = null;
LookupInClass(typeCls2, ref result);
}
}
// if we are requested with extension methods
_results = new CMemberLookupResults(GetAllTypes(), _name);
return !FError();
}
public CMemberLookupResults GetResults()
{
return _results;
}
// Whether there were errors.
private bool FError()
{
return !_swtFirst || _swtAmbig;
}
// The first symbol found.
public Symbol SymFirst()
{
return _swtFirst.Sym;
}
public SymWithType SwtFirst()
{
return _swtFirst;
}
public SymWithType SwtInaccessible()
{
return _swtInaccess;
}
public EXPR GetObject()
{
return _obj;
}
public CType GetSourceType()
{
return _typeSrc;
}
public MemLookFlags GetFlags()
{
return _flags;
}
// Put all the types in a type array.
private TypeArray GetAllTypes()
{
return GetSymbolLoader().getBSymmgr().AllocParams(_prgtype.Count, _prgtype.ToArray());
}
/******************************************************************************
Reports errors. Only call this if FError() is true.
******************************************************************************/
public void ReportErrors()
{
Debug.Assert(FError());
// Report error.
// NOTE: If the definition of FError changes, this code will need to change.
Debug.Assert(!_swtFirst || _swtAmbig);
if (_swtFirst)
{
// Ambiguous lookup.
GetErrorContext().ErrorRef(ErrorCode.ERR_AmbigMember, _swtFirst, _swtAmbig);
}
else if (_swtInaccess)
{
if (!_swtInaccess.Sym.isUserCallable() && ((_flags & MemLookFlags.UserCallable) != 0))
GetErrorContext().Error(ErrorCode.ERR_CantCallSpecialMethod, _swtInaccess);
else
GetSemanticChecker().ReportAccessError(_swtInaccess, _symWhere, _typeQual);
}
else if ((_flags & MemLookFlags.Ctor) != 0)
{
if (_arity > 0)
{
GetErrorContext().Error(ErrorCode.ERR_BadCtorArgCount, _typeSrc.getAggregate(), _arity);
}
else
{
GetErrorContext().Error(ErrorCode.ERR_NoConstructors, _typeSrc.getAggregate());
}
}
else if ((_flags & MemLookFlags.Operator) != 0)
{
GetErrorContext().Error(ErrorCode.ERR_NoSuchMember, _typeSrc, _name);
}
else if ((_flags & MemLookFlags.Indexer) != 0)
{
GetErrorContext().Error(ErrorCode.ERR_BadIndexLHS, _typeSrc);
}
else if (_swtBad)
{
GetErrorContext().Error((_flags & MemLookFlags.MustBeInvocable) != 0 ? ErrorCode.ERR_NonInvocableMemberCalled : ErrorCode.ERR_CantCallSpecialMethod, _swtBad);
}
else if (_swtBogus)
{
ReportBogus(_swtBogus);
}
else if (_swtBadArity)
{
int cvar;
switch (_swtBadArity.Sym.getKind())
{
case SYMKIND.SK_MethodSymbol:
Debug.Assert(_arity != 0);
cvar = _swtBadArity.Sym.AsMethodSymbol().typeVars.Count;
GetErrorContext().ErrorRef(cvar > 0 ? ErrorCode.ERR_BadArity : ErrorCode.ERR_HasNoTypeVars, _swtBadArity, new ErrArgSymKind(_swtBadArity.Sym), cvar);
break;
case SYMKIND.SK_AggregateSymbol:
cvar = _swtBadArity.Sym.AsAggregateSymbol().GetTypeVars().Count;
GetErrorContext().ErrorRef(cvar > 0 ? ErrorCode.ERR_BadArity : ErrorCode.ERR_HasNoTypeVars, _swtBadArity, new ErrArgSymKind(_swtBadArity.Sym), cvar);
break;
default:
Debug.Assert(_arity != 0);
ExpressionBinder.ReportTypeArgsNotAllowedError(GetSymbolLoader(), _arity, _swtBadArity, new ErrArgSymKind(_swtBadArity.Sym));
break;
}
}
else
{
if ((_flags & MemLookFlags.ExtensionCall) != 0)
{
GetErrorContext().Error(ErrorCode.ERR_NoSuchMemberOrExtension, _typeSrc, _name);
}
else
{
GetErrorContext().Error(ErrorCode.ERR_NoSuchMember, _typeSrc, _name);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using FluentValidation.Results;
using SFA.DAS.ProviderApprenticeshipsService.Web.Extensions;
using SFA.DAS.ProviderApprenticeshipsService.Web.Models;
using SFA.DAS.ProviderApprenticeshipsService.Web.Models.BulkUpload;
using SFA.DAS.ProviderApprenticeshipsService.Web.Models.Types;
using SFA.DAS.ProviderApprenticeshipsService.Web.Orchestrators.BulkUpload;
using SFA.DAS.ProviderApprenticeshipsService.Web.Validation.Text;
using SFA.DAS.Learners.Validators;
using SFA.DAS.ProviderApprenticeshipsService.Domain.Interfaces;
namespace SFA.DAS.ProviderApprenticeshipsService.Web.Validation
{
public sealed class ApprenticeshipUploadModelValidator : IApprenticeshipUploadModelValidator
{
private readonly IApprenticeshipValidationErrorText _validationText;
private readonly ICurrentDateTime _currentDateTime;
private readonly IUlnValidator _ulnValidator;
private readonly IAcademicYearDateProvider _academicYearDateProvider;
private static readonly Func<string, IEnumerable<string>, bool> InList = (v, l) => string.IsNullOrWhiteSpace(v) || l.Contains(v);
public ApprenticeshipUploadModelValidator(IApprenticeshipValidationErrorText validationText, ICurrentDateTime currentDateTime, IUlnValidator ulnValidator, IAcademicYearDateProvider academicYearDateProvider)
{
_validationText = validationText;
_currentDateTime = currentDateTime;
_ulnValidator = ulnValidator;
_academicYearDateProvider = academicYearDateProvider;
}
public ValidationResult Validate(ApprenticeshipUploadModel model)
{
var validationResult = new ValidationResult();
ValidateField(validationResult, ValidateFirstName, model);
ValidateField(validationResult, ValidateLastName, model);
ValidateField(validationResult, ValidateULN, model);
ValidateField(validationResult, ValidateDateOfBirth, model);
ValidateField(validationResult, ValidateStartDate, model);
ValidateField(validationResult, ValidateEndDate, model);
ValidateField(validationResult, ValidateCost, model);
ValidateField(validationResult, ValidateProviderRef, model);
ValidateField(validationResult, ValidateStdCode, model);
ValidateField(validationResult, ValidateEmail, model);
ValidateField(validationResult, ValidateAgreementId, model);
return validationResult;
}
private ValidationFailure ValidateFirstName(ApprenticeshipUploadModel model)
{
if (string.IsNullOrWhiteSpace(model.ApprenticeshipViewModel.FirstName))
{
return CreateValidationFailure("FirstName", _validationText.GivenNames01);
}
if (model.ApprenticeshipViewModel.FirstName.Length > 100)
{
return CreateValidationFailure("FirstName", _validationText.GivenNames02);
}
return null;
}
private ValidationFailure ValidateLastName(ApprenticeshipUploadModel model)
{
if (string.IsNullOrWhiteSpace(model.ApprenticeshipViewModel.LastName))
{
return CreateValidationFailure("LastName", _validationText.FamilyName01);
}
if (model.ApprenticeshipViewModel.LastName.Length > 100)
{
return CreateValidationFailure("LastName", _validationText.FamilyName02);
}
return null;
}
private ValidationFailure ValidateULN(ApprenticeshipUploadModel model)
{
var result = _ulnValidator.Validate(model.ApprenticeshipViewModel.ULN);
switch (result)
{
case UlnValidationResult.IsEmptyUlnNumber:
case UlnValidationResult.IsInValidTenDigitUlnNumber:
return CreateValidationFailure("ULN", _validationText.Uln01);
case UlnValidationResult.IsInvalidUln:
return CreateValidationFailure("ULN", _validationText.Uln03);
}
return null;
}
private ValidationFailure ValidateDateOfBirth(ApprenticeshipUploadModel model)
{
if (model.ApprenticeshipViewModel.DateOfBirth == null)
{
return CreateValidationFailure("DateOfBirth", _validationText.DateOfBirth01);
}
if (model.ApprenticeshipViewModel.DateOfBirth.DateTime == null || !model.ApprenticeshipViewModel.DateOfBirth.Day.HasValue)
{
return CreateValidationFailure("DateOfBirth", _validationText.DateOfBirth01);
}
if (!ApprenticeDobMustBeGreaterThenMinimumDob(model.ApprenticeshipViewModel.DateOfBirth))
{
return CreateValidationFailure("DateOfBirth", _validationText.DateOfBirth07);
}
if (!WillApprenticeBeAtLeast15AtStartOfTraining(model.ApprenticeshipViewModel, model.ApprenticeshipViewModel.DateOfBirth))
{
return CreateValidationFailure("DateOfBirth", _validationText.DateOfBirth02);
}
if (!ApprenticeAgeMustBeLessThen115AtStartOfTraining(model.ApprenticeshipViewModel, model.ApprenticeshipViewModel.DateOfBirth))
{
return CreateValidationFailure("DateOfBirth", _validationText.DateOfBirth06);
}
return null;
}
private bool ApprenticeDobMustBeGreaterThenMinimumDob(DateTimeViewModel dob)
{
DateTime? dobDate = dob?.DateTime;
DateTime minimumDataOfBirth = new DateTime(1900, 01, 01, 0, 0, 0, DateTimeKind.Utc);
if (dobDate == null) return true;
return dobDate > minimumDataOfBirth;
}
private ValidationFailure ValidateStartDate(ApprenticeshipUploadModel model)
{
if (model.ApprenticeshipViewModel.StartDate == null)
{
// we pass the field that failed, but that ultimatly gets discarded anyway, so why bother? we could just work with validationmessages
return CreateValidationFailure("StartDate", _validationText.LearnStartDate01);
}
if (model.ApprenticeshipViewModel.StartDate.DateTime == null)
{
return CreateValidationFailure("StartDate", _validationText.LearnStartDate01);
}
var apprenticeshipAllowedStartDate = new DateTime(2017, 05, 01);
if (model.ApprenticeshipViewModel.StartDate.DateTime < apprenticeshipAllowedStartDate
&& !model.ApprenticeshipViewModel.IsPaidForByTransfer)
return CreateValidationFailure("StartDate", _validationText.LearnStartDate02);
var transfersAllowedStartDate = new DateTime(2018, 05, 01);
if (model.ApprenticeshipViewModel.StartDate.DateTime < transfersAllowedStartDate
&& model.ApprenticeshipViewModel.IsPaidForByTransfer)
return CreateValidationFailure("StartDate", _validationText.LearnStartDate06);
if (model.ApprenticeshipViewModel.StartDate.DateTime > _academicYearDateProvider.CurrentAcademicYearEndDate.AddYears(1))
return CreateValidationFailure("StartDate", _validationText.LearnStartDate05);
// we could check the start date against the training programme here, but we'd have to pass the trainingprogrammes through the call stack, or refetch them, or make them available another way e.g. static.
// none of these choices are appealing, so we'll wait until bulk upload is refactored
return null;
}
private ValidationFailure ValidateEndDate(ApprenticeshipUploadModel model)
{
if (model.ApprenticeshipViewModel.EndDate == null)
{
return CreateValidationFailure("EndDate", _validationText.LearnPlanEndDate01);
}
if (model.ApprenticeshipViewModel.EndDate.DateTime == null)
{
return CreateValidationFailure("EndDate", _validationText.LearnPlanEndDate01);
}
if (model.ApprenticeshipViewModel.StartDate != null && model.ApprenticeshipViewModel.EndDate.DateTime <= model.ApprenticeshipViewModel.StartDate.DateTime)
{
return CreateValidationFailure("EndDate", _validationText.LearnPlanEndDate02);
}
return null;
}
private ValidationFailure ValidateCost(ApprenticeshipUploadModel model)
{
if (string.IsNullOrWhiteSpace(model.ApprenticeshipViewModel.Cost))
{
return CreateValidationFailure("Cost", _validationText.TrainingPrice01);
}
if (!Regex.Match(model.ApprenticeshipViewModel.Cost, "^([1-9]{1}([0-9]{1,2})?)+(,[0-9]{3})*$|^[1-9]{1}[0-9]*$").Success)
{
return CreateValidationFailure("Cost", _validationText.TrainingPrice01);
}
if (!decimal.TryParse(model.ApprenticeshipViewModel.Cost, out var parsed) || parsed > 100000)
{
return CreateValidationFailure("Cost", _validationText.TrainingPrice02);
}
return null;
}
private ValidationFailure ValidateProviderRef(ApprenticeshipUploadModel model)
{
if (!string.IsNullOrWhiteSpace(model.ApprenticeshipViewModel.ProviderRef) && model.ApprenticeshipViewModel.ProviderRef.Length > 20)
{
return CreateValidationFailure("ProviderRef", _validationText.ProviderRef01);
}
return null;
}
private ValidationFailure ValidateStdCode(ApprenticeshipUploadModel model)
{
if (string.IsNullOrWhiteSpace(model.CsvRecord.StdCode))
{
return CreateValidationFailure("StdCode", _validationText.StdCode04);
}
if (!string.IsNullOrWhiteSpace(model.CsvRecord.StdCode) && (model.CsvRecord.StdCode.TryParse() ?? 100000) > 99999)
{
return CreateValidationFailure("StdCode", _validationText.StdCode01);
}
if ((model.CsvRecord.StdCode.TryParse() ?? 0) <= 0)
{
return CreateValidationFailure("StdCode", _validationText.StdCode02);
}
return null;
}
private ValidationFailure ValidateEmail(ApprenticeshipUploadModel model)
{
if (model.ApprenticeshipViewModel.BlackListed && string.IsNullOrEmpty(model.CsvRecord.EmailAddress))
{
return null;
}
if (string.IsNullOrEmpty(model.CsvRecord.EmailAddress))
{
return CreateValidationFailure("EmailAddress", _validationText.EmailAddressBlank);
}
if (!model.CsvRecord.EmailAddress.IsAValidEmailAddress())
{
return CreateValidationFailure("EmailAddress", _validationText.EmailAddressNotValid);
}
if (model.CsvRecord.EmailAddress.Length > 200)
{
return CreateValidationFailure("EmailAddress", _validationText.EmailAddressLength);
}
return null;
}
private ValidationFailure ValidateAgreementId(ApprenticeshipUploadModel model)
{
if (string.IsNullOrEmpty(model.CsvRecord.AgreementId))
{
return CreateValidationFailure("AgreementId", _validationText.AgreementIdBlank);
}
return null;
}
private void ValidateField(ValidationResult validationResult, Func<ApprenticeshipUploadModel, ValidationFailure> validationFunc, ApprenticeshipUploadModel model)
{
var validationFailure = validationFunc(model);
if (validationFailure != null)
{
validationResult.Errors.Add(validationFailure);
}
}
private ValidationFailure CreateValidationFailure(string propertyName, ValidationMessage validationMessage)
{
return new ValidationFailure(propertyName, validationMessage.Text) {ErrorCode = validationMessage.ErrorCode};
}
private bool WillApprenticeBeAtLeast15AtStartOfTraining(ApprenticeshipViewModel model, DateTimeViewModel dob)
{
DateTime? startDate = model?.StartDate?.DateTime;
DateTime? dobDate = dob?.DateTime;
if (startDate == null || dob == null) return true; // Don't fail validation if both fields not set
int age = startDate.Value.Year - dobDate.Value.Year;
if (startDate < dobDate.Value.AddYears(age)) age--;
return age >= 15;
}
private bool ApprenticeAgeMustBeLessThen115AtStartOfTraining(ApprenticeshipViewModel model, DateTimeViewModel dob)
{
DateTime? startDate = model?.StartDate?.DateTime;
DateTime? dobDate = dob?.DateTime;
if (startDate == null || dob == null) return true; // Don't fail validation if both fields not set
int age = startDate.Value.Year - dobDate.Value.Year;
if (startDate < dobDate.Value.AddYears(age)) age--;
return age < 115;
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Adxstudio.Xrm.Services;
using Adxstudio.Xrm.Services.Query;
using Microsoft.Xrm.Portal.Cms;
using Microsoft.Xrm.Portal.Configuration;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Portal.Web;
using Microsoft.Xrm.Sdk.Query;
namespace Adxstudio.Xrm.Web
{
/// <summary>
/// An <see cref="IRedirectProvider"/> which implements its <see cref="Match"/> based on adx_urlhistory entities
/// associated with a given adx_website.
/// </summary>
public class UrlHistoryRedirectProvider : IRedirectProvider
{
private static readonly string[] _homePaths = new[] { "~", "/", "~/" };
public string PortalName { get; private set; }
public UrlHistoryRedirectProvider(string portalName)
{
PortalName = portalName;
}
protected OrganizationServiceContext CreateContext()
{
return PortalCrmConfigurationManager.CreateServiceContext(PortalName);
}
public IRedirectMatch Match(Guid websiteID, UrlBuilder url)
{
if (url == null)
{
throw new ArgumentNullException("url");
}
using (var context = CreateContext())
{
var website = context.RetrieveSingle(
"adx_website",
FetchAttribute.All,
new[] {
new Condition("statecode", ConditionOperator.Equal, 0),
new Condition("adx_websiteid", ConditionOperator.Equal, websiteID) },
true);
if (website == null)
{
return new FailedRedirectMatch();
}
var appRelativePath = VirtualPathUtility.ToAppRelative(url.Path);
var match = FindPage(context, website, appRelativePath);
// Matches must have actually used the URL history (not be live currently) to count as a match.
if (match.Success && match.UsedHistory)
{
return new UrlHistoryMatch(context.GetUrl(match.WebPage));
}
return new FailedRedirectMatch();
}
}
private static Entity FindHistoryMatchPage(OrganizationServiceContext context, Entity website, string path)
{
var fetch = new Fetch
{
Entity = new FetchEntity("adx_urlhistory")
{
Attributes = new[]
{
new FetchAttribute("adx_webpageid")
},
Filters = new List<Filter>
{
new Filter
{
Conditions = new[]
{
new Condition("statecode", ConditionOperator.Equal, 0),
new Condition("adx_websiteid", ConditionOperator.Equal, website.Id),
new Condition("adx_name", ConditionOperator.Equal, path)
}
}
},
Orders = new[]
{
new Order("adx_changeddate", OrderType.Descending)
}
}
};
var historyMatch = context.RetrieveSingle(fetch);
if (historyMatch == null)
{
return null;
}
var historyWebPageReference = historyMatch.GetAttributeValue<EntityReference>("adx_webpageid");
if (historyWebPageReference == null)
{
return null;
}
fetch = new Fetch
{
Entity = new FetchEntity("adx_webpage")
{
Filters = new List<Filter>
{
new Filter
{
Conditions = new[]
{
new Condition("statecode", ConditionOperator.Equal, 0),
new Condition("adx_webpageid", ConditionOperator.Equal, historyWebPageReference.Id)
}
}
}
}
};
return context.RetrieveSingle(fetch);
}
private static IMatch FindPage(OrganizationServiceContext context, Entity website, string path)
{
var mappedPageResult = UrlMapping.LookupPageByUrlPath(context, website, path);
if (mappedPageResult.Node != null)
{
return new NonHistoryMatch(mappedPageResult.Node);
}
var historyMatchPage = FindHistoryMatchPage(context, website, path);
if (historyMatchPage != null)
{
return new HistoryMatch(historyMatchPage);
}
// find the last slash in the path
var lastSlash = path.LastIndexOf('/');
if (lastSlash != -1)
{
// we found a slash
var pathBeforeSlash = path.Substring(0, lastSlash);
var pathAfterSlash = path.Substring(lastSlash + 1);
var parentMatch = (string.IsNullOrWhiteSpace(pathBeforeSlash) || _homePaths.Contains(pathBeforeSlash))
// do a final traversal against the home page
? GetHomePage(context, website)
// see if we can find a path for the parent url
: FindPage(context, website, pathBeforeSlash);
if (parentMatch.Success)
{
var foundParentPageID = parentMatch.WebPage.ToEntityReference();
var fetch = new Fetch
{
Entity = new FetchEntity("adx_webpage")
{
Filters = new List<Filter>
{
new Filter
{
Conditions = new[]
{
new Condition("statecode", ConditionOperator.Equal, 0),
new Condition("adx_parentpageid", ConditionOperator.Equal, foundParentPageID.Id),
new Condition("adx_partialurl", ConditionOperator.Equal, pathAfterSlash)
}
}
}
}
};
// we found a parent path, now rebuild the path of the child
var child = context.RetrieveSingle(fetch);
if (child != null)
{
return new SuccessfulMatch(child, parentMatch.UsedHistory);
}
var parentPath = context.GetApplicationPath(parentMatch.WebPage);
if (parentPath == null)
{
return new FailedMatch();
}
if (parentPath.AppRelativePath.TrimEnd('/') == path)
{
// prevent stack overflow
return new FailedMatch();
}
var newPath = parentPath.AppRelativePath + (parentPath.AppRelativePath.EndsWith("/") ? string.Empty : "/") + pathAfterSlash;
if (newPath == path)
{
return new FailedMatch();
}
var childMatch = FindPage(context, website, newPath);
if (childMatch.Success)
{
return new HistoryMatch(childMatch.WebPage);
}
}
}
return new FailedMatch();
}
private static IMatch GetHomePage(OrganizationServiceContext context, Entity website)
{
var homePage = context.GetPageBySiteMarkerName(website, "Home");
return homePage == null
? (IMatch)new FailedMatch()
: new NonHistoryMatch(homePage);
}
private interface IMatch
{
bool Success { get; }
bool UsedHistory { get; }
Entity WebPage { get; }
}
private class FailedMatch : IMatch
{
public bool Success
{
get { return false; }
}
public bool UsedHistory
{
get { return false; }
}
public Entity WebPage
{
get { return null; }
}
}
private class SuccessfulMatch : IMatch
{
public SuccessfulMatch(Entity webPage, bool usedHistory)
{
if (webPage == null)
{
throw new ArgumentNullException("webPage");
}
WebPage = webPage;
UsedHistory = usedHistory;
}
public bool Success
{
get { return true; }
}
public bool UsedHistory { get; private set; }
public Entity WebPage { get; private set; }
}
private class HistoryMatch : SuccessfulMatch
{
public HistoryMatch(Entity webPage) : base(webPage, true) { }
}
private class NonHistoryMatch : SuccessfulMatch
{
public NonHistoryMatch(Entity webPage) : base(webPage, false) { }
}
}
}
| |
// ==++==
//
//
// Copyright (c) 2006 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
// [assembly:System.Runtime.InteropServices.Guid("D3295D86-D604-11D4-A704-00C04FA137E4")]
// [assembly:System.Security.AllowPartiallyTrustedCallers()]
namespace Microsoft.Vsa
{
using System.CodeDom;
using System.Runtime.InteropServices;
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
/* VsaItemType is also defined in vs\src\vsa\vbapkg\src\vbapkg.idl
If you want to change the definition here, you have to make changes there too.
See comment in vs\src\vsa\vbapkg\src\vbapkg.idl which explain why we need
this definition twice */
[Guid("a9f6f86e-fcf5-3d8d-97e4-0fe6c7fe2274")]
[Obsolete(VsaObsolete.Description)]
public enum VsaItemType
{
Reference, // IVsaReferenceItem - COM+ Assembly or RCW
AppGlobal, // IVsaItem - application object
Code, // IVsaCodeItem - vsa code
}
[Guid("40d8ce77-8139-3483-8674-bb9e3acd9b89")]
[Obsolete(VsaObsolete.Description)]
public enum VsaItemFlag
{
None, // No special flags required or flags not accepted
Module, // Global Module
Class, // Instantiable COM+ class.
}
[Guid("05a1147d-6c8d-3bb8-888f-8bfa319b2e6f")]
[Obsolete(VsaObsolete.Description)]
public enum VsaIDEMode
{
Break, // Break mode - debugger is attached and in break mode
Design, // Design mode - debugger is not attached
Run, // Run mode - debugger is attached
}
[Guid("E0C0FFE1-7eea-4ee2-b7e4-0080c7eb0b74")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Obsolete(VsaObsolete.Description)]
public interface IVsaEngine
{
// === Site ===
IVsaSite Site
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
set;
}
// === Properties ===
// Name, RootMoniker, RootNameSpace are first class properties of the engine
// Never assume get, set operations of first class properties can be the
// equivalent of calling SetOption and GetOption
string Name
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
set;
}
string RootMoniker
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
set;
}
// Default namespace used by the engine
string RootNamespace
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
set;
}
int LCID
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
set;
}
bool GenerateDebugInfo
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
set;
}
System.Security.Policy.Evidence Evidence
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
set;
}
// collection of items
IVsaItems Items
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
}
// returns TRUE if any item in the engine has been dirtied
bool IsDirty
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
}
// return the programming language of the engine (e.g. VB or JScript)
string Language
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
}
// returns the engine version
string Version
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
}
// engine options (methods)
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
object GetOption(string name);
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
void SetOption(string name, object value);
// === State management ===
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
bool Compile();
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
void Run();
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
void Reset();
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
void Close();
bool IsRunning
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
}
bool IsCompiled
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
}
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
void RevokeCache();
// === Source State ===
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
void SaveSourceState(IVsaPersistSite site);
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
void LoadSourceState(IVsaPersistSite site);
// === Compiled State ===
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
void SaveCompiledState(out byte[] pe, out byte[] pdb);
// Called if the engine state will be set by calls (rather than a call to by LoadSourceState)
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
void InitNew();
// returns TRUE if the identifier if legal for the language of the engine
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
bool IsValidIdentifier(string identifier);
// === Assembly ===
System.Reflection.Assembly Assembly { get; }
} // IVsaEngine
[Guid("E0C0FFE2-7eea-4ee2-b7e4-0080c7eb0b74")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Obsolete(VsaObsolete.Description)]
public interface IVsaSite
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
void GetCompiledState(out byte[] pe, out byte[] debugInfo);
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
bool OnCompilerError(IVsaError error);
object GetGlobalInstance( string name );
object GetEventSourceInstance( string itemName,
string eventSourceName);
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
void Notify(string notify, object info);
} // IVSaSite
[Guid("E0C0FFE3-7eea-4ee2-b7e4-0080c7eb0b74")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Obsolete(VsaObsolete.Description)]
public interface IVsaPersistSite
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
void SaveElement(string name, string source);
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
string LoadElement(string name);
} // IVsaPersistSite
[Guid("E0C0FFE4-7eea-4ee2-b7e4-0080c7eb0b74")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Obsolete(VsaObsolete.Description)]
public interface IVsaError
{
int Line
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
}
int Severity
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
}
string Description
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
}
string LineText
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
}
IVsaItem SourceItem
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
}
// returns the ending column of the text creating the error
int EndColumn
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
}
// returns the beginning column of the text creating the error
int StartColumn
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
}
// Error number
int Number
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
}
// (fully qualified?) moniker of item with error
string SourceMoniker
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
}
} // IVsaError
[Guid("E0C0FFE5-7eea-4ee5-b7e4-0080c7eb0b74")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Obsolete(VsaObsolete.Description)]
public interface IVsaItem
{
string Name
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
set;
}
VsaItemType ItemType
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
}
// returns TRUE if item is dirty
bool IsDirty
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
}
// item option (property)
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
object GetOption(string name);
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
void SetOption(string name, object value);
} // IVsaItem
[Guid("0AB1EB6A-12BD-44d0-B941-0580ADFC73DE")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Obsolete(VsaObsolete.Description)]
public interface IVsaItems : System.Collections.IEnumerable
{
int Count
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
}
IVsaItem this[string name]
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
}
IVsaItem this[int index]
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
}
// Create an item
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
IVsaItem CreateItem(string name, VsaItemType itemType, VsaItemFlag itemFlag);
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
void Remove(string name);
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
void Remove(int index);
} // IVsaItems
[Guid("E0C0FFE6-7eea-4ee5-b7e4-0080c7eb0b74")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Obsolete(VsaObsolete.Description)]
public interface IVsaReferenceItem : IVsaItem
{
string AssemblyName
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
set;
}
} // IVsaReferenceItem
[Guid("E0C0FFE7-7eea-4ee5-b7e4-0080c7eb0b74")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Obsolete(VsaObsolete.Description)]
public interface IVsaCodeItem : IVsaItem
{
string SourceText
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
set;
}
// returns a CodeDom tree for this code item. The CodeObject returned is of type
// System.CodeDom.CodeCompileUnit
System.CodeDom.CodeObject CodeDOM
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
}
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
void AppendSourceText(string text);
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
void AddEventSource( string eventSourceName,
string eventSourceType);
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
void RemoveEventSource( string eventSourceName);
} // IVsaCodeItem
[Guid("4E76D92E-E29D-46f3-AE22-0333158109F1")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Obsolete(VsaObsolete.Description)]
public interface IVsaGlobalItem : IVsaItem
{
string TypeString
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
set;
}
bool ExposeMembers
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
set;
}
} // IVsaGlobalItem
[Guid("7BD84086-1FB5-4b5d-8E05-EAA2F17218E0")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Obsolete(VsaObsolete.Description)]
public interface IVsaIDESite
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
void Notify(string notify, object optional);
} // IVsaIDESite
[Guid("78470A10-8153-407d-AB1B-05067C54C36B")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Obsolete(VsaObsolete.Description)]
public interface IVsaIDE
{
// === Site ===
IVsaIDESite Site
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
set;
}
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
void ShowIDE(bool showOrHide);
// determines default starting search path of the Find dialog
string DefaultSearchPath
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
set;
}
object ExtensibilityObject
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
}
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
void EnableMainWindow(bool isEnable);
VsaIDEMode IDEMode
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
}
} // IVsaIDE
[Guid("E0C0FFEE-7eea-4ee5-b7e4-0080c7eb0b74")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Obsolete(VsaObsolete.Description)]
public interface IVsaDTEngine
{
// remote debugging properties
string TargetURL
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
set;
}
// methods
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
void InitCompleted();
IVsaIDE GetIDE();
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
void AttachDebugger(bool isAttach);
} // IVsaDTEngine
[Guid("E0C0FFED-7eea-4ee5-b7e4-0080c7eb0b74")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Obsolete(VsaObsolete.Description)]
public interface IVsaDTCodeItem
{
// IDE control attributes
bool CanDelete
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
set;
}
bool CanMove
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
set;
}
bool CanRename
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
set;
}
bool Hidden
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
set;
}
// TRUE means buffer cannot be edited
bool ReadOnly
{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get;
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
set;
}
} // IVsaDTCodeItem
// Make it contiguous so that it's easy to determine whether this is a VsaError.
// WARNING: If you change the error code below, you MUST make the corresponding changes in vs\src\common\inc\vsa\vsares.h
// Note we are using the int (as opposed to unsigned hex) values for CLS Compliance
[Guid("c216f805-8fab-3d33-bf81-7b1035e917b9")]
[Obsolete(VsaObsolete.Description)]
public enum VsaError : int
{
AppDomainCannotBeSet = -2146226176, // 0x80133000
AppDomainInvalid = -2146226175, // 0x80133001
ApplicationBaseCannotBeSet = -2146226174, // 0x80133002
ApplicationBaseInvalid = -2146226173, // 0x80133003
AssemblyExpected = -2146226172, // 0x80133004
AssemblyNameInvalid = -2146226171, // 0x80133005
BadAssembly = -2146226170, // 0x80133006
CachedAssemblyInvalid = -2146226169, // 0x80133007
CallbackUnexpected = -2146226168, // 0x80133008
CodeDOMNotAvailable = -2146226167, // 0x80133009
CompiledStateNotFound = -2146226166, // 0x8013300A
DebugInfoNotSupported = -2146226165, // 0x8013300B
ElementNameInvalid = -2146226164, // 0x8013300C
ElementNotFound = -2146226163, // 0x8013300D
EngineBusy = -2146226162, // 0x8013300E
EngineCannotClose = -2146226161, // 0x8013300F
EngineCannotReset = -2146226160, // 0x80133010
EngineClosed = -2146226159, // 0x80133011
EngineEmpty = -2146226159, // 0x80133012
EngineInitialized = -2146226157, // 0x80133013
EngineNameInUse = -2146226156, // 0x80133014
EngineNotCompiled = -2146226155, // 0x80133015
EngineNotInitialized = -2146226154, // 0x80133016
EngineNotRunning = -2146226153, // 0x80133017
EngineRunning = -2146226152, // 0x80133018
EventSourceInvalid = -2146226151, // 0x80133019
EventSourceNameInUse = -2146226150, // 0x8013301A
EventSourceNameInvalid = -2146226149, // 0x8013301B
EventSourceNotFound = -2146226148, // 0x8013301C
EventSourceTypeInvalid = -2146226147, // 0x8013301D
GetCompiledStateFailed = -2146226146, // 0x8013301E
GlobalInstanceInvalid = -2146226145, // 0x8013301F
GlobalInstanceTypeInvalid = -2146226144, // 0x80133020
InternalCompilerError = -2146226143, // 0x80133021
ItemCannotBeRemoved = -2146226142, // 0x80133022
ItemFlagNotSupported = -2146226141, // 0x80133023
ItemNameInUse = -2146226140, // 0x80133024
ItemNameInvalid = -2146226139, // 0x80133025
ItemNotFound = -2146226138, // 0x80133026
ItemTypeNotSupported = -2146226137, // 0x80133027
LCIDNotSupported = -2146226136, // 0x80133028
LoadElementFailed = -2146226135, // 0x80133029
NotificationInvalid = -2146226134, // 0x8013302A
OptionInvalid = -2146226133, // 0x8013302B
OptionNotSupported = -2146226132, // 0x8013302C
RevokeFailed = -2146226131, // 0x8013302D
RootMonikerAlreadySet = -2146226130, // 0x8013302E
RootMonikerInUse = -2146226129, // 0x8013302F
RootMonikerInvalid = -2146226128, // 0x80133030
RootMonikerNotSet = -2146226127, // 0x80133031
RootMonikerProtocolInvalid = -2146226126, // 0x80133032
RootNamespaceInvalid = -2146226125, // 0x80133033
RootNamespaceNotSet = -2146226124, // 0x80133034
SaveCompiledStateFailed = -2146226123, // 0x80133035
SaveElementFailed = -2146226122, // 0x80133036
SiteAlreadySet = -2146226121, // 0x80133037
SiteInvalid = -2146226120, // 0x80133038
SiteNotSet = -2146226119, // 0x80133039
SourceItemNotAvailable = -2146226118, // 0x8013303A
SourceMonikerNotAvailable = -2146226117, // 0x8013303B
URLInvalid = -2146226116, // 0x8013303C
BrowserNotExist = -2146226115, // 0x8013303D
DebuggeeNotStarted = -2146226114, // 0x8013303E
EngineNameInvalid = -2146226113, // 0x8013303F
EngineNotExist = -2146226112, // 0x80133040
FileFormatUnsupported = -2146226111, // 0x80133041
FileTypeUnknown = -2146226110, // 0x80133042
ItemCannotBeRenamed = -2146226109, // 0x80133043
MissingSource = -2146226108, // 0x80133044
NotInitCompleted = -2146226107, // 0x80133045
NameTooLong = -2146226106, // 0x80133046
ProcNameInUse = -2146226105, // 0x80133047
ProcNameInvalid = -2146226104, // 0x80133048
VsaServerDown = -2146226103, // 0x80133049
MissingPdb = -2146226102, // 0x8013304A
NotClientSideAndNoUrl = -2146226101, // 0x8013304B
CannotAttachToWebServer = -2146226100, // 0x8013304C
EngineNameNotSet = -2146226099, // 0x8013304D
UnknownError = -2146225921, // 0x801330FF
} // VsaErr
[System.SerializableAttribute]
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
[Guid("5f44bb1a-465a-37db-8e84-acc733bf7541")]
[Obsolete(VsaObsolete.Description)]
public class VsaException : ExternalException
{
//Standard constructors
public VsaException() {}
public VsaException(string message) : base(message) {}
public VsaException(string message, Exception innerException) : base(message, innerException) {}
//Serialization constructor
public VsaException (SerializationInfo info, StreamingContext context) : base(info, context)
{
//deserialize value
HResult = (Int32)info.GetValue("VsaException_HResult", typeof(Int32));
HelpLink = (String)info.GetValue("VsaException_HelpLink", typeof(String));
Source = (String)info.GetValue("VsaException_Source", typeof(String));
}
//serializes the object
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
//serialize value
info.AddValue("VsaException_HResult", HResult);
info.AddValue("VsaException_HelpLink", HelpLink);
info.AddValue("VsaException_Source", Source);
}
public override String ToString()
{
if ((null != this.Message) && ("" != this.Message))
return "Microsoft.Vsa.VsaException: " + System.Enum.GetName(((VsaError)HResult).GetType(), (VsaError)HResult) + " (0x" + String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0,8:X}", HResult) + "): " + Message;
else
return "Microsoft.Vsa.VsaException: " + System.Enum.GetName(((VsaError)HResult).GetType(), (VsaError)HResult) + " (0x" + String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0,8:X}", HResult) + ").";
}
public VsaException(VsaError error) : base(String.Empty, (int)error)
{
}
public VsaException(VsaError error, string message) : base(message, (int)error)
{
}
public VsaException(VsaError error, string message, Exception innerException) : base(message, innerException)
{
HResult = (int)error;
}
public new VsaError ErrorCode
{
get { return (VsaError)HResult; }
}
} // VsaException
// A custom attribute to identify this assembly as being generated by VSA
[type:System.AttributeUsageAttribute(System.AttributeTargets.All)]
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
[Guid("7f64f934-c1cc-338e-b695-f64d71e820fe")]
[Obsolete(VsaObsolete.Description)]
public class VsaModule : System.Attribute
{
public VsaModule(bool bIsVsaModule)
{
IsVsaModule = bIsVsaModule;
}
public bool IsVsaModule
{
get
{ return isVsaModule; }
set
{ isVsaModule = value; }
}
private bool isVsaModule;
} // VsaModule
} // Microsoft.Vsa
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using Avalonia.Controls;
using Xunit;
namespace Avalonia.Input.UnitTests
{
public class KeyboardNavigationTests_Tab
{
[Fact]
public void Next_Continue_Returns_Next_Control_In_Container()
{
Button current;
Button next;
var top = new StackPanel
{
Children =
{
new StackPanel
{
Children =
{
new Button { Name = "Button1" },
(current = new Button { Name = "Button2" }),
(next = new Button { Name = "Button3" }),
}
},
new StackPanel
{
Children =
{
new Button { Name = "Button4" },
new Button { Name = "Button5" },
new Button { Name = "Button6" },
}
},
}
};
var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);
Assert.Equal(next, result);
}
[Fact]
public void Next_Continue_Returns_First_Control_In_Next_Sibling_Container()
{
Button current;
Button next;
var top = new StackPanel
{
Children =
{
new StackPanel
{
Children =
{
new Button { Name = "Button1" },
new Button { Name = "Button2" },
(current = new Button { Name = "Button3" }),
}
},
new StackPanel
{
Children =
{
(next = new Button { Name = "Button4" }),
new Button { Name = "Button5" },
new Button { Name = "Button6" },
}
},
}
};
var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);
Assert.Equal(next, result);
}
[Fact]
public void Next_Skips_Unfocusable_Siblings()
{
Button current;
Button next;
var top = new StackPanel
{
Children =
{
new StackPanel
{
Children =
{
new Button { Name = "Button1" },
new Button { Name = "Button2" },
new StackPanel
{
Children =
{
(current = new Button { Name = "Button3" }),
}
},
new TextBlock { Name = "TextBlock" },
(next = new Button { Name = "Button4" }),
}
},
new Button { Name = "Button5" },
new Button { Name = "Button6" },
}
};
var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);
Assert.Equal(next, result);
}
[Fact]
public void Next_Continue_Doesnt_Enter_Panel_With_TabNavigation_None()
{
Button current;
Button next;
var top = new StackPanel
{
Children =
{
new StackPanel
{
Children =
{
(next = new Button { Name = "Button1" }),
new Button { Name = "Button2" },
(current = new Button { Name = "Button3" }),
}
},
new StackPanel
{
[KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.None,
Children =
{
new StackPanel
{
Children =
{
new Button { Name = "Button4" },
new Button { Name = "Button5" },
new Button { Name = "Button6" },
}
},
}
}
}
};
var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);
Assert.Equal(next, result);
}
[Fact]
public void Next_Continue_Returns_Next_Sibling()
{
Button current;
Button next;
var top = new StackPanel
{
Children =
{
new StackPanel
{
Children =
{
new Button { Name = "Button1" },
new Button { Name = "Button2" },
(current = new Button { Name = "Button3" }),
}
},
(next = new Button { Name = "Button4" }),
}
};
var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);
Assert.Equal(next, result);
}
[Fact]
public void Next_Continue_Returns_First_Control_In_Next_Uncle_Container()
{
Button current;
Button next;
var top = new StackPanel
{
Children =
{
new StackPanel
{
Children =
{
new StackPanel
{
Children =
{
new Button { Name = "Button1" },
new Button { Name = "Button2" },
(current = new Button { Name = "Button3" }),
}
},
},
},
new StackPanel
{
Children =
{
(next = new Button { Name = "Button4" }),
new Button { Name = "Button5" },
new Button { Name = "Button6" },
}
},
}
};
var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);
Assert.Equal(next, result);
}
[Fact]
public void Next_Continue_Returns_Child_Of_Top_Level()
{
Button next;
var top = new StackPanel
{
Children =
{
(next = new Button { Name = "Button1" }),
}
};
var result = KeyboardNavigationHandler.GetNext(top, NavigationDirection.Next);
Assert.Equal(next, result);
}
[Fact]
public void Next_Continue_Wraps()
{
Button current;
Button next;
var top = new StackPanel
{
Children =
{
new StackPanel
{
Children =
{
new StackPanel
{
Children =
{
(next = new Button { Name = "Button1" }),
new Button { Name = "Button2" },
new Button { Name = "Button3" },
}
},
},
},
new StackPanel
{
Children =
{
new Button { Name = "Button4" },
new Button { Name = "Button5" },
(current = new Button { Name = "Button6" }),
}
},
}
};
var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);
Assert.Equal(next, result);
}
[Fact]
public void Next_Cycle_Returns_Next_Control_In_Container()
{
Button current;
Button next;
var top = new StackPanel
{
Children =
{
new StackPanel
{
[KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
Children =
{
new Button { Name = "Button1" },
(current = new Button { Name = "Button2" }),
(next = new Button { Name = "Button3" }),
}
},
new StackPanel
{
Children =
{
new Button { Name = "Button4" },
new Button { Name = "Button5" },
new Button { Name = "Button6" },
}
},
}
};
var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);
Assert.Equal(next, result);
}
[Fact]
public void Next_Cycle_Wraps_To_First()
{
Button current;
Button next;
var top = new StackPanel
{
Children =
{
new StackPanel
{
[KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
Children =
{
(next = new Button { Name = "Button1" }),
new Button { Name = "Button2" },
(current = new Button { Name = "Button3" }),
}
},
new StackPanel
{
Children =
{
new Button { Name = "Button4" },
new Button { Name = "Button5" },
new Button { Name = "Button6" },
}
},
}
};
var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);
Assert.Equal(next, result);
}
[Fact]
public void Next_Contained_Returns_Next_Control_In_Container()
{
Button current;
Button next;
var top = new StackPanel
{
Children =
{
new StackPanel
{
[KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Contained,
Children =
{
new Button { Name = "Button1" },
(current = new Button { Name = "Button2" }),
(next = new Button { Name = "Button3" }),
}
},
new StackPanel
{
Children =
{
new Button { Name = "Button4" },
new Button { Name = "Button5" },
new Button { Name = "Button6" },
}
},
}
};
var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);
Assert.Equal(next, result);
}
[Fact]
public void Next_Contained_Stops_At_End()
{
Button current;
var top = new StackPanel
{
Children =
{
new StackPanel
{
[KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Contained,
Children =
{
new Button { Name = "Button1" },
new Button { Name = "Button2" },
(current = new Button { Name = "Button3" }),
}
},
new StackPanel
{
Children =
{
new Button { Name = "Button4" },
new Button { Name = "Button5" },
new Button { Name = "Button6" },
}
},
}
};
var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);
Assert.Null(result);
}
[Fact]
public void Next_Once_Moves_To_Next_Container()
{
Button current;
Button next;
var top = new StackPanel
{
Children =
{
new StackPanel
{
[KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Once,
Children =
{
new Button { Name = "Button1" },
(current = new Button { Name = "Button2" }),
new Button { Name = "Button3" },
}
},
new StackPanel
{
Children =
{
(next = new Button { Name = "Button4" }),
new Button { Name = "Button5" },
new Button { Name = "Button6" },
}
},
}
};
var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);
Assert.Equal(next, result);
}
[Fact]
public void Next_Once_Moves_To_Active_Element()
{
StackPanel container;
Button current;
Button next;
var top = new StackPanel
{
Children =
{
(container = new StackPanel
{
[KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Once,
Children =
{
new Button { Name = "Button1" },
(next = new Button { Name = "Button2" }),
new Button { Name = "Button3" },
}
}),
new StackPanel
{
Children =
{
new Button { Name = "Button4" },
new Button { Name = "Button5" },
(current = new Button { Name = "Button6" }),
}
},
}
};
KeyboardNavigation.SetTabOnceActiveElement(container, next);
var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);
Assert.Equal(next, result);
}
[Fact]
public void Next_None_Moves_To_Next_Container()
{
Button current;
Button next;
var top = new StackPanel
{
Children =
{
new StackPanel
{
[KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.None,
Children =
{
new Button { Name = "Button1" },
(current = new Button { Name = "Button2" }),
new Button { Name = "Button3" },
}
},
new StackPanel
{
Children =
{
(next = new Button { Name = "Button4" }),
new Button { Name = "Button5" },
new Button { Name = "Button6" },
}
},
}
};
var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);
Assert.Equal(next, result);
}
[Fact]
public void Next_None_Skips_Container()
{
StackPanel container;
Button current;
Button next;
var top = new StackPanel
{
Children =
{
(container = new StackPanel
{
[KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.None,
Children =
{
new Button { Name = "Button1" },
new Button { Name = "Button2" },
new Button { Name = "Button3" },
}
}),
new StackPanel
{
Children =
{
(next = new Button { Name = "Button4" }),
new Button { Name = "Button5" },
(current = new Button { Name = "Button6" }),
}
},
}
};
KeyboardNavigation.SetTabOnceActiveElement(container, next);
var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);
Assert.Equal(next, result);
}
[Fact]
public void Previous_Continue_Returns_Previous_Control_In_Container()
{
Button current;
Button next;
var top = new StackPanel
{
Children =
{
new StackPanel
{
Children =
{
new Button { Name = "Button1" },
(next = new Button { Name = "Button2" }),
(current = new Button { Name = "Button3" }),
}
},
new StackPanel
{
Children =
{
new Button { Name = "Button4" },
new Button { Name = "Button5" },
new Button { Name = "Button6" },
}
},
}
};
var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Previous);
Assert.Equal(next, result);
}
[Fact]
public void Previous_Continue_Returns_Last_Control_In_Previous_Sibling_Container()
{
Button current;
Button next;
var top = new StackPanel
{
Children =
{
new StackPanel
{
Children =
{
new Button { Name = "Button1" },
new Button { Name = "Button2" },
(next = new Button { Name = "Button3" }),
}
},
new StackPanel
{
Children =
{
(current = new Button { Name = "Button4" }),
new Button { Name = "Button5" },
new Button { Name = "Button6" },
}
},
}
};
var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Previous);
Assert.Equal(next, result);
}
[Fact]
public void Previous_Continue_Returns_Last_Child_Of_Sibling()
{
Button current;
Button next;
var top = new StackPanel
{
Children =
{
new StackPanel
{
Children =
{
new Button { Name = "Button1" },
new Button { Name = "Button2" },
(next = new Button { Name = "Button3" }),
}
},
(current = new Button { Name = "Button4" }),
}
};
var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Previous);
Assert.Equal(next, result);
}
[Fact]
public void Previous_Continue_Returns_Last_Control_In_Previous_Nephew_Container()
{
Button current;
Button next;
var top = new StackPanel
{
Children =
{
new StackPanel
{
Children =
{
new StackPanel
{
Children =
{
new Button { Name = "Button1" },
new Button { Name = "Button2" },
(next = new Button { Name = "Button3" }),
}
},
},
},
new StackPanel
{
Children =
{
(current = new Button { Name = "Button4" }),
new Button { Name = "Button5" },
new Button { Name = "Button6" },
}
},
}
};
var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Previous);
Assert.Equal(next, result);
}
[Fact]
public void Previous_Continue_Wraps()
{
Button current;
Button next;
var top = new StackPanel
{
Children =
{
new StackPanel
{
Children =
{
new StackPanel
{
Children =
{
(current = new Button { Name = "Button1" }),
new Button { Name = "Button2" },
new Button { Name = "Button3" },
}
},
},
},
new StackPanel
{
Children =
{
new Button { Name = "Button4" },
new Button { Name = "Button5" },
(next = new Button { Name = "Button6" }),
}
},
}
};
var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Previous);
Assert.Equal(next, result);
}
[Fact]
public void Previous_Continue_Returns_Parent()
{
Button current;
var top = new Decorator
{
Focusable = true,
Child = current = new Button
{
Name = "Button",
}
};
var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Previous);
Assert.Equal(top, result);
}
[Fact]
public void Previous_Cycle_Returns_Previous_Control_In_Container()
{
Button current;
Button next;
var top = new StackPanel
{
Children =
{
new StackPanel
{
[KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
Children =
{
(next = new Button { Name = "Button1" }),
(current = new Button { Name = "Button2" }),
new Button { Name = "Button3" },
}
},
new StackPanel
{
Children =
{
new Button { Name = "Button4" },
new Button { Name = "Button5" },
new Button { Name = "Button6" },
}
},
}
};
var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Previous);
Assert.Equal(next, result);
}
[Fact]
public void Previous_Cycle_Wraps_To_Last()
{
Button current;
Button next;
var top = new StackPanel
{
Children =
{
new StackPanel
{
[KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
Children =
{
(current = new Button { Name = "Button1" }),
new Button { Name = "Button2" },
(next = new Button { Name = "Button3" }),
}
},
new StackPanel
{
Children =
{
new Button { Name = "Button4" },
new Button { Name = "Button5" },
new Button { Name = "Button6" },
}
},
}
};
var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Previous);
Assert.Equal(next, result);
}
[Fact]
public void Previous_Contained_Returns_Previous_Control_In_Container()
{
Button current;
Button next;
var top = new StackPanel
{
Children =
{
new StackPanel
{
[KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Contained,
Children =
{
(next = new Button { Name = "Button1" }),
(current = new Button { Name = "Button2" }),
new Button { Name = "Button3" },
}
},
new StackPanel
{
Children =
{
new Button { Name = "Button4" },
new Button { Name = "Button5" },
new Button { Name = "Button6" },
}
},
}
};
var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Previous);
Assert.Equal(next, result);
}
[Fact]
public void Previous_Contained_Stops_At_Beginning()
{
Button current;
var top = new StackPanel
{
Children =
{
new StackPanel
{
[KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Contained,
Children =
{
(current = new Button { Name = "Button1" }),
new Button { Name = "Button2" },
new Button { Name = "Button3" },
}
},
new StackPanel
{
Children =
{
new Button { Name = "Button4" },
new Button { Name = "Button5" },
new Button { Name = "Button6" },
}
},
}
};
var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Previous);
Assert.Null(result);
}
[Fact]
public void Previous_Once_Moves_To_Previous_Container()
{
Button current;
Button next;
var top = new StackPanel
{
Children =
{
new StackPanel
{
Children =
{
new Button { Name = "Button1" },
new Button { Name = "Button2" },
(next = new Button { Name = "Button3" }),
}
},
new StackPanel
{
[KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Once,
Children =
{
new Button { Name = "Button4" },
(current = new Button { Name = "Button5" }),
new Button { Name = "Button6" },
}
},
}
};
var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Previous);
Assert.Equal(next, result);
}
[Fact]
public void Previous_Once_Moves_To_Active_Element()
{
StackPanel container;
Button current;
Button next;
var top = new StackPanel
{
Children =
{
(container = new StackPanel
{
[KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Once,
Children =
{
new Button { Name = "Button1" },
(next = new Button { Name = "Button2" }),
new Button { Name = "Button3" },
}
}),
new StackPanel
{
Children =
{
(current = new Button { Name = "Button4" }),
new Button { Name = "Button5" },
new Button { Name = "Button6" },
}
},
}
};
KeyboardNavigation.SetTabOnceActiveElement(container, next);
var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Previous);
Assert.Equal(next, result);
}
[Fact]
public void Previous_Once_Moves_To_First_Element()
{
Button current;
Button next;
var top = new StackPanel
{
Children =
{
new StackPanel
{
[KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Once,
Children =
{
(next = new Button { Name = "Button1" }),
new Button { Name = "Button2" },
new Button { Name = "Button3" },
}
},
new StackPanel
{
Children =
{
(current = new Button { Name = "Button4" }),
new Button { Name = "Button5" },
new Button { Name = "Button6" },
}
},
}
};
var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Previous);
Assert.Equal(next, result);
}
[Fact]
public void Previous_Contained_Doesnt_Select_Child_Control()
{
Decorator current;
var top = new StackPanel
{
[KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Contained,
Children =
{
(current = new Decorator
{
Focusable = true,
Child = new Button(),
})
}
};
var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Previous);
Assert.Null(result);
}
}
}
| |
#region namespace
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Security;
using System.Configuration;
using umbraco.BusinessLogic;
using System.Security.Cryptography;
using System.Web.Util;
using System.Collections.Specialized;
using System.Configuration.Provider;
using umbraco.cms.businesslogic;
using umbraco.cms.businesslogic.member;
using System.Security;
using System.Security.Permissions;
using System.Runtime.CompilerServices;
#endregion
namespace umbraco.providers.members
{
/// <summary>
/// Custom Membership Provider for Umbraco Members (User authentication for Frontend applications NOT umbraco CMS)
/// </summary>
public class UmbracoMembershipProvider : MembershipProvider
{
#region Fields
private string m_ApplicationName;
private bool m_EnablePasswordReset;
private bool m_EnablePasswordRetrieval;
private int m_MaxInvalidPasswordAttempts;
private int m_MinRequiredNonAlphanumericCharacters;
private int m_MinRequiredPasswordLength;
private int m_PasswordAttemptWindow;
private MembershipPasswordFormat m_PasswordFormat;
private string m_PasswordStrengthRegularExpression;
private bool m_RequiresQuestionAndAnswer;
private bool m_RequiresUniqueEmail;
private string m_DefaultMemberTypeAlias;
private string m_LockPropertyTypeAlias;
private string m_FailedPasswordAttemptsPropertyTypeAlias;
private string m_ApprovedPropertyTypeAlias;
private string m_CommentPropertyTypeAlias;
private string m_LastLoginPropertyTypeAlias;
private string m_PasswordRetrievalQuestionPropertyTypeAlias;
private string m_PasswordRetrievalAnswerPropertyTypeAlias;
private string m_providerName = Member.UmbracoMemberProviderName;
#endregion
#region Properties
/// <summary>
/// The name of the application using the custom membership provider.
/// </summary>
/// <value></value>
/// <returns>The name of the application using the custom membership provider.</returns>
public override string ApplicationName
{
get
{
return m_ApplicationName;
}
set
{
if (string.IsNullOrEmpty(value))
throw new ProviderException("ApplicationName cannot be empty.");
if (value.Length > 0x100)
throw new ProviderException("Provider application name too long.");
m_ApplicationName = value;
}
}
/// <summary>
/// Indicates whether the membership provider is configured to allow users to reset their passwords.
/// </summary>
/// <value></value>
/// <returns>true if the membership provider supports password reset; otherwise, false. The default is true.</returns>
public override bool EnablePasswordReset
{
get { return m_EnablePasswordReset; }
}
/// <summary>
/// Indicates whether the membership provider is configured to allow users to retrieve their passwords.
/// </summary>
/// <value></value>
/// <returns>true if the membership provider is configured to support password retrieval; otherwise, false. The default is false.</returns>
public override bool EnablePasswordRetrieval
{
get { return m_EnablePasswordRetrieval; }
}
/// <summary>
/// Gets the number of invalid password or password-answer attempts allowed before the membership user is locked out.
/// </summary>
/// <value></value>
/// <returns>The number of invalid password or password-answer attempts allowed before the membership user is locked out.</returns>
public override int MaxInvalidPasswordAttempts
{
get { return m_MaxInvalidPasswordAttempts; }
}
/// <summary>
/// Gets the minimum number of special characters that must be present in a valid password.
/// </summary>
/// <value></value>
/// <returns>The minimum number of special characters that must be present in a valid password.</returns>
public override int MinRequiredNonAlphanumericCharacters
{
get { return m_MinRequiredNonAlphanumericCharacters; }
}
/// <summary>
/// Gets the minimum length required for a password.
/// </summary>
/// <value></value>
/// <returns>The minimum length required for a password. </returns>
public override int MinRequiredPasswordLength
{
get { return m_MinRequiredPasswordLength; }
}
/// <summary>
/// Gets the number of minutes in which a maximum number of invalid password or password-answer attempts are allowed before the membership user is locked out.
/// </summary>
/// <value></value>
/// <returns>The number of minutes in which a maximum number of invalid password or password-answer attempts are allowed before the membership user is locked out.</returns>
public override int PasswordAttemptWindow
{
get { return m_PasswordAttemptWindow; }
}
/// <summary>
/// Gets a value indicating the format for storing passwords in the membership data store.
/// </summary>
/// <value></value>
/// <returns>One of the <see cref="T:System.Web.Security.MembershipPasswordFormat"></see> values indicating the format for storing passwords in the data store.</returns>
public override MembershipPasswordFormat PasswordFormat
{
get { return m_PasswordFormat; }
}
/// <summary>
/// Gets the regular expression used to evaluate a password.
/// </summary>
/// <value></value>
/// <returns>A regular expression used to evaluate a password.</returns>
public override string PasswordStrengthRegularExpression
{
get { return m_PasswordStrengthRegularExpression; }
}
/// <summary>
/// Gets a value indicating whether the membership provider is configured to require the user to answer a password question for password reset and retrieval.
/// </summary>
/// <value></value>
/// <returns>true if a password answer is required for password reset and retrieval; otherwise, false. The default is true.</returns>
public override bool RequiresQuestionAndAnswer
{
get { return m_RequiresQuestionAndAnswer; }
}
/// <summary>
/// Gets a value indicating whether the membership provider is configured to require a unique e-mail address for each user name.
/// </summary>
/// <value></value>
/// <returns>true if the membership provider requires a unique e-mail address; otherwise, false. The default is true.</returns>
public override bool RequiresUniqueEmail
{
get { return m_RequiresUniqueEmail; }
}
#endregion
#region Initialization Method
/// <summary>
/// Initializes the provider.
/// </summary>
/// <param name="name">The friendly name of the provider.</param>
/// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param>
/// <exception cref="T:System.ArgumentNullException">The name of the provider is null.</exception>
/// <exception cref="T:System.InvalidOperationException">An attempt is made to call
/// <see cref="M:System.Configuration.Provider.ProviderBase.Initialize(System.String,System.Collections.Specialized.NameValueCollection)"></see> on a provider after the provider
/// has already been initialized.</exception>
/// <exception cref="T:System.ArgumentException">The name of the provider has a length of zero.</exception>
public override void Initialize(string name, NameValueCollection config)
{
// Intialize values from web.config
if (config == null) throw new ArgumentNullException("config");
if (string.IsNullOrEmpty(name)) name = "UmbracoMembershipProvider";
// Initialize base provider class
base.Initialize(name, config);
m_providerName = name;
this.m_EnablePasswordRetrieval = SecUtility.GetBooleanValue(config, "enablePasswordRetrieval", false);
this.m_EnablePasswordReset = SecUtility.GetBooleanValue(config, "enablePasswordReset", false);
this.m_RequiresQuestionAndAnswer = SecUtility.GetBooleanValue(config, "requiresQuestionAndAnswer", false);
this.m_RequiresUniqueEmail = SecUtility.GetBooleanValue(config, "requiresUniqueEmail", true);
this.m_MaxInvalidPasswordAttempts = SecUtility.GetIntValue(config, "maxInvalidPasswordAttempts", 5, false, 0);
this.m_PasswordAttemptWindow = SecUtility.GetIntValue(config, "passwordAttemptWindow", 10, false, 0);
this.m_MinRequiredPasswordLength = SecUtility.GetIntValue(config, "minRequiredPasswordLength", 7, true, 0x80);
this.m_MinRequiredNonAlphanumericCharacters = SecUtility.GetIntValue(config, "minRequiredNonalphanumericCharacters", 1, true, 0x80);
this.m_PasswordStrengthRegularExpression = config["passwordStrengthRegularExpression"];
this.m_ApplicationName = config["applicationName"];
if (string.IsNullOrEmpty(this.m_ApplicationName))
this.m_ApplicationName = SecUtility.GetDefaultAppName();
// make sure password format is clear by default.
string str = config["passwordFormat"];
if (str == null) str = "Clear";
switch (str.ToLower())
{
case "clear":
this.m_PasswordFormat = MembershipPasswordFormat.Clear;
break;
case "encrypted":
this.m_PasswordFormat = MembershipPasswordFormat.Encrypted;
break;
case "hashed":
this.m_PasswordFormat = MembershipPasswordFormat.Hashed;
break;
default:
throw new ProviderException("Provider bad password format");
}
if ((this.PasswordFormat == MembershipPasswordFormat.Hashed) && this.EnablePasswordRetrieval)
throw new ProviderException("Provider can not retrieve hashed password");
// test for membertype (if not specified, choose the first member type available)
if (config["defaultMemberTypeAlias"] != null)
m_DefaultMemberTypeAlias = config["defaultMemberTypeAlias"];
else if (MemberType.GetAll.Length == 1)
m_DefaultMemberTypeAlias = MemberType.GetAll[0].Alias;
else
throw new ProviderException("No default MemberType alias is specified in the web.config string. Please add a 'defaultMemberTypeAlias' to the add element in the provider declaration in web.config");
// test for approve status
if (config["umbracoApprovePropertyTypeAlias"] != null)
{
m_ApprovedPropertyTypeAlias = config["umbracoApprovePropertyTypeAlias"];
}
// test for lock attempts
if (config["umbracoLockPropertyTypeAlias"] != null)
{
m_LockPropertyTypeAlias = config["umbracoLockPropertyTypeAlias"];
}
if (config["umbracoFailedPasswordAttemptsPropertyTypeAlias"] != null)
{
m_FailedPasswordAttemptsPropertyTypeAlias = config["umbracoFailedPasswordAttemptsPropertyTypeAlias"];
}
// comment property
if (config["umbracoCommentPropertyTypeAlias"] != null)
{
m_CommentPropertyTypeAlias = config["umbracoCommentPropertyTypeAlias"];
}
// last login date
if (config["umbracoLastLoginPropertyTypeAlias"] != null)
{
m_LastLoginPropertyTypeAlias = config["umbracoLastLoginPropertyTypeAlias"];
}
// password retrieval
if (config["umbracoPasswordRetrievalQuestionPropertyTypeAlias"] != null)
{
m_PasswordRetrievalQuestionPropertyTypeAlias = config["umbracoPasswordRetrievalQuestionPropertyTypeAlias"];
}
if (config["umbracoPasswordRetrievalAnswerPropertyTypeAlias"] != null)
{
m_PasswordRetrievalAnswerPropertyTypeAlias = config["umbracoPasswordRetrievalAnswerPropertyTypeAlias"];
}
}
#endregion
#region Methods
/// <summary>
/// Processes a request to update the password for a membership user.
/// </summary>
/// <param name="username">The user to update the password for.</param>
/// <param name="oldPassword">The current password for the specified user.</param>
/// <param name="newPassword">The new password for the specified user.</param>
/// <returns>
/// true if the password was updated successfully; otherwise, false.
/// </returns>
public override bool ChangePassword(string username, string oldPassword, string newPassword)
{
// in order to support updating passwords from the umbraco core, we can't validate the old password
Member m = Member.GetMemberFromLoginNameAndPassword(username, oldPassword);
if (m == null) return false;
ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, newPassword, false);
OnValidatingPassword(args);
if (args.Cancel)
{
if (args.FailureInformation != null)
throw args.FailureInformation;
else
throw new MembershipPasswordException("Change password canceled due to new password validation failure.");
}
string encodedPassword = EncodePassword(newPassword);
m.ChangePassword(encodedPassword);
return (m.Password == encodedPassword) ? true : false;
}
/// <summary>
/// Processes a request to update the password question and answer for a membership user.
/// </summary>
/// <param name="username">The user to change the password question and answer for.</param>
/// <param name="password">The password for the specified user.</param>
/// <param name="newPasswordQuestion">The new password question for the specified user.</param>
/// <param name="newPasswordAnswer">The new password answer for the specified user.</param>
/// <returns>
/// true if the password question and answer are updated successfully; otherwise, false.
/// </returns>
public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
{
if (!String.IsNullOrEmpty(m_PasswordRetrievalQuestionPropertyTypeAlias) && !String.IsNullOrEmpty(m_PasswordRetrievalAnswerPropertyTypeAlias))
{
if (ValidateUser(username, password))
{
Member m = Member.GetMemberFromLoginName(username);
if (m != null)
{
UpdateMemberProperty(m, m_PasswordRetrievalQuestionPropertyTypeAlias, newPasswordQuestion);
UpdateMemberProperty(m, m_PasswordRetrievalAnswerPropertyTypeAlias, newPasswordAnswer);
m.Save();
return true;
}
else
{
throw new MembershipPasswordException("The supplied user is not found!");
}
}
else {
throw new MembershipPasswordException("Invalid user/password combo");
}
}
else
{
throw new NotSupportedException("Updating the password Question and Answer is not valid if the properties aren't set in the config file");
}
}
/// <summary>
/// Adds a new membership user to the data source.
/// </summary>
/// <param name="username">The user name for the new user.</param>
/// <param name="password">The password for the new user.</param>
/// <param name="email">The e-mail address for the new user.</param>
/// <param name="passwordQuestion">The password question for the new user.</param>
/// <param name="passwordAnswer">The password answer for the new user</param>
/// <param name="isApproved">Whether or not the new user is approved to be validated.</param>
/// <param name="providerUserKey">The unique identifier from the membership data source for the user.</param>
/// <param name="status">A <see cref="T:System.Web.Security.MembershipCreateStatus"></see> enumeration value indicating whether the user was created successfully.</param>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUser"></see> object populated with the information for the newly created user.
/// </returns>
public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion,
string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
{
if (Member.GetMemberFromLoginName(username) != null)
status = MembershipCreateStatus.DuplicateUserName;
else if (Member.GetMemberFromEmail(email) != null && RequiresUniqueEmail)
status = MembershipCreateStatus.DuplicateEmail;
else
{
Member m = Member.MakeNew(username, email, MemberType.GetByAlias(m_DefaultMemberTypeAlias), User.GetUser(0));
m.Password = password;
MembershipUser mUser =
ConvertToMembershipUser(m);
// custom fields
if (!String.IsNullOrEmpty(m_PasswordRetrievalQuestionPropertyTypeAlias))
UpdateMemberProperty(m, m_PasswordRetrievalQuestionPropertyTypeAlias, passwordQuestion);
if (!String.IsNullOrEmpty(m_PasswordRetrievalAnswerPropertyTypeAlias))
UpdateMemberProperty(m, m_PasswordRetrievalAnswerPropertyTypeAlias, passwordAnswer);
if (!String.IsNullOrEmpty(m_ApprovedPropertyTypeAlias))
UpdateMemberProperty(m, m_ApprovedPropertyTypeAlias, isApproved);
if (!String.IsNullOrEmpty(m_LastLoginPropertyTypeAlias)) {
mUser.LastActivityDate = DateTime.Now;
UpdateMemberProperty(m, m_LastLoginPropertyTypeAlias, mUser.LastActivityDate);
}
// save
m.Save();
status = MembershipCreateStatus.Success;
return mUser;
}
return null;
}
/// <summary>
/// Removes a user from the membership data source.
/// </summary>
/// <param name="username">The name of the user to delete.</param>
/// <param name="deleteAllRelatedData">true to delete data related to the user from the database; false to leave data related to the user in the database.</param>
/// <returns>
/// true if the user was successfully deleted; otherwise, false.
/// </returns>
public override bool DeleteUser(string username, bool deleteAllRelatedData)
{
Member m = Member.GetMemberFromLoginName(username);
if (m == null) return false;
else
{
m.delete();
return true;
}
}
/// <summary>
/// Gets a collection of membership users where the e-mail address contains the specified e-mail address to match.
/// </summary>
/// <param name="emailToMatch">The e-mail address to search for.</param>
/// <param name="pageIndex">The index of the page of results to return. pageIndex is zero-based.</param>
/// <param name="pageSize">The size of the page of results to return.</param>
/// <param name="totalRecords">The total number of matched users.</param>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUserCollection"></see> collection that contains a page of pageSize<see cref="T:System.Web.Security.MembershipUser"></see> objects beginning at the page specified by pageIndex.
/// </returns>
public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
{
throw new Exception("The method or operation is not implemented.");
}
/// <summary>
/// Gets a collection of membership users where the user name contains the specified user name to match.
/// </summary>
/// <param name="usernameToMatch">The user name to search for.</param>
/// <param name="pageIndex">The index of the page of results to return. pageIndex is zero-based.</param>
/// <param name="pageSize">The size of the page of results to return.</param>
/// <param name="totalRecords">The total number of matched users.</param>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUserCollection"></see> collection that contains a page of pageSize<see cref="T:System.Web.Security.MembershipUser"></see> objects beginning at the page specified by pageIndex.
/// </returns>
public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
{
int counter = 0;
int startIndex = pageSize * pageIndex;
int endIndex = startIndex + pageSize - 1;
MembershipUserCollection membersList = new MembershipUserCollection();
Member[] memberArray = Member.GetMemberByName(usernameToMatch, false);
totalRecords = memberArray.Length;
foreach (Member m in memberArray)
{
if (counter >= startIndex)
membersList.Add(ConvertToMembershipUser(m));
if (counter >= endIndex) break;
counter++;
}
return membersList;
}
/// <summary>
/// Gets a collection of all the users in the data source in pages of data.
/// </summary>
/// <param name="pageIndex">The index of the page of results to return. pageIndex is zero-based.</param>
/// <param name="pageSize">The size of the page of results to return.</param>
/// <param name="totalRecords">The total number of matched users.</param>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUserCollection"></see> collection that contains a page of pageSize<see cref="T:System.Web.Security.MembershipUser"></see> objects beginning at the page specified by pageIndex.
/// </returns>
public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
{
int counter = 0;
int startIndex = pageSize * pageIndex;
int endIndex = startIndex + pageSize - 1;
MembershipUserCollection membersList = new MembershipUserCollection();
Member[] memberArray = Member.GetAll;
totalRecords = memberArray.Length;
foreach (Member m in memberArray)
{
if (counter >= startIndex)
membersList.Add(ConvertToMembershipUser(m));
if (counter >= endIndex) break;
counter++;
}
return membersList;
}
/// <summary>
/// Gets the number of users currently accessing the application.
/// </summary>
/// <returns>
/// The number of users currently accessing the application.
/// </returns>
public override int GetNumberOfUsersOnline()
{
return Member.CachedMembers().Count;
}
/// <summary>
/// Gets the password for the specified user name from the data source.
/// </summary>
/// <param name="username">The user to retrieve the password for.</param>
/// <param name="answer">The password answer for the user.</param>
/// <returns>
/// The password for the specified user name.
/// </returns>
public override string GetPassword(string username, string answer)
{
if (!EnablePasswordRetrieval)
throw new ProviderException("Password Retrieval Not Enabled.");
if (PasswordFormat == MembershipPasswordFormat.Hashed)
throw new ProviderException("Cannot retrieve Hashed passwords.");
Member m = Member.GetMemberFromLoginName(username);
if (m != null)
{
if (RequiresQuestionAndAnswer)
{
// check if password answer property alias is set
if (!String.IsNullOrEmpty(m_PasswordRetrievalAnswerPropertyTypeAlias))
{
// check if user is locked out
if (!String.IsNullOrEmpty(m_LockPropertyTypeAlias))
{
bool isLockedOut = false;
bool.TryParse(GetMemberProperty(m, m_LockPropertyTypeAlias, true), out isLockedOut);
if (isLockedOut)
{
throw new MembershipPasswordException("The supplied user is locked out");
}
}
// match password answer
if (GetMemberProperty(m, m_PasswordRetrievalAnswerPropertyTypeAlias, false) != answer)
{
throw new MembershipPasswordException("Incorrect password answer");
}
}
else
{
throw new ProviderException("Password retrieval answer property alias is not set! To automatically support password question/answers you'll need to add references to the membertype properties in the 'Member' element in web.config by adding their aliases to the 'umbracoPasswordRetrievalQuestionPropertyTypeAlias' and 'umbracoPasswordRetrievalAnswerPropertyTypeAlias' attributes");
}
}
}
if (m == null)
{
throw new MembershipPasswordException("The supplied user is not found");
}
else
{
return m.Password;
}
}
/// <summary>
/// Gets information from the data source for a user. Provides an option to update the last-activity date/time stamp for the user.
/// </summary>
/// <param name="username">The name of the user to get information for.</param>
/// <param name="userIsOnline">true to update the last-activity date/time stamp for the user; false to return user information without updating the last-activity date/time stamp for the user.</param>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUser"></see> object populated with the specified user's information from the data source.
/// </returns>
public override MembershipUser GetUser(string username, bool userIsOnline)
{
if (String.IsNullOrEmpty(username))
return null;
Member m = Member.GetMemberFromLoginName(username);
if (m == null) return null;
else return ConvertToMembershipUser(m);
}
/// <summary>
/// Gets information from the data source for a user based on the unique identifier for the membership user. Provides an option to update the last-activity date/time stamp for the user.
/// </summary>
/// <param name="providerUserKey">The unique identifier for the membership user to get information for.</param>
/// <param name="userIsOnline">true to update the last-activity date/time stamp for the user; false to return user information without updating the last-activity date/time stamp for the user.</param>
/// <returns>
/// A <see cref="T:System.Web.Security.MembershipUser"></see> object populated with the specified user's information from the data source.
/// </returns>
public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
{
if (String.IsNullOrEmpty(providerUserKey.ToString()))
return null;
Member m = new Member(Convert.ToInt32(providerUserKey));
if (m == null) return null;
else return ConvertToMembershipUser(m);
}
/// <summary>
/// Gets the user name associated with the specified e-mail address.
/// </summary>
/// <param name="email">The e-mail address to search for.</param>
/// <returns>
/// The user name associated with the specified e-mail address. If no match is found, return null.
/// </returns>
public override string GetUserNameByEmail(string email)
{
Member m = Member.GetMemberFromEmail(email);
if (m == null) return null;
else return m.LoginName;
}
/// <summary>
/// Resets a user's password to a new, automatically generated password.
/// </summary>
/// <param name="username">The user to reset the password for.</param>
/// <param name="answer">The password answer for the specified user (not used with Umbraco).</param>
/// <returns>The new password for the specified user.</returns>
public override string ResetPassword(string username, string answer)
{
if (!EnablePasswordReset)
{
throw new NotSupportedException("Password reset is not supported");
}
Member m = Member.GetMemberFromLoginName(username);
if (m == null)
throw new MembershipPasswordException("The supplied user is not found");
else
{
if (RequiresQuestionAndAnswer)
{
// check if password answer property alias is set
if (!String.IsNullOrEmpty(m_PasswordRetrievalAnswerPropertyTypeAlias))
{
// check if user is locked out
if (!String.IsNullOrEmpty(m_LockPropertyTypeAlias))
{
bool isLockedOut = false;
bool.TryParse(GetMemberProperty(m, m_LockPropertyTypeAlias, true), out isLockedOut);
if (isLockedOut)
{
throw new MembershipPasswordException("The supplied user is locked out");
}
}
// match password answer
if (GetMemberProperty(m, m_PasswordRetrievalAnswerPropertyTypeAlias, false) != answer)
{
throw new MembershipPasswordException("Incorrect password answer");
}
}
else
{
throw new ProviderException("Password retrieval answer property alias is not set! To automatically support password question/answers you'll need to add references to the membertype properties in the 'Member' element in web.config by adding their aliases to the 'umbracoPasswordRetrievalQuestionPropertyTypeAlias' and 'umbracoPasswordRetrievalAnswerPropertyTypeAlias' attributes");
}
}
string newPassword = Membership.GeneratePassword(MinRequiredPasswordLength, MinRequiredNonAlphanumericCharacters);
m.Password = newPassword;
return newPassword;
}
}
/// <summary>
/// Clears a lock so that the membership user can be validated.
/// </summary>
/// <param name="userName">The membership user to clear the lock status for.</param>
/// <returns>
/// true if the membership user was successfully unlocked; otherwise, false.
/// </returns>
public override bool UnlockUser(string userName)
{
if (!String.IsNullOrEmpty(m_LockPropertyTypeAlias))
{
Member m = Member.GetMemberFromLoginName(userName);
if (m != null)
{
UpdateMemberProperty(m, m_LockPropertyTypeAlias, false);
return true;
}
else
{
throw new Exception(String.Format("No member with the username '{0}' found", userName));
}
}
else
{
throw new ProviderException("To enable lock/unlocking, you need to add a 'bool' property on your membertype and add the alias of the property in the 'umbracoLockPropertyTypeAlias' attribute of the membership element in the web.config.");
}
}
/// <summary>
/// Updates e-mail and potentially approved status, lock status and comment on a user.
/// Note: To automatically support lock, approve and comments you'll need to add references to the membertype properties in the
/// 'Member' element in web.config by adding their aliases to the 'umbracoApprovePropertyTypeAlias', 'umbracoLockPropertyTypeAlias' and 'umbracoCommentPropertyTypeAlias' attributes
/// </summary>
/// <param name="user">A <see cref="T:System.Web.Security.MembershipUser"></see> object that represents the user to update and the updated information for the user.</param>
public override void UpdateUser(MembershipUser user)
{
Member m = Member.GetMemberFromLoginName(user.UserName);
m.Email = user.Email;
// if supported, update approve status
UpdateMemberProperty(m, m_ApprovedPropertyTypeAlias, user.IsApproved);
// if supported, update lock status
UpdateMemberProperty(m, m_LockPropertyTypeAlias, user.IsLockedOut);
// if supported, update comment
UpdateMemberProperty(m, m_CommentPropertyTypeAlias, user.Comment);
m.Save();
}
private static void UpdateMemberProperty(Member m, string propertyAlias, object propertyValue)
{
if (!String.IsNullOrEmpty(propertyAlias))
{
if (m.getProperty(propertyAlias) != null)
{
m.getProperty(propertyAlias).Value =
propertyValue;
}
}
}
private static string GetMemberProperty(Member m, string propertyAlias, bool isBool)
{
if (!String.IsNullOrEmpty(propertyAlias))
{
if (m.getProperty(propertyAlias) != null &&
m.getProperty(propertyAlias).Value != null)
{
if (isBool)
{
// Umbraco stored true as 1, which means it can be bool.tryParse'd
return m.getProperty(propertyAlias).Value.ToString().Replace("1", "true").Replace("0", "false");
}
else
return m.getProperty(propertyAlias).Value.ToString();
}
}
return null;
}
/// <summary>
/// Verifies that the specified user name and password exist in the data source.
/// </summary>
/// <param name="username">The name of the user to validate.</param>
/// <param name="password">The password for the specified user.</param>
/// <returns>
/// true if the specified username and password are valid; otherwise, false.
/// </returns>
public override bool ValidateUser(string username, string password)
{
Member m = Member.GetMemberFromLoginAndEncodedPassword(username, EncodePassword(password));
if (m != null)
{
// check for lock status. If locked, then set the member property to null
if (!String.IsNullOrEmpty(m_LockPropertyTypeAlias))
{
string lockedStatus = GetMemberProperty(m, m_LockPropertyTypeAlias, true);
if (!String.IsNullOrEmpty(lockedStatus))
{
bool isLocked = false;
if (bool.TryParse(lockedStatus, out isLocked))
{
if (isLocked)
{
m = null;
}
}
}
}
// check for approve status. If not approved, then set the member property to null
if (!CheckApproveStatus(m)) {
m = null;
}
// maybe update login date
if (m != null && !String.IsNullOrEmpty(m_LastLoginPropertyTypeAlias))
{
UpdateMemberProperty(m, m_LastLoginPropertyTypeAlias, DateTime.Now);
}
// maybe reset password attempts
if (m != null && !String.IsNullOrEmpty(m_FailedPasswordAttemptsPropertyTypeAlias))
{
UpdateMemberProperty(m, m_FailedPasswordAttemptsPropertyTypeAlias, 0);
}
// persist data
if (m != null)
m.Save();
}
else if (!String.IsNullOrEmpty(m_LockPropertyTypeAlias)
&& !String.IsNullOrEmpty(m_FailedPasswordAttemptsPropertyTypeAlias))
{
Member updateMemberDataObject = Member.GetMemberFromLoginName(username);
// update fail rate if it's approved
if (updateMemberDataObject != null && CheckApproveStatus(updateMemberDataObject))
{
int failedAttempts = 0;
int.TryParse(GetMemberProperty(updateMemberDataObject, m_FailedPasswordAttemptsPropertyTypeAlias, false), out failedAttempts);
failedAttempts = failedAttempts+1;
UpdateMemberProperty(updateMemberDataObject, m_FailedPasswordAttemptsPropertyTypeAlias, failedAttempts);
// lock user?
if (failedAttempts >= MaxInvalidPasswordAttempts)
{
UpdateMemberProperty(updateMemberDataObject, m_LockPropertyTypeAlias, true);
}
updateMemberDataObject.Save();
}
}
return (m != null);
}
private bool CheckApproveStatus(Member m)
{
bool isApproved = false;
if (!String.IsNullOrEmpty(m_ApprovedPropertyTypeAlias))
{
if (m != null)
{
string approveStatus = GetMemberProperty(m, m_ApprovedPropertyTypeAlias, true);
if (!String.IsNullOrEmpty(approveStatus))
{
bool.TryParse(approveStatus, out isApproved);
}
}
}
else {
// if we don't use approve statuses
isApproved = true;
}
return isApproved;
}
#endregion
#region Helper Methods
/// <summary>
/// Checks the password.
/// </summary>
/// <param name="password">The password.</param>
/// <param name="dbPassword">The dbPassword.</param>
/// <returns></returns>
internal bool CheckPassword(string password, string dbPassword)
{
string pass1 = password;
string pass2 = dbPassword;
switch (PasswordFormat)
{
case MembershipPasswordFormat.Encrypted:
pass2 = UnEncodePassword(dbPassword);
break;
case MembershipPasswordFormat.Hashed:
pass1 = EncodePassword(password);
break;
default:
break;
}
return (pass1 == pass2) ? true : false;
}
/// <summary>
/// Encodes the password.
/// </summary>
/// <param name="password">The password.</param>
/// <returns>The encoded password.</returns>
public string EncodePassword(string password)
{
string encodedPassword = password;
switch (PasswordFormat)
{
case MembershipPasswordFormat.Clear:
break;
case MembershipPasswordFormat.Encrypted:
encodedPassword =
Convert.ToBase64String(EncryptPassword(Encoding.Unicode.GetBytes(password)));
break;
case MembershipPasswordFormat.Hashed:
HMACSHA1 hash = new HMACSHA1();
hash.Key = Encoding.Unicode.GetBytes(password);
encodedPassword =
Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));
break;
default:
throw new ProviderException("Unsupported password format.");
}
return encodedPassword;
}
/// <summary>
/// Unencode password.
/// </summary>
/// <param name="encodedPassword">The encoded password.</param>
/// <returns>The unencoded password.</returns>
public string UnEncodePassword(string encodedPassword)
{
string password = encodedPassword;
switch (PasswordFormat)
{
case MembershipPasswordFormat.Clear:
break;
case MembershipPasswordFormat.Encrypted:
password = Encoding.Unicode.GetString(DecryptPassword(Convert.FromBase64String(password)));
break;
case MembershipPasswordFormat.Hashed:
throw new ProviderException("Cannot decrypt a hashed password.");
default:
throw new ProviderException("Unsupported password format.");
}
return password;
}
/// <summary>
/// Converts to membership user.
/// </summary>
/// <param name="m">The m.</param>
/// <returns></returns>
private MembershipUser ConvertToMembershipUser(Member m)
{
if (m == null) return null;
else
{
DateTime lastLogin = DateTime.Now;
bool isApproved = true;
bool isLocked = false;
string comment = "";
string passwordQuestion = "";
// last login
if (!String.IsNullOrEmpty(m_LastLoginPropertyTypeAlias))
{
DateTime.TryParse(GetMemberProperty(m, m_LastLoginPropertyTypeAlias, false), out lastLogin);
}
// approved
if (!String.IsNullOrEmpty(m_ApprovedPropertyTypeAlias))
{
bool.TryParse(GetMemberProperty(m, m_ApprovedPropertyTypeAlias, true), out isApproved);
}
// locked
if (!String.IsNullOrEmpty(m_LockPropertyTypeAlias))
{
bool.TryParse(GetMemberProperty(m, m_LockPropertyTypeAlias, true), out isLocked);
}
// comment
if (!String.IsNullOrEmpty(m_CommentPropertyTypeAlias))
{
comment = GetMemberProperty(m, m_CommentPropertyTypeAlias, false);
}
// password question
if (!String.IsNullOrEmpty(m_PasswordRetrievalQuestionPropertyTypeAlias))
{
passwordQuestion = GetMemberProperty(m, m_PasswordRetrievalQuestionPropertyTypeAlias, false);
}
return new MembershipUser(m_providerName, m.LoginName, m.Id, m.Email, passwordQuestion, comment, isApproved, isLocked, m.CreateDateTime, lastLogin,
DateTime.Now, DateTime.Now, DateTime.Now);
}
}
#endregion
}
}
| |
using ClosedXML.Excel;
using ClosedXML.Excel.Drawings;
using NUnit.Framework;
using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
namespace ClosedXML_Tests
{
[TestFixture]
public class XLWorksheetTests
{
[Test]
public void ColumnCountTime()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.Worksheets.Add("Sheet1");
DateTime start = DateTime.Now;
ws.ColumnCount();
DateTime end = DateTime.Now;
Assert.IsTrue((end - start).TotalMilliseconds < 500);
}
[Test]
public void CopyConditionalFormatsCount()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.AddWorksheet("Sheet1");
ws.Range("A1:C3").AddConditionalFormat().WhenContains("1").Fill.SetBackgroundColor(XLColor.Blue);
ws.Range("A1:C3").Value = 1;
IXLWorksheet ws2 = ws.CopyTo("Sheet2");
Assert.AreEqual(1, ws2.ConditionalFormats.Count());
}
[Test]
public void DeletingSheets1()
{
var wb = new XLWorkbook();
wb.Worksheets.Add("Sheet3");
wb.Worksheets.Add("Sheet2");
wb.Worksheets.Add("Sheet1", 1);
wb.Worksheet("Sheet3").Delete();
Assert.AreEqual("Sheet1", wb.Worksheet(1).Name);
Assert.AreEqual("Sheet2", wb.Worksheet(2).Name);
Assert.AreEqual(2, wb.Worksheets.Count);
}
[Test]
public void InsertingSheets1()
{
var wb = new XLWorkbook();
wb.Worksheets.Add("Sheet1");
wb.Worksheets.Add("Sheet2");
wb.Worksheets.Add("Sheet3");
Assert.AreEqual("Sheet1", wb.Worksheet(1).Name);
Assert.AreEqual("Sheet2", wb.Worksheet(2).Name);
Assert.AreEqual("Sheet3", wb.Worksheet(3).Name);
}
[Test]
public void InsertingSheets2()
{
var wb = new XLWorkbook();
wb.Worksheets.Add("Sheet2");
wb.Worksheets.Add("Sheet1", 1);
wb.Worksheets.Add("Sheet3");
Assert.AreEqual("Sheet1", wb.Worksheet(1).Name);
Assert.AreEqual("Sheet2", wb.Worksheet(2).Name);
Assert.AreEqual("Sheet3", wb.Worksheet(3).Name);
}
[Test]
public void InsertingSheets3()
{
var wb = new XLWorkbook();
wb.Worksheets.Add("Sheet3");
wb.Worksheets.Add("Sheet2", 1);
wb.Worksheets.Add("Sheet1", 1);
Assert.AreEqual("Sheet1", wb.Worksheet(1).Name);
Assert.AreEqual("Sheet2", wb.Worksheet(2).Name);
Assert.AreEqual("Sheet3", wb.Worksheet(3).Name);
}
[Test]
public void AddingDuplicateSheetNameThrowsException()
{
using (var wb = new XLWorkbook())
{
IXLWorksheet ws;
ws = wb.AddWorksheet("Sheet1");
Assert.Throws<ArgumentException>(() => wb.AddWorksheet("Sheet1"));
//Sheet names are case insensitive
Assert.Throws<ArgumentException>(() => wb.AddWorksheet("sheet1"));
}
}
[Test]
public void MergedRanges()
{
IXLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet1");
ws.Range("A1:B2").Merge();
ws.Range("C1:D3").Merge();
ws.Range("D2:E2").Merge();
Assert.AreEqual(2, ws.MergedRanges.Count);
Assert.AreEqual("A1:B2", ws.MergedRanges.First().RangeAddress.ToStringRelative());
Assert.AreEqual("D2:E2", ws.MergedRanges.Last().RangeAddress.ToStringRelative());
Assert.AreEqual("A1:B2", ws.Cell("A2").MergedRange().RangeAddress.ToStringRelative());
Assert.AreEqual("D2:E2", ws.Cell("D2").MergedRange().RangeAddress.ToStringRelative());
Assert.AreEqual(null, ws.Cell("Z10").MergedRange());
}
[Test]
public void RowCountTime()
{
var wb = new XLWorkbook();
IXLWorksheet ws = wb.Worksheets.Add("Sheet1");
DateTime start = DateTime.Now;
ws.RowCount();
DateTime end = DateTime.Now;
Assert.IsTrue((end - start).TotalMilliseconds < 500);
}
[Test]
public void SheetsWithCommas()
{
using (var wb = new XLWorkbook())
{
var sourceSheetName = "Sheet1, Sheet3";
var ws = wb.Worksheets.Add(sourceSheetName);
ws.Cell("A1").Value = 1;
ws.Cell("A2").Value = 2;
ws.Cell("B2").Value = 3;
ws = wb.Worksheets.Add("Formula");
ws.FirstCell().FormulaA1 = string.Format("=SUM('{0}'!A1:A2,'{0}'!B1:B2)", sourceSheetName);
var value = ws.FirstCell().Value;
Assert.AreEqual(6, value);
}
}
[Test]
public void CanRenameWorksheet()
{
using (var wb = new XLWorkbook())
{
var ws1 = wb.AddWorksheet("Sheet1");
var ws2 = wb.AddWorksheet("Sheet2");
ws1.Name = "New sheet name";
Assert.AreEqual("New sheet name", ws1.Name);
ws2.Name = "sheet2";
Assert.AreEqual("sheet2", ws2.Name);
Assert.Throws<ArgumentException>(() => ws1.Name = "SHEET2");
}
}
[Test]
public void TryGetWorksheet()
{
using (var wb = new XLWorkbook())
{
wb.AddWorksheet("Sheet1");
wb.AddWorksheet("Sheet2");
IXLWorksheet ws;
Assert.IsTrue(wb.Worksheets.TryGetWorksheet("Sheet1", out ws));
Assert.IsTrue(wb.Worksheets.TryGetWorksheet("sheet1", out ws));
Assert.IsTrue(wb.Worksheets.TryGetWorksheet("sHEeT1", out ws));
Assert.IsFalse(wb.Worksheets.TryGetWorksheet("Sheeeet2", out ws));
Assert.IsTrue(wb.TryGetWorksheet("Sheet1", out ws));
Assert.IsTrue(wb.TryGetWorksheet("sheet1", out ws));
Assert.IsTrue(wb.TryGetWorksheet("sHEeT1", out ws));
Assert.IsFalse(wb.TryGetWorksheet("Sheeeet2", out ws));
}
}
[Test]
public void HideWorksheet()
{
using (var ms = new MemoryStream())
{
using (var wb = new XLWorkbook())
{
wb.Worksheets.Add("VisibleSheet");
wb.Worksheets.Add("HiddenSheet").Hide();
wb.SaveAs(ms);
}
// unhide the hidden sheet
using (var wb = new XLWorkbook(ms))
{
Assert.AreEqual(XLWorksheetVisibility.Visible, wb.Worksheet("VisibleSheet").Visibility);
Assert.AreEqual(XLWorksheetVisibility.Hidden, wb.Worksheet("HiddenSheet").Visibility);
var ws = wb.Worksheet("HiddenSheet");
ws.Unhide().Name = "NoAlsoVisible";
Assert.AreEqual(XLWorksheetVisibility.Visible, ws.Visibility);
wb.Save();
}
using (var wb = new XLWorkbook(ms))
{
Assert.AreEqual(XLWorksheetVisibility.Visible, wb.Worksheet("VisibleSheet").Visibility);
Assert.AreEqual(XLWorksheetVisibility.Visible, wb.Worksheet("NoAlsoVisible").Visibility);
}
}
}
[Test]
public void CanCopySheetsWithAllAnchorTypes()
{
using (var stream = TestHelper.GetStreamFromResource(TestHelper.GetResourcePath(@"Examples\ImageHandling\ImageAnchors.xlsx")))
using (var wb = new XLWorkbook(stream))
{
var ws = wb.Worksheets.First();
ws.CopyTo("Copy1");
var ws2 = wb.Worksheets.Skip(1).First();
ws2.CopyTo("Copy2");
var ws3 = wb.Worksheets.Skip(2).First();
ws3.CopyTo("Copy3");
var ws4 = wb.Worksheets.Skip(3).First();
ws3.CopyTo("Copy4");
}
}
[Test]
public void WorksheetNameCannotStartWithApostrophe()
{
var title = "'StartsWithApostrophe";
TestDelegate addWorksheet = () =>
{
using (var wb = new XLWorkbook())
{
wb.Worksheets.Add(title);
}
};
Assert.Throws(typeof(ArgumentException), addWorksheet);
}
[Test]
public void WorksheetNameCannotEndWithApostrophe()
{
var title = "EndsWithApostrophe'";
TestDelegate addWorksheet = () =>
{
using (var wb = new XLWorkbook())
{
wb.Worksheets.Add(title);
}
};
Assert.Throws(typeof(ArgumentException), addWorksheet);
}
[Test]
public void WorksheetNameCanContainApostrophe()
{
var title = "With'Apostrophe";
var savedTitle = "";
TestDelegate saveAndOpenWorkbook = () =>
{
using (var ms = new MemoryStream())
{
using (var wb = new XLWorkbook())
{
wb.Worksheets.Add(title);
wb.Worksheets.First().Cell(1, 1).FormulaA1 = $"{title}!A2";
wb.SaveAs(ms);
}
using (var wb = new XLWorkbook(ms))
{
savedTitle = wb.Worksheets.First().Name;
}
}
};
Assert.DoesNotThrow(saveAndOpenWorkbook);
Assert.AreEqual(title, savedTitle);
}
[Test]
public void CopyWorksheetPreservesContents()
{
using (var wb1 = new XLWorkbook())
using (var wb2 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
ws1.Cell("A1").Value = "A1 value";
ws1.Cell("A2").Value = 100;
ws1.Cell("D4").Value = new DateTime(2018, 5, 1);
var ws2 = ws1.CopyTo(wb2, "Copy");
Assert.AreEqual("A1 value", ws2.Cell("A1").Value);
Assert.AreEqual(100, ws2.Cell("A2").Value);
Assert.AreEqual(new DateTime(2018, 5, 1), ws2.Cell("D4").Value);
}
}
[Test]
public void CopyWorksheetPreservesFormulae()
{
using (var wb1 = new XLWorkbook())
using (var wb2 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
ws1.Cell("A1").FormulaA1 = "10*10";
ws1.Cell("A2").FormulaA1 = "A1 * 2";
var ws2 = ws1.CopyTo(wb2, "Copy");
Assert.AreEqual("10*10", ws2.Cell("A1").FormulaA1);
Assert.AreEqual("A1 * 2", ws2.Cell("A2").FormulaA1);
}
}
[Test]
public void CopyWorksheetPreservesRowHeights()
{
using (var wb1 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
using (var wb2 = new XLWorkbook())
{
ws1.RowHeight = 55;
ws1.Row(2).Height = 0;
ws1.Row(3).Height = 20;
var ws2 = ws1.CopyTo(wb2, "Copy");
Assert.AreEqual(ws1.RowHeight, ws2.RowHeight);
for (int i = 1; i <= 3; i++)
{
Assert.AreEqual(ws1.Row(i).Height, ws2.Row(i).Height);
}
}
}
}
[Test]
public void CopyWorksheetPreservesColumnWidths()
{
using (var wb1 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
using (var wb2 = new XLWorkbook())
{
ws1.ColumnWidth = 160;
ws1.Column(2).Width = 0;
ws1.Column(3).Width = 240;
var ws2 = ws1.CopyTo(wb2, "Copy");
Assert.AreEqual(ws1.ColumnWidth, ws2.ColumnWidth);
for (int i = 1; i <= 3; i++)
{
Assert.AreEqual(ws1.Column(i).Width, ws2.Column(i).Width);
}
}
}
}
[Test]
public void CopyWorksheetPreservesMergedCells()
{
using (var wb1 = new XLWorkbook())
using (var wb2 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
ws1.Range("A:A").Merge();
ws1.Range("B1:C2").Merge();
var ws2 = ws1.CopyTo(wb2, "Copy");
Assert.AreEqual(ws1.MergedRanges.Count, ws2.MergedRanges.Count);
for (int i = 0; i < ws1.MergedRanges.Count; i++)
{
Assert.AreEqual(ws1.MergedRanges.ElementAt(i).RangeAddress.ToString(),
ws2.MergedRanges.ElementAt(i).RangeAddress.ToString());
}
}
}
[Test]
public void CopyWorksheetAcrossWorkbooksPreservesNamedRanges()
{
using (var wb1 = new XLWorkbook())
using (var wb2 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
ws1.Range("A1:A2").AddToNamed("GLOBAL", XLScope.Workbook);
ws1.Ranges("B1:B2,D1:D2").AddToNamed("LOCAL", XLScope.Worksheet);
var ws2 = ws1.CopyTo(wb2, "Copy");
Assert.AreEqual(ws1.NamedRanges.Count(), ws2.NamedRanges.Count());
for (int i = 0; i < ws1.NamedRanges.Count(); i++)
{
var nr1 = ws1.NamedRanges.ElementAt(i);
var nr2 = ws2.NamedRanges.ElementAt(i);
Assert.AreEqual(nr1.Ranges.ToString(), nr2.Ranges.ToString());
Assert.AreEqual(nr1.Scope, nr2.Scope);
Assert.AreEqual(nr1.Name, nr2.Name);
Assert.AreEqual(nr1.Visible, nr2.Visible);
Assert.AreEqual(nr1.Comment, nr2.Comment);
}
}
}
[Test]
public void CopyWorksheeInsideWorkbookMakesNamedRangesLocal()
{
using (var wb1 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
ws1.Range("A1:A2").AddToNamed("GLOBAL", XLScope.Workbook);
ws1.Ranges("B1:B2,D1:D2").AddToNamed("LOCAL", XLScope.Worksheet);
var ws2 = ws1.CopyTo("Copy");
Assert.AreEqual(ws1.NamedRanges.Count(), ws2.NamedRanges.Count());
for (int i = 0; i < ws1.NamedRanges.Count(); i++)
{
var nr1 = ws1.NamedRanges.ElementAt(i);
var nr2 = ws2.NamedRanges.ElementAt(i);
Assert.AreEqual(XLScope.Worksheet, nr2.Scope);
Assert.AreEqual(nr1.Ranges.ToString(), nr2.Ranges.ToString());
Assert.AreEqual(nr1.Name, nr2.Name);
Assert.AreEqual(nr1.Visible, nr2.Visible);
Assert.AreEqual(nr1.Comment, nr2.Comment);
}
}
}
[Test]
public void CopyWorksheetPreservesStyles()
{
using (var ms = new MemoryStream())
using (var wb1 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
ws1.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
ws1.Range("A1:B2").Style.Font.FontSize = 25;
ws1.Cell("C3").Style.Fill.BackgroundColor = XLColor.Red;
ws1.Cell("C4").Style.Fill.BackgroundColor = XLColor.AliceBlue;
ws1.Cell("C4").Value = "Non empty";
using (var wb2 = new XLWorkbook())
{
var ws2 = ws1.CopyTo(wb2, "Copy");
AssertStylesAreEqual(ws1, ws2);
wb2.SaveAs(ms);
}
using (var wb2 = new XLWorkbook(ms))
{
var ws2 = wb2.Worksheet("Copy");
AssertStylesAreEqual(ws1, ws2);
}
}
void AssertStylesAreEqual(IXLWorksheet ws1, IXLWorksheet ws2)
{
Assert.AreEqual((ws1.Style as XLStyle).Value, (ws2.Style as XLStyle).Value,
"Worksheet styles differ");
var cellsUsed = ws1.Range(ws1.FirstCell(), ws1.LastCellUsed()).Cells();
foreach (var cell in cellsUsed)
{
var style1 = (cell.Style as XLStyle).Value;
var style2 = (ws2.Cell(cell.Address.ToString()).Style as XLStyle).Value;
Assert.AreEqual(style1, style2, $"Cell {cell.Address} styles differ");
}
}
}
[Test]
public void CopyWorksheetPreservesConditionalFormats()
{
using (var wb1 = new XLWorkbook())
using (var wb2 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
ws1.Range("A:A").AddConditionalFormat()
.WhenContains("0").Fill.SetBackgroundColor(XLColor.Red);
var cf = ws1.Range("B1:C2").AddConditionalFormat();
cf.Ranges.Add(ws1.Range("D4:D5"));
cf.WhenEqualOrGreaterThan(100).Font.SetBold();
var ws2 = ws1.CopyTo(wb2, "Copy");
Assert.AreEqual(ws1.ConditionalFormats.Count(), ws2.ConditionalFormats.Count());
for (int i = 0; i < ws1.ConditionalFormats.Count(); i++)
{
var original = ws1.ConditionalFormats.ElementAt(i);
var copy = ws2.ConditionalFormats.ElementAt(i);
Assert.AreEqual(original.Ranges.Count, copy.Ranges.Count);
for (int j = 0; j < original.Ranges.Count; j++)
{
Assert.AreEqual(original.Ranges.ElementAt(j).RangeAddress.ToString(XLReferenceStyle.A1, false),
copy.Ranges.ElementAt(j).RangeAddress.ToString(XLReferenceStyle.A1, false));
}
Assert.AreEqual((original.Style as XLStyle).Value, (copy.Style as XLStyle).Value);
Assert.AreEqual(original.Values.Single().Value.Value, copy.Values.Single().Value.Value);
}
}
}
[Test]
public void CopyWorksheetPreservesTables()
{
using (var wb1 = new XLWorkbook())
using (var wb2 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
ws1.Cell("A2").Value = "Name";
ws1.Cell("B2").Value = "Count";
ws1.Cell("A3").Value = "John Smith";
ws1.Cell("B3").Value = 50;
ws1.Cell("A4").Value = "Ivan Ivanov";
ws1.Cell("B4").Value = 40;
var table1 = ws1.Range("A2:B4").CreateTable("Test table 1");
table1
.SetShowAutoFilter(true)
.SetShowTotalsRow(true)
.SetEmphasizeFirstColumn(true)
.SetShowColumnStripes(true)
.SetShowRowStripes(true);
table1.Theme = XLTableTheme.TableStyleDark8;
table1.Field(1).TotalsRowFunction = XLTotalsRowFunction.Sum;
var ws2 = ws1.CopyTo(wb2, "Copy");
Assert.AreEqual(ws1.Tables.Count(), ws2.Tables.Count());
for (int i = 0; i < ws1.Tables.Count(); i++)
{
var original = ws1.Tables.ElementAt(i);
var copy = ws2.Tables.ElementAt(i);
Assert.AreEqual(original.RangeAddress.ToString(XLReferenceStyle.A1, false), copy.RangeAddress.ToString(XLReferenceStyle.A1, false));
Assert.AreEqual(original.Fields.Count(), copy.Fields.Count());
for (int j = 0; j < original.Fields.Count(); j++)
{
var originalField = original.Fields.ElementAt(j);
var copyField = copy.Fields.ElementAt(j);
Assert.AreEqual(originalField.Name, copyField.Name);
Assert.AreEqual(originalField.TotalsRowFormulaA1, copyField.TotalsRowFormulaA1);
Assert.AreEqual(originalField.TotalsRowFunction, copyField.TotalsRowFunction);
}
Assert.AreEqual(original.Name, copy.Name);
Assert.AreEqual(original.ShowAutoFilter, copy.ShowAutoFilter);
Assert.AreEqual(original.ShowColumnStripes, copy.ShowColumnStripes);
Assert.AreEqual(original.ShowHeaderRow, copy.ShowHeaderRow);
Assert.AreEqual(original.ShowRowStripes, copy.ShowRowStripes);
Assert.AreEqual(original.ShowTotalsRow, copy.ShowTotalsRow);
Assert.AreEqual((original.Style as XLStyle).Value, (copy.Style as XLStyle).Value);
Assert.AreEqual(original.Theme, copy.Theme);
}
}
}
[Test]
public void CopyWorksheetPreservesDataValidation()
{
using (var wb1 = new XLWorkbook())
using (var wb2 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
var dv1 = ws1.Range("A:A").SetDataValidation();
dv1.WholeNumber.EqualTo(2);
dv1.ErrorStyle = XLErrorStyle.Warning;
dv1.ErrorTitle = "Number out of range";
dv1.ErrorMessage = "This cell only allows the number 2.";
var dv2 = ws1.Ranges("B2:C3,D4:E5").SetDataValidation();
dv2.Decimal.GreaterThan(5);
dv2.ErrorStyle = XLErrorStyle.Stop;
dv2.ErrorTitle = "Decimal number out of range";
dv2.ErrorMessage = "This cell only allows decimals greater than 5.";
var dv3 = ws1.Cell("D1").SetDataValidation();
dv3.TextLength.EqualOrLessThan(10);
dv3.ErrorStyle = XLErrorStyle.Information;
dv3.ErrorTitle = "Text length out of range";
dv3.ErrorMessage = "You entered more than 10 characters.";
var ws2 = ws1.CopyTo(wb2, "Copy");
Assert.AreEqual(ws1.DataValidations.Count(), ws2.DataValidations.Count());
for (int i = 0; i < ws1.DataValidations.Count(); i++)
{
var original = ws1.DataValidations.ElementAt(i);
var copy = ws2.DataValidations.ElementAt(i);
Assert.AreEqual(original.Ranges.ToString(), copy.Ranges.ToString());
Assert.AreEqual(original.AllowedValues, copy.AllowedValues);
Assert.AreEqual(original.Operator, copy.Operator);
Assert.AreEqual(original.ErrorStyle, copy.ErrorStyle);
Assert.AreEqual(original.ErrorTitle, copy.ErrorTitle);
Assert.AreEqual(original.ErrorMessage, copy.ErrorMessage);
}
}
}
[Test]
public void CopyWorksheetPreservesPictures()
{
using (var ms = new MemoryStream())
using (var resourceStream = Assembly.GetAssembly(typeof(ClosedXML_Examples.BasicTable))
.GetManifestResourceStream("ClosedXML_Examples.Resources.SampleImage.jpg"))
using (var bitmap = Bitmap.FromStream(resourceStream) as Bitmap)
using (var wb1 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
var picture = ws1.AddPicture(bitmap, "MyPicture")
.WithPlacement(XLPicturePlacement.FreeFloating)
.MoveTo(50, 50)
.WithSize(200, 200);
using (var wb2 = new XLWorkbook())
{
var ws2 = ws1.CopyTo(wb2, "Copy");
AssertPicturesAreEqual(ws1, ws2);
wb2.SaveAs(ms);
}
using (var wb2 = new XLWorkbook(ms))
{
var ws2 = wb2.Worksheet("Copy");
AssertPicturesAreEqual(ws1, ws2);
}
}
void AssertPicturesAreEqual(IXLWorksheet ws1, IXLWorksheet ws2)
{
Assert.AreEqual(ws1.Pictures.Count(), ws2.Pictures.Count());
for (int i = 0; i < ws1.Pictures.Count(); i++)
{
var original = ws1.Pictures.ElementAt(i);
var copy = ws2.Pictures.ElementAt(i);
Assert.AreEqual(ws2, copy.Worksheet);
Assert.AreEqual(original.Format, copy.Format);
Assert.AreEqual(original.Height, copy.Height);
Assert.AreEqual(original.Id, copy.Id);
Assert.AreEqual(original.Left, copy.Left);
Assert.AreEqual(original.Name, copy.Name);
Assert.AreEqual(original.Placement, copy.Placement);
Assert.AreEqual(original.Top, copy.Top);
Assert.AreEqual(original.TopLeftCellAddress.ToString(), copy.TopLeftCellAddress.ToString());
Assert.AreEqual(original.Width, copy.Width);
Assert.AreEqual(original.ImageStream.ToArray(), copy.ImageStream.ToArray(), "Image streams differ");
}
}
}
[Test]
public void CopyWorksheetPreservesSelectedRanges()
{
using (var wb1 = new XLWorkbook())
using (var wb2 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
ws1.SelectedRanges.RemoveAll();
ws1.SelectedRanges.Add(ws1.Range("E12:H20"));
ws1.SelectedRanges.Add(ws1.Range("B:B"));
ws1.SelectedRanges.Add(ws1.Range("3:6"));
var ws2 = ws1.CopyTo(wb2, "Copy");
Assert.AreEqual(ws1.SelectedRanges.Count, ws2.SelectedRanges.Count);
for (int i = 0; i < ws1.SelectedRanges.Count; i++)
{
Assert.AreEqual(ws1.SelectedRanges.ElementAt(i).RangeAddress.ToString(),
ws2.SelectedRanges.ElementAt(i).RangeAddress.ToString());
}
}
}
[Test]
public void CopyWorksheetPreservesPageSetup()
{
using (var wb1 = new XLWorkbook())
using (var wb2 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
ws1.PageSetup.AddHorizontalPageBreak(15);
ws1.PageSetup.AddVerticalPageBreak(5);
ws1.PageSetup
.SetBlackAndWhite()
.SetCenterHorizontally()
.SetCenterVertically()
.SetFirstPageNumber(200)
.SetPageOrientation(XLPageOrientation.Landscape)
.SetPaperSize(XLPaperSize.A5Paper)
.SetScale(89)
.SetShowGridlines()
.SetHorizontalDpi(200)
.SetVerticalDpi(300)
.SetPagesTall(5)
.SetPagesWide(2)
.SetColumnsToRepeatAtLeft(1, 3);
ws1.PageSetup.PrintAreas.Clear();
ws1.PageSetup.PrintAreas.Add("A1:Z200");
ws1.PageSetup.Margins.SetBottom(5).SetTop(6).SetLeft(7).SetRight(8).SetFooter(9).SetHeader(10);
ws1.PageSetup.Header.Left.AddText(XLHFPredefinedText.FullPath, XLHFOccurrence.AllPages);
ws1.PageSetup.Footer.Right.AddText(XLHFPredefinedText.PageNumber, XLHFOccurrence.OddPages);
var ws2 = ws1.CopyTo(wb2, "Copy");
Assert.AreEqual(ws1.PageSetup.FirstRowToRepeatAtTop, ws2.PageSetup.FirstRowToRepeatAtTop);
Assert.AreEqual(ws1.PageSetup.LastRowToRepeatAtTop, ws2.PageSetup.LastRowToRepeatAtTop);
Assert.AreEqual(ws1.PageSetup.FirstColumnToRepeatAtLeft, ws2.PageSetup.FirstColumnToRepeatAtLeft);
Assert.AreEqual(ws1.PageSetup.LastColumnToRepeatAtLeft, ws2.PageSetup.LastColumnToRepeatAtLeft);
Assert.AreEqual(ws1.PageSetup.PageOrientation, ws2.PageSetup.PageOrientation);
Assert.AreEqual(ws1.PageSetup.PagesWide, ws2.PageSetup.PagesWide);
Assert.AreEqual(ws1.PageSetup.PagesTall, ws2.PageSetup.PagesTall);
Assert.AreEqual(ws1.PageSetup.Scale, ws2.PageSetup.Scale);
Assert.AreEqual(ws1.PageSetup.HorizontalDpi, ws2.PageSetup.HorizontalDpi);
Assert.AreEqual(ws1.PageSetup.VerticalDpi, ws2.PageSetup.VerticalDpi);
Assert.AreEqual(ws1.PageSetup.FirstPageNumber, ws2.PageSetup.FirstPageNumber);
Assert.AreEqual(ws1.PageSetup.CenterHorizontally, ws2.PageSetup.CenterHorizontally);
Assert.AreEqual(ws1.PageSetup.CenterVertically, ws2.PageSetup.CenterVertically);
Assert.AreEqual(ws1.PageSetup.PaperSize, ws2.PageSetup.PaperSize);
Assert.AreEqual(ws1.PageSetup.Margins.Bottom, ws2.PageSetup.Margins.Bottom);
Assert.AreEqual(ws1.PageSetup.Margins.Top, ws2.PageSetup.Margins.Top);
Assert.AreEqual(ws1.PageSetup.Margins.Left, ws2.PageSetup.Margins.Left);
Assert.AreEqual(ws1.PageSetup.Margins.Right, ws2.PageSetup.Margins.Right);
Assert.AreEqual(ws1.PageSetup.Margins.Footer, ws2.PageSetup.Margins.Footer);
Assert.AreEqual(ws1.PageSetup.Margins.Header, ws2.PageSetup.Margins.Header);
Assert.AreEqual(ws1.PageSetup.ScaleHFWithDocument, ws2.PageSetup.ScaleHFWithDocument);
Assert.AreEqual(ws1.PageSetup.AlignHFWithMargins, ws2.PageSetup.AlignHFWithMargins);
Assert.AreEqual(ws1.PageSetup.ShowGridlines, ws2.PageSetup.ShowGridlines);
Assert.AreEqual(ws1.PageSetup.ShowRowAndColumnHeadings, ws2.PageSetup.ShowRowAndColumnHeadings);
Assert.AreEqual(ws1.PageSetup.BlackAndWhite, ws2.PageSetup.BlackAndWhite);
Assert.AreEqual(ws1.PageSetup.DraftQuality, ws2.PageSetup.DraftQuality);
Assert.AreEqual(ws1.PageSetup.PageOrder, ws2.PageSetup.PageOrder);
Assert.AreEqual(ws1.PageSetup.ShowComments, ws2.PageSetup.ShowComments);
Assert.AreEqual(ws1.PageSetup.PrintErrorValue, ws2.PageSetup.PrintErrorValue);
Assert.AreEqual(ws1.PageSetup.PrintAreas.Count(), ws2.PageSetup.PrintAreas.Count());
Assert.AreEqual(ws1.PageSetup.Header.Left.GetText(XLHFOccurrence.AllPages), ws2.PageSetup.Header.Left.GetText(XLHFOccurrence.AllPages));
Assert.AreEqual(ws1.PageSetup.Footer.Right.GetText(XLHFOccurrence.OddPages), ws2.PageSetup.Footer.Right.GetText(XLHFOccurrence.OddPages));
}
}
[Test, Ignore("Muted until #836 is fixed")]
public void CopyWorksheetChangesAbsoluteReferencesInFormulae()
{
using (var wb1 = new XLWorkbook())
using (var wb2 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
ws1.Cell("A1").FormulaA1 = "10*10";
ws1.Cell("A2").FormulaA1 = "Original!A1 * 3";
var ws2 = ws1.CopyTo(wb2, "Copy");
Assert.AreEqual("Copy!A1 * 3", ws2.Cell("A2").FormulaA1);
}
}
[Test, Ignore("Muted until #836 is fixed")]
public void RenameWorksheetChangesAbsoluteReferencesInFormulae()
{
using (var wb1 = new XLWorkbook())
{
var ws1 = wb1.Worksheets.Add("Original");
ws1.Cell("A1").FormulaA1 = "10*10";
ws1.Cell("A2").FormulaA1 = "Original!A1 * 3";
ws1.Name = "Renamed";
Assert.AreEqual("Renamed!A1 * 3", ws1.Cell("A2").FormulaA1);
}
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using System.Collections;
using System;
namespace UIWidgets {
/// <summary>
/// Dialog actions.
/// Key - button name.
/// Value - action on click.
/// </summary>
public class DialogActions : IDictionary<string,Func<bool>> {
List<string> keys = new List<string>();
List<Func<bool>> values = new List<Func<bool>>();
List<KeyValuePair<string,Func<bool>>> elements = new List<KeyValuePair<string,Func<bool>>>();
/// <summary>
/// Gets the number of elements contained in the dictionary.
/// </summary>
/// <value>The count.</value>
public int Count {
get {
return elements.Count;
}
}
/// <summary>
/// Gets a value indicating whether this instance is read only.
/// </summary>
/// <value><c>true</c> if this instance is read only; otherwise, <c>false</c>.</value>
public bool IsReadOnly {
get {
return false;
}
}
/// <summary>
/// Gets or sets the element with the specified key.
/// </summary>
/// <returns>The element with the specified key.</returns>
/// <param name="key">The key of the element to get or set.</param>
public Func<bool> this[string key] {
get {
var index = keys.IndexOf(key);
return elements[index].Value;
}
set {
var index = keys.IndexOf(key);
elements[index] = new KeyValuePair<string, Func<bool>>(key, value);
}
}
/// <summary>
/// Gets an ICollection<string> containing the keys of the dictionary.
/// </summary>
/// <value>The keys.</value>
public ICollection<string> Keys {
get {
return elements.Convert<KeyValuePair<string,Func<bool>>,string>(GetKey);
}
}
string GetKey(KeyValuePair<string,Func<bool>> item)
{
return item.Key;
}
/// <summary>
/// Gets an ICollection<Func<bool>> containing the values in the dictionary.
/// </summary>
/// <value>The values.</value>
public ICollection<Func<bool>> Values {
get {
return elements.Convert<KeyValuePair<string,Func<bool>>,Func<bool>>(GetValue);
}
}
Func<bool> GetValue(KeyValuePair<string, Func<bool>> item)
{
return item.Value;
}
/// <summary>
/// Add the specified item.
/// </summary>
/// <param name="item">Item.</param>
public void Add(KeyValuePair<string,Func<bool>> item)
{
Add(item.Key, item.Value);
}
/// <summary>
/// Add the specified key and value.
/// </summary>
/// <param name="key">Key.</param>
/// <param name="value">Value.</param>
public void Add(string key, Func<bool> value)
{
if (key==null)
{
throw new ArgumentNullException("key", "Key is null.");
}
if (ContainsKey(key))
{
throw new ArgumentException(string.Format("An element with the same key ({0}) already exists.", key));
}
keys.Add(key);
values.Add(value);
elements.Add(new KeyValuePair<string, Func<bool>>(key, value));
}
/// <summary>
/// Removes all items.
/// </summary>
public void Clear()
{
keys.Clear();
values.Clear();
elements.Clear();
}
/// <summary>
/// Determines whether contains a specific value.
/// </summary>
/// <param name="item">Item.</param>
public bool Contains(KeyValuePair<string,Func<bool>> item)
{
return elements.Contains(item);
}
/// <summary>
/// Determines whether the IDictionary<TKey,TValue> contains an element with the specified key.
/// </summary>
/// <param name="key">Key.</param>
/// <returns><c>true</c>, if key was containsed, <c>false</c> otherwise.</returns>
public bool ContainsKey(string key)
{
if (key==null)
{
throw new ArgumentNullException("key", "Key is null.");
}
return keys.Contains(key);
}
/// <summary>
/// Copies the elements of the KeyValuePair<string,Func<bool>> to an Array, starting at a particular Array index.
/// </summary>
/// <param name="array">Array.</param>
/// <param name="arrayIndex">Array index.</param>
public void CopyTo(KeyValuePair<string,Func<bool>>[] array, int arrayIndex)
{
elements.CopyTo(array, arrayIndex);
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
public IEnumerator<KeyValuePair<string,Func<bool>>> GetEnumerator()
{
return elements.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
IEnumerator IEnumerable.GetEnumerator()
{
return elements.GetEnumerator();
}
/// <summary>
/// Removes the first occurrence of a specific object from the dictionary.
/// </summary>
/// <param name="item">Item.</param>
public bool Remove(KeyValuePair<string,Func<bool>> item)
{
if (!elements.Contains(item))
{
return false;
}
var index = elements.IndexOf(item);
keys.RemoveAt(index);
values.RemoveAt(index);
elements.RemoveAt(index);
return true;
}
/// <summary>
/// Removes the element with the specified key from the dictionary.
/// </summary>
/// <param name="key">Key.</param>
public bool Remove(string key)
{
if (key==null)
{
throw new ArgumentNullException("key", "Key is null.");
}
if (!ContainsKey(key))
{
return false;
}
var index = keys.IndexOf(key);
keys.RemoveAt(index);
values.RemoveAt(index);
elements.RemoveAt(index);
return true;
}
/// <summary>
/// Gets the value associated with the specified key.
/// </summary>
/// <returns><c>true</c>, if get value was tryed, <c>false</c> otherwise.</returns>
/// <param name="key">Key.</param>
/// <param name="value">Value.</param>
public bool TryGetValue(string key, out Func<bool> value)
{
if (key==null)
{
throw new ArgumentNullException("key", "Key is null.");
}
if (!ContainsKey(key))
{
value = default(Func<bool>);
return false;
}
value = values[keys.IndexOf(key)];
return true;
}
}
}
| |
/*
The MIT License (MIT)
Copyright (c) 2015 Secret Lab Pty. Ltd. and Yarn Spinner contributors.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;
namespace Yarn {
// An exception representing something going wrong during parsing
[Serializable]
internal class ParseException : Exception {
internal int lineNumber = 0;
internal static ParseException Make(Token foundToken, params TokenType[] expectedTypes) {
var lineNumber = foundToken.lineNumber+1;
var expectedTypeNames = new List<String> ();
foreach (var type in expectedTypes) {
expectedTypeNames.Add (type.ToString ());
}
string possibleValues = string.Join(",", expectedTypeNames.ToArray());
string message = string.Format("Line {0}:{1}: Expected {2}, but found {3}",
lineNumber,
foundToken.columnNumber,
possibleValues,
foundToken.type.ToString()
);
var e = new ParseException (message);
e.lineNumber = lineNumber;
return e;
}
internal static ParseException Make(Token mostRecentToken, string message) {
var lineNumber = mostRecentToken.lineNumber+1;
string theMessage = string.Format ("Line {0}:{1}: {2}",
lineNumber,
mostRecentToken.columnNumber,
message);
var e = new ParseException (theMessage);
e.lineNumber = lineNumber;
return e;
}
internal ParseException (string message) : base(message) {}
}
// Magic abstract syntax tree producer - feed it tokens, and it gives you
// a tree representation! Or an error!
internal class Parser {
// Indents the 'input' string 'indentLevel' times
private static string Tab(int indentLevel, string input, bool newLine = true) {
var sb = new StringBuilder();
for (int i = 0; i < indentLevel; i++) {
sb.Append ("| ");
}
sb.Append (input);
if (newLine)
sb.Append ("\n");
return sb.ToString ();
}
#region Parse Nodes
// Base class for nodes in th parse tree
internal abstract class ParseNode {
private ParseNode parent;
// ParseNodes do their parsing by consuming tokens from the Parser.
// You parse tokens into a ParseNode by using its constructor.
internal ParseNode(ParseNode parent, Parser p) { this.parent = parent; }
// Recursively prints the ParseNode and all of its child ParseNodes.
internal abstract string PrintTree (int indentLevel);
public override string ToString ()
{
return this.GetType ().Name;
}
// The closest parent to this ParseNode that is a Node.
internal Node NodeParent() {
var node = this;
do {
if (node is Node) {
return node as Node;
}
node = node.parent;
} while (node
!= null);
return null;
}
}
// The top-level unit of parsing.
// Node = (Statement)* EndOfInput
internal class Node : ParseNode {
internal string name { get; set;}
internal string source { get; set; }
// Read-only internal accessor for statements
internal IEnumerable<Statement> statements { get { return _statements; }}
// The statements in this node
List<Statement> _statements = new List<Statement> ();
internal Node(string name, ParseNode parent, Parser p) : base(parent, p) {
this.name = name;
// Consume statements until we run out of input or we hit a dedent
while (p.tokens.Count > 0 && p.NextSymbolIs(TokenType.Dedent,TokenType.EndOfInput) == false) {
_statements.Add(new Statement(this, p));
}
}
// Print the statements we have
internal override string PrintTree (int indentLevel)
{
var sb = new StringBuilder ();
sb.Append (Tab (indentLevel, "Node "+name+" {"));
foreach (var statement in _statements) {
sb.Append( statement.PrintTree (indentLevel + 1));
}
sb.Append (Tab (indentLevel, "}"));
return sb.ToString();
}
}
// Statements are the items of execution in nodes.
// Statement = Block
// Statement = IfStatement
// Statement = OptionStatement
// Statement = ShortcutOptionGroup
// Statement = CustomCommand
// Statement = AssignmentStatement
// Statement = <Text>
internal class Statement : ParseNode {
internal enum Type {
CustomCommand,
ShortcutOptionGroup,
Block,
IfStatement,
OptionStatement,
AssignmentStatement,
Line
}
internal Statement.Type type { get; private set; }
// The possible types of statements we can have
internal Block block { get; private set;}
internal IfStatement ifStatement {get; private set;}
internal OptionStatement optionStatement {get; private set;}
internal AssignmentStatement assignmentStatement {get; private set;}
internal CustomCommand customCommand {get;private set;}
internal string line {get; private set;}
internal ShortcutOptionGroup shortcutOptionGroup { get; private set; }
internal Statement(ParseNode parent, Parser p) : base(parent, p) {
if (Block.CanParse(p)) {
type = Type.Block;
block = new Block(this, p);
return;
} else if (IfStatement.CanParse(p)) {
type = Type.IfStatement;
ifStatement = new IfStatement(this, p);
return;
} else if (OptionStatement.CanParse(p)) {
type = Type.OptionStatement;
optionStatement = new OptionStatement(this, p);
return;
} else if (AssignmentStatement.CanParse(p)) {
type = Type.AssignmentStatement;
assignmentStatement = new AssignmentStatement(this, p);
return;
} else if (ShortcutOptionGroup.CanParse(p)) {
type = Type.ShortcutOptionGroup;
shortcutOptionGroup = new ShortcutOptionGroup(this, p);
return;
} else if (CustomCommand.CanParse(p)) {
type = Type.CustomCommand;
customCommand = new CustomCommand(this, p);
return;
} else if (p.NextSymbolIs(TokenType.Text)) {
line = p.ExpectSymbol(TokenType.Text).value as string;
type = Type.Line;
} else {
throw ParseException.Make(p.tokens.Peek(), "Expected a statement here but got " + p.tokens.Peek().ToString() +" instead (was there an unbalanced if statement earlier?)");
}
}
internal override string PrintTree (int indentLevel)
{
switch (type) {
case Type.Block:
return block.PrintTree (indentLevel);
case Type.IfStatement:
return ifStatement.PrintTree (indentLevel);
case Type.OptionStatement:
return optionStatement.PrintTree (indentLevel);
case Type.AssignmentStatement:
return assignmentStatement.PrintTree (indentLevel);
case Type.ShortcutOptionGroup:
return shortcutOptionGroup.PrintTree (indentLevel);
case Type.CustomCommand:
return customCommand.PrintTree (indentLevel);
case Type.Line:
return Tab (indentLevel, "Line: "+ line);
}
throw new ArgumentNullException ();
}
}
// Custom commands are meant to be interpreted by whatever
// system that owns this dialogue sytem. eg <<stand>>
// CustomCommand = BeginCommand <ANY>* EndCommand
internal class CustomCommand : ParseNode {
internal enum Type {
Expression,
ClientCommand
}
internal Type type;
internal Expression expression {get; private set;}
internal string clientCommand { get; private set;}
internal static bool CanParse (Parser p)
{
return p.NextSymbolsAre (TokenType.BeginCommand, TokenType.Text) ||
p.NextSymbolsAre (TokenType.BeginCommand, TokenType.Identifier);
}
internal CustomCommand(ParseNode parent, Parser p) : base(parent, p) {
p.ExpectSymbol(TokenType.BeginCommand);
// Custom commands can have ANY token in them. Read them all until we hit the
// end command token.
var commandTokens = new List<Token>();
do {
commandTokens.Add(p.ExpectSymbol());
} while (p.NextSymbolIs(TokenType.EndCommand) == false);
p.ExpectSymbol(TokenType.EndCommand);
// If the first token is an identifier and the second is
// a left paren, it may be a function call expression;
// evaluate it as such
if (commandTokens.Count > 1 &&
commandTokens[0].type == TokenType.Identifier &&
commandTokens[1].type == TokenType.LeftParen) {
var parser = new Parser(commandTokens, p.library);
var expression = Expression.Parse(this, parser);
type = Type.Expression;
this.expression = expression;
} else {
// Otherwise, evaluate it as a command
type = Type.ClientCommand;
this.clientCommand = commandTokens[0].value;
}
}
internal override string PrintTree (int indentLevel)
{
switch (type) {
case Type.Expression:
return Tab (indentLevel, "Expression: ") + expression.PrintTree (indentLevel + 1);
case Type.ClientCommand:
return Tab (indentLevel, "Command: " + clientCommand);
}
return "";
}
}
// Shortcut option groups are groups of shortcut options,
// followed by the node that they rejoin.
// ShortcutOptionGroup = ShortcutOption+ Node
internal class ShortcutOptionGroup : ParseNode {
internal static bool CanParse (Parser p)
{
return p.NextSymbolIs (TokenType.ShortcutOption);
}
internal IEnumerable<ShortcutOption> options { get { return _options; }}
// The options in this group
private List<ShortcutOption> _options = new List<ShortcutOption>();
internal ShortcutOptionGroup(ParseNode parent, Parser p) : base(parent, p) {
// keep parsing options until we can't, but expect at least one (otherwise it's
// not actually a list of options)
int shortcutIndex = 1; // give each option a number so it can name itself
do {
_options.Add(new ShortcutOption(shortcutIndex++, this, p));
} while (p.NextSymbolIs(TokenType.ShortcutOption));
}
internal override string PrintTree (int indentLevel)
{
var sb = new StringBuilder ();
sb.Append (Tab (indentLevel, "Shortcut option group {"));
foreach (var option in options) {
sb.Append (option.PrintTree (indentLevel + 1));
}
sb.Append (Tab (indentLevel, "}"));
return sb.ToString ();
}
}
// Shortcut options are a convenient way to define new options.
// ShortcutOption = -> <text> [BeginCommand If Expression EndCommand] [Block]
internal class ShortcutOption : ParseNode {
internal string label { get; private set;}
internal Expression condition { get; private set;}
internal Node optionNode { get; private set;}
internal ShortcutOption(int optionIndex, ParseNode parent, Parser p) : base(parent, p) {
p.ExpectSymbol(TokenType.ShortcutOption);
label = p.ExpectSymbol(TokenType.Text).value as string;
// Parse the conditional ("<<if $foo>>") if it's there
if (p.NextSymbolsAre(TokenType.BeginCommand, TokenType.If)) {
p.ExpectSymbol(TokenType.BeginCommand);
p.ExpectSymbol(TokenType.If);
condition = Expression.Parse(this, p);
p.ExpectSymbol(TokenType.EndCommand);
}
// Parse the statements belonging to this option if it has any
if (p.NextSymbolIs(TokenType.Indent)) {
p.ExpectSymbol(TokenType.Indent);
optionNode = new Node(NodeParent().name + "." + optionIndex, this, p);
p.ExpectSymbol(TokenType.Dedent);
}
}
internal override string PrintTree (int indentLevel)
{
var sb = new StringBuilder ();
sb.Append (Tab (indentLevel, "Option \"" +label + "\""));
if (condition != null) {
sb.Append (Tab (indentLevel + 1, "(when:"));
sb.Append (condition.PrintTree(indentLevel+2));
sb.Append (Tab (indentLevel + 1, "),"));
}
if (optionNode != null) {
sb.Append (Tab (indentLevel, "{"));
sb.Append (optionNode.PrintTree (indentLevel + 1));
sb.Append (Tab (indentLevel, "}"));
}
return sb.ToString ();
}
}
// Blocks are indented groups of statements
// Block = Indent Statement* Dedent
internal class Block : ParseNode {
internal static bool CanParse (Parser p)
{
return p.NextSymbolIs (TokenType.Indent);
}
internal IEnumerable<Statement> statements { get { return _statements; }}
List<Statement> _statements = new List<Statement> ();
internal Block(ParseNode parent, Parser p) : base(parent, p) {
// Read the indent token
p.ExpectSymbol(TokenType.Indent);
// Keep reading statements until we hit a dedent
while (p.NextSymbolIs(TokenType.Dedent) == false) {
// fun fact! because Blocks are a type of Statement,
// we get nested block parsing for free! \:D/
_statements.Add(new Statement(this, p));
}
// Tidy up by reading the dedent
p.ExpectSymbol(TokenType.Dedent);
}
internal override string PrintTree (int indentLevel)
{
var sb = new StringBuilder ();
sb.Append (Tab(indentLevel, "Block {"));
foreach (var statement in _statements) {
sb.Append (statement.PrintTree (indentLevel + 1));
}
sb.Append (Tab(indentLevel, "}"));
return sb.ToString ();
}
}
// Options are links to other nodes
// OptionStatement = OptionStart <Text> OptionEnd
// OptionStatement = OptionStart <Text> OptionDelimit <Text>|<Identifier> OptionEnd
internal class OptionStatement : ParseNode {
internal static bool CanParse (Parser p)
{
return p.NextSymbolIs (TokenType.OptionStart);
}
internal string destination { get; private set;}
internal string label { get; private set;}
internal OptionStatement(ParseNode parent, Parser p) : base(parent, p) {
// The meaning of the string(s) we have changes
// depending on whether we have one or two, so
// keep them both and decide their meaning once
// we know more
string firstString;
string secondString;
// Parse "[[LABEL"
p.ExpectSymbol(TokenType.OptionStart);
firstString = p.ExpectSymbol(TokenType.Text).value as String;
// If there's a | in there, get the string that comes after it
if (p.NextSymbolIs(TokenType.OptionDelimit)) {
p.ExpectSymbol(TokenType.OptionDelimit);
secondString = p.ExpectSymbol(TokenType.Text, TokenType.Identifier).value as String;
// Two strings mean that the first is the label, and the second
// is the name of the node that we should head to if this option
// is selected
label = firstString;
destination = secondString;
} else {
// One string means we don't have a label
label = null;
destination = firstString;
}
// Parse the closing ]]
p.ExpectSymbol(TokenType.OptionEnd);
}
internal override string PrintTree (int indentLevel)
{
if (label != null) {
return Tab (indentLevel, string.Format ("Option: \"{0}\" -> {1}", label, destination));
} else {
return Tab (indentLevel, string.Format ("Option: -> {0}", destination));
}
}
}
// If statements are the usual if-else-elseif-endif business.
// If = BeginCommand If Expression EndCommand Statement* BeginCommand EndIf EndCommand
// TODO: elseif
internal class IfStatement : ParseNode {
internal static bool CanParse (Parser p)
{
return p.NextSymbolsAre (TokenType.BeginCommand, TokenType.If);
}
// Clauses are collections of statements with an
// optional conditional that determines whether they're run
// or not. The condition is used by the If and ElseIf parts of
// an if statement, and not used by the Else statement.
internal struct Clause {
internal Expression expression;
internal IEnumerable<Statement> statements;
internal string PrintTree(int indentLevel) {
var sb = new StringBuilder ();
if (expression != null)
sb.Append (expression.PrintTree (indentLevel));
sb.Append (Tab (indentLevel, "{"));
foreach (var statement in statements) {
sb.Append (statement.PrintTree (indentLevel + 1));
}
sb.Append (Tab (indentLevel, "}"));
return sb.ToString ();
}
}
internal List<Clause> clauses = new List<Clause>();
internal IfStatement(ParseNode parent, Parser p) : base(parent, p) {
// All if statements begin with "<<if EXPRESSION>>", so parse that
Clause primaryClause = new Clause();
p.ExpectSymbol(TokenType.BeginCommand);
p.ExpectSymbol(TokenType.If);
primaryClause.expression = Expression.Parse(this, p);
p.ExpectSymbol(TokenType.EndCommand);
// Read the statements for this clause until we hit an <<endif or <<else
// (which could be an "<<else>>" or an "<<else if"
var statements = new List<Statement>();
while (p.NextSymbolsAre(TokenType.BeginCommand, TokenType.EndIf) == false &&
p.NextSymbolsAre(TokenType.BeginCommand, TokenType.Else) == false &&
p.NextSymbolsAre(TokenType.BeginCommand, TokenType.ElseIf) == false) {
statements.Add(new Statement(this, p));
// Ignore any dedents
while (p.NextSymbolIs(TokenType.Dedent)) {
p.ExpectSymbol(TokenType.Dedent);
}
}
primaryClause.statements = statements;
clauses.Add(primaryClause);
// Handle as many <<elseif clauses as we find
while (p.NextSymbolsAre(TokenType.BeginCommand, TokenType.ElseIf)) {
var elseIfClause = new Clause();
// Parse the syntax for this clause's condition
p.ExpectSymbol(TokenType.BeginCommand);
p.ExpectSymbol(TokenType.ElseIf);
elseIfClause.expression = Expression.Parse(this, p);
p.ExpectSymbol(TokenType.EndCommand);
// Read statements until we hit an <<endif, <<else or another <<elseif
var clauseStatements = new List<Statement>();
while (p.NextSymbolsAre(TokenType.BeginCommand, TokenType.EndIf) == false &&
p.NextSymbolsAre(TokenType.BeginCommand, TokenType.Else) == false &&
p.NextSymbolsAre(TokenType.BeginCommand, TokenType.ElseIf) == false) {
clauseStatements.Add(new Statement(this, p));
// Ignore any dedents
while (p.NextSymbolIs(TokenType.Dedent)) {
p.ExpectSymbol(TokenType.Dedent);
}
}
elseIfClause.statements = clauseStatements;
clauses.Add(elseIfClause);
}
// Handle <<else>> if we have it
if (p.NextSymbolsAre(TokenType.BeginCommand, TokenType.Else, TokenType.EndCommand)) {
// parse the syntax (no expression this time, just "<<else>>"
p.ExpectSymbol(TokenType.BeginCommand);
p.ExpectSymbol(TokenType.Else);
p.ExpectSymbol(TokenType.EndCommand);
// and parse statements until we hit "<<endif"
var elseClause = new Clause();
var clauseStatements = new List<Statement>();
while (p.NextSymbolsAre(TokenType.BeginCommand, TokenType.EndIf) == false) {
clauseStatements.Add(new Statement(this, p));
}
elseClause.statements = clauseStatements;
this.clauses.Add(elseClause);
// Ignore any dedents
while (p.NextSymbolIs(TokenType.Dedent)) {
p.ExpectSymbol(TokenType.Dedent);
}
}
// Finish up by reading the <<endif>>
p.ExpectSymbol(TokenType.BeginCommand);
p.ExpectSymbol(TokenType.EndIf);
p.ExpectSymbol(TokenType.EndCommand);
}
internal override string PrintTree (int indentLevel)
{
var sb = new StringBuilder ();
var first = true;
foreach (var clause in clauses) {
if (first) {
sb.Append (Tab (indentLevel, "If:"));
first = false;
} else if (clause.expression != null) {
sb.Append (Tab (indentLevel, "Else If:"));
} else {
sb.Append (Tab (indentLevel, "Else:"));
}
sb.Append (clause.PrintTree (indentLevel + 1));
}
return sb.ToString ();
}
}
// A value, which forms part of an expression.
public class ValueNode : ParseNode {
public Value value { get; private set;}
private void UseToken(Token t) {
// Store the value depending on token's type
switch (t.type) {
case TokenType.Number:
value = new Value (float.Parse (t.value as String));
break;
case TokenType.String:
value = new Value (t.value as String);
break;
case TokenType.False:
value = new Value (false);
break;
case TokenType.True:
value = new Value (true);
break;
case TokenType.Variable:
value = new Value ();
value.type = Value.Type.Variable;
value.variableName = t.value as String;
break;
case TokenType.Null:
value = Value.NULL;
break;
default:
throw ParseException.Make (t, "Invalid token type " + t.ToString ());
}
}
// Use a provided token
internal ValueNode(ParseNode parent, Token t) : base (parent, null) {
UseToken(t);
}
// Read a number or a variable name from the parser
internal ValueNode(ParseNode parent, Parser p) : base(parent, p) {
Token t = p.ExpectSymbol(TokenType.Number, TokenType.Variable, TokenType.String);
UseToken(t);
}
internal override string PrintTree (int indentLevel)
{
switch (value.type) {
case Value.Type.Number:
return Tab (indentLevel, value.numberValue.ToString());
case Value.Type.String:
return Tab(indentLevel, String.Format("\"{0}\"", value.stringValue));
case Value.Type.Bool:
return Tab (indentLevel, value.boolValue.ToString());
case Value.Type.Variable:
return Tab (indentLevel, value.variableName);
case Value.Type.Null:
return Tab (indentLevel, "(null)");
}
throw new ArgumentException ();
}
}
// Expressions are things like "1 + 2 * 5 / 2 - 1"
// Expression = Expression Operator Expression
// Expression = Identifier ( Expression [, Expression]* )
// Expression = Value
internal class Expression : ParseNode {
internal enum Type {
Value,
FunctionCall
}
internal Type type;
internal ValueNode value;
// - or -
internal FunctionInfo function;
internal List<Expression> parameters;
internal Expression(ParseNode parent, ValueNode value) : base(parent, null) {
this.type = Type.Value;
this.value = value;
}
internal Expression(ParseNode parent, FunctionInfo function, List<Expression> parameters) : base(parent, null) {
type = Type.FunctionCall;
this.function = function;
this.parameters = parameters;
}
internal static Expression Parse(ParseNode parent, Parser p) {
// Applies Djikstra's "shunting-yard" algorithm to convert the
// stream of infix expressions into postfix notation; we then
// build a tree of expressions from the result
// https://en.wikipedia.org/wiki/Shunting-yard_algorithm
Queue<Token> _expressionRPN = new Queue<Token> ();
var operatorStack = new Stack<Token>();
// used for keeping count of parameters for each function
var functionStack = new Stack<Token> ();
var allValidTokenTypes = new List<TokenType>(Operator.operatorTypes);
allValidTokenTypes.Add(TokenType.Number);
allValidTokenTypes.Add(TokenType.Variable);
allValidTokenTypes.Add(TokenType.String);
allValidTokenTypes.Add(TokenType.LeftParen);
allValidTokenTypes.Add(TokenType.RightParen);
allValidTokenTypes.Add(TokenType.Identifier);
allValidTokenTypes.Add(TokenType.Comma);
allValidTokenTypes.Add(TokenType.True);
allValidTokenTypes.Add(TokenType.False);
allValidTokenTypes.Add(TokenType.Null);
Token lastToken = null;
// Read all the contents of the expression
while (p.tokens.Count > 0 && p.NextSymbolIs(allValidTokenTypes.ToArray())) {
Token nextToken = p.ExpectSymbol(allValidTokenTypes.ToArray());
if (nextToken.type == TokenType.Number ||
nextToken.type == TokenType.Variable ||
nextToken.type == TokenType.String ||
nextToken.type == TokenType.True ||
nextToken.type == TokenType.False ||
nextToken.type == TokenType.Null) {
// Primitive values go straight onto the output
_expressionRPN.Enqueue (nextToken);
} else if (nextToken.type == TokenType.Identifier) {
operatorStack.Push (nextToken);
functionStack.Push (nextToken);
// next token must be a left paren, so process that immediately
nextToken = p.ExpectSymbol (TokenType.LeftParen);
// enter that sub-expression
operatorStack.Push (nextToken);
} else if (nextToken.type == TokenType.Comma) {
// Resolve this sub-expression before moving on to the
// next parameter
try {
// pop operators until we reach a left paren
while (operatorStack.Peek().type != TokenType.LeftParen) {
_expressionRPN.Enqueue(operatorStack.Pop());
}
} catch (InvalidOperationException) {
// we reached the end of the stack prematurely
// this means unbalanced parens!
throw ParseException.Make(nextToken, "Error parsing expression: " +
"unbalanced parentheses");
}
// We expect the top of the stack to now contain the left paren that
// began the list of parameters
if (operatorStack.Peek().type != TokenType.LeftParen) {
throw ParseException.Make (operatorStack.Peek (), "Expression parser got " +
"confused dealing with a function");
}
// The next token is not allowed to be a right-paren or a comma
// (that is, you can't say "foo(2,,)")
if (p.NextSymbolIs(TokenType.RightParen, TokenType.Comma)) {
throw ParseException.Make (p.tokens.Peek(), "Expected expression");
}
// Find the closest function on the stack
// and increment the number of parameters
functionStack.Peek().parameterCount++;
} else if (Operator.IsOperator(nextToken.type)) {
// This is an operator
// If this is a Minus, we need to determine if it's a
// unary minus or a binary minus.
// Unary minus looks like this: "-1"
// Binary minus looks like this: "2 - 3"
// Things get complex when we say stuff like "1 + -1".
// But it's easier when we realise that a minus
// is ONLY unary when the last token was a left paren,
// an operator, or it's the first token.
if (nextToken.type == TokenType.Minus) {
if (lastToken == null ||
lastToken.type == TokenType.LeftParen ||
Operator.IsOperator(lastToken.type)) {
// This is actually a unary minus.
nextToken.type = TokenType.UnaryMinus;
}
}
// We cannot assign values inside an expression. That is,
// saying "$foo = 2" in an express does not assign $foo to 2
// and then evaluate to 2. Instead, Yarn defines this
// to mean "$foo == 2"
if (nextToken.type == TokenType.EqualToOrAssign) {
nextToken.type = TokenType.EqualTo;
}
// O1 = this operator
// O2 = the token at the top of the stack
// While O2 is an operator, and EITHER: 1. O1 is left-associative and
// has precedence <= O2, or 2. O1 is right-associative and
// has precedence > O2:
while (ShouldApplyPrecedence(nextToken.type, operatorStack)) {
var o = operatorStack.Pop();
_expressionRPN.Enqueue(o);
}
operatorStack.Push(nextToken);
} else if (nextToken.type == TokenType.LeftParen) {
// Record that we have entered a paren-delimited
// subexpression
operatorStack.Push(nextToken);
} else if (nextToken.type == TokenType.RightParen) {
// We're leaving a subexpression; time to resolve the
// order of operations that we saw in between the parens.
try {
// pop operators until we reach a left paren
while (operatorStack.Peek().type != TokenType.LeftParen) {
_expressionRPN.Enqueue(operatorStack.Pop());
}
// pop the left paren
operatorStack.Pop();
} catch (InvalidOperationException) {
// we reached the end of the stack prematurely
// this means unbalanced parens!
throw ParseException.Make(nextToken, "Error parsing expression: unbalanced parentheses");
}
if (operatorStack.Peek().type == TokenType.Identifier) {
// This whole paren-delimited subexpression is actually
// a function call
// If the last token was a left-paren, then this
// was a function with no parameters; otherwise, we
// have an additional parameter (on top of the ones we counted
// while encountering commas)
if (lastToken.type != TokenType.LeftParen) {
functionStack.Peek ().parameterCount++;
}
_expressionRPN.Enqueue(operatorStack.Pop());
functionStack.Pop ();
}
}
// Record this as the last token we saw; we'll use
// this to figure out if minuses are unary or not
lastToken = nextToken;
}
// No more tokens; pop all operators onto the output queue
while (operatorStack.Count > 0) {
_expressionRPN.Enqueue(operatorStack.Pop());
}
// If the output queue is empty, then this is not an expression
if (_expressionRPN.Count == 0) {
throw new ParseException ("Error parsing expression: no expression found!");
}
// We've now got this in more easily parsed RPN form;
// time to build the expression tree.
Token firstToken = _expressionRPN.Peek();
var evaluationStack = new Stack<Expression>();
while (_expressionRPN.Count > 0) {
var next = _expressionRPN.Dequeue();
if (Operator.IsOperator(next.type)) {
// This is an operation
var info = Operator.InfoForOperator(next.type);
if (evaluationStack.Count < info.arguments) {
throw ParseException.Make(next, "Error parsing expression: not enough " +
"arguments for operator "+next.type.ToString());
}
var parameters = new List<Expression> ();
for (int i = 0; i < info.arguments; i++) {
parameters.Add (evaluationStack.Pop ());
}
parameters.Reverse ();
var operatorFunc = p.library.GetFunction (next.type.ToString());
var expr = new Expression (parent, operatorFunc, parameters);
evaluationStack.Push(expr);
} else if (next.type == TokenType.Identifier) {
// This is a function call
var info = p.library.GetFunction(next.value as String);
// Ensure that this call has the right number of params
if (info.IsParameterCountCorrect(next.parameterCount) == false) {
string error = string.Format("Error parsing expression: " +
"Unsupported number of parameters for function {0} (expected {1}, got {2})",
next.value as String,
info.paramCount,
next.parameterCount
);
throw ParseException.Make(next, error);
}
var parameterList = new List<Expression> ();
for (int i = 0; i < next.parameterCount; i++) {
parameterList.Add (evaluationStack.Pop());
}
parameterList.Reverse ();
var expr = new Expression (parent, info, parameterList);
evaluationStack.Push (expr);
} else {
// This is a raw value
var v = new ValueNode(parent, next);
Expression expr = new Expression(parent, v);
evaluationStack.Push(expr);
}
}
// We should now have a single expression in this stack, which is the root
// of the expression's tree. If we have more than one, then we have a problem.
if (evaluationStack.Count != 1) {
throw ParseException.Make(firstToken, "Error parsing expression " +
"(stack did not reduce correctly)");
}
// Return it
return evaluationStack.Pop ();
}
// Used to determine whether the shunting-yard algorithm should pop operators from
// the operator stack.
private static bool ShouldApplyPrecedence(TokenType o1, Stack<Token> operatorStack) {
if (operatorStack.Count == 0) {
return false;
}
if (Operator.IsOperator (o1) == false) {
throw new ParseException ("Internal error parsing expression");
}
TokenType o2 = operatorStack.Peek ().type;
if (Operator.IsOperator (o2) == false)
return false;
var o1Info = Operator.InfoForOperator (o1);
var o2Info = Operator.InfoForOperator (o2);
if (o1Info.associativity == Operator.Associativity.Left && o1Info.precedence <= o2Info.precedence) {
return true;
}
if (o1Info.associativity == Operator.Associativity.Right && o1Info.precedence < o2Info.precedence) {
return true;
}
return false;
}
internal override string PrintTree (int indentLevel)
{
var stringBuilder = new StringBuilder ();
switch (type) {
case Type.Value:
return value.PrintTree (indentLevel);
case Type.FunctionCall:
if (parameters.Count == 0) {
stringBuilder.Append(Tab(indentLevel, "Function call to " + function.name + " (no parameters)"));
} else {
stringBuilder.Append(Tab(indentLevel, "Function call to " + function.name + " (" +parameters.Count+" parameters) {"));
foreach (var param in parameters) {
stringBuilder.Append(param.PrintTree(indentLevel+1));
}
stringBuilder.Append(Tab(indentLevel, "}"));
}
return stringBuilder.ToString();
}
return Tab(indentLevel, "<error printing expression!>");
}
}
// AssignmentStatements are things like <<set $foo = 1>>
// AssignmentStatement = BeginCommand Set <variable> <operation> Expression EndCommand
internal class AssignmentStatement : ParseNode {
internal static bool CanParse (Parser p)
{
return p.NextSymbolsAre (TokenType.BeginCommand, TokenType.Set);
}
internal string destinationVariableName { get; private set; }
internal Expression valueExpression { get; private set; }
internal TokenType operation { get; private set; }
private static TokenType[] validOperators = {
TokenType.EqualToOrAssign,
TokenType.AddAssign,
TokenType.MinusAssign,
TokenType.DivideAssign,
TokenType.MultiplyAssign
};
internal AssignmentStatement(ParseNode parent, Parser p) : base(parent, p) {
p.ExpectSymbol(TokenType.BeginCommand);
p.ExpectSymbol(TokenType.Set);
destinationVariableName = p.ExpectSymbol(TokenType.Variable).value as string;
operation = p.ExpectSymbol(validOperators).type;
valueExpression = Expression.Parse(this, p);
p.ExpectSymbol(TokenType.EndCommand);
}
internal override string PrintTree (int indentLevel)
{
var sb = new StringBuilder ();
sb.Append (Tab(indentLevel, "Set:"));
sb.Append (Tab(indentLevel+1, destinationVariableName));
sb.Append (Tab (indentLevel+1, operation.ToString()));
sb.Append (valueExpression.PrintTree (indentLevel + 1));
return sb.ToString ();
}
}
// Operators are used in expressions - things like + - / * != neq
internal class Operator : ParseNode {
internal TokenType operatorType { get; private set; }
internal enum Associativity {
Left, // resolve leftmost operand first
Right, // resolve rightmost operand first
None // special-case (like "(", ")", ","
}
// Info used during expression parsing
internal struct OperatorInfo {
internal Associativity associativity;
internal int precedence;
internal int arguments;
internal OperatorInfo(Associativity associativity, int precedence, int arguments) {
this.associativity = associativity;
this.precedence = precedence;
this.arguments = arguments;
}
}
internal static OperatorInfo InfoForOperator(TokenType op) {
if (Array.IndexOf(operatorTypes, op) == -1) {
throw new ParseException (op.ToString () + " is not a valid operator");
}
// Determine the precendence, associativity and
// number of operands that each operator has.
switch (op) {
case TokenType.Not:
case TokenType.UnaryMinus:
return new OperatorInfo (Associativity.Right, 30, 1);
case TokenType.Multiply:
case TokenType.Divide:
return new OperatorInfo(Associativity.Left, 20,2);
case TokenType.Add:
case TokenType.Minus:
return new OperatorInfo(Associativity.Left, 15,2);
case TokenType.GreaterThan:
case TokenType.LessThan:
case TokenType.GreaterThanOrEqualTo:
case TokenType.LessThanOrEqualTo:
return new OperatorInfo(Associativity.Left, 10,2);
case TokenType.EqualTo:
case TokenType.EqualToOrAssign:
case TokenType.NotEqualTo:
return new OperatorInfo(Associativity.Left, 5,2);
case TokenType.And:
return new OperatorInfo(Associativity.Left, 4,2);
case TokenType.Or:
return new OperatorInfo(Associativity.Left, 3,2);
case TokenType.Xor:
return new OperatorInfo(Associativity.Left, 2,2);
}
throw new InvalidOperationException ();
}
internal static bool IsOperator(TokenType type) {
return Array.IndexOf (operatorTypes, type) != -1;
}
// Valid types of operators.
internal static TokenType[] operatorTypes {
get {
return new TokenType[] {
TokenType.Not,
TokenType.UnaryMinus,
TokenType.Add,
TokenType.Minus,
TokenType.Divide,
TokenType.Multiply,
TokenType.EqualToOrAssign,
TokenType.EqualTo,
TokenType.GreaterThan,
TokenType.GreaterThanOrEqualTo,
TokenType.LessThan,
TokenType.LessThanOrEqualTo,
TokenType.NotEqualTo,
TokenType.And,
TokenType.Or,
TokenType.Xor
};
}
}
internal Operator(ParseNode parent, TokenType t) : base(parent, null) {
operatorType = t;
}
internal Operator(ParseNode parent, Parser p) : base(parent, p) {
operatorType = p.ExpectSymbol(Operator.operatorTypes).type;
}
internal override string PrintTree (int indentLevel)
{
return Tab (indentLevel, operatorType.ToString ());
}
}
#endregion Parse Nodes
// Use a queue since we're continuously consuming them as
// we parse
Queue<Token> tokens;
Library library;
// Take whatever we were given and make a queue out of it
internal Parser(ICollection<Token> tokens, Library library) {
this.tokens = new Queue<Token>(tokens);
this.library = library;
}
internal Node Parse() {
// Kick off the parsing process by trying to parse a whole node
return new Node("Start", null, this);
}
// Returns true if the next symbol is one of 'validTypes'
bool NextSymbolIs(params TokenType[] validTypes) {
var t = this.tokens.Peek().type;
foreach (var validType in validTypes) {
if (t == validType) {
return true;
}
}
return false;
}
// Returns true if the next symbols are of the same type as
// 'validTypes' - this is used to look further ahead in the
// token stream, eg when we're looking for '<<' 'else'
bool NextSymbolsAre(params TokenType[] validTypes) {
var tempQueue = new Queue<Token> (tokens);
foreach (var type in validTypes) {
if (tempQueue.Dequeue ().type != type)
return false;
}
return true;
}
// Return the next token, which must be of type 'type',
// or throw an exception
Token ExpectSymbol(TokenType type) {
var t = this.tokens.Dequeue();
if (t.type != type) {
throw ParseException.Make(t, type);
}
return t;
}
// Return the next token, which can be of any type except EndOfInput.
Token ExpectSymbol() {
var token = this.tokens.Dequeue ();
if (token.type == TokenType.EndOfInput) {
throw ParseException.Make (token, "Unexpected end of input");
}
return token;
}
// Return the next token, which must be one of 'validTypes',
// or throw an exception
Token ExpectSymbol(params TokenType[] validTypes) {
var t = this.tokens.Dequeue();
foreach (var validType in validTypes) {
if (t.type == validType) {
return t;
}
}
throw ParseException.Make(t, validTypes);
}
}
}
| |
using System;
using System.Linq;
using System.Text.RegularExpressions;
using cstsd.Core.Extensions;
using cstsd.Core.Net;
using cstsd.Core.Ts;
using System.Collections.Generic;
using cstsd.TypeScript.Extensions;
namespace cstsd.TypeScript
{
public class NetTsControllerConverter : NetTsConverter
{
public virtual TsModule GetControllerTsModule(NetClass controllerNetClass)
{
var controllerMethods = controllerNetClass
.Methods
.ToList();
var ajaxMethods = controllerMethods
.Where(m => m.ReturnType.UnwrapTaskType().Name != "IActionResult")
.Where(m => m.IsPublic && m.Attributes.Any(a => a == "TsExport"))
.Select(a => GetControllerExecFunction(a, controllerNetClass.Name))
.ToArray();
var httpMethods = controllerMethods
.Where(m => m.ReturnType.UnwrapTaskType().Name == "IActionResult")
.Where(m => m.IsPublic && m.Attributes.Any(a => a == "TsExport"))
.Select(a => GetControllerNavigateFunction(a, controllerNetClass.Name))
.ToArray();
return new TsModule
{
Name = controllerNetClass.Name,
FunctionDeclarations = httpMethods.Concat(ajaxMethods).ToArray(),
FieldDeclarations = GetFields(controllerMethods, controllerNetClass),
IsExport = true
};
}
public static string GetControllerName(string controllerName)
{
if (controllerName.EndsWith("Controller"))
return controllerName.Substring(0, controllerName.Length - "Controller".Length);
return controllerName;
}
public List<TsFieldDeclaration> GetFields(List<NetMethod> controllerMethods, NetClass controllerNetClass)
{
var distinctControllerMethods = controllerMethods.Select(m => m.Name)
.Distinct()
.GroupJoin(
controllerMethods,
name => name,
netMethod => netMethod.Name,
(name, netMethods) => netMethods.First());
var urlStringFields =
distinctControllerMethods.Select(m => GetUrlNavigateConstFieldDeclaration(m, controllerNetClass));
var routeDataFields =
distinctControllerMethods.Select(m => GetRouteDataFieldDeclaration(m, controllerNetClass));
return urlStringFields.Union(routeDataFields).ToList();
}
public TsFunction GetControllerExecFunction(NetMethod netMethod, string controllerName)
{
var a = base.GetTsFunction(netMethod);
var functionReturnType = GetTsType(netMethod.ReturnType).Name;
a.ReturnType = new TsType
{
Name = "JQueryXHR"
};
var actionType = netMethod.Attributes.Any(attr => string.Equals(attr, "HttpGet", StringComparison.InvariantCultureIgnoreCase)) ? "GET" : "POST";
actionType = netMethod.Attributes.Any(attr => string.Equals(attr, "HttpPost", StringComparison.InvariantCultureIgnoreCase)) ? "POST" : actionType;
//a.FunctionBody = $"/* controller: {controllerNetClass.Name}; action: {netMethod.Name} */";
var dataParametersString = GetDataParametersString(a);
//last function parameter is always a callback
a.Parameters.Add(new TsParameter
{
FieldType = new TsType
{
Name = $"(response: {functionReturnType}) => void"
},
Name = "callback"
});
a.FunctionBody =
@"return frameworkExec({
url: " + $"{controllerName}.{netMethod.Name}Url" + @",
data: {
" + dataParametersString.Indent("\t\t") + @"
},
type: """ + actionType + @""",
callback: callback
});";
return a;
}
public static string GetDataParametersString(TsFunction tsFunction)
{
var dataParametersString = string.Join(",\r\n", tsFunction.Parameters.Select(p => $"{p.Name}: {p.Name}"));
return dataParametersString;
}
public TsFunction GetControllerNavigateFunction(NetMethod netMethod, string controllerName)
{
var tsFunction = GetTsFunction(netMethod);
tsFunction.ReturnType = new TsType
{
Name = "void"
};
var actionName = netMethod.Name;
var dataParametersString = GetDataParametersString(tsFunction);
tsFunction.FunctionBody =
@"return frameworkNavigate({
route: " + $"this.{actionName}Route" + @",
data: {
" + dataParametersString.Indent("\t\t") + @"
}
});";
return tsFunction;
}
public TsFieldDeclaration GetUrlNavigateConstFieldDeclaration(NetMethod netMethod, NetClass controllerNetClass)
{
var route = GetRouteInfo(controllerNetClass, netMethod);
var a = new TsFieldDeclaration
{
DefaultValue = "\"" + route.Url + "\"",
FieldDeclarationType = FieldDeclarationType.Const,
FieldType = new TsType { Name = "string" },
IsStatic = true,
Name = netMethod.Name + "Url"
};
return a;
}
public TsFieldDeclaration GetRouteDataFieldDeclaration(NetMethod netMethod, NetClass controllerNetClass)
{
var routeStr = GetRouteDataFieldDeclarationString(netMethod, controllerNetClass);
var a = new TsFieldDeclaration
{
DefaultValue = routeStr,
FieldDeclarationType = FieldDeclarationType.Const,
FieldType = new TsType { Name = "IRouteData" },
IsStatic = true,
Name = netMethod.Name + "Route"
};
return a;
}
public static string GetRouteDataFieldDeclarationString(NetMethod netMethod, NetClass controllerNetClass)
{
var route = GetRouteInfo(controllerNetClass, netMethod);
var r =
$@"{{
baseUrl: '/',
controller: '{route.Controller}',
action: '{route.Action}'
}}";
return r;
}
public static RouteInfo GetRouteInfo(NetClass controllerNetClass, NetMethod netMethod)
{
var controllerName = GetControllerName(controllerNetClass.Name);
var actionName = netMethod.Name;
var routeInfo = controllerNetClass.Attributes.FirstOrDefault(attr => attr.StartsWith("Route"));
if (string.IsNullOrWhiteSpace(routeInfo))
{
routeInfo = "[controller]/[action]";
}
else
{
var m = Regex.Match(routeInfo, "\"(.*?)\"");
if (m.Success && m.Groups.Count > 1 && m.Groups[1].Success)
{
routeInfo = m.Groups[1].Value;
}
}
var route = routeInfo
.Replace("[controller]", controllerName)
.Replace("[action]", actionName);
if (!route.StartsWith("/"))
route = "/" + route;
return new RouteInfo
{
Url = route,
Controller = controllerName,
Action = actionName
};
}
public class RouteInfo
{
public string Controller { get; set; }
public string Action { get; set; }
public string Url { get; set; }
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.World.Land
{
/// <summary>
/// Keeps track of a specific piece of land's information
/// </summary>
public class LandObject : ILandObject
{
#region Member Variables
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private const int landArrayMax = ((int)((int)Constants.RegionSize / 4) >= 64) ? (int)((int)Constants.RegionSize / 4) : 64;
private bool[,] m_landBitmap = new bool[landArrayMax,landArrayMax];
protected LandData m_landData = new LandData();
protected Scene m_scene;
protected List<SceneObjectGroup> primsOverMe = new List<SceneObjectGroup>();
public bool[,] landBitmap
{
get { return m_landBitmap; }
set { m_landBitmap = value; }
}
#endregion
#region ILandObject Members
public LandData landData
{
get { return m_landData; }
set { m_landData = value; }
}
public UUID regionUUID
{
get { return m_scene.RegionInfo.RegionID; }
}
#region Constructors
public LandObject(UUID owner_id, bool is_group_owned, Scene scene)
{
m_scene = scene;
landData.OwnerID = owner_id;
landData.IsGroupOwned = is_group_owned;
}
#endregion
#region Member Functions
#region General Functions
/// <summary>
/// Checks to see if this land object contains a point
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns>Returns true if the piece of land contains the specified point</returns>
public bool containsPoint(int x, int y)
{
if (x >= 0 && y >= 0 && x <= Constants.RegionSize && x <= Constants.RegionSize)
{
return (landBitmap[x / 4, y / 4] == true);
}
else
{
return false;
}
}
public ILandObject Copy()
{
ILandObject newLand = new LandObject(landData.OwnerID, landData.IsGroupOwned, m_scene);
//Place all new variables here!
newLand.landBitmap = (bool[,]) (landBitmap.Clone());
newLand.landData = landData.Copy();
return newLand;
}
static overrideParcelMaxPrimCountDelegate overrideParcelMaxPrimCount;
static overrideSimulatorMaxPrimCountDelegate overrideSimulatorMaxPrimCount;
public void setParcelObjectMaxOverride(overrideParcelMaxPrimCountDelegate overrideDel)
{
overrideParcelMaxPrimCount = overrideDel;
}
public void setSimulatorObjectMaxOverride(overrideSimulatorMaxPrimCountDelegate overrideDel)
{
overrideSimulatorMaxPrimCount = overrideDel;
}
public int getParcelMaxPrimCount(ILandObject thisObject)
{
if (overrideParcelMaxPrimCount != null)
{
return overrideParcelMaxPrimCount(thisObject);
}
else
{
//Normal Calculations
return Convert.ToInt32(
Math.Round((Convert.ToDecimal(landData.Area) / Convert.ToDecimal(65536)) * m_scene.objectCapacity *
Convert.ToDecimal(m_scene.RegionInfo.RegionSettings.ObjectBonus))); ;
}
}
public int getSimulatorMaxPrimCount(ILandObject thisObject)
{
if (overrideSimulatorMaxPrimCount != null)
{
return overrideSimulatorMaxPrimCount(thisObject);
}
else
{
//Normal Calculations
return m_scene.objectCapacity;
}
}
#endregion
#region Packet Request Handling
public void sendLandProperties(int sequence_id, bool snap_selection, int request_result, IClientAPI remote_client)
{
IEstateModule estateModule = m_scene.RequestModuleInterface<IEstateModule>();
uint regionFlags = 336723974 & ~((uint)(RegionFlags.AllowLandmark | RegionFlags.AllowSetHome));
if (estateModule != null)
regionFlags = estateModule.GetRegionFlags();
// In a perfect world, this would have worked.
//
// if ((landData.Flags & (uint)ParcelFlags.AllowLandmark) != 0)
// regionFlags |= (uint)RegionFlags.AllowLandmark;
// if (landData.OwnerID == remote_client.AgentId)
// regionFlags |= (uint)RegionFlags.AllowSetHome;
remote_client.SendLandProperties(sequence_id,
snap_selection, request_result, landData,
(float)m_scene.RegionInfo.RegionSettings.ObjectBonus,
getParcelMaxPrimCount(this),
getSimulatorMaxPrimCount(this), regionFlags);
}
public void updateLandProperties(LandUpdateArgs args, IClientAPI remote_client)
{
if (m_scene.Permissions.CanEditParcel(remote_client.AgentId,this))
{
//Needs later group support
LandData newData = landData.Copy();
if (args.AuthBuyerID != newData.AuthBuyerID || args.SalePrice != newData.SalePrice)
{
if (m_scene.Permissions.CanSellParcel(remote_client.AgentId, this))
{
newData.AuthBuyerID = args.AuthBuyerID;
newData.SalePrice = args.SalePrice;
}
}
newData.Category = args.Category;
newData.Description = args.Desc;
newData.GroupID = args.GroupID;
newData.LandingType = args.LandingType;
newData.MediaAutoScale = args.MediaAutoScale;
newData.MediaID = args.MediaID;
newData.MediaURL = args.MediaURL;
newData.MusicURL = args.MusicURL;
newData.Name = args.Name;
newData.Flags = args.ParcelFlags;
newData.PassHours = args.PassHours;
newData.PassPrice = args.PassPrice;
newData.SnapshotID = args.SnapshotID;
newData.UserLocation = args.UserLocation;
newData.UserLookAt = args.UserLookAt;
m_scene.LandChannel.UpdateLandObject(landData.LocalID, newData);
sendLandUpdateToAvatarsOverMe();
}
}
public void updateLandSold(UUID avatarID, UUID groupID, bool groupOwned, uint AuctionID, int claimprice, int area)
{
LandData newData = landData.Copy();
newData.OwnerID = avatarID;
newData.GroupID = groupID;
newData.IsGroupOwned = groupOwned;
//newData.auctionID = AuctionID;
newData.ClaimDate = Util.UnixTimeSinceEpoch();
newData.ClaimPrice = claimprice;
newData.SalePrice = 0;
newData.AuthBuyerID = UUID.Zero;
newData.Flags &= ~(uint) (ParcelFlags.ForSale | ParcelFlags.ForSaleObjects | ParcelFlags.SellParcelObjects);
m_scene.LandChannel.UpdateLandObject(landData.LocalID, newData);
sendLandUpdateToAvatarsOverMe();
}
public void deedToGroup(UUID groupID)
{
LandData newData = landData.Copy();
newData.OwnerID = groupID;
newData.GroupID = groupID;
newData.IsGroupOwned = true;
m_scene.LandChannel.UpdateLandObject(landData.LocalID, newData);
sendLandUpdateToAvatarsOverMe();
}
public bool isEitherBannedOrRestricted(UUID avatar)
{
if (isBannedFromLand(avatar))
{
return true;
}
else if (isRestrictedFromLand(avatar))
{
return true;
}
return false;
}
public bool isBannedFromLand(UUID avatar)
{
if ((landData.Flags & (uint) ParcelFlags.UseBanList) > 0)
{
ParcelManager.ParcelAccessEntry entry = new ParcelManager.ParcelAccessEntry();
entry.AgentID = avatar;
entry.Flags = AccessList.Ban;
entry.Time = new DateTime();
if (landData.ParcelAccessList.Contains(entry))
{
//They are banned, so lets send them a notice about this parcel
return true;
}
}
return false;
}
public bool isRestrictedFromLand(UUID avatar)
{
if ((landData.Flags & (uint) ParcelFlags.UseAccessList) > 0)
{
ParcelManager.ParcelAccessEntry entry = new ParcelManager.ParcelAccessEntry();
entry.AgentID = avatar;
entry.Flags = AccessList.Access;
entry.Time = new DateTime();
if (!landData.ParcelAccessList.Contains(entry))
{
//They are not allowed in this parcel, but not banned, so lets send them a notice about this parcel
return true;
}
}
return false;
}
public void sendLandUpdateToClient(IClientAPI remote_client)
{
sendLandProperties(0, false, 0, remote_client);
}
public void sendLandUpdateToAvatarsOverMe()
{
List<ScenePresence> avatars = m_scene.GetAvatars();
ILandObject over = null;
for (int i = 0; i < avatars.Count; i++)
{
try
{
over =
m_scene.LandChannel.GetLandObject(Util.Clamp<int>((int)Math.Round(avatars[i].AbsolutePosition.X), 0, ((int)Constants.RegionSize - 1)),
Util.Clamp<int>((int)Math.Round(avatars[i].AbsolutePosition.Y), 0, ((int)Constants.RegionSize - 1)));
}
catch (Exception)
{
m_log.Warn("[LAND]: " + "unable to get land at x: " + Math.Round(avatars[i].AbsolutePosition.X) + " y: " +
Math.Round(avatars[i].AbsolutePosition.Y));
}
if (over != null)
{
if (over.landData.LocalID == landData.LocalID)
{
if (((over.landData.Flags & (uint)ParcelFlags.AllowDamage) != 0) && m_scene.RegionInfo.RegionSettings.AllowDamage)
avatars[i].Invulnerable = false;
else
avatars[i].Invulnerable = true;
sendLandUpdateToClient(avatars[i].ControllingClient);
}
}
}
}
#endregion
#region AccessList Functions
public List<UUID> createAccessListArrayByFlag(AccessList flag)
{
List<UUID> list = new List<UUID>();
foreach (ParcelManager.ParcelAccessEntry entry in landData.ParcelAccessList)
{
if (entry.Flags == flag)
{
list.Add(entry.AgentID);
}
}
if (list.Count == 0)
{
list.Add(UUID.Zero);
}
return list;
}
public void sendAccessList(UUID agentID, UUID sessionID, uint flags, int sequenceID,
IClientAPI remote_client)
{
if (flags == (uint) AccessList.Access || flags == (uint) AccessList.Both)
{
List<UUID> avatars = createAccessListArrayByFlag(AccessList.Access);
remote_client.SendLandAccessListData(avatars,(uint) AccessList.Access,landData.LocalID);
}
if (flags == (uint) AccessList.Ban || flags == (uint) AccessList.Both)
{
List<UUID> avatars = createAccessListArrayByFlag(AccessList.Ban);
remote_client.SendLandAccessListData(avatars, (uint)AccessList.Ban, landData.LocalID);
}
}
public void updateAccessList(uint flags, List<ParcelManager.ParcelAccessEntry> entries, IClientAPI remote_client)
{
LandData newData = landData.Copy();
if (entries.Count == 1 && entries[0].AgentID == UUID.Zero)
{
entries.Clear();
}
List<ParcelManager.ParcelAccessEntry> toRemove = new List<ParcelManager.ParcelAccessEntry>();
foreach (ParcelManager.ParcelAccessEntry entry in newData.ParcelAccessList)
{
if (entry.Flags == (AccessList)flags)
{
toRemove.Add(entry);
}
}
foreach (ParcelManager.ParcelAccessEntry entry in toRemove)
{
newData.ParcelAccessList.Remove(entry);
}
foreach (ParcelManager.ParcelAccessEntry entry in entries)
{
ParcelManager.ParcelAccessEntry temp = new ParcelManager.ParcelAccessEntry();
temp.AgentID = entry.AgentID;
temp.Time = new DateTime(); //Pointless? Yes.
temp.Flags = (AccessList)flags;
if (!newData.ParcelAccessList.Contains(temp))
{
newData.ParcelAccessList.Add(temp);
}
}
m_scene.LandChannel.UpdateLandObject(landData.LocalID, newData);
}
#endregion
#region Update Functions
public void updateLandBitmapByteArray()
{
landData.Bitmap = convertLandBitmapToBytes();
}
/// <summary>
/// Update all settings in land such as area, bitmap byte array, etc
/// </summary>
public void forceUpdateLandInfo()
{
updateAABBAndAreaValues();
updateLandBitmapByteArray();
}
public void setLandBitmapFromByteArray()
{
landBitmap = convertBytesToLandBitmap();
}
/// <summary>
/// Updates the AABBMin and AABBMax values after area/shape modification of the land object
/// </summary>
private void updateAABBAndAreaValues()
{
int min_x = 64;
int min_y = 64;
int max_x = 0;
int max_y = 0;
int tempArea = 0;
int x, y;
for (x = 0; x < 64; x++)
{
for (y = 0; y < 64; y++)
{
if (landBitmap[x, y] == true)
{
if (min_x > x) min_x = x;
if (min_y > y) min_y = y;
if (max_x < x) max_x = x;
if (max_y < y) max_y = y;
tempArea += 16; //16sqm peice of land
}
}
}
int tx = min_x * 4;
if (tx > ((int)Constants.RegionSize - 1))
tx = ((int)Constants.RegionSize - 1);
int ty = min_y * 4;
if (ty > ((int)Constants.RegionSize - 1))
ty = ((int)Constants.RegionSize - 1);
landData.AABBMin =
new Vector3((float) (min_x * 4), (float) (min_y * 4),
(float) m_scene.Heightmap[tx, ty]);
tx = max_x * 4;
if (tx > ((int)Constants.RegionSize - 1))
tx = ((int)Constants.RegionSize - 1);
ty = max_y * 4;
if (ty > ((int)Constants.RegionSize - 1))
ty = ((int)Constants.RegionSize - 1);
landData.AABBMax =
new Vector3((float) (max_x * 4), (float) (max_y * 4),
(float) m_scene.Heightmap[tx, ty]);
landData.Area = tempArea;
}
#endregion
#region Land Bitmap Functions
/// <summary>
/// Sets the land's bitmap manually
/// </summary>
/// <param name="bitmap">64x64 block representing where this land is on a map</param>
public void setLandBitmap(bool[,] bitmap)
{
if (bitmap.GetLength(0) != 64 || bitmap.GetLength(1) != 64 || bitmap.Rank != 2)
{
//Throw an exception - The bitmap is not 64x64
//throw new Exception("Error: Invalid Parcel Bitmap");
}
else
{
//Valid: Lets set it
landBitmap = bitmap;
forceUpdateLandInfo();
}
}
/// <summary>
/// Gets the land's bitmap manually
/// </summary>
/// <returns></returns>
public bool[,] getLandBitmap()
{
return landBitmap;
}
/// <summary>
/// Full sim land object creation
/// </summary>
/// <returns></returns>
public bool[,] basicFullRegionLandBitmap()
{
return getSquareLandBitmap(0, 0, (int) Constants.RegionSize, (int) Constants.RegionSize);
}
/// <summary>
/// Used to modify the bitmap between the x and y points. Points use 64 scale
/// </summary>
/// <param name="start_x"></param>
/// <param name="start_y"></param>
/// <param name="end_x"></param>
/// <param name="end_y"></param>
/// <returns></returns>
public bool[,] getSquareLandBitmap(int start_x, int start_y, int end_x, int end_y)
{
bool[,] tempBitmap = new bool[64,64];
tempBitmap.Initialize();
tempBitmap = modifyLandBitmapSquare(tempBitmap, start_x, start_y, end_x, end_y, true);
return tempBitmap;
}
/// <summary>
/// Change a land bitmap at within a square and set those points to a specific value
/// </summary>
/// <param name="land_bitmap"></param>
/// <param name="start_x"></param>
/// <param name="start_y"></param>
/// <param name="end_x"></param>
/// <param name="end_y"></param>
/// <param name="set_value"></param>
/// <returns></returns>
public bool[,] modifyLandBitmapSquare(bool[,] land_bitmap, int start_x, int start_y, int end_x, int end_y,
bool set_value)
{
if (land_bitmap.GetLength(0) != 64 || land_bitmap.GetLength(1) != 64 || land_bitmap.Rank != 2)
{
//Throw an exception - The bitmap is not 64x64
//throw new Exception("Error: Invalid Parcel Bitmap in modifyLandBitmapSquare()");
}
int x, y;
for (y = 0; y < 64; y++)
{
for (x = 0; x < 64; x++)
{
if (x >= start_x / 4 && x < end_x / 4
&& y >= start_y / 4 && y < end_y / 4)
{
land_bitmap[x, y] = set_value;
}
}
}
return land_bitmap;
}
/// <summary>
/// Join the true values of 2 bitmaps together
/// </summary>
/// <param name="bitmap_base"></param>
/// <param name="bitmap_add"></param>
/// <returns></returns>
public bool[,] mergeLandBitmaps(bool[,] bitmap_base, bool[,] bitmap_add)
{
if (bitmap_base.GetLength(0) != 64 || bitmap_base.GetLength(1) != 64 || bitmap_base.Rank != 2)
{
//Throw an exception - The bitmap is not 64x64
throw new Exception("Error: Invalid Parcel Bitmap - Bitmap_base in mergeLandBitmaps");
}
if (bitmap_add.GetLength(0) != 64 || bitmap_add.GetLength(1) != 64 || bitmap_add.Rank != 2)
{
//Throw an exception - The bitmap is not 64x64
throw new Exception("Error: Invalid Parcel Bitmap - Bitmap_add in mergeLandBitmaps");
}
int x, y;
for (y = 0; y < 64; y++)
{
for (x = 0; x < 64; x++)
{
if (bitmap_add[x, y])
{
bitmap_base[x, y] = true;
}
}
}
return bitmap_base;
}
/// <summary>
/// Converts the land bitmap to a packet friendly byte array
/// </summary>
/// <returns></returns>
private byte[] convertLandBitmapToBytes()
{
byte[] tempConvertArr = new byte[512];
byte tempByte = 0;
int x, y, i, byteNum = 0;
i = 0;
for (y = 0; y < 64; y++)
{
for (x = 0; x < 64; x++)
{
tempByte = Convert.ToByte(tempByte | Convert.ToByte(landBitmap[x, y]) << (i++ % 8));
if (i % 8 == 0)
{
tempConvertArr[byteNum] = tempByte;
tempByte = (byte) 0;
i = 0;
byteNum++;
}
}
}
return tempConvertArr;
}
private bool[,] convertBytesToLandBitmap()
{
bool[,] tempConvertMap = new bool[landArrayMax, landArrayMax];
tempConvertMap.Initialize();
byte tempByte = 0;
int x = 0, y = 0, i = 0, bitNum = 0;
for (i = 0; i < 512; i++)
{
tempByte = landData.Bitmap[i];
for (bitNum = 0; bitNum < 8; bitNum++)
{
bool bit = Convert.ToBoolean(Convert.ToByte(tempByte >> bitNum) & (byte) 1);
tempConvertMap[x, y] = bit;
x++;
if (x > 63)
{
x = 0;
y++;
}
}
}
return tempConvertMap;
}
#endregion
#region Object Select and Object Owner Listing
public void sendForceObjectSelect(int local_id, int request_type, List<UUID> returnIDs, IClientAPI remote_client)
{
if (m_scene.Permissions.CanEditParcel(remote_client.AgentId, this))
{
List<uint> resultLocalIDs = new List<uint>();
try
{
lock (primsOverMe)
{
foreach (SceneObjectGroup obj in primsOverMe)
{
if (obj.LocalId > 0)
{
if (request_type == LandChannel.LAND_SELECT_OBJECTS_OWNER && obj.OwnerID == landData.OwnerID)
{
resultLocalIDs.Add(obj.LocalId);
}
else if (request_type == LandChannel.LAND_SELECT_OBJECTS_GROUP && obj.GroupID == landData.GroupID && landData.GroupID != UUID.Zero)
{
resultLocalIDs.Add(obj.LocalId);
}
else if (request_type == LandChannel.LAND_SELECT_OBJECTS_OTHER &&
obj.OwnerID != remote_client.AgentId)
{
resultLocalIDs.Add(obj.LocalId);
}
else if (request_type == (int)ObjectReturnType.List && returnIDs.Contains(obj.OwnerID))
{
resultLocalIDs.Add(obj.LocalId);
}
}
}
}
} catch (InvalidOperationException)
{
m_log.Error("[LAND]: Unable to force select the parcel objects. Arr.");
}
remote_client.SendForceClientSelectObjects(resultLocalIDs);
}
}
/// <summary>
/// Notify the parcel owner each avatar that owns prims situated on their land. This notification includes
/// aggreagete details such as the number of prims.
///
/// </summary>
/// <param name="remote_client">
/// A <see cref="IClientAPI"/>
/// </param>
public void sendLandObjectOwners(IClientAPI remote_client)
{
if (m_scene.Permissions.CanEditParcel(remote_client.AgentId, this))
{
Dictionary<UUID, int> primCount = new Dictionary<UUID, int>();
List<UUID> groups = new List<UUID>();
lock (primsOverMe)
{
try
{
foreach (SceneObjectGroup obj in primsOverMe)
{
try
{
if (!primCount.ContainsKey(obj.OwnerID))
{
primCount.Add(obj.OwnerID, 0);
}
}
catch (NullReferenceException)
{
m_log.Info("[LAND]: " + "Got Null Reference when searching land owners from the parcel panel");
}
try
{
primCount[obj.OwnerID] += obj.PrimCount;
}
catch (KeyNotFoundException)
{
m_log.Error("[LAND]: Unable to match a prim with it's owner.");
}
if (obj.OwnerID == obj.GroupID && (!groups.Contains(obj.OwnerID)))
groups.Add(obj.OwnerID);
}
}
catch (InvalidOperationException)
{
m_log.Error("[LAND]: Unable to Enumerate Land object arr.");
}
}
remote_client.SendLandObjectOwners(landData, groups, primCount);
}
}
public Dictionary<UUID, int> getLandObjectOwners()
{
Dictionary<UUID, int> ownersAndCount = new Dictionary<UUID, int>();
lock (primsOverMe)
{
try
{
foreach (SceneObjectGroup obj in primsOverMe)
{
if (!ownersAndCount.ContainsKey(obj.OwnerID))
{
ownersAndCount.Add(obj.OwnerID, 0);
}
ownersAndCount[obj.OwnerID] += obj.PrimCount;
}
}
catch (InvalidOperationException)
{
m_log.Error("[LAND]: Unable to enumerate land owners. arr.");
}
}
return ownersAndCount;
}
#endregion
#region Object Returning
public void returnObject(SceneObjectGroup obj)
{
SceneObjectGroup[] objs = new SceneObjectGroup[1];
objs[0] = obj;
m_scene.returnObjects(objs, obj.OwnerID);
}
public void returnLandObjects(uint type, UUID[] owners, UUID[] tasks, IClientAPI remote_client)
{
Dictionary<UUID,List<SceneObjectGroup>> returns =
new Dictionary<UUID,List<SceneObjectGroup>>();
lock (primsOverMe)
{
if (type == (uint)ObjectReturnType.Owner)
{
foreach (SceneObjectGroup obj in primsOverMe)
{
if (obj.OwnerID == m_landData.OwnerID)
{
if (!returns.ContainsKey(obj.OwnerID))
returns[obj.OwnerID] =
new List<SceneObjectGroup>();
returns[obj.OwnerID].Add(obj);
}
}
}
else if (type == (uint)ObjectReturnType.Group && m_landData.GroupID != UUID.Zero)
{
foreach (SceneObjectGroup obj in primsOverMe)
{
if (obj.GroupID == m_landData.GroupID)
{
if (!returns.ContainsKey(obj.OwnerID))
returns[obj.OwnerID] =
new List<SceneObjectGroup>();
returns[obj.OwnerID].Add(obj);
}
}
}
else if (type == (uint)ObjectReturnType.Other)
{
foreach (SceneObjectGroup obj in primsOverMe)
{
if (obj.OwnerID != m_landData.OwnerID &&
(obj.GroupID != m_landData.GroupID ||
m_landData.GroupID == UUID.Zero))
{
if (!returns.ContainsKey(obj.OwnerID))
returns[obj.OwnerID] =
new List<SceneObjectGroup>();
returns[obj.OwnerID].Add(obj);
}
}
}
else if (type == (uint)ObjectReturnType.List)
{
List<UUID> ownerlist = new List<UUID>(owners);
foreach (SceneObjectGroup obj in primsOverMe)
{
if (ownerlist.Contains(obj.OwnerID))
{
if (!returns.ContainsKey(obj.OwnerID))
returns[obj.OwnerID] =
new List<SceneObjectGroup>();
returns[obj.OwnerID].Add(obj);
}
}
}
}
foreach (List<SceneObjectGroup> ol in returns.Values)
{
if (m_scene.Permissions.CanUseObjectReturn(this, type, remote_client, ol))
m_scene.returnObjects(ol.ToArray(), remote_client.AgentId);
}
}
#endregion
#region Object Adding/Removing from Parcel
public void resetLandPrimCounts()
{
landData.GroupPrims = 0;
landData.OwnerPrims = 0;
landData.OtherPrims = 0;
landData.SelectedPrims = 0;
lock (primsOverMe)
primsOverMe.Clear();
}
public void addPrimToCount(SceneObjectGroup obj)
{
UUID prim_owner = obj.OwnerID;
int prim_count = obj.PrimCount;
if (obj.IsSelected)
{
landData.SelectedPrims += prim_count;
}
else
{
if (prim_owner == landData.OwnerID)
{
landData.OwnerPrims += prim_count;
}
else if ((obj.GroupID == landData.GroupID ||
prim_owner == landData.GroupID) &&
landData.GroupID != UUID.Zero)
{
landData.GroupPrims += prim_count;
}
else
{
landData.OtherPrims += prim_count;
}
}
lock (primsOverMe)
primsOverMe.Add(obj);
}
public void removePrimFromCount(SceneObjectGroup obj)
{
lock (primsOverMe)
{
if (primsOverMe.Contains(obj))
{
UUID prim_owner = obj.OwnerID;
int prim_count = obj.PrimCount;
if (prim_owner == landData.OwnerID)
{
landData.OwnerPrims -= prim_count;
}
else if (obj.GroupID == landData.GroupID ||
prim_owner == landData.GroupID)
{
landData.GroupPrims -= prim_count;
}
else
{
landData.OtherPrims -= prim_count;
}
primsOverMe.Remove(obj);
}
}
}
#endregion
#endregion
#endregion
/// <summary>
/// Set the media url for this land parcel
/// </summary>
/// <param name="url"></param>
public void SetMediaUrl(string url)
{
landData.MediaURL = url;
sendLandUpdateToAvatarsOverMe();
}
/// <summary>
/// Set the music url for this land parcel
/// </summary>
/// <param name="url"></param>
public void SetMusicUrl(string url)
{
landData.MusicURL = url;
sendLandUpdateToAvatarsOverMe();
}
}
}
| |
using System;
using NUnit.Framework;
using IBatisNet.DataMapper.Test.Domain;
namespace IBatisNet.DataMapper.Test.NUnit.SqlMapTests
{
/// <summary>
/// Summary description for ResultClassTest.
/// </summary>
[TestFixture]
public class ResultClassTest : BaseTest
{
#region SetUp & TearDown
/// <summary>
/// SetUp
/// </summary>
[SetUp]
public void Init()
{
}
/// <summary>
/// TearDown
/// </summary>
[TearDown]
public void Dispose()
{ /* ... */ }
#endregion
#region Specific statement test
/// <summary>
/// Test a boolean resultClass
/// </summary>
[Test]
public void TestBoolean()
{
bool bit = (bool) sqlMap.QueryForObject("GetBoolean", 1);
Assert.AreEqual(true, bit);
}
/// <summary>
/// Test a boolean implicit resultClass
/// </summary>
[Test]
public void TestBooleanWithoutResultClass()
{
bool bit = Convert.ToBoolean(sqlMap.QueryForObject("GetBooleanWithoutResultClass", 1));
Assert.AreEqual(true, bit);
}
/// <summary>
/// Test a byte resultClass
/// </summary>
[Test]
public void TestByte()
{
byte letter = (byte) sqlMap.QueryForObject("GetByte", 1);
Assert.AreEqual(155, letter);
}
/// <summary>
/// Test a byte implicit resultClass
/// </summary>
[Test]
public void TestByteWithoutResultClass()
{
byte letter = Convert.ToByte(sqlMap.QueryForObject("GetByteWithoutResultClass", 1));
Assert.AreEqual(155, letter);
}
/// <summary>
/// Test a char resultClass
/// </summary>
[Test]
public void TestChar()
{
char letter = (char) sqlMap.QueryForObject("GetChar", 1);
Assert.AreEqual('a', letter);
}
/// <summary>
/// Test a char implicit resultClass
/// </summary>
[Test]
public void TestCharWithoutResultClass()
{
char letter = Convert.ToChar(sqlMap.QueryForObject("GetCharWithoutResultClass", 1));
Assert.AreEqual('a', letter);
}
/// <summary>
/// Test a DateTime resultClass
/// </summary>
[Test]
public void TestDateTime()
{
DateTime orderDate = (DateTime) sqlMap.QueryForObject("GetDate", 1);
System.DateTime date = new DateTime(2003, 2, 15, 8, 15, 00);
Assert.AreEqual(date.ToString(), orderDate.ToString());
}
/// <summary>
/// Test a DateTime implicit resultClass
/// </summary>
[Test]
public void TestDateTimeWithoutResultClass()
{
DateTime orderDate = Convert.ToDateTime(sqlMap.QueryForObject("GetDateWithoutResultClass", 1));
System.DateTime date = new DateTime(2003, 2, 15, 8, 15, 00);
Assert.AreEqual(date.ToString(), orderDate.ToString());
}
/// <summary>
/// Test a decimal resultClass
/// </summary>
[Test]
public void TestDecimal()
{
decimal price = (decimal) sqlMap.QueryForObject("GetDecimal", 1);
Assert.AreEqual((decimal)1.56, price);
}
/// <summary>
/// Test a decimal implicit resultClass
/// </summary>
[Test]
public void TestDecimalWithoutResultClass()
{
decimal price = Convert.ToDecimal(sqlMap.QueryForObject("GetDecimalWithoutResultClass", 1));
Assert.AreEqual((decimal)1.56, price);
}
/// <summary>
/// Test a double resultClass
/// </summary>
[Test]
public void TestDouble()
{
double price = (double) sqlMap.QueryForObject("GetDouble", 1);
Assert.AreEqual(99.5f, price);
}
/// <summary>
/// Test a double implicit resultClass
/// </summary>
[Test]
public void TestDoubleWithoutResultClass()
{
double price = Convert.ToDouble(sqlMap.QueryForObject("GetDoubleWithoutResultClass", 1));
Assert.AreEqual(99.5f, price);
}
/// <summary>
/// IBATISNET-25 Error applying ResultMap when using 'Guid' in resultClass
/// </summary>
[Test]
public void TestGuid()
{
Guid newGuid = new Guid("CD5ABF17-4BBC-4C86-92F1-257735414CF4");
Guid guid = (Guid) sqlMap.QueryForObject("GetGuid", 1);
Assert.AreEqual(newGuid, guid);
}
/// <summary>
/// Test a Guid implicit resultClass
/// </summary>
[Test]
public void TestGuidWithoutResultClass()
{
Guid newGuid = new Guid("CD5ABF17-4BBC-4C86-92F1-257735414CF4");
string guidString = Convert.ToString(sqlMap.QueryForObject("GetGuidWithoutResultClass", 1));
Guid guid = new Guid(guidString);
Assert.AreEqual(newGuid, guid);
}
/// <summary>
/// Test a int16 resultClass
/// </summary>
[Test]
public void TestInt16()
{
short integer = (short) sqlMap.QueryForObject("GetInt16", 1);
Assert.AreEqual(32111, integer);
}
/// <summary>
/// Test a int16 implicit resultClass
/// </summary>
[Test]
public void TestInt16WithoutResultClass()
{
short integer = Convert.ToInt16(sqlMap.QueryForObject("GetInt16WithoutResultClass", 1));
Assert.AreEqual(32111, integer);
}
/// <summary>
/// Test a int 32 resultClass
/// </summary>
[Test]
public void TestInt32()
{
int integer = (int) sqlMap.QueryForObject("GetInt32", 1);
Assert.AreEqual(999999, integer);
}
/// <summary>
/// Test a int 32 implicit resultClass
/// </summary>
[Test]
public void TestInt32WithoutResultClass()
{
int integer = Convert.ToInt32(sqlMap.QueryForObject("GetInt32WithoutResultClass", 1));
Assert.AreEqual(999999, integer);
}
/// <summary>
/// Test a int64 resultClass
/// </summary>
[Test]
public void TestInt64()
{
long bigInt = (long) sqlMap.QueryForObject("GetInt64", 1);
Assert.AreEqual(9223372036854775800, bigInt);
}
/// <summary>
/// Test a int64 implicit resultClass
/// </summary>
[Test]
public void TestInt64WithoutResultClass()
{
long bigInt = Convert.ToInt64(sqlMap.QueryForObject("GetInt64WithoutResultClass", 1));
Assert.AreEqual(9223372036854775800, bigInt);
}
/// <summary>
/// Test a single/float resultClass
/// </summary>
[Test]
public void TestSingle()
{
float price = (float)sqlMap.QueryForObject("GetSingle", 1);
Assert.AreEqual(92233.5, price);
}
/// <summary>
/// Test a single/float implicit resultClass
/// </summary>
[Test]
public void TestSingleWithoutResultClass()
{
double price = Convert.ToDouble(sqlMap.QueryForObject("GetSingleWithoutResultClass", 1));
Assert.AreEqual(92233.5, price);
}
/// <summary>
/// Test a string resultClass
/// </summary>
[Test]
public void TestString()
{
string cardType = sqlMap.QueryForObject("GetString", 1) as string;
Assert.AreEqual("VISA", cardType);
}
/// <summary>
/// Test a string implicit resultClass
/// </summary>
[Test]
public void TestStringWithoutResultClass()
{
string cardType = Convert.ToString(sqlMap.QueryForObject("GetStringWithoutResultClass", 1));
Assert.AreEqual("VISA", cardType);
}
/// <summary>
/// Test a TimeSpan resultClass
/// </summary>
[Test]
[Ignore("To do")]
public void TestTimeSpan()
{
Guid newGuid = Guid.NewGuid();;
Category category = new Category();
category.Name = "toto";
category.Guid = newGuid;
int key = (int)sqlMap.Insert("InsertCategory", category);
Guid guid = (Guid)sqlMap.QueryForObject("GetGuid", key);
Assert.AreEqual(newGuid, guid);
}
/// <summary>
/// Test a TimeSpan implicit resultClass
/// </summary>
[Test]
[Ignore("To do")]
public void TestTimeSpanWithoutResultClass()
{
}
#endregion
}
}
| |
namespace WixSharp
{
/// <summary>
/// Specifies predefined values for <see cref="Action.Step"/>,
/// which controls order of <c>Custom Action</c> to be executed.
/// <para><c>Before</c> or <c>After</c> switch for <c>Custom Action</c> is controlled by <see cref="When"/>.</para>
/// </summary>
public class Step
{
/// <summary>
/// A top-level action used for an administrative installation.
/// </summary>
public static Step ADMIN = new Step("ADMIN");
/// <summary>
/// A top-level action called to install or remove advertised components.
/// </summary>
public static Step ADVERTISE = new Step("ADVERTISE");
/// <summary>
/// Validates that the free space specified by AVAILABLEFREEREG exists in the registry.
/// </summary>
public static Step AllocateRegistrySpace = new Step("AllocateRegistrySpace");
/// <summary>
/// Searches for previous versions of products and determines that upgrades are installed.
/// </summary>
public static Step AppSearch = new Step("AppSearch");
/// <summary>
/// Binds executables to imported DLLs.
/// </summary>
public static Step BindImage = new Step("BindImage");
/// <summary>
/// Uses file signatures to validate that qualifying products are installed on a system before an upgrade installation is performed.
/// </summary>
public static Step CCPSearch = new Step("CCPSearch");
/// <summary>
/// Ends the internal installation costing process begun by the CostInitialize action.
/// </summary>
public static Step CostFinalize = new Step("CostFinalize");
/// <summary>
/// Starts the installation costing process.
/// </summary>
public static Step CostInitialize = new Step("CostInitialize");
/// <summary>
/// Creates empty folders for components.
/// </summary>
public static Step CreateFolders = new Step("CreateFolders");
/// <summary>
/// Creates shortcuts.
/// </summary>
public static Step CreateShortcuts = new Step("CreateShortcuts");
/// <summary>
/// Removes system services.
/// </summary>
public static Step DeleteServices = new Step("DeleteServices");
/// <summary>
/// Disables rollback for the remainder of the installation.
/// </summary>
public static Step DisableRollback = new Step("DisableRollback");
/// <summary>
/// Duplicates files installed by the InstallFiles action.
/// </summary>
public static Step DuplicateFiles = new Step("DuplicateFiles");
/// <summary>
/// Checks the EXECUTEACTION property to determine which top-level action begins the execution sequence, then runs that action.
/// </summary>
public static Step ExecuteAction = new Step("ExecuteAction");
/// <summary>
/// Initializes disk cost calculation with the installer. Disk costing is not finalized until the CostFinalize action is executed.
/// </summary>
public static Step FileCost = new Step("FileCost");
/// <summary>
/// Detects correspondence between the Upgrade table and installed products.
/// </summary>
public static Step FindRelatedProducts = new Step("FindRelatedProducts");
/// <summary>
/// Used in the action sequence to prompt the user for a restart of the system during the installation.
/// </summary>
public static Step ForceReboot = new Step("ForceReboot");
/// <summary>
/// A top-level action called to install or remove components.
/// </summary>
public static Step INSTALL = new Step("INSTALL");
/// <summary>
/// Copies the installer database to the administrative installation point.
/// </summary>
public static Step InstallAdminPackage = new Step("InstallAdminPackage");
/// <summary>
/// Runs a script containing all operations in the action sequence since either the start of the installation or the last InstallFinalize action. Does not end the transaction.
/// </summary>
public static Step InstallExecute = new Step("InstallExecute");
/// <summary>
/// Copies files from the source to the destination directory.
/// </summary>
public static Step InstallFiles = new Step("InstallFiles");
/// <summary>
/// Runs a script containing all operations in the action sequence since either the start of the installation or the last InstallFinalize action. Marks the end of a transaction.
/// </summary>
public static Step InstallFinalize = new Step("InstallFinalize");
/// <summary>
/// Marks the beginning of a transaction.
/// </summary>
public static Step InstallInitialize = new Step("InstallInitialize");
/// <summary>
/// The InstallSFPCatalogFile action installs the catalogs used by Windows Me for Windows File Protection.
/// </summary>
public static Step InstallSFPCatalogFile = new Step("InstallSFPCatalogFile");
/// <summary>
/// Verifies that all volumes with attributed costs have sufficient space for the installation.
/// </summary>
public static Step InstallValidate = new Step("InstallValidate");
/// <summary>
/// Processes the IsolatedComponent table
/// </summary>
public static Step IsolateComponents = new Step("IsolateComponents");
/// <summary>
/// Evaluates a set of conditional statements contained in the LaunchCondition table that must all evaluate to True before the installation can proceed.
/// </summary>
public static Step LaunchConditions = new Step("LaunchConditions");
/// <summary>
/// Migrates current feature states to the pending installation.
/// </summary>
public static Step MigrateFeatureStates = new Step("MigrateFeatureStates");
/// <summary>
/// Locates existing files and moves or copies those files to a new location.
/// </summary>
public static Step MoveFiles = new Step("MoveFiles");
/// <summary>
/// Configures a service for the system.
/// Windows Installer 4.5 and earlier: Not supported.
/// </summary>
public static Step MsiConfigureServices = new Step("MsiConfigureServices");
/// <summary>
/// Manages the advertisement of common language runtime assemblies and Win32 assemblies that are being installed.
/// </summary>
public static Step MsiPublishAssemblies = new Step("MsiPublishAssemblies");
/// <summary>
/// Manages the advertisement of common language runtime assemblies and Win32 assemblies that are being removed.
/// </summary>
public static Step MsiUnpublishAssemblies = new Step("MsiUnpublishAssemblies");
/// <summary>
/// Installs the ODBC drivers, translators, and data sources.
/// </summary>
public static Step InstallODBC = new Step("InstallODBC");
/// <summary>
/// Registers a service with the system.
/// </summary>
public static Step InstallServices = new Step("InstallServices");
/// <summary>
/// Queries the Patch table to determine which patches are applied to specific files and then performs the byte-wise patching of the files.
/// </summary>
public static Step PatchFiles = new Step("PatchFiles");
/// <summary>
/// Registers components, their key paths, and component clients.
/// </summary>
public static Step ProcessComponents = new Step("ProcessComponents");
/// <summary>
/// Advertises the components specified in the PublishComponent table.
/// </summary>
public static Step PublishComponents = new Step("PublishComponents");
/// <summary>
/// Writes the feature state of each feature into the system registry
/// </summary>
public static Step PublishFeatures = new Step("PublishFeatures");
/// <summary>
/// Publishes product information with the system.
/// </summary>
public static Step PublishProduct = new Step("PublishProduct");
/// <summary>
/// Manages the registration of COM class information with the system.
/// </summary>
public static Step RegisterClassInfo = new Step("RegisterClassInfo");
/// <summary>
/// The RegisterComPlus action registers COM+ applications.
/// </summary>
public static Step RegisterComPlus = new Step("RegisterComPlus");
/// <summary>
/// Registers extension related information with the system.
/// </summary>
public static Step RegisterExtensionInfo = new Step("RegisterExtensionInfo");
/// <summary>
/// Registers installed fonts with the system.
/// </summary>
public static Step RegisterFonts = new Step("RegisterFonts");
/// <summary>
/// Registers MIME information with the system.
/// </summary>
public static Step RegisterMIMEInfo = new Step("RegisterMIMEInfo");
/// <summary>
/// Registers product information with the installer and stores the installer database on the local computer.
/// </summary>
public static Step RegisterProduct = new Step("RegisterProduct");
/// <summary>
/// Registers OLE ProgId information with the system.
/// </summary>
public static Step RegisterProgIdInfo = new Step("RegisterProgIdInfo");
/// <summary>
/// Registers type libraries with the system.
/// </summary>
public static Step RegisterTypeLibraries = new Step("RegisterTypeLibraries");
/// <summary>
/// Registers user information to identify the user of a product.
/// </summary>
public static Step RegisterUser = new Step("RegisterUser");
/// <summary>
/// Deletes files installed by the DuplicateFiles action.
/// </summary>
public static Step RemoveDuplicateFiles = new Step("RemoveDuplicateFiles");
/// <summary>
/// Modifies the values of environment variables.
/// </summary>
public static Step RemoveEnvironmentStrings = new Step("RemoveEnvironmentStrings");
/// <summary>
/// Removes installed versions of a product.
/// </summary>
public static Step RemoveExistingProducts = new Step("RemoveExistingProducts");
/// <summary>
/// Removes files previously installed by the InstallFiles action.
/// </summary>
public static Step RemoveFiles = new Step("RemoveFiles");
/// <summary>
/// Removes empty folders linked to components set to be removed.
/// </summary>
public static Step RemoveFolders = new Step("RemoveFolders");
/// <summary>
/// Deletes .ini file information associated with a component specified in the IniFile table.
/// </summary>
public static Step RemoveIniValues = new Step("RemoveIniValues");
/// <summary>
/// Removes ODBC data sources, translators, and drivers.
/// </summary>
public static Step RemoveODBC = new Step("RemoveODBC");
/// <summary>
/// Removes an application's registry keys that were created from the Registry table..
/// </summary>
public static Step RemoveRegistryValues = new Step("RemoveRegistryValues");
/// <summary>
/// Manages the removal of an advertised shortcut whose feature is selected for uninstallation.
/// </summary>
public static Step RemoveShortcuts = new Step("RemoveShortcuts");
/// <summary>
/// Determines the source location and sets the SourceDir property.
/// </summary>
public static Step ResolveSource = new Step("ResolveSource");
/// <summary>
/// Uses file signatures to validate that qualifying products are installed on a system before an upgrade installation is performed.
/// </summary>
public static Step RMCCPSearch = new Step("RMCCPSearch");
/// <summary>
/// Prompts the user for a system restart at the end of the installation.
/// </summary>
public static Step ScheduleReboot = new Step("ScheduleReboot");
/// <summary>
/// Processes modules in the SelfReg table and registers them if they are installed.
/// </summary>
public static Step SelfRegModules = new Step("SelfRegModules");
/// <summary>
/// Unregisters the modules in the SelfReg table that are set to be uninstalled.
/// </summary>
public static Step SelfUnregModules = new Step("SelfUnregModules");
/// <summary>
/// Runs the actions in a table specified by the SEQUENCE property.
/// </summary>
public static Step SEQUENCE = new Step("SEQUENCE");
/// <summary>
/// Checks the system for existing ODBC drivers and sets target directory for new ODBC drivers.
/// </summary>
public static Step SetODBCFolders = new Step("SetODBCFolders");
/// <summary>
/// Starts system services.
/// </summary>
public static Step StartServices = new Step("StartServices");
/// <summary>
/// Stops system services.
/// </summary>
public static Step StopServices = new Step("StopServices");
/// <summary>
/// Manages the unadvertisement of components from the PublishComponent table and removes information about published components.
/// </summary>
public static Step UnpublishComponents = new Step("UnpublishComponents");
/// <summary>
/// Removes the selection-state and feature-component mapping information from the system registry.
/// </summary>
public static Step UnpublishFeatures = new Step("UnpublishFeatures");
/// <summary>
/// Manages the removal of COM classes from the system registry.
/// </summary>
public static Step UnregisterClassInfo = new Step("UnregisterClassInfo");
/// <summary>
/// The UnregisterComPlus action removes COM+ applications from the registry.
/// </summary>
public static Step UnregisterComPlus = new Step("UnregisterComPlus");
/// <summary>
/// Manages the removal of extension-related information from the system.
/// </summary>
public static Step UnregisterExtensionInfo = new Step("UnregisterExtensionInfo");
/// <summary>
/// Removes registration information about installed fonts from the system.
/// </summary>
public static Step UnregisterFonts = new Step("UnregisterFonts");
/// <summary>
/// Unregisters MIME-related information from the system registry.
/// </summary>
public static Step UnregisterMIMEInfo = new Step("UnregisterMIMEInfo");
/// <summary>
/// Manages the unregistration of OLE ProgId information with the system.
/// </summary>
public static Step UnregisterProgIdInfo = new Step("UnregisterProgIdInfo");
/// <summary>
/// Unregisters type libraries with the system.
/// </summary>
public static Step UnregisterTypeLibraries = new Step("UnregisterTypeLibraries");
/// <summary>
/// Sets ProductID property to the full product identifier.
/// </summary>
public static Step ValidateProductID = new Step("ValidateProductID");
/// <summary>
/// Modifies the values of environment variables.
/// </summary>
public static Step WriteEnvironmentStrings = new Step("WriteEnvironmentStrings");
/// <summary>
/// Writes .ini file information.
/// </summary>
public static Step WriteIniValues = new Step("WriteIniValues");
/// <summary>
/// Sets up registry information.
/// </summary>
public static Step WriteRegistryValues = new Step("WriteRegistryValues");
/// <summary>
/// The InstallExecuteAgain action runs a script containing all operations in the action sequence since either the start of the installation or the last InstallExecuteAgain action or the last InstallExecute action. The InstallExecute action updates the system without ending the transaction. InstallExecuteAgain performs the same operation as the InstallExecute action but should only be used after InstallExecute.
/// </summary>
public static Step InstallExecuteAgain = new Step("InstallExecuteAgain");
/// <summary>
/// <c>Custom Action</c> is to be executed before/after the previous action declared in <see cref="Project.Actions"/>.
/// </summary>
public static Step PreviousAction = new Step("PreviousAction");
/// <summary>
/// <c>Custom Action</c> is to be executed before/after the previous action item in <see cref="Project.Actions"/>.
/// If <c>Custom Action</c> is the first item in item in <see cref="Project.Actions"/> it will be executed before/after
/// MSI built-in <c>InstallFinalize</c> action.
/// </summary>
public static Step PreviousActionOrInstallFinalize = new Step("PreviousActionOrInstallFinalize"); //if first usage of a CA, same as "InstallFinalize"; otherwise same as "PreviousAction"
/// <summary>
/// <c>Custom Action</c> is to be executed before/after the previous action item in <see cref="Project.Actions"/>.
/// If <c>Custom Action</c> is the first item in item in <see cref="Project.Actions"/> it will be executed before/after
/// MSI built-in <c>InstallInitialize</c> action.
/// </summary>
public static Step PreviousActionOrInstallInitialize = new Step("PreviousActionOrInstallInitialize"); //if first usage of a CA, same as "InstallInitialize"; otherwise same as "PreviousAction"
/// <summary>
/// Initializes a new instance of the <see cref="Step"/> class.
/// </summary>
/// <param name="value">The value.</param>
public Step(string value)
{
Value = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="Step"/> class.
/// </summary>
/// <param name="value">The value.</param>
public Step(Step value)
{
Value = value.ToString();
}
/// <summary>
/// The string value of the Step object
/// </summary>
protected string Value;
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String" /> that represents this instance.
/// </returns>
public override string ToString()
{
return Value;
}
}
}
| |
/* 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.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using XenAdmin.Actions;
using XenAdmin.Network;
namespace XenAdmin.Dialogs
{
public partial class DialogWithProgress : XenDialogBase
{
private int dx = 0;
private bool shrunk = false;
List<Control> ProgressControls; //List of controls not to undock
Dictionary<Control, AnchorStyles> PreviousAnchors; //State of previous anchors (for resizing window)
/// <summary>
/// All dialog that extend this one MUST be set to the same size as this, otherwise layout will break.
/// If you want I different size, I suggest you do it in you derived forms on_load.
/// </summary>
/// <param name="connection"></param>
public DialogWithProgress(IXenConnection connection)
: base(connection)
{
InitializeComponent();
RegisterProgressControls();
}
public DialogWithProgress()
: base()
{
InitializeComponent();
RegisterProgressControls();
SucceededWithWarningDescription = String.Empty;
SucceededWithWarning = false;
}
private void RegisterProgressControls()
{
ProgressControls = new List<Control>();
ProgressControls.Add(this.ActionProgressBar);
ProgressControls.Add(this.ActionStatusLabel);
ProgressControls.Add(this.ProgressSeparator);
dx = ClientSize.Height - ProgressSeparator.Top;
}
private void Unanchor()
{
PreviousAnchors = new Dictionary<Control, AnchorStyles>();
foreach (Control control in Controls)
{
if (ProgressControls.Contains(control))
continue;
PreviousAnchors.Add(control, control.Anchor);
control.Anchor = AnchorStyles.Top | AnchorStyles.Left;
}
}
private void Reanchor()
{
foreach (Control control in Controls)
{
if (ProgressControls.Contains(control))
continue;
control.Anchor = PreviousAnchors[control];
}
}
protected void Shrink()
{
Program.AssertOnEventThread();
if (!shrunk)
{
shrunk = true;
//First, clear all the anchors.
Unanchor();
//Next, hide the progress bar and label
ClearAction();
ActionStatusLabel.Hide();
ActionProgressBar.Hide();
ProgressSeparator.Hide();
//Finnally, shrink the window and put the anchors back
MinimumSize = new Size(MinimumSize.Width, MinimumSize.Height - dx);
ClientSize = new Size(ClientSize.Width, ClientSize.Height - dx);
Reanchor();
}
}
protected void Grow(MethodInvoker afterwards)
{
Program.AssertOnEventThread();
if (shrunk)
{
shrunk = false;
//First, clear all the anchors.
Unanchor();
//Next, grow the window
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(delegate(object o, DoWorkEventArgs e)
{
int expectedHeight = ClientSize.Height + dx;
while (ClientSize.Height < expectedHeight)
{
Program.Invoke(this, delegate()
{
ClientSize = new Size(ClientSize.Width, (int) (((2.0 * ClientSize.Height) / 3.0) + (expectedHeight / 3.0) + 1.0));
});
Thread.Sleep(50);
}
});
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(delegate(object o, RunWorkerCompletedEventArgs e)
{
Program.Invoke(this, delegate()
{
MinimumSize = new Size(MinimumSize.Width, MinimumSize.Height + dx);
//and put the anchors back
Reanchor();
//Finnally, show the progress bar and label
ClearAction();
ActionStatusLabel.Show();
ActionProgressBar.Show();
ProgressSeparator.Show();
afterwards();
});
});
worker.RunWorkerAsync();
}
else
{
afterwards();
}
}
protected void FinalizeProgressControls(ActionBase action)
{
if (action == null)
return;
Program.AssertOnEventThread();
if (action.Succeeded)
{
if (SucceededWithWarning && !String.IsNullOrEmpty(SucceededWithWarningDescription))
SetActionLabelText(String.Format(Messages.X_WITH_WARNING_X, action.Description, SucceededWithWarningDescription), Color.OrangeRed);
else
SetActionLabelText(action.Description, Color.Green);
}
else
{
string text = action.Exception is CancelledException ? Messages.CANCELLED_BY_USER : action.Exception.Message;
SetActionLabelText(text, Color.Red);
}
}
protected bool SucceededWithWarning { private get; set; }
protected string SucceededWithWarningDescription { private get; set; }
private void SetActionLabelText(string text, Color color)
{
ExceptionToolTip.RemoveAll();
if (string.IsNullOrEmpty(text))
{
ActionStatusLabel.Text = "";
return;
}
// take first line, adding elipses if needed to show that text has been cut
string[] parts = text.Replace("\r", "").Split('\n');
string clippedText = parts[0];
if (parts.Length > 1)
clippedText = clippedText.AddEllipsis();
ActionStatusLabel.ForeColor = color;
ActionStatusLabel.Text = clippedText;
// use original text for tooltip
ExceptionToolTip.SetToolTip(ActionStatusLabel, text);
}
protected void UpdateProgressControls(ActionBase action)
{
if (action == null)
return;
Program.AssertOnEventThread();
SetActionLabelText(action.Description, SystemColors.ControlText);
ActionProgressBar.Value = action.PercentComplete;
}
private void ClearAction()
{
SetActionLabelText("", SystemColors.ControlText);
this.ActionProgressBar.Value = 0;
}
}
}
| |
#region
using System;
using System.Diagnostics;
using System.Threading;
using CodeToast;
using OpenGL;
using Tao.FreeGlut;
#endregion
namespace GameCore.Render.OpenGl4CSharp
{
public class RendererOpenGl4CSharp : RendererBase
{
/// <summary>
/// The initial form width and height.
/// </summary>
private int formWidth = 1280, formHeight = 720;
/// <summary>
/// The current form width and height.
/// </summary>
private int width = 1280, height = 720;
private RenderLayerGame layerGame;
private RenderLayerTextInfo layerInfo;
private RenderLayerHud layerHud;
private Stopwatch watch;
private bool fullscreen;
private bool exit;
private float fps = 30;
public Vector3 MouseWorld = Vector3.Zero;
public Vector2 MouseCoord = Vector2.Zero;
public RendererOpenGl4CSharp()
{
name = "RendererOpenGl4CSharp";
}
public override void Start()
{
Async.Do(delegate { StartOpenGl(); });
}
private void StartOpenGl()
{
exit = false;
Glut.glutInit();
Glut.glutInitDisplayMode(Glut.GLUT_DOUBLE | Glut.GLUT_DEPTH | Glut.GLUT_ALPHA | Glut.GLUT_STENCIL |
Glut.GLUT_MULTISAMPLE);
// http://www.lighthouse3d.com/cg-topics/glut-and-freeglut/
// Note: glutSetOption is only available with freeglut
Glut.glutSetOption(Glut.GLUT_ACTION_ON_WINDOW_CLOSE, Glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS);
Glut.glutInitWindowSize(width, height);
Glut.glutCreateWindow("OpenGL RendererOpenGl4CSharp");
Glut.glutIdleFunc(OnRenderFrame);
Glut.glutDisplayFunc(OnDisplay);
Glut.glutKeyboardFunc(OnKeyboardDown);
Glut.glutSpecialFunc(OnSpecialKeyboardDown);
Glut.glutKeyboardUpFunc(OnKeyboardUp);
Glut.glutSpecialUpFunc(OnSpecialKeyboardUp);
Glut.glutCloseFunc(OnClose);
Glut.glutReshapeFunc(OnReshape);
// add our mouse callbacks for this tutorial
Glut.glutMouseFunc(OnMouse);
Glut.glutMotionFunc(OnMove);
#region GL_VERSION
//this will return your version of opengl
int major, minor;
major = Gl.GetInteger(GetPName.MajorVersion);
minor = Gl.GetInteger(GetPName.MinorVersion);
Console.WriteLine("Major " + major + " Minor " + minor);
//you can also get your GLSL version, although not sure if it varies from the above
Console.WriteLine("GLSL " + Gl.GetString(StringName.ShadingLanguageVersion));
#endregion
Gl.Enable(EnableCap.DepthTest);
Gl.Enable(EnableCap.Blend);
Gl.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
layerGame = new RenderLayerGame(width, height, TheGameStatus, TheUserInput);
layerGame.OnLoad();
layerHud = new RenderLayerHud(width, height, TheGameStatus, TheUserInput);
layerHud.OnLoad();
layerInfo = new RenderLayerTextInfo(width, height, TheGameStatus, TheUserInput);
layerInfo.OnLoad();
watch = Stopwatch.StartNew();
Glut.glutMainLoop();
}
public override void Close()
{
exit = true;
Thread.Sleep(100);
// OnClose();
// Glut.glutLeaveMainLoop();
}
public override void MapLoaded()
{
Close();
// foreach (ObjObject aObjObject in theTileObjects)
// {
// aObjObject.Dispose();
// }
// theTileObjects = GetTileObjects();
Start();
}
private void OnDisplay()
{
}
private void OnRenderFrame()
{
if (exit)
{
Glut.glutLeaveMainLoop();
}
else
{
watch.Stop();
float deltaTime = (float) watch.ElapsedTicks/Stopwatch.Frequency;
float tempfps = 1.0f/deltaTime;
fps = fps*0.9f + tempfps*0.1f;
if (layerInfo.ShowInfo)
{
string tempText = string.Format(
"FPS: {0:0.00}, Mouse: [({1:0},{2:0}),{3:0.0},{4:0.0},{5:0.0}], Camera: [{6:0.0},{7:0.0},{8:0.0}]",
fps, MouseCoord.x, MouseCoord.y, MouseWorld.x, MouseWorld.y, MouseWorld.z,
layerGame.Camera.Position.x, layerGame.Camera.Position.y, layerGame.Camera.Position.z);
layerInfo.GameInfo = tempText;
}
// linear interpolate retained fps with this frames fps with a strong weighting to former.
watch.Restart();
// set camForward the viewport and clear the previous depth and color buffers
Gl.Viewport(0, 0, width, height);
Gl.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
layerGame.OnRenderFrame(deltaTime);
layerInfo.OnRenderFrame(deltaTime);
layerHud.OnRenderFrame(deltaTime);
Glut.glutSwapBuffers();
}
}
//GLvoid displayFPS(GLvoid)
//{
// static long lastTime = SDL_GetTicks();
// static long frames = 0;
// static GLfloat fps = 0.0f;
//
// int newTime = SDL_GetTicks();
//
// if (newTime - lastTime > 100)
// {
// float newFPS = (float)frames / float(newTime - lastTime) * 1000.0f;
//
// fps = (fps + newFPS) / 2.0f;
//
// //Show FPS in window title
// char title[80];
// sprintf(title, "OpenGl Demo - %.2f", fps);
// SDL_WM_SetCaption(title, NULL);
//
// lastTime = newTime;
// frames = 0;
// }
// frames++;
//}
private void OnReshape(int width, int height)
{
this.width = width;
this.height = height;
layerGame.OnReshape(width, height);
layerHud.OnReshape(width, height);
layerInfo.OnReshape(width, height);
}
private void OnClose()
{
layerGame.OnClose();
layerHud.OnClose();
layerInfo.OnClose();
}
#region Controls
private void OnMouse(int button, int state, int x, int y)
{
MouseCoord = new Vector2(x, y);
if (layerHud.OnMouse(button, state, x, y))
{
MouseWorld = layerHud.MouseWorld;
}
else
{
if (layerGame.OnMouse(button, state, x, y))
{
MouseWorld = layerGame.MouseWorld;
}
}
}
private void OnMove(int x, int y)
{
layerGame.OnMove(x, y);
}
private void OnSpecialKeyboardDown(int key, int x, int y)
{
layerGame.OnSpecialKeyboardDown(key, x, y);
}
private void OnSpecialKeyboardUp(int key, int x, int y)
{
layerGame.OnSpecialKeyboardUp(key, x, y);
}
private void OnKeyboardDown(byte key, int x, int y)
{
layerGame.OnKeyboardDown(key, x, y);
// else if (key == 27) Glut.glutLeaveMainLoop();
// else
// {
// // char c = Convert.ToChar(key);
// // string b = Encoding.ASCII.GetString(new byte[] { (byte)key });
// // Console.WriteLine("Key: " + key + " : " + b);
// // Console.WriteLine("Key: " + key);
// }
}
private void OnKeyboardUp(byte key, int x, int y)
{
if (key == 'f')
{
fullscreen = !fullscreen;
if (fullscreen)
{
Glut.glutFullScreen();
}
else
{
Glut.glutPositionWindow(0, 0);
Glut.glutReshapeWindow(formWidth, formHeight);
}
}
layerGame.OnKeyboardUp(key, x, y);
layerInfo.OnKeyboardUp(key, x, y);
}
#endregion
#region Sample Shader
public static string vertexShaderSource = @"
#version 330
uniform mat4 projection_matrix;
uniform mat4 modelview_matrix;
uniform mat4 view_matrix;
uniform float animation_factor;
in vec3 in_position;
in vec3 in_normal;
in vec2 in_uv;
out vec2 uv;
void main(void)
{
vec4 pos2 = projection_matrix * modelview_matrix * vec4(in_normal, 1);
vec4 pos1 = projection_matrix * modelview_matrix * vec4(in_position, 1);
uv = in_uv;
gl_Position = mix(pos2, pos1, animation_factor);
}";
public static string fragmentShaderSource = @"
#version 330
uniform sampler2D active_texture;
in vec2 uv;
out vec4 out_frag_color;
void main(void)
{
out_frag_color = mix(texture2D(active_texture, uv), vec4(1, 1, 1, 1), 0.05);
}";
#endregion
}
}
| |
using NUnit.Framework;
using System;
using System.Collections.Generic;
using Assert = Lucene.Net.TestFramework.Assert;
namespace Lucene.Net.Util
{
/*
* 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.
*/
[TestFixture]
public class TestMergedIterator : LuceneTestCase
{
private const int REPEATS = 2;
private const int VALS_TO_MERGE = 15000;
[Test]
public virtual void TestMergeEmpty()
{
IEnumerator<int> merged = new MergedEnumerator<int>();
Assert.IsFalse(merged.MoveNext());
merged = new MergedEnumerator<int>((new List<int>()).GetEnumerator());
Assert.IsFalse(merged.MoveNext());
IEnumerator<int>[] itrs = new IEnumerator<int>[Random.Next(100)];
for (int i = 0; i < itrs.Length; i++)
{
itrs[i] = (new List<int>()).GetEnumerator();
}
merged = new MergedEnumerator<int>(itrs);
Assert.IsFalse(merged.MoveNext());
}
[Test]
public virtual void TestNoDupsRemoveDups()
{
TestCase(1, 1, true);
}
[Test]
public virtual void TestOffItrDupsRemoveDups()
{
TestCase(3, 1, true);
}
[Test]
public virtual void TestOnItrDupsRemoveDups()
{
TestCase(1, 3, true);
}
[Test]
public virtual void TestOnItrRandomDupsRemoveDups()
{
TestCase(1, -3, true);
}
[Test]
public virtual void TestBothDupsRemoveDups()
{
TestCase(3, 3, true);
}
[Test]
public virtual void TestBothDupsWithRandomDupsRemoveDups()
{
TestCase(3, -3, true);
}
[Test]
public virtual void TestNoDupsKeepDups()
{
TestCase(1, 1, false);
}
[Test]
public virtual void TestOffItrDupsKeepDups()
{
TestCase(3, 1, false);
}
[Test]
public virtual void TestOnItrDupsKeepDups()
{
TestCase(1, 3, false);
}
[Test]
public virtual void TestOnItrRandomDupsKeepDups()
{
TestCase(1, -3, false);
}
[Test]
public virtual void TestBothDupsKeepDups()
{
TestCase(3, 3, false);
}
[Test]
public virtual void TestBothDupsWithRandomDupsKeepDups()
{
TestCase(3, -3, false);
}
private void TestCase(int itrsWithVal, int specifiedValsOnItr, bool removeDups)
{
// Build a random number of lists
IList<int?> expected = new List<int?>();
Random random = new Random(Random.Next());
int numLists = itrsWithVal + random.Next(1000 - itrsWithVal);
IList<int>[] lists = new IList<int>[numLists];
for (int i = 0; i < numLists; i++)
{
lists[i] = new List<int>();
}
int start = random.Next(1000000);
int end = start + VALS_TO_MERGE / itrsWithVal / Math.Abs(specifiedValsOnItr);
for (int i = start; i < end; i++)
{
int maxList = lists.Length;
int maxValsOnItr = 0;
int sumValsOnItr = 0;
for (int itrWithVal = 0; itrWithVal < itrsWithVal; itrWithVal++)
{
int list = random.Next(maxList);
int valsOnItr = specifiedValsOnItr < 0 ? (1 + random.Next(-specifiedValsOnItr)) : specifiedValsOnItr;
maxValsOnItr = Math.Max(maxValsOnItr, valsOnItr);
sumValsOnItr += valsOnItr;
for (int valOnItr = 0; valOnItr < valsOnItr; valOnItr++)
{
lists[list].Add(i);
}
maxList = maxList - 1;
ArrayUtil.Swap(lists, list, maxList);
}
int maxCount = removeDups ? maxValsOnItr : sumValsOnItr;
for (int count = 0; count < maxCount; count++)
{
expected.Add(i);
}
}
// Now check that they get merged cleanly
IEnumerator<int>[] itrs = new IEnumerator<int>[numLists];
for (int i = 0; i < numLists; i++)
{
itrs[i] = lists[i].GetEnumerator();
}
try
{
MergedEnumerator<int> mergedItr = new MergedEnumerator<int>(removeDups, itrs);
IEnumerator<int?> expectedItr = expected.GetEnumerator();
while (expectedItr.MoveNext())
{
Assert.IsTrue(mergedItr.MoveNext());
Assert.AreEqual(expectedItr.Current, mergedItr.Current);
}
Assert.IsFalse(mergedItr.MoveNext());
}
finally
{
IOUtils.Dispose(itrs);
}
}
[Test]
[Obsolete("This method will be removed in 4.8.0 release candidate.")]
public virtual void TestMergeEmptyIterator()
{
IEnumerator<int> merged = new MergedIterator<int>();
Assert.IsFalse(merged.MoveNext());
merged = new MergedIterator<int>((new List<int>()).GetEnumerator());
Assert.IsFalse(merged.MoveNext());
IEnumerator<int>[] itrs = new IEnumerator<int>[Random.Next(100)];
for (int i = 0; i < itrs.Length; i++)
{
itrs[i] = (new List<int>()).GetEnumerator();
}
merged = new MergedIterator<int>(itrs);
Assert.IsFalse(merged.MoveNext());
}
[Test]
[Obsolete("This method will be removed in 4.8.0 release candidate.")]
public virtual void TestNoDupsRemoveDupsIterator()
{
TestCaseIterator(1, 1, true);
}
[Test]
[Obsolete("This method will be removed in 4.8.0 release candidate.")]
public virtual void TestOffItrDupsRemoveDupsIterator()
{
TestCaseIterator(3, 1, true);
}
[Test]
[Obsolete("This method will be removed in 4.8.0 release candidate.")]
public virtual void TestOnItrDupsRemoveDupsIterator()
{
TestCaseIterator(1, 3, true);
}
[Test]
[Obsolete("This method will be removed in 4.8.0 release candidate.")]
public virtual void TestOnItrRandomDupsRemoveDupsIterator()
{
TestCaseIterator(1, -3, true);
}
[Test]
[Obsolete("This method will be removed in 4.8.0 release candidate.")]
public virtual void TestBothDupsRemoveDupsIterator()
{
TestCaseIterator(3, 3, true);
}
[Test]
[Obsolete("This method will be removed in 4.8.0 release candidate.")]
public virtual void TestBothDupsWithRandomDupsRemoveDupsIterator()
{
TestCaseIterator(3, -3, true);
}
[Test]
[Obsolete("This method will be removed in 4.8.0 release candidate.")]
public virtual void TestNoDupsKeepDupsIterator()
{
TestCaseIterator(1, 1, false);
}
[Test]
[Obsolete("This method will be removed in 4.8.0 release candidate.")]
public virtual void TestOffItrDupsKeepDupsIterator()
{
TestCaseIterator(3, 1, false);
}
[Test]
[Obsolete("This method will be removed in 4.8.0 release candidate.")]
public virtual void TestOnItrDupsKeepDupsIterator()
{
TestCaseIterator(1, 3, false);
}
[Test]
[Obsolete("This method will be removed in 4.8.0 release candidate.")]
public virtual void TestOnItrRandomDupsKeepDupsIterator()
{
TestCaseIterator(1, -3, false);
}
[Test]
[Obsolete("This method will be removed in 4.8.0 release candidate.")]
public virtual void TestBothDupsKeepDupsIterator()
{
TestCaseIterator(3, 3, false);
}
[Test]
[Obsolete("This method will be removed in 4.8.0 release candidate.")]
public virtual void TestBothDupsWithRandomDupsKeepDupsIterator()
{
TestCaseIterator(3, -3, false);
}
[Obsolete("This method will be removed in 4.8.0 release candidate.")]
private void TestCaseIterator(int itrsWithVal, int specifiedValsOnItr, bool removeDups)
{
// Build a random number of lists
IList<int?> expected = new List<int?>();
Random random = new Random(Random.Next());
int numLists = itrsWithVal + random.Next(1000 - itrsWithVal);
IList<int>[] lists = new IList<int>[numLists];
for (int i = 0; i < numLists; i++)
{
lists[i] = new List<int>();
}
int start = random.Next(1000000);
int end = start + VALS_TO_MERGE / itrsWithVal / Math.Abs(specifiedValsOnItr);
for (int i = start; i < end; i++)
{
int maxList = lists.Length;
int maxValsOnItr = 0;
int sumValsOnItr = 0;
for (int itrWithVal = 0; itrWithVal < itrsWithVal; itrWithVal++)
{
int list = random.Next(maxList);
int valsOnItr = specifiedValsOnItr < 0 ? (1 + random.Next(-specifiedValsOnItr)) : specifiedValsOnItr;
maxValsOnItr = Math.Max(maxValsOnItr, valsOnItr);
sumValsOnItr += valsOnItr;
for (int valOnItr = 0; valOnItr < valsOnItr; valOnItr++)
{
lists[list].Add(i);
}
maxList = maxList - 1;
ArrayUtil.Swap(lists, list, maxList);
}
int maxCount = removeDups ? maxValsOnItr : sumValsOnItr;
for (int count = 0; count < maxCount; count++)
{
expected.Add(i);
}
}
// Now check that they get merged cleanly
IEnumerator<int>[] itrs = new IEnumerator<int>[numLists];
for (int i = 0; i < numLists; i++)
{
itrs[i] = lists[i].GetEnumerator();
}
MergedIterator<int> mergedItr = new MergedIterator<int>(removeDups, itrs);
IEnumerator<int?> expectedItr = expected.GetEnumerator();
while (expectedItr.MoveNext())
{
Assert.IsTrue(mergedItr.MoveNext());
Assert.AreEqual(expectedItr.Current, mergedItr.Current);
}
Assert.IsFalse(mergedItr.MoveNext());
}
}
}
| |
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using Abp.Application.Editions;
using Abp.Application.Features;
using Abp.Auditing;
using Abp.Authorization.Roles;
using Abp.Authorization.Users;
using Abp.BackgroundJobs;
using Abp.EntityFramework.Extensions;
using Abp.MultiTenancy;
using Abp.Notifications;
namespace Abp.Zero.EntityFramework
{
/// <summary>
/// Base DbContext for ABP zero.
/// Derive your DbContext from this class to have base entities.
/// </summary>
public abstract class AbpZeroDbContext<TTenant, TRole, TUser, TSelf> : AbpZeroCommonDbContext<TRole, TUser, TSelf>
where TTenant : AbpTenant<TUser>
where TRole : AbpRole<TUser>
where TUser : AbpUser<TUser>
where TSelf : AbpZeroDbContext<TTenant, TRole, TUser, TSelf>
{
/// <summary>
/// Tenants
/// </summary>
public virtual DbSet<TTenant> Tenants { get; set; }
/// <summary>
/// Editions.
/// </summary>
public virtual DbSet<Edition> Editions { get; set; }
/// <summary>
/// FeatureSettings.
/// </summary>
public virtual DbSet<FeatureSetting> FeatureSettings { get; set; }
/// <summary>
/// TenantFeatureSetting.
/// </summary>
public virtual DbSet<TenantFeatureSetting> TenantFeatureSettings { get; set; }
/// <summary>
/// EditionFeatureSettings.
/// </summary>
public virtual DbSet<EditionFeatureSetting> EditionFeatureSettings { get; set; }
/// <summary>
/// Background jobs.
/// </summary>
public virtual DbSet<BackgroundJobInfo> BackgroundJobs { get; set; }
/// <summary>
/// User accounts
/// </summary>
public virtual DbSet<UserAccount> UserAccounts { get; set; }
/// <summary>
/// Notifications.
/// </summary>
public virtual DbSet<NotificationInfo> Notifications { get; set; }
protected AbpZeroDbContext()
{
}
protected AbpZeroDbContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
protected AbpZeroDbContext(DbCompiledModel model)
: base(model)
{
}
protected AbpZeroDbContext(DbConnection existingConnection, bool contextOwnsConnection)
: base(existingConnection, contextOwnsConnection)
{
}
protected AbpZeroDbContext(string nameOrConnectionString, DbCompiledModel model)
: base(nameOrConnectionString, model)
{
}
protected AbpZeroDbContext(ObjectContext objectContext, bool dbContextOwnsObjectContext)
: base(objectContext, dbContextOwnsObjectContext)
{
}
protected AbpZeroDbContext(DbConnection existingConnection, DbCompiledModel model, bool contextOwnsConnection)
: base(existingConnection, model, contextOwnsConnection)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
#region BackgroundJobInfo.IX_IsAbandoned_NextTryTime
modelBuilder.Entity<BackgroundJobInfo>()
.Property(e => e.IsAbandoned)
.CreateIndex("IX_IsAbandoned_NextTryTime", 1);
modelBuilder.Entity<BackgroundJobInfo>()
.Property(e => e.NextTryTime)
.CreateIndex("IX_IsAbandoned_NextTryTime", 2);
#endregion
#region TenantFeatureSetting.IX_TenantId_Name
modelBuilder.Entity<TenantFeatureSetting>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_Name", 1);
modelBuilder.Entity<TenantFeatureSetting>()
.Property(e => e.Name)
.CreateIndex("IX_TenantId_Name", 2);
#endregion
#region EditionFeatureSetting.IX_EditionId_Name
modelBuilder.Entity<EditionFeatureSetting>()
.Property(e => e.EditionId)
.CreateIndex("IX_EditionId_Name", 1);
modelBuilder.Entity<EditionFeatureSetting>()
.Property(e => e.Name)
.CreateIndex("IX_EditionId_Name", 2);
#endregion
#region TTenant.IX_TenancyName
modelBuilder.Entity<TTenant>()
.Property(e => e.TenancyName)
.CreateIndex("IX_TenancyName", 1);
#endregion
#region TTenant.Set_ForeignKeys
modelBuilder.Entity<TTenant>()
.HasOptional(p => p.DeleterUser)
.WithMany()
.HasForeignKey(p => p.DeleterUserId);
modelBuilder.Entity<TTenant>()
.HasOptional(p => p.CreatorUser)
.WithMany()
.HasForeignKey(p => p.CreatorUserId);
modelBuilder.Entity<TTenant>()
.HasOptional(p => p.LastModifierUser)
.WithMany()
.HasForeignKey(p => p.LastModifierUserId);
#endregion
#region UserAccount.IX_TenantId_UserId
modelBuilder.Entity<UserAccount>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_UserId", 1);
modelBuilder.Entity<UserAccount>()
.Property(e => e.UserId)
.CreateIndex("IX_TenantId_UserId", 2);
#endregion
#region UserAccount.IX_TenantId_UserName
modelBuilder.Entity<UserAccount>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_UserName", 1);
modelBuilder.Entity<UserAccount>()
.Property(e => e.UserName)
.CreateIndex("IX_TenantId_UserName", 2);
#endregion
#region UserAccount.IX_TenantId_EmailAddress
modelBuilder.Entity<UserAccount>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_EmailAddress", 1);
modelBuilder.Entity<UserAccount>()
.Property(e => e.EmailAddress)
.CreateIndex("IX_TenantId_EmailAddress", 2);
#endregion
#region UserAccount.IX_UserName
modelBuilder.Entity<UserAccount>()
.Property(e => e.UserName)
.CreateIndex("IX_UserName", 1);
#endregion
#region UserAccount.IX_EmailAddress
modelBuilder.Entity<UserAccount>()
.Property(e => e.EmailAddress)
.CreateIndex("IX_EmailAddress", 1);
#endregion
#region AuditLog.Set_MaxLengths
modelBuilder.Entity<AuditLog>()
.Property(e => e.ServiceName)
.HasMaxLength(AuditLog.MaxServiceNameLength);
modelBuilder.Entity<AuditLog>()
.Property(e => e.MethodName)
.HasMaxLength(AuditLog.MaxMethodNameLength);
modelBuilder.Entity<AuditLog>()
.Property(e => e.Parameters)
.HasMaxLength(AuditLog.MaxParametersLength);
modelBuilder.Entity<AuditLog>()
.Property(e => e.ClientIpAddress)
.HasMaxLength(AuditLog.MaxClientIpAddressLength);
modelBuilder.Entity<AuditLog>()
.Property(e => e.ClientName)
.HasMaxLength(AuditLog.MaxClientNameLength);
modelBuilder.Entity<AuditLog>()
.Property(e => e.BrowserInfo)
.HasMaxLength(AuditLog.MaxBrowserInfoLength);
modelBuilder.Entity<AuditLog>()
.Property(e => e.Exception)
.HasMaxLength(AuditLog.MaxExceptionLength);
modelBuilder.Entity<AuditLog>()
.Property(e => e.CustomData)
.HasMaxLength(AuditLog.MaxCustomDataLength);
#endregion
}
}
}
| |
using JeffFerguson.Gepsio.IoC;
using JeffFerguson.Gepsio.Validators.Xbrl2Dot1;
using JeffFerguson.Gepsio.Xml.Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace JeffFerguson.Gepsio
{
/// <summary>
/// A fragment of XBRL data. A collection of fragments is available in the <see cref="XbrlDocument"/>
/// class.
/// </summary>
/// <remarks>
/// <para>
/// An XBRL fragment is a fragment of XBRL data having an xbrl tag as its root. In the generic case,
/// an XBRL document will have an xbrl tag as the root tag of the XML document, and, in this case,
/// the entire XBRL document is one large XBRL fragment. However, section 4.1 of the XBRL 2.1 Specification
/// makes provisions for multiple XBRL fragments to be stored in a single document:
/// </para>
/// <para>
/// "If multiple 'data islands' of XBRL mark-up are included in a larger document, the xbrl element is
/// the container for each [fragment]."
/// </para>
/// <para>
/// Gepsio supports this notion by defining an XBRL document containing a collection of one or more
/// XBRL fragments, as in the following code sample:
/// </para>
/// <code>
/// var myDocument = new XbrlDocument();
/// myDocument.Load("myxbrldoc.xml");
/// foreach(var currentFragment in myDocument.XbrlFragments)
/// {
/// // XBRL data is available from the "currentFragment" variable
/// }
/// </code>
/// <para>
/// In the vast majority of cases, an XBRL document will be an XML document with the xbrl tag at its
/// root, and, as a result, the <see cref="XbrlDocument"/> uses to load the XBRL document will have
/// a single <see cref="XbrlFragment"/> in the document's fragments container. Consider, however, the
/// possibility of having more than one fragment in a document, in accordance of the text in section
/// 4.1 of the XBRL 2.1 Specification.
/// </para>
/// </remarks>
public class XbrlFragment
{
private LinkbaseDocumentCollection thisLinkbaseDocuments;
/// <summary>
/// The delegate used to handle events fired by the class.
/// </summary>
/// <param name="sender">
/// The sender of the event.
/// </param>
/// <param name="e">
/// Event arguments.
/// </param>
public delegate void XbrlEventHandler(object sender, EventArgs e);
/// <summary>
/// Event fired after a document has been loaded.
/// </summary>
public event XbrlEventHandler Loaded;
/// <summary>
/// Event fired after all XBRL validation has been completed.
/// </summary>
public event XbrlEventHandler Validated;
private INamespaceManager thisNamespaceManager;
/// <summary>
/// A reference to the <see cref="XbrlDocument"/> instance in which the fragment
/// was contained.
/// </summary>
public XbrlDocument Document { get; private set; }
/// <summary>
/// The root XML node for the XBRL fragment.
/// </summary>
internal INode XbrlRootNode { get; private set; }
/// <summary>
/// A dictionary of context references, keyed by their ID.
/// </summary>
internal IDictionary<string, Context> ContextDictionary { get; private set; }
/// <summary>
/// A collection of <see cref="Context"/> objects representing all contexts found in the fragment.
/// </summary>
public List<Context> Contexts { get; private set; }
/// <summary>
/// A collection of <see cref="XbrlSchema"/> objects representing all schemas found in the fragment.
/// </summary>
public XbrlSchemaCollection Schemas { get; private set; }
/// <summary>
/// A collection of <see cref="Fact"/> objects representing all facts found in the fragment.
/// </summary>
public FactCollection Facts { get; private set; }
/// <summary>
/// A collection of <see cref="Unit"/> objects representing all units found in the fragment.
/// </summary>
public List<Unit> Units { get; private set; }
/// <summary>
/// A collection of <see cref="FootnoteLink"/> objects representing all footnote links
/// found in the fragment.
/// </summary>
public List<FootnoteLink> FootnoteLinks { get; private set; }
/// <summary>
/// Evaluates to true if the fragment contains no XBRL validation errors. Evaluates to
/// false if the fragment contains at least one XBRL validation error.
/// </summary>
public bool IsValid
{
get
{
if (this.ValidationErrors == null)
return true;
if (this.ValidationErrors.Count == 0)
return true;
return false;
}
}
/// <summary>
/// A collection of all validation errors found while validating the fragment.
/// </summary>
public List<ValidationError> ValidationErrors { get; private set; }
internal INamespaceManager NamespaceManager { get; private set; }
/// <summary>
/// A collection of role references found in the fragment.
/// </summary>
public List<RoleReference> RoleReferences { get; private set; }
/// <summary>
/// A collection of arcrole references found in the fragment.
/// </summary>
public List<ArcroleReference> ArcroleReferences { get; private set; }
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
internal XbrlFragment(XbrlDocument ParentDocument, INamespaceManager namespaceManager, INode XbrlRootNode)
{
this.Document = ParentDocument;
this.NamespaceManager = namespaceManager;
this.XbrlRootNode = XbrlRootNode;
this.Schemas = new XbrlSchemaCollection();
this.ValidationErrors = new List<ValidationError>();
CreateNamespaceManager();
//---------------------------------------------------------------------------
// Load.
//---------------------------------------------------------------------------
ReadSchemaLocationAttributes();
ReadLinkbaseReferences();
ReadTaxonomySchemaReferences();
ReadTaxonomySchemaImports();
ReadRoleReferences();
ReadArcroleReferences();
ReadContexts();
ReadUnits();
ReadFacts();
ReadFootnoteLinks();
Loaded?.Invoke(this, null);
//---------------------------------------------------------------------------
// Validate.
//---------------------------------------------------------------------------
var validator = new Xbrl2Dot1Validator();
validator.Validate(this);
Validated?.Invoke(this, null);
}
internal void AddValidationError(ValidationError validationError)
{
this.ValidationErrors.Add(validationError);
}
/// <summary>
/// Returns a reference to the context having the supplied context ID.
/// </summary>
/// <param name="ContextId">
/// The ID of the context to return.
/// </param>
/// <returns>
/// A reference to the context having the supplied context ID.
/// A null is returned if no contexts with the supplied context ID is available.
/// </returns>
public Context GetContext(string ContextId)
{
foreach (Context CurrentContext in this.Contexts)
{
if (CurrentContext.Id == ContextId)
return CurrentContext;
}
return null;
}
/// <summary>
/// Returns a reference to the unit having the supplied unit ID.
/// </summary>
/// <param name="UnitId">
/// The ID of the unit to return.
/// </param>
/// <returns>
/// A reference to the unit having the supplied unit ID.
/// A null is returned if no units with the supplied unit ID is available.
/// </returns>
public Unit GetUnit(string UnitId)
{
foreach (Unit CurrentUnit in this.Units)
{
if (CurrentUnit.Id == UnitId)
return CurrentUnit;
}
return null;
}
/// <summary>
/// Returns a reference to the fact having the supplied fact ID.
/// </summary>
/// <param name="FactId">
/// The ID of the fact to return.
/// </param>
/// <returns>
/// A reference to the fact having the supplied fact ID.
/// A null is returned if no facts with the supplied fact ID is available.
/// </returns>
public Item GetFact(string FactId)
{
var matchingFact = this.Facts.GetFactById(FactId);
if (matchingFact == null)
return null;
return matchingFact as Item;
}
/// <summary>
/// Gets the URI associated with a given namespace prefix.
/// </summary>
/// <param name="Prefix">
/// The namespace prefix whose URI should be returned.
/// </param>
/// <returns>
/// The namespace URI associated with the specified namespace prefix.
/// </returns>
public string GetUriForPrefix(string Prefix)
{
return thisNamespaceManager.LookupNamespace(Prefix);
}
/// <summary>
/// Gets the namespace prefix associated with a given URI.
/// </summary>
/// <param name="Uri">
/// The URI whose namespace prefix should be returned.
/// </param>
/// <returns>
/// The namespace prefix associated with the specified namespace URI.
/// </returns>
public string GetPrefixForUri(string Uri)
{
return thisNamespaceManager.LookupPrefix(Uri);
}
/// <summary>
/// Gets the schema associated with a given namespace prefix.
/// </summary>
/// <param name="Prefix">
/// The namespace prefix whose schema should be returned.
/// </param>
/// <returns>
/// A reference to the XBRL schema containing the specified namespace prefix. A null
/// is returned if the given namespace prefix is not found in any of the XBRL schemas.
/// </returns>
public XbrlSchema GetXbrlSchemaForPrefix(string Prefix)
{
string Uri = GetUriForPrefix(Prefix);
if (Uri == null)
return null;
if (Uri.Length == 0)
return null;
return this.Schemas.GetSchemaFromTargetNamespace(Uri, this);
}
/// <summary>
/// Finds the <see cref="RoleType"/> object having the given ID.
/// </summary>
/// <param name="RoleTypeId">
/// The ID of the role type to find.
/// </param>
/// <returns>
/// The <see cref="RoleType"/> object having the given ID, or null if no
/// object can be found.
/// </returns>
public RoleType GetRoleType(string RoleTypeId)
{
return this.Schemas.GetRoleType(RoleTypeId);
}
/// <summary>
/// Finds the <see cref="CalculationLink"/> object having the given role.
/// </summary>
/// <param name="CalculationLinkRole">
/// The role type to find.
/// </param>
/// <returns>
/// The <see cref="CalculationLink"/> object having the given role, or
/// null if no object can be found.
/// </returns>
public CalculationLink GetCalculationLink(RoleType CalculationLinkRole)
{
return this.Schemas.GetCalculationLink(CalculationLinkRole);
}
/// <summary>
/// Returns a prestable fact tree.
/// </summary>
/// <returns>
/// A presentable fact tree. A null will be returned if no presentation linkbase
/// is available.
/// </returns>
public PresentableFactTree GetPresentableFactTree()
{
foreach (var currentSchema in Schemas.SchemaList)
{
if (currentSchema.PresentationLinkbase != null)
return new PresentableFactTree(currentSchema, this.Facts);
}
return null;
}
/// <summary>
/// Read and process any schemaLocation attributes found in the XBRL root node.
/// </summary>
private void ReadSchemaLocationAttributes()
{
SchemaLocationAttributeProcessor.Process(this.XbrlRootNode, this);
}
/// <summary>
/// Read any linkbase references contained directly in the fragment.
/// </summary>
/// <remarks>
/// Linkbase references found as children of XBRL elements is allowed by section
/// 4.3 of the XBRL specification.
/// </remarks>
private void ReadLinkbaseReferences()
{
thisLinkbaseDocuments = new LinkbaseDocumentCollection();
thisLinkbaseDocuments.ReadLinkbaseReferences(this.XbrlRootNode.BaseURI, this.XbrlRootNode);
}
private void ProcessSchemaNamespaceAndLocation(string schemaNamespace, string schemaLocation)
{
var newSchema = new XbrlSchema(this, schemaLocation, string.Empty);
if (newSchema.SchemaRootNode == null) return;
newSchema.TargetNamespace ??= schemaNamespace;
AddSchemaToSchemaList(newSchema);
}
/// <summary>
/// Adds a schema to the schema collection.
/// </summary>
/// <remarks>
/// The supplied schema will not be added if its target namespace is already in the list. This will help
/// with some of the XBRL instance documents in the XBRL Conformance Suite which uses both the "schemaLocation"
/// attribute as well as a "schemaRef" node to specify the same schema. The "301-01-IdScopeValid.xml"
/// instance document in the XBRL-CONF-CR5-2012-01-24 suite is one such example.
/// </remarks>
/// <param name="schemaToAdd">
/// The schema to be added.
/// </param>
private void AddSchemaToSchemaList(XbrlSchema schemaToAdd)
{
this.Schemas.Add(schemaToAdd);
}
/// <summary>
/// Read any process any schemaRef nodes beneath the main XBRL node.
/// </summary>
private void ReadTaxonomySchemaReferences()
{
var LinkbaseNamespacePrefix = thisNamespaceManager.LookupPrefix(XbrlDocument.XbrlLinkbaseNamespaceUri);
var XPathExpressionBuilder = new StringBuilder();
XPathExpressionBuilder.AppendFormat("//{0}:schemaRef", LinkbaseNamespacePrefix);
var XPathExpression = XPathExpressionBuilder.ToString();
var SchemaRefNodes = this.XbrlRootNode.SelectNodes(XPathExpression, thisNamespaceManager);
foreach (INode SchemaRefNode in SchemaRefNodes)
ReadTaxonomySchemaReference(SchemaRefNode);
}
private void ReadTaxonomySchemaImports()
{
int count;
do
{
count = 0;
var schemaList = Schemas.SchemaList.ToList();
foreach (var currentSchema in schemaList)
{
count += ReadTaxonomySchemaImport(currentSchema);
}
} while (count > 0);
}
private int ReadTaxonomySchemaImport(XbrlSchema schema)
{
int count = 0;
var xmlSchemaPrefix = schema.NamespaceManager.LookupPrefix(XbrlSchema.XmlSchemaNamespaceUri);
var xpathExpression = string.Format("//{0}:import", xmlSchemaPrefix);
var schemaImportNodes = schema.SchemaRootNode.SelectNodes(xpathExpression, schema.NamespaceManager);
foreach (INode schemaImportNode in schemaImportNodes)
{
var schemaNamespace = schemaImportNode.GetAttributeValue("namespace");
if (Schemas.SchemaList.Any(currentSchema => currentSchema.TargetNamespace == schemaNamespace)) continue;
var schemaLocation = schemaImportNode.GetAttributeValue("schemaLocation");
var schemaFullLocation = GetFullSchemaPath(schema.LoadPath, schemaLocation);
ProcessSchemaNamespaceAndLocation(schemaNamespace, schemaFullLocation);
count++;
}
return count;
}
private string GetFullSchemaPath(string schemaLoadPath, string schemaLocation)
{
var lowerCaseSchemaLocatione = schemaLocation.ToLower();
if (lowerCaseSchemaLocatione.StartsWith("http://") ||
lowerCaseSchemaLocatione.StartsWith("https://") ||
lowerCaseSchemaLocatione.StartsWith("file://"))
{
return schemaLocation;
}
var firstPathSeparator = schemaLocation.IndexOf(Path.DirectorySeparatorChar);
if (firstPathSeparator == -1 && Path.DirectorySeparatorChar != '/')
firstPathSeparator = schemaLocation.IndexOf('/');
if (firstPathSeparator != -1 || string.IsNullOrEmpty(schemaLoadPath))
throw new NotImplementedException("XbrlFragment.GetFullSchemaPath() code path not implemented.");
var lastPathSeparator = schemaLoadPath.LastIndexOf(Path.DirectorySeparatorChar);
if (lastPathSeparator == -1 && Path.DirectorySeparatorChar != '/')
lastPathSeparator = schemaLoadPath.LastIndexOf('/');
var documentPath = schemaLoadPath.Substring(0, lastPathSeparator + 1);
return documentPath + schemaLocation;
}
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
private void ReadRoleReferences()
{
var LinkbaseNamespacePrefix = thisNamespaceManager.LookupPrefix(XbrlDocument.XbrlLinkbaseNamespaceUri);
if (string.IsNullOrEmpty(LinkbaseNamespacePrefix))
throw new InvalidOperationException("XbrlFragment.ReadRoleReferences() role reference prefix not found.");
var XPathExpressionBuilder = new StringBuilder();
XPathExpressionBuilder.AppendFormat("//{0}:roleRef", LinkbaseNamespacePrefix);
var XPathExpression = XPathExpressionBuilder.ToString();
var RoleRefNodes = this.XbrlRootNode.SelectNodes(XPathExpression, thisNamespaceManager);
RoleReferences = new List<RoleReference>();
foreach (INode RoleRefNode in RoleRefNodes)
RoleReferences.Add(new RoleReference(RoleRefNode));
}
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
private void ReadArcroleReferences()
{
var LinkbaseNamespacePrefix = thisNamespaceManager.LookupPrefix(XbrlDocument.XbrlLinkbaseNamespaceUri);
if (string.IsNullOrEmpty(LinkbaseNamespacePrefix))
throw new InvalidOperationException("XbrlFragment.ReadArcroleReferences() Arc role reference prefix not found.");
var XPathExpressionBuilder = new StringBuilder();
XPathExpressionBuilder.AppendFormat("//{0}:arcroleRef", LinkbaseNamespacePrefix);
var XPathExpression = XPathExpressionBuilder.ToString();
var ArcroleRefNodes = this.XbrlRootNode.SelectNodes(XPathExpression, thisNamespaceManager);
ArcroleReferences = new List<ArcroleReference>();
foreach (INode ArcroleRefNode in ArcroleRefNodes)
this.ArcroleReferences.Add(new ArcroleReference(ArcroleRefNode));
}
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
private void ReadTaxonomySchemaReference(INode SchemaRefNode)
{
string HrefAttributeValue = SchemaRefNode.GetAttributeValue(Xlink.XlinkNode.xlinkNamespace, "href");
string Base = SchemaRefNode.GetAttributeValue(XbrlDocument.XmlNamespaceUri1998, "base");
var newSchema = new XbrlSchema(this, HrefAttributeValue, Base);
if(newSchema.SchemaRootNode != null)
AddSchemaToSchemaList(newSchema);
}
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
private void CreateNamespaceManager()
{
thisNamespaceManager = Container.Resolve<INamespaceManager>();
thisNamespaceManager.AddNamespace("instance", this.XbrlRootNode.NamespaceURI);
foreach (IAttribute CurrentAttribute in this.XbrlRootNode.Attributes)
{
if (CurrentAttribute.Prefix == "xmlns")
thisNamespaceManager.AddNamespace(CurrentAttribute.LocalName, CurrentAttribute.Value);
}
}
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
private void ReadContexts()
{
this.Contexts = new List<Context>();
INodeList ContextNodes = this.XbrlRootNode.SelectNodes("//instance:context", thisNamespaceManager);
foreach (INode ContextNode in ContextNodes)
this.Contexts.Add(new Context(this, ContextNode));
ContextDictionary = this.Contexts.ToDictionary(context => context.Id);
}
/// <summary>
/// Reads all of the facts in the XBRL fragment and creates an object for each.
/// </summary>
/// <remarks>
/// <para>
/// Element instances can be any of the following:
/// </para>
/// <para>
/// <list type="bullet">
/// <item>
/// an item, represented in an XBRL schema by an element with a substitution group of "item"
/// and represented by an <see cref="Item"/> object
/// </item>
/// <item>
/// a tuple, represented in an XBRL schema by an element with a substitution group of "tuple"
/// and represented by an <see cref="Tuple"/> object
/// </item>
/// </list>
/// </para>
/// </remarks>
private void ReadFacts()
{
this.Facts = new FactCollection
{
Capacity = this.XbrlRootNode.ChildNodes.Count
};
foreach (INode CurrentChild in this.XbrlRootNode.ChildNodes)
{
var CurrentFact = Fact.Create(this, CurrentChild);
if (CurrentFact != null)
this.Facts.Add(CurrentFact);
}
this.Facts.TrimExcess();
}
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
private void ReadUnits()
{
this.Units = new List<Unit>();
INodeList UnitNodes = this.XbrlRootNode.SelectNodes("//instance:unit", thisNamespaceManager);
foreach (INode UnitNode in UnitNodes)
this.Units.Add(new Unit(this, UnitNode, thisNamespaceManager));
}
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
private void ReadFootnoteLinks()
{
this.FootnoteLinks = new List<FootnoteLink>();
string LinkbaseNamespacePrefix = thisNamespaceManager.LookupPrefix(XbrlDocument.XbrlLinkbaseNamespaceUri);
StringBuilder XPathExpressionBuilder = new StringBuilder();
XPathExpressionBuilder.AppendFormat("//{0}:footnoteLink", LinkbaseNamespacePrefix);
string XPathExpression = XPathExpressionBuilder.ToString();
INodeList FootnoteLinkNodes = this.XbrlRootNode.SelectNodes(XPathExpression, thisNamespaceManager);
foreach (INode FootnoteLinkNode in FootnoteLinkNodes)
this.FootnoteLinks.Add(new FootnoteLink(this, FootnoteLinkNode));
}
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
internal bool UrlReferencesFragmentDocument(HyperlinkReference Href)
{
if (Href.UrlSpecified == false)
return false;
string DocFullPath = Path.GetFullPath(this.Document.Filename);
string HrefFullPathString;
if (Href.Url.IndexOf(Path.DirectorySeparatorChar) == -1)
HrefFullPathString = this.Document.Path + Path.DirectorySeparatorChar + Href.Url;
else
HrefFullPathString = Href.Url;
string HrefFullPath = Path.GetFullPath(HrefFullPathString);
if (DocFullPath.Equals(HrefFullPath) == true)
return true;
return false;
}
/// <summary>
/// Find the calculation arc whose "to" attribute matches the supplied locator.
/// </summary>
/// <param name="toLocator">
/// The locator used to find the matching calculation arc.
/// </param>
/// <remarks>
/// This method will look through all calculation links, in both the document fragment itself
/// as well as any referenced schemas. If multiple arcs are found, then the one with the highest
/// priority is returned.
/// </remarks>
/// <returns>
/// The calculation arc referencing the supplied "to" locator. If there is no matching calculation
/// arc, then null will be returned.
/// </returns>
internal CalculationArc GetCalculationArc(Locator toLocator)
{
var matchingArcs = new List<CalculationArc>();
var docReferencedCalculationLinkbase = thisLinkbaseDocuments.CalculationLinkbase;
if (docReferencedCalculationLinkbase != null)
{
var matchingArc = docReferencedCalculationLinkbase.GetCalculationArc(toLocator);
if (matchingArc != null)
{
matchingArcs.Add(matchingArc);
}
}
foreach (var currentSchema in this.Schemas)
{
var schemaCalcLinkbase = currentSchema.CalculationLinkbase;
if (schemaCalcLinkbase != null)
{
var matchingArc = schemaCalcLinkbase.GetCalculationArc(toLocator);
if (matchingArc != null)
{
matchingArcs.Add(matchingArc);
}
}
}
return GetHighestPriorityArc(matchingArcs);
}
/// <summary>
/// Given a list of calculation arcs, find the arc with the highest priority.
/// </summary>
/// <param name="arcs">
/// A list of calculation arcs.
/// </param>
/// <returns>
/// The calculation arc with the highest priority, or null if no arc is available.
/// </returns>
private CalculationArc GetHighestPriorityArc(List<CalculationArc> arcs)
{
if (arcs.Count == 0)
{
return null;
}
if (arcs.Count == 1)
{
return arcs[0];
}
var sortedArcs = arcs.OrderBy(o => o.Priority).ToList();
var highestPriorityArc = sortedArcs[0];
for (var arcIndex = 1; arcIndex < sortedArcs.Count; arcIndex++)
{
var currentArc = sortedArcs[arcIndex];
if (currentArc.Priority > highestPriorityArc.Priority)
{
if(currentArc.EquivalentTo(highestPriorityArc, this) == true)
{
highestPriorityArc = currentArc;
}
}
}
return highestPriorityArc;
}
}
}
| |
/* 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.Linq;
using System.Xml;
using XenAdmin;
using XenAdmin.Core;
using XenAdmin.Network;
namespace XenAPI
{
public partial class SR : IComparable<SR>, IEquatable<SR>
{
/// <summary>
/// The SR types. Note that the names of these enum members correspond exactly to the SR type string as
/// recognised by the server. If you add anything here, check whether it should also be added to
/// SR.CanCreateWithXenCenter. Also add it to XenAPI/FriendlyNames.resx under
/// Label-SR.SRTypes-*. Don't change the lower-casing!
/// </summary>
public enum SRTypes
{
local, ext, lvmoiscsi, iso, nfs, lvm, netapp, udev, lvmofc,
lvmohba, egenera, egeneracd, dummy, unknown, equal, cslg, shm,
iscsi,
ebs, rawhba,
smb, lvmofcoe,
nutanix, nutanixiso,
tmpfs
}
public const string Content_Type_ISO = "iso";
public const string SM_Config_Type_CD = "cd";
private const string XenServer_Tools_Label = "XenServer Tools";
public override string ToString()
{
return Name;
}
/// <returns>A friendly name for the SR.</returns>
public override string Name
{
get
{
return I18N("name_label", name_label, true);
}
}
/// <summary>
/// Get the given SR's home, i.e. the host under which we are going to display it. May return null, if this SR should live
/// at the pool level.
/// </summary>
public Host Home
{
get
{
if (shared || PBDs.Count != 1)
return null;
PBD pbd = Connection.Resolve(PBDs[0]);
if (pbd == null)
return null;
return Connection.Resolve(pbd.host);
}
}
public string NameWithoutHost
{
get
{
return I18N("name_label", name_label, false);
}
}
/// <returns>A friendly description for the SR.</returns>
public override string Description
{
get
{
return I18N("name_description", name_description, true);
}
}
public bool Physical
{
get
{
SRTypes type = GetSRType(false);
return type == SRTypes.local || (type == SRTypes.udev && SMConfigType == SM_Config_Type_CD);
}
}
public string SMConfigType
{
get { return Get(sm_config, "type"); }
}
public bool IsToolsSR
{
get
{
return name_label == SR.XenServer_Tools_Label || is_tools_sr;
}
}
public string FriendlyTypeName
{
get
{
return getFriendlyTypeName(GetSRType(false));
}
}
/// <summary>
/// A friendly (internationalized) name for the SR type.
/// </summary>
public static string getFriendlyTypeName(SRTypes srType)
{
return PropertyManager.GetFriendlyName(string.Format("Label-SR.SRTypes-{0}", srType.ToString()),
"Label-SR.SRTypes-unknown");
}
/// <summary>
/// Use this instead of type
/// </summary>
public SRTypes GetSRType(bool ignoreCase)
{
try
{
return (SRTypes)Enum.Parse(typeof(SRTypes), type, ignoreCase);
}
catch
{
return SRTypes.unknown;
}
}
public string ConfigType
{
get { return Get(sm_config, "type"); }
}
private string I18N(string field_name, string field_value, bool with_host)
{
if (!other_config.ContainsKey("i18n-key"))
{
return field_value;
}
string i18n_key = other_config["i18n-key"];
string original_value_key = "i18n-original-value-" + field_name;
string original_value =
other_config.ContainsKey(original_value_key) ? other_config[original_value_key] : "";
if (original_value != field_value)
return field_value;
string hostname = with_host ? GetHostName() : null;
if (hostname == null)
{
string pattern = PropertyManager.GetFriendlyName(string.Format("SR.{0}-{1}", field_name, i18n_key));
return pattern == null ? field_value : pattern;
}
else
{
string pattern = PropertyManager.GetFriendlyName(string.Format("SR.{0}-{1}-host", field_name, i18n_key));
return pattern == null ? field_value : string.Format(pattern, hostname);
}
}
/// <returns>The name of the host to which this SR is attached, or null if the storage is shared
/// or unattached.</returns>
private string GetHostName()
{
if (Connection == null)
return null;
Host host = GetStorageHost();
return host == null ? null : host.Name;
}
/// <returns>The host to which the given SR belongs, or null if the SR is shared or completely disconnected.</returns>
public Host GetStorageHost()
{
if (shared || PBDs.Count != 1)
return null;
PBD pbd = Connection.Resolve(PBDs[0]);
return pbd == null ? null : Connection.Resolve(pbd.host);
}
/// <summary>
/// Iterating through the PBDs, this will return the storage host of the first PBD that is currently_attached.
/// This will return null if there are no PBDs or none of them is currently_attached
/// </summary>
/// <returns></returns>
public Host GetFirstAttachedStorageHost()
{
if (PBDs.Count == 0)
return null;
var currentlyAttachedPBDs = PBDs.Select(pbdref => Connection.Resolve(pbdref)).Where(p => p != null && p.currently_attached);
if (currentlyAttachedPBDs.FirstOrDefault() != null)
return currentlyAttachedPBDs.Select(p => Connection.Resolve(p.host)).Where(h => h != null).FirstOrDefault();
return null;
}
public bool IsDetachable()
{
return !IsDetached && !HasRunningVMs() && CanCreateWithXenCenter;
}
/// <summary>
/// Can create with XC, or is citrix storage link gateway. Special case alert!
/// </summary>
public bool CanCreateWithXenCenter
{
get
{
SRTypes type = GetSRType(false);
return type == SRTypes.iso
|| type == SRTypes.lvmoiscsi
|| type == SRTypes.nfs
|| type == SRTypes.equal
|| type == SRTypes.netapp
|| type == SRTypes.lvmohba
|| type == SRTypes.cslg
|| type == SRTypes.smb
|| type == SRTypes.lvmofcoe;
}
}
public bool IsLocalSR
{
get
{
SRTypes type = GetSRType(false);
return type == SRTypes.local
|| type == SRTypes.ext
|| type == SRTypes.lvm
|| type == SRTypes.udev
|| type == SRTypes.egeneracd
|| type == SRTypes.dummy;
}
}
public bool ShowForgetWarning
{
get
{
return GetSRType(false) != SRTypes.iso;
}
}
/// <summary>
/// Internal helper function. True if all the PBDs for this SR are currently_attached.
/// </summary>
/// <returns></returns>
private bool AllPBDsAttached()
{
return Connection.ResolveAll(this.PBDs).All(pbd => pbd.currently_attached);
}
/// <summary>
/// Internal helper function. True if any of the PBDs for this SR is currently_attached.
/// </summary>
/// <returns></returns>
private bool AnyPBDAttached()
{
return Connection.ResolveAll(this.PBDs).Any(pbd => pbd.currently_attached);
}
/// <summary>
/// Returns true if there are any Running or Suspended VMs attached to VDIs on this SR.
/// </summary>
/// <param name="connection"></param>
/// <returns></returns>
public bool HasRunningVMs()
{
foreach (VDI vdi in Connection.ResolveAll(VDIs))
{
foreach (VBD vbd in Connection.ResolveAll(vdi.VBDs))
{
VM vm = Connection.Resolve(vbd.VM);
if (vm == null)
continue;
// PR-1223: ignore control domain VM on metadata VDIs, so that the SR can be detached if there are no other running VMs
if (vdi.type == vdi_type.metadata && vm.is_control_domain)
continue;
if (vm.power_state == vm_power_state.Running)
return true;
}
}
return false;
}
/// <summary>
/// If host is non-null, return whether this storage can be seen from the given host.
/// If host is null, return whether the storage is shared, with a PBD for each host and at least one PBD plugged.
/// (See CA-36285 for why this is the right test when looking for SRs on which to create a new VM).
/// </summary>
public virtual bool CanBeSeenFrom(Host host)
{
if (host == null)
{
return shared && Connection != null && !IsBroken(false) && AnyPBDAttached();
}
foreach (PBD pbd in host.Connection.ResolveAll(PBDs))
if (pbd.currently_attached && pbd.host.opaque_ref == host.opaque_ref)
return true;
return false;
}
public PBD GetPBDFor(Host host)
{
foreach (PBD pbd in host.Connection.ResolveAll(PBDs))
if (pbd.host.opaque_ref == host.opaque_ref)
return pbd;
return null;
}
/// <summary>
/// True if there is less than 0.5GB free. Always false for dummy and ebs SRs.
/// </summary>
public bool IsFull
{
get
{
SRTypes t = GetSRType(false);
return t != SRTypes.dummy && t != SRTypes.ebs && FreeSpace < XenAdmin.Util.BINARY_GIGA / 2;
}
}
public virtual long FreeSpace
{
get
{
return physical_size - physical_utilisation;
}
}
public virtual bool ShowInVDISRList(bool showHiddenVMs)
{
if (content_type == Content_Type_ISO)
return false;
return Show(showHiddenVMs);
}
public bool IsDetached
{
get
{
// SR is detached when it has no PBDs or when all its PBDs are unplugged
return !HasPBDs || !AnyPBDAttached();
}
}
public bool HasPBDs
{
get
{
// CA-15188: Show SRs with no PBDs on Orlando, as pool-eject bug has been fixed.
// SRs are detached if they have no PBDs
return PBDs.Count > 0;
}
}
public override bool Show(bool showHiddenVMs)
{
if (name_label.StartsWith(Helpers.GuiTempObjectPrefix))
return false;
SRTypes srType = GetSRType(false);
// CA-15012 - dont show cd drives of type local on miami (if dont get destroyed properly on upgrade)
if (srType == SRTypes.local)
return false;
// Hide Memory SR
if (srType == SRTypes.tmpfs)
return false;
if (showHiddenVMs)
return true;
//CP-2458: hide SRs that were introduced by a DR_task
if (introduced_by != null && introduced_by.opaque_ref != Helper.NullOpaqueRef)
return false;
return !IsHidden;
}
public override bool IsHidden
{
get
{
return BoolKey(other_config, HIDE_FROM_XENCENTER);
}
}
/// <summary>
/// The SR is broken when it has the wrong number of PBDs, or (optionally) not all the PBDs are attached.
/// </summary>
/// <param name="checkAttached">Whether to check that all the PBDs are attached</param>
/// <returns></returns>
public virtual bool IsBroken(bool checkAttached)
{
if (PBDs == null || PBDs.Count == 0 ||
checkAttached && !AllPBDsAttached())
{
return true;
}
Pool pool = Helpers.GetPoolOfOne(Connection);
if (pool == null || !shared)
{
if (PBDs.Count != 1)
{
// There should be exactly one PBD, since this is a non-shared SR
return true;
}
}
else
{
if (PBDs.Count != Connection.Cache.HostCount)
{
// There isn't a PBD for each host
return true;
}
}
return false;
}
public bool IsBroken()
{
return IsBroken(true);
}
public static bool IsDefaultSr(SR sr)
{
Pool pool = Helpers.GetPoolOfOne(sr.Connection);
return pool != null && pool.default_SR != null && pool.default_SR.opaque_ref == sr.opaque_ref;
}
/// <summary>
/// Returns true if a new VM may be created on this SR: the SR supports VDI_CREATE, has the right number of PBDs, and is not full.
/// </summary>
/// <param name="myConnection">The IXenConnection whose cache this XenObject belongs to. May not be null.</param>
/// <returns></returns>
public bool CanCreateVmOn()
{
System.Diagnostics.Trace.Assert(Connection != null, "Connection must not be null");
return SupportsVdiCreate() && !IsBroken(false) && !IsFull;
}
/// <summary>
/// Whether the underlying SR backend supports VDI_CREATE. Will return true even if the SR is full.
/// </summary>
/// <param name="connection"></param>
/// <returns></returns>
public virtual bool SupportsVdiCreate()
{
// ISO SRs are deemed not to support VDI create in the GUI, even though the back end
// knows that they do. See CA-40119.
if (content_type == SR.Content_Type_ISO)
return false;
// Memory SRs should not support VDI create in the GUI
if (GetSRType(false) == SR.SRTypes.tmpfs)
return false;
SM sm = SM.GetByType(Connection, type);
return sm != null && -1 != Array.IndexOf(sm.capabilities, "VDI_CREATE");
}
/// <summary>
/// Parses an XML list of SRs (as returned by the SR.probe() call) into a list of SRInfos.
/// </summary>
public static List<SRInfo> ParseSRListXML(string xml)
{
List<SRInfo> results = new List<SRInfo>();
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
// If we've got this from an async task result, then it will be wrapped
// in a <value> element. Parse the contents instead.
foreach (XmlNode node in doc.GetElementsByTagName("value"))
{
xml = node.InnerText;
doc = new XmlDocument();
doc.LoadXml(xml);
break;
}
foreach (XmlNode node in doc.GetElementsByTagName("SR"))
{
string uuid = "";
long size = 0;
string aggr = "";
string name_label = "";
string name_description = "";
bool pool_metadata_detected = false;
foreach (XmlNode info in node.ChildNodes)
{
if (info.Name.ToLowerInvariant() == "uuid")
{
uuid = info.InnerText.Trim();
}
else if (info.Name.ToLowerInvariant() == "size")
{
size = long.Parse(info.InnerText.Trim());
}
else if (info.Name.ToLowerInvariant() == "aggregate")
{
aggr = info.InnerText.Trim();
}
else if (info.Name.ToLowerInvariant() == "name_label")
{
name_label = info.InnerText.Trim();
}
else if (info.Name.ToLowerInvariant() == "name_description")
{
name_description = info.InnerText.Trim();
}
else if (info.Name.ToLowerInvariant() == "pool_metadata_detected")
{
bool.TryParse(info.InnerText.Trim(), out pool_metadata_detected);
}
}
results.Add(new SRInfo(uuid, size, aggr, name_label, name_description, pool_metadata_detected));
/*if (aggr != "")
results.Add(new SRInfo(uuid, size, aggr));
else
results.Add(new SRInfo(uuid, size));*/
}
return results;
}
public static List<string> ParseSupportedVersionsListXML(string xml)
{
var supportedVersionsResult = new List<string>();
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
// If we've got this from an async task result, then it will be wrapped
// in a <value> element. Parse the contents instead.
foreach (XmlNode node in doc.GetElementsByTagName("value"))
{
xml = node.InnerText;
doc = new XmlDocument();
doc.LoadXml(xml);
break;
}
foreach (XmlNode node in doc.GetElementsByTagName("SupportedVersions"))
{
foreach (XmlNode info in node.ChildNodes)
{
if (info.Name.ToLowerInvariant() == "version")
{
supportedVersionsResult.Add(info.InnerText.Trim());
}
}
}
return supportedVersionsResult;
}
public String GetScsiID()
{
foreach (PBD pbd in Connection.ResolveAll(PBDs))
{
if (!pbd.device_config.ContainsKey("SCSIid"))
continue;
return pbd.device_config["SCSIid"];
}
if (!sm_config.ContainsKey("devserial"))
return null;
String SCSIid = sm_config["devserial"];
if (SCSIid.StartsWith("scsi-"))
SCSIid = SCSIid.Remove(0, 5);
// CA-22352: SCSI IDs on the general panel for a NetApp SR have a trailing comma
SCSIid = SCSIid.TrimEnd(new char[] { ',' });
return SCSIid;
}
/// <summary>
/// New Lun Per VDI mode (cf. LunPerVDI method) using the hba encapsulating type
/// </summary>
public virtual bool HBALunPerVDI
{
get { return GetSRType(true) == SRTypes.rawhba; }
}
/// <summary>
/// Legacy LunPerVDI mode - for old servers that this was set up on
/// This is no longer an option (2012) for newer servers but we need to keep this
/// </summary>
public bool LunPerVDI
{
get
{
// Look for the mapping from scsi id -> vdi uuid
// in sm-config.
foreach (String key in sm_config.Keys)
if (key.Contains("LUNperVDI") || key.StartsWith("scsi-"))
return true;
return false;
}
}
private const String MPATH = "mpath";
public Dictionary<VM, Dictionary<VDI, String>> GetMultiPathStatusLunPerVDI()
{
Dictionary<VM, Dictionary<VDI, String>> result =
new Dictionary<VM, Dictionary<VDI, String>>();
if (Connection == null)
return result;
foreach (PBD pbd in Connection.ResolveAll(PBDs))
{
if (!pbd.MultipathActive)
continue;
foreach (KeyValuePair<String, String> kvp in pbd.other_config)
{
if (!kvp.Key.StartsWith(MPATH))
continue;
int current;
int max;
if (!PBD.ParsePathCounts(kvp.Value, out current, out max))
continue;
String scsiIdKey = String.Format("scsi-{0}", kvp.Key.Substring(MPATH.Length + 1));
if (!sm_config.ContainsKey(scsiIdKey))
continue;
String vdiUUID = sm_config[scsiIdKey];
VDI vdi = null;
foreach (VDI candidate in Connection.ResolveAll(VDIs))
{
if (candidate.uuid != vdiUUID)
continue;
vdi = candidate;
break;
}
if (vdi == null)
continue;
foreach (VBD vbd in Connection.ResolveAll(vdi.VBDs))
{
VM vm = Connection.Resolve(vbd.VM);
if (vm == null)
continue;
if (vm.power_state != vm_power_state.Running)
continue;
if (!result.ContainsKey(vm))
result[vm] = new Dictionary<VDI, String>();
result[vm][vdi] = kvp.Value;
}
}
}
return result;
}
public Dictionary<PBD, String> GetMultiPathStatusLunPerSR()
{
Dictionary<PBD, String> result =
new Dictionary<PBD, String>();
if (Connection == null)
return result;
foreach (PBD pbd in Connection.ResolveAll(PBDs))
{
if (!pbd.MultipathActive)
continue;
String status = String.Empty;
foreach (KeyValuePair<String, String> kvp in pbd.other_config)
{
if (!kvp.Key.StartsWith(MPATH))
continue;
status = kvp.Value;
break;
}
int current;
int max;
if (!PBD.ParsePathCounts(status, out current, out max))
continue;
result[pbd] = status;
}
return result;
}
public bool MultipathAOK
{
get
{
if (!MultipathCapable)
return true;
if (LunPerVDI)
{
Dictionary<VM, Dictionary<VDI, String>>
multipathStatus = GetMultiPathStatusLunPerVDI();
foreach (VM vm in multipathStatus.Keys)
foreach (VDI vdi in multipathStatus[vm].Keys)
if (!CheckMultipathString(multipathStatus[vm][vdi]))
return false;
}
else
{
Dictionary<PBD, String> multipathStatus =
GetMultiPathStatusLunPerSR();
foreach (PBD pbd in multipathStatus.Keys)
if (pbd.MultipathActive && !CheckMultipathString(multipathStatus[pbd]))
return false;
}
return true;
}
}
public override string NameWithLocation
{
get
{
//return only the Name for local SRs
if (Connection != null && !shared)
{
return Name;
}
return base.NameWithLocation;
}
}
internal override string LocationString
{
get
{
return Home != null ? Home.LocationString : base.LocationString;
}
}
private bool CheckMultipathString(String status)
{
int current;
int max;
if (!PBD.ParsePathCounts(status, out current, out max))
return true;
return current >= max;
}
public Dictionary<String, String> GetDeviceConfig(IXenConnection connection)
{
foreach (PBD pbd in connection.ResolveAll(PBDs))
return pbd.device_config;
return null;
}
public class SRInfo : IComparable<SRInfo>, IEquatable<SRInfo>
{
public readonly string UUID;
public readonly long Size;
public readonly string Aggr;
public string Name;
public string Description;
public readonly bool PoolMetadataDetected;
public SRInfo(string uuid)
: this(uuid, 0, "", "", "", false)
{
}
public SRInfo(string uuid, long size)
: this(uuid, size, "", "", "", false)
{
}
public SRInfo(string uuid, long size, string aggr)
: this(uuid, size, aggr, "", "", false)
{
}
public SRInfo(string uuid, long size, string aggr, string name, string description, bool poolMetadataDetected)
{
UUID = uuid;
Size = size;
Aggr = aggr;
Name = name;
Description = description;
PoolMetadataDetected = poolMetadataDetected;
}
public int CompareTo(SRInfo other)
{
return (this.UUID.CompareTo(other.UUID));
}
public bool Equals(SRInfo other)
{
return this.CompareTo(other) == 0;
}
public override string ToString()
{
return UUID;
}
}
//public bool TypeCIFS
//{
// get
// {
// if (Connection == null || PBDs.Count == 0)
// return false;
// PBD pbd = Connection.Resolve<PBD>(PBDs[0]);
// if (pbd == null)
// return false;
// return (pbd.device_config.ContainsKey("options") && pbd.device_config["options"].Contains("-t cifs"))
// || (pbd.device_config.ContainsKey("type") && pbd.device_config["type"] == "cifs");
// }
//}
public bool MultipathCapable
{
get
{
return "true" == Get(sm_config, "multipathable");
}
}
public string Target
{
get
{
SR sr = Connection.Resolve(new XenRef<SR>(this.opaque_ref));
if (sr == null)
return String.Empty;
foreach (PBD pbd in sr.Connection.ResolveAll(sr.PBDs))
{
SRTypes type = sr.GetSRType(false);
if ((type == SR.SRTypes.netapp || type == SR.SRTypes.lvmoiscsi || type == SR.SRTypes.equal) && pbd.device_config.ContainsKey("target")) // netapp or iscsi
{
return pbd.device_config["target"];
}
else if (type == SR.SRTypes.iso && pbd.device_config.ContainsKey("location")) // cifs or nfs iso
{
String target = Helpers.HostnameFromLocation(pbd.device_config["location"]); // has form //ip_address/path
if (String.IsNullOrEmpty(target))
continue;
return target;
}
else if (type == SR.SRTypes.nfs && pbd.device_config.ContainsKey("server"))
{
return pbd.device_config["server"];
}
}
return String.Empty;
}
}
public Icons GetIcon
{
get
{
if (!HasPBDs || IsHidden)
{
return Icons.StorageDisabled;
}
else if (IsDetached || IsBroken() || !MultipathAOK)
{
return Icons.StorageBroken;
}
else if (SR.IsDefaultSr(this))
{
return Icons.StorageDefault;
}
else
{
return Icons.Storage;
}
}
}
/// <summary>
/// The amount of memory used as compared to the available and allocated amounts as a friendly string
/// </summary>
public String SizeString
{
get
{
return string.Format(Messages.SR_SIZE_USED,
Util.DiskSizeString(physical_utilisation),
Util.DiskSizeString(physical_size),
Util.DiskSizeString(virtual_allocation));
}
}
/// <summary>
/// A friendly string indicating whether the sr is detached/broken/multipath failing/needs upgrade/ok
/// </summary>
public String StatusString
{
get
{
if (!HasPBDs)
return Messages.DETACHED;
if (IsDetached || IsBroken())
return Messages.GENERAL_SR_STATE_BROKEN;
if (!MultipathAOK)
return Messages.GENERAL_MULTIPATH_FAILURE;
return Messages.GENERAL_STATE_OK;
}
}
/// <summary>
/// Returns true when there is a pbd containing adapterid else false
/// </summary>
public bool CanRepairAfterUpgradeFromLegacySL
{
get
{
if (type == "cslg")
{
var pbds = Connection.ResolveAll(PBDs);
if (pbds != null)
{
return pbds.Any(pbd => pbd.device_config.ContainsKey("adapterid"));
}
return false;
}
return true;
}
}
/// <summary>
/// Whether SR supports database replication.
/// </summary>
public static bool SupportsDatabaseReplication(IXenConnection connection, SR sr)
{
try
{
assert_supports_database_replication(connection.Session, sr.opaque_ref);
return true;
}
catch (Failure)
{
return false;
}
}
/// <summary>
/// Is an iSL type or legacy iSl adpater type
/// </summary>
/// <param name="sr"></param>
/// <returns></returns>
public static bool IsIslOrIslLegacy(SR sr)
{
SRTypes currentType = sr.GetSRType(true);
return currentType == SRTypes.cslg || currentType == SRTypes.equal || currentType == SRTypes.netapp;
}
/// <summary>
/// Whether the underlying SR backend supports SR_TRIM
/// </summary>
/// <returns></returns>
public bool SupportsTrim
{
get
{
System.Diagnostics.Trace.Assert(Connection != null, "Connection must not be null");
SM sm = SM.GetByType(Connection, type);
return sm != null && sm.features != null && sm.features.ContainsKey("SR_TRIM");
}
}
public bool IsThinProvisioned
{
get
{
return false; // DISABLED THIN PROVISIONING this.sm_config != null && this.sm_config.ContainsKey("allocation") && this.sm_config["allocation"] == "xlvhd";
}
}
public long PercentageCommitted
{
get
{
return (long)Math.Round(virtual_allocation / (double)physical_size * 100.0);
}
}
#region IEquatable<SR> Members
/// <summary>
/// Indicates whether the current object is equal to the specified object. This calls the implementation from XenObject.
/// This implementation is required for ToStringWrapper.
/// </summary>
public bool Equals(SR other)
{
return base.Equals(other);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void MultiplyHighRoundScaleInt16()
{
var test = new SimpleBinaryOpTest__MultiplyHighRoundScaleInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__MultiplyHighRoundScaleInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int16> _fld1;
public Vector128<Int16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__MultiplyHighRoundScaleInt16 testClass)
{
var result = Ssse3.MultiplyHighRoundScale(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__MultiplyHighRoundScaleInt16 testClass)
{
fixed (Vector128<Int16>* pFld1 = &_fld1)
fixed (Vector128<Int16>* pFld2 = &_fld2)
{
var result = Ssse3.MultiplyHighRoundScale(
Sse2.LoadVector128((Int16*)(pFld1)),
Sse2.LoadVector128((Int16*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector128<Int16> _clsVar1;
private static Vector128<Int16> _clsVar2;
private Vector128<Int16> _fld1;
private Vector128<Int16> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__MultiplyHighRoundScaleInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
}
public SimpleBinaryOpTest__MultiplyHighRoundScaleInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Ssse3.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Ssse3.MultiplyHighRoundScale(
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Ssse3.MultiplyHighRoundScale(
Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Ssse3.MultiplyHighRoundScale(
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Ssse3).GetMethod(nameof(Ssse3.MultiplyHighRoundScale), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Ssse3).GetMethod(nameof(Ssse3.MultiplyHighRoundScale), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Ssse3).GetMethod(nameof(Ssse3.MultiplyHighRoundScale), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Ssse3.MultiplyHighRoundScale(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int16>* pClsVar1 = &_clsVar1)
fixed (Vector128<Int16>* pClsVar2 = &_clsVar2)
{
var result = Ssse3.MultiplyHighRoundScale(
Sse2.LoadVector128((Int16*)(pClsVar1)),
Sse2.LoadVector128((Int16*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr);
var result = Ssse3.MultiplyHighRoundScale(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr));
var result = Ssse3.MultiplyHighRoundScale(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr));
var result = Ssse3.MultiplyHighRoundScale(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__MultiplyHighRoundScaleInt16();
var result = Ssse3.MultiplyHighRoundScale(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__MultiplyHighRoundScaleInt16();
fixed (Vector128<Int16>* pFld1 = &test._fld1)
fixed (Vector128<Int16>* pFld2 = &test._fld2)
{
var result = Ssse3.MultiplyHighRoundScale(
Sse2.LoadVector128((Int16*)(pFld1)),
Sse2.LoadVector128((Int16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Ssse3.MultiplyHighRoundScale(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int16>* pFld1 = &_fld1)
fixed (Vector128<Int16>* pFld2 = &_fld2)
{
var result = Ssse3.MultiplyHighRoundScale(
Sse2.LoadVector128((Int16*)(pFld1)),
Sse2.LoadVector128((Int16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Ssse3.MultiplyHighRoundScale(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Ssse3.MultiplyHighRoundScale(
Sse2.LoadVector128((Int16*)(&test._fld1)),
Sse2.LoadVector128((Int16*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int16> op1, Vector128<Int16> op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (short)((((left[0] * right[0]) >> 14) + 1) >> 1))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (short)((((left[i] * right[i]) >> 14) + 1) >> 1))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Ssse3)}.{nameof(Ssse3.MultiplyHighRoundScale)}<Int16>(Vector128<Int16>, Vector128<Int16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// FlowRevisionResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Types;
namespace Twilio.Rest.Studio.V2.Flow
{
public class FlowRevisionResource : Resource
{
public sealed class StatusEnum : StringEnum
{
private StatusEnum(string value) : base(value) {}
public StatusEnum() {}
public static implicit operator StatusEnum(string value)
{
return new StatusEnum(value);
}
public static readonly StatusEnum Draft = new StatusEnum("draft");
public static readonly StatusEnum Published = new StatusEnum("published");
}
private static Request BuildReadRequest(ReadFlowRevisionOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Studio,
"/v2/Flows/" + options.PathSid + "/Revisions",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Retrieve a list of all Flows revisions.
/// </summary>
/// <param name="options"> Read FlowRevision parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of FlowRevision </returns>
public static ResourceSet<FlowRevisionResource> Read(ReadFlowRevisionOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<FlowRevisionResource>.FromJson("revisions", response.Content);
return new ResourceSet<FlowRevisionResource>(page, options, client);
}
#if !NET35
/// <summary>
/// Retrieve a list of all Flows revisions.
/// </summary>
/// <param name="options"> Read FlowRevision parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of FlowRevision </returns>
public static async System.Threading.Tasks.Task<ResourceSet<FlowRevisionResource>> ReadAsync(ReadFlowRevisionOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<FlowRevisionResource>.FromJson("revisions", response.Content);
return new ResourceSet<FlowRevisionResource>(page, options, client);
}
#endif
/// <summary>
/// Retrieve a list of all Flows revisions.
/// </summary>
/// <param name="pathSid"> The SID that identifies the resource to fetch </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of FlowRevision </returns>
public static ResourceSet<FlowRevisionResource> Read(string pathSid,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadFlowRevisionOptions(pathSid){PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// Retrieve a list of all Flows revisions.
/// </summary>
/// <param name="pathSid"> The SID that identifies the resource to fetch </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of FlowRevision </returns>
public static async System.Threading.Tasks.Task<ResourceSet<FlowRevisionResource>> ReadAsync(string pathSid,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadFlowRevisionOptions(pathSid){PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<FlowRevisionResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<FlowRevisionResource>.FromJson("revisions", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<FlowRevisionResource> NextPage(Page<FlowRevisionResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Studio)
);
var response = client.Request(request);
return Page<FlowRevisionResource>.FromJson("revisions", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<FlowRevisionResource> PreviousPage(Page<FlowRevisionResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Studio)
);
var response = client.Request(request);
return Page<FlowRevisionResource>.FromJson("revisions", response.Content);
}
private static Request BuildFetchRequest(FetchFlowRevisionOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Studio,
"/v2/Flows/" + options.PathSid + "/Revisions/" + options.PathRevision + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Retrieve a specific Flow revision.
/// </summary>
/// <param name="options"> Fetch FlowRevision parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of FlowRevision </returns>
public static FlowRevisionResource Fetch(FetchFlowRevisionOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Retrieve a specific Flow revision.
/// </summary>
/// <param name="options"> Fetch FlowRevision parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of FlowRevision </returns>
public static async System.Threading.Tasks.Task<FlowRevisionResource> FetchAsync(FetchFlowRevisionOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Retrieve a specific Flow revision.
/// </summary>
/// <param name="pathSid"> The SID that identifies the resource to fetch </param>
/// <param name="pathRevision"> Specific Revision number or can be `LatestPublished` and `LatestRevision` </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of FlowRevision </returns>
public static FlowRevisionResource Fetch(string pathSid, string pathRevision, ITwilioRestClient client = null)
{
var options = new FetchFlowRevisionOptions(pathSid, pathRevision);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// Retrieve a specific Flow revision.
/// </summary>
/// <param name="pathSid"> The SID that identifies the resource to fetch </param>
/// <param name="pathRevision"> Specific Revision number or can be `LatestPublished` and `LatestRevision` </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of FlowRevision </returns>
public static async System.Threading.Tasks.Task<FlowRevisionResource> FetchAsync(string pathSid,
string pathRevision,
ITwilioRestClient client = null)
{
var options = new FetchFlowRevisionOptions(pathSid, pathRevision);
return await FetchAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a FlowRevisionResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> FlowRevisionResource object represented by the provided JSON </returns>
public static FlowRevisionResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<FlowRevisionResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The unique string that identifies the resource
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The SID of the Account that created the resource
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The string that you assigned to describe the Flow
/// </summary>
[JsonProperty("friendly_name")]
public string FriendlyName { get; private set; }
/// <summary>
/// JSON representation of flow definition
/// </summary>
[JsonProperty("definition")]
public object Definition { get; private set; }
/// <summary>
/// The status of the Flow
/// </summary>
[JsonProperty("status")]
[JsonConverter(typeof(StringEnumConverter))]
public FlowRevisionResource.StatusEnum Status { get; private set; }
/// <summary>
/// The latest revision number of the Flow's definition
/// </summary>
[JsonProperty("revision")]
public int? Revision { get; private set; }
/// <summary>
/// Description of change made in the revision
/// </summary>
[JsonProperty("commit_message")]
public string CommitMessage { get; private set; }
/// <summary>
/// Boolean if the flow definition is valid
/// </summary>
[JsonProperty("valid")]
public bool? Valid { get; private set; }
/// <summary>
/// List of error in the flow definition
/// </summary>
[JsonProperty("errors")]
public List<object> Errors { get; private set; }
/// <summary>
/// The ISO 8601 date and time in GMT when the resource was created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// The ISO 8601 date and time in GMT when the resource was last updated
/// </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
/// <summary>
/// The absolute URL of the resource
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
private FlowRevisionResource()
{
}
}
}
| |
/*******************************************************************************
* Copyright 2017 ROBOTIS CO., LTD.
*
* 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.
*******************************************************************************/
/* Author: Ryu Woon Jung (Leon) */
//
// ********* Indirect Address Example *********
//
//
// Available Dynamixel model on this example : All models using Protocol 2.0
// This example is designed for using a Dynamixel PRO 54-200, and an USB2DYNAMIXEL.
// To use another Dynamixel model, such as X series, see their details in E-Manual(emanual.robotis.com) and edit below variables yourself.
// Be sure that Dynamixel PRO properties are already set as %% ID : 1 / Baudnum : 1 (Baudrate : 57600)
//
using System;
using System.Runtime.InteropServices;
using dynamixel_sdk;
namespace sync_write
{
class SyncWrite
{
// Control table address // Control table address is different in Dynamixel model
public const int ADDR_PRO_INDIRECTADDRESS_FOR_WRITE = 49; // EEPROM region
public const int ADDR_PRO_INDIRECTADDRESS_FOR_READ = 59; // EEPROM region
public const int ADDR_PRO_TORQUE_ENABLE = 562;
public const int ADDR_PRO_LED_RED = 563;
public const int ADDR_PRO_GOAL_POSITION = 596;
public const int ADDR_PRO_MOVING = 610;
public const int ADDR_PRO_PRESENT_POSITION = 611;
public const int ADDR_PRO_INDIRECTDATA_FOR_WRITE = 634;
public const int ADDR_PRO_INDIRECTDATA_FOR_READ = 639;
// Data Byte Length
public const int LEN_PRO_LED_RED = 1;
public const int LEN_PRO_GOAL_POSITION = 4;
public const int LEN_PRO_MOVING = 1;
public const int LEN_PRO_PRESENT_POSITION = 4;
public const int LEN_PRO_INDIRECTDATA_FOR_WRITE = 5;
public const int LEN_PRO_INDIRECTDATA_FOR_READ = 5;
// Protocol version
public const int PROTOCOL_VERSION = 2; // See which protocol version is used in the Dynamixel
// Default setting
public const int DXL_ID = 1; // Dynamixel ID: 1
public const int BAUDRATE = 57600;
public const string DEVICENAME = "COM1"; // Check which port is being used on your controller
// ex) Windows: "COM1" Linux: "/dev/ttyUSB0" Mac: "/dev/tty.usbserial-*"
public const int TORQUE_ENABLE = 1; // Value for enabling the torque
public const int TORQUE_DISABLE = 0; // Value for disabling the torque
public const int DXL_MINIMUM_POSITION_VALUE = -150000; // Dynamixel will rotate between this value
public const int DXL_MAXIMUM_POSITION_VALUE = 150000; // and this value (note that the Dynamixel would not move when the position value is out of movable range. Check e-manual about the range of the Dynamixel you use.)
public const int DXL_MINIMUM_LED_VALUE = 0; // Dynamixel LED will light between this value
public const int DXL_MAXIMUM_LED_VALUE = 255; // and this value
public const int DXL_MOVING_STATUS_THRESHOLD = 20; // Dynamixel moving status threshold
public const byte ESC_ASCII_VALUE = 0x1b;
public const int COMM_SUCCESS = 0; // Communication Success result value
public const int COMM_TX_FAIL = -1001; // Communication Tx Failed
static void Main(string[] args)
{
// Initialize PortHandler Structs
// Set the port path
// Get methods and members of PortHandlerLinux or PortHandlerWindows
int port_num = dynamixel.portHandler(DEVICENAME);
// Initialize PacketHandler Structs
dynamixel.packetHandler();
// Initialize Groupsyncwrite instance
int groupwrite_num = dynamixel.groupSyncWrite(port_num, PROTOCOL_VERSION, ADDR_PRO_INDIRECTDATA_FOR_WRITE, LEN_PRO_INDIRECTDATA_FOR_WRITE);
// Initialize Groupsyncread Structs for Present Position
int groupread_num = dynamixel.groupSyncRead(port_num, PROTOCOL_VERSION, ADDR_PRO_INDIRECTDATA_FOR_READ, LEN_PRO_INDIRECTDATA_FOR_READ);
int index = 0;
int dxl_comm_result = COMM_TX_FAIL; // Communication result
bool dxl_addparam_result = false; // AddParam result
bool dxl_getdata_result = false; // GetParam result
int[] dxl_goal_position = new int[2]{ DXL_MINIMUM_POSITION_VALUE, DXL_MAXIMUM_POSITION_VALUE }; // Goal position
byte dxl_error = 0; // Dynamixel error
byte dxl_moving = 0; // Dynamixel moving status
byte[] dxl_led_value = new byte[2]{ 0x00, 0xFF }; // Dynamixel LED value
Int32 dxl_present_position = 0; // Present position
// Open port
if (dynamixel.openPort(port_num))
{
Console.WriteLine("Succeeded to open the port!");
}
else
{
Console.WriteLine("Failed to open the port!");
Console.WriteLine("Press any key to terminate...");
Console.ReadKey();
return;
}
// Set port baudrate
if (dynamixel.setBaudRate(port_num, BAUDRATE))
{
Console.WriteLine("Succeeded to change the baudrate!");
}
else
{
Console.WriteLine("Failed to change the baudrate!");
Console.WriteLine("Press any key to terminate...");
Console.ReadKey();
return;
}
// Disable Dynamixel Torque :
// Indirect address would not accessible when the torque is already enabled
dynamixel.write1ByteTxRx(port_num, PROTOCOL_VERSION, DXL_ID, ADDR_PRO_TORQUE_ENABLE, TORQUE_DISABLE);
if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num, PROTOCOL_VERSION)) != COMM_SUCCESS)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result)));
}
else if ((dxl_error = dynamixel.getLastRxPacketError(port_num, PROTOCOL_VERSION)) != 0)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error)));
}
else
{
Console.WriteLine("Dynamixel has been successfully connected");
}
// INDIRECTDATA parameter storages replace LED, goal position, present position and moving status storages
dynamixel.write2ByteTxRx(port_num, PROTOCOL_VERSION, DXL_ID, ADDR_PRO_INDIRECTADDRESS_FOR_WRITE + 0, ADDR_PRO_GOAL_POSITION + 0);
if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num, PROTOCOL_VERSION)) != COMM_SUCCESS)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result)));
}
else if ((dxl_error = dynamixel.getLastRxPacketError(port_num, PROTOCOL_VERSION)) != 0)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error)));
}
dynamixel.write2ByteTxRx(port_num, PROTOCOL_VERSION, DXL_ID, ADDR_PRO_INDIRECTADDRESS_FOR_WRITE + 2, ADDR_PRO_GOAL_POSITION + 1);
if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num, PROTOCOL_VERSION)) != COMM_SUCCESS)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result)));
}
else if ((dxl_error = dynamixel.getLastRxPacketError(port_num, PROTOCOL_VERSION)) != 0)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error)));
}
dynamixel.write2ByteTxRx(port_num, PROTOCOL_VERSION, DXL_ID, ADDR_PRO_INDIRECTADDRESS_FOR_WRITE + 4, ADDR_PRO_GOAL_POSITION + 2);
if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num, PROTOCOL_VERSION)) != COMM_SUCCESS)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result)));
}
else if ((dxl_error = dynamixel.getLastRxPacketError(port_num, PROTOCOL_VERSION)) != 0)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error)));
}
dynamixel.write2ByteTxRx(port_num, PROTOCOL_VERSION, DXL_ID, ADDR_PRO_INDIRECTADDRESS_FOR_WRITE + 6, ADDR_PRO_GOAL_POSITION + 3);
if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num, PROTOCOL_VERSION)) != COMM_SUCCESS)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result)));
}
else if ((dxl_error = dynamixel.getLastRxPacketError(port_num, PROTOCOL_VERSION)) != 0)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error)));
}
dynamixel.write2ByteTxRx(port_num, PROTOCOL_VERSION, DXL_ID, ADDR_PRO_INDIRECTADDRESS_FOR_WRITE + 8, ADDR_PRO_LED_RED);
if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num, PROTOCOL_VERSION)) != COMM_SUCCESS)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result)));
}
else if ((dxl_error = dynamixel.getLastRxPacketError(port_num, PROTOCOL_VERSION)) != 0)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error)));
}
dynamixel.write2ByteTxRx(port_num, PROTOCOL_VERSION, DXL_ID, ADDR_PRO_INDIRECTADDRESS_FOR_READ + 0, ADDR_PRO_PRESENT_POSITION + 0);
if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num, PROTOCOL_VERSION)) != COMM_SUCCESS)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result)));
}
else if ((dxl_error = dynamixel.getLastRxPacketError(port_num, PROTOCOL_VERSION)) != 0)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error)));
}
dynamixel.write2ByteTxRx(port_num, PROTOCOL_VERSION, DXL_ID, ADDR_PRO_INDIRECTADDRESS_FOR_READ + 2, ADDR_PRO_PRESENT_POSITION + 1);
if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num, PROTOCOL_VERSION)) != COMM_SUCCESS)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result)));
}
else if ((dxl_error = dynamixel.getLastRxPacketError(port_num, PROTOCOL_VERSION)) != 0)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error)));
}
dynamixel.write2ByteTxRx(port_num, PROTOCOL_VERSION, DXL_ID, ADDR_PRO_INDIRECTADDRESS_FOR_READ + 4, ADDR_PRO_PRESENT_POSITION + 2);
if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num, PROTOCOL_VERSION)) != COMM_SUCCESS)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result)));
}
else if ((dxl_error = dynamixel.getLastRxPacketError(port_num, PROTOCOL_VERSION)) != 0)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error)));
}
dynamixel.write2ByteTxRx(port_num, PROTOCOL_VERSION, DXL_ID, ADDR_PRO_INDIRECTADDRESS_FOR_READ + 6, ADDR_PRO_PRESENT_POSITION + 3);
if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num, PROTOCOL_VERSION)) != COMM_SUCCESS)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result)));
}
else if ((dxl_error = dynamixel.getLastRxPacketError(port_num, PROTOCOL_VERSION)) != 0)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error)));
}
dynamixel.write2ByteTxRx(port_num, PROTOCOL_VERSION, DXL_ID, ADDR_PRO_INDIRECTADDRESS_FOR_READ + 8, ADDR_PRO_MOVING);
if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num, PROTOCOL_VERSION)) != COMM_SUCCESS)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result)));
}
else if ((dxl_error = dynamixel.getLastRxPacketError(port_num, PROTOCOL_VERSION)) != 0)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error)));
}
// Enable Dynamixel Torque
dynamixel.write1ByteTxRx(port_num, PROTOCOL_VERSION, DXL_ID, ADDR_PRO_TORQUE_ENABLE, TORQUE_ENABLE);
if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num, PROTOCOL_VERSION)) != COMM_SUCCESS)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result)));
}
else if ((dxl_error = dynamixel.getLastRxPacketError(port_num, PROTOCOL_VERSION)) != 0)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error)));
}
// Add parameter storage for Dynamixel present position value
dxl_addparam_result = dynamixel.groupSyncReadAddParam(groupread_num, DXL_ID);
if (dxl_addparam_result != true)
{
Console.WriteLine("[ID: {0}] groupSyncRead addparam failed", DXL_ID);
return;
}
while (true)
{
Console.WriteLine("Press any key to continue! (or press ESC to quit!)");
if (Console.ReadKey().KeyChar == ESC_ASCII_VALUE)
break;
// Add values to the Syncwrite storage
dxl_addparam_result = dynamixel.groupSyncWriteAddParam(groupwrite_num, DXL_ID, (UInt32)dxl_goal_position[index], LEN_PRO_GOAL_POSITION);
if (dxl_addparam_result != true)
{
Console.WriteLine("[ID: {0}] groupSyncWrite addparam failed", DXL_ID);
return;
}
dxl_addparam_result = dynamixel.groupSyncWriteAddParam(groupwrite_num, DXL_ID, dxl_led_value[index], LEN_PRO_LED_RED);
if (dxl_addparam_result != true)
{
Console.WriteLine("[ID: {0}] groupSyncWrite addparam failed", DXL_ID);
return;
}
// Syncwrite goal position
dynamixel.groupSyncWriteTxPacket(groupwrite_num);
if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num, PROTOCOL_VERSION)) != COMM_SUCCESS)
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result)));
// Clear syncwrite parameter storage
dynamixel.groupSyncWriteClearParam(groupwrite_num);
do
{
// Syncread present position from indirectdata2
dynamixel.groupSyncReadTxRxPacket(groupread_num);
if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num, PROTOCOL_VERSION)) != COMM_SUCCESS)
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result)));
// Check if groupsyncread data of Dyanamixel is available
dxl_getdata_result = dynamixel.groupSyncReadIsAvailable(groupread_num, DXL_ID, ADDR_PRO_INDIRECTDATA_FOR_READ, LEN_PRO_PRESENT_POSITION);
if (dxl_getdata_result != true)
{
Console.WriteLine("[ID: {0}] groupSyncRead getdata failed", DXL_ID);
return;
}
// Check if groupsyncread data of Dyanamixel is available
dxl_getdata_result = dynamixel.groupSyncReadIsAvailable(groupread_num, DXL_ID, ADDR_PRO_INDIRECTDATA_FOR_READ + LEN_PRO_PRESENT_POSITION, LEN_PRO_MOVING);
if (dxl_getdata_result != true)
{
Console.WriteLine("[ID: {0}] groupSyncRead getdata failed", DXL_ID);
return;
}
// Get Dynamixel present position value
dxl_present_position = (Int32)dynamixel.groupSyncReadGetData(groupread_num, DXL_ID, ADDR_PRO_INDIRECTDATA_FOR_READ, LEN_PRO_PRESENT_POSITION);
// Get Dynamixel moving status value
dxl_moving = (byte)dynamixel.groupSyncReadGetData(groupread_num, DXL_ID, ADDR_PRO_INDIRECTDATA_FOR_READ + LEN_PRO_PRESENT_POSITION, LEN_PRO_MOVING);
Console.WriteLine("[ID: {0}] GoalPos: {1} PresPos: {2} IsMoving: {3}", DXL_ID, dxl_goal_position[index], dxl_present_position, dxl_moving);
} while (Math.Abs(dxl_goal_position[index] - dxl_present_position) > DXL_MOVING_STATUS_THRESHOLD);
// Change goal position
if (index == 0)
{
index = 1;
}
else
{
index = 0;
}
}
// Disable Dynamixel Torque
dynamixel.write1ByteTxRx(port_num, PROTOCOL_VERSION, DXL_ID, ADDR_PRO_TORQUE_ENABLE, TORQUE_DISABLE);
if ((dxl_comm_result = dynamixel.getLastTxRxResult(port_num, PROTOCOL_VERSION)) != COMM_SUCCESS)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getTxRxResult(PROTOCOL_VERSION, dxl_comm_result)));
}
else if ((dxl_error = dynamixel.getLastRxPacketError(port_num, PROTOCOL_VERSION)) != 0)
{
Console.WriteLine(Marshal.PtrToStringAnsi(dynamixel.getRxPacketError(PROTOCOL_VERSION, dxl_error)));
}
// Close port
dynamixel.closePort(port_num);
return;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using iSukces.Code.Interfaces;
namespace iSukces.Code.Irony
{
public class NonTerminalInfo : TokenInfo, ICsExpression
{
public NonTerminalInfo(TokenName name) : base(name)
{
var factory = AstClassNameFactory ?? DefaultAstClassNameFactory;
AstClass = factory(name);
factory = DataClassNameFactory ?? DefaultDataClassNameFactory;
DataClass = factory(name);
}
public static TypeNameProviderEx DefaultAstClassNameFactory(TokenName name)
{
var a = new StringTypeNameProvider(".Ast" + name.GetCamelTerminalName());
return new TypeNameProviderEx(a, TypeNameProviderFlags.CreateAutoCode);
}
public static TypeNameProviderEx DefaultDataClassNameFactory(TokenName name)
{
var a = new StringTypeNameProvider(".Data" + name.GetCamelTerminalName());
return new TypeNameProviderEx(a, TypeNameProviderFlags.CreateAutoCode);
}
public static NonTerminalInfo Parse(string parsecode)
{
var parts = (parsecode + ",,,,").Split(',').Select(a => a.Trim()).ToArray();
var result = new NonTerminalInfo(new TokenName(parts[0]));
if (parts.Length > 1)
{
var baseClass = parts[1];
if (!string.IsNullOrEmpty(baseClass))
result.AstBaseClassTypeName = new StringTypeNameProvider(baseClass);
}
/*var createClassCommand = parts[2].ToLower();
result.as
result.CreateAstClass = createClassCommand == "" || createClassCommand == "true";*/
return result;
}
private static TermListOptions2 EncodeDelimiters(Delimiters2 a)
{
var r = TermListOptions2.None;
if ((a & Delimiters2.Starting) != 0)
r |= TermListOptions2.AllowStartingDelimiter;
if ((a & Delimiters2.Trailing) != 0)
r |= TermListOptions2.AllowTrailingDelimiter;
return r;
}
private static TypeNameProviderEx GetAlternativeInterfaceName(TokenName name)
{
var provider = new StringTypeNameProvider(".IAst" + name.GetCamelTerminalName());
return new TypeNameProviderEx(provider,
TypeNameProviderFlags.CreateAutoCode | TypeNameProviderFlags.IsInterface);
}
/*
public NonTerminalInfo AsExpressionList(string listItemName)
{
// // "using_directives,ExpressionListNode<UsingStatement>",
BaseClassNameFactory = _ => "ExpressionListNode<" + listItemName + ">";
return this;
}
*/
/*public NonTerminalInfo AsExpressionList<T>()
{
BaseClassNameFactory = r =>
{
var t = typeof(ExpressionListNode<>).MakeGenericType(typeof(T));
return r.GetTypeName(t);
};
return this;
}*/
public NonTerminalInfo AsOneOf(params ICsExpression[] elements) => AsOneOf(null, elements);
public NonTerminalInfo AsOneOf(Action<RuleBuilder.ListAlternative> setup,
params ICsExpression[] elements)
{
var map = new[] {new MapInfo(0, 0)};
var alternativeInterfaceName = GetAlternativeInterfaceName(Name);
var rule = new RuleBuilder.ListAlternative(alternativeInterfaceName,
map, elements);
Rule = rule;
if (setup != null)
setup(rule);
return this;
}
public NonTerminalInfo AsOptional(TokenInfo basedOn)
{
var alternativeInterfaceName = GetAlternativeInterfaceName(Name);
Rule = new RuleBuilder.OptionAlternative(basedOn, alternativeInterfaceName);
return this;
}
public string GetBaseClassAndInterfaces(IReadOnlyList<NonTerminalInfo> nonterminals,
ITypeNameResolver resolver, string classNamespace)
{
var baseClass = AstBaseClassTypeName?.GetTypeName(resolver, classNamespace)?.Name;
if (string.IsNullOrEmpty(baseClass))
throw new Exception("Empty base class");
var list = new List<string> {baseClass};
foreach (var i in nonterminals)
{
if (!(i.Rule is RuleBuilder.ListAlternative al))
continue;
if (al.Contains(Name))
{
var tmp = al.AlternativeInterfaceName;
if (tmp.IsInterface)
{
var n = tmp.Provider.GetTypeName(resolver, classNamespace);
list.Add(n.Name);
}
}
}
return string.Join(",", list.Distinct());
}
public override string GetCode(ITypeNameResolver resolver) => Name.GetCode(resolver);
public override TokenNameTarget GetTokenNameIsNonterminal() => TokenNameTarget.Terminal;
public override string ToString() => "NonTerminal " + Name.Name;
public NonTerminalInfo WithDataBaseClassName(Type type)
{
DataBaseClassName = new TypeNameProvider(type);
return this;
}
public NonTerminalInfo WithNoAstClass()
{
var newFlags = AstClass.Flags & ~TypeNameProviderFlags.CreateAutoCode;
AstClass = new TypeNameProviderEx(AstClass.Provider, newFlags);
return this;
}
/*public NonTerminalInfo WithDataClassName(ITypeNameProvider name)
{
DataClassName2 = name;
return this;
}
public NonTerminalInfo WithDataClassName(string name, Type baseType = null)
{
DataClassName = new StringTypeNameProvider(name);
if (baseType != null)
WithDataBaseClassName(baseType);
return this;
}*/
public NonTerminalInfo WithNoDataClass()
{
var newFlags = DataClass.Flags & ~TypeNameProviderFlags.CreateAutoCode;
DataClass = new TypeNameProviderEx(DataClass.Provider, newFlags);
return this;
}
public NonTerminalInfo WithPlusRule(ICsExpression delimiter, TokenName element,
Delimiters2 delimiters = Delimiters2.None)
{
var options = TermListOptions2.PlusList;
options |= EncodeDelimiters(delimiters);
Rule = new RuleBuilder.PlusOrStar(delimiter, element, options, Name);
return this;
}
public NonTerminalInfo WithPlusRule(TokenName element) => WithPlusRule(null, element);
public NonTerminalInfo WithPlusRule(ICsExpression delimiter, ITokenNameSource element,
Delimiters2 delimiters = Delimiters2.None)
{
var options = TermListOptions2.PlusList;
options |= EncodeDelimiters(delimiters);
Rule = new RuleBuilder.PlusOrStar(delimiter, element, options, Name);
return this;
}
public NonTerminalInfo WithRule(RuleBuilder rule)
{
Rule = rule;
return this;
}
public NonTerminalInfo WithSequenceRule(SequenceRuleBuilder builder)
{
var map = builder.GetMap();
WithSequenceRule(null, map, builder.GetRuleItems());
return this;
}
public NonTerminalInfo WithSequenceRule(Action<RuleBuilder.SequenceRule> process,
IReadOnlyList<MapInfo> map, IReadOnlyList<RuleBuilder.SequenceRule.SequenceItem> items)
{
var sequenceRule = new RuleBuilder.SequenceRule(items, map);
process?.Invoke(sequenceRule);
Rule = sequenceRule;
return this;
}
public NonTerminalInfo WithStarRule(ICsExpression delimiter, ITokenNameSource element,
Delimiters2 delimiters = Delimiters2.None)
{
var options = TermListOptions2.StarList;
options |= EncodeDelimiters(delimiters);
Rule = new RuleBuilder.PlusOrStar(delimiter, element, options, Name);
return this;
}
public NonTerminalInfo WithStarRule(ITokenNameSource element,
Delimiters2 addPreferShiftHint = Delimiters2.None) =>
WithStarRule(null, element, addPreferShiftHint);
public TypeNameProviderEx AstClass { get; set; }
public TypeNameProviderEx DataClass { get; set; }
public ITypeNameProvider AstBaseClassTypeName { get; set; }
public RuleBuilder Rule
{
get { return _rule; }
set
{
if (!(_rule is null))
throw new Exception("Rule already set");
_rule = value;
}
}
public ITypeNameProvider DataBaseClassName { get; set; }
public static Func<TokenName, TypeNameProviderEx> AstClassNameFactory = DefaultAstClassNameFactory;
public static Func<TokenName, TypeNameProviderEx> DataClassNameFactory = DefaultDataClassNameFactory;
private RuleBuilder _rule;
}
[Flags]
public enum TermListOptions2
{
None = 0,
AllowEmpty = 1,
AllowTrailingDelimiter = 2,
AddPreferShiftHint = 4,
PlusList = AddPreferShiftHint,
StarList = PlusList | AllowEmpty,
AllowStartingDelimiter = 8,
BothDelimiters = AllowStartingDelimiter | AllowTrailingDelimiter
}
[Flags]
public enum Delimiters2
{
None = 0,
Starting = 1,
Trailing = 2,
Both = Starting | Trailing
}
}
| |
using static DiffMatchPatch.Operation;
namespace DiffMatchPatch;
public static class DiffList
{
/// <summary>
/// Compute and return the source text (all equalities and deletions).
/// </summary>
/// <param name="diffs"></param>
/// <returns></returns>
public static string Text1(this IEnumerable<Diff> diffs)
=> diffs
.Where(d => d.Operation != Insert)
.Aggregate(new StringBuilder(), (sb, diff) => sb.Append(diff.Text))
.ToString();
/// <summary>
/// Compute and return the destination text (all equalities and insertions).
/// </summary>
/// <param name="diffs"></param>
/// <returns></returns>
public static string Text2(this IEnumerable<Diff> diffs)
=> diffs
.Where(d => d.Operation != Delete)
.Aggregate(new StringBuilder(), (sb, diff) => sb.Append(diff.Text))
.ToString();
readonly record struct LevenshteinState(int Insertions, int Deletions, int Levenshtein)
{
public LevenshteinState Consolidate() => new(0, 0, Levenshtein + Math.Max(Insertions, Deletions));
}
/// <summary>
/// Compute the Levenshtein distance; the number of inserted, deleted or substituted characters.
/// </summary>
/// <param name="diffs"></param>
/// <returns></returns>
internal static int Levenshtein(this IEnumerable<Diff> diffs)
{
var state = new LevenshteinState(0, 0, 0);
foreach (var aDiff in diffs)
{
state = aDiff.Operation switch
{
Insert => state with { Insertions = state.Insertions + aDiff.Text.Length },
Delete => state with { Deletions = state.Deletions + aDiff.Text.Length },
Equal => state.Consolidate(),
_ => throw new IndexOutOfRangeException()
};
}
return state.Consolidate().Levenshtein;
}
private static StringBuilder AppendHtml(this StringBuilder sb, string tag, string backgroundColor, string content)
=> sb
.Append(string.IsNullOrEmpty(backgroundColor) ? $"<{tag}>" : $"<{tag} style=\"background:{backgroundColor};\">")
.Append(content)
.Append($"</{tag}>");
private static StringBuilder AppendHtml(this StringBuilder sb, Operation operation, string text) => operation switch
{
Insert => sb.AppendHtml("ins", "#e6ffe6", text),
Delete => sb.AppendHtml("del", "#ffe6e6", text),
Equal => sb.AppendHtml("span", "", text),
_ => throw new IndexOutOfRangeException()
};
/// <summary>
/// Convert a Diff list into a pretty HTML report.
/// </summary>
/// <param name="diffs"></param>
/// <returns></returns>
public static string PrettyHtml(this IEnumerable<Diff> diffs) => diffs
.Aggregate(new StringBuilder(), (sb, diff) => sb.AppendHtml(diff.Operation, diff.Text.HtmlEncodeLight()))
.ToString();
private static string HtmlEncodeLight(this string s)
{
var text = new StringBuilder(s)
.Replace("&", "&")
.Replace("<", "<")
.Replace(">", ">")
.Replace("\n", "¶<br>")
.ToString();
return text;
}
static char ToDelta(this Operation o) => o switch
{
Delete => '-',
Insert => '+',
Equal => '=',
_ => throw new ArgumentException($"Unknown Operation: {o}")
};
static Operation FromDelta(char c) => c switch
{
'-' => Delete,
'+' => Insert,
'=' => Equal,
_ => throw new ArgumentException($"Invalid Delta Token: {c}")
};
/// <summary>
/// Crush the diff into an encoded string which describes the operations
/// required to transform text1 into text2.
/// E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'.
/// Operations are tab-separated. Inserted text is escaped using %xx
/// notation.
/// </summary>
/// <param name="diffs"></param>
/// <returns></returns>
public static string ToDelta(this IEnumerable<Diff> diffs)
{
var s =
from aDiff in diffs
let sign = aDiff.Operation.ToDelta()
let textToAppend = aDiff.Operation == Insert
? aDiff.Text.UrlEncoded()
: aDiff.Text.Length.ToString()
select string.Concat(sign, textToAppend);
var delta = string.Join("\t", s);
return delta;
}
/// <summary>
/// Given the original text1, and an encoded string which describes the
/// operations required to transform text1 into text2, compute the full diff.
/// </summary>
/// <param name="text1">Source string for the diff.</param>
/// <param name="delta">Delta text.</param>
/// <returns></returns>
public static IEnumerable<Diff> FromDelta(string text1, string delta)
{
var pointer = 0; // Cursor in text1
foreach (var token in delta.SplitBy('\t'))
{
if (token.Length == 0)
{
// Blank tokens are ok (from a trailing \t).
continue;
}
// Each token begins with a one character parameter which specifies the
// operation of this token (delete, insert, equality).
var param = token[1..];
var operation = FromDelta(token[0]);
int n = 0;
if (operation != Insert)
{
if (!int.TryParse(param, out n))
{
throw new ArgumentException($"Invalid number in Diff.FromDelta: {param}");
}
if (pointer > text1.Length - n)
{
throw new ArgumentException($"Delta length ({pointer}) larger than source text length ({text1.Length}).");
}
}
string text;
(text, pointer) = operation switch
{
Insert => (param.Replace("+", "%2b").UrlDecoded(), pointer),
Equal => (text1.Substring(pointer, n), pointer + n),
Delete => (text1.Substring(pointer, n), pointer + n),
_ => throw new ArgumentException($"Unknown Operation: {operation}")
};
yield return Diff.Create(operation, text);
}
if (pointer != text1.Length)
{
throw new ArgumentException($"Delta length ({pointer}) smaller than source text length ({text1.Length}).");
}
}
internal static IEnumerable<Diff> CleanupMergePass1(this IEnumerable<Diff> diffs)
{
var sbDelete = new StringBuilder();
var sbInsert = new StringBuilder();
Diff lastEquality = Diff.Empty;
var enumerator = diffs.Concat(Diff.Empty).GetEnumerator();
while (enumerator.MoveNext())
{
var diff = enumerator.Current;
(sbInsert, sbDelete) = diff.Operation switch
{
Insert => (sbInsert.Append(diff.Text), sbDelete),
Delete => (sbInsert, sbDelete.Append(diff.Text)),
_ => (sbInsert, sbDelete)
};
switch (diff.Operation)
{
case Equal:
// Upon reaching an equality, check for prior redundancies.
if (sbInsert.Length > 0 || sbDelete.Length > 0)
{
// first equality after number of inserts/deletes
// Factor out any common prefixies.
var prefixLength = TextUtil.CommonPrefix(sbInsert, sbDelete);
if (prefixLength > 0)
{
var commonprefix = sbInsert.ToString(0, prefixLength);
sbInsert.Remove(0, prefixLength);
sbDelete.Remove(0, prefixLength);
lastEquality = lastEquality.Append(commonprefix);
}
// Factor out any common suffixies.
var suffixLength = TextUtil.CommonSuffix(sbInsert, sbDelete);
if (suffixLength > 0)
{
var commonsuffix = sbInsert.ToString(sbInsert.Length - suffixLength, suffixLength);
sbInsert.Remove(sbInsert.Length - suffixLength, suffixLength);
sbDelete.Remove(sbDelete.Length - suffixLength, suffixLength);
diff = diff.Prepend(commonsuffix);
}
// Delete the offending records and add the merged ones.
if (!lastEquality.IsEmpty)
{
yield return lastEquality;
}
if (sbDelete.Length > 0) yield return Diff.Delete(sbDelete.ToString());
if (sbInsert.Length > 0) yield return Diff.Insert(sbInsert.ToString());
lastEquality = diff;
sbDelete.Clear();
sbInsert.Clear();
}
else
{
// Merge this equality with the previous one.
lastEquality = lastEquality.Append(diff.Text);
}
break;
}
}
if (!lastEquality.IsEmpty)
yield return lastEquality;
}
internal static IEnumerable<Diff> CleanupMergePass2(this IEnumerable<Diff> input, out bool haschanges)
{
haschanges = false;
// Second pass: look for single edits surrounded on both sides by
// equalities which can be shifted sideways to eliminate an equality.
// e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
var diffs = input.ToList();
// Intentionally ignore the first and last element (don't need checking).
for (var i = 1; i < diffs.Count - 1; i++)
{
var previous = diffs[i - 1];
var current = diffs[i];
var next = diffs[i + 1];
if (previous.Operation == Equal && next.Operation == Equal)
{
// This is a single edit surrounded by equalities.
if (current.Text.EndsWith(previous.Text, StringComparison.Ordinal))
{
// Shift the edit over the previous equality.
var text = previous.Text + current.Text.Substring(0, current.Text.Length - previous.Text.Length);
diffs[i] = current.Replace(text);
diffs[i + 1] = next.Replace(previous.Text + next.Text);
diffs.Splice(i - 1, 1);
haschanges = true;
}
else if (current.Text.StartsWith(next.Text, StringComparison.Ordinal))
{
// Shift the edit over the next equality.
diffs[i - 1] = previous.Replace(previous.Text + next.Text);
diffs[i] = current.Replace(current.Text[next.Text.Length..] + next.Text);
diffs.Splice(i + 1, 1);
haschanges = true;
}
}
}
return diffs;
}
/// <summary>
/// Reorder and merge like edit sections. Merge equalities.
/// Any edit section can move as long as it doesn't cross an equality.
/// </summary>
/// <param name="diffs">list of Diffs</param>
internal static IEnumerable<Diff> CleanupMerge(this IEnumerable<Diff> diffs)
{
bool changes;
do
{
diffs = diffs
.CleanupMergePass1()
.CleanupMergePass2(out changes)
.ToList(); // required to detect if anything changed
} while (changes);
return diffs;
}
readonly record struct EditBetweenEqualities(string Equality1, string Edit, string Equality2)
{
public int Score => DiffCleanupSemanticScore(Equality1, Edit) + DiffCleanupSemanticScore(Edit, Equality2);
readonly record struct ScoreHelper(string Str, Index I, Regex Regex)
{
char C => Str[I];
public bool IsEmpty => Str.Length == 0;
public bool NonAlphaNumeric => !char.IsLetterOrDigit(C);
public bool IsWhitespace => char.IsWhiteSpace(C);
public bool IsLineBreak => C == '\n' || C == '\r';
public bool IsBlankLine => IsLineBreak && Regex.IsMatch(Str);
}
/// Given two strings, computes a score representing whether the internal boundary falls on logical boundaries.
/// higher is better
private static int DiffCleanupSemanticScore(string one, string two)
=> (h1: new ScoreHelper(one, ^1, BlankLineEnd), h2: new ScoreHelper(two, 0, BlankLineStart)) switch
{
{ h1.IsEmpty: true } or { h2.IsEmpty: true } => 6,
{ h1.IsBlankLine: true } or { h2.IsBlankLine: true } => 5,
{ h1.IsLineBreak: true } or { h2.IsLineBreak: true } => 4,
{ h1.NonAlphaNumeric: true } and { h1.IsWhitespace: false } and { h2.IsWhitespace: true } => 3,
{ h1.IsWhitespace: true } or { h2.IsWhitespace: true } => 2,
{ h1.NonAlphaNumeric: true } or { h2.NonAlphaNumeric: true } => 1,
_ => 0
};
// Shift the edit as far left as possible.
public EditBetweenEqualities ShiftLeft()
{
var commonOffset = TextUtil.CommonSuffix(Equality1, Edit);
if (commonOffset > 0)
{
var commonString = Edit[^commonOffset..];
var equality1 = Equality1.Substring(0, Equality1.Length - commonOffset);
var edit = commonString + Edit.Substring(0, Edit.Length - commonOffset);
var equality2 = commonString + Equality2;
return this with { Equality1 = equality1, Edit = edit, Equality2 = equality2 };
}
else
{
return this;
}
}
// Shift one right
EditBetweenEqualities ShiftRight() => this with { Equality1 = Equality1 + Edit[0], Edit = Edit[1..] + Equality2[0], Equality2 = Equality2[1..] };
public IEnumerable<EditBetweenEqualities> TraverseRight()
{
var item = this;
while (item.Edit.Length != 0 && item.Equality2.Length != 0 && item.Edit[0] == item.Equality2[0])
{
yield return item = item.ShiftRight();
}
}
public IEnumerable<Diff> ToDiffs(Operation edit)
{
yield return Diff.Equal(Equality1);
yield return Diff.Create(edit, Edit);
yield return Diff.Equal(Equality2);
}
}
/// <summary>
/// Look for single edits surrounded on both sides by equalities
/// which can be shifted sideways to align the edit to a word boundary.
/// e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.
/// </summary>
/// <param name="diffs"></param>
internal static IEnumerable<Diff> CleanupSemanticLossless(this IEnumerable<Diff> diffs)
{
var enumerator = diffs.GetEnumerator();
if (!enumerator.MoveNext()) yield break;
var previous = enumerator.Current;
if (!enumerator.MoveNext())
{
yield return previous;
yield break;
}
var current = enumerator.Current;
while (true)
{
if (!enumerator.MoveNext())
{
yield return previous;
yield return current;
yield break;
}
var next = enumerator.Current;
if (previous.Operation == Equal && next.Operation == Equal)
{
// This is a single edit surrounded by equalities.
var item = new EditBetweenEqualities(previous.Text, current.Text, next.Text).ShiftLeft();
// Second, step character by character right, looking for the best fit.
var best = item.TraverseRight().Aggregate(item, (best, x) => best.Score > x.Score ? best : x);
if (previous.Text != best.Equality1)
{
// We have an improvement; yield the improvement instead of the original diffs
foreach (var d in best.ToDiffs(current.Operation).Where(d => !d.IsEmpty))
yield return d;
if (!enumerator.MoveNext())
yield break;
previous = current;
current = next;
next = enumerator.Current;
}
else
{
yield return previous;
}
}
else
{
yield return previous;
}
previous = current;
current = next;
}
}
// Define some regex patterns for matching boundaries.
private static readonly Regex BlankLineEnd = new("\\n\\r?\\n\\Z", RegexOptions.Compiled);
private static readonly Regex BlankLineStart = new("\\A\\r?\\n\\r?\\n", RegexOptions.Compiled);
/// <summary>
/// Reduce the number of edits by eliminating operationally trivial equalities.
/// </summary>
/// <param name="diffs"></param>
/// <param name="diffEditCost"></param>
internal static IEnumerable<Diff> CleanupEfficiency(this IEnumerable<Diff> input, short diffEditCost = 4)
{
var diffs = input.ToList();
var changes = false;
// Stack of indices where equalities are found.
var equalities = new Stack<int>();
// Always equal to equalities[equalitiesLength-1][1]
var lastEquality = string.Empty;
// Is there an insertion operation before the last equality.
var insertionBeforeLastEquality = false;
// Is there a deletion operation before the last equality.
var deletionBeforeLastEquality = false;
// Is there an insertion operation after the last equality.
var insertionAfterLastEquality = false;
// Is there a deletion operation after the last equality.
var deletionAfterLastEquality = false;
for (var i = 0; i < diffs.Count; i++)
{
var diff = diffs[i];
if (diff.Operation == Equal)
{ // Equality found.
if (diff.Text.Length < diffEditCost && (insertionAfterLastEquality || deletionAfterLastEquality))
{
// Candidate found.
equalities.Push(i);
(insertionBeforeLastEquality, deletionBeforeLastEquality) = (insertionAfterLastEquality, deletionAfterLastEquality);
lastEquality = diff.Text;
}
else
{
// Not a candidate, and can never become one.
equalities.Clear();
lastEquality = string.Empty;
}
insertionAfterLastEquality = deletionAfterLastEquality = false;
}
else
{ // An insertion or deletion.
if (diff.Operation == Delete)
{
deletionAfterLastEquality = true;
}
else
{
insertionAfterLastEquality = true;
}
/*
* Five types to be split:
* <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
* <ins>A</ins>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<ins>C</ins>
* <ins>A</del>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<del>C</del>
*/
if ((lastEquality.Length != 0)
&& ((insertionBeforeLastEquality && deletionBeforeLastEquality && insertionAfterLastEquality && deletionAfterLastEquality)
|| ((lastEquality.Length < diffEditCost / 2)
&& (insertionBeforeLastEquality ? 1 : 0) + (deletionBeforeLastEquality ? 1 : 0) + (insertionAfterLastEquality ? 1 : 0)
+ (deletionAfterLastEquality ? 1 : 0) == 3)))
{
// replace equality by delete/insert
diffs.Splice(equalities.Peek(), 1, Diff.Delete(lastEquality), Diff.Insert(lastEquality));
equalities.Pop(); // Throw away the equality we just deleted.
lastEquality = string.Empty;
if (insertionBeforeLastEquality && deletionBeforeLastEquality)
{
// No changes made which could affect previous entry, keep going.
insertionAfterLastEquality = deletionAfterLastEquality = true;
equalities.Clear();
}
else
{
if (equalities.Count > 0)
{
equalities.Pop();
}
i = equalities.Count > 0 ? equalities.Peek() : -1;
insertionAfterLastEquality = deletionAfterLastEquality = false;
}
changes = true;
}
}
}
if (changes)
{
return diffs.CleanupMerge();
}
return input;
}
/// <summary>
/// A diff of two unrelated texts can be filled with coincidental matches.
/// For example, the diff of "mouse" and "sofas" is
/// `[(-1, "m"), (1, "s"), (0, "o"), (-1, "u"), (1, "fa"), (0, "s"), (-1, "e")]`.
/// While this is the optimum diff, it is difficult for humans to understand. Semantic
/// cleanup rewrites the diff, expanding it into a more intelligible format. The above
/// example would become: `[(-1, "mouse"), (1, "sofas")]`.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static IImmutableList<Diff> MakeHumanReadable(this IEnumerable<Diff> input) => input.CleanupSemantic().ToImmutableList();
/// <summary>
/// This function is similar to `OptimizeForReadability`, except that instead of optimising a diff
/// to be human-readable, it optimises the diff to be efficient for machine processing. The results
/// of both cleanup types are often the same.
/// The efficiency cleanup is based on the observation that a diff made up of large numbers of
/// small diffs edits may take longer to process(in downstream applications) or take more capacity
/// to store or transmit than a smaller number of larger diffs.
/// </summary>
/// <param name="input"></param>
/// <param name="diffEditCost">The cost of handling a new edit in terms of handling extra characters in an existing edit.
/// The default value is 4, which means if expanding the length of a diff by three characters can eliminate one edit,
/// then that optimisation will reduce the total costs</param>
/// <returns></returns>
public static IImmutableList<Diff> OptimizeForMachineProcessing(this IEnumerable<Diff> input, short diffEditCost = 4) => input.CleanupEfficiency(diffEditCost).ToImmutableList();
/// <summary>
/// Reduce the number of edits by eliminating semantically trivial equalities.
/// </summary>
/// <param name="diffs"></param>
internal static List<Diff> CleanupSemantic(this IEnumerable<Diff> input)
{
var diffs = input.ToList();
// Stack of indices where equalities are found.
var equalities = new Stack<int>();
// Always equal to equalities[equalitiesLength-1][1]
string? lastEquality = null;
var pointer = 0; // Index of current position.
// Number of characters that changed prior to the equality.
var lengthInsertions1 = 0;
var lengthDeletions1 = 0;
// Number of characters that changed after the equality.
var lengthInsertions2 = 0;
var lengthDeletions2 = 0;
while (pointer < diffs.Count)
{
if (diffs[pointer].Operation == Equal)
{ // Equality found.
equalities.Push(pointer);
lengthInsertions1 = lengthInsertions2;
lengthDeletions1 = lengthDeletions2;
lengthInsertions2 = 0;
lengthDeletions2 = 0;
lastEquality = diffs[pointer].Text;
}
else
{ // an insertion or deletion
if (diffs[pointer].Operation == Insert)
{
lengthInsertions2 += diffs[pointer].Text.Length;
}
else
{
lengthDeletions2 += diffs[pointer].Text.Length;
}
// Eliminate an equality that is smaller or equal to the edits on both
// sides of it.
if (lastEquality != null
&& (lastEquality.Length <= Math.Max(lengthInsertions1, lengthDeletions1))
&& (lastEquality.Length <= Math.Max(lengthInsertions2, lengthDeletions2)))
{
// Duplicate record.
diffs.Splice(equalities.Peek(), 1, Diff.Delete(lastEquality), Diff.Insert(lastEquality));
// Throw away the equality we just deleted.
equalities.Pop();
if (equalities.Count > 0)
{
equalities.Pop();
}
pointer = equalities.Count > 0 ? equalities.Peek() : -1;
lengthInsertions1 = 0; // Reset the counters.
lengthDeletions1 = 0;
lengthInsertions2 = 0;
lengthDeletions2 = 0;
lastEquality = null;
}
}
pointer++;
}
diffs = diffs.CleanupMerge().CleanupSemanticLossless().ToList();
// Find any overlaps between deletions and insertions.
// e.g: <del>abcxxx</del><ins>xxxdef</ins>
// -> <del>abc</del>xxx<ins>def</ins>
// e.g: <del>xxxabc</del><ins>defxxx</ins>
// -> <ins>def</ins>xxx<del>abc</del>
// Only extract an overlap if it is as big as the edit ahead or behind it.
pointer = 1;
while (pointer < diffs.Count)
{
if (diffs[pointer - 1].Operation == Delete &&
diffs[pointer].Operation == Insert)
{
var deletion = diffs[pointer - 1].Text.AsSpan();
var insertion = diffs[pointer].Text.AsSpan();
var overlapLength1 = TextUtil.CommonOverlap(deletion, insertion);
var overlapLength2 = TextUtil.CommonOverlap(insertion, deletion);
var minLength = Math.Min(deletion.Length, insertion.Length);
Diff[]? newdiffs = null;
if ((overlapLength1 >= overlapLength2) && (overlapLength1 >= minLength / 2.0))
{
// Overlap found.
// Insert an equality and trim the surrounding edits.
newdiffs = new[]
{
Diff.Delete(deletion.Slice(0, deletion.Length - overlapLength1).ToArray()),
Diff.Equal(insertion.Slice(0, overlapLength1).ToArray()),
Diff.Insert(insertion[overlapLength1..].ToArray())
};
}
else if ((overlapLength2 >= overlapLength1) && overlapLength2 >= minLength / 2.0)
{
// Reverse overlap found.
// Insert an equality and swap and trim the surrounding edits.
newdiffs = new[]
{
Diff.Insert(insertion.Slice(0, insertion.Length - overlapLength2)),
Diff.Equal(deletion.Slice(0, overlapLength2)),
Diff.Delete(deletion[overlapLength2..])
};
}
if (newdiffs != null)
{
diffs.Splice(pointer - 1, 2, newdiffs);
pointer++;
}
pointer++;
}
pointer++;
}
return diffs;
}
/// <summary>
/// Rehydrate the text in a diff from a string of line hashes to real lines of text.
/// </summary>
/// <param name="diffs"></param>
/// <param name="lineArray">list of unique strings</param>
/// <returns></returns>
internal static IEnumerable<Diff> CharsToLines(this ICollection<Diff> diffs, IList<string> lineArray)
{
foreach (var diff in diffs)
{
var text = new StringBuilder();
foreach (var c in diff.Text)
{
text.Append(lineArray[c]);
}
yield return diff.Replace(text.ToString());
}
}
/// <summary>
/// Compute and return equivalent location in target text.
/// </summary>
/// <param name="diffs">list of diffs</param>
/// <param name="location1">location in source</param>
/// <returns>location in target</returns>
internal static int FindEquivalentLocation2(this IEnumerable<Diff> diffs, int location1)
{
var chars1 = 0;
var chars2 = 0;
var lastChars1 = 0;
var lastChars2 = 0;
Diff lastDiff = Diff.Empty;
foreach (var aDiff in diffs)
{
if (aDiff.Operation != Insert)
{
// Equality or deletion.
chars1 += aDiff.Text.Length;
}
if (aDiff.Operation != Delete)
{
// Equality or insertion.
chars2 += aDiff.Text.Length;
}
if (chars1 > location1)
{
// Overshot the location.
lastDiff = aDiff;
break;
}
lastChars1 = chars1;
lastChars2 = chars2;
}
if (lastDiff.Operation == Delete)
{
// The location was deleted.
return lastChars2;
}
// Add the remaining character length.
return lastChars2 + (location1 - lastChars1);
}
}
| |
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// -----------------------------------------------------------------------------
// Helper methods to extract method inheritance.
// Original code from https://github.com/mono/mono/blob/master/mcs/tools/linker/Mono.Linker.Steps/TypeMapStep.cs
// -----------------------------------------------------------------------------
//
// TypeMapStep.cs
//
// Author:
// Jb Evain (jbevain@novell.com)
//
// (C) 2009 Novell, Inc.
//
// 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.
//
// ----------------------------------------------------------------------
// Reuse of some methods to navigate Mono.Cecil type definitions.
// https://github.com/mono/mono/blob/master/mcs/tools/linker/Mono.Linker.Steps/TypeMapStep.cs
// ----------------------------------------------------------------------
//
// TypeMapStep.cs
//
// Author:
// Jb Evain (jbevain@novell.com)
//
// (C) 2009 Novell, Inc.
//
// 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 Mono.Cecil;
namespace SharpDoc
{
/// <summary>
/// Helper methods for Mono.Cecil.
/// </summary>
public class MonoCecilHelper
{
void MapType(TypeDefinition type)
{
MapVirtualMethods(type);
MapInterfaceMethodsInTypeHierarchy(type);
}
void MapInterfaceMethodsInTypeHierarchy(TypeDefinition type)
{
if (!type.HasInterfaces)
return;
foreach (TypeReference @interface in type.Interfaces)
{
var iface = @interface.Resolve();
if (iface == null || !iface.HasMethods)
continue;
foreach (MethodDefinition method in iface.Methods)
{
if (TryMatchMethod(type, method) != null)
continue;
var @base = GetBaseMethodInTypeHierarchy(type, method);
if (@base == null)
continue;
//Annotations.AddPreservedMethod(type, @base);
}
}
}
void MapVirtualMethods(TypeDefinition type)
{
if (!type.HasMethods)
return;
foreach (MethodDefinition method in type.Methods)
{
if (!method.IsVirtual)
continue;
MapVirtualMethod(method);
if (method.HasOverrides)
MapOverrides(method);
}
}
void MapVirtualMethod(MethodDefinition method)
{
MapVirtualBaseMethod(method);
MapVirtualInterfaceMethod(method);
}
void MapVirtualBaseMethod(MethodDefinition method)
{
MethodDefinition @base = GetBaseMethodInTypeHierarchy(method);
if (@base == null)
return;
//AnnotateMethods(@base, method);
}
void MapVirtualInterfaceMethod(MethodDefinition method)
{
MethodDefinition @base = GetBaseMethodInInterfaceHierarchy(method);
if (@base == null)
return;
//AnnotateMethods(@base, method);
}
void MapOverrides(MethodDefinition method)
{
foreach (MethodReference override_ref in method.Overrides)
{
MethodDefinition @override = override_ref.Resolve();
if (@override == null)
continue;
//AnnotateMethods(@override, method);
}
}
public static MethodDefinition GetBaseMethodInTypeHierarchy(MethodDefinition method)
{
return GetBaseMethodInTypeHierarchy(method.DeclaringType, method);
}
public static MethodDefinition GetBaseMethodInTypeHierarchy(TypeDefinition type, MethodDefinition method)
{
TypeDefinition @base = GetBaseType(type);
while (@base != null)
{
MethodDefinition base_method = TryMatchMethod(@base, method);
if (base_method != null)
return base_method;
@base = GetBaseType(@base);
}
return null;
}
public static MethodDefinition GetBaseMethodInInterfaceHierarchy(MethodDefinition method)
{
return GetBaseMethodInInterfaceHierarchy(method.DeclaringType, method);
}
public static MethodDefinition GetBaseMethodInInterfaceHierarchy(TypeDefinition type, MethodDefinition method)
{
if (!type.HasInterfaces)
return null;
foreach (TypeReference interface_ref in type.Interfaces)
{
TypeDefinition @interface = interface_ref.Resolve();
if (@interface == null)
continue;
MethodDefinition base_method = TryMatchMethod(@interface, method);
if (base_method != null)
return base_method;
base_method = GetBaseMethodInInterfaceHierarchy(@interface, method);
if (base_method != null)
return base_method;
}
return null;
}
static MethodDefinition TryMatchMethod(TypeDefinition type, MethodDefinition method)
{
if (!type.HasMethods)
return null;
foreach (MethodDefinition candidate in type.Methods)
if (MethodMatch(candidate, method))
return candidate;
return null;
}
static bool MethodMatch(MethodDefinition candidate, MethodDefinition method)
{
if (!candidate.IsVirtual)
return false;
if (candidate.Name != method.Name)
return false;
if (!TypeMatch(candidate.ReturnType, method.ReturnType))
return false;
if (candidate.Parameters.Count != method.Parameters.Count)
return false;
for (int i = 0; i < candidate.Parameters.Count; i++)
if (!TypeMatch(candidate.Parameters[i].ParameterType, method.Parameters[i].ParameterType))
return false;
return true;
}
static bool TypeMatch(IModifierType a, IModifierType b)
{
if (!TypeMatch(a.ModifierType, b.ModifierType))
return false;
return TypeMatch(a.ElementType, b.ElementType);
}
static bool TypeMatch(TypeSpecification a, TypeSpecification b)
{
if (a is GenericInstanceType)
return TypeMatch((GenericInstanceType)a, (GenericInstanceType)b);
if (a is IModifierType)
return TypeMatch((IModifierType)a, (IModifierType)b);
return TypeMatch(a.ElementType, b.ElementType);
}
static bool TypeMatch(GenericInstanceType a, GenericInstanceType b)
{
if (!TypeMatch(a.ElementType, b.ElementType))
return false;
if (a.GenericArguments.Count != b.GenericArguments.Count)
return false;
if (a.GenericArguments.Count == 0)
return true;
for (int i = 0; i < a.GenericArguments.Count; i++)
if (!TypeMatch(a.GenericArguments[i], b.GenericArguments[i]))
return false;
return true;
}
static bool TypeMatch(TypeReference a, TypeReference b)
{
if (a is GenericParameter)
return true;
if (a is TypeSpecification || b is TypeSpecification)
{
if (a.GetType() != b.GetType())
return false;
return TypeMatch((TypeSpecification)a, (TypeSpecification)b);
}
return a.FullName == b.FullName;
}
public static TypeDefinition GetBaseType(TypeDefinition type)
{
if (type == null || type.BaseType == null)
return null;
return type.BaseType.Resolve();
}
public static TypeDefinition GetBaseTypeAfterSystemObject(TypeDefinition type)
{
var baseType = GetBaseType(type);
if (baseType == null)
return type;
if (baseType.FullName == "System.Object")
return type;
return GetBaseTypeAfterSystemObject(baseType);
}
public static bool IsDelegate(TypeDefinition type)
{
var baseType = GetBaseTypeAfterSystemObject(type);
if (baseType == null)
return false;
return (baseType.FullName == "System.Delegate");
}
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Glacier.Model
{
/// <summary>
/// Container for the parameters to the UploadMultipartPart operation.
/// <para>This operation uploads a part of an archive. You can upload archive parts in any order. You can also upload them in parallel. You can
/// upload up to 10,000 parts for a multipart upload.</para> <para>Amazon Glacier rejects your upload part request if any of the following
/// conditions is true:</para>
/// <ul>
/// <li> <para> <b>SHA256 tree hash does not match</b> To ensure that part data is not corrupted in transmission, you compute a SHA256 tree
/// hash of the part and include it in your request. Upon receiving the part data, Amazon Glacier also computes a SHA256 tree hash. If these
/// hash values don't match, the operation fails. For information about computing a SHA256 tree hash, see Computing Checksums.</para> </li>
/// <li> <para> <b>Part size does not match</b> The size of each part except the last must match the size specified in the corresponding
/// InitiateMultipartUpload request. The size of the last part must be the same size as, or smaller than, the specified size.</para>
/// <para><b>NOTE:</b> If you upload a part whose size is smaller than the part size you specified in your initiate multipart upload request and
/// that part is not the last part, then the upload part request will succeed. However, the subsequent Complete Multipart Upload request will
/// fail. </para> </li>
/// <li> <b>Range does not align</b> The byte range value in the request does not align with the part size specified in the corresponding
/// initiate request. For example, if you specify a part size of 4194304 bytes (4 MB), then 0 to 4194303 bytes (4 MB - 1) and 4194304 (4 MB) to
/// 8388607 (8 MB - 1) are valid part ranges. However, if you set a range value of 2 MB to 6 MB, the range does not align with the part size and
/// the upload will fail. </li>
///
/// </ul>
/// <para>This operation is idempotent. If you upload the same part multiple times, the data included in the most recent request overwrites the
/// previously uploaded data.</para> <para>An AWS account has full permission to perform all operations (actions). However, AWS Identity and
/// Access Management (IAM) users don't have any permissions by default. You must grant them explicit permission to perform specific actions.
/// For more information, see Access Control Using AWS Identity and Access Management (IAM).</para> <para> For conceptual information and
/// underlying REST API, go to Uploading Large Archives in Parts (Multipart Upload) and Upload Part in the <i>Amazon Glacier Developer
/// Guide</i> .</para>
/// </summary>
/// <seealso cref="Amazon.Glacier.AmazonGlacier.UploadMultipartPart"/>
public class UploadMultipartPartRequest : AmazonWebServiceRequest
{
private string accountId;
private string vaultName;
private string uploadId;
private string checksum;
private string range;
private Stream body;
/// <summary>
/// The <c>AccountId</c> is the AWS Account ID. You can specify either the AWS Account ID or optionally a '-', in which case Amazon Glacier uses
/// the AWS Account ID associated with the credentials used to sign the request. If you specify your Account ID, do not include hyphens in it.
///
/// </summary>
public string AccountId
{
get { return this.accountId; }
set { this.accountId = value; }
}
/// <summary>
/// Sets the AccountId property
/// </summary>
/// <param name="accountId">The value to set for the AccountId property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public UploadMultipartPartRequest WithAccountId(string accountId)
{
this.accountId = accountId;
return this;
}
// Check to see if AccountId property is set
internal bool IsSetAccountId()
{
return this.accountId != null;
}
/// <summary>
/// The name of the vault.
///
/// </summary>
public string VaultName
{
get { return this.vaultName; }
set { this.vaultName = value; }
}
/// <summary>
/// Sets the VaultName property
/// </summary>
/// <param name="vaultName">The value to set for the VaultName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public UploadMultipartPartRequest WithVaultName(string vaultName)
{
this.vaultName = vaultName;
return this;
}
// Check to see if VaultName property is set
internal bool IsSetVaultName()
{
return this.vaultName != null;
}
/// <summary>
/// The upload ID of the multipart upload.
///
/// </summary>
public string UploadId
{
get { return this.uploadId; }
set { this.uploadId = value; }
}
/// <summary>
/// Sets the UploadId property
/// </summary>
/// <param name="uploadId">The value to set for the UploadId property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public UploadMultipartPartRequest WithUploadId(string uploadId)
{
this.uploadId = uploadId;
return this;
}
// Check to see if UploadId property is set
internal bool IsSetUploadId()
{
return this.uploadId != null;
}
/// <summary>
/// The SHA256 tree hash of the data being uploaded.
///
/// </summary>
public string Checksum
{
get { return this.checksum; }
set { this.checksum = value; }
}
/// <summary>
/// Sets the Checksum property
/// </summary>
/// <param name="checksum">The value to set for the Checksum property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public UploadMultipartPartRequest WithChecksum(string checksum)
{
this.checksum = checksum;
return this;
}
// Check to see if Checksum property is set
internal bool IsSetChecksum()
{
return this.checksum != null;
}
/// <summary>
/// Identifies the range of bytes in the assembled archive that will be uploaded in this part. Amazon Glacier uses this information to assemble
/// the archive in the proper sequence. The format of this header follows RFC 2616. An example header is Content-Range:bytes 0-4194303/*.
///
/// </summary>
public string Range
{
get { return this.range; }
set { this.range = value; }
}
/// <summary>
/// Sets the Range property
/// </summary>
/// <param name="range">The value to set for the Range property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public UploadMultipartPartRequest WithRange(string range)
{
this.range = range;
return this;
}
// Check to see if Range property is set
internal bool IsSetRange()
{
return this.range != null;
}
/// <summary>
/// The data to upload.
///
/// </summary>
public Stream Body
{
get { return this.body; }
set { this.body = value; }
}
/// <summary>
/// Sets the Body property
/// </summary>
/// <param name="body">The value to set for the Body property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public UploadMultipartPartRequest WithBody(Stream body)
{
this.body = body;
return this;
}
// Check to see if Body property is set
internal bool IsSetBody()
{
return this.body != null;
}
/// <summary>
/// Attach a callback that will be called as data is being sent to the AWS Service.
/// </summary>
public EventHandler<Amazon.Runtime.StreamTransferProgressArgs> StreamTransferProgress
{
get
{
return this.StreamUploadProgressCallback;
}
set
{
this.StreamUploadProgressCallback = value;
}
}
}
}
| |
using System;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using HttpServer.Exceptions;
using HttpServer.FormDecoders;
namespace HttpServer
{
/// <summary>
/// Contains server side HTTP request information.
/// </summary>
public class HttpRequest : IHttpRequest
{
/// <summary>
/// Chars used to split an URL path into multiple parts.
/// </summary>
public static readonly char[] UriSplitters = new[] {'/'};
private readonly NameValueCollection _headers = new NameValueCollection();
private readonly HttpParam _param = new HttpParam(HttpInput.Empty, HttpInput.Empty);
private Stream _body = new MemoryStream();
private int _bodyBytesLeft;
private ConnectionType _connection = ConnectionType.Close;
private int _contentLength;
private HttpForm _form = HttpForm.EmptyForm;
private string _httpVersion = string.Empty;
private string _method = string.Empty;
private HttpInput _queryString = HttpInput.Empty;
private Uri _uri = HttpHelper.EmptyUri;
private string _uriPath;
/// <summary>
/// Gets or sets a value indicating whether this <see cref="HttpRequest"/> is secure.
/// </summary>
public bool Secure { get; internal set; }
/// <summary>
/// Path and query (will be merged with the host header) and put in Uri
/// </summary>
/// <see cref="Uri"/>
public string UriPath
{
get { return _uriPath; }
set
{
_uriPath = value;
int pos = _uriPath.IndexOf('?');
if (pos != -1)
{
_queryString = HttpHelper.ParseQueryString(_uriPath.Substring(pos + 1));
_param.SetQueryString(_queryString);
string path = _uriPath.Substring(0, pos);
_uriPath = System.Web.HttpUtility.UrlDecode(path) + "?" + _uriPath.Substring(pos + 1);
UriParts = value.Substring(0, pos).Split(UriSplitters, StringSplitOptions.RemoveEmptyEntries);
}
else
{
_uriPath = System.Web.HttpUtility.UrlDecode(_uriPath);
UriParts = value.Split(UriSplitters, StringSplitOptions.RemoveEmptyEntries);
}
}
}
/// <summary>
/// Assign a form.
/// </summary>
/// <param name="form"></param>
internal void AssignForm(HttpForm form)
{
_form = form;
}
internal static bool ShouldReplyTo100Continue(IHttpRequest request)
{
string expectHeader = request.Headers["expect"];
return expectHeader != null && expectHeader.Contains("100-continue");
}
#region IHttpRequest Members
/// <summary>
/// Gets whether the body is complete.
/// </summary>
public bool BodyIsComplete
{
get { return _bodyBytesLeft == 0; }
}
/// <summary>
/// Gets kind of types accepted by the client.
/// </summary>
public string[] AcceptTypes { get; private set; }
/// <summary>
/// Gets or sets body stream.
/// </summary>
public Stream Body
{
get { return _body; }
set { _body = value; }
}
/// <summary>
/// Gets or sets kind of connection used for the session.
/// </summary>
public ConnectionType Connection
{
get { return _connection; }
set { _connection = value; }
}
/// <summary>
/// Gets or sets number of bytes in the body.
/// </summary>
public int ContentLength
{
get { return _contentLength; }
set
{
_contentLength = value;
_bodyBytesLeft = value;
}
}
/// <summary>
/// Gets headers sent by the client.
/// </summary>
public NameValueCollection Headers
{
get { return _headers; }
}
/// <summary>
/// Gets or sets version of HTTP protocol that's used.
/// </summary>
/// <remarks>
/// Probably <see cref="HttpHelper.HTTP10"/> or <see cref="HttpHelper.HTTP11"/>.
/// </remarks>
/// <seealso cref="HttpHelper"/>
public string HttpVersion
{
get { return _httpVersion; }
set { _httpVersion = value; }
}
/// <summary>
/// Gets or sets requested method.
/// </summary>
/// <value></value>
/// <remarks>
/// Will always be in upper case.
/// </remarks>
/// <see cref="HttpServer.Method"/>
public string Method
{
get { return _method; }
set { _method = value; }
}
/// <summary>
/// Gets variables sent in the query string
/// </summary>
public HttpInput QueryString
{
get { return _queryString; }
}
/// <summary>
/// Gets or sets requested URI.
/// </summary>
public Uri Uri
{
get { return _uri; }
set
{
_uri = value ?? HttpHelper.EmptyUri;
UriParts = _uri.AbsolutePath.Split(UriSplitters, StringSplitOptions.RemoveEmptyEntries);
}
}
/// <summary>
/// Uri absolute path splitted into parts.
/// </summary>
/// <example>
/// // uri is: http://gauffin.com/code/tiny/
/// Console.WriteLine(request.UriParts[0]); // result: code
/// Console.WriteLine(request.UriParts[1]); // result: tiny
/// </example>
/// <remarks>
/// If you're using controllers than the first part is controller name,
/// the second part is method name and the third part is Id property.
/// </remarks>
/// <seealso cref="Uri"/>
public string[] UriParts { get; private set; }
/// <summary>
/// Gets parameter from <see cref="QueryString"/> or <see cref="Form"/>.
/// </summary>
public HttpParam Param
{
get { return _param; }
}
/// <summary>
/// Gets form parameters.
/// </summary>
public HttpForm Form
{
get { return _form; }
}
/// <summary>
/// Gets whether the request was made by Ajax (Asynchronous JavaScript)
/// </summary>
public bool IsAjax { get; private set; }
/// <summary>
/// Gets cookies that was sent with the request.
/// </summary>
public RequestCookies Cookies { get; private set; }
///<summary>
///Creates a new object that is a copy of the current instance.
///</summary>
///
///<returns>
///A new object that is a copy of this instance.
///</returns>
///<filterpriority>2</filterpriority>
public object Clone()
{
// this method was mainly created for testing.
// dont use it that much...
var request = new HttpRequest();
request.Method = _method;
if (AcceptTypes != null)
{
request.AcceptTypes = new string[AcceptTypes.Length];
AcceptTypes.CopyTo(request.AcceptTypes, 0);
}
request._httpVersion = _httpVersion;
request._queryString = _queryString;
request.Uri = _uri;
var buffer = new byte[_body.Length];
_body.Read(buffer, 0, (int) _body.Length);
request.Body = new MemoryStream();
request.Body.Write(buffer, 0, buffer.Length);
request.Body.Seek(0, SeekOrigin.Begin);
request.Body.Flush();
request._headers.Clear();
foreach (string key in _headers)
{
string[] values = _headers.GetValues(key);
if (values != null)
foreach (string value in values)
request.AddHeader(key, value);
}
Clear();
return request;
}
/// <summary>
/// Decode body into a form.
/// </summary>
/// <param name="providers">A list with form decoders.</param>
/// <exception cref="InvalidDataException">If body contents is not valid for the chosen decoder.</exception>
/// <exception cref="InvalidOperationException">If body is still being transferred.</exception>
public void DecodeBody(FormDecoderProvider providers)
{
if (_bodyBytesLeft > 0)
throw new InvalidOperationException("Body have not yet been completed.");
_form = providers.Decode(_headers["content-type"], _body, Encoding.UTF8);
if (_form != HttpInput.Empty)
_param.SetForm(_form);
}
///<summary>
/// Cookies
///</summary>
///<param name="cookies">the cookies</param>
public void SetCookies(RequestCookies cookies)
{
Cookies = cookies;
}
/// <summary>
/// Create a response object.
/// </summary>
/// <returns>A new <see cref="IHttpResponse"/>.</returns>
public IHttpResponse CreateResponse(IHttpClientContext context)
{
return new HttpResponse(context, this);
}
/// <summary>
/// Called during parsing of a <see cref="IHttpRequest"/>.
/// </summary>
/// <param name="name">Name of the header, should not be URL encoded</param>
/// <param name="value">Value of the header, should not be URL encoded</param>
/// <exception cref="BadRequestException">If a header is incorrect.</exception>
public void AddHeader(string name, string value)
{
if (string.IsNullOrEmpty(name))
throw new BadRequestException("Invalid header name: " + name ?? "<null>");
if (string.IsNullOrEmpty(value))
throw new BadRequestException("Header '" + name + "' do not contain a value.");
name = name.ToLowerInvariant();
switch (name)
{
case "http_x_requested_with":
case "x-requested-with":
if (string.Compare(value, "XMLHttpRequest", true) == 0)
IsAjax = true;
break;
case "accept":
AcceptTypes = value.Split(',');
for (int i = 0; i < AcceptTypes.Length; ++i)
AcceptTypes[i] = AcceptTypes[i].Trim();
break;
case "content-length":
int t;
if (!int.TryParse(value, out t))
throw new BadRequestException("Invalid content length.");
ContentLength = t;
break; //todo: maybe throw an exception
case "host":
try
{
_uri = new Uri(Secure ? "https://" : "http://" + value + _uriPath);
UriParts = _uri.AbsolutePath.Split(UriSplitters, StringSplitOptions.RemoveEmptyEntries);
}
catch (UriFormatException err)
{
throw new BadRequestException("Failed to parse uri: " + value + _uriPath, err);
}
break;
case "remote_addr":
// to prevent hacking (since it's added by IHttpClientContext before parsing).
if (_headers[name] == null)
_headers.Add(name, value);
break;
case "connection":
if (string.Compare(value, "close", true) == 0)
Connection = ConnectionType.Close;
else if (value.StartsWith("keep-alive", StringComparison.CurrentCultureIgnoreCase))
Connection = ConnectionType.KeepAlive;
else
throw new BadRequestException("Unknown 'Connection' header type.");
break;
case "expect":
if (value.Contains("100-continue"))
{
}
_headers.Add(name, value);
break;
default:
_headers.Add(name, value);
break;
}
}
/// <summary>
/// Add bytes to the body
/// </summary>
/// <param name="bytes">buffer to read bytes from</param>
/// <param name="offset">where to start read</param>
/// <param name="length">number of bytes to read</param>
/// <returns>Number of bytes actually read (same as length unless we got all body bytes).</returns>
/// <exception cref="InvalidOperationException">If body is not writable</exception>
/// <exception cref="ArgumentNullException"><c>bytes</c> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException"><c>offset</c> is out of range.</exception>
public int AddToBody(byte[] bytes, int offset, int length)
{
if (bytes == null)
throw new ArgumentNullException("bytes");
if (offset + length > bytes.Length)
throw new ArgumentOutOfRangeException("offset");
if (length == 0)
return 0;
if (!_body.CanWrite)
throw new InvalidOperationException("Body is not writable.");
if (length > _bodyBytesLeft)
{
length = _bodyBytesLeft;
}
_body.Write(bytes, offset, length);
_bodyBytesLeft -= length;
return length;
}
/// <summary>
/// Clear everything in the request
/// </summary>
public void Clear()
{
//return;
_body.Dispose();
_body = new MemoryStream();
_contentLength = 0;
_method = string.Empty;
_uri = HttpHelper.EmptyUri;
_queryString = HttpInput.Empty;
_bodyBytesLeft = 0;
_headers.Clear();
_connection = ConnectionType.Close;
IsAjax = false;
_form.Clear();
}
#endregion
}
}
| |
// 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.AcceptanceTestsHead
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
/// <summary>
/// HttpSuccessOperations operations.
/// </summary>
internal partial class HttpSuccessOperations : Microsoft.Rest.IServiceOperations<AutoRestHeadTestService>, IHttpSuccessOperations
{
/// <summary>
/// Initializes a new instance of the HttpSuccessOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal HttpSuccessOperations(AutoRestHeadTestService client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestHeadTestService
/// </summary>
public AutoRestHeadTestService Client { get; private set; }
/// <summary>
/// Return 200 status code if successful
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<bool>> Head200WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Head200", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/success/200").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("HEAD");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.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)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 404)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<bool>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
_result.Body = (_statusCode == System.Net.HttpStatusCode.OK);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 204 status code if successful
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<bool>> Head204WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Head204", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/success/204").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("HEAD");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.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)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204 && (int)_statusCode != 404)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<bool>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
_result.Body = (_statusCode == System.Net.HttpStatusCode.NoContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Return 404 status code if successful
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<bool>> Head404WithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Head404", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/success/404").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("HEAD");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.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)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204 && (int)_statusCode != 404)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<bool>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
_result.Body = (_statusCode == System.Net.HttpStatusCode.NoContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
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;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal sealed class TypeManager
{
private BSYMMGR _BSymmgr;
private PredefinedTypes _predefTypes;
private readonly TypeFactory _typeFactory;
private readonly TypeTable _typeTable;
private SymbolTable _symbolTable;
// Special types
private readonly VoidType _voidType;
private readonly NullType _nullType;
private readonly MethodGroupType _typeMethGrp;
private readonly ArgumentListType _argListType;
private readonly ErrorType _errorType;
private readonly StdTypeVarColl _stvcMethod;
private readonly StdTypeVarColl _stvcClass;
public TypeManager(BSYMMGR bsymmgr, PredefinedTypes predefTypes)
{
_typeFactory = new TypeFactory();
_typeTable = new TypeTable();
// special types with their own symbol kind.
_errorType = _typeFactory.CreateError(null, null, null, null, null);
_voidType = _typeFactory.CreateVoid();
_nullType = _typeFactory.CreateNull();
_typeMethGrp = _typeFactory.CreateMethodGroup();
_argListType = _typeFactory.CreateArgList();
_errorType.SetErrors(true);
_stvcMethod = new StdTypeVarColl();
_stvcClass = new StdTypeVarColl();
_BSymmgr = bsymmgr;
_predefTypes = predefTypes;
}
public void InitTypeFactory(SymbolTable table)
{
_symbolTable = table;
}
private sealed class StdTypeVarColl
{
private readonly List<TypeParameterType> prgptvs;
public StdTypeVarColl()
{
prgptvs = new List<TypeParameterType>();
}
////////////////////////////////////////////////////////////////////////////////
// Get the standard type variable (eg, !0, !1, or !!0, !!1).
//
// iv is the index.
// pbsm is the containing symbol manager
// fMeth designates whether this is a method type var or class type var
//
// The standard class type variables are useful during emit, but not for type
// comparison when binding. The standard method type variables are useful during
// binding for signature comparison.
public TypeParameterType GetTypeVarSym(int iv, TypeManager pTypeManager, bool fMeth)
{
Debug.Assert(iv >= 0);
TypeParameterType tpt = null;
if (iv >= this.prgptvs.Count)
{
TypeParameterSymbol pTypeParameter = new TypeParameterSymbol();
pTypeParameter.SetIsMethodTypeParameter(fMeth);
pTypeParameter.SetIndexInOwnParameters(iv);
pTypeParameter.SetIndexInTotalParameters(iv);
pTypeParameter.SetAccess(ACCESS.ACC_PRIVATE);
tpt = pTypeManager.GetTypeParameter(pTypeParameter);
this.prgptvs.Add(tpt);
}
else
{
tpt = this.prgptvs[iv];
}
Debug.Assert(tpt != null);
return tpt;
}
}
public ArrayType GetArray(CType elementType, int args, bool isSZArray)
{
Name name;
Debug.Assert(args > 0 && args < 32767);
Debug.Assert(args == 1 || !isSZArray);
switch (args)
{
case 1:
if (isSZArray)
{
goto case 2;
}
else
{
goto default;
}
case 2:
name = NameManager.GetPredefinedName(PredefinedName.PN_ARRAY0 + args);
break;
default:
name = _BSymmgr.GetNameManager().Add("[X" + args + 1);
break;
}
// See if we already have an array type of this element type and rank.
ArrayType pArray = _typeTable.LookupArray(name, elementType);
if (pArray == null)
{
// No existing array symbol. Create a new one.
pArray = _typeFactory.CreateArray(name, elementType, args, isSZArray);
pArray.InitFromParent();
_typeTable.InsertArray(name, elementType, pArray);
}
else
{
Debug.Assert(pArray.HasErrors() == elementType.HasErrors());
}
Debug.Assert(pArray.rank == args);
Debug.Assert(pArray.GetElementType() == elementType);
return pArray;
}
public AggregateType GetAggregate(AggregateSymbol agg, AggregateType atsOuter, TypeArray typeArgs)
{
Debug.Assert(agg.GetTypeManager() == this);
Debug.Assert(atsOuter == null || atsOuter.getAggregate() == agg.Parent, "");
if (typeArgs == null)
{
typeArgs = BSYMMGR.EmptyTypeArray();
}
Debug.Assert(agg.GetTypeVars().Count == typeArgs.Count);
Name name = _BSymmgr.GetNameFromPtrs(typeArgs, atsOuter);
Debug.Assert(name != null);
AggregateType pAggregate = _typeTable.LookupAggregate(name, agg);
if (pAggregate == null)
{
pAggregate = _typeFactory.CreateAggregateType(
name,
agg,
typeArgs,
atsOuter
);
Debug.Assert(!pAggregate.fConstraintsChecked && !pAggregate.fConstraintError);
pAggregate.SetErrors(false);
_typeTable.InsertAggregate(name, agg, pAggregate);
// If we have a generic type definition, then we need to set the
// base class to be our current base type, and use that to calculate
// our agg type and its base, then set it to be the generic version of the
// base type. This is because:
//
// Suppose we have Foo<T> : IFoo<T>
//
// Initially, the BaseType will be IFoo<Foo.T>, which gives us the substitution
// that we want to use for our agg type's base type. However, in the Symbol chain,
// we want the base type to be IFoo<IFoo.T>. Thats why we need to do this little trick.
//
// If we don't have a generic type definition, then we just need to set our base
// class. This is so that if we have a base type that's generic, we'll be
// getting the correctly instantiated base type.
var baseType = pAggregate.AssociatedSystemType?.BaseType;
if (baseType != null)
{
// Store the old base class.
AggregateType oldBaseType = agg.GetBaseClass();
agg.SetBaseClass(_symbolTable.GetCTypeFromType(baseType) as AggregateType);
pAggregate.GetBaseClass(); // Get the base type for the new agg type we're making.
agg.SetBaseClass(oldBaseType);
}
}
else
{
Debug.Assert(!pAggregate.HasErrors());
}
Debug.Assert(pAggregate.getAggregate() == agg);
Debug.Assert(pAggregate.GetTypeArgsThis() != null && pAggregate.GetTypeArgsAll() != null);
Debug.Assert(pAggregate.GetTypeArgsThis() == typeArgs);
return pAggregate;
}
public AggregateType GetAggregate(AggregateSymbol agg, TypeArray typeArgsAll)
{
Debug.Assert(typeArgsAll != null && typeArgsAll.Count == agg.GetTypeVarsAll().Count);
if (typeArgsAll.Count == 0)
return agg.getThisType();
AggregateSymbol aggOuter = agg.GetOuterAgg();
if (aggOuter == null)
return GetAggregate(agg, null, typeArgsAll);
int cvarOuter = aggOuter.GetTypeVarsAll().Count;
Debug.Assert(cvarOuter <= typeArgsAll.Count);
TypeArray typeArgsOuter = _BSymmgr.AllocParams(cvarOuter, typeArgsAll, 0);
TypeArray typeArgsInner = _BSymmgr.AllocParams(agg.GetTypeVars().Count, typeArgsAll, cvarOuter);
AggregateType atsOuter = GetAggregate(aggOuter, typeArgsOuter);
return GetAggregate(agg, atsOuter, typeArgsInner);
}
public PointerType GetPointer(CType baseType)
{
PointerType pPointer = _typeTable.LookupPointer(baseType);
if (pPointer == null)
{
// No existing type. Create a new one.
Name namePtr = NameManager.GetPredefinedName(PredefinedName.PN_PTR);
pPointer = _typeFactory.CreatePointer(namePtr, baseType);
pPointer.InitFromParent();
_typeTable.InsertPointer(baseType, pPointer);
}
else
{
Debug.Assert(pPointer.HasErrors() == baseType.HasErrors());
}
Debug.Assert(pPointer.GetReferentType() == baseType);
return pPointer;
}
public NullableType GetNullable(CType pUnderlyingType)
{
if (pUnderlyingType is NullableType nt)
{
Debug.Fail("Attempt to make nullable of nullable");
return nt;
}
NullableType pNullableType = _typeTable.LookupNullable(pUnderlyingType);
if (pNullableType == null)
{
Name pName = NameManager.GetPredefinedName(PredefinedName.PN_NUB);
pNullableType = _typeFactory.CreateNullable(pName, pUnderlyingType, _BSymmgr, this);
pNullableType.InitFromParent();
_typeTable.InsertNullable(pUnderlyingType, pNullableType);
}
return pNullableType;
}
public NullableType GetNubFromNullable(AggregateType ats)
{
Debug.Assert(ats.isPredefType(PredefinedType.PT_G_OPTIONAL));
return GetNullable(ats.GetTypeArgsAll()[0]);
}
public ParameterModifierType GetParameterModifier(CType paramType, bool isOut)
{
Name name = NameManager.GetPredefinedName(isOut ? PredefinedName.PN_OUTPARAM : PredefinedName.PN_REFPARAM);
ParameterModifierType pParamModifier = _typeTable.LookupParameterModifier(name, paramType);
if (pParamModifier == null)
{
// No existing parammod symbol. Create a new one.
pParamModifier = _typeFactory.CreateParameterModifier(name, paramType);
pParamModifier.isOut = isOut;
pParamModifier.InitFromParent();
_typeTable.InsertParameterModifier(name, paramType, pParamModifier);
}
else
{
Debug.Assert(pParamModifier.HasErrors() == paramType.HasErrors());
}
Debug.Assert(pParamModifier.GetParameterType() == paramType);
return pParamModifier;
}
public ErrorType GetErrorType(
CType pParentType,
AssemblyQualifiedNamespaceSymbol pParentNS,
Name nameText,
TypeArray typeArgs)
{
Debug.Assert(nameText != null);
Debug.Assert(pParentType == null || pParentNS == null);
if (pParentType == null && pParentNS == null)
{
// Use the root namespace as the parent.
pParentNS = _BSymmgr.GetRootNsAid();
}
if (typeArgs == null)
{
typeArgs = BSYMMGR.EmptyTypeArray();
}
Name name = _BSymmgr.GetNameFromPtrs(nameText, typeArgs);
Debug.Assert(name != null);
ErrorType pError = null;
if (pParentType != null)
{
pError = _typeTable.LookupError(name, pParentType);
}
else
{
Debug.Assert(pParentNS != null);
pError = _typeTable.LookupError(name, pParentNS);
}
if (pError == null)
{
// No existing error symbol. Create a new one.
pError = _typeFactory.CreateError(name, pParentType, pParentNS, nameText, typeArgs);
pError.SetErrors(true);
if (pParentType != null)
{
_typeTable.InsertError(name, pParentType, pError);
}
else
{
_typeTable.InsertError(name, pParentNS, pError);
}
}
else
{
Debug.Assert(pError.HasErrors());
Debug.Assert(pError.nameText == nameText);
Debug.Assert(pError.typeArgs == typeArgs);
}
return pError;
}
public VoidType GetVoid()
{
return _voidType;
}
public NullType GetNullType()
{
return _nullType;
}
public MethodGroupType GetMethGrpType()
{
return _typeMethGrp;
}
public ArgumentListType GetArgListType()
{
return _argListType;
}
public ErrorType GetErrorSym()
{
return _errorType;
}
public AggregateSymbol GetNullable() => GetPredefAgg(PredefinedType.PT_G_OPTIONAL);
private CType SubstType(CType typeSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth, SubstTypeFlags grfst)
{
if (typeSrc == null)
return null;
var ctx = new SubstContext(typeArgsCls, typeArgsMeth, grfst);
return ctx.FNop() ? typeSrc : SubstTypeCore(typeSrc, ctx);
}
public CType SubstType(CType typeSrc, TypeArray typeArgsCls)
{
return SubstType(typeSrc, typeArgsCls, null, SubstTypeFlags.NormNone);
}
private CType SubstType(CType typeSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth)
{
return SubstType(typeSrc, typeArgsCls, typeArgsMeth, SubstTypeFlags.NormNone);
}
public TypeArray SubstTypeArray(TypeArray taSrc, SubstContext pctx)
{
if (taSrc == null || taSrc.Count == 0 || pctx == null || pctx.FNop())
return taSrc;
CType[] prgpts = new CType[taSrc.Count];
for (int ipts = 0; ipts < taSrc.Count; ipts++)
{
prgpts[ipts] = this.SubstTypeCore(taSrc[ipts], pctx);
}
return _BSymmgr.AllocParams(taSrc.Count, prgpts);
}
private TypeArray SubstTypeArray(TypeArray taSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth, SubstTypeFlags grfst)
{
if (taSrc == null || taSrc.Count == 0)
return taSrc;
var ctx = new SubstContext(typeArgsCls, typeArgsMeth, grfst);
if (ctx.FNop())
return taSrc;
CType[] prgpts = new CType[taSrc.Count];
for (int ipts = 0; ipts < taSrc.Count; ipts++)
{
prgpts[ipts] = SubstTypeCore(taSrc[ipts], ctx);
}
return _BSymmgr.AllocParams(taSrc.Count, prgpts);
}
public TypeArray SubstTypeArray(TypeArray taSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth)
{
return this.SubstTypeArray(taSrc, typeArgsCls, typeArgsMeth, SubstTypeFlags.NormNone);
}
public TypeArray SubstTypeArray(TypeArray taSrc, TypeArray typeArgsCls)
{
return this.SubstTypeArray(taSrc, typeArgsCls, (TypeArray)null, SubstTypeFlags.NormNone);
}
private CType SubstTypeCore(CType type, SubstContext pctx)
{
CType typeSrc;
CType typeDst;
switch (type.GetTypeKind())
{
default:
Debug.Assert(false);
return type;
case TypeKind.TK_NullType:
case TypeKind.TK_VoidType:
case TypeKind.TK_MethodGroupType:
case TypeKind.TK_ArgumentListType:
return type;
case TypeKind.TK_ParameterModifierType:
ParameterModifierType mod = (ParameterModifierType)type;
typeDst = SubstTypeCore(typeSrc = mod.GetParameterType(), pctx);
return (typeDst == typeSrc) ? type : GetParameterModifier(typeDst, mod.isOut);
case TypeKind.TK_ArrayType:
var arr = (ArrayType)type;
typeDst = SubstTypeCore(typeSrc = arr.GetElementType(), pctx);
return (typeDst == typeSrc) ? type : GetArray(typeDst, arr.rank, arr.IsSZArray);
case TypeKind.TK_PointerType:
typeDst = SubstTypeCore(typeSrc = ((PointerType)type).GetReferentType(), pctx);
return (typeDst == typeSrc) ? type : GetPointer(typeDst);
case TypeKind.TK_NullableType:
typeDst = SubstTypeCore(typeSrc = ((NullableType)type).GetUnderlyingType(), pctx);
return (typeDst == typeSrc) ? type : GetNullable(typeDst);
case TypeKind.TK_AggregateType:
AggregateType ats = (AggregateType)type;
if (ats.GetTypeArgsAll().Count > 0)
{
TypeArray typeArgs = SubstTypeArray(ats.GetTypeArgsAll(), pctx);
if (ats.GetTypeArgsAll() != typeArgs)
return GetAggregate(ats.getAggregate(), typeArgs);
}
return type;
case TypeKind.TK_ErrorType:
ErrorType err = (ErrorType)type;
if (err.HasParent())
{
Debug.Assert(err.nameText != null && err.typeArgs != null);
CType pParentType = null;
if (err.HasTypeParent())
{
pParentType = SubstTypeCore(err.GetTypeParent(), pctx);
}
TypeArray typeArgs = SubstTypeArray(err.typeArgs, pctx);
if (typeArgs != err.typeArgs || (err.HasTypeParent() && pParentType != err.GetTypeParent()))
{
return GetErrorType(pParentType, err.GetNSParent(), err.nameText, typeArgs);
}
}
return type;
case TypeKind.TK_TypeParameterType:
{
TypeParameterSymbol tvs = ((TypeParameterType)type).GetTypeParameterSymbol();
int index = tvs.GetIndexInTotalParameters();
if (tvs.IsMethodTypeParameter())
{
if ((pctx.grfst & SubstTypeFlags.DenormMeth) != 0 && tvs.parent != null)
return type;
Debug.Assert(tvs.GetIndexInOwnParameters() == tvs.GetIndexInTotalParameters());
if (index < pctx.ctypeMeth)
{
Debug.Assert(pctx.prgtypeMeth != null);
return pctx.prgtypeMeth[index];
}
else
{
return ((pctx.grfst & SubstTypeFlags.NormMeth) != 0 ? GetStdMethTypeVar(index) : type);
}
}
if ((pctx.grfst & SubstTypeFlags.DenormClass) != 0 && tvs.parent != null)
return type;
return index < pctx.ctypeCls ? pctx.prgtypeCls[index] :
((pctx.grfst & SubstTypeFlags.NormClass) != 0 ? GetStdClsTypeVar(index) : type);
}
}
}
public bool SubstEqualTypes(CType typeDst, CType typeSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth, SubstTypeFlags grfst)
{
if (typeDst.Equals(typeSrc))
{
Debug.Assert(typeDst.Equals(SubstType(typeSrc, typeArgsCls, typeArgsMeth, grfst)));
return true;
}
var ctx = new SubstContext(typeArgsCls, typeArgsMeth, grfst);
return !ctx.FNop() && SubstEqualTypesCore(typeDst, typeSrc, ctx);
}
public bool SubstEqualTypeArrays(TypeArray taDst, TypeArray taSrc, TypeArray typeArgsCls, TypeArray typeArgsMeth, SubstTypeFlags grfst)
{
// Handle the simple common cases first.
if (taDst == taSrc || (taDst != null && taDst.Equals(taSrc)))
{
// The following assertion is not always true and indicates a problem where
// the signature of override method does not match the one inherited from
// the base class. The method match we have found does not take the type
// arguments of the base class into account. So actually we are not overriding
// the method that we "intend" to.
// Debug.Assert(taDst == SubstTypeArray(taSrc, typeArgsCls, typeArgsMeth, grfst));
return true;
}
if (taDst.Count != taSrc.Count)
return false;
if (taDst.Count == 0)
return true;
var ctx = new SubstContext(typeArgsCls, typeArgsMeth, grfst);
if (ctx.FNop())
return false;
for (int i = 0; i < taDst.Count; i++)
{
if (!SubstEqualTypesCore(taDst[i], taSrc[i], ctx))
return false;
}
return true;
}
private bool SubstEqualTypesCore(CType typeDst, CType typeSrc, SubstContext pctx)
{
LRecurse: // Label used for "tail" recursion.
if (typeDst == typeSrc || typeDst.Equals(typeSrc))
{
return true;
}
switch (typeSrc.GetTypeKind())
{
default:
Debug.Assert(false, "Bad Symbol kind in SubstEqualTypesCore");
return false;
case TypeKind.TK_NullType:
case TypeKind.TK_VoidType:
// There should only be a single instance of these.
Debug.Assert(typeDst.GetTypeKind() != typeSrc.GetTypeKind());
return false;
case TypeKind.TK_ArrayType:
ArrayType arrSrc = (ArrayType)typeSrc;
if (!(typeDst is ArrayType arrDst) || arrDst.rank != arrSrc.rank || arrDst.IsSZArray != arrSrc.IsSZArray)
return false;
goto LCheckBases;
case TypeKind.TK_ParameterModifierType:
if (!(typeDst is ParameterModifierType modDest) ||
((pctx.grfst & SubstTypeFlags.NoRefOutDifference) == 0 &&
modDest.isOut != ((ParameterModifierType)typeSrc).isOut))
return false;
goto LCheckBases;
case TypeKind.TK_PointerType:
case TypeKind.TK_NullableType:
if (typeDst.GetTypeKind() != typeSrc.GetTypeKind())
return false;
LCheckBases:
typeSrc = typeSrc.GetBaseOrParameterOrElementType();
typeDst = typeDst.GetBaseOrParameterOrElementType();
goto LRecurse;
case TypeKind.TK_AggregateType:
if (!(typeDst is AggregateType atsDst))
return false;
{ // BLOCK
AggregateType atsSrc = (AggregateType)typeSrc;
if (atsSrc.getAggregate() != atsDst.getAggregate())
return false;
Debug.Assert(atsSrc.GetTypeArgsAll().Count == atsDst.GetTypeArgsAll().Count);
// All the args must unify.
for (int i = 0; i < atsSrc.GetTypeArgsAll().Count; i++)
{
if (!SubstEqualTypesCore(atsDst.GetTypeArgsAll()[i], atsSrc.GetTypeArgsAll()[i], pctx))
return false;
}
}
return true;
case TypeKind.TK_ErrorType:
ErrorType errSrc = (ErrorType)typeSrc;
if (!(typeDst is ErrorType errDst) || !errSrc.HasParent() || !errDst.HasParent())
return false;
{
Debug.Assert(errSrc.nameText != null && errSrc.typeArgs != null);
Debug.Assert(errDst.nameText != null && errDst.typeArgs != null);
if (errSrc.nameText != errDst.nameText || errSrc.typeArgs.Count != errDst.typeArgs.Count)
return false;
if (errSrc.HasTypeParent() != errDst.HasTypeParent())
{
return false;
}
if (errSrc.HasTypeParent())
{
if (errSrc.GetTypeParent() != errDst.GetTypeParent())
{
return false;
}
if (!SubstEqualTypesCore(errDst.GetTypeParent(), errSrc.GetTypeParent(), pctx))
{
return false;
}
}
else
{
if (errSrc.GetNSParent() != errDst.GetNSParent())
{
return false;
}
}
// All the args must unify.
for (int i = 0; i < errSrc.typeArgs.Count; i++)
{
if (!SubstEqualTypesCore(errDst.typeArgs[i], errSrc.typeArgs[i], pctx))
return false;
}
}
return true;
case TypeKind.TK_TypeParameterType:
{ // BLOCK
TypeParameterSymbol tvs = ((TypeParameterType)typeSrc).GetTypeParameterSymbol();
int index = tvs.GetIndexInTotalParameters();
if (tvs.IsMethodTypeParameter())
{
if ((pctx.grfst & SubstTypeFlags.DenormMeth) != 0 && tvs.parent != null)
{
// typeDst == typeSrc was handled above.
Debug.Assert(typeDst != typeSrc);
return false;
}
Debug.Assert(tvs.GetIndexInOwnParameters() == tvs.GetIndexInTotalParameters());
Debug.Assert(pctx.prgtypeMeth == null || tvs.GetIndexInTotalParameters() < pctx.ctypeMeth);
if (index < pctx.ctypeMeth && pctx.prgtypeMeth != null)
{
return typeDst == pctx.prgtypeMeth[index];
}
if ((pctx.grfst & SubstTypeFlags.NormMeth) != 0)
{
return typeDst == GetStdMethTypeVar(index);
}
}
else
{
if ((pctx.grfst & SubstTypeFlags.DenormClass) != 0 && tvs.parent != null)
{
// typeDst == typeSrc was handled above.
Debug.Assert(typeDst != typeSrc);
return false;
}
Debug.Assert(pctx.prgtypeCls == null || tvs.GetIndexInTotalParameters() < pctx.ctypeCls);
if (index < pctx.ctypeCls)
return typeDst == pctx.prgtypeCls[index];
if ((pctx.grfst & SubstTypeFlags.NormClass) != 0)
return typeDst == GetStdClsTypeVar(index);
}
}
return false;
}
}
public static bool TypeContainsType(CType type, CType typeFind)
{
LRecurse: // Label used for "tail" recursion.
if (type == typeFind || type.Equals(typeFind))
return true;
switch (type.GetTypeKind())
{
default:
Debug.Assert(false, "Bad Symbol kind in TypeContainsType");
return false;
case TypeKind.TK_NullType:
case TypeKind.TK_VoidType:
// There should only be a single instance of these.
Debug.Assert(typeFind.GetTypeKind() != type.GetTypeKind());
return false;
case TypeKind.TK_ArrayType:
case TypeKind.TK_NullableType:
case TypeKind.TK_ParameterModifierType:
case TypeKind.TK_PointerType:
type = type.GetBaseOrParameterOrElementType();
goto LRecurse;
case TypeKind.TK_AggregateType:
{ // BLOCK
AggregateType ats = (AggregateType)type;
for (int i = 0; i < ats.GetTypeArgsAll().Count; i++)
{
if (TypeContainsType(ats.GetTypeArgsAll()[i], typeFind))
return true;
}
}
return false;
case TypeKind.TK_ErrorType:
ErrorType err = (ErrorType)type;
if (err.HasParent())
{
Debug.Assert(err.nameText != null && err.typeArgs != null);
for (int i = 0; i < err.typeArgs.Count; i++)
{
if (TypeContainsType(err.typeArgs[i], typeFind))
return true;
}
if (err.HasTypeParent())
{
type = err.GetTypeParent();
goto LRecurse;
}
}
return false;
case TypeKind.TK_TypeParameterType:
return false;
}
}
public static bool TypeContainsTyVars(CType type, TypeArray typeVars)
{
LRecurse: // Label used for "tail" recursion.
switch (type.GetTypeKind())
{
default:
Debug.Assert(false, "Bad Symbol kind in TypeContainsTyVars");
return false;
case TypeKind.TK_NullType:
case TypeKind.TK_VoidType:
case TypeKind.TK_MethodGroupType:
return false;
case TypeKind.TK_ArrayType:
case TypeKind.TK_NullableType:
case TypeKind.TK_ParameterModifierType:
case TypeKind.TK_PointerType:
type = type.GetBaseOrParameterOrElementType();
goto LRecurse;
case TypeKind.TK_AggregateType:
{ // BLOCK
AggregateType ats = (AggregateType)type;
for (int i = 0; i < ats.GetTypeArgsAll().Count; i++)
{
if (TypeContainsTyVars(ats.GetTypeArgsAll()[i], typeVars))
{
return true;
}
}
}
return false;
case TypeKind.TK_ErrorType:
ErrorType err = (ErrorType)type;
if (err.HasParent())
{
Debug.Assert(err.nameText != null && err.typeArgs != null);
for (int i = 0; i < err.typeArgs.Count; i++)
{
if (TypeContainsTyVars(err.typeArgs[i], typeVars))
{
return true;
}
}
if (err.HasTypeParent())
{
type = err.GetTypeParent();
goto LRecurse;
}
}
return false;
case TypeKind.TK_TypeParameterType:
if (typeVars != null && typeVars.Count > 0)
{
int ivar = ((TypeParameterType)type).GetIndexInTotalParameters();
return ivar < typeVars.Count && type == typeVars[ivar];
}
return true;
}
}
public static bool ParametersContainTyVar(TypeArray @params, TypeParameterType typeFind)
{
Debug.Assert(@params != null);
Debug.Assert(typeFind != null);
for (int p = 0; p < @params.Count; p++)
{
CType sym = @params[p];
if (TypeContainsType(sym, typeFind))
{
return true;
}
}
return false;
}
public AggregateSymbol GetPredefAgg(PredefinedType pt) => _predefTypes.GetPredefinedAggregate(pt);
public TypeArray ConcatenateTypeArrays(TypeArray pTypeArray1, TypeArray pTypeArray2)
{
return _BSymmgr.ConcatParams(pTypeArray1, pTypeArray2);
}
public TypeArray GetStdMethTyVarArray(int cTyVars)
{
TypeParameterType[] prgvar = new TypeParameterType[cTyVars];
for (int ivar = 0; ivar < cTyVars; ivar++)
{
prgvar[ivar] = GetStdMethTypeVar(ivar);
}
return _BSymmgr.AllocParams(cTyVars, (CType[])prgvar);
}
public CType SubstType(CType typeSrc, SubstContext pctx)
{
return (pctx == null || pctx.FNop()) ? typeSrc : SubstTypeCore(typeSrc, pctx);
}
public CType SubstType(CType typeSrc, AggregateType atsCls)
{
return SubstType(typeSrc, atsCls, (TypeArray)null);
}
public CType SubstType(CType typeSrc, AggregateType atsCls, TypeArray typeArgsMeth)
{
return SubstType(typeSrc, atsCls?.GetTypeArgsAll(), typeArgsMeth);
}
public CType SubstType(CType typeSrc, CType typeCls, TypeArray typeArgsMeth)
{
return SubstType(typeSrc, (typeCls as AggregateType)?.GetTypeArgsAll(), typeArgsMeth);
}
public TypeArray SubstTypeArray(TypeArray taSrc, AggregateType atsCls, TypeArray typeArgsMeth)
{
return SubstTypeArray(taSrc, atsCls?.GetTypeArgsAll(), typeArgsMeth);
}
public TypeArray SubstTypeArray(TypeArray taSrc, AggregateType atsCls)
{
return this.SubstTypeArray(taSrc, atsCls, (TypeArray)null);
}
private bool SubstEqualTypes(CType typeDst, CType typeSrc, CType typeCls, TypeArray typeArgsMeth)
{
return SubstEqualTypes(typeDst, typeSrc, (typeCls as AggregateType)?.GetTypeArgsAll(), typeArgsMeth, SubstTypeFlags.NormNone);
}
public bool SubstEqualTypes(CType typeDst, CType typeSrc, CType typeCls)
{
return SubstEqualTypes(typeDst, typeSrc, typeCls, (TypeArray)null);
}
//public bool SubstEqualTypeArrays(TypeArray taDst, TypeArray taSrc, AggregateType atsCls, TypeArray typeArgsMeth)
//{
// return SubstEqualTypeArrays(taDst, taSrc, atsCls != null ? atsCls.GetTypeArgsAll() : (TypeArray)null, typeArgsMeth, SubstTypeFlags.NormNone);
//}
public TypeParameterType GetStdMethTypeVar(int iv)
{
return _stvcMethod.GetTypeVarSym(iv, this, true);
}
private TypeParameterType GetStdClsTypeVar(int iv)
{
return _stvcClass.GetTypeVarSym(iv, this, false);
}
public TypeParameterType GetTypeParameter(TypeParameterSymbol pSymbol)
{
// These guys should be singletons for each.
TypeParameterType pTypeParameter = _typeTable.LookupTypeParameter(pSymbol);
if (pTypeParameter == null)
{
pTypeParameter = _typeFactory.CreateTypeParameter(pSymbol);
_typeTable.InsertTypeParameter(pSymbol, pTypeParameter);
}
return pTypeParameter;
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// RUNTIME BINDER ONLY CHANGE
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
internal bool GetBestAccessibleType(CSemanticChecker semanticChecker, BindingContext bindingContext, CType typeSrc, out CType typeDst)
{
// This method implements the "best accessible type" algorithm for determining the type
// of untyped arguments in the runtime binder. It is also used in method type inference
// to fix type arguments to types that are accessible.
// The new type is returned in an out parameter. The result will be true (and the out param
// non-null) only when the algorithm could find a suitable accessible type.
Debug.Assert(semanticChecker != null);
Debug.Assert(bindingContext != null);
Debug.Assert(typeSrc != null);
typeDst = null;
if (semanticChecker.CheckTypeAccess(typeSrc, bindingContext.ContextForMemberLookup))
{
// If we already have an accessible type, then use it. This is the terminal point of the recursion.
typeDst = typeSrc;
return true;
}
// These guys have no accessibility concerns.
Debug.Assert(!(typeSrc is VoidType) && !(typeSrc is ErrorType) && !(typeSrc is TypeParameterType));
if (typeSrc is ParameterModifierType || typeSrc is PointerType)
{
// We cannot vary these.
return false;
}
CType intermediateType;
if (typeSrc is AggregateType aggSrc && (aggSrc.isInterfaceType() || aggSrc.isDelegateType()) && TryVarianceAdjustmentToGetAccessibleType(semanticChecker, bindingContext, aggSrc, out intermediateType))
{
// If we have an interface or delegate type, then it can potentially be varied by its type arguments
// to produce an accessible type, and if that's the case, then return that.
// Example: IEnumerable<PrivateConcreteFoo> --> IEnumerable<PublicAbstractFoo>
typeDst = intermediateType;
Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup));
return true;
}
if (typeSrc is ArrayType arrSrc && TryArrayVarianceAdjustmentToGetAccessibleType(semanticChecker, bindingContext, arrSrc, out intermediateType))
{
// Similarly to the interface and delegate case, arrays are covariant in their element type and
// so we can potentially produce an array type that is accessible.
// Example: PrivateConcreteFoo[] --> PublicAbstractFoo[]
typeDst = intermediateType;
Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup));
return true;
}
if (typeSrc is NullableType)
{
// We have an inaccessible nullable type, which means that the best we can do is System.ValueType.
typeDst = GetPredefAgg(PredefinedType.PT_VALUE).getThisType();
Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup));
return true;
}
if (typeSrc is ArrayType)
{
// We have an inaccessible array type for which we could not earlier find a better array type
// with a covariant conversion, so the best we can do is System.Array.
typeDst = GetPredefAgg(PredefinedType.PT_ARRAY).getThisType();
Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup));
return true;
}
Debug.Assert(typeSrc is AggregateType);
if (typeSrc is AggregateType aggType)
{
// We have an AggregateType, so recurse on its base class.
AggregateType baseType = aggType.GetBaseClass();
if (baseType == null)
{
// This happens with interfaces, for instance. But in that case, the
// conversion to object does exist, is an implicit reference conversion,
// and so we will use it.
baseType = GetPredefAgg(PredefinedType.PT_OBJECT).getThisType();
}
return GetBestAccessibleType(semanticChecker, bindingContext, baseType, out typeDst);
}
return false;
}
private bool TryVarianceAdjustmentToGetAccessibleType(CSemanticChecker semanticChecker, BindingContext bindingContext, AggregateType typeSrc, out CType typeDst)
{
Debug.Assert(typeSrc != null);
Debug.Assert(typeSrc.isInterfaceType() || typeSrc.isDelegateType());
typeDst = null;
AggregateSymbol aggSym = typeSrc.GetOwningAggregate();
AggregateType aggOpenType = aggSym.getThisType();
if (!semanticChecker.CheckTypeAccess(aggOpenType, bindingContext.ContextForMemberLookup))
{
// if the aggregate symbol itself is not accessible, then forget it, there is no
// variance that will help us arrive at an accessible type.
return false;
}
TypeArray typeArgs = typeSrc.GetTypeArgsThis();
TypeArray typeParams = aggOpenType.GetTypeArgsThis();
CType[] newTypeArgsTemp = new CType[typeArgs.Count];
for (int i = 0; i < typeArgs.Count; i++)
{
if (semanticChecker.CheckTypeAccess(typeArgs[i], bindingContext.ContextForMemberLookup))
{
// we have an accessible argument, this position is not a problem.
newTypeArgsTemp[i] = typeArgs[i];
continue;
}
if (!typeArgs[i].IsRefType() || !((TypeParameterType)typeParams[i]).Covariant)
{
// This guy is inaccessible, and we are not going to be able to vary him, so we need to fail.
return false;
}
CType intermediateTypeArg;
if (GetBestAccessibleType(semanticChecker, bindingContext, typeArgs[i], out intermediateTypeArg))
{
// now we either have a value type (which must be accessible due to the above
// check, OR we have an inaccessible type (which must be a ref type). In either
// case, the recursion worked out and we are OK to vary this argument.
newTypeArgsTemp[i] = intermediateTypeArg;
continue;
}
else
{
Debug.Assert(false, "GetBestAccessibleType unexpectedly failed on a type that was used as a type parameter");
return false;
}
}
TypeArray newTypeArgs = semanticChecker.getBSymmgr().AllocParams(typeArgs.Count, newTypeArgsTemp);
CType intermediateType = this.GetAggregate(aggSym, typeSrc.outerType, newTypeArgs);
// All type arguments were varied successfully, which means now we must be accessible. But we could
// have violated constraints. Let's check that out.
if (!TypeBind.CheckConstraints(semanticChecker, null/*ErrorHandling*/, intermediateType, CheckConstraintsFlags.NoErrors))
{
return false;
}
typeDst = intermediateType;
Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup));
return true;
}
private bool TryArrayVarianceAdjustmentToGetAccessibleType(CSemanticChecker semanticChecker, BindingContext bindingContext, ArrayType typeSrc, out CType typeDst)
{
Debug.Assert(typeSrc != null);
typeDst = null;
// We are here because we have an array type with an inaccessible element type. If possible,
// we should create a new array type that has an accessible element type for which a
// conversion exists.
CType elementType = typeSrc.GetElementType();
if (!elementType.IsRefType())
{
// Covariant array conversions exist for reference types only.
return false;
}
CType intermediateType;
if (GetBestAccessibleType(semanticChecker, bindingContext, elementType, out intermediateType))
{
typeDst = this.GetArray(intermediateType, typeSrc.rank, typeSrc.IsSZArray);
Debug.Assert(semanticChecker.CheckTypeAccess(typeDst, bindingContext.ContextForMemberLookup));
return true;
}
return false;
}
public AggregateType ObjectAggregateType => (AggregateType)_symbolTable.GetCTypeFromType(typeof(object));
private readonly Dictionary<Tuple<Assembly, Assembly>, bool> _internalsVisibleToCalculated
= new Dictionary<Tuple<Assembly, Assembly>, bool>();
internal bool InternalsVisibleTo(Assembly assemblyThatDefinesAttribute, Assembly assemblyToCheck)
{
bool result;
var key = Tuple.Create(assemblyThatDefinesAttribute, assemblyToCheck);
if (!_internalsVisibleToCalculated.TryGetValue(key, out result))
{
AssemblyName assyName = null;
// Assembly.GetName() requires FileIOPermission to FileIOPermissionAccess.PathDiscovery.
// If we don't have that (we're in low trust), then we are going to effectively turn off
// InternalsVisibleTo. The alternative is to crash when this happens.
try
{
assyName = assemblyToCheck.GetName();
}
catch (System.Security.SecurityException)
{
result = false;
goto SetMemo;
}
result = assemblyThatDefinesAttribute.GetCustomAttributes()
.OfType<InternalsVisibleToAttribute>()
.Select(ivta => new AssemblyName(ivta.AssemblyName))
.Any(an => AssemblyName.ReferenceMatchesDefinition(an, assyName));
SetMemo:
_internalsVisibleToCalculated[key] = result;
}
return result;
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// END RUNTIME BINDER ONLY CHANGE
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}
| |
//
// Manager.cs
//
// Author:
// Alex Launi <alex.launi@gmail.com>
//
// Copyright (c) 2010 Alex Launi
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if ENABLE_GIO_HARDWARE
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using GLib;
using GUdev;
using System.Runtime.InteropServices;
using Banshee.Hardware;
namespace Banshee.Hardware.Gio
{
public class Manager : IEnumerable<IDevice>, IDisposable
{
private readonly string[] subsystems = new string[] {"block", "usb"};
private Client client;
private VolumeMonitor monitor;
// When a device is unplugged we need to be able to map the Gio.Volume to the
// GUDev.Device as the device will already be gone from udev. We use the native
// handle for the Gio volume as the key to link it to the correct gudev device.
private Dictionary<IntPtr, GUdev.Device> volume_device_map;
public event EventHandler<MountArgs> DeviceAdded;
public event EventHandler<MountArgs> DeviceRemoved;
public Manager ()
{
client = new Client (subsystems);
monitor = VolumeMonitor.Default;
monitor.MountAdded += HandleMonitorMountAdded;
monitor.MountRemoved += HandleMonitorMountRemoved;
monitor.VolumeRemoved += HandleMonitorVolumeRemoved;
volume_device_map= new Dictionary<IntPtr, GUdev.Device> ();
}
#region IDisposable
public void Dispose ()
{
client.Dispose ();
monitor.Dispose ();
}
#endregion
void HandleMonitorMountAdded (object o, MountAddedArgs args)
{
// Manually get the mount as gio-sharp translates it to the wrong managed object
var mount = GLib.MountAdapter.GetObject ((GLib.Object) args.Args [0]);
if (mount.Volume == null)
return;
var device = GudevDeviceFromGioMount (mount);
volume_device_map [mount.Volume.Handle] = device;
var h = DeviceAdded;
if (h != null) {
var v = new RawVolume (mount.Volume,
this,
new GioVolumeMetadataSource (mount.Volume),
new UdevMetadataSource (device));
h (this, new MountArgs (HardwareManager.Resolve (new Device (v))));
}
}
void HandleMonitorMountRemoved (object o, MountRemovedArgs args)
{
// Manually get the mount as gio-sharp translates it to the wrong managed object
var mount = GLib.MountAdapter.GetObject ((GLib.Object) args.Args [0]);
if (mount.Volume == null || mount.Root == null || mount.Root.Path == null) {
return;
}
VolumeRemoved (mount.Volume);
}
void HandleMonitorVolumeRemoved (object o, VolumeRemovedArgs args)
{
var volume = GLib.VolumeAdapter.GetObject ((GLib.Object) args.Args [0]);
if (volume == null) {
return;
}
VolumeRemoved (volume);
}
void VolumeRemoved (GLib.Volume volume)
{
var h = DeviceRemoved;
if (h != null) {
GUdev.Device device;
volume_device_map.TryGetValue (volume.Handle, out device);
var v = new RawVolume (volume,
this,
new GioVolumeMetadataSource (volume),
new UdevMetadataSource (device));
h (this, new MountArgs (new Device (v)));
}
}
public IEnumerable<IDevice> GetAllDevices ()
{
foreach (GLib.Volume vol in monitor.Volumes) {
var device = GudevDeviceFromGioVolume (vol);
if (device == null) {
continue;
}
volume_device_map [vol.Handle] = device;
var raw = new RawVolume (vol,
this,
new GioVolumeMetadataSource (vol),
new UdevMetadataSource (device));
yield return HardwareManager.Resolve (new Device (raw));
}
}
public GUdev.Device GudevDeviceFromSubsystemPropertyValue (string sub, string prop, string val)
{
foreach (GUdev.Device dev in client.QueryBySubsystem (sub)) {
if (dev.HasProperty (prop) && dev.GetProperty (prop) == val)
return dev;
}
return null;
}
public GUdev.Device GudevDeviceFromGioDrive (GLib.Drive drive)
{
GUdev.Device device = null;
if (drive == null) {
return null;
}
string devFile = drive.GetIdentifier ("unix-device");
if (!String.IsNullOrEmpty (devFile)) {
device = client.QueryByDeviceFile (devFile);
}
return device;
}
public GUdev.Device GudevDeviceFromGioVolume (GLib.Volume volume)
{
GUdev.Device device = null;
if (volume == null) {
return null;
}
var s = volume.GetIdentifier ("unix-device");
if (!String.IsNullOrEmpty (s)) {
device = client.QueryByDeviceFile (s);
}
if (device == null) {
s = volume.Uuid;
foreach (GUdev.Device d in client.QueryBySubsystem ("usb")) {
if (s == d.GetSysfsAttr ("serial")) {
device = d;
break;
}
}
}
return device;
}
public GUdev.Device GudevDeviceFromGioMount (GLib.Mount mount)
{
if (mount == null) {
return null;
}
return GudevDeviceFromGioVolume (mount.Volume);
}
#region IEnumerable
public IEnumerator<IDevice> GetEnumerator ()
{
foreach (var device in GetAllDevices ())
yield return device;
}
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
#endregion
}
public class MountArgs : EventArgs
{
public IDevice Device {
get; private set;
}
public MountArgs (IDevice device)
{
Device = device;
}
}
}
#endif
| |
using System;
using System.Data;
using System.Data.OleDb;
using System.Xml;
using System.Collections;
using System.Collections.Generic;
using Epi.Collections;
using System.IO;
using System.Text;
using Epi.Data;
using System.Globalization;
using Epi.Data.Office.Forms;
namespace Epi.Data.Office
{
/// <summary>
/// Concrete Microsoft Excel database implementation
/// </summary>
public partial class Excel2007Workbook : OleDbDatabase
{
#region Constructors
/// <summary>
/// Default Constructor
/// </summary>
public Excel2007Workbook(): base(){}
#endregion Constructors
#region Database Implementation
/// <summary>
/// Set Access database file path
/// </summary>
/// <param name="filePath"></param>
public override void SetDataSourceFilePath(string filePath)
{
this.ConnectionString = filePath;
}
/// <summary>
/// Returns the full name of the data source
/// </summary>
public override string FullName // Implements Database.FullName
{
get
{
return "[MS Excel] " + Location ?? "";
}
}
protected override OleDbConnection GetNativeConnection(string connectionString)
{
OleDbConnectionStringBuilder oleDBCnnStrBuilder = new OleDbConnectionStringBuilder(connectionString);
oleDBCnnStrBuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
oleDBCnnStrBuilder.Add("Extended Properties", "Excel 12.0 Xml;HDR=YES");
return new OleDbConnection(oleDBCnnStrBuilder.ToString());
}
/// <summary>
/// Gets the names of all tables in the database
/// </summary>
/// <returns>Names of all tables in the database</returns>
public override List<string> GetTableNames()
{
List<string> tableNames = new List<string>();
DataTable schemaTable = GetTableSchema();
foreach (DataRow row in schemaTable.Rows)
{
string tableNameCandidate = row[ColumnNames.SCHEMA_TABLE_NAME].ToString();
tableNameCandidate = tableNameCandidate.Replace("'", string.Empty);
if ((tableNameCandidate.Split('$').Length > 1) && (string.IsNullOrEmpty(tableNameCandidate.Split('$')[1])))
{
tableNames.Add(tableNameCandidate);
}
}
return tableNames;
}
/// <summary>
/// Compact the database
/// << may only apply to Access databases >>
/// </summary>
public override bool CompactDatabase()
{
bool success = true;
Type typeJRO = Type.GetTypeFromProgID("JRO.JetEngine");
if (typeJRO == null)
{
throw new InvalidOperationException("JRO.JetEngine can not be created... please check if it is installed");
}
object JRO = Activator.CreateInstance(typeJRO);
string dataSource = DataSource;
string dataSource_Temp = dataSource.Insert(dataSource.LastIndexOf('.'), "_Temp");
object[] paramObjects = new object[]
{
OleConnectionString,
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"" + dataSource_Temp + "\";Jet OLEDB:Engine Type=5"
};
try
{
JRO.GetType().InvokeMember
(
"CompactDatabase",
System.Reflection.BindingFlags.InvokeMethod,
null,
JRO,
paramObjects
);
}
finally
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(JRO);
JRO = null;
}
if (success)
{
System.IO.File.Delete(dataSource);
System.IO.File.Move(dataSource_Temp, dataSource);
}
return success;
}
/// <summary>
/// Creates a table with the given columns
/// </summary>
/// <param name="tableName">Table name to be created</param>
/// <param name="columns">List of columns</param>
public override void CreateTable(string tableName, List<TableColumn> columns)
{
StringBuilder sb = new StringBuilder();
sb.Append("create table ");
sb.Append("[");
sb.Append(tableName);
sb.Append("]");
sb.Append(" ( ");
foreach (TableColumn column in columns)
{
//if (column.Name.ToLowerInvariant() != "uniquekey")
//{
if (column.IsIdentity)
{
sb.Append("[");
sb.Append(column.Name);
sb.Append("]");
sb.Append(" ");
sb.Append(" COUNTER ");
}
else
{
sb.Append("[");
sb.Append(column.Name);
sb.Append("]");
sb.Append(" ");
if (GetDbSpecificColumnType(column.DataType).Equals("text") && column.Length.HasValue && column.Length.Value > 255)
{
sb.Append("memo");
}
else
{
sb.Append(GetDbSpecificColumnType(column.DataType));
}
}
//}
//else
//{
// //UniqueKey exists
// sb.Append("[");
// sb.Append(column.Name);
// sb.Append("] counter ");
//}
if (column.Length != null)
{
if (GetDbSpecificColumnType(column.DataType).Equals("text") && column.Length.HasValue && column.Length.Value <= 255 && column.Length.Value > 0)
{
sb.Append("(");
sb.Append(column.Length.Value.ToString());
sb.Append(") ");
}
}
if (!column.AllowNull)
{
sb.Append(" NOT ");
}
sb.Append(" null ");
if (column.IsPrimaryKey)
{
sb.Append(" constraint");
sb.Append(" PK_");
sb.Append(column.Name);
sb.Append("_");
sb.Append(tableName);
sb.Append(" primary key ");
}
if (!string.IsNullOrEmpty(column.ForeignKeyColumnName) && !string.IsNullOrEmpty(column.ForeignKeyTableName))
{
sb.Append(" references ");
sb.Append(column.ForeignKeyTableName);
sb.Append("([");
sb.Append(column.ForeignKeyColumnName);
sb.Append("]) ");
if (column.CascadeDelete)
{
sb.Append(" on delete cascade");
}
}
sb.Append(", ");
}
sb.Remove(sb.Length - 2, 2);
sb.Append(") ");
ExecuteNonQuery(CreateQuery(sb.ToString()));
}
#endregion
#region Private Members
/// <summary>
/// Gets the database-specific column data type.
/// </summary>
/// <param name="dataType">An extension of the System.Data.DbType that adds StringLong (Text, Memo) data type that Epi Info commonly uses.</param>
/// <returns>Database-specific column data type.</returns>
public override string GetDbSpecificColumnType(GenericDbColumnType dataType)
{
switch (dataType)
{
case GenericDbColumnType.AnsiString:
case GenericDbColumnType.AnsiStringFixedLength:
return AccessColumnType.Text;
case GenericDbColumnType.Binary:
return "binary";
case GenericDbColumnType.Boolean:
return AccessColumnType.YesNo;
case GenericDbColumnType.Byte:
return "byte";
case GenericDbColumnType.Currency:
return AccessColumnType.Currency;
case GenericDbColumnType.Date:
case GenericDbColumnType.DateTime:
case GenericDbColumnType.Time:
return "datetime";
case GenericDbColumnType.Decimal:
case GenericDbColumnType.Double:
return "double";
case GenericDbColumnType.Guid:
return "GUID";
case GenericDbColumnType.Int16:
case GenericDbColumnType.UInt16:
return "SHORT";
case GenericDbColumnType.Int32:
case GenericDbColumnType.UInt32:
return "integer";
case GenericDbColumnType.Int64:
case GenericDbColumnType.UInt64:
return "LONG";
case GenericDbColumnType.Object:
case GenericDbColumnType.Image:
return "LONGBINARY";
case GenericDbColumnType.SByte:
return "byte";
case GenericDbColumnType.Single:
return "single";
case GenericDbColumnType.String:
case GenericDbColumnType.StringFixedLength:
return "text";
case GenericDbColumnType.StringLong:
case GenericDbColumnType.Xml:
return "MEMO";
case GenericDbColumnType.VarNumeric:
return "double";
default:
throw new GeneralException("genericDbColumnType is unknown");
}
}
/// <summary>
/// Read only attribute of connection description
/// </summary>
public override string ConnectionDescription
{
get { return "Microsoft Excel Workbook: " + Location; }
}
/// <summary>
/// Connection String attribute
/// </summary>
public override string ConnectionString
{
get
{
OleDbConnectionStringBuilder cnnBuilder = new OleDbConnectionStringBuilder(base.ConnectionString);
cnnBuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
cnnBuilder.Add("Extended Properties", "Excel 12.0 Xml;HDR=YES");
return cnnBuilder.ToString();
}
set
{
string connectionString;
if (Util.IsFilePath(value))
{
connectionString = Excel2007Workbook.BuildConnectionString(value, "");
}
else
{
connectionString = value;
}
base.ConnectionString = connectionString;
}
}
#endregion
public static string BuildConnectionString(string filePath, string password)
{
StringBuilder builder = new StringBuilder();
if (filePath.EndsWith(".xls", true, System.Globalization.CultureInfo.InvariantCulture))
{
builder.Append("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=");
}
builder.Append(EncodeOleDbConnectionStringValue(filePath));
builder.Append(";ReadOnly=False;Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";");
// sanity check
OleDbConnectionStringBuilder connectionBuilder = new OleDbConnectionStringBuilder(builder.ToString());
return connectionBuilder.ToString();
}
/// <summary>
/// Builds a connection string using default parameters given a database name
/// </summary>
/// <param name="databaseName">Name of the database</param>
/// <returns>A connection string</returns>
public static string BuildDefaultConnectionString(string databaseName)
{
string cnnString = BuildConnectionString(Configuration.GetNewInstance().Directories.Project + "\\" + databaseName + ".xls", string.Empty);
cnnString += ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";
return cnnString;
}
/// <summary>
/// Returns Code Table names for the project
/// </summary>
/// <param name="project">Project</param>
/// <returns>DataTable</returns>
public override DataTable GetCodeTableNamesForProject(Project project)
{
List<string> tables = project.GetDataTableList();
DataSets.TableSchema.TablesDataTable codeTables = project.GetCodeTableList();
foreach (DataSets.TableSchema.TablesRow row in codeTables)
{
tables.Add(row.TABLE_NAME);
}
DataTable bindingTable = new DataTable();
bindingTable.Columns.Add(ColumnNames.NAME);
foreach (string table in tables)
{
if (!string.IsNullOrEmpty(table))
{
if (project.CollectedData.TableExists(table))
{
bindingTable.Rows.Add(new string[] { table });
}
}
}
return bindingTable;
}
/// <summary>
/// Returns code table list
/// </summary>
/// <param name="db">IDbDriver</param>
/// <returns>Epi.DataSets.TableSchema.TablesDataTable</returns>
public override Epi.DataSets.TableSchema.TablesDataTable GetCodeTableList(IDbDriver db)
{
DataSets.TableSchema.TablesDataTable tables = db.GetTableSchema();
//remove tables without prefix "code"
DataRow[] rowsFiltered = tables.Select("TABLE_NAME not like 'code%'");
foreach (DataRow rowFiltered in rowsFiltered)
{
tables.Rows.Remove(rowFiltered);
}
foreach (DataRow row in tables)
{
if (String.IsNullOrEmpty(row.ItemArray[2].ToString()))
{
//remove a row with an empty string
tables.Rows.Remove(row);
}
}
DataRow[] rowsCode = tables.Select("TABLE_NAME like 'code%'");
return tables;
}
/// <summary>
/// Identify Database
/// Note: This will need to be revisited
/// </summary>
/// <returns></returns>
public override string IdentifyDatabase()
{
return "EXCEL";
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="MainForm.Designer.cs" company="None">
// Copyright (c) Brandon Wallace and Jesse Calhoun. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Drawing;
using TQVaultAE.GUI.Properties;
namespace TQVaultAE.GUI
{
/// <summary>
/// MainForm Designer class
/// </summary>
internal partial class MainForm
{
/// <summary>
/// Windows Form Exit button
/// </summary>
private ScalingButton exitButton;
/// <summary>
/// Windows Form Character dropdown
/// </summary>
private ScalingComboBox characterComboBox;
/// <summary>
/// Windows Form Character Label
/// </summary>
private ScalingLabel characterLabel;
/// <summary>
/// Windows Form Item Text Panel
/// </summary>
private System.Windows.Forms.Panel itemTextPanel;
/// <summary>
/// Windows Form item text label
/// </summary>
private ScalingLabel itemText;
/// <summary>
/// Windows Form Vault List Dropdown
/// </summary>
private ScalingComboBox vaultListComboBox;
/// <summary>
/// Windows Form Vault Label
/// </summary>
private ScalingLabel vaultLabel;
/// <summary>
/// Windows Form Configure Button
/// </summary>
private ScalingButton configureButton;
/// <summary>
/// Windows Form Custom Map Text Label
/// </summary>
private ScalingLabel customMapText;
/// <summary>
/// Windows Form Panel Selection Button
/// </summary>
private ScalingButton panelSelectButton;
/// <summary>
/// Windows Form Secondary Vault List Dropdown
/// </summary>
private ScalingComboBox secondaryVaultListComboBox;
/// <summary>
/// Windows Form About Button
/// </summary>
private ScalingButton aboutButton;
/// <summary>
/// Windows Form TQVault Title Label
/// </summary>
private ScalingLabel titleLabel;
/// <summary>
/// Windows Form Search Button
/// </summary>
private ScalingButton searchButton;
/// <summary>
/// Background worker to load resources.
/// </summary>
private System.ComponentModel.BackgroundWorker backgroundWorker1;
/// <summary>
/// Timer for fading in the main form.
/// </summary>
private System.Windows.Forms.Timer fadeInTimer;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (this.components != null))
{
this.components.Dispose();
}
base.Dispose(disposing);
}
#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.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.exitButton = new TQVaultAE.GUI.ScalingButton();
this.characterComboBox = new TQVaultAE.GUI.ScalingComboBox();
this.characterLabel = new TQVaultAE.GUI.ScalingLabel();
this.itemTextPanel = new System.Windows.Forms.Panel();
this.itemText = new TQVaultAE.GUI.ScalingLabel();
this.vaultListComboBox = new TQVaultAE.GUI.ScalingComboBox();
this.vaultLabel = new TQVaultAE.GUI.ScalingLabel();
this.configureButton = new TQVaultAE.GUI.ScalingButton();
this.customMapText = new TQVaultAE.GUI.ScalingLabel();
this.panelSelectButton = new TQVaultAE.GUI.ScalingButton();
this.secondaryVaultListComboBox = new TQVaultAE.GUI.ScalingComboBox();
this.aboutButton = new TQVaultAE.GUI.ScalingButton();
this.titleLabel = new TQVaultAE.GUI.ScalingLabel();
this.searchButton = new TQVaultAE.GUI.ScalingButton();
this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
this.fadeInTimer = new System.Windows.Forms.Timer(this.components);
this.itemTextPanel.SuspendLayout();
this.SuspendLayout();
//
// exitButton
//
this.exitButton.BackColor = System.Drawing.Color.Transparent;
this.exitButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.exitButton.DownBitmap = ((System.Drawing.Bitmap)(resources.GetObject("exitButton.DownBitmap")));
this.exitButton.FlatAppearance.BorderSize = 0;
this.exitButton.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28)))));
this.exitButton.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28)))));
this.exitButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.exitButton.Font = new System.Drawing.Font("Albertus MT Light", 12F * TQVaultData.Database.DB.Scale);
this.exitButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28)))));
this.exitButton.Image = ((System.Drawing.Image)(resources.GetObject("exitButton.Image")));
this.exitButton.Location = this.scalePoint(new System.Drawing.Point(434, 24));
this.exitButton.Name = "exitButton";
this.exitButton.OverBitmap = ((System.Drawing.Bitmap)(resources.GetObject("exitButton.OverBitmap")));
this.exitButton.Size = this.scaleSize(new System.Drawing.Size(137, 30));
this.exitButton.SizeToGraphic = false;
this.exitButton.TabIndex = 0;
this.exitButton.Text = "Exit";
this.exitButton.UpBitmap = ((System.Drawing.Bitmap)(resources.GetObject("exitButton.UpBitmap")));
this.exitButton.UseCustomGraphic = true;
this.exitButton.UseVisualStyleBackColor = false;
this.exitButton.Click += new System.EventHandler(this.ExitButtonClick);
//
// characterComboBox
//
this.characterComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.characterComboBox.Font = new System.Drawing.Font("Albertus MT Light", 11F * TQVaultData.Database.DB.Scale);
this.characterComboBox.Location = this.scalePoint(new System.Drawing.Point(777 , 72));
this.characterComboBox.MaxDropDownItems = 10;
this.characterComboBox.Name = "characterComboBox";
this.characterComboBox.Size = this.scaleSize(new System.Drawing.Size(481, 26));
this.characterComboBox.TabIndex = 1;
this.characterComboBox.SelectedIndexChanged += new System.EventHandler(this.CharacterComboBoxSelectedIndexChanged);
//
// characterLabel
//
this.characterLabel.BackColor = System.Drawing.Color.Transparent;
this.characterLabel.Font = new System.Drawing.Font("Albertus MT Light", 11F * TQVaultData.Database.DB.Scale);
this.characterLabel.ForeColor = System.Drawing.Color.White;
this.characterLabel.Location = this.scalePoint(new System.Drawing.Point(681, 72));
this.characterLabel.Name = "characterLabel";
this.characterLabel.Size = this.scaleSize(new System.Drawing.Size(90, 24));
this.characterLabel.TabIndex = 2;
this.characterLabel.Text = "Character:";
this.characterLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// itemTextPanel
//
this.itemTextPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(188)))), ((int)(((byte)(97)))));
this.itemTextPanel.Controls.Add(this.itemText);
this.itemTextPanel.Location = this.scalePoint(new System.Drawing.Point(6, 606));
this.itemTextPanel.Name = "itemTextPanel";
this.itemTextPanel.Size = this.scaleSize(new System.Drawing.Size(592, 22));
this.itemTextPanel.TabIndex = 4;
//
// itemText
//
this.itemText.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(46)))), ((int)(((byte)(41)))), ((int)(((byte)(31)))));
this.itemText.Font = new System.Drawing.Font("Arial Black", 8.25F);
this.itemText.Location = this.scalePoint(new System.Drawing.Point(2, 2));
this.itemText.Name = "itemText";
this.itemText.Size = this.scaleSize(new System.Drawing.Size(576, 18));
this.itemText.TabIndex = 0;
//
// vaultListComboBox
//
this.vaultListComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.vaultListComboBox.Font = new System.Drawing.Font("Albertus MT Light", 11F * TQVaultData.Database.DB.Scale);
this.vaultListComboBox.Location = this.scalePoint(new System.Drawing.Point(108, 72));
this.vaultListComboBox.Name = "vaultListComboBox";
this.vaultListComboBox.Size = this.scaleSize(new System.Drawing.Size(481, 26));
this.vaultListComboBox.TabIndex = 5;
this.vaultListComboBox.SelectedIndexChanged += new System.EventHandler(this.VaultListComboBoxSelectedIndexChanged);
//
// vaultLabel
//
this.vaultLabel.BackColor = System.Drawing.Color.Transparent;
this.vaultLabel.Font = new System.Drawing.Font("Albertus MT Light", 11F * TQVaultData.Database.DB.Scale);
this.vaultLabel.ForeColor = System.Drawing.Color.White;
this.vaultLabel.Location = this.scalePoint(new System.Drawing.Point(12, 72));
this.vaultLabel.Name = "vaultLabel";
this.vaultLabel.Size = this.scaleSize(new System.Drawing.Size(90, 24));
this.vaultLabel.TabIndex = 6;
this.vaultLabel.Text = "Vault:";
this.vaultLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// configureButton
//
this.configureButton.BackColor = System.Drawing.Color.Transparent;
this.configureButton.DownBitmap = ((System.Drawing.Bitmap)(resources.GetObject("configureButton.DownBitmap")));
this.configureButton.FlatAppearance.BorderSize = 0;
this.configureButton.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28)))));
this.configureButton.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28)))));
this.configureButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.configureButton.Font = new System.Drawing.Font("Albertus MT Light", 12F * TQVaultData.Database.DB.Scale);
this.configureButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28)))));
this.configureButton.Image = ((System.Drawing.Image)(resources.GetObject("configureButton.Image")));
this.configureButton.Location = this.scalePoint(new System.Drawing.Point(6, 24));
this.configureButton.Name = "configureButton";
this.configureButton.OverBitmap = ((System.Drawing.Bitmap)(resources.GetObject("configureButton.OverBitmap")));
this.configureButton.Size = this.scaleSize(new System.Drawing.Size(137, 30));
this.configureButton.SizeToGraphic = false;
this.configureButton.TabIndex = 9;
this.configureButton.Text = "Configure";
this.configureButton.UpBitmap = ((System.Drawing.Bitmap)(resources.GetObject("configureButton.UpBitmap")));
this.configureButton.UseCustomGraphic = true;
this.configureButton.UseVisualStyleBackColor = false;
this.configureButton.Click += new System.EventHandler(this.ConfigureButtonClick);
//
// customMapText
//
this.customMapText.BackColor = System.Drawing.Color.Gold;
this.customMapText.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.customMapText.Font = new System.Drawing.Font("Albertus MT", 11.25F * TQVaultData.Database.DB.Scale, System.Drawing.FontStyle.Bold);
this.customMapText.ForeColor = System.Drawing.Color.Black;
this.customMapText.Location = this.scalePoint(new System.Drawing.Point(312, 811));
this.customMapText.Name = "customMapText";
this.customMapText.Size = this.scaleSize(new System.Drawing.Size(323, 46));
this.customMapText.TabIndex = 11;
this.customMapText.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// panelSelectButton
//
this.panelSelectButton.BackColor = System.Drawing.Color.Transparent;
this.panelSelectButton.DownBitmap = ((System.Drawing.Bitmap)(resources.GetObject("panelSelectButton.DownBitmap")));
this.panelSelectButton.FlatAppearance.BorderSize = 0;
this.panelSelectButton.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28)))));
this.panelSelectButton.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28)))));
this.panelSelectButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.panelSelectButton.Font = new System.Drawing.Font("Albertus MT Light", 12F * TQVaultData.Database.DB.Scale);
this.panelSelectButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28)))));
this.panelSelectButton.Image = ((System.Drawing.Image)(resources.GetObject("panelSelectButton.Image")));
this.panelSelectButton.Location = this.scalePoint(new System.Drawing.Point(148, 24));
this.panelSelectButton.Name = "panelSelectButton";
this.panelSelectButton.OverBitmap = ((System.Drawing.Bitmap)(resources.GetObject("panelSelectButton.OverBitmap")));
this.panelSelectButton.Size = this.scaleSize(new System.Drawing.Size(137, 30));
this.panelSelectButton.SizeToGraphic = false;
this.panelSelectButton.TabIndex = 12;
this.panelSelectButton.Text = "Show Vault";
this.panelSelectButton.UpBitmap = ((System.Drawing.Bitmap)(resources.GetObject("panelSelectButton.UpBitmap")));
this.panelSelectButton.UseCustomGraphic = true;
this.panelSelectButton.UseVisualStyleBackColor = false;
this.panelSelectButton.Click += new System.EventHandler(this.PanelSelectButtonClick);
//
// secondaryVaultListComboBox
//
this.secondaryVaultListComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.secondaryVaultListComboBox.Font = new System.Drawing.Font("Albertus MT Light", 11F * TQVaultData.Database.DB.Scale);
this.secondaryVaultListComboBox.Location = this.scalePoint(new System.Drawing.Point(777, 72));
this.secondaryVaultListComboBox.MaxDropDownItems = 10;
this.secondaryVaultListComboBox.Name = "secondaryVaultListComboBox";
this.secondaryVaultListComboBox.Size = this.scaleSize(new System.Drawing.Size(481, 26));
this.secondaryVaultListComboBox.TabIndex = 15;
this.secondaryVaultListComboBox.SelectedIndexChanged += new System.EventHandler(this.SecondaryVaultListComboBoxSelectedIndexChanged);
//
// aboutButton
//
this.aboutButton.BackColor = System.Drawing.Color.Transparent;
this.aboutButton.DownBitmap = null;
this.aboutButton.FlatAppearance.BorderSize = 0;
this.aboutButton.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28)))));
this.aboutButton.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28)))));
this.aboutButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.aboutButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F * TQVaultData.Database.DB.Scale);
this.aboutButton.Image = ((System.Drawing.Image)(resources.GetObject("aboutButton.Image")));
this.aboutButton.Location = this.scalePoint(new System.Drawing.Point(1130, 21));
this.aboutButton.Name = "aboutButton";
this.aboutButton.OverBitmap = null;
this.aboutButton.Size = this.scaleSize(new System.Drawing.Size(48, 38));
this.aboutButton.SizeToGraphic = false;
this.aboutButton.TabIndex = 16;
this.aboutButton.UpBitmap = ((System.Drawing.Bitmap)(resources.GetObject("aboutButton.UpBitmap")));
this.aboutButton.UseCustomGraphic = true;
this.aboutButton.UseVisualStyleBackColor = false;
this.aboutButton.Click += new System.EventHandler(this.AboutButtonClick);
//
// titleLabel
//
this.titleLabel.AutoSize = true;
this.titleLabel.BackColor = System.Drawing.Color.Transparent;
this.titleLabel.Font = new System.Drawing.Font("Albertus MT Light", 24F * TQVaultData.Database.DB.Scale);
this.titleLabel.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(216)))), ((int)(((byte)(195)))), ((int)(((byte)(112)))));
this.titleLabel.Location = this.scalePoint(new System.Drawing.Point(1180, 18));
this.titleLabel.Name = "titleLabel";
this.titleLabel.Size = this.scaleSize(new System.Drawing.Size(136, 37));
this.titleLabel.TabIndex = 17;
this.titleLabel.Text = "TQVault";
//
// searchButton
//
this.searchButton.BackColor = System.Drawing.Color.Transparent;
this.searchButton.DownBitmap = ((System.Drawing.Bitmap)(resources.GetObject("searchButton.DownBitmap")));
this.searchButton.FlatAppearance.BorderSize = 0;
this.searchButton.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28)))));
this.searchButton.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28)))));
this.searchButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.searchButton.Font = new System.Drawing.Font("Albertus MT Light", 12F * TQVaultData.Database.DB.Scale);
this.searchButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28)))));
this.searchButton.Image = ((System.Drawing.Image)(resources.GetObject("searchButton.Image")));
this.searchButton.Location = this.scalePoint(new System.Drawing.Point(291, 24));
this.searchButton.Name = "searchButton";
this.searchButton.OverBitmap = ((System.Drawing.Bitmap)(resources.GetObject("searchButton.OverBitmap")));
this.searchButton.Size = this.scaleSize(new System.Drawing.Size(137, 30));
this.searchButton.SizeToGraphic = false;
this.searchButton.TabIndex = 18;
this.searchButton.Text = "Search";
this.searchButton.UpBitmap = ((System.Drawing.Bitmap)(resources.GetObject("searchButton.UpBitmap")));
this.searchButton.UseCustomGraphic = true;
this.searchButton.UseVisualStyleBackColor = false;
this.searchButton.Click += new System.EventHandler(this.SearchButtonClick);
//
// backgroundWorker1
//
this.backgroundWorker1.WorkerReportsProgress = true;
this.backgroundWorker1.WorkerSupportsCancellation = true;
this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.BackgroundWorker1_DoWork);
this.backgroundWorker1.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.BackgroundWorker1_ProgressChanged);
this.backgroundWorker1.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.BackgroundWorker1_RunWorkerCompleted);
//
// fadeInTimer
//
this.fadeInTimer.Interval = 50;
this.fadeInTimer.Tick += new System.EventHandler(this.FadeInTimerTick);
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.BackgroundImage = global::TQVaultAE.GUI.Properties.Resources.MainForm_NewBackground;
this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.CancelButton = this.exitButton;
this.ConstrainToDesignRatio = true;
this.Controls.Add(this.searchButton);
this.Controls.Add(this.aboutButton);
this.Controls.Add(this.secondaryVaultListComboBox);
this.Controls.Add(this.panelSelectButton);
this.Controls.Add(this.customMapText);
this.Controls.Add(this.configureButton);
this.Controls.Add(this.vaultLabel);
this.Controls.Add(this.vaultListComboBox);
this.Controls.Add(this.itemTextPanel);
this.Controls.Add(this.characterLabel);
this.Controls.Add(this.characterComboBox);
this.Controls.Add(this.exitButton);
this.Controls.Add(this.titleLabel);
this.DrawCustomBorder = true;
this.ForeColor = System.Drawing.Color.White;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "MainForm";
this.ResizeCustomAllowed = true;
this.ScaleOnResize = true;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Titan Quest Item Vault";
this.TitleTextColor = System.Drawing.Color.FromArgb(((int)(((byte)(51)))), ((int)(((byte)(44)))), ((int)(((byte)(28)))));
this.Closing += new System.ComponentModel.CancelEventHandler(this.MainFormClosing);
this.Load += new System.EventHandler(this.MainFormLoad);
this.Shown += new System.EventHandler(this.MainFormShown);
this.ResizeEnd += new System.EventHandler(this.ResizeEndCallback);
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.MainFormKeyDown);
this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.MainFormKeyPress);
this.Resize += new System.EventHandler(this.ResizeBeginCallback);
this.Controls.SetChildIndex(this.titleLabel, 0);
this.Controls.SetChildIndex(this.exitButton, 0);
this.Controls.SetChildIndex(this.characterComboBox, 0);
this.Controls.SetChildIndex(this.characterLabel, 0);
this.Controls.SetChildIndex(this.itemTextPanel, 0);
this.Controls.SetChildIndex(this.vaultListComboBox, 0);
this.Controls.SetChildIndex(this.vaultLabel, 0);
this.Controls.SetChildIndex(this.configureButton, 0);
this.Controls.SetChildIndex(this.customMapText, 0);
this.Controls.SetChildIndex(this.panelSelectButton, 0);
this.Controls.SetChildIndex(this.secondaryVaultListComboBox, 0);
this.Controls.SetChildIndex(this.aboutButton, 0);
this.Controls.SetChildIndex(this.searchButton, 0);
this.itemTextPanel.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
//
// Authors:
// Ben Motmans <ben.motmans@gmail.com>
//
// Copyright (c) 2007 Ben Motmans
//
// 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 Gtk;
using System;
using System.Threading;
using System.Collections.Generic;
using MonoDevelop.Core;
using MonoDevelop.Ide;
using MonoDevelop.Components;
using MonoDevelop.Database.Sql;
using MonoDevelop.Database.Components;
namespace MonoDevelop.Database.Designer
{
public partial class TableEditorDialog : Gtk.Dialog
{
private SchemaActions action;
private IEditSchemaProvider schemaProvider;
private TableSchemaCollection tables;
private TableSchema table;
private TableSchema originalTable;
private ColumnSchemaCollection columns;
private ConstraintSchemaCollection constraints;
private IndexSchemaCollection indexes;
private TriggerSchemaCollection triggers;
private DataTypeSchemaCollection dataTypes;
private Notebook notebook;
private ColumnsEditorWidget columnEditor;
private ConstraintsEditorWidget constraintEditor;
private IndicesEditorWidget indexEditor;
private TriggersEditorWidget triggerEditor;
private CommentEditorWidget commentEditor;
TableEditorSettings settings;
public TableEditorDialog (IEditSchemaProvider schemaProvider, bool create, TableEditorSettings settings)
{
if (schemaProvider == null)
throw new ArgumentNullException ("schemaProvider");
this.schemaProvider = schemaProvider;
this.action = create ? SchemaActions.Create : SchemaActions.Alter;
this.settings = settings;
this.Build();
if (create)
Title = AddinCatalog.GetString ("Create Table");
else
Title = AddinCatalog.GetString ("Alter Table");
notebook = new Notebook ();
vboxContent.PackStart (notebook, true, true, 0);
notebook.Sensitive = false;
ThreadPool.QueueUserWorkItem (new WaitCallback (InitializeThreaded));
vboxContent.ShowAll ();
}
public void Initialize (TableSchema table)
{
if (table == null)
throw new ArgumentNullException ("table");
this.originalTable = table;
this.table = table;
SetWarning (null);
columnEditor = new ColumnsEditorWidget (schemaProvider, action, settings.ColumnSettings);
columnEditor.ContentChanged += new EventHandler (OnContentChanged);
// When primary Key are selected on the "Column Editor", it has to refresh the "Primary Key" Widget.
columnEditor.PrimaryKeyChanged += delegate(object sender, EventArgs e) {
if (constraintEditor != null)
constraintEditor.RefreshConstraints ();
};
notebook.AppendPage (columnEditor, new Label (AddinCatalog.GetString ("Columns")));
if (settings.ShowConstraints) {
constraintEditor = new ConstraintsEditorWidget (schemaProvider, action, settings.ConstraintSettings);
constraintEditor.ContentChanged += new EventHandler (OnContentChanged);
notebook.AppendPage (constraintEditor, new Label (AddinCatalog.GetString ("Constraints")));
// If Primary Key are changed on it has to refresh the "Column Editor" Widget to select the correct
// columns
constraintEditor.PrimaryKeyChanged += delegate(object sender, EventArgs e) {
columnEditor.RefreshConstraints ();
};
}
//TODO: Implement Index
/*
if (settings.ShowIndices) {
indexEditor = new IndicesEditorWidget (schemaProvider, action);
indexEditor.ContentChanged += OnContentChanged;
notebook.AppendPage (indexEditor, new Label (AddinCatalog.GetString ("Indexes")));
}
*/
if (settings.ShowTriggers) {
triggerEditor = new TriggersEditorWidget (schemaProvider, action);
triggerEditor.ContentChanged += new EventHandler (OnContentChanged);
notebook.AppendPage (triggerEditor, new Label (AddinCatalog.GetString ("Triggers")));
}
if (settings.ShowComment) {
commentEditor = new CommentEditorWidget ();
notebook.AppendPage (commentEditor, new Label (AddinCatalog.GetString ("Comment")));
}
notebook.Page = 0;
entryName.Text = originalTable.Name;
WaitDialog.ShowDialog ("Loading table data ...");
}
private void InitializeThreaded (object state)
{
tables = schemaProvider.GetTables ();
dataTypes = schemaProvider.GetDataTypes ();
columns = originalTable.Columns;
constraints = originalTable.Constraints;
triggers = originalTable.Triggers;
//TODO: indices
indexes = new IndexSchemaCollection ();
System.Text.StringBuilder builder = new System.Text.StringBuilder ();
builder.Append ("Loading editor for TABLE ");
builder.Append (originalTable.Name);
builder.AppendLine ();
builder.Append (" columns = ");
builder.Append (columns.Count);
builder.AppendLine ();
builder.Append ("constraints = ");
builder.Append (constraints.Count);
builder.AppendLine ();
try {
foreach (ColumnSchema col in columns) {
int dummy = col.Constraints.Count; //get column constraints
builder.Append ("CONSTRAINTS ");
builder.Append (col.Name);
builder.Append (" ");
builder.Append (dummy);
builder.AppendLine ();
}
LoggingService.LogDebug (builder.ToString ());
} catch (Exception ee) {
LoggingService.LogDebug (builder.ToString ());
LoggingService.LogError (ee.ToString ());
}
if (action == SchemaActions.Alter) //make a duplicate if we are going to alter the table
this.table = originalTable.Clone () as TableSchema;
DispatchService.GuiDispatch (delegate () {
InitializeGui ();
});
}
private void InitializeGui ()
{
notebook.Sensitive = true;
WaitDialog.HideDialog ();
LoggingService.LogDebug ("TableEditorDialog: entering InitializeGui");
columnEditor.Initialize (table, columns, constraints, dataTypes);
if (constraintEditor != null)
constraintEditor.Initialize (tables, table, columns, constraints, dataTypes);
if (triggerEditor != null)
triggerEditor.Initialize (table, triggers);
LoggingService.LogDebug ("TableEditorDialog: leaving InitializeGui");
}
protected virtual void CancelClicked (object sender, System.EventArgs e)
{
Respond (ResponseType.Cancel);
Hide ();
}
protected virtual void OkClicked (object sender, System.EventArgs e)
{
columnEditor.FillSchemaObjects ();
if (constraintEditor != null)
constraintEditor.FillSchemaObjects ();
if (triggerEditor != null)
triggerEditor.FillSchemaObjects ();
if (commentEditor != null)
table.Comment = commentEditor.Comment;
if (action == SchemaActions.Create)
table.Definition = schemaProvider.GetTableCreateStatement (table);
// else
// table.Definition = schemaProvider.GetTableAlterStatement (table);
if (checkPreview.Active) {
// Preview Dialog: If it's canceled the response to the previous dialog should be None to know that it
// isn't OK and don't close the table editor dialog.
PreviewDialog dlg = new PreviewDialog (table.Definition);
int resp = 0;
while ((resp = dlg.Run ()) != (int)ResponseType.Ok)
if (resp == (int)ResponseType.Cancel)
break;
else
Respond (ResponseType.Cancel);
if (resp == (int)ResponseType.Ok) {
table.Definition = dlg.Text;
Respond (ResponseType.Ok);
Hide ();
} else
Respond (ResponseType.None);
dlg.Destroy ();
} else {
Respond (ResponseType.Ok);
Hide ();
}
}
protected virtual void NameChanged (object sender, System.EventArgs e)
{
table.Name = entryName.Text;
}
protected virtual void OnContentChanged (object sender, EventArgs args)
{
string msg;
bool val = entryName.Text.Length > 0;
if (!val) {
msg = AddinCatalog.GetString ("No name specified.");
goto sens;
}
val &= columnEditor.ValidateSchemaObjects (out msg);
if (!val) goto sens;
if (constraintEditor != null) {
val &= constraintEditor.ValidateSchemaObjects (out msg);
if (!val) goto sens;
}
if (triggerEditor != null) {
val &= triggerEditor.ValidateSchemaObjects (out msg);
if (!val) goto sens;
}
//TODO: validate indexEditor
sens:
SetWarning (msg);
buttonOk.Sensitive = val;
}
protected virtual void SetWarning (string msg)
{
if (msg == null) {
hboxWarning.Hide ();
labelWarning.Text = "";
} else {
hboxWarning.ShowAll ();
labelWarning.Text = msg;
}
}
}
public class TableEditorSettings
{
private bool showConstraints = true;
private bool showComment = false;
private bool showTriggers = true;
private bool showIndices = true;
private ConstraintEditorSettings constraintSettings;
private ColumnEditorSettings columnSettings;
public TableEditorSettings ()
{
constraintSettings = new ConstraintEditorSettings ();
columnSettings = new ColumnEditorSettings ();
}
public ConstraintEditorSettings ConstraintSettings {
get { return constraintSettings; }
}
public ColumnEditorSettings ColumnSettings {
get { return columnSettings; }
}
public bool ShowConstraints {
get {
return constraintSettings.ShowPrimaryKeyConstraints |
constraintSettings.ShowForeignKeyConstraints |
constraintSettings.ShowCheckConstraints |
constraintSettings.ShowUniqueConstraints;
}
}
public bool ShowComment {
get { return showComment; }
set { showComment = value; }
}
public bool ShowTriggers {
get { return showTriggers; }
set { showTriggers = value; }
}
public bool ShowIndices {
get { return showIndices; }
set { showIndices = value; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
namespace System.IO.Compression
{
/// <summary>
/// Provides a wrapper around the ZLib decompression API.
/// </summary>
internal sealed class Inflater : IDisposable
{
private const int MinWindowBits = -15; // WindowBits must be between -8..-15 to ignore the header, 8..15 for
private const int MaxWindowBits = 47; // zlib headers, 24..31 for GZip headers, or 40..47 for either Zlib or GZip
private bool _finished; // Whether the end of the stream has been reached
private bool _isDisposed; // Prevents multiple disposals
private ZLibNative.ZLibStreamHandle _zlibStream; // The handle to the primary underlying zlib stream
private GCHandle _inputBufferHandle; // The handle to the buffer that provides input to _zlibStream
private object SyncLock => this; // Used to make writing to unmanaged structures atomic
/// <summary>
/// Initialized the Inflater with the given windowBits size
/// </summary>
internal Inflater(int windowBits)
{
Debug.Assert(windowBits >= MinWindowBits && windowBits <= MaxWindowBits);
_finished = false;
_isDisposed = false;
InflateInit(windowBits);
}
public int AvailableOutput => (int)_zlibStream.AvailOut;
/// <summary>
/// Returns true if the end of the stream has been reached.
/// </summary>
public bool Finished() => _finished;
public unsafe bool Inflate(out byte b)
{
fixed (byte* bufPtr = &b)
{
int bytesRead = InflateVerified(bufPtr, 1);
Debug.Assert(bytesRead == 0 || bytesRead == 1);
return bytesRead != 0;
}
}
public unsafe int Inflate(byte[] bytes, int offset, int length)
{
// If Inflate is called on an invalid or unready inflater, return 0 to indicate no bytes have been read.
if (length == 0)
return 0;
Debug.Assert(null != bytes, "Can't pass in a null output buffer!");
fixed (byte* bufPtr = bytes)
{
return InflateVerified(bufPtr + offset, length);
}
}
public unsafe int Inflate(Span<byte> destination)
{
// If Inflate is called on an invalid or unready inflater, return 0 to indicate no bytes have been read.
if (destination.Length == 0)
return 0;
fixed (byte* bufPtr = &MemoryMarshal.GetReference(destination))
{
return InflateVerified(bufPtr, destination.Length);
}
}
public unsafe int InflateVerified(byte* bufPtr, int length)
{
// State is valid; attempt inflation
try
{
int bytesRead;
if (ReadInflateOutput(bufPtr, length, ZLibNative.FlushCode.NoFlush, out bytesRead) == ZLibNative.ErrorCode.StreamEnd)
{
_finished = true;
}
return bytesRead;
}
finally
{
// Before returning, make sure to release input buffer if necessary:
if (0 == _zlibStream.AvailIn && _inputBufferHandle.IsAllocated)
{
DeallocateInputBufferHandle();
}
}
}
public bool NeedsInput() => _zlibStream.AvailIn == 0;
public void SetInput(byte[] inputBuffer, int startIndex, int count)
{
Debug.Assert(NeedsInput(), "We have something left in previous input!");
Debug.Assert(inputBuffer != null);
Debug.Assert(startIndex >= 0 && count >= 0 && count + startIndex <= inputBuffer.Length);
Debug.Assert(!_inputBufferHandle.IsAllocated);
if (0 == count)
return;
lock (SyncLock)
{
_inputBufferHandle = GCHandle.Alloc(inputBuffer, GCHandleType.Pinned);
_zlibStream.NextIn = _inputBufferHandle.AddrOfPinnedObject() + startIndex;
_zlibStream.AvailIn = (uint)count;
_finished = false;
}
}
private void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
_zlibStream.Dispose();
if (_inputBufferHandle.IsAllocated)
DeallocateInputBufferHandle();
_isDisposed = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~Inflater()
{
Dispose(false);
}
/// <summary>
/// Creates the ZStream that will handle inflation.
/// </summary>
private void InflateInit(int windowBits)
{
ZLibNative.ErrorCode error;
try
{
error = ZLibNative.CreateZLibStreamForInflate(out _zlibStream, windowBits);
}
catch (Exception exception) // could not load the ZLib dll
{
throw new ZLibException(SR.ZLibErrorDLLLoadError, exception);
}
switch (error)
{
case ZLibNative.ErrorCode.Ok: // Successful initialization
return;
case ZLibNative.ErrorCode.MemError: // Not enough memory
throw new ZLibException(SR.ZLibErrorNotEnoughMemory, "inflateInit2_", (int)error, _zlibStream.GetErrorMessage());
case ZLibNative.ErrorCode.VersionError: //zlib library is incompatible with the version assumed
throw new ZLibException(SR.ZLibErrorVersionMismatch, "inflateInit2_", (int)error, _zlibStream.GetErrorMessage());
case ZLibNative.ErrorCode.StreamError: // Parameters are invalid
throw new ZLibException(SR.ZLibErrorIncorrectInitParameters, "inflateInit2_", (int)error, _zlibStream.GetErrorMessage());
default:
throw new ZLibException(SR.ZLibErrorUnexpected, "inflateInit2_", (int)error, _zlibStream.GetErrorMessage());
}
}
/// <summary>
/// Wrapper around the ZLib inflate function, configuring the stream appropriately.
/// </summary>
private unsafe ZLibNative.ErrorCode ReadInflateOutput(byte* bufPtr, int length, ZLibNative.FlushCode flushCode, out int bytesRead)
{
lock (SyncLock)
{
_zlibStream.NextOut = (IntPtr)bufPtr;
_zlibStream.AvailOut = (uint)length;
ZLibNative.ErrorCode errC = Inflate(flushCode);
bytesRead = length - (int)_zlibStream.AvailOut;
return errC;
}
}
/// <summary>
/// Wrapper around the ZLib inflate function
/// </summary>
private ZLibNative.ErrorCode Inflate(ZLibNative.FlushCode flushCode)
{
ZLibNative.ErrorCode errC;
try
{
errC = _zlibStream.Inflate(flushCode);
}
catch (Exception cause) // could not load the Zlib DLL correctly
{
throw new ZLibException(SR.ZLibErrorDLLLoadError, cause);
}
switch (errC)
{
case ZLibNative.ErrorCode.Ok: // progress has been made inflating
case ZLibNative.ErrorCode.StreamEnd: // The end of the input stream has been reached
return errC;
case ZLibNative.ErrorCode.BufError: // No room in the output buffer - inflate() can be called again with more space to continue
return errC;
case ZLibNative.ErrorCode.MemError: // Not enough memory to complete the operation
throw new ZLibException(SR.ZLibErrorNotEnoughMemory, "inflate_", (int)errC, _zlibStream.GetErrorMessage());
case ZLibNative.ErrorCode.DataError: // The input data was corrupted (input stream not conforming to the zlib format or incorrect check value)
throw new InvalidDataException(SR.UnsupportedCompression);
case ZLibNative.ErrorCode.StreamError: //the stream structure was inconsistent (for example if next_in or next_out was NULL),
throw new ZLibException(SR.ZLibErrorInconsistentStream, "inflate_", (int)errC, _zlibStream.GetErrorMessage());
default:
throw new ZLibException(SR.ZLibErrorUnexpected, "inflate_", (int)errC, _zlibStream.GetErrorMessage());
}
}
/// <summary>
/// Frees the GCHandle being used to store the input buffer
/// </summary>
private void DeallocateInputBufferHandle()
{
Debug.Assert(_inputBufferHandle.IsAllocated);
lock (SyncLock)
{
_zlibStream.AvailIn = 0;
_zlibStream.NextIn = ZLibNative.ZNullPtr;
_inputBufferHandle.Free();
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.Compute.Fluent;
using Microsoft.Azure.Management.Compute.Fluent.Models;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.Samples.Common;
using System;
using System.Collections.Generic;
namespace ManageVirtualMachineWithDisk
{
public class Program
{
private static string userName = "tirekicker";
private static string password = "12NewPA$$w0rd!";
private static Region region = Region.USWestCentral;
/**
* Azure Compute sample for managing virtual machines -
* - Create a virtual machine with
* - Implicit data disks
* - Creatable data disks
* - Existing data disks
* - Update a virtual machine
* - Attach data disks
* - Detach data disks
* - Stop a virtual machine
* - Update a virtual machine
* - Expand the OS disk
* - Expand data disks.
*/
public static void RunSample(IAzure azure)
{
var linuxVmName1 = Utilities.CreateRandomName("VM1");
var rgName = Utilities.CreateRandomName("rgCOMV");
var publicIpDnsLabel = Utilities.CreateRandomName("pip");
try
{
// Creates an empty data disk to attach to the virtual machine
//
Utilities.Log("Creating an empty managed disk");
var dataDisk1 = azure.Disks.Define(Utilities.CreateRandomName("dsk-"))
.WithRegion(region)
.WithNewResourceGroup(rgName)
.WithData()
.WithSizeInGB(50)
.Create();
Utilities.Log("Created managed disk");
// Prepare first creatable data disk
//
var dataDiskCreatable1 = azure.Disks.Define(Utilities.CreateRandomName("dsk-"))
.WithRegion(region)
.WithExistingResourceGroup(rgName)
.WithData()
.WithSizeInGB(100);
// Prepare second creatable data disk
//
var dataDiskCreatable2 = azure.Disks.Define(Utilities.CreateRandomName("dsk-"))
.WithRegion(region)
.WithExistingResourceGroup(rgName)
.WithData()
.WithSizeInGB(50)
.WithSku(DiskSkuTypes.StandardLRS);
//======================================================================
// Create a Linux VM using a PIR image with managed OS and Data disks
Utilities.Log("Creating a managed Linux VM");
var linuxVM = azure.VirtualMachines.Define(linuxVmName1)
.WithRegion(region)
.WithNewResourceGroup(rgName)
.WithNewPrimaryNetwork("10.0.0.0/28")
.WithPrimaryPrivateIPAddressDynamic()
.WithNewPrimaryPublicIPAddress(publicIpDnsLabel)
.WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
.WithRootUsername(userName)
.WithRootPassword(password)
// Begin: Managed data disks
.WithNewDataDisk(100)
.WithNewDataDisk(100, 1, CachingTypes.ReadWrite)
.WithNewDataDisk(dataDiskCreatable1)
.WithNewDataDisk(dataDiskCreatable2, 2, CachingTypes.ReadOnly)
.WithExistingDataDisk(dataDisk1)
// End: Managed data disks
.WithSize(VirtualMachineSizeTypes.StandardD3V2)
.Create();
Utilities.Log("Created a Linux VM with managed OS and data disks: " + linuxVM.Id);
Utilities.PrintVirtualMachine(linuxVM);
//======================================================================
// Update the virtual machine by detaching two data disks with lun 3 and 4 and adding one
Utilities.Log("Updating Linux VM");
var lun3DiskId = linuxVM.DataDisks[3].Id;
linuxVM.Update()
.WithoutDataDisk(3)
.WithoutDataDisk(4)
.WithNewDataDisk(200)
.Apply();
Utilities.Log("Updated Linux VM: " + linuxVM.Id);
Utilities.PrintVirtualMachine(linuxVM);
// ======================================================================
// Delete a managed disk
var disk = azure.Disks.GetById(lun3DiskId);
Utilities.Log("Delete managed disk: " + disk.Id);
azure.Disks.DeleteByResourceGroup(disk.ResourceGroupName, disk.Name);
Utilities.Log("Deleted managed disk");
//======================================================================
// Deallocate the virtual machine
Utilities.Log("De-allocate Linux VM");
linuxVM.Deallocate();
Utilities.Log("De-allocated Linux VM");
//======================================================================
// Resize the OS and Data Disks
var osDisk = azure.Disks.GetById(linuxVM.OSDiskId);
var dataDisks = new List<IDisk>();
foreach (var vmDataDisk in linuxVM.DataDisks.Values)
{
var dataDisk = azure.Disks.GetById(vmDataDisk.Id);
dataDisks.Add(dataDisk);
}
Utilities.Log("Update OS disk: " + osDisk.Id);
osDisk.Update()
.WithSizeInGB(2 * osDisk.SizeInGB)
.Apply();
Utilities.Log("OS disk updated");
foreach (var dataDisk in dataDisks)
{
Utilities.Log("Update data disk: " + dataDisk.Id);
dataDisk.Update()
.WithSizeInGB(dataDisk.SizeInGB + 10)
.Apply();
Utilities.Log("Data disk updated");
}
//======================================================================
// Starting the virtual machine
Utilities.Log("Starting Linux VM");
linuxVM.Start();
Utilities.Log("Started Linux VM");
Utilities.PrintVirtualMachine(linuxVM);
}
finally
{
try
{
Utilities.Log("Deleting Resource Group: " + rgName);
azure.ResourceGroups.DeleteByName(rgName);
Utilities.Log("Deleted Resource Group: " + rgName);
}
catch (NullReferenceException)
{
Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
}
catch (Exception g)
{
Utilities.Log(g);
}
}
}
public static void Main(string[] args)
{
try
{
//=================================================================
// Authenticate
var credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));
var azure = Azure
.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(credentials)
.WithDefaultSubscription();
// Print selected subscription
Utilities.Log("Selected subscription: " + azure.SubscriptionId);
RunSample(azure);
}
catch (Exception e)
{
Utilities.Log(e);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
using Microsoft.Its.Domain.Sql;
using Microsoft.Its.Domain.Sql.CommandScheduler;
using Microsoft.Its.Recipes;
namespace Microsoft.Its.Domain.Testing
{
/// <summary>
/// Provides methods for setting up the starting scenario for a test, including defining past events and routing domain events to handers during the test.
/// </summary>
public class ScenarioBuilder
{
internal bool prepared = false;
private Scenario scenario;
private readonly List<Action> beforePrepare = new List<Action>();
internal readonly List<object> handlers = new List<object>();
private readonly Dictionary<Type, object> commandSchedulers = new Dictionary<Type, object>();
internal readonly List<IEvent> events = new List<IEvent>();
private readonly FakeEventBus eventBus = new FakeEventBus();
private long startCatchupAtEventId;
private readonly Dictionary<Guid, object> aggregateBuilders = new Dictionary<Guid, object>();
// a dictionary of repositories by aggregate type
internal readonly Dictionary<Type, dynamic> repositories = new Dictionary<Type, dynamic>();
internal readonly Dictionary<Type, Guid> defaultAggregateIdsByType = new Dictionary<Type, Guid>();
private readonly Configuration configuration = new Configuration();
/// <summary>
/// Initializes a new instance of the <see cref="ScenarioBuilder"/> class.
/// </summary>
public ScenarioBuilder(Action<Configuration> configure = null)
{
configuration.Container
.Register<IEventBus>(c => eventBus);
configuration.UseInMemoryEventStore();
if (configure != null)
{
configure(Configuration);
}
}
/// <summary>
/// Specifes a delegate used to create <see cref="EventStoreDbContext" /> instances if <see cref="ScenarioBuilderExtensions.UseSqlEventStore{TScenarioBuilder}" /> is set to true.
/// </summary>
public Func<EventStoreDbContext> CreateEventStoreDbContext = () => new EventStoreDbContext();
/// <summary>
/// Specifes a delegate used to create <see cref="DbContext" /> instances for accessing read models.
/// </summary>
public Func<DbContext> CreateReadModelDbContext = () => new ReadModelDbContext();
/// <summary>
/// Helps to organize sets of events by aggregate.
/// </summary>
/// <typeparam name="TAggregate">The type of the aggregate.</typeparam>
/// <param name="aggregateId">The aggregate id.</param>
/// <returns></returns>
public AggregateBuilder<TAggregate> For<TAggregate>(Guid aggregateId)
where TAggregate : IEventSourced
{
return (AggregateBuilder<TAggregate>) aggregateBuilders.GetOrAdd(aggregateId, id => new AggregateBuilder<TAggregate>(id, this));
}
/// <summary>
/// Gets the domain configuration that the scenario builder uses.
/// </summary>
public Configuration Configuration
{
get
{
return configuration;
}
}
/// <summary>
/// Instantiates aggregates from the events within the scenario, and optionally runs projection catchups through specified handlers.
/// </summary>
/// <returns>A Scenario based on the specifications built-up using a <see cref="ScenarioBuilder" />.</returns>
/// <exception cref="System.InvalidOperationException">Already prepared</exception>
public virtual Scenario Prepare()
{
EnsureScenarioHasNotBeenPrepared();
beforePrepare.ForEach(@do => @do());
prepared = true;
// command scheduling
if (configuration.IsUsingCommandSchedulerPipeline() &&
!configuration.IsUsingInMemoryCommandScheduling())
{
var clockName = "TEST-" + Guid.NewGuid().ToString("N");
Configuration.Properties["CommandSchedulerClockName"] = clockName;
Configuration.Container.Register<GetClockName>(c => e => clockName);
var clockRepository = Configuration.SchedulerClockRepository();
clockRepository.CreateClock(clockName, DateTimeOffset.Parse("1970-01-01 12:00:00 +00:00"));
}
configuration.EnsureCommandSchedulerPipelineTrackerIsInitialized();
scenario = new Scenario(this);
var configurationContext = ConfigurationContext.Establish(configuration);
configurationContext.AllowOverride = true;
scenario.RegisterForDispose(configurationContext);
scenario.RegisterForDispose(configuration);
if (configuration.IsUsingSqlEventStore())
{
// capture the highest event id from the event store before the scenario adds new ones
startCatchupAtEventId = CreateEventStoreDbContext().DisposeAfter(db => db.Events.Max<StorableEvent, long?>(e => e.Id) ?? 0) + 1;
}
SourceAggregatesFromInitialEvents();
SubscribeProjectors();
RunCatchup();
SubscribeConsequenters();
InitialEvents.ForEach(ScheduleIfNeeded);
return scenario;
}
/// <summary>
/// Gets the initial events for the scenario.
/// </summary>
/// <remarks>Events added when saving aggregates via a repository after Prepare is called will not be added to <see cref="InitialEvents" />.</remarks>
public IEnumerable<IEvent> InitialEvents
{
get
{
return events.ToArray();
}
}
/// <summary>
/// Gets the event bus on which events are published when saved to the scenario.
/// </summary>
/// <value>
/// The event bus.
/// </value>
public FakeEventBus EventBus
{
get
{
return eventBus;
}
}
internal void EnsureScenarioHasNotBeenPrepared()
{
if (prepared)
{
throw new InvalidOperationException("Once the scenario has been created by calling Prepare, you can no longer make this change.");
}
}
internal void BeforePrepare(Action @do)
{
EnsureScenarioHasNotBeenPrepared();
beforePrepare.Add(@do);
}
internal void ScheduleIfNeeded(IEvent e)
{
var aggregateType = e.AggregateType();
if (e is IScheduledCommand)
{
DateTimeOffset dueTime = ((dynamic) e).DueTime;
var now = Clock.Now();
if (dueTime > now)
{
dynamic commandScheduler = GetOrAddCommandScheduler(aggregateType);
Task schedule = commandScheduler.Schedule((dynamic) e);
schedule.Wait(TimeSpan.FromSeconds(5));
}
}
}
internal object GetOrAddCommandScheduler(Type aggregateType)
{
return commandSchedulers.GetOrAdd(aggregateType, t =>
{
object handler = null;
var container = configuration.Container;
var subscriptionType = typeof (ICommandScheduler<>).MakeGenericType(t);
handler = container.Resolve(subscriptionType);
// add it to handlers so that it will be subscribed with the others
handlers.Add(handler);
return handler;
});
}
private void SourceAggregatesFromInitialEvents()
{
InitialEvents.GroupBy(e => e.AggregateType(),
e => e)
.ForEach(es =>
{
// populate the event stream
var aggregateType = es.Key;
var repositoryType = typeof (IEventSourcedRepository<>).MakeGenericType(aggregateType);
if (!configuration.IsUsingSqlEventStore())
{
var eventStream = configuration.Container.Resolve<InMemoryEventStream>();
var storableEvents = es.AssignSequenceNumbers()
.Select(e => e.ToStoredEvent());
eventStream.Append(storableEvents.ToArray())
.Wait();
}
else
{
PersistEventsToSql(es);
}
dynamic repository = Configuration.Container
.Resolve(repositoryType);
es.Select(e => e.AggregateId).Distinct().ForEach(id =>
{
var aggregate = repository.GetLatest(id).Result;
scenario.aggregates.Add(aggregate);
});
});
}
internal IEventSourcedRepository<TAggregate> GetRepository<TAggregate>() where TAggregate : class, IEventSourced
{
return Configuration.Container.Resolve<IEventSourcedRepository<TAggregate>>();
}
private void PersistEventsToSql(IEnumerable<IEvent> events)
{
using (var eventStore = CreateEventStoreDbContext())
{
events
.AssignSequenceNumbers()
.Select(e => e.ToStorableEvent())
.ForEach(e => eventStore.Events.Add(e));
eventStore.SaveChanges();
}
}
private void RunCatchup()
{
// TODO: (RunCatchup) provide trace output here and throughout
var projectors = handlers.OrEmpty()
.Where(h => h.GetType().IsProjectorType())
.ToArray();
if (!projectors.Any())
{
return;
}
if (configuration.IsUsingSqlEventStore())
{
var catchup = new ReadModelCatchup(projectors)
{
CreateEventStoreDbContext = CreateEventStoreDbContext,
CreateReadModelDbContext = CreateReadModelDbContext,
StartAtEventId = startCatchupAtEventId
};
using (catchup)
using (catchup.EventBus.Errors.Subscribe(scenario.AddEventHandlingError))
using (catchup.Progress.Subscribe(s => Console.WriteLine(s)))
{
catchup.Run();
}
}
else
{
EventBus.PublishAsync(InitialEvents.ToArray()).Wait();
}
if (scenario.EventHandlingErrors.Any())
{
throw new ScenarioSetupException(
"The following event handling errors occurred during projection catchup: " +
string.Join("\n", scenario.EventHandlingErrors.Select(e => e.Exception.ToString())));
}
}
private void SubscribeProjectors()
{
handlers
.Where(h => h.GetType().IsProjectorType())
.ForEach(h => EventBus.Subscribe(h));
}
private void SubscribeConsequenters()
{
handlers
.Where(h => h.GetType().IsConsequenterType())
.ForEach(h => EventBus.Subscribe(h));
}
}
}
| |
#pragma warning disable 1634, 1691 // To enable presharp warning disables (#pragma suppress) below.
//---------------------------------------------------------------------------
//
// <copyright file=RangeContentEnumerator.cs company=Microsoft>
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: IEnumerator for TextRange and TextElement content.
//
//
// History:
// 05/27/2003 : [....] - Created
//
//---------------------------------------------------------------------------
using System;
using System.Collections;
using MS.Internal;
using System.Text;
using MS.Utility;
using System.Windows.Controls;
#pragma warning disable 1634, 1691 // suppressing PreSharp warnings
namespace System.Windows.Documents
{
internal class RangeContentEnumerator : IEnumerator
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
// Creates an enumerator instance.
// Null start/end creates an empty enumerator.
internal RangeContentEnumerator(TextPointer start, TextPointer end)
{
Invariant.Assert(start != null && end != null || start == null && end == null, "If start is null end should be null!");
_start = start;
_end = end;
// Remember what generation the backing store was in when we started,
// so we can throw if this enumerator is accessed after content has
// changed.
if (_start != null)
{
_generation = _start.TextContainer.Generation;
}
}
#endregion Constructors
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Return the current object this enumerator is pointing to. This is
/// generally a FrameworkElement, TextElement, an embedded
/// object, or Text content.
/// </summary>
public object Current
{
get
{
int runLength;
int offset;
if (_navigator == null)
{
// Disable presharp 6503: Property get methods should not throw exceptions.
// We must throw here -- it's part of the IEnumerator contract.
#pragma warning suppress 6503
throw new InvalidOperationException(SR.Get(SRID.EnumeratorNotStarted));
}
// Check _currentCache before looking at _navigator. For the
// last item in the enumeration, _navigator == _end, but
// that's ok, the previous get_Current call (which sets _currentCache
// non-null) put it there.
if (_currentCache != null)
{
return _currentCache;
}
if (_navigator.CompareTo(_end) >= 0)
{
#pragma warning suppress 6503 // IEnumerator.Current is documented to throw this exception
throw new InvalidOperationException(SR.Get(SRID.EnumeratorReachedEnd));
}
// Throw if the tree has been modified since this enumerator was created unless a tree walk
// by the property system is in progress. For example, changing DataContext on FlowDocument
// can invalidate a binding on Run.Text during the inherited property change tree walk,
// which in turn can modify the TextContainer.
if (_generation != _start.TextContainer.Generation && !IsLogicalChildrenIterationInProgress)
{
#pragma warning suppress 6503 // IEnumerator.Current is documented to throw this exception
throw new InvalidOperationException(SR.Get(SRID.EnumeratorVersionChanged));
}
switch (_navigator.GetPointerContext(LogicalDirection.Forward))
{
case TextPointerContext.Text:
offset = 0;
// Merge all successive text runs into a single value.
do
{
runLength = _navigator.GetTextRunLength(LogicalDirection.Forward);
EnsureBufferCapacity(offset + runLength);
_navigator.GetTextInRun(LogicalDirection.Forward, _buffer, offset, runLength);
offset += runLength;
_navigator.MoveToNextContextPosition(LogicalDirection.Forward);
}
while (_navigator.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text);
_currentCache = new string(_buffer, 0, offset);
// _navigator is at next content.
break;
case TextPointerContext.EmbeddedElement:
_currentCache = _navigator.GetAdjacentElement(LogicalDirection.Forward);
// Position _navigator at next content.
_navigator.MoveToNextContextPosition(LogicalDirection.Forward);
break;
case TextPointerContext.ElementStart:
// Return the element, and advance past its entire content.
_navigator.MoveToNextContextPosition(LogicalDirection.Forward);
_currentCache = _navigator.Parent;
// Position _navigator at next content.
_navigator.MoveToElementEdge(ElementEdge.AfterEnd);
break;
default:
Invariant.Assert(false, "Unexpected run type!");
_currentCache = null; // We should never get here.
break;
}
return _currentCache;
}
}
/// <summary>
/// Advance the enumerator to the next object in the range. Return true if content
/// was found.
/// </summary>
public bool MoveNext()
{
// Throw if the tree has been modified since this enumerator was created unless a tree walk
// by the property system is in progress. For example, changing DataContext on FlowDocument
// can invalidate a binding on Run.Text during the inherited property change tree walk,
// which in turn can modify the TextContainer.
if (_start != null && _generation != _start.TextContainer.Generation && !IsLogicalChildrenIterationInProgress)
{
throw new InvalidOperationException(SR.Get(SRID.EnumeratorVersionChanged));
}
if (_start == null || _start.CompareTo(_end) == 0)
return false;
if (_navigator != null && _navigator.CompareTo(_end) >= 0)
{
return false;
}
if (_navigator == null)
{
_navigator = new TextPointer(_start);
}
else if (_currentCache == null) // If we have a cache, _navigator is already positioned at the next item.
{
switch (_navigator.GetPointerContext(LogicalDirection.Forward))
{
case TextPointerContext.Text:
// Skip all successive text runs as a single value.
do
{
_navigator.MoveToNextContextPosition(LogicalDirection.Forward);
}
while (_navigator.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text && _navigator.CompareTo(_end) < 0);
break;
case TextPointerContext.EmbeddedElement:
_navigator.MoveToNextContextPosition(LogicalDirection.Forward);
break;
case TextPointerContext.ElementStart:
// Return the element, and advance past its entire content.
_navigator.MoveToNextContextPosition(LogicalDirection.Forward);
_navigator.MoveToPosition(((TextElement)_navigator.Parent).ElementEnd);
break;
default:
Invariant.Assert(false, "Unexpected run type!");
break;
}
}
_currentCache = null;
return (_navigator.CompareTo(_end) < 0);
}
/// <summary>
/// Reset the enumerator to the start of the range.
/// </summary>
public void Reset()
{
// Throw if the tree has been modified since this enumerator was created.
if (_start != null && _generation != _start.TextContainer.Generation)
{
throw new InvalidOperationException(SR.Get(SRID.EnumeratorVersionChanged));
}
_navigator = null;
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region Public Properties
#endregion Public Properties
//------------------------------------------------------
//
// Public Events
//
//------------------------------------------------------
#region Public Events
#endregion Public Events
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
#endregion Protected Events
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
#endregion Internal methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
#endregion Internal Properties
//------------------------------------------------------
//
// Internal Events
//
//------------------------------------------------------
#region Internal Events
#endregion Internal Events
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
private void EnsureBufferCapacity(int size)
{
char [] newBuffer;
if (_buffer == null)
{
_buffer = new char[size];
}
else if (_buffer.Length < size)
{
newBuffer = new char[Math.Max(2*_buffer.Length, size)];
_buffer.CopyTo(newBuffer, 0);
_buffer = newBuffer;
}
}
#endregion Private methods
//------------------------------------------------------
//
// Private Properties
//
//------------------------------------------------------
#region Private Properties
private bool IsLogicalChildrenIterationInProgress
{
get
{
DependencyObject node = _start.Parent;
while (node != null)
{
FrameworkElement fe = node as FrameworkElement;
if (fe != null)
{
if (fe.IsLogicalChildrenIterationInProgress)
{
return true;
}
}
else
{
FrameworkContentElement fce = node as FrameworkContentElement;
if (fce != null && fce.IsLogicalChildrenIterationInProgress)
{
return true;
}
}
node = LogicalTreeHelper.GetParent(node);
}
return false;
}
}
#endregion Private Properties
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
// Edges of the span to enumerator over.
private readonly TextPointer _start;
private readonly TextPointer _end;
// Backing store generation when this enumerator was created.
private readonly uint _generation;
// Current position in the enumeration.
private TextPointer _navigator;
// Calculated content at the current position.
private object _currentCache;
// Buffer to text content retrieval.
private char [] _buffer;
#endregion Private Fields
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
namespace gov.va.medora.mdo
{
public class Adt
{
string id;
Patient patient;
string checkInId;
string checkOutId;
string relatedPhysicalMovementId;
string transaction;
string movementType;
DateTime timestamp;
string diagnosis;
HospitalLocation assignedLocation;
User provider;
User attending;
string transferFacility;
KeyValuePair<string, string> specialty;
string patientTxId;
string visitId;
string patientMovementNumber;
string nextPatientMovement;
User enteredBy;
string lengthOfStay;
string passDays;
string daysAbsent;
KeyValuePair<string, string> asihAdmission;
string asihTransfer;
string asihSequence;
string asihDays;
DateTime absenceReturnDate;
bool admittedForScCondition;
bool scheduledAdmission;
string admissionSource;
string admittingCategory;
KeyValuePair<string, string> admittingRegulation;
KeyValuePair<string, string> admittingEligibility;
KeyValuePair<string, string> masMovementType;
string lodgingReason;
string lodgingComments;
string disposition;
string eligibility;
string preAdmitId;
User referring;
User consulting;
User admitting;
KeyValuePair<string,string> service;
HospitalLocation priorLocation;
HospitalLocation temporaryLocation;
HospitalLocation pendingLocation;
string patientType;
DateTime admitTimestamp;
DateTime dischargeTimestamp;
string admitReason;
string transferReason;
public Adt() {}
public string Id
{
get
{
return id;
}
set
{
id = value;
}
}
public Patient Patient
{
get
{
return patient;
}
set
{
patient = value;
}
}
public string CheckInId
{
get
{
return checkInId;
}
set
{
checkInId = value;
}
}
public string CheckOutId
{
get
{
return checkOutId;
}
set
{
checkOutId = value;
}
}
public string RelatedPhysicalMovementId
{
get
{
return relatedPhysicalMovementId;
}
set
{
relatedPhysicalMovementId = value;
}
}
public string MovementType
{
get
{
return movementType;
}
set
{
movementType = value;
}
}
public string TransferFacility
{
get
{
return transferFacility;
}
set
{
transferFacility = value;
}
}
public string Transaction
{
get
{
return transaction;
}
set
{
transaction = value;
}
}
public KeyValuePair<string, string> Specialty
{
get
{
return specialty;
}
set
{
specialty = value;
}
}
public string PreAdmitId
{
get
{
return preAdmitId;
}
set
{
preAdmitId = value;
}
}
public User Provider
{
get
{
return provider;
}
set
{
provider = value;
}
}
public User Attending
{
get
{
return attending;
}
set
{
attending = value;
}
}
public User Referring
{
get
{
return referring;
}
set
{
referring = value;
}
}
public User Consulting
{
get
{
return consulting;
}
set
{
consulting = value;
}
}
public User Admitting
{
get
{
return admitting;
}
set
{
admitting = value;
}
}
public KeyValuePair<string,string> Service
{
get
{
return service;
}
set
{
service = value;
}
}
public HospitalLocation AssignedLocation
{
get
{
return assignedLocation;
}
set
{
assignedLocation = value;
}
}
public HospitalLocation PriorLocation
{
get
{
return priorLocation;
}
set
{
priorLocation = value;
}
}
public HospitalLocation TemporaryLocation
{
get
{
return temporaryLocation;
}
set
{
temporaryLocation = value;
}
}
public HospitalLocation PendingLocation
{
get
{
return pendingLocation;
}
set
{
pendingLocation = value;
}
}
public string PatientType
{
get
{
return patientType;
}
set
{
patientType = value;
}
}
public string VisitId
{
get
{
return visitId;
}
set
{
visitId = value;
}
}
public DateTime Timestamp
{
get
{
return timestamp;
}
set
{
timestamp = value;
}
}
public DateTime AdmitTimestamp
{
get
{
return admitTimestamp;
}
set
{
admitTimestamp = value;
}
}
public DateTime DischargeTimestamp
{
get
{
return dischargeTimestamp;
}
set
{
dischargeTimestamp = value;
}
}
public string AdmitReason
{
get
{
return admitReason;
}
set
{
admitReason = value;
}
}
public string TransferReason
{
get
{
return transferReason;
}
set
{
transferReason = value;
}
}
public string Diagnosis
{
get
{
return diagnosis;
}
set
{
diagnosis = value;
}
}
public string PatientTxId
{
get
{
return patientTxId;
}
set
{
patientTxId = value;
}
}
public string PatientMovementNumber
{
get
{
return patientMovementNumber;
}
set
{
patientMovementNumber = value;
}
}
public string NextPatientMovement
{
get
{
return nextPatientMovement;
}
set
{
nextPatientMovement = value;
}
}
public User EnteredBy
{
get
{
return enteredBy;
}
set
{
enteredBy = value;
}
}
public string LengthOfStay
{
get
{
return lengthOfStay;
}
set
{
lengthOfStay = value;
}
}
public string PassDays
{
get
{
return passDays;
}
set
{
passDays = value;
}
}
public string DaysAbsent
{
get
{
return daysAbsent;
}
set
{
daysAbsent = value;
}
}
public KeyValuePair<string,string> AsihAdmission
{
get
{
return asihAdmission;
}
set
{
asihAdmission = value;
}
}
public string AsihTransfer
{
get
{
return asihTransfer;
}
set
{
asihTransfer = value;
}
}
public string AsihSequence
{
get
{
return asihSequence;
}
set
{
asihSequence = value;
}
}
public string AsihDays
{
get
{
return asihDays;
}
set
{
asihDays = value;
}
}
public DateTime AbsenceReturnDate
{
get
{
return absenceReturnDate;
}
set
{
absenceReturnDate = value;
}
}
public bool AdmittedForScCondition
{
get
{
return admittedForScCondition;
}
set
{
admittedForScCondition = value;
}
}
public bool ScheduledAdmission
{
get
{
return scheduledAdmission;
}
set
{
scheduledAdmission = value;
}
}
public string AdmissionSource
{
get
{
return admissionSource;
}
set
{
admissionSource = value;
}
}
public string AdmittingCategory
{
get
{
return admittingCategory;
}
set
{
admittingCategory = value;
}
}
public KeyValuePair<string,string> AdmittingRegulation
{
get
{
return admittingRegulation;
}
set
{
admittingRegulation = value;
}
}
public KeyValuePair<string,string> AdmittingEligibility
{
get
{
return admittingEligibility;
}
set
{
admittingEligibility = value;
}
}
public KeyValuePair<string,string> MasMovementType
{
get
{
return masMovementType;
}
set
{
masMovementType = value;
}
}
public string LodgingReason
{
get
{
return lodgingReason;
}
set
{
lodgingReason = value;
}
}
public string LodgingComments
{
get
{
return lodgingComments;
}
set
{
lodgingComments = value;
}
}
public string Disposition
{
get
{
return disposition;
}
set
{
disposition = value;
}
}
public string Eligibility
{
get
{
return eligibility;
}
set
{
eligibility = value;
}
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using NUnit.Framework;
using NServiceKit.Common;
using NServiceKit.Common.Tests.Models;
using NServiceKit.Text;
using NServiceKit.DataAnnotations;
using System.ComponentModel.DataAnnotations;
namespace NServiceKit.OrmLite.Tests
{
/// <summary>An ORM lite get scalar tests.</summary>
[TestFixture]
public class OrmLiteGetScalarTests:OrmLiteTestBase
{
/// <summary>Can get scalar value.</summary>
[Test]
public void Can_get_scalar_value(){
List<Author> authors = new List<Author>();
authors.Add(new Author() { Name = "Demis Bellot", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 99.9m, Comments = "CSharp books", Rate = 10, City = "London", FloatProperty=10.25f, DoubleProperty=3.23 });
authors.Add(new Author() { Name = "Angel Colmenares", Birthday = DateTime.Today.AddYears(-25), Active = true, Earnings = 50.0m, Comments = "CSharp books", Rate = 5, City = "Bogota",FloatProperty=7.59f,DoubleProperty=4.23 });
authors.Add(new Author() { Name = "Adam Witco", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 80.0m, Comments = "Math Books", Rate = 9, City = "London",FloatProperty=15.5f,DoubleProperty=5.42 });
authors.Add(new Author() { Name = "Claudia Espinel", Birthday = DateTime.Today.AddYears(-23), Active = true, Earnings = 60.0m, Comments = "Cooking books", Rate = 10, City = "Bogota",FloatProperty=0.57f, DoubleProperty=8.76});
authors.Add(new Author() { Name = "Libardo Pajaro", Birthday = DateTime.Today.AddYears(-25), Active = true, Earnings = 80.0m, Comments = "CSharp books", Rate = 9, City = "Bogota", FloatProperty=8.43f, DoubleProperty=7.35});
authors.Add(new Author() { Name = "Jorge Garzon", Birthday = DateTime.Today.AddYears(-28), Active = true, Earnings = 70.0m, Comments = "CSharp books", Rate = 9, City = "Bogota", FloatProperty=1.25f, DoubleProperty=0.3652});
authors.Add(new Author() { Name = "Alejandro Isaza", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 70.0m, Comments = "Java books", Rate = 0, City = "Bogota", FloatProperty=1.5f, DoubleProperty=100.563});
authors.Add(new Author() { Name = "Wilmer Agamez", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 30.0m, Comments = "Java books", Rate = 0, City = "Cartagena", FloatProperty=3.5f,DoubleProperty=7.23 });
authors.Add(new Author() { Name = "Rodger Contreras", Birthday = DateTime.Today.AddYears(-25), Active = true, Earnings = 90.0m, Comments = "CSharp books", Rate = 8, City = "Cartagena", FloatProperty=0.25f,DoubleProperty=9.23 });
authors.Add(new Author() { Name = "Chuck Benedict", Birthday = DateTime.Today.AddYears(-22), Active = true, Earnings = 85.5m, Comments = "CSharp books", Rate = 8, City = "London", FloatProperty=9.95f,DoubleProperty=4.91 });
authors.Add(new Author() { Name = "James Benedict II", Birthday = DateTime.Today.AddYears(-22), Active = true, Earnings = 85.5m, Comments = "Java books", Rate = 5, City = "Berlin",FloatProperty=4.44f,DoubleProperty=6.41 });
authors.Add(new Author() { Name = "Ethan Brown", Birthday = DateTime.Today.AddYears(-20), Active = true, Earnings = 45.0m, Comments = "CSharp books", Rate = 5, City = "Madrid", FloatProperty=6.67f, DoubleProperty=8.05 });
authors.Add(new Author() { Name = "Xavi Garzon", Birthday = DateTime.Today.AddYears(-22), Active = true, Earnings = 75.0m, Comments = "CSharp books", Rate = 9, City = "Madrid", FloatProperty=1.25f, DoubleProperty=3.99});
authors.Add(new Author() { Name = "Luis garzon", Birthday = DateTime.Today.AddYears(-22), Active = true, Earnings = 85.0m, Comments = "CSharp books", Rate = 10,
City = "Mexico",
LastActivity= DateTime.Today,
NRate=5,
FloatProperty=1.25f,
NFloatProperty=3.15f,
DoubleProperty= 1.25,
NDoubleProperty= 8.25
});
using (var db = OpenDbConnection())
{
db.CreateTable<Author>(true);
db.DeleteAll<Author>();
db.InsertAll(authors);
var expectedDate = authors.Max(e=>e.Birthday);
var r1 = db.GetScalar<Author, DateTime>( e => Sql.Max(e.Birthday) );
Assert.That(expectedDate, Is.EqualTo(r1));
expectedDate = authors.Where(e=>e.City=="London").Max(e=>e.Birthday);
r1 = db.GetScalar<Author, DateTime>( e => Sql.Max(e.Birthday), e=>e.City=="London" );
Assert.That(expectedDate, Is.EqualTo(r1));
r1 = db.GetScalar<Author, DateTime>( e => Sql.Max(e.Birthday), e=>e.City=="SinCity" );
Assert.That( default(DateTime), Is.EqualTo(r1));
var expectedNullableDate= authors.Max(e=>e.LastActivity);
DateTime? r2 = db.GetScalar<Author,DateTime?>(e=> Sql.Max(e.LastActivity));
Assert.That(expectedNullableDate, Is.EqualTo(r2));
expectedNullableDate= authors.Where(e=> e.City=="Bogota").Max(e=>e.LastActivity);
r2 = db.GetScalar<Author,DateTime?>(
e=> Sql.Max(e.LastActivity),
e=> e.City=="Bogota" );
Assert.That(expectedNullableDate, Is.EqualTo(r2));
r2 = db.GetScalar<Author, DateTime?>( e => Sql.Max(e.LastActivity), e=>e.City=="SinCity" );
Assert.That( default(DateTime?), Is.EqualTo(r2));
var expectedDecimal= authors.Max(e=>e.Earnings);
decimal r3 = db.GetScalar<Author,decimal>(e=> Sql.Max(e.Earnings));
Assert.That(expectedDecimal, Is.EqualTo(r3));
expectedDecimal= authors.Where(e=>e.City=="London").Max(e=>e.Earnings);
r3 = db.GetScalar<Author,decimal>(e=> Sql.Max(e.Earnings), e=>e.City=="London");
Assert.That(expectedDecimal, Is.EqualTo(r3));
r3 = db.GetScalar<Author,decimal>(e=> Sql.Max(e.Earnings), e=>e.City=="SinCity");
Assert.That( default(decimal), Is.EqualTo(r3));
var expectedNullableDecimal= authors.Max(e=>e.NEarnings);
decimal? r4 = db.GetScalar<Author,decimal?>(e=> Sql.Max(e.NEarnings));
Assert.That(expectedNullableDecimal, Is.EqualTo(r4));
expectedNullableDecimal= authors.Where(e=>e.City=="London").Max(e=>e.NEarnings);
r4 = db.GetScalar<Author,decimal?>(e=> Sql.Max(e.NEarnings), e=>e.City=="London");
Assert.That(expectedNullableDecimal, Is.EqualTo(r4));
r4 = db.GetScalar<Author,decimal?>(e=> Sql.Max(e.NEarnings), e=>e.City=="SinCity");
Assert.That( default(decimal?), Is.EqualTo(r4));
var expectedDouble =authors.Max(e=>e.DoubleProperty);
double r5 = db.GetScalar<Author,double>(e=> Sql.Max(e.DoubleProperty));
Assert.That(expectedDouble, Is.EqualTo(r5));
expectedDouble =authors.Where(e=>e.City=="London").Max(e=>e.DoubleProperty);
r5 = db.GetScalar<Author,double>(e=> Sql.Max(e.DoubleProperty), e=>e.City=="London");
Assert.That(expectedDouble, Is.EqualTo(r5));
r5 = db.GetScalar<Author,double>(e=> Sql.Max(e.DoubleProperty), e=>e.City=="SinCity");
Assert.That(default(double),Is.EqualTo(r5));
var expectedNullableDouble =authors.Max(e=>e.NDoubleProperty);
double? r6 = db.GetScalar<Author,double?>(e=> Sql.Max(e.NDoubleProperty));
Assert.That(expectedNullableDouble, Is.EqualTo(r6));
expectedNullableDouble =authors.Where(e=>e.City=="London").Max(e=>e.NDoubleProperty);
r6 = db.GetScalar<Author,double?>(e=> Sql.Max(e.NDoubleProperty), e=>e.City=="London");
Assert.That(expectedNullableDouble, Is.EqualTo(r6));
r6 = db.GetScalar<Author,double?>(e=> Sql.Max(e.NDoubleProperty), e=>e.City=="SinCity");
Assert.That(default(double?),Is.EqualTo(r6));
var expectedFloat =authors.Max(e=>e.FloatProperty);
var r7 = db.GetScalar<Author,float>(e=> Sql.Max(e.FloatProperty));
Assert.That(expectedFloat, Is.EqualTo(r7));
expectedFloat =authors.Where(e=>e.City=="London").Max(e=>e.FloatProperty);
r7 = db.GetScalar<Author,float>(e=> Sql.Max(e.FloatProperty), e=>e.City=="London");
Assert.That(expectedFloat, Is.EqualTo(r7));
r7 = db.GetScalar<Author,float>(e=> Sql.Max(e.FloatProperty), e=>e.City=="SinCity");
Assert.That(default(float),Is.EqualTo(r7));
var expectedNullableFloat =authors.Max(e=>e.NFloatProperty);
var r8 = db.GetScalar<Author,float?>(e=> Sql.Max(e.NFloatProperty));
Assert.That(expectedNullableFloat, Is.EqualTo(r8));
expectedNullableFloat =authors.Where(e=>e.City=="London").Max(e=>e.NFloatProperty);
r8 = db.GetScalar<Author,float?>(e=> Sql.Max(e.NFloatProperty), e=>e.City=="London");
Assert.That(expectedNullableFloat, Is.EqualTo(r8));
r8 = db.GetScalar<Author,float?>(e=> Sql.Max(e.NFloatProperty), e=>e.City=="SinCity");
Assert.That(default(float?),Is.EqualTo(r8));
var expectedString=authors.Min(e=>e.Name);
var r9 = db.GetScalar<Author,string>(e=> Sql.Min(e.Name));
Assert.That(expectedString, Is.EqualTo(r9));
expectedString=authors.Where(e=>e.City=="London").Min(e=>e.Name);
r9 = db.GetScalar<Author,string>(e=> Sql.Min(e.Name), e=>e.City=="London");
Assert.That(expectedString, Is.EqualTo(r9));
r9 = db.GetScalar<Author,string>(e=> Sql.Max(e.Name), e=>e.City=="SinCity");
Assert.IsNullOrEmpty(r9);
//var expectedBool=authors.Min(e=>e.Active);
//var r10 = db.GetScalar<Author,bool>(e=> Sql.Min(e.Active));
//Assert.That(expectedBool, Is.EqualTo(r10));
//expectedBool=authors.Max(e=>e.Active);
//r10 = db.GetScalar<Author,bool>(e=> Sql.Max(e.Active));
//Assert.That(expectedBool, Is.EqualTo(r10));
//r10 = db.GetScalar<Author,bool>(e=> Sql.Max(e.Active), e=>e.City=="SinCity");
//Assert.IsFalse(r10);
var expectedShort =authors.Max(e=>e.Rate);
var r11 = db.GetScalar<Author,short>(e=> Sql.Max(e.Rate));
Assert.That(expectedShort, Is.EqualTo(r11));
expectedShort =authors.Where(e=>e.City=="London").Max(e=>e.Rate);
r11 = db.GetScalar<Author,short>(e=> Sql.Max(e.Rate), e=>e.City=="London");
Assert.That(expectedShort, Is.EqualTo(r11));
r11 = db.GetScalar<Author,short>(e=> Sql.Max(e.Rate), e=>e.City=="SinCity");
Assert.That(default(short),Is.EqualTo(r7));
var expectedNullableShort =authors.Max(e=>e.NRate);
var r12 = db.GetScalar<Author,short?>(e=> Sql.Max(e.NRate));
Assert.That(expectedNullableShort, Is.EqualTo(r12));
expectedNullableShort =authors.Where(e=>e.City=="London").Max(e=>e.NRate);
r12 = db.GetScalar<Author,short?>(e=> Sql.Max(e.NRate), e=>e.City=="London");
Assert.That(expectedNullableShort, Is.EqualTo(r12));
r12 = db.GetScalar<Author,short?>(e=> Sql.Max(e.NRate), e=>e.City=="SinCity");
Assert.That(default(short?),Is.EqualTo(r12));
}
}
}
/// <summary>An author.</summary>
public class Author
{
/// <summary>
/// Initializes a new instance of the NServiceKit.OrmLite.Tests.Author class.
/// </summary>
public Author(){}
/// <summary>Gets or sets the identifier.</summary>
/// <value>The identifier.</value>
[AutoIncrement]
[Alias("AuthorID")]
public Int32 Id { get; set;}
/// <summary>Gets or sets the name.</summary>
/// <value>The name.</value>
[Index(Unique = true)]
[StringLength(40)]
public string Name { get; set;}
/// <summary>Gets or sets the Date/Time of the birthday.</summary>
/// <value>The birthday.</value>
public DateTime Birthday { get; set;}
/// <summary>Gets or sets the Date/Time of the last activity.</summary>
/// <value>The last activity.</value>
public DateTime? LastActivity { get; set;}
/// <summary>Gets or sets the earnings.</summary>
/// <value>The earnings.</value>
public decimal Earnings { get; set;}
/// <summary>Gets or sets the earnings.</summary>
/// <value>The n earnings.</value>
public decimal? NEarnings { get; set;}
/// <summary>Gets or sets a value indicating whether the active.</summary>
/// <value>true if active, false if not.</value>
public bool Active { get; set; }
/// <summary>Gets or sets the city.</summary>
/// <value>The city.</value>
[StringLength(80)]
[Alias("JobCity")]
public string City { get; set;}
/// <summary>Gets or sets the comments.</summary>
/// <value>The comments.</value>
[StringLength(80)]
[Alias("Comment")]
public string Comments { get; set;}
/// <summary>Gets or sets the rate.</summary>
/// <value>The rate.</value>
public short Rate{ get; set;}
/// <summary>Gets or sets the rate.</summary>
/// <value>The n rate.</value>
public short? NRate{ get; set;}
/// <summary>Gets or sets the float property.</summary>
/// <value>The float property.</value>
public float FloatProperty { get; set;}
/// <summary>Gets or sets the float property.</summary>
/// <value>The n float property.</value>
public float? NFloatProperty { get; set;}
/// <summary>Gets or sets the double property.</summary>
/// <value>The double property.</value>
public double DoubleProperty { get; set;}
/// <summary>Gets or sets the double property.</summary>
/// <value>The n double property.</value>
public double? NDoubleProperty { get; set;}
}
}
| |
using System;
using System.Linq.Expressions;
using OpenQA.Selenium.Remote;
using Signum.Engine;
using Signum.Entities;
using Signum.Entities.Reflection;
using Signum.Utilities;
using System.Reflection;
using Signum.Entities.DynamicQuery;
using Signum.Entities.UserAssets;
using OpenQA.Selenium;
using System.Linq;
using Signum.Utilities.ExpressionTrees;
using Signum.React.Extensions.Selenium.Search;
namespace Signum.React.Selenium
{
public interface ILineContainer<T> : ILineContainer where T : IModifiableEntity
{
}
public interface ILineContainer
{
IWebElement Element { get; }
PropertyRoute Route { get; }
}
public class LineLocator<T>
{
public LineLocator(WebElementLocator elementLocator, PropertyRoute route)
{
ElementLocator = elementLocator;
Route = route;
}
public WebElementLocator ElementLocator { get; set; }
public PropertyRoute Route { get; set; }
}
public static class LineContainerExtensions
{
public static bool HasError(this RemoteWebDriver selenium, string elementId)
{
return selenium.IsElementPresent(By.CssSelector("#{0}.input-validation-error".FormatWith(elementId)));
}
public static LineLocator<S> LineLocator<T, S>(this ILineContainer<T> lineContainer, Expression<Func<T, S>> property) where T : IModifiableEntity
{
PropertyRoute route = lineContainer.Route ?? PropertyRoute.Root(typeof(T));
var element = lineContainer.Element;
foreach (var mi in Reflector.GetMemberList(property))
{
if (mi is MethodInfo && ((MethodInfo)mi).IsInstantiationOf(MixinDeclarations.miMixin))
{
route = route.Add(((MethodInfo)mi).GetGenericArguments()[0]);
}
else
{
var newRoute = route.Add(mi);
if (newRoute.Parent != route && route != lineContainer.Route)
element = element.FindElement(By.CssSelector("[data-property-path='" + route.PropertyString() + "']"));
route = newRoute;
}
}
return new LineLocator<S>(
elementLocator : element.WithLocator(By.CssSelector("[data-property-path='" + route.PropertyString() + "']")),
route : route
);
}
public static bool IsVisible<T, S>(this ILineContainer<T> lineContainer, Expression<Func<T, S>> property)
where T : IModifiableEntity
{
return lineContainer.LineLocator(property).ElementLocator.IsVisible();
}
public static bool IsPresent<T, S>(this ILineContainer<T> lineContainer, Expression<Func<T, S>> property)
where T : IModifiableEntity
{
return lineContainer.LineLocator(property).ElementLocator.IsPresent();
}
public static void WaitVisible<T, S>(this ILineContainer<T> lineContainer, Expression<Func<T, S>> property)
where T : IModifiableEntity
{
lineContainer.LineLocator(property).ElementLocator.WaitVisible();
}
public static void WaitPresent<T, S>(this ILineContainer<T> lineContainer, Expression<Func<T, S>> property)
where T : IModifiableEntity
{
lineContainer.LineLocator(property).ElementLocator.WaitPresent();
}
public static void WaitNoVisible<T, S>(this ILineContainer<T> lineContainer, Expression<Func<T, S>> property)
where T : IModifiableEntity
{
lineContainer.LineLocator(property).ElementLocator.WaitNoVisible();
}
public static void WaitNoPresent<T, S>(this ILineContainer<T> lineContainer, Expression<Func<T, S>> property)
where T : IModifiableEntity
{
lineContainer.LineLocator(property).ElementLocator.WaitNoPresent();
}
public static LineContainer<S> SubContainer<T, S>(this ILineContainer<T> lineContainer, Expression<Func<T, S>> property, IWebElement? element = null)
where T : IModifiableEntity
where S : IModifiableEntity
{
var lineLocator = lineContainer.LineLocator(property);
return new LineContainer<S>(element ?? lineLocator.ElementLocator.WaitVisible(), lineLocator.Route);
}
public static ValueLineProxy ValueLine<T, V>(this ILineContainer<T> lineContainer, Expression<Func<T, V>> property)
where T : IModifiableEntity
{
var lineLocator = lineContainer.LineLocator(property);
return new ValueLineProxy(lineLocator.ElementLocator.WaitVisible(), lineLocator.Route);
}
public static void ValueLineValue<T, V>(this ILineContainer<T> lineContainer, Expression<Func<T, V>> property, V value, bool loseFocus = false)
where T : IModifiableEntity
{
var valueLine = lineContainer.ValueLine(property);
valueLine.SetValue(value);
if (loseFocus)
valueLine.EditableElement.Find().LoseFocus();
}
public static FileLineProxy FileLine<T, V>(this ILineContainer<T> lineContainer, Expression<Func<T, V>> property)
where T : IModifiableEntity
{
var lineLocator = lineContainer.LineLocator(property);
return new FileLineProxy(lineLocator.ElementLocator.WaitVisible(), lineLocator.Route);
}
public static V ValueLineValue<T, V>(this ILineContainer<T> lineContainer, Expression<Func<T, V>> property)
where T : IModifiableEntity
{
return (V)lineContainer.ValueLine(property).GetValue()!;
}
public static EntityLineProxy EntityLine<T, V>(this ILineContainer<T> lineContainer, Expression<Func<T, V>> property)
where T : IModifiableEntity
{
var lineLocator = lineContainer.LineLocator(property);
return new EntityLineProxy(lineLocator.ElementLocator.WaitVisible(), lineLocator.Route);
}
public static V EntityLineValue<T, V>(this ILineContainer<T> lineContainer, Expression<Func<T, V>> property)
where T : IModifiableEntity
{
var lite = lineContainer.EntityLine(property).GetLite();
return lite is V ? (V)lite : (V)(object)lite?.RetrieveAndRemember()!;
}
public static void EntityLineValue<T, V>(this ILineContainer<T> lineContainer, Expression<Func<T, V>> property, V value)
where T : IModifiableEntity
{
lineContainer.EntityLine(property).SetLite(value as Lite<IEntity> ?? ((IEntity?)value)?.ToLite());
}
public static EntityComboProxy EntityCombo<T, V>(this ILineContainer<T> lineContainer, Expression<Func<T, V>> property)
where T : IModifiableEntity
{
var lineLocator = lineContainer.LineLocator(property);
return new EntityComboProxy(lineLocator.ElementLocator.WaitVisible(), lineLocator.Route);
}
public static V EntityComboValue<T, V>(this ILineContainer<T> lineContainer, Expression<Func<T, V>> property)
where T : IModifiableEntity
{
var lite = lineContainer.EntityCombo(property).LiteValue;
return lite is V ? (V)lite : (V)(object)lite?.RetrieveAndRemember()!;
}
public static void EntityComboValue<T, V>(this ILineContainer<T> lineContainer, Expression<Func<T, V>> property, V value, bool loseFocus = false)
where T : IModifiableEntity
{
var combo = lineContainer.EntityCombo(property);
combo.LiteValue = value as Lite<IEntity> ?? ((IEntity?)value)?.ToLite();
if (loseFocus)
combo.ComboElement.WrappedElement.LoseFocus();
}
public static EntityDetailProxy EntityDetail<T, V>(this ILineContainer<T> lineContainer, Expression<Func<T, V>> property)
where T : IModifiableEntity
{
var lineLocator = lineContainer.LineLocator(property);
return new EntityDetailProxy(lineLocator.ElementLocator.WaitVisible(), lineLocator.Route);
}
public static EntityRepeaterProxy EntityRepeater<T, V>(this ILineContainer<T> lineContainer, Expression<Func<T, V>> property)
where T : IModifiableEntity
{
var lineLocator = lineContainer.LineLocator(property);
return new EntityRepeaterProxy(lineLocator.ElementLocator.WaitVisible(), lineLocator.Route);
}
public static EntityTabRepeaterProxy EntityTabRepeater<T, V>(this ILineContainer<T> lineContainer, Expression<Func<T, V>> property)
where T : IModifiableEntity
{
var lineLocator = lineContainer.LineLocator(property);
return new EntityTabRepeaterProxy(lineLocator.ElementLocator.WaitVisible(), lineLocator.Route);
}
public static EntityStripProxy EntityStrip<T, V>(this ILineContainer<T> lineContainer, Expression<Func<T, V>> property)
where T : IModifiableEntity
{
var lineLocator = lineContainer.LineLocator(property);
return new EntityStripProxy(lineLocator.ElementLocator.WaitVisible(), lineLocator.Route);
}
public static EntityListProxy EntityList<T, V>(this ILineContainer<T> lineContainer, Expression<Func<T, V>> property)
where T : IModifiableEntity
{
var lineLocator = lineContainer.LineLocator(property);
return new EntityListProxy(lineLocator.ElementLocator.WaitVisible(), lineLocator.Route);
}
public static EntityTableProxy EntityTable<T, V>(this ILineContainer<T> lineContainer, Expression<Func<T, V>> property)
where T : IModifiableEntity
{
var lineLocator = lineContainer.LineLocator(property);
return new EntityTableProxy(lineLocator.ElementLocator.WaitVisible(), lineLocator.Route);
}
public static EntityListCheckBoxProxy EntityListCheckBox<T, V>(this ILineContainer<T> lineContainer, Expression<Func<T, V>> property)
where T : IModifiableEntity
{
var lineLocator = lineContainer.LineLocator(property);
return new EntityListCheckBoxProxy(lineLocator.ElementLocator.WaitVisible(), lineLocator.Route);
}
public static QueryTokenBuilderProxy QueryTokenBuilder<T>(this ILineContainer<T> lineContainer, Expression<Func<T, QueryTokenEmbedded>> property)
where T : IModifiableEntity
{
var lineLocator = lineContainer.LineLocator(property);
return new QueryTokenBuilderProxy(lineLocator.ElementLocator.WaitVisible());
}
public static void SelectTab(this ILineContainer lineContainer, string eventKey)
{
var element = lineContainer.Element.WaitElementVisible(By.CssSelector($"a.nav-item[data-rb-event-key='{eventKey}']"));
element.ScrollTo();
element.Click();
}
public static SearchControlProxy GetSearchControl(this ILineContainer lineContainer, object queryName)
{
string queryKey = QueryUtils.GetKey(queryName);
var element = lineContainer.Element.WaitElementVisible(By.CssSelector("div.sf-search-control[data-query-key={0}]".FormatWith(queryKey)));
return new SearchControlProxy(element);
}
public static ValueSearchControlLineProxy GetValueSearchControlLine(this ILineContainer lineContainer, object queryName)
{
string queryKey = QueryUtils.GetKey(queryName);
var element = lineContainer.Element.WaitElementVisible(By.CssSelector("[data-value-query-key={0}]".FormatWith(queryKey)));
return new ValueSearchControlLineProxy(element);
}
}
public class LineContainer<T> :ILineContainer<T> where T:IModifiableEntity
{
public IWebElement Element { get; private set; }
public PropertyRoute Route { get; private set; }
public LineContainer(IWebElement element, PropertyRoute? route = null)
{
this.Element = element;
this.Route = route ?? PropertyRoute.Root(typeof(T));
}
public LineContainer<S> As<S>() where S : T
{
return new LineContainer<S>(this.Element, PropertyRoute.Root(typeof(S)));
}
}
}
| |
/****************************************************************************
Copyright 2002-2005 GL Conseil/Flow Group SAS. All rights reserved.
Permission is granted to anyone to use this software for any purpose on
any computer system, and to alter it and redistribute it, subject
to the following restrictions:
1. The author is not responsible for the consequences of use of this
software, no matter how awful, even if they arise from flaws in it.
2. The origin of this software must not be misrepresented, either by
explicit claim or by omission. Since few users ever read sources,
credits must appear in the documentation.
3. Altered versions must be plainly marked as such, and must not be
misrepresented as being the original software. Since few users
ever read sources, credits must appear in the documentation.
4. This notice may not be removed or altered.
----------------------------------------------------------------------------
This software is derived from the RSA Data Security, Inc.
MD5 Message-Digest Algorithm.
Copyright (C) 1990-2, RSA Data Security, Inc. Created 1990.
All rights reserved.
RSA Data Security, Inc. makes no representations concerning either
the merchantability of this software or the suitability of this
software for any particular purpose. It is provided ""as is""
without express or implied warranty of any kind.
These notices must be retained in any copies of any part of this
documentation and/or software.
Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991.
All rights reserved.
****************************************************************************/
// src: http://www.flowgroup.fr/en/kb/technical/md5.aspx
// 03/17/07
// Changed namespace
using System;
using System.IO;
using System.Text;
namespace RPiAndroid_new
{
public class MD5CryptoServiceProvider : MD5
{
public MD5CryptoServiceProvider()
: base()
{
}
}
/// <summary>
/// Summary description for MD5.
/// </summary>
public class MD5 : IDisposable
{
static public MD5 Create(string hashName)
{
if (hashName == "MD5")
return new MD5();
else
throw new NotSupportedException();
}
static public string GetMd5String(String source)
{
MD5 md = MD5CryptoServiceProvider.Create();
byte[] hash;
//Create a new instance of ASCIIEncoding to
//convert the string into an array of Unicode bytes.
UTF8Encoding enc = new UTF8Encoding();
// ASCIIEncoding enc = new ASCIIEncoding();
//Convert the string into an array of bytes.
byte[] buffer = enc.GetBytes(source);
//Create the hash value from the array of bytes.
hash = md.ComputeHash(buffer);
StringBuilder sb = new StringBuilder();
foreach (byte b in hash)
sb.Append(b.ToString("x2"));
return sb.ToString();
}
static public MD5 Create()
{
return new MD5();
}
#region base implementation of the MD5
#region constants
private const byte S11 = 7;
private const byte S12 = 12;
private const byte S13 = 17;
private const byte S14 = 22;
private const byte S21 = 5;
private const byte S22 = 9;
private const byte S23 = 14;
private const byte S24 = 20;
private const byte S31 = 4;
private const byte S32 = 11;
private const byte S33 = 16;
private const byte S34 = 23;
private const byte S41 = 6;
private const byte S42 = 10;
private const byte S43 = 15;
private const byte S44 = 21;
static private byte[] PADDING = new byte[] {
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
#endregion
#region F, G, H and I are basic MD5 functions.
static private uint F(uint x, uint y, uint z)
{
return (((x) & (y)) | ((~x) & (z)));
}
static private uint G(uint x, uint y, uint z)
{
return (((x) & (z)) | ((y) & (~z)));
}
static private uint H(uint x, uint y, uint z)
{
return ((x) ^ (y) ^ (z));
}
static private uint I(uint x, uint y, uint z)
{
return ((y) ^ ((x) | (~z)));
}
#endregion
#region rotates x left n bits.
/// <summary>
/// rotates x left n bits.
/// </summary>
/// <param name="x"></param>
/// <param name="n"></param>
/// <returns></returns>
static private uint ROTATE_LEFT(uint x, byte n)
{
return (((x) << (n)) | ((x) >> (32 - (n))));
}
#endregion
#region FF, GG, HH, and II transformations
/// FF, GG, HH, and II transformations
/// for rounds 1, 2, 3, and 4.
/// Rotation is separate from addition to prevent recomputation.
static private void FF(ref uint a, uint b, uint c, uint d, uint x, byte s, uint ac)
{
(a) += F((b), (c), (d)) + (x) + (uint)(ac);
(a) = ROTATE_LEFT((a), (s));
(a) += (b);
}
static private void GG(ref uint a, uint b, uint c, uint d, uint x, byte s, uint ac)
{
(a) += G((b), (c), (d)) + (x) + (uint)(ac);
(a) = ROTATE_LEFT((a), (s));
(a) += (b);
}
static private void HH(ref uint a, uint b, uint c, uint d, uint x, byte s, uint ac)
{
(a) += H((b), (c), (d)) + (x) + (uint)(ac);
(a) = ROTATE_LEFT((a), (s));
(a) += (b);
}
static private void II(ref uint a, uint b, uint c, uint d, uint x, byte s, uint ac)
{
(a) += I((b), (c), (d)) + (x) + (uint)(ac);
(a) = ROTATE_LEFT((a), (s));
(a) += (b);
}
#endregion
#region context info
/// <summary>
/// state (ABCD)
/// </summary>
uint[] state = new uint[4];
/// <summary>
/// number of bits, modulo 2^64 (lsb first)
/// </summary>
uint[] count = new uint[2];
/// <summary>
/// input buffer
/// </summary>
byte[] buffer = new byte[64];
#endregion
internal MD5()
{
Initialize();
}
/// <summary>
/// MD5 initialization. Begins an MD5 operation, writing a new context.
/// </summary>
/// <remarks>
/// The RFC named it "MD5Init"
/// </remarks>
public virtual void Initialize()
{
count[0] = count[1] = 0;
// Load magic initialization constants.
state[0] = 0x67452301;
state[1] = 0xefcdab89;
state[2] = 0x98badcfe;
state[3] = 0x10325476;
}
/// <summary>
/// MD5 block update operation. Continues an MD5 message-digest
/// operation, processing another message block, and updating the
/// context.
/// </summary>
/// <param name="input"></param>
/// <param name="offset"></param>
/// <param name="count"></param>
/// <remarks>The RFC Named it MD5Update</remarks>
protected virtual void HashCore(byte[] input, int offset, int count)
{
int i;
int index;
int partLen;
// Compute number of bytes mod 64
index = (int)((this.count[0] >> 3) & 0x3F);
// Update number of bits
if ((this.count[0] += (uint)((uint)count << 3)) < ((uint)count << 3))
this.count[1]++;
this.count[1] += ((uint)count >> 29);
partLen = 64 - index;
// Transform as many times as possible.
if (count >= partLen)
{
Buffer.BlockCopy(input, offset, this.buffer, index, partLen);
Transform(this.buffer, 0);
for (i = partLen; i + 63 < count; i += 64)
Transform(input, offset + i);
index = 0;
}
else
i = 0;
// Buffer remaining input
Buffer.BlockCopy(input, offset + i, this.buffer, index, count - i);
}
/// <summary>
/// MD5 finalization. Ends an MD5 message-digest operation, writing the
/// the message digest and zeroizing the context.
/// </summary>
/// <returns>message digest</returns>
/// <remarks>The RFC named it MD5Final</remarks>
protected virtual byte[] HashFinal()
{
byte[] digest = new byte[16];
byte[] bits = new byte[8];
int index, padLen;
// Save number of bits
Encode(bits, 0, this.count, 0, 8);
// Pad out to 56 mod 64.
index = (int)((uint)(this.count[0] >> 3) & 0x3f);
padLen = (index < 56) ? (56 - index) : (120 - index);
HashCore(PADDING, 0, padLen);
// Append length (before padding)
HashCore(bits, 0, 8);
// Store state in digest
Encode(digest, 0, state, 0, 16);
// Zeroize sensitive information.
count[0] = count[1] = 0;
state[0] = 0;
state[1] = 0;
state[2] = 0;
state[3] = 0;
// initialize again, to be ready to use
Initialize();
return digest;
}
/// <summary>
/// MD5 basic transformation. Transforms state based on 64 bytes block.
/// </summary>
/// <param name="block"></param>
/// <param name="offset"></param>
private void Transform(byte[] block, int offset)
{
uint a = state[0], b = state[1], c = state[2], d = state[3];
uint[] x = new uint[16];
Decode(x, 0, block, offset, 64);
// Round 1
FF(ref a, b, c, d, x[0], S11, 0xd76aa478); /* 1 */
FF(ref d, a, b, c, x[1], S12, 0xe8c7b756); /* 2 */
FF(ref c, d, a, b, x[2], S13, 0x242070db); /* 3 */
FF(ref b, c, d, a, x[3], S14, 0xc1bdceee); /* 4 */
FF(ref a, b, c, d, x[4], S11, 0xf57c0faf); /* 5 */
FF(ref d, a, b, c, x[5], S12, 0x4787c62a); /* 6 */
FF(ref c, d, a, b, x[6], S13, 0xa8304613); /* 7 */
FF(ref b, c, d, a, x[7], S14, 0xfd469501); /* 8 */
FF(ref a, b, c, d, x[8], S11, 0x698098d8); /* 9 */
FF(ref d, a, b, c, x[9], S12, 0x8b44f7af); /* 10 */
FF(ref c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
FF(ref b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
FF(ref a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
FF(ref d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
FF(ref c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
FF(ref b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
// Round 2
GG(ref a, b, c, d, x[1], S21, 0xf61e2562); /* 17 */
GG(ref d, a, b, c, x[6], S22, 0xc040b340); /* 18 */
GG(ref c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
GG(ref b, c, d, a, x[0], S24, 0xe9b6c7aa); /* 20 */
GG(ref a, b, c, d, x[5], S21, 0xd62f105d); /* 21 */
GG(ref d, a, b, c, x[10], S22, 0x2441453); /* 22 */
GG(ref c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
GG(ref b, c, d, a, x[4], S24, 0xe7d3fbc8); /* 24 */
GG(ref a, b, c, d, x[9], S21, 0x21e1cde6); /* 25 */
GG(ref d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
GG(ref c, d, a, b, x[3], S23, 0xf4d50d87); /* 27 */
GG(ref b, c, d, a, x[8], S24, 0x455a14ed); /* 28 */
GG(ref a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
GG(ref d, a, b, c, x[2], S22, 0xfcefa3f8); /* 30 */
GG(ref c, d, a, b, x[7], S23, 0x676f02d9); /* 31 */
GG(ref b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
// Round 3
HH(ref a, b, c, d, x[5], S31, 0xfffa3942); /* 33 */
HH(ref d, a, b, c, x[8], S32, 0x8771f681); /* 34 */
HH(ref c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
HH(ref b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
HH(ref a, b, c, d, x[1], S31, 0xa4beea44); /* 37 */
HH(ref d, a, b, c, x[4], S32, 0x4bdecfa9); /* 38 */
HH(ref c, d, a, b, x[7], S33, 0xf6bb4b60); /* 39 */
HH(ref b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
HH(ref a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
HH(ref d, a, b, c, x[0], S32, 0xeaa127fa); /* 42 */
HH(ref c, d, a, b, x[3], S33, 0xd4ef3085); /* 43 */
HH(ref b, c, d, a, x[6], S34, 0x4881d05); /* 44 */
HH(ref a, b, c, d, x[9], S31, 0xd9d4d039); /* 45 */
HH(ref d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
HH(ref c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
HH(ref b, c, d, a, x[2], S34, 0xc4ac5665); /* 48 */
// Round 4
II(ref a, b, c, d, x[0], S41, 0xf4292244); /* 49 */
II(ref d, a, b, c, x[7], S42, 0x432aff97); /* 50 */
II(ref c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
II(ref b, c, d, a, x[5], S44, 0xfc93a039); /* 52 */
II(ref a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
II(ref d, a, b, c, x[3], S42, 0x8f0ccc92); /* 54 */
II(ref c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
II(ref b, c, d, a, x[1], S44, 0x85845dd1); /* 56 */
II(ref a, b, c, d, x[8], S41, 0x6fa87e4f); /* 57 */
II(ref d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
II(ref c, d, a, b, x[6], S43, 0xa3014314); /* 59 */
II(ref b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
II(ref a, b, c, d, x[4], S41, 0xf7537e82); /* 61 */
II(ref d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
II(ref c, d, a, b, x[2], S43, 0x2ad7d2bb); /* 63 */
II(ref b, c, d, a, x[9], S44, 0xeb86d391); /* 64 */
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
// Zeroize sensitive information.
for (int i = 0; i < x.Length; i++)
x[i] = 0;
}
/// <summary>
/// Encodes input (uint) into output (byte). Assumes len is
/// multiple of 4.
/// </summary>
/// <param name="output"></param>
/// <param name="outputOffset"></param>
/// <param name="input"></param>
/// <param name="inputOffset"></param>
/// <param name="count"></param>
private static void Encode(byte[] output, int outputOffset, uint[] input, int inputOffset, int count)
{
int i, j;
int end = outputOffset + count;
for (i = inputOffset, j = outputOffset; j < end; i++, j += 4)
{
output[j] = (byte)(input[i] & 0xff);
output[j + 1] = (byte)((input[i] >> 8) & 0xff);
output[j + 2] = (byte)((input[i] >> 16) & 0xff);
output[j + 3] = (byte)((input[i] >> 24) & 0xff);
}
}
/// <summary>
/// Decodes input (byte) into output (uint). Assumes len is
/// a multiple of 4.
/// </summary>
/// <param name="output"></param>
/// <param name="outputOffset"></param>
/// <param name="input"></param>
/// <param name="inputOffset"></param>
/// <param name="count"></param>
static private void Decode(uint[] output, int outputOffset, byte[] input, int inputOffset, int count)
{
int i, j;
int end = inputOffset + count;
for (i = outputOffset, j = inputOffset; j < end; i++, j += 4)
output[i] = ((uint)input[j]) | (((uint)input[j + 1]) << 8) | (((uint)input[j + 2]) << 16) | (((uint)input[j + 3]) << 24);
}
#endregion
#region expose the same interface as the regular MD5 object
protected byte[] HashValue;
protected int State;
public virtual bool CanReuseTransform
{
get
{
return true;
}
}
public virtual bool CanTransformMultipleBlocks
{
get
{
return true;
}
}
public virtual byte[] Hash
{
get
{
if (this.State != 0)
throw new InvalidOperationException();
return (byte[])HashValue.Clone();
}
}
public virtual int HashSize
{
get
{
return HashSizeValue;
}
}
protected int HashSizeValue = 128;
public virtual int InputBlockSize
{
get
{
return 1;
}
}
public virtual int OutputBlockSize
{
get
{
return 1;
}
}
public void Clear()
{
Dispose(true);
}
public byte[] ComputeHash(byte[] buffer)
{
return ComputeHash(buffer, 0, buffer.Length);
}
public byte[] ComputeHash(byte[] buffer, int offset, int count)
{
Initialize();
HashCore(buffer, offset, count);
HashValue = HashFinal();
return (byte[])HashValue.Clone();
}
public byte[] ComputeHash(Stream inputStream)
{
Initialize();
int count;
byte[] buffer = new byte[4096];
while (0 < (count = inputStream.Read(buffer, 0, 4096)))
{
HashCore(buffer, 0, count);
}
HashValue = HashFinal();
return (byte[])HashValue.Clone();
}
public int TransformBlock(
byte[] inputBuffer,
int inputOffset,
int inputCount,
byte[] outputBuffer,
int outputOffset
)
{
if (inputBuffer == null)
{
throw new ArgumentNullException("inputBuffer");
}
if (inputOffset < 0)
{
throw new ArgumentOutOfRangeException("inputOffset");
}
if ((inputCount < 0) || (inputCount > inputBuffer.Length))
{
throw new ArgumentException("inputCount");
}
if ((inputBuffer.Length - inputCount) < inputOffset)
{
throw new ArgumentOutOfRangeException("inputOffset");
}
if (this.State == 0)
{
Initialize();
this.State = 1;
}
HashCore(inputBuffer, inputOffset, inputCount);
if ((inputBuffer != outputBuffer) || (inputOffset != outputOffset))
{
Buffer.BlockCopy(inputBuffer, inputOffset, outputBuffer, outputOffset, inputCount);
}
return inputCount;
}
public byte[] TransformFinalBlock(
byte[] inputBuffer,
int inputOffset,
int inputCount
)
{
if (inputBuffer == null)
{
throw new ArgumentNullException("inputBuffer");
}
if (inputOffset < 0)
{
throw new ArgumentOutOfRangeException("inputOffset");
}
if ((inputCount < 0) || (inputCount > inputBuffer.Length))
{
throw new ArgumentException("inputCount");
}
if ((inputBuffer.Length - inputCount) < inputOffset)
{
throw new ArgumentOutOfRangeException("inputOffset");
}
if (this.State == 0)
{
Initialize();
}
HashCore(inputBuffer, inputOffset, inputCount);
HashValue = HashFinal();
byte[] buffer = new byte[inputCount];
Buffer.BlockCopy(inputBuffer, inputOffset, buffer, 0, inputCount);
this.State = 0;
return buffer;
}
#endregion
protected virtual void Dispose(bool disposing)
{
if (!disposing)
Initialize();
}
public void Dispose()
{
Dispose(true);
}
}
}
| |
/*
*
* (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.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text.RegularExpressions;
using System.Threading;
using ASC.Common.Logging;
using ASC.Core;
using ASC.Core.Tenants;
using ASC.Core.Users;
using ASC.Notify;
using ASC.Notify.Engine;
using ASC.Notify.Messages;
using ASC.Notify.Patterns;
using ASC.Web.Core;
using ASC.Web.Core.WhiteLabel;
using ASC.Web.Studio.Utility;
using MimeKit.Utils;
namespace ASC.Web.Studio.Core.Notify
{
public static class NotifyConfiguration
{
private static bool configured;
private static readonly object locker = new object();
private static readonly Regex urlReplacer = new Regex(@"(<a [^>]*href=(('(?<url>[^>']*)')|(""(?<url>[^>""]*)""))[^>]*>)|(<img [^>]*src=(('(?<url>(?![data:|cid:])[^>']*)')|(""(?<url>(?![data:|cid:])[^>""]*)""))[^/>]*/?>)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex textileLinkReplacer = new Regex(@"""(?<text>[\w\W]+?)"":""(?<link>[^""]+)""", RegexOptions.Singleline | RegexOptions.Compiled);
public static void Configure()
{
lock (locker)
{
if (!configured)
{
configured = true;
WorkContext.NotifyContext.NotifyClientRegistration += NotifyClientRegisterCallback;
WorkContext.NotifyContext.NotifyEngine.BeforeTransferRequest += BeforeTransferRequest;
}
}
}
public static void RegisterSendMethods()
{
StudioNotifyService.Instance.RegisterSendMethod();
}
private static void NotifyClientRegisterCallback(Context context, INotifyClient client)
{
#region url correction
var absoluteUrl = new SendInterceptorSkeleton(
"Web.UrlAbsoluter",
InterceptorPlace.MessageSend,
InterceptorLifetime.Global,
(r, p) =>
{
if (r != null && r.CurrentMessage != null && r.CurrentMessage.ContentType == Pattern.HTMLContentType)
{
var body = r.CurrentMessage.Body;
body = urlReplacer.Replace(body, m =>
{
var url = m.Groups["url"].Value;
var ind = m.Groups["url"].Index - m.Index;
return string.IsNullOrEmpty(url) && ind > 0 ?
m.Value.Insert(ind, CommonLinkUtility.GetFullAbsolutePath(string.Empty)) :
m.Value.Replace(url, CommonLinkUtility.GetFullAbsolutePath(url));
});
body = textileLinkReplacer.Replace(body, m =>
{
var url = m.Groups["link"].Value;
var ind = m.Groups["link"].Index - m.Index;
return string.IsNullOrEmpty(url) && ind > 0 ?
m.Value.Insert(ind, CommonLinkUtility.GetFullAbsolutePath(string.Empty)) :
m.Value.Replace(url, CommonLinkUtility.GetFullAbsolutePath(url));
});
r.CurrentMessage.Body = body;
}
return false;
});
client.AddInterceptor(absoluteUrl);
#endregion
#region security and culture
var securityAndCulture = new SendInterceptorSkeleton(
"ProductSecurityInterceptor",
InterceptorPlace.DirectSend,
InterceptorLifetime.Global,
(r, p) =>
{
try
{
// culture
var u = Constants.LostUser;
if (!(CoreContext.Configuration.Personal && r.NotifyAction.ID == Actions.PersonalConfirmation.ID))
{
if (32 <= r.Recipient.ID.Length)
{
var guid = default(Guid);
try
{
guid = new Guid(r.Recipient.ID);
}
catch (FormatException) { }
catch (OverflowException) { }
if (guid != default(Guid))
{
u = CoreContext.UserManager.GetUsers(guid);
}
}
if (Constants.LostUser.Equals(u))
{
u = CoreContext.UserManager.GetUserByEmail(r.Recipient.ID);
}
if (Constants.LostUser.Equals(u))
{
u = CoreContext.UserManager.GetUserByUserName(r.Recipient.ID);
}
if (!Constants.LostUser.Equals(u))
{
var culture = !string.IsNullOrEmpty(u.CultureName) ? u.GetCulture() : CoreContext.TenantManager.GetCurrentTenant().GetCulture();
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
// security
var tag = r.Arguments.Find(a => a.Tag == CommonTags.ModuleID);
var productId = tag != null ? (Guid)tag.Value : Guid.Empty;
if (productId == Guid.Empty)
{
tag = r.Arguments.Find(a => a.Tag == CommonTags.ProductID);
productId = tag != null ? (Guid)tag.Value : Guid.Empty;
}
if (productId == Guid.Empty)
{
productId = (Guid)(CallContext.GetData("asc.web.product_id") ?? Guid.Empty);
}
if (productId != Guid.Empty && productId != new Guid("f4d98afdd336433287783c6945c81ea0") /* ignore people product */)
{
return !WebItemSecurity.IsAvailableForUser(productId, u.ID);
}
}
}
var tagCulture = r.Arguments.FirstOrDefault(a => a.Tag == CommonTags.Culture);
if (tagCulture != null)
{
var culture = CultureInfo.GetCultureInfo((string)tagCulture.Value);
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
}
}
catch (Exception error)
{
LogManager.GetLogger("ASC").Error(error);
}
return false;
});
client.AddInterceptor(securityAndCulture);
#endregion
#region white label correction
var whiteLabel = new SendInterceptorSkeleton(
"WhiteLabelInterceptor",
InterceptorPlace.MessageSend,
InterceptorLifetime.Global,
(r, p) =>
{
try
{
var tags = r.Arguments;
var logoTextTag = tags.FirstOrDefault(a => a.Tag == CommonTags.LetterLogoText);
var logoText = logoTextTag != null ? (String)logoTextTag.Value : string.Empty;
if (!string.IsNullOrEmpty(logoText))
{
r.CurrentMessage.Body = r.CurrentMessage.Body
.Replace(string.Format("${{{0}}}", CommonTags.LetterLogoText), logoText);
}
}
catch (Exception error)
{
LogManager.GetLogger("ASC").Error(error);
}
return false;
});
client.AddInterceptor(whiteLabel);
#endregion
}
private static void BeforeTransferRequest(NotifyEngine sender, NotifyRequest request)
{
var aid = Guid.Empty;
var aname = string.Empty;
if (SecurityContext.IsAuthenticated)
{
aid = SecurityContext.CurrentAccount.ID;
if (CoreContext.UserManager.UserExists(aid))
{
aname = CoreContext.UserManager.GetUsers(aid).DisplayUserName(false)
.Replace(">", ">")
.Replace("<", "<");
}
}
IProduct product;
IModule module;
CommonLinkUtility.GetLocationByRequest(out product, out module);
if (product == null && CallContext.GetData("asc.web.product_id") != null)
{
product = WebItemManager.Instance[(Guid)CallContext.GetData("asc.web.product_id")] as IProduct;
}
var logoText = TenantWhiteLabelSettings.DefaultLogoText;
if ((TenantExtra.Enterprise || CoreContext.Configuration.CustomMode) && !MailWhiteLabelSettings.Instance.IsDefault)
{
logoText = TenantLogoManager.GetLogoText();
}
request.Arguments.Add(new TagValue(CommonTags.AuthorID, aid));
request.Arguments.Add(new TagValue(CommonTags.AuthorName, aname));
request.Arguments.Add(new TagValue(CommonTags.AuthorUrl, CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.GetUserProfile(aid))));
request.Arguments.Add(new TagValue(CommonTags.VirtualRootPath, CommonLinkUtility.GetFullAbsolutePath("~").TrimEnd('/')));
request.Arguments.Add(new TagValue(CommonTags.ProductID, product != null ? product.ID : Guid.Empty));
request.Arguments.Add(new TagValue(CommonTags.ModuleID, module != null ? module.ID : Guid.Empty));
request.Arguments.Add(new TagValue(CommonTags.ProductUrl, CommonLinkUtility.GetFullAbsolutePath(product != null ? product.StartURL : "~")));
request.Arguments.Add(new TagValue(CommonTags.DateTime, TenantUtil.DateTimeNow()));
request.Arguments.Add(new TagValue(CommonTags.RecipientID, Context.SYS_RECIPIENT_ID));
request.Arguments.Add(new TagValue(CommonTags.ProfileUrl, CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.GetMyStaff())));
request.Arguments.Add(new TagValue(CommonTags.RecipientSubscriptionConfigURL, CommonLinkUtility.GetMyStaff()));
request.Arguments.Add(new TagValue(CommonTags.HelpLink, CommonLinkUtility.GetHelpLink(false)));
request.Arguments.Add(new TagValue(CommonTags.LetterLogoText, logoText));
request.Arguments.Add(new TagValue(CommonTags.MailWhiteLabelSettings, MailWhiteLabelSettings.Instance));
request.Arguments.Add(new TagValue(CommonTags.SendFrom, CoreContext.TenantManager.GetCurrentTenant().Name));
request.Arguments.Add(new TagValue(CommonTags.ImagePath, StudioNotifyHelper.GetNotificationImageUrl("").TrimEnd('/')));
AddLetterLogo(request);
}
private static void AddLetterLogo(NotifyRequest request)
{
if (TenantExtra.Enterprise || CoreContext.Configuration.CustomMode)
{
try
{
var logoData = TenantLogoManager.GetMailLogoDataFromCache();
if (logoData == null)
{
var logoStream = TenantLogoManager.GetWhitelabelMailLogo();
logoData = ReadStreamToByteArray(logoStream) ?? GetDefaultMailLogo();
if (logoData != null)
TenantLogoManager.InsertMailLogoDataToCache(logoData);
}
if (logoData != null)
{
var attachment = new NotifyMessageAttachment
{
FileName = "logo.png",
Content = logoData,
ContentId = MimeUtils.GenerateMessageId()
};
request.Arguments.Add(new TagValue(CommonTags.LetterLogo, "cid:" + attachment.ContentId));
request.Arguments.Add(new TagValue(CommonTags.EmbeddedAttachments, new[] { attachment }));
return;
}
}
catch (Exception error)
{
LogManager.GetLogger("ASC").Error(error);
}
}
var logoUrl = CommonLinkUtility.GetFullAbsolutePath(TenantLogoManager.GetLogoDark(true));
request.Arguments.Add(new TagValue(CommonTags.LetterLogo, logoUrl));
}
private static byte[] ReadStreamToByteArray(Stream inputStream)
{
if (inputStream == null) return null;
using (inputStream)
{
using (var memoryStream = new MemoryStream())
{
inputStream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
}
public static byte[] GetDefaultMailLogo()
{
var filePath = Path.Combine(Environment.CurrentDirectory, "skins", "default", "images", "logo", "dark_general.png");
return File.Exists(filePath) ? File.ReadAllBytes(filePath) : null;
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.POIFS.Crypt
{
using System;
using System.Collections.Generic;
using System.IO;
using NPOI.OpenXml4Net.OPC;
using NPOI.POIFS.Crypt;
using NPOI.POIFS.Crypt.Agile;
using NPOI.POIFS.FileSystem;
using NPOI.Util;
using NPOI.XWPF.UserModel;
using NUnit.Framework;
using TestCases;
[TestFixture]
public class TestEncryptor
{
[Test]
[Ignore("Implement this test in future, maybe based on poi 4.2")]
public void BinaryRC4Encryption()
{
// please contribute a real sample file, which is binary rc4 encrypted
// ... at least the output can be opened in Excel Viewer
String password = "pass";
Stream is1 = POIDataSamples.GetSpreadSheetInstance().OpenResourceAsStream("SimpleMultiCell.xlsx");
MemoryStream payloadExpected = new MemoryStream();
IOUtils.Copy(is1, payloadExpected);
is1.Close();
POIFSFileSystem fs = new POIFSFileSystem();
EncryptionInfo ei = new EncryptionInfo(EncryptionMode.BinaryRC4);
Encryptor enc = ei.Encryptor;
enc.ConfirmPassword(password);
Stream os = enc.GetDataStream(fs.Root);
payloadExpected.WriteTo(os);
os.Close();
MemoryStream bos = new MemoryStream();
fs.WriteFileSystem(bos);
fs = new POIFSFileSystem(new MemoryStream(bos.ToArray()));
ei = new EncryptionInfo(fs);
Decryptor dec = ei.Decryptor;
bool b = dec.VerifyPassword(password);
Assert.IsTrue(b);
MemoryStream payloadActual = new MemoryStream();
is1 = dec.GetDataStream(fs.Root);
IOUtils.Copy(is1, payloadActual);
is1.Close();
Assert.IsTrue(Arrays.Equals(payloadExpected.ToArray(), payloadActual.ToArray()));
//assertArrayEquals(payloadExpected.ToArray(), payloadActual.ToArray());
}
[Test]
public void AgileEncryption()
{
int maxKeyLen = Cipher.GetMaxAllowedKeyLength("AES");
Assume.That(maxKeyLen == 2147483647, "Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256");
FileStream file = POIDataSamples.GetDocumentInstance().GetFile("bug53475-password-is-pass.docx");
String pass = "pass";
NPOIFSFileSystem nfs = new NPOIFSFileSystem(file);
// Check the encryption details
EncryptionInfo infoExpected = new EncryptionInfo(nfs);
Decryptor decExpected = Decryptor.GetInstance(infoExpected);
bool passed = decExpected.VerifyPassword(pass);
Assert.IsTrue(passed, "Unable to Process: document is encrypted");
// extract the payload
Stream is1 = decExpected.GetDataStream(nfs);
byte[] payloadExpected = IOUtils.ToByteArray(is1);
is1.Close();
long decPackLenExpected = decExpected.GetLength();
Assert.AreEqual(decPackLenExpected, payloadExpected.Length);
is1 = nfs.Root.CreateDocumentInputStream(Decryptor.DEFAULT_POIFS_ENTRY);
///is1 = new BoundedInputStream(is1, is1.Available() - 16); // ignore pAdding block
///throw new NotImplementedException(BoundedInputStream);
byte[] encPackExpected = IOUtils.ToByteArray(is1);
is1.Close();
// listDir(nfs.Root, "orig", "");
nfs.Close();
// check that same verifier/salt lead to same hashes
byte[] verifierSaltExpected = infoExpected.Verifier.Salt;
byte[] verifierExpected = decExpected.GetVerifier();
byte[] keySalt = infoExpected.Header.KeySalt;
byte[] keySpec = decExpected.GetSecretKey().GetEncoded();
byte[] integritySalt = decExpected.GetIntegrityHmacKey();
// the hmacs of the file always differ, as we use PKCS5-pAdding to pad the bytes
// whereas office just uses random bytes
// byte integrityHash[] = d.IntegrityHmacValue;
POIFSFileSystem fs = new POIFSFileSystem();
EncryptionInfo infoActual = new EncryptionInfo(
EncryptionMode.Agile
, infoExpected.Verifier.CipherAlgorithm
, infoExpected.Verifier.HashAlgorithm
, infoExpected.Header.KeySize
, infoExpected.Header.BlockSize
, infoExpected.Verifier.ChainingMode
);
Encryptor e = Encryptor.GetInstance(infoActual);
e.ConfirmPassword(pass, keySpec, keySalt, verifierExpected, verifierSaltExpected, integritySalt);
Stream os = e.GetDataStream(fs);
IOUtils.Copy(new MemoryStream(payloadExpected), os);
os.Close();
MemoryStream bos = new MemoryStream();
fs.WriteFileSystem(bos);
nfs = new NPOIFSFileSystem(new MemoryStream(bos.ToArray()));
infoActual = new EncryptionInfo(nfs.Root);
Decryptor decActual = Decryptor.GetInstance(infoActual);
passed = decActual.VerifyPassword(pass);
Assert.IsTrue(passed, "Unable to Process: document is encrypted");
// extract the payload
is1 = decActual.GetDataStream(nfs);
byte[] payloadActual = IOUtils.ToByteArray(is1);
is1.Close();
long decPackLenActual = decActual.GetLength();
is1 = nfs.Root.CreateDocumentInputStream(Decryptor.DEFAULT_POIFS_ENTRY);
///is1 = new BoundedInputStream(is1, is1.Available() - 16); // ignore pAdding block
///throw new NotImplementedException(BoundedInputStream);
byte[] encPackActual = IOUtils.ToByteArray(is1);
is1.Close();
// listDir(nfs.Root, "copy", "");
nfs.Close();
AgileEncryptionHeader aehExpected = (AgileEncryptionHeader)infoExpected.Header;
AgileEncryptionHeader aehActual = (AgileEncryptionHeader)infoActual.Header;
CollectionAssert.AreEqual(aehExpected.GetEncryptedHmacKey(), aehActual.GetEncryptedHmacKey());
Assert.AreEqual(decPackLenExpected, decPackLenActual);
CollectionAssert.AreEqual(payloadExpected, payloadActual);
CollectionAssert.AreEqual(encPackExpected, encPackActual);
}
[Test]
[Ignore("Implement this test in future, maybe based on poi 4.2")]
public void StandardEncryption()
{
FileStream file = POIDataSamples.GetDocumentInstance().GetFile("bug53475-password-is-solrcell.docx");
String pass = "solrcell";
NPOIFSFileSystem nfs = new NPOIFSFileSystem(file);
// Check the encryption details
EncryptionInfo infoExpected = new EncryptionInfo(nfs);
Decryptor d = Decryptor.GetInstance(infoExpected);
bool passed = d.VerifyPassword(pass);
Assert.IsTrue(passed, "Unable to Process: document is encrypted");
// extract the payload
MemoryStream bos = new MemoryStream();
Stream is1 = d.GetDataStream(nfs);
IOUtils.Copy(is1, bos);
is1.Close();
nfs.Close();
byte[] payloadExpected = bos.ToArray();
// check that same verifier/salt lead to same hashes
byte[] verifierSaltExpected = infoExpected.Verifier.Salt;
byte[] verifierExpected = d.GetVerifier();
byte[] keySpec = d.GetSecretKey().GetEncoded();
byte[] keySalt = infoExpected.Header.KeySalt;
EncryptionInfo infoActual = new EncryptionInfo(
EncryptionMode.Standard
, infoExpected.Verifier.CipherAlgorithm
, infoExpected.Verifier.HashAlgorithm
, infoExpected.Header.KeySize
, infoExpected.Header.BlockSize
, infoExpected.Verifier.ChainingMode
);
Encryptor e = Encryptor.GetInstance(infoActual);
e.ConfirmPassword(pass, keySpec, keySalt, verifierExpected, verifierSaltExpected, null);
CollectionAssert.AreEqual(infoExpected.Verifier.EncryptedVerifier, infoActual.Verifier.EncryptedVerifier);
CollectionAssert.AreEqual(infoExpected.Verifier.EncryptedVerifierHash, infoActual.Verifier.EncryptedVerifierHash);
// now we use a newly generated salt/verifier and check
// if the file content is still the same
infoActual = new EncryptionInfo(
EncryptionMode.Standard
, infoExpected.Verifier.CipherAlgorithm
, infoExpected.Verifier.HashAlgorithm
, infoExpected.Header.KeySize
, infoExpected.Header.BlockSize
, infoExpected.Verifier.ChainingMode
);
e = Encryptor.GetInstance(infoActual);
e.ConfirmPassword(pass);
POIFSFileSystem fs = new POIFSFileSystem();
Stream os = e.GetDataStream(fs);
IOUtils.Copy(new MemoryStream(payloadExpected), os);
os.Close();
bos.Seek(0, SeekOrigin.Begin); //bos.Reset();
fs.WriteFileSystem(bos);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.ToArray());
// FileOutputStream fos = new FileOutputStream("encrypted.docx");
// IOUtils.Copy(bis, fos);
// fos.Close();
// bis.Reset();
nfs = new NPOIFSFileSystem(bis);
infoExpected = new EncryptionInfo(nfs);
d = Decryptor.GetInstance(infoExpected);
passed = d.VerifyPassword(pass);
Assert.IsTrue(passed, "Unable to Process: document is encrypted");
bos.Seek(0, SeekOrigin.Begin); //bos.Reset();
is1 = d.GetDataStream(nfs);
IOUtils.Copy(is1, bos);
is1.Close();
nfs.Close();
byte[] payloadActual = bos.ToArray();
CollectionAssert.AreEqual(payloadExpected, payloadActual);
//assertArrayEquals(payloadExpected, payloadActual);
}
/**
* Ensure we can encrypt a package that is missing the Core
* Properties, eg one from dodgy versions of Jasper Reports
* See https://github.com/nestoru/xlsxenc/ and
* http://stackoverflow.com/questions/28593223
*/
[Test]
[Ignore("Implement this test in future, maybe based on poi 4.2")]
public void EncryptPackageWithoutCoreProperties()
{
// Open our file without core properties
FileStream inp = POIDataSamples.GetOpenXML4JInstance().GetFile("OPCCompliance_NoCoreProperties.xlsx");
OPCPackage pkg = OPCPackage.Open(inp.Name);
// It doesn't have any core properties yet
Assert.AreEqual(0, pkg.GetPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).Count);
Assert.IsNotNull(pkg.GetPackageProperties());
Assert.IsNotNull(pkg.GetPackageProperties().GetLanguageProperty());
//Assert.IsNull(pkg.GetPackageProperties().GetLanguageProperty().GetValue());
// Encrypt it
EncryptionInfo info = new EncryptionInfo(EncryptionMode.Agile);
NPOIFSFileSystem fs = new NPOIFSFileSystem();
Encryptor enc = info.Encryptor;
enc.ConfirmPassword("password");
OutputStream os = enc.GetDataStream(fs);
pkg.Save(os);
pkg.Revert();
// Save the resulting OLE2 document, and re-open it
MemoryStream baos = new MemoryStream();
fs.WriteFileSystem(baos);
MemoryStream bais = new MemoryStream(baos.ToArray());
NPOIFSFileSystem inpFS = new NPOIFSFileSystem(bais);
// Check we can decrypt it
info = new EncryptionInfo(inpFS);
Decryptor d = Decryptor.GetInstance(info);
Assert.AreEqual(true, d.VerifyPassword("password"));
OPCPackage inpPkg = OPCPackage.Open(d.GetDataStream(inpFS));
// Check it now has empty core properties
Assert.AreEqual(1, inpPkg.GetPartsByContentType(ContentTypes.CORE_PROPERTIES_PART).Count);
Assert.IsNotNull(inpPkg.GetPackageProperties());
Assert.IsNotNull(inpPkg.GetPackageProperties().GetLanguageProperty());
//Assert.IsNull(inpPkg.PackageProperties.LanguageProperty.Value);
}
[Test]
[Ignore("poi")]
public void InPlaceReWrite()
{
FileInfo f = TempFile.CreateTempFile("protected_agile", ".docx");
// File f = new File("protected_agile.docx");
FileStream fos = f.Create();
Stream fis = POIDataSamples.GetPOIFSInstance().OpenResourceAsStream("protected_agile.docx");
IOUtils.Copy(fis, fos);
fis.Close();
fos.Close();
NPOIFSFileSystem fs = new NPOIFSFileSystem(f, false);
// decrypt the protected file - in this case it was encrypted with the default password
EncryptionInfo encInfo = new EncryptionInfo(fs);
Decryptor d = encInfo.Decryptor;
bool b = d.VerifyPassword(Decryptor.DEFAULT_PASSWORD);
Assert.IsTrue(b);
// do some strange things with it ;)
XWPFDocument docx = new XWPFDocument(d.GetDataStream(fs));
docx.GetParagraphArray(0).InsertNewRun(0).SetText("POI was here! All your base are belong to us!");
docx.GetParagraphArray(0).InsertNewRun(1).AddBreak();
// and encrypt it again
Encryptor e = encInfo.Encryptor;
e.ConfirmPassword("AYBABTU");
docx.Write(e.GetDataStream(fs));
fs.Close();
}
private void ListEntry(DocumentNode de, string ext, string path)
{
path += "\\" + de.Name.Replace("[\\p{Cntrl}]", "_");
Console.WriteLine(ext + ": " + path + " (" + de.Size + " bytes)");
string name = de.Name.Replace("[\\p{Cntrl}]", "_");
Stream is1 = ((DirectoryNode)de.Parent).CreateDocumentInputStream(de);
FileStream fos = new FileStream("solr." + name + "." + ext, FileMode.OpenOrCreate, FileAccess.ReadWrite);
IOUtils.Copy(is1, fos);
fos.Close();
is1.Close();
}
private void ListDir(DirectoryNode dn, string ext, string path)
{
path += "\\" + dn.Name.Replace('\u0006', '_');
Console.WriteLine(ext + ": " + path + " (" + dn.StorageClsid + ")");
IEnumerator<Entry> iter = dn.Entries;
while (iter.MoveNext())
{
Entry ent = iter.Current;
if (ent is DirectoryNode)
{
ListDir((DirectoryNode)ent, ext, path);
}
else
{
ListEntry((DocumentNode)ent, ext, path);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Windows.Forms;
using NetGore;
namespace DemoGame.Editor.UITypeEditors
{
public partial class CharacterTemplateInventoryItemListForm : Form
{
readonly List<CharacterTemplateInventoryItem> _list;
ItemTemplateID? _selectedItem;
/// <summary>
/// Initializes a new instance of the <see cref="CharacterTemplateAndAmountListForm"/> class.
/// </summary>
/// <param name="list">The list of <see cref="CharacterTemplateID"/>s and amounts.</param>
/// <exception cref="ArgumentNullException"><paramref name="list"/> is null.</exception>
[SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists")]
public CharacterTemplateInventoryItemListForm(List<CharacterTemplateInventoryItem> list)
{
if (DesignMode)
return;
if (list == null)
throw new ArgumentNullException("list");
_list = list;
RequireDistinct = true;
InitializeComponent();
lstItems.Items.AddRange(list.Cast<object>().ToArray());
}
/// <summary>
/// Gets or sets if the <see cref="CharacterTemplateID"/>s must be distinct. Default value is true.
/// </summary>
public bool RequireDistinct { get; set; }
/// <summary>
/// Raises the <see cref="E:System.Windows.Forms.Form.Closing"/> event.
/// </summary>
/// <param name="e">A <see cref="T:System.ComponentModel.CancelEventArgs"/> that contains the event data.</param>
protected override void OnClosing(CancelEventArgs e)
{
if (DesignMode)
return;
_list.Clear();
_list.AddRange(lstItems.Items.OfType<CharacterTemplateInventoryItem>());
base.OnClosing(e);
}
/// <summary>
/// Handles the Click event of the btnAdd control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
void btnAdd_Click(object sender, EventArgs e)
{
// Validate
if (!_selectedItem.HasValue)
{
MessageBox.Show("You must select an item to add first.");
return;
}
if (RequireDistinct)
{
if (lstItems.Items.Cast<CharacterTemplateInventoryItem>().Any(x => _selectedItem.HasValue && x.ID == _selectedItem.Value))
{
MessageBox.Show("That item is already in the list.");
_selectedItem = null;
return;
}
}
// Add
var newItem = new CharacterTemplateInventoryItem(_selectedItem.Value, ItemChance.FromPercent(1f), 1, 1);
lstItems.Items.Add(newItem);
if (RequireDistinct)
{
_selectedItem = null;
txtItem.Text = string.Empty;
}
// Select the new item
lstItems.SelectedItem = newItem;
}
/// <summary>
/// Handles the Click event of the btnBrowse control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
void btnBrowse_Click(object sender, EventArgs e)
{
using (var f = new ItemTemplateUITypeEditorForm(null))
{
// If we require distinct, skip items we already have in the list
if (RequireDistinct)
{
var listItems = lstItems.Items.OfType<CharacterTemplateInventoryItem>().ToImmutable();
f.SkipItems = (x => listItems.Any(y => y.ID == x.ID));
}
if (f.ShowDialog(this) != DialogResult.OK)
return;
var item = f.SelectedItem;
_selectedItem = item.ID;
txtItem.Text = item.ID + " [" + item.Name + "]";
}
}
/// <summary>
/// Handles the KeyDown event of the lstItems control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.Forms.KeyEventArgs"/> instance containing the event data.</param>
void lstItems_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Return)
txtChance_Leave(sender, null);
}
/// <summary>
/// Handles the SelectedIndexChanged event of the lstItems control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
void lstItems_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstItems.SelectedItem == null)
return;
// Get the selected item
if (!(lstItems.SelectedItem is CharacterTemplateInventoryItem))
{
Debug.Fail("Was expecting type " + typeof(CharacterTemplateInventoryItem));
return;
}
var sel = (CharacterTemplateInventoryItem)lstItems.SelectedItem;
txtChance.Text = Math.Round(sel.Chance.Percentage * 100f, 4).ToString();
txtMin.Text = sel.Min.ToString();
txtMax.Text = sel.Max.ToString();
}
/// <summary>
/// Handles the Leave event of the txtAmount control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
void txtChance_Leave(object sender, EventArgs e)
{
if (lstItems.SelectedItem == null)
return;
// Get the selected item
if (!(lstItems.SelectedItem is CharacterTemplateInventoryItem))
{
Debug.Fail("Was expecting type " + typeof(CharacterTemplateInventoryItem));
return;
}
var sel = (CharacterTemplateInventoryItem)lstItems.SelectedItem;
// Parse the new amount
float chancePct;
if (!float.TryParse(txtChance.Text, out chancePct))
return;
ItemChance newItemChance = ItemChance.FromPercent(chancePct / 100f);
// Check that the amount changed
if (sel.Chance == newItemChance)
return;
// Set the new amount
sel.Chance = newItemChance;
// Force the text to refresh
lstItems.Items[lstItems.SelectedIndex] = sel;
}
/// <summary>
/// Handles the Leave event of the txtMax control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
void txtMax_Leave(object sender, EventArgs e)
{
if (lstItems.SelectedItem == null)
return;
// Get the selected item
if (!(lstItems.SelectedItem is CharacterTemplateInventoryItem))
{
Debug.Fail("Was expecting type " + typeof(CharacterTemplateInventoryItem));
return;
}
var sel = (CharacterTemplateInventoryItem)lstItems.SelectedItem;
// Parse the new amount
ushort v;
if (!ushort.TryParse(txtMax.Text, out v))
return;
// Check that the amount changed
if (sel.Chance == v)
return;
// Set the new amount
sel.Max = v;
// Force the text to refresh
lstItems.Items[lstItems.SelectedIndex] = sel;
}
/// <summary>
/// Handles the Leave event of the txtMin control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
void txtMin_Leave(object sender, EventArgs e)
{
if (lstItems.SelectedItem == null)
return;
// Get the selected item
if (!(lstItems.SelectedItem is CharacterTemplateInventoryItem))
{
Debug.Fail("Was expecting type " + typeof(CharacterTemplateInventoryItem));
return;
}
var sel = (CharacterTemplateInventoryItem)lstItems.SelectedItem;
// Parse the new amount
ushort v;
if (!ushort.TryParse(txtMin.Text, out v))
return;
// Check that the amount changed
if (sel.Chance == v)
return;
// Set the new amount
sel.Min = v;
// Force the text to refresh
lstItems.Items[lstItems.SelectedIndex] = sel;
}
}
}
| |
// 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.
namespace System.Xml.Schema
{
using System;
using System.Threading;
using System.Collections;
using System.Xml.Schema;
using System.Runtime.Versioning;
/// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection"]/*' />
/// <devdoc>
/// <para>The XmlSchemaCollection contains a set of namespace URI's.
/// Each namespace also have an associated private data cache
/// corresponding to the XML-Data Schema or W3C XML Schema.
/// The XmlSchemaCollection will able to load XSD and XDR schemas,
/// and compile them into an internal "cooked schema representation".
/// The Validate method then uses this internal representation for
/// efficient runtime validation of any given subtree.</para>
/// </devdoc>
[Obsolete("Use System.Xml.Schema.XmlSchemaSet for schema compilation and validation. http://go.microsoft.com/fwlink/?linkid=14202")]
public sealed class XmlSchemaCollection : ICollection
{
private Hashtable _collection;
private XmlNameTable _nameTable;
private SchemaNames _schemaNames;
private object _wLock;
private bool _isThreadSafe = true;
private ValidationEventHandler _validationEventHandler = null;
private XmlResolver _xmlResolver = null;
/// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.XmlSchemaCollection"]/*' />
/// <devdoc>
/// <para>Construct a new empty schema collection.</para>
/// </devdoc>
public XmlSchemaCollection() : this(new NameTable())
{
}
/// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.XmlSchemaCollection1"]/*' />
/// <devdoc>
/// <para>Construct a new empty schema collection with associated XmlNameTable.
/// The XmlNameTable is used when loading schemas</para>
/// </devdoc>
public XmlSchemaCollection(XmlNameTable nametable)
{
if (nametable == null)
{
throw new ArgumentNullException(nameof(nametable));
}
_nameTable = nametable;
_collection = Hashtable.Synchronized(new Hashtable());
_xmlResolver = System.Xml.XmlConfiguration.XmlReaderSection.CreateDefaultResolver();
_isThreadSafe = true;
if (_isThreadSafe)
{
_wLock = new object();
}
}
/// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.Count"]/*' />
/// <devdoc>
/// <para>Returns the number of namespaces defined in this collection
/// (whether or not there is an actual schema associated with those namespaces or not).</para>
/// </devdoc>
public int Count
{
get { return _collection.Count; }
}
/// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.NameTable"]/*' />
/// <devdoc>
/// <para>The default XmlNameTable used by the XmlSchemaCollection when loading new schemas.</para>
/// </devdoc>
public XmlNameTable NameTable
{
get { return _nameTable; }
}
/// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.ValidationEventHandler"]/*' />
public event ValidationEventHandler ValidationEventHandler
{
add { _validationEventHandler += value; }
remove { _validationEventHandler -= value; }
}
internal XmlResolver XmlResolver
{
set
{
_xmlResolver = value;
}
}
/// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.Add"]/*' />
/// <devdoc>
/// <para>Add the schema located by the given URL into the schema collection.
/// If the given schema references other namespaces, the schemas for those other
/// namespaces are NOT automatically loaded.</para>
/// </devdoc>
public XmlSchema Add(string ns, string uri)
{
if (uri == null || uri.Length == 0)
throw new ArgumentNullException(nameof(uri));
XmlTextReader reader = new XmlTextReader(uri, _nameTable);
reader.XmlResolver = _xmlResolver;
XmlSchema schema = null;
try
{
schema = Add(ns, reader, _xmlResolver);
while (reader.Read()) ;// wellformness check
}
finally
{
reader.Close();
}
return schema;
}
/// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.Add4"]/*' />
public XmlSchema Add(String ns, XmlReader reader)
{
return Add(ns, reader, _xmlResolver);
}
/// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.Add1"]/*' />
/// <devdoc>
/// <para>Add the given schema into the schema collection.
/// If the given schema references other namespaces, the schemas for those
/// other namespaces are NOT automatically loaded.</para>
/// </devdoc>
public XmlSchema Add(String ns, XmlReader reader, XmlResolver resolver)
{
if (reader == null)
throw new ArgumentNullException(nameof(reader));
XmlNameTable readerNameTable = reader.NameTable;
SchemaInfo schemaInfo = new SchemaInfo();
Parser parser = new Parser(SchemaType.None, readerNameTable, GetSchemaNames(readerNameTable), _validationEventHandler);
parser.XmlResolver = resolver;
SchemaType schemaType;
try
{
schemaType = parser.Parse(reader, ns);
}
catch (XmlSchemaException e)
{
SendValidationEvent(e);
return null;
}
if (schemaType == SchemaType.XSD)
{
schemaInfo.SchemaType = SchemaType.XSD;
return Add(ns, schemaInfo, parser.XmlSchema, true, resolver);
}
else
{
SchemaInfo xdrSchema = parser.XdrSchema;
return Add(ns, parser.XdrSchema, null, true, resolver);
}
}
/// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.Add2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSchema Add(XmlSchema schema)
{
return Add(schema, _xmlResolver);
}
/// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.Add5"]/*' />
public XmlSchema Add(XmlSchema schema, XmlResolver resolver)
{
if (schema == null)
throw new ArgumentNullException(nameof(schema));
SchemaInfo schemaInfo = new SchemaInfo();
schemaInfo.SchemaType = SchemaType.XSD;
return Add(schema.TargetNamespace, schemaInfo, schema, true, resolver);
}
/// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.Add3"]/*' />
/// <devdoc>
/// <para>Adds all the namespaces defined in the given collection
/// (including their associated schemas) to this collection.</para>
/// </devdoc>
public void Add(XmlSchemaCollection schema)
{
if (schema == null)
throw new ArgumentNullException(nameof(schema));
if (this == schema)
return;
IDictionaryEnumerator enumerator = schema._collection.GetEnumerator();
while (enumerator.MoveNext())
{
XmlSchemaCollectionNode node = (XmlSchemaCollectionNode)enumerator.Value;
Add(node.NamespaceURI, node);
}
}
/// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.this"]/*' />
/// <devdoc>
/// <para>Looks up the schema by it's associated namespace URI</para>
/// </devdoc>
public XmlSchema this[string ns]
{
get
{
XmlSchemaCollectionNode node = (XmlSchemaCollectionNode)_collection[(ns != null) ? ns : string.Empty];
return (node != null) ? node.Schema : null;
}
}
/// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.Contains"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public bool Contains(XmlSchema schema)
{
if (schema == null)
{
throw new ArgumentNullException(nameof(schema));
}
return this[schema.TargetNamespace] != null;
}
/// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.Contains1"]/*' />
public bool Contains(string ns)
{
return _collection[(ns != null) ? ns : string.Empty] != null;
}
/// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.IEnumerable.GetEnumerator"]/*' />
/// <internalonly/>
/// <devdoc>
/// Get a IEnumerator of the XmlSchemaCollection.
/// </devdoc>
IEnumerator IEnumerable.GetEnumerator()
{
return new XmlSchemaCollectionEnumerator(_collection);
}
/// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.GetEnumerator"]/*' />
public XmlSchemaCollectionEnumerator GetEnumerator()
{
return new XmlSchemaCollectionEnumerator(_collection);
}
/// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.ICollection.CopyTo"]/*' />
/// <internalonly/>
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index));
for (XmlSchemaCollectionEnumerator e = this.GetEnumerator(); e.MoveNext();)
{
if (index == array.Length)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
array.SetValue(e.Current, index++);
}
}
/// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.CopyTo"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public void CopyTo(XmlSchema[] array, int index)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index));
for (XmlSchemaCollectionEnumerator e = this.GetEnumerator(); e.MoveNext();)
{
XmlSchema schema = e.Current;
if (schema != null)
{
if (index == array.Length)
{
throw new ArgumentOutOfRangeException(nameof(index));
}
array[index++] = e.Current;
}
}
}
/// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.ICollection.IsSynchronized"]/*' />
/// <internalonly/>
bool ICollection.IsSynchronized
{
get { return true; }
}
/// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.ICollection.SyncRoot"]/*' />
/// <internalonly/>
object ICollection.SyncRoot
{
get { return this; }
}
/// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollection.ICollection.Count"]/*' />
/// <internalonly/>
int ICollection.Count
{
get { return _collection.Count; }
}
internal SchemaInfo GetSchemaInfo(string ns)
{
XmlSchemaCollectionNode node = (XmlSchemaCollectionNode)_collection[(ns != null) ? ns : string.Empty];
return (node != null) ? node.SchemaInfo : null;
}
internal SchemaNames GetSchemaNames(XmlNameTable nt)
{
if (_nameTable != nt)
{
return new SchemaNames(nt);
}
else
{
if (_schemaNames == null)
{
_schemaNames = new SchemaNames(_nameTable);
}
return _schemaNames;
}
}
internal XmlSchema Add(string ns, SchemaInfo schemaInfo, XmlSchema schema, bool compile)
{
return Add(ns, schemaInfo, schema, compile, _xmlResolver);
}
private XmlSchema Add(string ns, SchemaInfo schemaInfo, XmlSchema schema, bool compile, XmlResolver resolver)
{
int errorCount = 0;
if (schema != null)
{
if (schema.ErrorCount == 0 && compile)
{
if (!schema.CompileSchema(this, resolver, schemaInfo, ns, _validationEventHandler, _nameTable, true))
{
errorCount = 1;
}
ns = schema.TargetNamespace == null ? string.Empty : schema.TargetNamespace;
}
errorCount += schema.ErrorCount;
}
else
{
errorCount += schemaInfo.ErrorCount;
//ns = ns == null? string.Empty : NameTable.Add(ns);
ns = NameTable.Add(ns); //Added without checking for ns == null, since XDR cannot have null namespace
}
if (errorCount == 0)
{
XmlSchemaCollectionNode node = new XmlSchemaCollectionNode();
node.NamespaceURI = ns;
node.SchemaInfo = schemaInfo;
node.Schema = schema;
Add(ns, node);
return schema;
}
return null;
}
private void AddNonThreadSafe(string ns, XmlSchemaCollectionNode node)
{
if (_collection[ns] != null)
_collection.Remove(ns);
_collection.Add(ns, node);
}
private void Add(string ns, XmlSchemaCollectionNode node)
{
if (_isThreadSafe)
{
lock (_wLock)
{
AddNonThreadSafe(ns, node);
}
}
else
{
AddNonThreadSafe(ns, node);
}
}
private void SendValidationEvent(XmlSchemaException e)
{
if (_validationEventHandler != null)
{
_validationEventHandler(this, new ValidationEventArgs(e));
}
else
{
throw e;
}
}
internal ValidationEventHandler EventHandler
{
get
{
return _validationEventHandler;
}
set
{
_validationEventHandler = value;
}
}
};
internal sealed class XmlSchemaCollectionNode
{
private String _namespaceUri;
private SchemaInfo _schemaInfo;
private XmlSchema _schema;
internal String NamespaceURI
{
get { return _namespaceUri; }
set { _namespaceUri = value; }
}
internal SchemaInfo SchemaInfo
{
get { return _schemaInfo; }
set { _schemaInfo = value; }
}
internal XmlSchema Schema
{
get { return _schema; }
set { _schema = value; }
}
}
/// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollectionEnumerator"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public sealed class XmlSchemaCollectionEnumerator : IEnumerator
{
private IDictionaryEnumerator _enumerator;
internal XmlSchemaCollectionEnumerator(Hashtable collection)
{
_enumerator = collection.GetEnumerator();
}
/// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollectionEnumerator.IEnumerator.Reset"]/*' />
/// <internalonly/>
void IEnumerator.Reset()
{
_enumerator.Reset();
}
/// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollectionEnumerator.IEnumerator.MoveNext"]/*' />
/// <internalonly/>
bool IEnumerator.MoveNext()
{
return _enumerator.MoveNext();
}
/// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollectionEnumerator.MoveNext"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public bool MoveNext()
{
return _enumerator.MoveNext();
}
/// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollectionEnumerator.IEnumerator.Current"]/*' />
/// <internalonly/>
object IEnumerator.Current
{
get { return this.Current; }
}
/// <include file='doc\XmlSchemaCollection.uex' path='docs/doc[@for="XmlSchemaCollectionEnumerator.Current"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public XmlSchema Current
{
get
{
XmlSchemaCollectionNode n = (XmlSchemaCollectionNode)_enumerator.Value;
if (n != null)
return n.Schema;
else
return null;
}
}
internal XmlSchemaCollectionNode CurrentNode
{
get
{
XmlSchemaCollectionNode n = (XmlSchemaCollectionNode)_enumerator.Value;
return n;
}
}
}
}
| |
// 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 Xunit;
using XunitPlatformID = Xunit.PlatformID;
namespace System.IO.Tests
{
public class File_Move : FileSystemTest
{
#region Utilities
public virtual void Move(string sourceFile, string destFile)
{
File.Move(sourceFile, destFile);
}
#endregion
#region UniversalTests
[Fact]
public void NullPath()
{
Assert.Throws<ArgumentNullException>(() => Move(null, "."));
Assert.Throws<ArgumentNullException>(() => Move(".", null));
}
[Fact]
public void EmptyPath()
{
Assert.Throws<ArgumentException>(() => Move(string.Empty, "."));
Assert.Throws<ArgumentException>(() => Move(".", string.Empty));
}
[Fact]
public virtual void NonExistentPath()
{
FileInfo testFile = new FileInfo(GetTestFilePath());
testFile.Create().Dispose();
Assert.Throws<FileNotFoundException>(() => Move(GetTestFilePath(), testFile.FullName));
Assert.Throws<DirectoryNotFoundException>(() => Move(testFile.FullName, Path.Combine(TestDirectory, GetTestFileName(), GetTestFileName())));
Assert.Throws<FileNotFoundException>(() => Move(Path.Combine(TestDirectory, GetTestFileName(), GetTestFileName()), testFile.FullName));
}
[Fact]
public void PathWithIllegalCharacters()
{
FileInfo testFile = new FileInfo(GetTestFilePath());
testFile.Create().Dispose();
Assert.All(IOInputs.GetPathsWithInvalidCharacters(), (invalid) =>
{
if (invalid.Contains(@"\\?\"))
Assert.Throws<IOException>(() => Move(testFile.FullName, invalid));
else
Assert.Throws<ArgumentException>(() => Move(testFile.FullName, invalid));
});
}
[Fact]
public void BasicMove()
{
FileInfo testFileSource = new FileInfo(GetTestFilePath());
testFileSource.Create().Dispose();
string testFileDest = GetTestFilePath();
Move(testFileSource.FullName, testFileDest);
Assert.True(File.Exists(testFileDest));
Assert.False(File.Exists(testFileSource.FullName));
}
[Fact]
public void MoveNonEmptyFile()
{
FileInfo testFileSource = new FileInfo(GetTestFilePath());
using (var stream = testFileSource.Create())
{
var writer = new StreamWriter(stream);
writer.Write("testing\nwrite\n");
writer.Flush();
}
string testFileDest = GetTestFilePath();
Move(testFileSource.FullName, testFileDest);
Assert.True(File.Exists(testFileDest));
Assert.False(File.Exists(testFileSource.FullName));
Assert.Equal("testing\nwrite\n", File.ReadAllText(testFileDest));
}
[Fact]
public void MoveOntoDirectory()
{
FileInfo testFile = new FileInfo(GetTestFilePath());
testFile.Create().Dispose();
Assert.Throws<IOException>(() => Move(testFile.FullName, TestDirectory));
}
[Fact]
public void MoveOntoExistingFile()
{
FileInfo testFileSource = new FileInfo(GetTestFilePath());
testFileSource.Create().Dispose();
FileInfo testFileDest = new FileInfo(GetTestFilePath());
testFileDest.Create().Dispose();
Assert.Throws<IOException>(() => Move(testFileSource.FullName, testFileDest.FullName));
Assert.True(File.Exists(testFileSource.FullName));
Assert.True(File.Exists(testFileDest.FullName));
}
[Fact]
public void MoveIntoParentDirectory()
{
string testDir = GetTestFilePath();
Directory.CreateDirectory(testDir);
FileInfo testFileSource = new FileInfo(Path.Combine(testDir, GetTestFileName()));
testFileSource.Create().Dispose();
FileInfo testFileDest = new FileInfo(Path.Combine(testDir, "..", GetTestFileName()));
Move(testFileSource.FullName, testFileDest.FullName);
Assert.True(File.Exists(testFileDest.FullName));
}
[Fact]
public void MultipleMoves()
{
FileInfo testFileSource = new FileInfo(GetTestFilePath());
testFileSource.Create().Dispose();
string testFileDest1 = GetTestFilePath();
string testFileDest2 = GetTestFilePath();
Move(testFileSource.FullName, testFileDest1);
Move(testFileDest1, testFileDest2);
Assert.True(File.Exists(testFileDest2));
Assert.False(File.Exists(testFileDest1));
Assert.False(File.Exists(testFileSource.FullName));
}
[Fact]
public void FileNameWithSignificantWhitespace()
{
string testFileSource = Path.Combine(TestDirectory, GetTestFileName());
string testFileDest = Path.Combine(TestDirectory, " e n d");
File.Create(testFileSource).Dispose();
Move(testFileSource, testFileDest);
Assert.True(File.Exists(testFileDest));
Assert.False(File.Exists(testFileSource));
}
[Fact]
[PlatformSpecific(XunitPlatformID.Windows)]
public void MaxPath_Windows()
{
// Create a destination path longer than the traditional Windows limit of 256 characters,
// but under the long path limitation (32K).
string testFileSource = Path.Combine(TestDirectory, GetTestFileName());
File.Create(testFileSource).Dispose();
Assert.True(File.Exists(testFileSource), "test file should exist");
Assert.All(IOInputs.GetPathsLongerThanMaxPath(GetTestFilePath()), (path) =>
{
string baseDestinationPath = Path.GetDirectoryName(path);
if (!Directory.Exists(baseDestinationPath))
{
Directory.CreateDirectory(baseDestinationPath);
}
Assert.True(Directory.Exists(baseDestinationPath), "base destination path should exist");
Move(testFileSource, path);
Assert.True(File.Exists(path), "moved test file should exist");
File.Delete(testFileSource);
Assert.False(File.Exists(testFileSource), "source test file should not exist");
Move(path, testFileSource);
Assert.True(File.Exists(testFileSource), "restored test file should exist");
});
}
[Fact]
[PlatformSpecific(XunitPlatformID.AnyUnix)]
public void LongPath()
{
//Create a destination path longer than the traditional Windows limit of 256 characters
string testFileSource = Path.Combine(TestDirectory, GetTestFileName());
File.Create(testFileSource).Dispose();
Assert.All(IOInputs.GetPathsLongerThanMaxLongPath(GetTestFilePath()), (path) =>
{
Assert.Throws<PathTooLongException>(() => Move(testFileSource, path));
File.Delete(testFileSource);
Assert.Throws<PathTooLongException>(() => Move(path, testFileSource));
});
}
#endregion
#region PlatformSpecific
[Fact]
[PlatformSpecific(XunitPlatformID.Windows)]
public void WindowsPathWithIllegalColons()
{
FileInfo testFile = new FileInfo(GetTestFilePath());
testFile.Create().Dispose();
Assert.All(IOInputs.GetPathsWithInvalidColons(), (invalid) =>
{
Assert.Throws<NotSupportedException>(() => Move(testFile.FullName, invalid));
});
}
[Fact]
[PlatformSpecific(XunitPlatformID.Windows)]
public void WindowsWildCharacterPath()
{
Assert.Throws<ArgumentException>(() => Move("*", GetTestFilePath()));
Assert.Throws<ArgumentException>(() => Move(GetTestFilePath(), "*"));
Assert.Throws<ArgumentException>(() => Move(GetTestFilePath(), "Test*t"));
Assert.Throws<ArgumentException>(() => Move(GetTestFilePath(), "*Test"));
}
[Fact]
[PlatformSpecific(XunitPlatformID.AnyUnix)]
public void UnixWildCharacterPath()
{
string testDir = GetTestFilePath();
string testFileSource = Path.Combine(testDir, "*");
string testFileShouldntMove = Path.Combine(testDir, "*t");
string testFileDest = Path.Combine(testDir, "*" + GetTestFileName());
Directory.CreateDirectory(testDir);
File.Create(testFileSource).Dispose();
File.Create(testFileShouldntMove).Dispose();
Move(testFileSource, testFileDest);
Assert.True(File.Exists(testFileDest));
Assert.False(File.Exists(testFileSource));
Assert.True(File.Exists(testFileShouldntMove));
Move(testFileDest, testFileSource);
Assert.False(File.Exists(testFileDest));
Assert.True(File.Exists(testFileSource));
Assert.True(File.Exists(testFileShouldntMove));
}
[Fact]
[PlatformSpecific(XunitPlatformID.Windows)]
public void WindowsWhitespacePath()
{
FileInfo testFile = new FileInfo(GetTestFilePath());
Assert.All(IOInputs.GetWhiteSpace(), (whitespace) =>
{
Assert.Throws<ArgumentException>(() => Move(testFile.FullName, whitespace));
});
}
[Fact]
[PlatformSpecific(XunitPlatformID.AnyUnix)]
public void UnixWhitespacePath()
{
FileInfo testFileSource = new FileInfo(GetTestFilePath());
testFileSource.Create().Dispose();
Assert.All(IOInputs.GetWhiteSpace(), (whitespace) =>
{
Move(testFileSource.FullName, Path.Combine(TestDirectory, whitespace));
Move(Path.Combine(TestDirectory, whitespace), testFileSource.FullName);
});
}
#endregion
}
}
| |
namespace Projections
{
partial class PolyPanel
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component 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.groupBox1 = new System.Windows.Forms.GroupBox();
this.m_setButton = new System.Windows.Forms.Button();
this.m_flatteningTextBox = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.m_equatorialRadiusTextBox = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.m_latitudeTextBox = new System.Windows.Forms.TextBox();
this.m_longitudeTextBox = new System.Windows.Forms.TextBox();
this.button1 = new System.Windows.Forms.Button();
this.label5 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.m_azimuthTextBox = new System.Windows.Forms.TextBox();
this.m_distanceTextBox = new System.Windows.Forms.TextBox();
this.m_edgeButton = new System.Windows.Forms.Button();
this.label7 = new System.Windows.Forms.Label();
this.label8 = new System.Windows.Forms.Label();
this.label9 = new System.Windows.Forms.Label();
this.label10 = new System.Windows.Forms.Label();
this.label11 = new System.Windows.Forms.Label();
this.m_numPointsTextBox = new System.Windows.Forms.TextBox();
this.m_currLatTextBox = new System.Windows.Forms.TextBox();
this.m_currLonTextBox = new System.Windows.Forms.TextBox();
this.m_lengthTextBox = new System.Windows.Forms.TextBox();
this.m_areaTextBox = new System.Windows.Forms.TextBox();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.m_polylineCheckBox = new System.Windows.Forms.CheckBox();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.m_polylineCheckBox);
this.groupBox1.Controls.Add(this.m_setButton);
this.groupBox1.Controls.Add(this.m_flatteningTextBox);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this.m_equatorialRadiusTextBox);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Location = new System.Drawing.Point(3, 3);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(146, 169);
this.groupBox1.TabIndex = 6;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Ellipsoid Parameters";
//
// m_setButton
//
this.m_setButton.Location = new System.Drawing.Point(30, 135);
this.m_setButton.Name = "m_setButton";
this.m_setButton.Size = new System.Drawing.Size(75, 23);
this.m_setButton.TabIndex = 4;
this.m_setButton.Text = "Set";
this.m_setButton.UseVisualStyleBackColor = true;
this.m_setButton.Click += new System.EventHandler(this.OnSet);
//
// m_flatteningTextBox
//
this.m_flatteningTextBox.Location = new System.Drawing.Point(12, 83);
this.m_flatteningTextBox.Name = "m_flatteningTextBox";
this.m_flatteningTextBox.Size = new System.Drawing.Size(125, 20);
this.m_flatteningTextBox.TabIndex = 3;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 25);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(109, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Equatorial Radius (meters)";
//
// m_equatorialRadiusTextBox
//
this.m_equatorialRadiusTextBox.Location = new System.Drawing.Point(12, 42);
this.m_equatorialRadiusTextBox.Name = "m_equatorialRadiusTextBox";
this.m_equatorialRadiusTextBox.Size = new System.Drawing.Size(125, 20);
this.m_equatorialRadiusTextBox.TabIndex = 2;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(12, 66);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(53, 13);
this.label2.TabIndex = 1;
this.label2.Text = "Flattening";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(154, 10);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(92, 13);
this.label3.TabIndex = 7;
this.label3.Text = "Latitude (degrees)";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(154, 36);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(101, 13);
this.label4.TabIndex = 8;
this.label4.Text = "Longitude (degrees)";
//
// m_latitudeTextBox
//
this.m_latitudeTextBox.Location = new System.Drawing.Point(263, 6);
this.m_latitudeTextBox.Name = "m_latitudeTextBox";
this.m_latitudeTextBox.Size = new System.Drawing.Size(127, 20);
this.m_latitudeTextBox.TabIndex = 9;
//
// m_longitudeTextBox
//
this.m_longitudeTextBox.Location = new System.Drawing.Point(263, 32);
this.m_longitudeTextBox.Name = "m_longitudeTextBox";
this.m_longitudeTextBox.Size = new System.Drawing.Size(127, 20);
this.m_longitudeTextBox.TabIndex = 10;
//
// button1
//
this.button1.Location = new System.Drawing.Point(289, 60);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 11;
this.button1.Text = "Add Point";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.OnAddPoint);
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(400, 8);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(91, 13);
this.label5.TabIndex = 12;
this.label5.Text = "Azimuth (degrees)";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(400, 34);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(89, 13);
this.label6.TabIndex = 13;
this.label6.Text = "Distance (meters)";
//
// m_azimuthTextBox
//
this.m_azimuthTextBox.Location = new System.Drawing.Point(495, 4);
this.m_azimuthTextBox.Name = "m_azimuthTextBox";
this.m_azimuthTextBox.Size = new System.Drawing.Size(127, 20);
this.m_azimuthTextBox.TabIndex = 14;
//
// m_distanceTextBox
//
this.m_distanceTextBox.Location = new System.Drawing.Point(495, 30);
this.m_distanceTextBox.Name = "m_distanceTextBox";
this.m_distanceTextBox.Size = new System.Drawing.Size(127, 20);
this.m_distanceTextBox.TabIndex = 15;
//
// m_edgeButton
//
this.m_edgeButton.Enabled = false;
this.m_edgeButton.Location = new System.Drawing.Point(515, 58);
this.m_edgeButton.Name = "m_edgeButton";
this.m_edgeButton.Size = new System.Drawing.Size(75, 23);
this.m_edgeButton.TabIndex = 16;
this.m_edgeButton.Text = "Add Edge";
this.m_edgeButton.UseVisualStyleBackColor = true;
this.m_edgeButton.Click += new System.EventHandler(this.OnAddEdge);
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(634, 8);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(87, 13);
this.label7.TabIndex = 17;
this.label7.Text = "Number of points";
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(634, 34);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(82, 13);
this.label8.TabIndex = 18;
this.label8.Text = "Current Latitude";
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(634, 61);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(91, 13);
this.label9.TabIndex = 19;
this.label9.Text = "Current Longitude";
//
// label10
//
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(634, 89);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(40, 13);
this.label10.TabIndex = 20;
this.label10.Text = "Length";
//
// label11
//
this.label11.AutoSize = true;
this.label11.Location = new System.Drawing.Point(634, 116);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(29, 13);
this.label11.TabIndex = 21;
this.label11.Text = "Area";
//
// m_numPointsTextBox
//
this.m_numPointsTextBox.Location = new System.Drawing.Point(729, 4);
this.m_numPointsTextBox.Name = "m_numPointsTextBox";
this.m_numPointsTextBox.ReadOnly = true;
this.m_numPointsTextBox.Size = new System.Drawing.Size(127, 20);
this.m_numPointsTextBox.TabIndex = 22;
this.m_numPointsTextBox.Text = "0";
//
// m_currLatTextBox
//
this.m_currLatTextBox.Location = new System.Drawing.Point(729, 30);
this.m_currLatTextBox.Name = "m_currLatTextBox";
this.m_currLatTextBox.ReadOnly = true;
this.m_currLatTextBox.Size = new System.Drawing.Size(127, 20);
this.m_currLatTextBox.TabIndex = 23;
//
// m_currLonTextBox
//
this.m_currLonTextBox.Location = new System.Drawing.Point(729, 57);
this.m_currLonTextBox.Name = "m_currLonTextBox";
this.m_currLonTextBox.ReadOnly = true;
this.m_currLonTextBox.Size = new System.Drawing.Size(127, 20);
this.m_currLonTextBox.TabIndex = 24;
//
// m_lengthTextBox
//
this.m_lengthTextBox.Location = new System.Drawing.Point(729, 85);
this.m_lengthTextBox.Name = "m_lengthTextBox";
this.m_lengthTextBox.ReadOnly = true;
this.m_lengthTextBox.Size = new System.Drawing.Size(127, 20);
this.m_lengthTextBox.TabIndex = 25;
//
// m_areaTextBox
//
this.m_areaTextBox.Location = new System.Drawing.Point(729, 112);
this.m_areaTextBox.Name = "m_areaTextBox";
this.m_areaTextBox.ReadOnly = true;
this.m_areaTextBox.Size = new System.Drawing.Size(127, 20);
this.m_areaTextBox.TabIndex = 26;
//
// button2
//
this.button2.Location = new System.Drawing.Point(405, 84);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 23);
this.button2.TabIndex = 27;
this.button2.Text = "Clear";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.OnClear);
//
// button3
//
this.button3.Location = new System.Drawing.Point(405, 109);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(75, 23);
this.button3.TabIndex = 28;
this.button3.Text = "Validate";
this.button3.UseVisualStyleBackColor = true;
this.button3.Click += new System.EventHandler(this.OnValidate);
//
// m_polylineCheckBox
//
this.m_polylineCheckBox.AutoSize = true;
this.m_polylineCheckBox.Location = new System.Drawing.Point(15, 112);
this.m_polylineCheckBox.Name = "m_polylineCheckBox";
this.m_polylineCheckBox.Size = new System.Drawing.Size(62, 17);
this.m_polylineCheckBox.TabIndex = 29;
this.m_polylineCheckBox.Text = "Polyline";
this.m_polylineCheckBox.UseVisualStyleBackColor = true;
//
// PolyPanel
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.button3);
this.Controls.Add(this.button2);
this.Controls.Add(this.m_areaTextBox);
this.Controls.Add(this.m_lengthTextBox);
this.Controls.Add(this.m_currLonTextBox);
this.Controls.Add(this.m_currLatTextBox);
this.Controls.Add(this.m_numPointsTextBox);
this.Controls.Add(this.label11);
this.Controls.Add(this.label10);
this.Controls.Add(this.label9);
this.Controls.Add(this.label8);
this.Controls.Add(this.label7);
this.Controls.Add(this.m_edgeButton);
this.Controls.Add(this.m_distanceTextBox);
this.Controls.Add(this.m_azimuthTextBox);
this.Controls.Add(this.label6);
this.Controls.Add(this.label5);
this.Controls.Add(this.button1);
this.Controls.Add(this.m_longitudeTextBox);
this.Controls.Add(this.m_latitudeTextBox);
this.Controls.Add(this.label4);
this.Controls.Add(this.label3);
this.Controls.Add(this.groupBox1);
this.Name = "PolyPanel";
this.Size = new System.Drawing.Size(979, 359);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Button m_setButton;
private System.Windows.Forms.TextBox m_flatteningTextBox;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox m_equatorialRadiusTextBox;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox m_latitudeTextBox;
private System.Windows.Forms.TextBox m_longitudeTextBox;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.TextBox m_azimuthTextBox;
private System.Windows.Forms.TextBox m_distanceTextBox;
private System.Windows.Forms.Button m_edgeButton;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.TextBox m_numPointsTextBox;
private System.Windows.Forms.TextBox m_currLatTextBox;
private System.Windows.Forms.TextBox m_currLonTextBox;
private System.Windows.Forms.TextBox m_lengthTextBox;
private System.Windows.Forms.TextBox m_areaTextBox;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.CheckBox m_polylineCheckBox;
}
}
| |
using System;
using System.Threading;
using Gdk;
using GLib;
using MasterLogFile;
using MasterTimeSpan;
namespace MasterChaosDisplay
{
//Render Method(s)
class ChaosRenderer : PassThroughLoggedClass
{
//The rendering machine to render on
private ChaosRenderingMachine _OutputPort;
//The rendering engine to render
private ChaosEngine _RenderingEngine;
//This is the amount that is completed of the render (from 0.0 to 1.0)
private double _RenderProgressAmount;
private bool _CurrentlyRendering;
//If this is true we will render a visual preview and divide it into quads
private bool _VisualRender;
//If this is true we will only render 1/4 of the pixels for a quick preview mode
private bool _QuadSampling;
public ChaosRenderer ( ChaosRenderingMachine pOutputPort, ChaosEngine pRenderingEngine )
{
//Assign the object references for this renderer.
this._RenderingEngine = pRenderingEngine;
this._OutputPort = pOutputPort;
this._RenderProgressAmount = 0;
//Default to visual interactive renders
this._VisualRender = true;
}
public void Render()
{
if ( !this._CurrentlyRendering )
{
ThreadStart tmpRenderThreadStart;
this._CurrentlyRendering = true;
//Now set the color count
this._RenderingEngine.SetParameter( "Screen_Color_Count", this._OutputPort.Pallete.Count.ToString() );
if (this._VisualRender && !this._QuadSampling)
tmpRenderThreadStart = new ThreadStart(this.RenderFullVisual);
else
tmpRenderThreadStart = new ThreadStart(this.RenderFull);
System.Threading.Thread tmpRenderThread = new System.Threading.Thread(tmpRenderThreadStart);
tmpRenderThread.Start();
}
}
private void RenderFullVisual()
{
this.WriteToLog ( "*** Visually Hinted Image Computation Beginning ***" );
this.WriteToLog ( this._RenderingEngine.Name + " " + this._RenderingEngine.ParameterSerialization );
TimeSpanMetric tmpRenderTimer = new TimeSpanMetric();
int tmpScreenXCounter, tmpScreenYCounter;
double tmpChaosXCounter, tmpChaosYCounter;
double tmpChaosXIncrement, tmpChaosYIncrement;
int tmpTotalPixelCount, tmpCurrentPixelCount;
//A thread-safe container for the display refresh event
IdleHandler tmpIdleMessageRefreshContainer = new IdleHandler(this.RefreshDisplaySafe);
this._RenderingEngine.RenderBegin();
//Compute the Pixel to Chaos space ratio
tmpChaosXIncrement = (double)((this._RenderingEngine.ChaosMaxX - this._RenderingEngine.ChaosMinX) / (double)_OutputPort.Width );
//Chaos_Y_Incriment = (double)((this.Rendering_Engine.Chaos_Max_Y - this.Rendering_Engine.Chaos_Min_Y) / (double)Output_Port.Height );
tmpChaosYIncrement = tmpChaosXIncrement;
//Compute the pixel counter for the progress bar.
tmpTotalPixelCount = _OutputPort.Width * _OutputPort.Height;
tmpCurrentPixelCount = 0;
_OutputPort.LastXOrigin = this._RenderingEngine.ChaosMinX;
_OutputPort.LastYOrigin = this._RenderingEngine.ChaosMinY;
_OutputPort.LastXRatio = tmpChaosXIncrement;
_OutputPort.LastYRatio = tmpChaosYIncrement;
this._RenderingEngine.CurrentRenderRatio = tmpChaosXIncrement;
//Clear the render port
for (tmpScreenXCounter = 0; tmpScreenXCounter < _OutputPort.Width; tmpScreenXCounter++)
{
for (tmpScreenYCounter = 0; tmpScreenYCounter < _OutputPort.Height; tmpScreenYCounter++)
_OutputPort.MarkPixel ( tmpScreenXCounter, tmpScreenYCounter, -1 );
}
this.WriteToLog ( " --> Viewport Cleared" );
//Refresh the display
Gdk.Threads.Enter();
GLib.Idle.Add( tmpIdleMessageRefreshContainer );
Gdk.Threads.Leave();
//Now render a quad fractal preview
tmpChaosXCounter = this._RenderingEngine.ChaosMinX;
for (tmpScreenXCounter = 0; tmpScreenXCounter < _OutputPort.Width; tmpScreenXCounter++)
{
tmpChaosYCounter = this._RenderingEngine.ChaosMinY;
for (tmpScreenYCounter = 0; tmpScreenYCounter < _OutputPort.Height; tmpScreenYCounter++)
{
if ( (tmpScreenXCounter % 2 == 0) && (tmpScreenYCounter % 2 == 0) )
{
_OutputPort.MarkPixelQuad ( tmpScreenXCounter, tmpScreenYCounter, this._RenderingEngine.RenderPixel ( tmpChaosXCounter, tmpChaosYCounter ) );
tmpCurrentPixelCount++;
}
//if ( Current_Pixel_Counter % (this.Output_Port.Width*4) == 1 )
//{
this._RenderProgressAmount = ((double)tmpCurrentPixelCount/(double)tmpTotalPixelCount);
//}
tmpChaosYCounter += tmpChaosXIncrement;
}
tmpChaosXCounter += tmpChaosYIncrement;
}
this.WriteToLog ( " --> Quad 0,0 Done [" + tmpCurrentPixelCount.ToString()+"/"+tmpTotalPixelCount.ToString()+"]" );
//Refresh the display
Gdk.Threads.Enter();
GLib.Idle.Add( tmpIdleMessageRefreshContainer );
Gdk.Threads.Leave();
//Now render the 1,1 fractal set
tmpChaosXCounter = this._RenderingEngine.ChaosMinX;
for (tmpScreenXCounter = 0; tmpScreenXCounter < _OutputPort.Width; tmpScreenXCounter++)
{
tmpChaosYCounter = this._RenderingEngine.ChaosMinY;
for (tmpScreenYCounter = 0; tmpScreenYCounter < _OutputPort.Height; tmpScreenYCounter++)
{
if ( (tmpScreenXCounter % 2 == 1) && (tmpScreenYCounter % 2 == 1) )
{
_OutputPort.MarkPixel ( tmpScreenXCounter, tmpScreenYCounter, this._RenderingEngine.RenderPixel ( tmpChaosXCounter, tmpChaosYCounter ) );
tmpCurrentPixelCount++;
}
this._RenderProgressAmount = ((double)tmpCurrentPixelCount/(double)tmpTotalPixelCount);
tmpChaosYCounter += tmpChaosXIncrement;
}
tmpChaosXCounter += tmpChaosYIncrement;
}
this.WriteToLog ( " --> Subquad 1,1 Done [" + tmpCurrentPixelCount.ToString()+"/"+tmpTotalPixelCount.ToString()+"]" );
//Refresh the display
Gdk.Threads.Enter();
GLib.Idle.Add( tmpIdleMessageRefreshContainer );
Gdk.Threads.Leave();
//Now render the 1,0 fractal set
tmpChaosXCounter = this._RenderingEngine.ChaosMinX;
for (tmpScreenXCounter = 0; tmpScreenXCounter < _OutputPort.Width; tmpScreenXCounter++)
{
tmpChaosYCounter = this._RenderingEngine.ChaosMinY;
for (tmpScreenYCounter = 0; tmpScreenYCounter < _OutputPort.Height; tmpScreenYCounter++)
{
if ( (tmpScreenXCounter % 2 == 1) && (tmpScreenYCounter % 2 == 0) )
{
_OutputPort.MarkPixel ( tmpScreenXCounter, tmpScreenYCounter, this._RenderingEngine.RenderPixel ( tmpChaosXCounter, tmpChaosYCounter ) );
tmpCurrentPixelCount++;
}
this._RenderProgressAmount = ((double)tmpCurrentPixelCount/(double)tmpTotalPixelCount);
tmpChaosYCounter += tmpChaosXIncrement;
}
tmpChaosXCounter += tmpChaosYIncrement;
}
this.WriteToLog ( " --> Subquad 1,0 Done [" + tmpCurrentPixelCount.ToString()+"/"+tmpTotalPixelCount.ToString()+"]" );
//Refresh the display
Gdk.Threads.Enter();
GLib.Idle.Add( tmpIdleMessageRefreshContainer );
Gdk.Threads.Leave();
//Now render the 0,1 fractal set
tmpChaosXCounter = this._RenderingEngine.ChaosMinX;
for (tmpScreenXCounter = 0; tmpScreenXCounter < _OutputPort.Width; tmpScreenXCounter++)
{
tmpChaosYCounter = this._RenderingEngine.ChaosMinY;
for (tmpScreenYCounter = 0; tmpScreenYCounter < _OutputPort.Height; tmpScreenYCounter++)
{
if ( (tmpScreenXCounter % 2 == 0) && (tmpScreenYCounter % 2 == 1) )
{
_OutputPort.MarkPixel ( tmpScreenXCounter, tmpScreenYCounter, this._RenderingEngine.RenderPixel ( tmpChaosXCounter, tmpChaosYCounter ) );
tmpCurrentPixelCount++;
}
//if ( Current_Pixel_Counter % (this.Output_Port.Width*4) == 1 )
//{
this._RenderProgressAmount = ((double)tmpCurrentPixelCount/(double)tmpTotalPixelCount);
//}
tmpChaosYCounter += tmpChaosXIncrement;
}
tmpChaosXCounter += tmpChaosYIncrement;
}
this.WriteToLog ( " --> Subquad 0,1 Done [" + tmpCurrentPixelCount.ToString()+"/"+tmpTotalPixelCount.ToString()+"]" );
//Refresh the display
Gdk.Threads.Enter();
GLib.Idle.Add( tmpIdleMessageRefreshContainer );
Gdk.Threads.Leave();
this._RenderingEngine.Render_End();
//Update the progress at 100%
this._RenderProgressAmount = 1;
tmpRenderTimer.Time_Stamp();
this.WriteToLog ( "*** Image Computation Complete (" + tmpRenderTimer.TimeDifference.ToString() + "ms) ***" );
this._CurrentlyRendering = false;
}
private void RenderFull()
{
this.WriteToLog ( "*** Silent Image Computation Beginning ***" );
this.WriteToLog ( this._RenderingEngine.Name + " " + this._RenderingEngine.ParameterSerialization );
TimeSpanMetric tmpComputationTimer = new TimeSpanMetric();
int tmpScreenXCounter, tmpScreenYCounter;
double tmpChaosXCounter, tmpChaosYCounter;
double tmpChaosXIncrement, tmpChaosYIncrement;
int tmpTotalPixelCount, tmpCurrentPixelCounter;
//A thread-safe container for the display refresh event
IdleHandler tmpIdleMessageRefreshContainer = new IdleHandler(this.RefreshDisplaySafe);
this._RenderingEngine.RenderBegin();
//Compute the Pixel to Chaos space ratio
tmpChaosXIncrement = (double)((this._RenderingEngine.ChaosMaxX - this._RenderingEngine.ChaosMinX) / (double)_OutputPort.Width );
//Chaos_Y_Incriment = (double)((this.Rendering_Engine.Chaos_Max_Y - this.Rendering_Engine.Chaos_Min_Y) / (double)Output_Port.Height );
tmpChaosYIncrement = tmpChaosXIncrement;
//Compute the pixel counter for the progress bar.
tmpTotalPixelCount = _OutputPort.Width * _OutputPort.Height;
tmpCurrentPixelCounter = 0;
_OutputPort.LastXOrigin = this._RenderingEngine.ChaosMinX;
_OutputPort.LastYOrigin = this._RenderingEngine.ChaosMinY;
_OutputPort.LastXRatio = tmpChaosXIncrement;
_OutputPort.LastYRatio = tmpChaosYIncrement;
this._RenderingEngine.CurrentRenderRatio = tmpChaosXIncrement;
tmpChaosXCounter = this._RenderingEngine.ChaosMinX;
for (tmpScreenXCounter = 0; tmpScreenXCounter < _OutputPort.Width; tmpScreenXCounter++)
{
tmpChaosYCounter = this._RenderingEngine.ChaosMinY;
for (tmpScreenYCounter = 0; tmpScreenYCounter < _OutputPort.Height; tmpScreenYCounter++)
{
if ( this._QuadSampling )
{
if ( (tmpScreenXCounter % 2 == 0) && (tmpScreenYCounter % 2 == 0) )
{
_OutputPort.MarkPixelQuad ( tmpScreenXCounter, tmpScreenYCounter, this._RenderingEngine.RenderPixel ( tmpChaosXCounter, tmpChaosYCounter ) );
}
tmpCurrentPixelCounter++;
}
else
{
_OutputPort.MarkPixel ( tmpScreenXCounter, tmpScreenYCounter, this._RenderingEngine.RenderPixel ( tmpChaosXCounter, tmpChaosYCounter ) );
tmpCurrentPixelCounter++;
}
//if ( Current_Pixel_Counter % (this.Output_Port.Width*4) == 1 )
//{
this._RenderProgressAmount = ((double)tmpCurrentPixelCounter/(double)tmpTotalPixelCount);
//}
tmpChaosYCounter += tmpChaosXIncrement;
}
tmpChaosXCounter += tmpChaosYIncrement;
}
this._RenderingEngine.Render_End();
//It's now safe to refresh the display and such.
Gdk.Threads.Enter();
GLib.Idle.Add( tmpIdleMessageRefreshContainer );
Gdk.Threads.Leave();
//Update the progress at 100%
this._RenderProgressAmount = 1;
tmpComputationTimer.Time_Stamp();
this.WriteToLog ( "*** Image Computation Complete (" + tmpComputationTimer.TimeDifference.ToString() + "ms) ***" );
this._CurrentlyRendering = false;
}
//Progress Bar Data Access
public double Progress
{
get { return this._RenderProgressAmount; }
}
public bool Rendering
{
get { return this._CurrentlyRendering; }
}
public int RenderQuality
{
set
{
if ( value > 0 )
{
this.WriteToLog ( "Quality Set To: " + value.ToString() );
this._RenderingEngine.CurrentRenderQuality = value;
this._QuadSampling = false;
}
else
{
this.WriteToLog ( "Quality Set To: 0 (preview)" );
//Zero or subzero means a special quality where the renderer is on 1 and we only do 1/4 pixels
this._RenderingEngine.CurrentRenderQuality = 1;
this._QuadSampling = true;
}
}
}
public bool RenderVisual
{
set
{
if (value)
this.WriteToLog ( "Visually Hinted Render Mode Activated" );
else
this.WriteToLog ( "Silent Render Mode Activated" );
this._VisualRender = value;
}
}
public ChaosEngine Engine
{
set { this._RenderingEngine = value; }
}
#region Display Refresh Event
public event EventHandler RefreshDisplay;
public bool RefreshDisplaySafe()
{
EventArgs tmpArguments = new EventArgs();
this.RefreshDisplay( this, tmpArguments );
return false;
}
#endregion
}
}
| |
#region Apache Notice
/*****************************************************************************
* $Header: $
* $Revision: $
* $Date: $
*
* iBATIS.NET Data Mapper
* Copyright (C) 2004 - Gilles Bayon
*
*
* 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.Collections;
using System.Text;
namespace IBatisNet.Common.Utilities
{
/// <summary>
/// A StringTokenizer java like object
/// </summary>
public class StringTokenizer : IEnumerable
{
private static readonly string _defaultDelim=" \t\n\r\f";
string _origin = string.Empty;
string _delimiters = string.Empty;
bool _returnDelimiters = false;
/// <summary>
/// Constructs a StringTokenizer on the specified String, using the
/// default delimiter set (which is " \t\n\r\f").
/// </summary>
/// <param name="str">The input String</param>
public StringTokenizer(string str)
{
_origin = str;
_delimiters = _defaultDelim;
_returnDelimiters = false;
}
/// <summary>
/// Constructs a StringTokenizer on the specified String,
/// using the specified delimiter set.
/// </summary>
/// <param name="str">The input String</param>
/// <param name="delimiters">The delimiter String</param>
public StringTokenizer(string str, string delimiters)
{
_origin = str;
_delimiters = delimiters;
_returnDelimiters = false;
}
/// <summary>
/// Constructs a StringTokenizer on the specified String,
/// using the specified delimiter set.
/// </summary>
/// <param name="str">The input String</param>
/// <param name="delimiters">The delimiter String</param>
/// <param name="returnDelimiters">Returns delimiters as tokens or skip them</param>
public StringTokenizer(string str, string delimiters, bool returnDelimiters)
{
_origin = str;
_delimiters = delimiters;
_returnDelimiters = returnDelimiters;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IEnumerator GetEnumerator()
{
return new StringTokenizerEnumerator(this);
}
/// <summary>
/// Returns the number of tokens in the String using
/// the current deliminter set. This is the number of times
/// nextToken() can return before it will generate an exception.
/// Use of this routine to count the number of tokens is faster
/// than repeatedly calling nextToken() because the substrings
/// are not constructed and returned for each token.
/// </summary>
public int TokenNumber
{
get
{
int count = 0;
int currpos = 0;
int maxPosition = _origin.Length;
while (currpos < maxPosition)
{
while (!_returnDelimiters &&
(currpos < maxPosition) &&
(_delimiters.IndexOf(_origin[currpos]) >= 0))
{
currpos++;
}
if (currpos >= maxPosition)
{
break;
}
int start = currpos;
while ((currpos < maxPosition) &&
(_delimiters.IndexOf(_origin[currpos]) < 0))
{
currpos++;
}
if (_returnDelimiters && (start == currpos) &&
(_delimiters.IndexOf(_origin[currpos]) >= 0))
{
currpos++;
}
count++;
}
return count;
}
}
private class StringTokenizerEnumerator : IEnumerator
{
private StringTokenizer _stokenizer;
private int _cursor = 0;
private string _next = null;
public StringTokenizerEnumerator(StringTokenizer stok)
{
_stokenizer = stok;
}
public bool MoveNext()
{
_next = GetNext();
return _next != null;
}
public void Reset()
{
_cursor = 0;
}
public object Current
{
get
{
return _next;
}
}
private string GetNext()
{
char c;
bool isDelim;
if( _cursor >= _stokenizer._origin.Length )
return null;
c = _stokenizer._origin[_cursor];
isDelim = (_stokenizer._delimiters.IndexOf(c) != -1);
if ( isDelim )
{
_cursor++;
if ( _stokenizer._returnDelimiters )
{
return c.ToString();
}
return GetNext();
}
int nextDelimPos = _stokenizer._origin.IndexOfAny(_stokenizer._delimiters.ToCharArray(), _cursor);
if (nextDelimPos == -1)
{
nextDelimPos = _stokenizer._origin.Length;
}
string nextToken = _stokenizer._origin.Substring(_cursor, nextDelimPos - _cursor);
_cursor = nextDelimPos;
return nextToken;
}
}
}
}
| |
// 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.IO;
using System.Runtime.InteropServices;
using System.Threading;
using Xunit;
namespace System.IO.Tests
{
public class CreatedTests : FileSystemWatcherTest
{
[Fact]
public void FileSystemWatcher_Created_File()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var watcher = new FileSystemWatcher(testDirectory.Path))
{
string fileName = Path.Combine(testDirectory.Path, GetTestFileName());
watcher.Filter = Path.GetFileName(fileName);
AutoResetEvent eventOccurred = WatchForEvents(watcher, WatcherChangeTypes.Created);
watcher.EnableRaisingEvents = true;
using (var file = new TempFile(fileName))
{
ExpectEvent(eventOccurred, "created");
}
}
}
[Fact]
public void FileSystemWatcher_Created_File_ForceRestart()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var watcher = new FileSystemWatcher(testDirectory.Path))
{
string fileName = Path.Combine(testDirectory.Path, GetTestFileName());
watcher.Filter = Path.GetFileName(fileName);
AutoResetEvent eventOccurred = WatchForEvents(watcher, WatcherChangeTypes.Created);
watcher.EnableRaisingEvents = true;
watcher.NotifyFilter = NotifyFilters.FileName; // change filter to force restart
using (var file = new TempFile(fileName))
{
ExpectEvent(eventOccurred, "created");
}
}
}
[Fact]
public void FileSystemWatcher_Created_Directory()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var watcher = new FileSystemWatcher(testDirectory.Path))
{
string dirName = Path.Combine(testDirectory.Path, GetTestFileName());
watcher.Filter = Path.GetFileName(dirName);
AutoResetEvent eventOccurred = WatchForEvents(watcher, WatcherChangeTypes.Created);
watcher.EnableRaisingEvents = true;
using (var dir = new TempDirectory(dirName))
{
ExpectEvent(eventOccurred, "created");
}
}
}
[Fact]
[ActiveIssue(2011, PlatformID.OSX)]
public void FileSystemWatcher_Created_MoveDirectory()
{
// create two test directories
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (TempDirectory originalDir = new TempDirectory(Path.Combine(testDirectory.Path, GetTestFileName())))
using (TempDirectory targetDir = new TempDirectory(originalDir.Path + "_target"))
using (var watcher = new FileSystemWatcher(testDirectory.Path))
{
string testFileName = GetTestFileName();
// watch the target dir
watcher.Path = Path.GetFullPath(targetDir.Path);
watcher.Filter = testFileName;
AutoResetEvent eventOccurred = WatchForEvents(watcher, WatcherChangeTypes.Created);
string sourceFile = Path.Combine(originalDir.Path, testFileName);
string targetFile = Path.Combine(targetDir.Path, testFileName);
// create a test file in source
File.WriteAllText(sourceFile, "test content");
watcher.EnableRaisingEvents = true;
// move the test file from source to target directory
File.Move(sourceFile, targetFile);
ExpectEvent(eventOccurred, "created");
}
}
[Fact]
public void FileSystemWatcher_Created_Negative()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, GetTestFileName())))
using (var watcher = new FileSystemWatcher())
{
// put everything in our own directory to avoid collisions
watcher.Path = Path.GetFullPath(dir.Path);
watcher.Filter = "*.*";
AutoResetEvent eventOccurred = WatchForEvents(watcher, WatcherChangeTypes.Created);
// run all scenarios together to avoid unnecessary waits,
// assert information is verbose enough to trace to failure cause
using (var testFile = new TempFile(Path.Combine(dir.Path, "file")))
using (var testDir = new TempDirectory(Path.Combine(dir.Path, "dir")))
{
// start listening after we've created these
watcher.EnableRaisingEvents = true;
// change a file
File.AppendAllText(testFile.Path, "change");
// renaming a directory
//
// We don't do this on Linux because depending on the timing of MOVED_FROM and MOVED_TO events,
// a rename can trigger delete + create as a deliberate handling of an edge case, and this
// test is checking that no create events are raised.
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
Directory.Move(testDir.Path, testDir.Path + "_rename");
}
// deleting a file & directory by leaving the using block
}
ExpectNoEvent(eventOccurred, "created");
}
}
[Fact]
public void FileSystemWatcher_Created_FileCreatedInNestedDirectory()
{
TestNestedDirectoriesHelper(GetTestFilePath(), WatcherChangeTypes.Created, (AutoResetEvent are, TempDirectory ttd) =>
{
using (var nestedFile = new TempFile(Path.Combine(ttd.Path, "nestedFile")))
{
ExpectEvent(are, "nested file created");
}
});
}
// This can potentially fail, depending on where the test is run from, due to
// the MAX_PATH limitation. When issue 645 is closed, this shouldn't be a problem
[Fact, ActiveIssue(645, PlatformID.Any)]
public void FileSystemWatcher_Created_DeepDirectoryStructure()
{
// List of created directories
List<TempDirectory> lst = new List<TempDirectory>();
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, GetTestFileName())))
using (var watcher = new FileSystemWatcher())
{
AutoResetEvent eventOccurred = WatchForEvents(watcher, WatcherChangeTypes.Created);
// put everything in our own directory to avoid collisions
watcher.Path = Path.GetFullPath(dir.Path);
watcher.Filter = "*.*";
watcher.IncludeSubdirectories = true;
watcher.EnableRaisingEvents = true;
// Priming directory
TempDirectory priming = new TempDirectory(Path.Combine(dir.Path, "dir"));
lst.Add(priming);
ExpectEvent(eventOccurred, "priming create");
// Create a deep directory structure and expect things to work
for (int i = 1; i < 20; i++)
{
lst.Add(new TempDirectory(Path.Combine(lst[i - 1].Path, String.Format("dir{0}", i))));
ExpectEvent(eventOccurred, lst[i].Path + " create");
}
// Put a file at the very bottom and expect it to raise an event
using (var file = new TempFile(Path.Combine(lst[lst.Count - 1].Path, "temp file")))
{
ExpectEvent(eventOccurred, "temp file create");
}
}
}
[ConditionalFact(nameof(CanCreateSymbolicLinks))]
[ActiveIssue(3215, PlatformID.OSX)]
public void FileSystemWatcher_Created_WatcherDoesntFollowSymLinkToFile()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, GetTestFileName())))
using (var temp = new TempFile(GetTestFilePath()))
using (var watcher = new FileSystemWatcher())
{
AutoResetEvent eventOccurred = WatchForEvents(watcher, WatcherChangeTypes.Created);
// put everything in our own directory to avoid collisions
watcher.Path = Path.GetFullPath(dir.Path);
watcher.Filter = "*";
watcher.EnableRaisingEvents = true;
// Make the symlink in our path (to the temp file) and make sure an event is raised
string symLinkPath = Path.Combine(dir.Path, Path.GetFileName(temp.Path));
Assert.True(CreateSymLink(temp.Path, symLinkPath, false));
Assert.True(File.Exists(symLinkPath));
ExpectEvent(eventOccurred, "symlink created");
}
}
[ConditionalFact(nameof(CanCreateSymbolicLinks))]
public void FileSystemWatcher_Created_WatcherDoesntFollowSymLinkToFolder()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, GetTestFileName())))
using (var temp = new TempDirectory(GetTestFilePath()))
using (var watcher = new FileSystemWatcher())
{
AutoResetEvent eventOccurred = WatchForEvents(watcher, WatcherChangeTypes.Created);
// put everything in our own directory to avoid collisions
watcher.Path = Path.GetFullPath(dir.Path);
watcher.Filter = "*";
watcher.EnableRaisingEvents = true;
// Make the symlink in our path (to the temp folder) and make sure an event is raised
string symLinkPath = Path.Combine(dir.Path, Path.GetFileName(temp.Path));
Assert.True(CreateSymLink(temp.Path, symLinkPath, true));
Assert.True(Directory.Exists(symLinkPath));
ExpectEvent(eventOccurred, "symlink created");
}
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using mshtml;
using OpenLiveWriter.BrowserControl;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.Interop.Com;
using OpenLiveWriter.Interop.Com.ActiveDocuments;
using OpenLiveWriter.ApplicationFramework;
namespace OpenLiveWriter.InternalWriterPlugin
{
/// <summary>
/// Summary description for MapControl.
/// </summary>
public class MapControl : BorderControl
{
public static int MIN_ZOOM = 1;
public static int MAX_ZOOM = 19;
private ExplorerBrowserControl explorerBrowserControl;
/// <summary>
/// Required designer variable.
/// </summary>
private Container components = null;
private MapActiveObject _activeObject;
private string _address;
public MapControl()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
explorerBrowserControl.DocumentComplete += new BrowserDocumentEventHandler(explorerBrowserControl_DocumentComplete);
this.RightToLeft = RightToLeft.No;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (explorerBrowserControl != null)
{
explorerBrowserControl.DocumentComplete -= new BrowserDocumentEventHandler(explorerBrowserControl_DocumentComplete);
explorerBrowserControl.Dispose();
explorerBrowserControl = null;
}
if (MapActiveObject != null)
{
MapActiveObject = null;
}
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Component 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.explorerBrowserControl = new OpenLiveWriter.BrowserControl.ExplorerBrowserControl();
this.SuspendLayout();
//
// explorerBrowserControl
//
this.explorerBrowserControl.Dock = System.Windows.Forms.DockStyle.Fill;
this.explorerBrowserControl.Location = new System.Drawing.Point(1, 1);
this.explorerBrowserControl.Name = "explorerBrowserControl";
this.explorerBrowserControl.Silent = true;
this.explorerBrowserControl.Size = new System.Drawing.Size(326, 278);
this.explorerBrowserControl.TabIndex = 0;
this.explorerBrowserControl.TextSize = OpenLiveWriter.BrowserControl.TextSize.Medium;
this.explorerBrowserControl.WorkOffline = false;
//
// MapControl
//
this.Controls.Add(this.explorerBrowserControl);
this.DockPadding.All = 1;
this.Name = "MapControl";
this.Size = new System.Drawing.Size(328, 280);
this.Controls.SetChildIndex(this.explorerBrowserControl, 0);
this.ResumeLayout(false);
}
#endregion
#region Events
public event EventHandler MapStyleChanged;
protected virtual void OnMapStyleChanged(EventArgs e)
{
if (MapStyleChanged != null)
MapStyleChanged(this, e);
}
public event EventHandler ZoomLevelChanged;
protected virtual void OnZoomLevelChanged(EventArgs e)
{
if (ZoomLevelChanged != null)
ZoomLevelChanged(this, e);
}
public delegate void PushpinEventHandler(VEPushpin pushpin);
public event PushpinEventHandler PushpinAdded;
protected virtual void OnPushpinAdded(VEPushpin pushpin)
{
if (PushpinAdded != null)
PushpinAdded(pushpin);
}
public event PushpinEventHandler PushpinRemoved;
protected virtual void OnPushpinRemoved(VEPushpin pushpin)
{
if (PushpinRemoved != null)
PushpinRemoved(pushpin);
}
public event EventHandler BirdseyeChanged;
protected virtual void OnBirdseyeChanged(EventArgs e)
{
if (BirdseyeChanged != null)
BirdseyeChanged(this, e);
}
public event MapContextMenuHandler ShowMapContextMenu;
protected virtual void OnShowMapContextMenu(MapContextMenuEvent e)
{
if (ShowMapContextMenu != null)
ShowMapContextMenu(e);
}
public event MapPushpinContextMenuHandler ShowPushpinContextMenu;
protected virtual void OnShowPushpinContextMenu(MapContextMenuEvent e, string pushpinId)
{
if (ShowPushpinContextMenu != null)
ShowPushpinContextMenu(e, pushpinId);
}
#endregion
private void explorerBrowserControl_DocumentComplete(object sender, BrowserDocumentEventArgs e)
{
IHTMLDocument2 document = (IHTMLDocument2)explorerBrowserControl.Document;
// turn off borders
(document.body as IHTMLElement).style.borderStyle = "none";
//MapActiveObject.ClearEvents();
if (_address != null)
{
MapActiveObject.FindLocation(_address);
_address = null;
}
MapActiveObject.AttachToMapDocument(document);
}
/// <summary>
/// Initializes the map to a center on a set of coordinates.
/// </summary>
/// <param name="address"></param>
public void LoadMap(string address)
{
MapActiveObject.FindLocation(address);
}
/// <summary>
/// Initializes the map to a center on a set of coordinates.
/// </summary>
/// <param name="latitude"></param>
/// <param name="longitude"></param>
/// <param name="mapStyle"></param>
/// <param name="zoomLevel"></param>
public void LoadMap(float latitude, float longitude, string reserved, string mapStyle, int zoomLevel)
{
LoadMap(latitude, longitude, reserved, mapStyle, zoomLevel, null);
}
/// <summary>
/// Initializes the map to a center on a set of coordinates.
/// </summary>
/// <param name="latitude"></param>
/// <param name="longitude"></param>
/// <param name="mapStyle"></param>
/// <param name="zoomLevel"></param>
public void LoadMap(float latitude, float longitude, string reserved, string mapStyle, int zoomLevel, VEBirdseyeScene scene)
{
MapActiveObject = new MapActiveObject(new VELatLong(latitude, longitude, reserved), mapStyle, zoomLevel, scene);
//string url = MapUrlHelper.CreateMapUrl(LocalMapUrl, latitude, longitude, mapStyle, zoomLevel);
string url = LocalMapUrl;
url = new Uri(url).ToString();
explorerBrowserControl.Navigate(url);
}
public void PanMap(int deltaX, int deltaY)
{
_activeObject.PanMap(deltaX, deltaY);
}
public void AddPushpin(VEPushpin pushpin)
{
_activeObject.AddPushpin(pushpin);
}
public VEPushpin GetPushpin(string pushpinId)
{
return _activeObject.GetPushpin(pushpinId);
}
public void UpdatePushpin(VEPushpin pushpin)
{
_activeObject.UpdatePushpin(pushpin);
}
public void DeletePushpin(string pushpinId)
{
_activeObject.DeletePushpin(pushpinId);
}
public void DeleteAllPushpins()
{
_activeObject.DeleteAllPushpins();
}
public void ZoomToLocation(Point p, int zoomLevel)
{
_activeObject.ZoomToLocation(p, zoomLevel);
}
public float Latitude
{
get
{
return MapActiveObject.GetCenter().Latitude;
}
}
public float Longitude
{
get
{
return MapActiveObject.GetCenter().Longitude;
}
}
public string Reserved
{
get
{
return MapActiveObject.GetCenter().Reserved;
}
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string Style
{
get
{
return MapActiveObject.MapStyle;
}
set
{
if (MapActiveObject != null) MapActiveObject.MapStyle = value;
}
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public int ZoomLevel
{
get
{
return MapActiveObject.ZoomLevel;
}
set
{
if (MapActiveObject != null) MapActiveObject.ZoomLevel = value;
}
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public VEPushpin[] Pushpins
{
get
{
return MapActiveObject.GetPushpins();
}
set
{
if (MapActiveObject != null)
{
MapActiveObject.DeleteAllPushpins();
foreach (VEPushpin pushpin in value)
MapActiveObject.AddPushpin(pushpin);
}
}
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool BirdsEyeAvailable
{
get { return _activeObject.BirdsEyeAvailable; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public VEBirdseyeScene BirdseyeScene
{
get { return _activeObject.BirdseyeScene; }
set { if (_activeObject != null) _activeObject.BirdseyeScene = value; }
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public VEOrientation BirdseyeOrientation
{
get { return _activeObject.BirdseyeOrientation; }
set { if (_activeObject != null) _activeObject.BirdseyeOrientation = value; }
}
private static string LocalMapUrl
{
get
{
string mapHtmlFile = Path.Combine(ApplicationEnvironment.InstallationDirectory, @"html\map.html");
return UrlHelper.CreateUrlFromPath(MapUrlHelper.FixedUpMapHtml(mapHtmlFile));
}
}
private MapActiveObject MapActiveObject
{
get { return _activeObject; }
set
{
if (_activeObject != value)
{
if (_activeObject != null)
{
_activeObject.StyleChanged -= new EventHandler(_activeObject_StyleChanged);
_activeObject.ZoomLevelChanged -= new EventHandler(_activeObject_ZoomLevelChanged);
_activeObject.PushpinAdded -= new OpenLiveWriter.InternalWriterPlugin.PushpinEventHandler(_activeObject_PushpinAdded);
_activeObject.PushpinRemoved -= new OpenLiveWriter.InternalWriterPlugin.PushpinEventHandler(_activeObject_PushpinRemoved);
_activeObject.BirdseyeChanged -= new EventHandler(_activeObject_BirdseyeChanged);
_activeObject.ShowMapContextMenu -= new MapContextMenuHandler(_activeObject_ShowMapContextMenu);
_activeObject.ShowPushpinContextMenu -= new MapPushpinContextMenuHandler(_activeObject_ShowPushpinContextMenu);
}
_activeObject = value;
if (_activeObject != null)
{
_activeObject.StyleChanged += new EventHandler(_activeObject_StyleChanged);
_activeObject.ZoomLevelChanged += new EventHandler(_activeObject_ZoomLevelChanged);
_activeObject.PushpinAdded += new OpenLiveWriter.InternalWriterPlugin.PushpinEventHandler(_activeObject_PushpinAdded);
_activeObject.PushpinRemoved += new OpenLiveWriter.InternalWriterPlugin.PushpinEventHandler(_activeObject_PushpinRemoved);
_activeObject.BirdseyeChanged += new EventHandler(_activeObject_BirdseyeChanged);
_activeObject.ShowMapContextMenu += new MapContextMenuHandler(_activeObject_ShowMapContextMenu);
_activeObject.ShowPushpinContextMenu += new MapPushpinContextMenuHandler(_activeObject_ShowPushpinContextMenu);
}
}
}
}
private void _activeObject_StyleChanged(object sender, EventArgs e)
{
OnMapStyleChanged(e);
}
private void _activeObject_ZoomLevelChanged(object sender, EventArgs e)
{
OnZoomLevelChanged(e);
}
private void _activeObject_PushpinAdded(VEPushpin pushpin)
{
OnPushpinAdded(pushpin);
}
private void _activeObject_PushpinRemoved(VEPushpin pushpin)
{
OnPushpinRemoved(pushpin);
}
private void _activeObject_BirdseyeChanged(object sender, EventArgs e)
{
OnBirdseyeChanged(e);
}
private void _activeObject_ShowMapContextMenu(MapContextMenuEvent e)
{
OnShowMapContextMenu(e);
}
private void _activeObject_ShowPushpinContextMenu(MapContextMenuEvent e, string pushpinId)
{
OnShowPushpinContextMenu(e, pushpinId);
}
}
}
| |
/*
* 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 IItemLegacyLowStockContactApi : IApiAccessor
{
#region Synchronous Operations
/// <summary>
/// Search itemLegacyLowStockContacts
/// </summary>
/// <remarks>
/// Returns the list of itemLegacyLowStockContacts that match the given searchText.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, 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>
/// <returns>List<ItemLegacyLowStockContact></returns>
List<ItemLegacyLowStockContact> GetItemLegacyLowStockContactBySearchText (string searchText = null, int? page = null, int? limit = null);
/// <summary>
/// Search itemLegacyLowStockContacts
/// </summary>
/// <remarks>
/// Returns the list of itemLegacyLowStockContacts that match the given searchText.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, 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>
/// <returns>ApiResponse of List<ItemLegacyLowStockContact></returns>
ApiResponse<List<ItemLegacyLowStockContact>> GetItemLegacyLowStockContactBySearchTextWithHttpInfo (string searchText = null, int? page = null, int? limit = null);
/// <summary>
/// Get an itemLegacyLowStockContact by id
/// </summary>
/// <remarks>
/// Returns the itemLegacyLowStockContact identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="itemLegacyLowStockContactId">Id of itemLegacyLowStockContact to be returned.</param>
/// <returns>ItemLegacyLowStockContact</returns>
ItemLegacyLowStockContact GetTranslateLowStockContactById (string itemLegacyLowStockContactId);
/// <summary>
/// Get an itemLegacyLowStockContact by id
/// </summary>
/// <remarks>
/// Returns the itemLegacyLowStockContact identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="itemLegacyLowStockContactId">Id of itemLegacyLowStockContact to be returned.</param>
/// <returns>ApiResponse of ItemLegacyLowStockContact</returns>
ApiResponse<ItemLegacyLowStockContact> GetTranslateLowStockContactByIdWithHttpInfo (string itemLegacyLowStockContactId);
#endregion Synchronous Operations
#region Asynchronous Operations
/// <summary>
/// Search itemLegacyLowStockContacts
/// </summary>
/// <remarks>
/// Returns the list of itemLegacyLowStockContacts that match the given searchText.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, 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>
/// <returns>Task of List<ItemLegacyLowStockContact></returns>
System.Threading.Tasks.Task<List<ItemLegacyLowStockContact>> GetItemLegacyLowStockContactBySearchTextAsync (string searchText = null, int? page = null, int? limit = null);
/// <summary>
/// Search itemLegacyLowStockContacts
/// </summary>
/// <remarks>
/// Returns the list of itemLegacyLowStockContacts that match the given searchText.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, 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>
/// <returns>Task of ApiResponse (List<ItemLegacyLowStockContact>)</returns>
System.Threading.Tasks.Task<ApiResponse<List<ItemLegacyLowStockContact>>> GetItemLegacyLowStockContactBySearchTextAsyncWithHttpInfo (string searchText = null, int? page = null, int? limit = null);
/// <summary>
/// Get an itemLegacyLowStockContact by id
/// </summary>
/// <remarks>
/// Returns the itemLegacyLowStockContact identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="itemLegacyLowStockContactId">Id of itemLegacyLowStockContact to be returned.</param>
/// <returns>Task of ItemLegacyLowStockContact</returns>
System.Threading.Tasks.Task<ItemLegacyLowStockContact> GetTranslateLowStockContactByIdAsync (string itemLegacyLowStockContactId);
/// <summary>
/// Get an itemLegacyLowStockContact by id
/// </summary>
/// <remarks>
/// Returns the itemLegacyLowStockContact identified by the specified id.
/// </remarks>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="itemLegacyLowStockContactId">Id of itemLegacyLowStockContact to be returned.</param>
/// <returns>Task of ApiResponse (ItemLegacyLowStockContact)</returns>
System.Threading.Tasks.Task<ApiResponse<ItemLegacyLowStockContact>> GetTranslateLowStockContactByIdAsyncWithHttpInfo (string itemLegacyLowStockContactId);
#endregion Asynchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public partial class ItemLegacyLowStockContactApi : IItemLegacyLowStockContactApi
{
private Infoplus.Client.ExceptionFactory _exceptionFactory = (name, response) => null;
/// <summary>
/// Initializes a new instance of the <see cref="ItemLegacyLowStockContactApi"/> class.
/// </summary>
/// <returns></returns>
public ItemLegacyLowStockContactApi(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="ItemLegacyLowStockContactApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public ItemLegacyLowStockContactApi(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 itemLegacyLowStockContacts Returns the list of itemLegacyLowStockContacts that match the given searchText.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, 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>
/// <returns>List<ItemLegacyLowStockContact></returns>
public List<ItemLegacyLowStockContact> GetItemLegacyLowStockContactBySearchText (string searchText = null, int? page = null, int? limit = null)
{
ApiResponse<List<ItemLegacyLowStockContact>> localVarResponse = GetItemLegacyLowStockContactBySearchTextWithHttpInfo(searchText, page, limit);
return localVarResponse.Data;
}
/// <summary>
/// Search itemLegacyLowStockContacts Returns the list of itemLegacyLowStockContacts that match the given searchText.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, 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>
/// <returns>ApiResponse of List<ItemLegacyLowStockContact></returns>
public ApiResponse< List<ItemLegacyLowStockContact> > GetItemLegacyLowStockContactBySearchTextWithHttpInfo (string searchText = null, int? page = null, int? limit = null)
{
var localVarPath = "/v1.0/itemLegacyLowStockContact/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 (searchText != null) localVarQueryParams.Add("searchText", Configuration.ApiClient.ParameterToString(searchText)); // 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
// 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("GetItemLegacyLowStockContactBySearchText", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<List<ItemLegacyLowStockContact>>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(List<ItemLegacyLowStockContact>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<ItemLegacyLowStockContact>)));
}
/// <summary>
/// Search itemLegacyLowStockContacts Returns the list of itemLegacyLowStockContacts that match the given searchText.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, 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>
/// <returns>Task of List<ItemLegacyLowStockContact></returns>
public async System.Threading.Tasks.Task<List<ItemLegacyLowStockContact>> GetItemLegacyLowStockContactBySearchTextAsync (string searchText = null, int? page = null, int? limit = null)
{
ApiResponse<List<ItemLegacyLowStockContact>> localVarResponse = await GetItemLegacyLowStockContactBySearchTextAsyncWithHttpInfo(searchText, page, limit);
return localVarResponse.Data;
}
/// <summary>
/// Search itemLegacyLowStockContacts Returns the list of itemLegacyLowStockContacts that match the given searchText.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="searchText">Search text, 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>
/// <returns>Task of ApiResponse (List<ItemLegacyLowStockContact>)</returns>
public async System.Threading.Tasks.Task<ApiResponse<List<ItemLegacyLowStockContact>>> GetItemLegacyLowStockContactBySearchTextAsyncWithHttpInfo (string searchText = null, int? page = null, int? limit = null)
{
var localVarPath = "/v1.0/itemLegacyLowStockContact/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 (searchText != null) localVarQueryParams.Add("searchText", Configuration.ApiClient.ParameterToString(searchText)); // 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
// 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("GetItemLegacyLowStockContactBySearchText", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<List<ItemLegacyLowStockContact>>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(List<ItemLegacyLowStockContact>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<ItemLegacyLowStockContact>)));
}
/// <summary>
/// Get an itemLegacyLowStockContact by id Returns the itemLegacyLowStockContact identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="itemLegacyLowStockContactId">Id of itemLegacyLowStockContact to be returned.</param>
/// <returns>ItemLegacyLowStockContact</returns>
public ItemLegacyLowStockContact GetTranslateLowStockContactById (string itemLegacyLowStockContactId)
{
ApiResponse<ItemLegacyLowStockContact> localVarResponse = GetTranslateLowStockContactByIdWithHttpInfo(itemLegacyLowStockContactId);
return localVarResponse.Data;
}
/// <summary>
/// Get an itemLegacyLowStockContact by id Returns the itemLegacyLowStockContact identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="itemLegacyLowStockContactId">Id of itemLegacyLowStockContact to be returned.</param>
/// <returns>ApiResponse of ItemLegacyLowStockContact</returns>
public ApiResponse< ItemLegacyLowStockContact > GetTranslateLowStockContactByIdWithHttpInfo (string itemLegacyLowStockContactId)
{
// verify the required parameter 'itemLegacyLowStockContactId' is set
if (itemLegacyLowStockContactId == null)
throw new ApiException(400, "Missing required parameter 'itemLegacyLowStockContactId' when calling ItemLegacyLowStockContactApi->GetTranslateLowStockContactById");
var localVarPath = "/v1.0/itemLegacyLowStockContact/{itemLegacyLowStockContactId}";
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 (itemLegacyLowStockContactId != null) localVarPathParams.Add("itemLegacyLowStockContactId", Configuration.ApiClient.ParameterToString(itemLegacyLowStockContactId)); // 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("GetTranslateLowStockContactById", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<ItemLegacyLowStockContact>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ItemLegacyLowStockContact) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ItemLegacyLowStockContact)));
}
/// <summary>
/// Get an itemLegacyLowStockContact by id Returns the itemLegacyLowStockContact identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="itemLegacyLowStockContactId">Id of itemLegacyLowStockContact to be returned.</param>
/// <returns>Task of ItemLegacyLowStockContact</returns>
public async System.Threading.Tasks.Task<ItemLegacyLowStockContact> GetTranslateLowStockContactByIdAsync (string itemLegacyLowStockContactId)
{
ApiResponse<ItemLegacyLowStockContact> localVarResponse = await GetTranslateLowStockContactByIdAsyncWithHttpInfo(itemLegacyLowStockContactId);
return localVarResponse.Data;
}
/// <summary>
/// Get an itemLegacyLowStockContact by id Returns the itemLegacyLowStockContact identified by the specified id.
/// </summary>
/// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="itemLegacyLowStockContactId">Id of itemLegacyLowStockContact to be returned.</param>
/// <returns>Task of ApiResponse (ItemLegacyLowStockContact)</returns>
public async System.Threading.Tasks.Task<ApiResponse<ItemLegacyLowStockContact>> GetTranslateLowStockContactByIdAsyncWithHttpInfo (string itemLegacyLowStockContactId)
{
// verify the required parameter 'itemLegacyLowStockContactId' is set
if (itemLegacyLowStockContactId == null)
throw new ApiException(400, "Missing required parameter 'itemLegacyLowStockContactId' when calling ItemLegacyLowStockContactApi->GetTranslateLowStockContactById");
var localVarPath = "/v1.0/itemLegacyLowStockContact/{itemLegacyLowStockContactId}";
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 (itemLegacyLowStockContactId != null) localVarPathParams.Add("itemLegacyLowStockContactId", Configuration.ApiClient.ParameterToString(itemLegacyLowStockContactId)); // 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("GetTranslateLowStockContactById", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<ItemLegacyLowStockContact>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(ItemLegacyLowStockContact) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ItemLegacyLowStockContact)));
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using Network;
using UnityEngine;
using Pluton.Events;
using System.Reactive.Subjects;
using System.Collections.Generic;
using Steamworks;
namespace Pluton
{
public class Hook : CountedInstance
{
~Hook()
{
if (hook != null)
hook.Dispose();
}
public Hook(string method, Action<object[]> callback)
{
if (Hooks.HookNames.Contains(method))
hook = Hooks.Subjects[method].Subscribe(callback);
else
throw new Exception($"Can't find the hook '{method}' to subscribe to.");
Name = method;
}
public string Name;
public IDisposable hook;
}
public class Hooks
{
static internal List<string> HookNames = new List<string>() {
"On_AllPluginsLoaded",
"On_BeingHammered",
"On_BuildingComplete",
"On_BuildingPartDemolished",
"On_BuildingPartDestroyed",
"On_BuildingPartGradeChange",
"On_Chat",
"On_ClientAuth",
"On_ClientConsole",
"On_CombatEntityHurt",
"On_Command",
"On_CommandPermission",
"On_ConsumeFuel",
"On_CorpseHurt",
"On_DoorCode",
"On_DoorUse",
"On_EventTriggered",
"On_ItemAdded",
"On_ItemLoseCondition",
"On_ItemPickup",
"On_ItemRemoved",
"On_ItemRepaired",
"On_ItemUsed",
"On_LandmineArmed",
"On_LandmineExploded",
"On_LandmineTriggered",
"On_LootingEntity",
"On_LootingItem",
"On_LootingPlayer",
"On_NetworkableKill",
"On_NPCHurt",
"On_NPCKilled",
"On_Placement",
"On_PlayerAssisted",
"On_PlayerClothingChanged",
"On_PlayerConnected",
"On_PlayerDied",
"On_PlayerDisconnected",
"On_PlayerGathering",
"On_PlayerHurt",
"On_PlayerLoaded",
"On_PlayerSleep",
"On_PlayerStartCrafting",
"On_PlayerSyringeOther",
"On_PlayerSyringeSelf",
"On_PlayerHealthChange",
"On_PlayerTakeRadiation",
"On_PlayerWakeUp",
"On_PlayerWounded",
"On_QuarryMining",
"On_Respawn",
"On_RocketShooting",
"On_Shooting",
"On_ServerConsole",
"On_ServerInit",
"On_ServerSaved",
"On_ServerShutdown",
"On_WeaponThrow"
};
static internal Dictionary<string, Subject<object[]>> Subjects = new Dictionary<string, Subject<object[]>>();
public static Dictionary<string, Subject<object[]>> CreateOrUpdateSubjects()
{
for (int i = 0; i < HookNames.Count; i++) {
string hookName = HookNames[i];
if (!Subjects.ContainsKey(hookName))
Subjects.Add(hookName, new Subject<object[]>());
}
return Subjects;
}
static internal void OnNext(string hook, params object[] args)
{
Subjects[hook].OnNext(args);
}
public static Hook Subscribe(string hookname, Action<object[]> callback)
{
return new Hook(hookname, callback);
}
public static Hook Subscribe(string hookname, BasePlugin plugin)
{
return new Hook(hookname, args => plugin.Invoke(hookname, args));
}
#region Handlers
[Documentation.Doq(
typeof(ChatEvent),
category = Documentation.DoqCategory.Pluton_Hooks,
doqType = Documentation.DoqType.Hook,
description = "Gets called when the user enters something in the chat and it doesn't start with '/'."
)]
public static void On_Chat(ConsoleSystem.Arg arg)
{
if (arg.ArgsStr.StartsWith("\"/") && !arg.ArgsStr.StartsWith("\"/ ")) {
On_Command(arg);
return;
}
if (!ConVar.Chat.enabled) {
arg.ReplyWith("Chat is disabled.");
} else {
if (arg.ArgsStr == "\"\"") {
return;
}
BasePlayer basePlayer = arg.Player();
if (!basePlayer) {
return;
}
ChatEvent pChat = new ChatEvent(Server.GetPlayer(basePlayer), arg);
string str = arg.GetString(0, "text");
if (str.Length > 128)
str = str.Substring(0, 128);
if (str.Length <= 0)
return;
if (ConVar.Chat.serverlog) {
ServerConsole.PrintColoured(new object[] {
ConsoleColor.DarkYellow,
basePlayer.displayName + ": ",
ConsoleColor.DarkGreen,
str
});
ConVar.Server.Log("Log.Chat.txt", string.Format("{0}/{1}: {2}\r\n", basePlayer.userID, basePlayer.displayName, str));
Debug.Log(string.Format("[CHAT] {0}: {1}", basePlayer.displayName, str));
}
string arg2 = "#5af";
if (basePlayer.IsAdmin()) {
arg2 = "#af5";
}
if (DeveloperList.IsDeveloper(basePlayer)) {
arg2 = "#fa5";
}
OnNext("On_Chat", pChat);
string text2 = string.Format("<color={2}>{0}</color>: {1}", basePlayer.displayName.Replace('<', '[').Replace('>', ']'), pChat.FinalText, arg2);
if (pChat.FinalText != "") {
Logger.ChatLog(pChat.BroadcastName, pChat.OriginalText);
arg.ReplyWith(pChat.Reply);
if (ConVar.Server.globalchat) {
ConsoleSystem.Broadcast("chat.add", basePlayer.userID, text2, 1);
} else {
float num = 2500;
foreach (Connection current in Net.sv.connections) {
if (current.player != null) {
float sqrMagnitude = (current.player.transform.position - basePlayer.transform.position).sqrMagnitude;
if (sqrMagnitude <= num) {
ConsoleSystem.SendClientCommand(current, "chat.add", basePlayer.userID, text2, Mathf.Clamp01(num - sqrMagnitude + 0.2f));
}
}
}
}
}
}
}
// ConnectionAuth.Approve()
public static void On_ClientAuth(ConnectionAuth ca, Connection connection)
{
var ae = new Events.AuthEvent(connection);
OnNext("On_ClientAuth", ae);
ConnectionAuth.m_AuthConnection.Remove(connection);
if (!ae.Approved) {
ConnectionAuth.Reject(connection, ae.Reason);
return;
}
SingletonComponent<ServerMgr>.Instance.ConnectionApproved(connection);
}
// ConsoleSystem.OnClientCommand()
public static void On_ClientConsole(ConsoleSystem.Arg arg, String rconCmd)
{
ClientConsoleEvent ce = new ClientConsoleEvent(arg, rconCmd);
if (arg.connection != null) {
OnNext("On_ClientConsole", ce);
if (arg.Invalid) {
if (!Net.sv.IsConnected()) {
return;
}
Net.sv.write.Start();
Net.sv.write.PacketID(Message.Type.ConsoleMessage);
Net.sv.write.String(ce.Reply);
Net.sv.write.Send(new SendInfo(arg.connection));
} else {
arg.ReplyWith(ce.Reply);
}
}
}
// chat.say().Hooks.Chat()
public static void On_Command(ConsoleSystem.Arg arg)
{
Player player = Server.GetPlayer(arg.Player());
string[] args = arg.ArgsStr.Substring(2, arg.ArgsStr.Length - 3).Replace("\\", "").Split(new string[] { " " }, StringSplitOptions.None);
CommandEvent cmd = new CommandEvent(player, args);
// TODO: do this part in a different function to be documented
if (cmd.Cmd == "")
return;
foreach (KeyValuePair<string, BasePlugin> pl in PluginLoader.GetInstance().Plugins) {
ChatCommand[] commands = pl.Value.chatCommands.getChatCommands(cmd.Cmd);
foreach (ChatCommand chatCmd in commands) {
if (chatCmd.callback == null)
continue;
CommandPermissionEvent permission = new CommandPermissionEvent(player, args, chatCmd);
OnNext("On_CommandPermission", permission);
if (permission.Blocked) {
player.Message(permission.Reply);
continue;
}
try {
chatCmd.callback(cmd.Args, player);
} catch (Exception ex) {
Logger.LogError(chatCmd.plugin.FormatException(ex));
}
}
}
OnNext("On_Command", cmd);
if (cmd.Reply != "")
arg.ReplyWith(cmd.Reply);
}
public static void On_Shooting(BaseProjectile baseProjectile, BaseEntity.RPCMessage msg)
{
OnNext("On_Shooting", new ShootEvent(baseProjectile, msg));
}
public static void On_ItemUsed(Item item, int amountToConsume)
{
OnNext("On_ItemUsed", new ItemUsedEvent(item, amountToConsume));
}
public static void On_QuarryMining(MiningQuarry miningQuarry)
{
OnNext("On_QuarryMining", miningQuarry);
}
public static void On_WeaponThrow(ThrownWeapon thrownWeapon, BaseEntity.RPCMessage msg)
{
OnNext("On_WeaponThrow", new WeaponThrowEvent(thrownWeapon, msg));
}
public static void On_RocketShooting(BaseLauncher baseLauncher, BaseEntity.RPCMessage msg, BaseEntity baseEntity)
{
OnNext("On_RocketShooting", new RocketShootEvent(baseLauncher, msg, baseEntity));
}
public static void On_ItemPickup(CollectibleEntity ce, BaseEntity.RPCMessage msg, Item i)
{
OnNext("On_ItemPickup", new ItemPickupEvent(ce, msg, i));
}
public static void On_ConsumeFuel(BaseOven bo, Item fuel, ItemModBurnable burn)
{
OnNext("On_ConsumeFuel", new ConsumeFuelEvent(bo, fuel, burn));
}
public static void On_PlayerSleep(BasePlayer bp)
{
OnNext("On_PlayerSleep", Server.GetPlayer(bp));
}
public static void On_PlayerWakeUp(BasePlayer bp)
{
OnNext("On_PlayerWakeUp", Server.GetPlayer(bp));
}
public static void On_PlayerLoaded(BasePlayer bp)
{
OnNext("On_PlayerLoaded", Server.GetPlayer(bp));
}
public static void On_PlayerWounded(BasePlayer bp)
{
OnNext("On_PlayerWounded", Server.GetPlayer(bp));
}
public static void On_PlayerAssisted(BasePlayer bp)
{
OnNext("On_PlayerAssisted", Server.GetPlayer(bp));
}
public static void On_ItemRepaired(RepairBench rb, BaseEntity.RPCMessage msg)
{
OnNext("On_ItemRepaired", new ItemRepairEvent(rb, msg));
}
public static void On_PlayerSyringeSelf(SyringeWeapon sw, BaseEntity.RPCMessage msg)
{
OnNext("On_PlayerSyringeSelf", new SyringeUseEvent(sw, msg, true));
}
public static void On_PlayerSyringeOther(SyringeWeapon sw, BaseEntity.RPCMessage msg)
{
OnNext("On_PlayerSyringeOther", new SyringeUseEvent(sw, msg, false));
}
public static void On_PlayerHealthChange(BasePlayer p, float f, float f2)
{
OnNext("On_PlayerHealthChange", new PlayerHealthChangeEvent(p, f, f2));
}
public static void On_ItemAdded(ItemContainer ic, Item i)
{
OnNext("On_ItemAdded", new InventoryModEvent(ic, i));
}
public static void On_ItemRemoved(ItemContainer ic, Item i)
{
OnNext("On_ItemRemoved", new InventoryModEvent(ic, i));
}
public static void On_ItemLoseCondition(Item i, float f)
{
OnNext("On_ItemLoseCondition", new ItemConditionEvent(i, f));
}
public static void On_PlayerClothingChanged(PlayerInventory pi, Item i)
{
OnNext("On_PlayerClothingChanged", new PlayerClothingEvent(pi, i));
}
public static void On_BuildingPartDemolished(BuildingBlock bb, BaseEntity.RPCMessage msg)
{
OnNext("On_BuildingPartDemolished", new BuildingPartDemolishedEvent(bb, msg.player));
}
public static void On_NetworkableKill(BaseNetworkable bn)
{
OnNext("On_NetworkableKill", bn);
}
public static void On_BeingHammered(HitInfo info, BasePlayer ownerPlayer)
{
OnNext("On_BeingHammered", new HammerEvent(info, ownerPlayer));
}
public static void On_EventTriggered(TriggeredEventPrefab tep)
{
EventTriggeredEvent ete = new EventTriggeredEvent(tep);
OnNext("On_EventTriggered", ete);
if (ete.Stop) return;
Debug.Log("[event] " + ete.Prefab);
BaseEntity baseEntity = GameManager.server.CreateEntity(ete.Prefab);
if (baseEntity) baseEntity.Spawn();
}
public static void On_BuildingPartGradeChange(BuildingBlock bb, BaseEntity.RPCMessage msg)
{
BuildingGrade.Enum bgrade = (BuildingGrade.Enum)msg.read.Int32();
BasePlayer player = msg.player;
BuildingPartGradeChangeEvent bpgce = new BuildingPartGradeChangeEvent(bb, bgrade, player);
OnNext("On_BuildingPartGradeChange", bpgce);
ConstructionGrade cg = (ConstructionGrade)bb.CallMethod("GetGrade", bpgce.Grade);
if (bpgce.DoDestroy) {
bpgce.Builder.Message(bpgce.DestroyReason);
UnityEngine.Object.Destroy(bb);
return;
}
if (cg == null) return;
if (!bpgce.HasPrivilege) return;
if (bpgce.PayForUpgrade && !(bool)bb.CallMethod("CanAffordUpgrade", bpgce.Grade, player)) return;
if (bb.TimeSinceAttacked() < 8f) return;
if (bpgce.PayForUpgrade) bb.CallMethod("PayForUpgrade", cg, player);
bb.SetGrade(bpgce.Grade);
bb.SetHealthToMax();
if (bpgce.Rotatable) bb.CallMethod("StartBeingRotatable");
bb.SendNetworkUpdate();
bb.CallMethod("UpdateSkin", false);
Effect.server.Run("assets/bundled/prefabs/fx/build/promote_" + bpgce.Grade.ToString().ToLower() + ".prefab", bb, 0u, Vector3.zero, Vector3.zero);
}
public static void On_CombatEntityHurt(BaseCombatEntity combatEnt, HitInfo info, bool useProtection = true)
{
try {
Assert.Test(combatEnt.isServer, "This should be called serverside only");
if (combatEnt.IsDead()) return;
using (TimeWarning.New("Hurt", 50)) {
BaseNPC npc = combatEnt.GetComponent<BaseNPC>();
BaseCorpse corpse = combatEnt.GetComponent<BaseCorpse>();
BasePlayer player = combatEnt.GetComponent<BasePlayer>();
combatEnt.ScaleDamage(info, useProtection);
HurtEvent he;
if (player != null) {
Player p = Server.GetPlayer(player);
if (p.Teleporting) {
for (int i = 0; i < info.damageTypes.types.Length; i++) {
info.damageTypes.types[i] = 0f;
}
}
he = new PlayerHurtEvent(p, info);
OnNext("On_PlayerHurt", he);
} else if (npc != null) {
he = new NPCHurtEvent(new NPC(npc), info);
OnNext("On_NPCHurt", he);
} else if (corpse != null) {
he = new CorpseHurtEvent(corpse, info);
OnNext("On_CorpseHurt", he);
} else {
he = new CombatEntityHurtEvent(combatEnt, info);
OnNext("On_CombatEntityHurt", he);
}
if (info.PointStart != Vector3.zero) {
DirectionProperties[] directionProperties = (DirectionProperties[])combatEnt.GetFieldValue("propDirection");
for (int i = 0; i < directionProperties.Length; i++) {
if (!(directionProperties[i].extraProtection == null)) {
if (directionProperties[i].IsPointWithinRadius(combatEnt.transform, info.PointStart)) {
directionProperties[i].extraProtection.Scale(info.damageTypes);
}
}
}
}
// the DebugHurt() method
if (ConVar.Vis.attack) {
if (info.PointStart != info.PointEnd) {
ConsoleSystem.Broadcast("ddraw.arrow", new object[] {
60, Color.cyan, info.PointStart, info.PointEnd, 0.1
});
ConsoleSystem.Broadcast("ddraw.sphere", new object[] {
60, Color.cyan, info.HitPositionWorld, 0.05
});
}
string text = String.Empty;
for (int i = 0; i < info.damageTypes.types.Length; i++) {
float num = info.damageTypes.types[i];
if (num != 0) {
string text2 = text;
text = String.Concat(new string[] {
text2, " ", ((Rust.DamageType)i).ToString().PadRight(10), num.ToString("0.00"), "\r\n"
});
}
}
string text3 = String.Concat(new object[] {
"<color=lightblue>Damage:</color>".PadRight(10),
info.damageTypes.Total().ToString("0.00"),
"\r\n<color=lightblue>Health:</color>".PadRight(10),
combatEnt.health.ToString("0.00"), " / ",
(combatEnt.health - info.damageTypes.Total() > 0) ? "<color=green>" : "<color=red>",
(combatEnt.health - info.damageTypes.Total()).ToString("0.00"), "</color>",
"\r\n<color=lightblue>Hit Ent:</color>".PadRight(10), combatEnt,
"\r\n<color=lightblue>Attacker:</color>".PadRight(10), info.Initiator,
"\r\n<color=lightblue>Weapon:</color>".PadRight(10), info.Weapon,
"\r\n<color=lightblue>Damages:</color>\r\n", text
});
ConsoleSystem.Broadcast("ddraw.text", new object[] {
60, Color.white, info.HitPositionWorld, text3
});
}
combatEnt.health -= info.damageTypes.Total();
combatEnt.SendNetworkUpdate(BasePlayer.NetworkQueue.Update);
if (ConVar.Global.developer > 1) {
Debug.Log(string.Concat(new object[]
{
"[Combat]".PadRight(10),
combatEnt.gameObject.name,
" hurt ",
info.damageTypes.GetMajorityDamageType(),
"/",
info.damageTypes.Total(),
" - ",
combatEnt.health.ToString("0"),
" health left"
}));
}
combatEnt.lastDamage = info.damageTypes.GetMajorityDamageType();
combatEnt.lastAttacker = info.Initiator;
combatEnt.SetFieldValue("_lastAttackedTime", Time.time);
if (combatEnt.health <= 0f) {
combatEnt.Die(info);
BuildingBlock bb = combatEnt.GetComponent<BuildingBlock>();
if (bb != null)
{
OnNext("On_BuildingPartDestroyed", new BuildingPartDestroyedEvent(bb, info));
}
}
}
} catch (Exception ex) {
Logger.LogError("[Hooks] Error in CombatEntityHurt hook.");
Logger.LogException(ex);
}
}
public static void On_DoorCode(CodeLock doorLock, BaseEntity.RPCMessage rpc)
{
if (!doorLock.IsLocked())
return;
string code = rpc.read.String();
DoorCodeEvent dc = new DoorCodeEvent(doorLock, rpc.player, code);
OnNext("On_DoorCode", dc);
if ((!dc.IsCorrect() || !dc.allowed) && !dc.forceAllow)
{
Effect.server.Run(doorLock.effectDenied.resourcePath, doorLock, 0u, Vector3.zero, Vector3.forward);
rpc.player.Hurt(1f, Rust.DamageType.ElectricShock, doorLock, true);
return;
}
Effect.server.Run(doorLock.effectUnlocked.resourcePath, doorLock, 0u, Vector3.zero, Vector3.forward);
doorLock.SetFlag(BaseEntity.Flags.Locked, false);
doorLock.SendNetworkUpdate(BasePlayer.NetworkQueue.Update);
List<ulong> whitelist = new List<ulong>();
whitelist = (List<ulong>)doorLock.GetFieldValue("whitelistPlayers");
if (!whitelist.Contains(rpc.player.userID))
{
whitelist.Add(rpc.player.userID);
doorLock.SetFieldValue("whitelistPlayers", whitelist);
}
}
public static void On_LandmineArmed(Landmine l)
{
OnNext("On_LandmineArmed", l);
}
public static void On_LandmineExploded(Landmine l)
{
OnNext("On_LandmineExploded", l);
}
public static void On_LandmineTriggered(Landmine landmine, BasePlayer basePlayer)
{
LandmineTriggerEvent landmineTriggerEvent = new LandmineTriggerEvent(landmine, basePlayer);
OnNext("On_LandmineTriggered", landmineTriggerEvent);
if (landmineTriggerEvent.Explode)
{
if (basePlayer != null)
landmine.SetFieldValue("triggerPlayerID", basePlayer.userID);
landmine.SetFlag(BaseEntity.Flags.Open, true);
landmine.SendNetworkUpdate(BasePlayer.NetworkQueue.Update);
}
}
// Door.RPC_CloseDoor()/RPC_OpenDoor()
public static void On_DoorUse(Door door, BaseEntity.RPCMessage rpc, bool open)
{
if ((open && door.IsOpen()) || (!open && !door.IsOpen()))
return;
DoorUseEvent due = new DoorUseEvent(new Entity(door), Server.GetPlayer(rpc.player), open);
OnNext("On_DoorUse", due);
if (!due.Allow) {
if (due.DenyReason != "")
rpc.player.SendConsoleCommand("chat.add", 0, String.Format("{0}: {1}", Server.server_message_name.ColorText("fa5"), due.DenyReason));
return;
}
bool doaction = true;
BaseLock baseLock = door.GetSlot(BaseEntity.Slot.Lock) as BaseLock;
if (!due.IgnoreLock && baseLock != null) {
doaction = open ? baseLock.OnTryToOpen(rpc.player) : baseLock.OnTryToClose(rpc.player);
if (doaction && open && (baseLock.IsLocked() && Time.realtimeSinceStartup - (float)door.GetFieldValue("decayResetTimeLast") > 60)) {
Decay.RadialDecayTouch (door.transform.position, 40, 270532608);
door.SetFieldValue("decayResetTimeLast", Time.realtimeSinceStartup);
}
}
if (doaction) {
door.SetFlag(BaseEntity.Flags.Open, open);
door.SendNetworkUpdateImmediate (false);
door.CallMethod("UpdateDoorAnimationParameters", false);
}
}
// Construiction.Common.CreateConstruction()
public static BaseEntity On_Placement(Construction construction, Construction.Target target, bool bNeedsValidPlacement)
{
try {
GameObject gameObject = GameManager.server.CreatePrefab(construction.fullName, default(Vector3), default(Quaternion), true);
BuildingBlock component = gameObject.GetComponent<BuildingBlock>();
bool flag = construction.UpdatePlacement(gameObject.transform, construction, target);
if (bNeedsValidPlacement && !flag) {
UnityEngine.Object.Destroy(gameObject);
return null;
}
BuildingEvent be = null;
if (component != null) {
be = new BuildingEvent(construction, target, component, bNeedsValidPlacement);
OnNext("On_Placement", be);
}
if (be != null && be.DoDestroy) {
be.Builder.Message(be.DestroyReason);
UnityEngine.Object.Destroy(gameObject);
return null;
}
return gameObject.GetComponent<BaseEntity>();
} catch (Exception ex) {
Logger.LogException(ex);
return null;
}
}
public static void On_PlayerGathering(ResourceDispenser dispenser, BaseEntity to, ItemAmount itemAmt, float gatherDamage, float destroyFraction)
{
BaseEntity from = (BaseEntity)dispenser.GetFieldValue("baseEntity");
if (itemAmt.amount == 0) {
return;
}
float num = gatherDamage / from.MaxHealth ();
float num2 = itemAmt.startAmount / (float)dispenser.GetFieldValue("startingItemCounts");
float value = itemAmt.startAmount * num / num2;
float num3 = Mathf.Clamp (value, 0, itemAmt.amount);
float num4 = num3 * destroyFraction * 2;
if (itemAmt.amount < num3 + num4) {
itemAmt.amount -= destroyFraction * num3;
num3 = itemAmt.amount;
num4 = 0;
}
float amount = itemAmt.amount;
itemAmt.amount -= num3;
if (itemAmt.amount < 0) {
itemAmt.amount = 0;
}
int num5 = Mathf.Clamp (Mathf.RoundToInt (num3), 0, Mathf.CeilToInt (amount));
itemAmt.amount -= num4;
if (itemAmt.amount < 0) {
itemAmt.amount = 0;
}
GatherEvent ge = new GatherEvent(dispenser, from, to, itemAmt, num5);
OnNext("On_PlayerGathering", ge);
if (ge.Amount <= 0) {
return;
}
Item item = ItemManager.CreateByItemID (itemAmt.itemid, ge.Amount);
if (item == null) {
return;
}
to.GiveItem (item, BaseEntity.GiveItemReason.ResourceHarvested);
}
// BaseAnimal.Die()
public static void On_NPCKilled(BaseNPC bnpc, HitInfo info)
{
if (info.Initiator != null && info.Initiator.ToPlayer() != null) {
Server.GetPlayer(info.Initiator as BasePlayer).Stats.AddKill(false, true);
}
var npc = new NPC(bnpc);
OnNext("On_NPCKilled", new Events.NPCDeathEvent(npc, info));
}
// ItemCrafter.CraftItem()
public static bool On_PlayerStartCrafting(ItemCrafter self, ItemBlueprint bp, BasePlayer owner, ProtoBuf.Item.InstanceData instanceData = null, int amount = 1, int skinID = 0)
{
CraftEvent ce = new CraftEvent(self, bp, owner, instanceData, amount, skinID);
OnNext("On_PlayerStartCrafting", ce);
if (!self.CanCraft(bp, ce.Amount))
return false;
if (ce.Cancel) {
if (ce.cancelReason != String.Empty) ce.Crafter.Message(ce.cancelReason);
return false;
}
self.taskUID++;
ItemCraftTask itemCraftTask = Facepunch.Pool.Get<ItemCraftTask>();
itemCraftTask.blueprint = bp;
self.CallMethod("CollectIngredients", bp, ce.Amount, owner);
itemCraftTask.endTime = 0;
itemCraftTask.taskUID = self.taskUID;
itemCraftTask.owner = owner;
itemCraftTask.instanceData = instanceData;
if (itemCraftTask.instanceData != null) {
itemCraftTask.instanceData.ShouldPool = false;
}
itemCraftTask.amount = ce.Amount;
itemCraftTask.skinID = ce.SkinID;
self.queue.Enqueue(itemCraftTask);
if (itemCraftTask.owner != null) {
itemCraftTask.owner.Command("note.craft_add", new object[] {
itemCraftTask.taskUID,
itemCraftTask.blueprint.targetItem.itemid,
amount
});
}
return true;
}
// BasePlayer.Die()
public static void On_PlayerDied(BasePlayer player, HitInfo info)
{
using (TimeWarning.New("Player.Die", 0.1f))
{
if (!player.IsDead())
{
if (info == null)
{
info = new HitInfo();
info.damageTypes.Add(player.lastDamage, Single.MaxValue);
info.Initiator = player as BaseEntity;
}
Player victim = Server.GetPlayer(player);
if (!((bool)player.CallMethod("WoundInsteadOfDying", info)))
{
var pde = new PlayerDeathEvent(victim, info);
OnNext("On_PlayerDied", pde);
if (pde.Die)
{
if (info.Initiator != null)
{
PlayerStats statsV = victim.Stats;
if (info.Initiator is BasePlayer)
{
Server.GetPlayer(info.Initiator as BasePlayer).Stats.AddKill(true, false);
victim.Stats.AddDeath(true, false);
}
else if (info.Initiator is BaseNPC)
{
victim.Stats.AddDeath(false, true);
}
}
if (!pde.dropLoot)
{
if (player.belt != null)
{
var vector = new Vector3(UnityEngine.Random.Range(-2f, 2f), 0.2f, UnityEngine.Random.Range(-2f, 2f));
player.belt.DropActive(vector.normalized * 3f);
}
player.inventory.Strip();
}
player.CallMethodOnBase(typeof(BaseCombatEntity), "Die", info);
}
}
}
}
}
public static void On_PlayerConnected(BasePlayer player)
{
var p = new Player(player);
if (Server.GetInstance().OfflinePlayers.ContainsKey(player.userID))
Server.GetInstance().OfflinePlayers.Remove(player.userID);
if (!Server.GetInstance().Players.ContainsKey(player.userID))
Server.GetInstance().Players.Add(player.userID, p);
OnNext("On_PlayerConnected", p);
}
// BasePlayer.OnDisconnected()
public static void On_PlayerDisconnected(BasePlayer player)
{
var p = Server.GetPlayer(player);
if (Server.GetInstance().serverData.ContainsKey("OfflinePlayers", p.SteamID)) {
OfflinePlayer op = (Server.GetInstance().serverData.Get("OfflinePlayers", p.SteamID) as OfflinePlayer);
op.Update(p);
Server.GetInstance().OfflinePlayers[player.userID] = op;
} else {
OfflinePlayer op = new OfflinePlayer(p);
Server.GetInstance().OfflinePlayers.Add(player.userID, op);
}
if (Server.GetInstance().Players.ContainsKey(player.userID))
Server.GetInstance().Players.Remove(player.userID);
OnNext("On_PlayerDisconnected", p);
}
// BasePlayer.UpdateRadiation()
public static void On_PlayerTakeRadiation(BasePlayer player, float radAmount)
{
var ptr = new PlayerTakeRadsEvent(Server.GetPlayer(player), player.metabolism.radiation_level.value, radAmount);
OnNext("On_PlayerTakeRadiation", ptr);
player.metabolism.radiation_level.value = ptr.Next;
}
public static void On_Respawn(BasePlayer player, Vector3 pos, Quaternion quat)
{
Player p = Server.GetPlayer(player);
RespawnEvent re = new RespawnEvent(p, pos, quat);
OnNext("On_Respawn", re);
++ServerPerformance.spawns;
player.SetFieldValue("lastPositionValue", pos);
player.transform.position = re.SpawnPos;
player.transform.rotation = re.SpawnRot;
player.SetPlayerFlag(BasePlayer.PlayerFlags.Wounded, false);
player.SetPlayerFlag(BasePlayer.PlayerFlags.ReceivingSnapshot, true);
player.SetFieldValue("lastTickTime", 0f);
player.CancelInvoke("WoundingEnd");
player.StopSpectating();
player.UpdateNetworkGroup();
player.UpdatePlayerCollider(true, false);
player.StartSleeping();
player.Invoke("LifeStoryStart", 0f);
player.metabolism.Reset();
if (re.StartHealth < Single.Epsilon) {
player.InitializeHealth(player.StartHealth(), player.StartMaxHealth());
} else {
player.InitializeHealth(re.StartHealth, player.StartMaxHealth());
}
if (re.GiveDefault)
player.inventory.GiveDefaultItems();
if (re.WakeUp)
player.EndSleeping();
player.SendNetworkUpdateImmediate(false);
player.ClientRPCPlayer(null, player, "StartLoading");
player.SendFullSnapshot ();
player.SetPlayerFlag (BasePlayer.PlayerFlags.ReceivingSnapshot, false);
player.ClientRPCPlayer(null, player, "FinishLoading");
}
// PlayerLoot.StartLootingEntity()
public static void On_LootingEntity(PlayerLoot playerLoot)
{
BasePlayer looter = playerLoot.GetComponent<BasePlayer>();
var ele = new Events.EntityLootEvent(playerLoot, Server.GetPlayer(looter), new Entity(playerLoot.entitySource));
OnNext("On_LootingEntity", ele);
if (ele.Cancel) {
playerLoot.Clear();
looter.SendConsoleCommand("chat.add", 0, String.Format("{0}: {1}", Server.server_message_name.ColorText("fa5"), ele.cancelReason));
}
}
// PlayerLoot.StartLootingPlayer()
public static void On_LootingPlayer(PlayerLoot playerLoot)
{
BasePlayer looter = playerLoot.GetComponent<BasePlayer>();
var ple = new Events.PlayerLootEvent(playerLoot, Server.GetPlayer(looter), Server.GetPlayer(playerLoot.entitySource as BasePlayer));
OnNext("On_LootingPlayer", ple);
if (ple.Cancel) {
playerLoot.Clear();
looter.SendConsoleCommand("chat.add", 0, String.Format("{0}: {1}", Server.server_message_name.ColorText("fa5"), ple.cancelReason));
}
}
// PlayerLoot.StartLootingItem()
public static void On_LootingItem(PlayerLoot playerLoot)
{
BasePlayer looter = playerLoot.GetComponent<BasePlayer>();
var ile = new Events.ItemLootEvent(playerLoot, Server.GetPlayer(looter), playerLoot.itemSource);
OnNext("On_LootingItem", ile);
if (ile.Cancel) {
playerLoot.Clear();
looter.SendConsoleCommand("chat.add", 0, String.Format("{0}: {1}", Server.server_message_name.ColorText("fa5"), ile.cancelReason));
}
}
// ConsoleSystem.SystemRealm.Normal
public static void On_ServerConsole(ConsoleSystem.Arg arg, string cmd)
{
try {
if (!Bootstrap.PlutonLoaded)
return;
ServerConsoleEvent ssc = new ServerConsoleEvent(arg, cmd);
foreach (KeyValuePair<string, BasePlugin> pl in PluginLoader.GetInstance().Plugins) {
ConsoleCommand[] commands = pl.Value.consoleCommands.getConsoleCommands(ssc.cmd);
foreach (ConsoleCommand cc in commands) {
if (cc.callback == null)
continue;
try {
cc.callback(arg.ArgsStr.Split(' '));
} catch (Exception ex) {
Logger.LogError(cc.plugin.FormatException(ex));
}
}
}
OnNext("On_ServerConsole", ssc);
if (arg.Invalid) {
Debug.Log(ssc.Reply);
}
} catch (Exception ex) {
Logger.LogException(ex);
}
}
public static void On_ServerInit()
{
Server.GetInstance().SendCommand("plugins.loaded");
if (Server.GetInstance().Loaded)
return;
Server.GetInstance().Loaded = true;
OnNext("On_ServerInit");
}
public static void On_ServerSaved()
{
OnNext("On_ServerSaved");
}
public static void On_ServerShutdown()
{
Bootstrap.timers.Dispose();
OnNext("On_ServerShutdown");
PluginLoader.GetInstance().UnloadPlugins();
Bootstrap.SaveAll();
}
public static void SetModded()
{
try {
using (TimeWarning.New ("UpdateServerInformation", 0.1f)) {
SteamGameServer.SetServerName(ConVar.Server.hostname);
SteamGameServer.SetMaxPlayerCount(ConVar.Server.maxplayers);
SteamGameServer.SetPasswordProtected(false);
SteamGameServer.SetMapName(UnityEngine.SceneManagement.SceneManager.GetActiveScene().name);
string pchGameTags = string.Format("mp{0},cp{1},v{2}{3}{4}", new object[] {
ConVar.Server.maxplayers,
BasePlayer.activePlayerList.Count,
Rust.Protocol.network,
ConVar.Server.pve ? ",pve" : string.Empty,
pluton.enabled ? ",modded,pluton" : string.Empty
});
SteamGameServer.SetGameTags(pchGameTags);
string[] array = ConVar.Server.description.SplitToChunks(100).ToArray<string>();
for (int i = 0; i < 16; i++) {
if (i < array.Length) {
SteamGameServer.SetKeyValue(string.Format("description_{0:00}", i), array[i]);
}
else {
SteamGameServer.SetKeyValue(string.Format("description_{0:00}", i), String.Empty);
}
}
SteamGameServer.SetKeyValue("country", SteamGameServerUtils.GetIPCountry());
SteamGameServer.SetKeyValue("world.seed", global::World.Seed.ToString());
SteamGameServer.SetKeyValue("world.size", global::World.Size.ToString());
SteamGameServer.SetKeyValue("official", ConVar.Server.official.ToString());
SteamGameServer.SetKeyValue("pve", ConVar.Server.pve.ToString());
SteamGameServer.SetKeyValue("headerimage", ConVar.Server.headerimage);
SteamGameServer.SetKeyValue("url", ConVar.Server.url);
SteamGameServer.SetKeyValue("uptime", ((int)Time.realtimeSinceStartup).ToString());
SteamGameServer.SetKeyValue("mem_ws", Performance.usedMemoryWorkingSetMB.ToString());
SteamGameServer.SetKeyValue("mem_pv", Performance.usedMemoryPrivateMB.ToString());
SteamGameServer.SetKeyValue("gc_mb", Performance.memoryAllocations.ToString());
SteamGameServer.SetKeyValue("gc_cl", Performance.memoryCollections.ToString());
SteamGameServer.SetKeyValue("fps", Performance.frameRate.ToString());
SteamGameServer.SetKeyValue("fps_avg", Performance.frameRateAverage.ToString("0.00"));
SteamGameServer.SetKeyValue("ent_cnt", BaseNetworkable.serverEntities.Count.ToString());
SteamGameServer.SetKeyValue("build", BuildInformation.VersionStampDays.ToString());
}
} catch (Exception ex) {
Logger.LogError("[Hooks] Error while setting the server modded.");
Logger.LogException(ex);
}
}
#endregion
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Positioning.Forms.dll
// Description: A library for managing GPS connections.
// ********************************************************************************************************
//
// The Original Code is from http://gps3.codeplex.com/ version 3.0
//
// The Initial Developer of this original code is Jon Pearson. Submitted Oct. 21, 2010 by Ben Tombs (tidyup)
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// -------------------------------------------------------------------------------------------------------
// | Developer | Date | Comments
// |--------------------------|------------|--------------------------------------------------------------
// | Tidyup (Ben Tombs) | 10/21/2010 | Original copy submitted from modified GPS.Net 3.0
// | Shade1974 (Ted Dunsford) | 10/22/2010 | Added file headers reviewed formatting with resharper.
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Globalization;
using System.Threading;
using System.Windows.Forms;
#if !PocketPC || DesignTime || Framework20
using System.ComponentModel;
#endif
#if PocketPC
using DotSpatial.Positioning.Licensing;
#endif
namespace DotSpatial.Positioning.Forms
{
/// <summary>
/// Controls whether controls are rotated to show the current bearing straight up.
/// </summary>
public enum RotationOrientation
{
/// <summary>
/// The control will be rotated so that North always points to the top of the screen.
/// </summary>
NorthUp = 0,
/// <summary>
/// The control will be rotated so the the current bearing points to the top of the screen.
/// </summary>
TrackUp = 1
}
#if !PocketPC || DesignTime
/// <summary>
/// Represents a user control used to display the location and signal strength of GPS satellites.
/// </summary>
[ToolboxBitmap(typeof(SatelliteViewer), "Resources.SatelliteViewer.bmp")]
[DefaultProperty("Satellites")]
#endif
#if Framework20
#if !PocketPC
[ToolboxItem(true)]
#endif
#endif
//[CLSCompliant(false)]
public sealed class SatelliteViewer : PolarControl
{
private Azimuth _bearing = Azimuth.North;
#if PocketPC
private Angle _MinorTickInterval = new Angle(5);
#if Framework20
private Pen _MajorTickPen = new Pen(Color.Black, 2.0f);
#else
private Pen _MajorTickPen = new Pen(Color.Black);
#endif
#else
private Angle _minorTickInterval = new Angle(2);
private Pen _majorTickPen = new Pen(Color.Black, 2.0f);
#endif
private Angle _majorTickInterval = new Angle(15);
private Pen _minorTickPen = new Pen(Color.Black);
private Angle _directionLabelInterval = new Angle(45);
private string _directionLabelFormat = "c";
private SolidBrush _directionLabelBrush = new SolidBrush(Color.Black);
private Pen _halfwayUpPen = new Pen(Color.Gray);
#if PocketPC
private Font _DirectionLabelFont = new Font("Tahoma", 7.0f, FontStyle.Regular);
private Font _PseudorandomNumberFont = new Font("Tahoma", 7.0f, FontStyle.Bold);
private SolidBrush _SatelliteFixBrush = new SolidBrush(Color.LimeGreen);
#else
private Font _directionLabelFont = new Font("Tahoma", 12.0f, FontStyle.Bold);
private Font _pseudorandomNumberFont = new Font("Tahoma", 9.0f, FontStyle.Regular);
#endif
private SolidBrush _pseudorandomNumberBrush = new SolidBrush(Color.Black);
private bool _isUsingRealTimeData = true;
#if !PocketPC
private SolidBrush _satelliteShadowBrush = new SolidBrush(Color.FromArgb(32, 0, 0, 0));
private Color _satelliteFixColor = Color.LightGreen;
#endif
private Color _satelliteNoSignalFillColor = Color.Transparent;
private Color _satellitePoorSignalFillColor = Color.Red;
private Color _satelliteModerateSignalFillColor = Color.Orange;
private Color _satelliteGoodSignalFillColor = Color.Green;
private Color _satelliteExcellentSignalFillColor = Color.LightGreen;
private Color _satelliteNoSignalOutlineColor = Color.Transparent;
private Color _satellitePoorSignalOutlineColor = Color.Black;
private Color _satelliteModerateSignalOutlineColor = Color.Black;
private Color _satelliteGoodSignalOutlineColor = Color.Black;
private Color _satelliteExcellentSignalOutlineColor = Color.Black;
private readonly ColorInterpolator _fillNone = new ColorInterpolator(Color.Transparent, Color.Red, 10);
private readonly ColorInterpolator _fillPoor = new ColorInterpolator(Color.Red, Color.Orange, 10);
private readonly ColorInterpolator _pFillModerate = new ColorInterpolator(Color.Orange, Color.Green, 10);
private readonly ColorInterpolator _pFillGood = new ColorInterpolator(Color.Green, Color.LightGreen, 10);
private readonly ColorInterpolator _pFillExcellent = new ColorInterpolator(Color.LightGreen, Color.White, 10);
private readonly ColorInterpolator _pOutlineNone = new ColorInterpolator(Color.Transparent, Color.Gray, 10);
private readonly ColorInterpolator _pOutlinePoor = new ColorInterpolator(Color.Gray, Color.Gray, 10);
private readonly ColorInterpolator _pOutlineModerate = new ColorInterpolator(Color.Gray, Color.Gray, 10);
private readonly ColorInterpolator _pOutlineGood = new ColorInterpolator(Color.Gray, Color.Gray, 10);
private readonly ColorInterpolator _pOutlineExcellent = new ColorInterpolator(Color.Gray, Color.LightGreen, 10);
private List<Satellite> _satellites;
private RotationOrientation _rotationOrientation = RotationOrientation.TrackUp;
//private object RenderSyncLock = new object();
private static readonly PointD[] _icon = new[]
{
new PointD(0, 0),
new PointD(0, 10),
new PointD(3, 10),
new PointD(3, 5),
new PointD(4, 5),
new PointD(4, 10),
new PointD(8, 10),
new PointD(8, 5),
new PointD(10, 5),
new PointD(10, 6),
new PointD(12, 8),
new PointD(14, 8),
new PointD(16, 6),
new PointD(16, 5),
new PointD(18, 5),
new PointD(18, 10),
new PointD(22, 10),
new PointD(22, 5),
new PointD(23, 5),
new PointD(23, 10),
new PointD(26, 10),
new PointD(26, 0),
new PointD(23, 0),
new PointD(23, 5),
new PointD(22, 5),
new PointD(22, 0),
new PointD(18, 0),
new PointD(18, 5),
new PointD(16, 5),
new PointD(16, 4),
new PointD(14, 2),
new PointD(12, 2),
new PointD(10, 4),
new PointD(10, 5),
new PointD(8, 5),
new PointD(8, 0),
new PointD(4, 0),
new PointD(4, 5),
new PointD(3, 5),
new PointD(3, 0),
new PointD(0, 0)
};
private static PointD _iconCenter = new PointD(13, 5);
/// <summary>
/// Creates a new instance.
/// </summary>
public SatelliteViewer()
: base("DotSpatial.Positioning Multithreaded Satellite Viewer Control (http://dotspatial.codeplex.com)")
{
//MessageBox.Show("SatelliteViewer Initialization started.");
_satellites = new List<Satellite>();
Orientation = PolarCoordinateOrientation.Clockwise;
Origin = Azimuth.North;
// Set the max and min
CenterR = 0;
MaximumR = 90;
#if PocketPC
#if Framework20
_HalfwayUpPen.DashStyle = DashStyle.Dash;
#endif
#else
_halfwayUpPen.DashStyle = DashStyle.DashDotDot;
#endif
#if PocketPC && !Framework20 && !DesignTime
// Bind global events when GPS data changes
DotSpatial.Positioning.Gps.IO.Devices.SatellitesChanged += new SatelliteCollectionEventHandler(Devices_CurrentSatellitesChanged);
DotSpatial.Positioning.Gps.IO.Devices.BearingChanged += new EventHandler<AzimuthEventArgs>(Devices_CurrentBearingChanged);
#endif
}
#if !PocketPC || Framework20
/// <inheritdocs/>
protected override void OnHandleCreated(EventArgs e)
{
// Subscribe to events
try
{
base.OnHandleCreated(e);
// Only hook into events if we're at run-time. Hooking events
// at design-time can actually cause errors in the WF Designer.
if (LicenseManager.UsageMode == LicenseUsageMode.Runtime)
{
Devices.SatellitesChanged += Devices_CurrentSatellitesChanged;
Devices.BearingChanged += Devices_CurrentBearingChanged;
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
/// <inheritdocs/>
protected override void OnHandleDestroyed(EventArgs e)
{
try
{
// Only hook into events if we're at run-time. Hooking events
// at design-time can actually cause errors in the WF Designer.
if (LicenseManager.UsageMode == LicenseUsageMode.Runtime)
{
Devices.SatellitesChanged -= Devices_CurrentSatellitesChanged;
Devices.BearingChanged -= Devices_CurrentBearingChanged;
}
}
finally
{
base.OnHandleDestroyed(e);
}
}
#endif
/// <inheritdocs/>
protected override void OnInitialize()
{
//MessageBox.Show("SatelliteViewer OnInitialize.");
base.OnInitialize();
// Set the collection if it's design mode
if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)
{
// TODO: How to Randomize satellites?
_satellites = new List<Satellite>(); // SatelliteCollection.Random(45);
}
else
{
if (_isUsingRealTimeData)
{
// Merge it with live satellite data
_satellites = Devices.Satellites;
}
}
//MessageBox.Show("SatelliteViewer OnInitialize completed.");
}
/// <inheritdocs/>
protected override void Dispose(bool disposing)
{
#if PocketPC && !Framework20 && !DesignTime
//MessageBox.Show("SatelliteViewer Dispose.");
// Bind global events when GPS data changes
try
{
DotSpatial.Positioning.Gps.IO.Devices.SatellitesChanged -= new SatelliteCollectionEventHandler(Devices_CurrentSatellitesChanged);
}
catch
{
}
try
{
DotSpatial.Positioning.Gps.IO.Devices.BearingChanged -= new EventHandler<AzimuthEventArgs>(Devices_CurrentBearingChanged);
}
catch
{
}
#endif
#if PocketPC
if (_SatelliteFixBrush != null)
{
try
{
_SatelliteFixBrush.Dispose();
}
catch
{
}
finally
{
_SatelliteFixBrush = null;
}
}
#endif
if (_minorTickPen != null)
{
try
{
_minorTickPen.Dispose();
}
finally
{
_minorTickPen = null;
}
}
if (_majorTickPen != null)
{
try
{
_majorTickPen.Dispose();
}
finally
{
_majorTickPen = null;
}
}
if (_directionLabelBrush != null)
{
try
{
_directionLabelBrush.Dispose();
}
finally
{
_directionLabelBrush = null;
}
}
if (_directionLabelFont != null)
{
try
{
_directionLabelFont.Dispose();
}
finally
{
_directionLabelFont = null;
}
}
#if !PocketPC
if (_satelliteShadowBrush != null)
{
_satelliteShadowBrush.Dispose();
_satelliteShadowBrush = null;
}
#endif
if (_pseudorandomNumberFont != null)
{
try
{
_pseudorandomNumberFont.Dispose();
}
finally
{
_pseudorandomNumberFont = null;
}
}
if (_pseudorandomNumberBrush != null)
{
try
{
_pseudorandomNumberBrush.Dispose();
}
finally
{
_pseudorandomNumberBrush = null;
}
}
if (_halfwayUpPen != null)
{
try
{
_halfwayUpPen.Dispose();
}
finally
{
_halfwayUpPen = null;
}
}
base.Dispose(disposing);
}
private Color GetFillColor(SignalToNoiseRatio signal)
{
if (signal.Value < 10)
return _fillNone[signal.Value];
if (signal.Value < 20)
return _fillPoor[signal.Value - 10];
if (signal.Value < 30)
return _pFillModerate[signal.Value - 20];
if (signal.Value < 40)
return _pFillGood[signal.Value - 30];
if (signal.Value < 50)
return _pFillExcellent[signal.Value - 40];
return _pFillExcellent[9];
}
private Color GetOutlineColor(SignalToNoiseRatio signal)
{
if (signal.Value < 10)
return _pOutlineNone[signal.Value];
if (signal.Value < 20)
return _pOutlinePoor[signal.Value - 10];
if (signal.Value < 30)
return _pOutlineModerate[signal.Value - 20];
if (signal.Value < 40)
return _pOutlineGood[signal.Value - 30];
if (signal.Value < 50)
return _pOutlineExcellent[signal.Value - 40];
return _pOutlineExcellent[9];
}
#if !PocketPC || DesignTime
/// <summary>
/// Controls the amount of rotation applied to the entire control to indicate the current direction of travel.
/// </summary>
[Category("Behavior")]
[DefaultValue(typeof(Azimuth), "0")]
[Description("Controls the amount of rotation applied to the entire control to indicate the current direction of travel.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public Azimuth Bearing
{
get
{
return _bearing;
}
set
{
if (_bearing.Equals(value)) return;
_bearing = value;
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Controls whether the Satellites property is set manually, or automatically read from any available GPS device.
/// </summary>
[Category("Behavior")]
[DefaultValue(typeof(bool), "True")]
[Description("Controls whether the Satellites property is set manually, or automatically read from any available GPS device.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public bool IsUsingRealTimeData
{
get
{
return _isUsingRealTimeData;
}
set
{
if (_isUsingRealTimeData == value)
return;
//MessageBox.Show("IsUsingRealTimeData started.");
_isUsingRealTimeData = value;
#if !DesignTime
if (_isUsingRealTimeData)
{
// Use current satellite information
_satellites = Devices.Satellites;
// Also set the bearing
if (_rotationOrientation == RotationOrientation.TrackUp)
Rotation = new Angle(-Devices.Bearing.DecimalDegrees);
}
else
{
_satellites.Clear();
// Clear the rotation
if (_rotationOrientation == RotationOrientation.TrackUp)
Rotation = Angle.Empty;
}
#endif
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
#if PocketPC
[DefaultValue(typeof(Angle), "5")]
#else
/// <summary>
/// Controls the number of degrees in between each smaller tick mark around the control.
/// </summary>
[DefaultValue(typeof(Angle), "2")]
#endif
[Category("Tick Marks")]
[Description("Controls the number of degrees in between each smaller tick mark around the control.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
////[CLSCompliant(false)]
public Angle MinorTickInterval
{
get
{
return _minorTickInterval;
}
set
{
if (_minorTickInterval.Equals(value)) return;
_minorTickInterval = value;
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Controls the format of compass directions drawn around the control.
/// </summary>
[Category("Direction Labels")]
[DefaultValue(typeof(string), "c")]
[Description("Controls the format of compass directions drawn around the control.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public string DirectionLabelFormat
{
get
{
return _directionLabelFormat;
}
set
{
if (_directionLabelFormat == value) return;
_directionLabelFormat = value;
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Controls the number of degrees in between each larger tick mark around the control.
/// </summary>
[DefaultValue(typeof(Angle), "15")]
[Category("Tick Marks")]
[Description("Controls the number of degrees in between each larger tick mark around the control.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public Angle MajorTickInterval
{
get
{
return _majorTickInterval;
}
set
{
if (_majorTickInterval.Equals(value)) return;
_majorTickInterval = value;
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Controls the color used to draw smaller tick marks around the control.
/// </summary>
[Category("Tick Marks")]
[DefaultValue(typeof(Color), "Black")]
[Description("Controls the color used to draw smaller tick marks around the control.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public Color MinorTickColor
{
get
{
return _minorTickPen.Color;
}
set
{
lock (_minorTickPen)
{
if (_minorTickPen.Color.Equals(value)) return;
_minorTickPen.Color = value;
}
Thread.Sleep(0);
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Controls the color used to draw larger tick marks around the control.
/// </summary>
[Category("Tick Marks")]
[DefaultValue(typeof(Color), "Black")]
[Description("Controls the color used to draw larger tick marks around the control.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public Color MajorTickColor
{
get
{
return _majorTickPen.Color;
}
set
{
lock (_majorTickPen)
{
if (_majorTickPen.Color.Equals(value)) return;
_majorTickPen.Color = value;
}
Thread.Sleep(0);
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Controls the number of degrees in between each compass label around the control.
/// </summary>
[Category("Direction Labels")]
[DefaultValue(typeof(Angle), "45")]
[Description("Controls the number of degrees in between each compass label around the control.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
////[CLSCompliant(false)]
public Angle DirectionLabelInterval
{
get
{
return _directionLabelInterval;
}
set
{
if (_directionLabelInterval.Equals(value)) return;
_directionLabelInterval = value;
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Controls the color used to display compass direction letters around the control.
/// </summary>
[Category("Direction Labels")]
[DefaultValue(typeof(Color), "Black")]
[Description("Controls the color used to display compass direction letters around the control.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public Color DirectionLabelColor
{
get
{
return _directionLabelBrush.Color;
}
set
{
lock (_directionLabelBrush)
{
if (_directionLabelBrush.Color.Equals(value)) return;
_directionLabelBrush.Color = value;
}
Thread.Sleep(0);
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Controls the font used to draw compass labels around the control.
/// </summary>
[Category("Direction Labels")]
#if PocketPC
[DefaultValue(typeof(Font), "Tahoma, 7pt")]
#else
[DefaultValue(typeof(Font), "Tahoma, 12pt, style=Bold")]
#endif
[Description("Controls the font used to draw compass labels around the control.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public Font DirectionLabelFont
{
get
{
return _directionLabelFont;
}
set
{
if (_directionLabelFont.Equals(value)) return;
_directionLabelFont = value;
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Controls the color inside of satellite icons with no signal.
/// </summary>
[Category("Satellite Colors")]
[DefaultValue(typeof(Color), "Transparent")]
[Description("Controls the color inside of satellite icons with no signal.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public Color NoSignalFillColor
{
get
{
return _satelliteNoSignalFillColor;
}
set
{
if (_satelliteNoSignalFillColor.Equals(value)) return;
_satelliteNoSignalFillColor = value;
_fillNone.EndColor = value;
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Controls the color inside of satellite icons with a weak signal.
/// </summary>
[Category("Satellite Colors")]
[DefaultValue(typeof(Color), "Red")]
[Description("Controls the color inside of satellite icons with a weak signal.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public Color PoorSignalFillColor
{
get
{
return _satellitePoorSignalFillColor;
}
set
{
if (_satellitePoorSignalFillColor.Equals(value)) return;
_satellitePoorSignalFillColor = value;
_fillNone.EndColor = value;
_fillPoor.StartColor = value;
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Controls the color inside of satellite icons with a moderate signal.
/// </summary>
[Category("Satellite Colors")]
[DefaultValue(typeof(Color), "Orange")]
[Description("Controls the color inside of satellite icons with a moderate signal.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public Color ModerateSignalFillColor
{
get
{
return _satelliteModerateSignalFillColor;
}
set
{
if (_satelliteModerateSignalFillColor.Equals(value)) return;
_satelliteModerateSignalFillColor = value;
_pFillModerate.StartColor = value;
_fillPoor.EndColor = value;
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Controls the color inside of satellite icons with a strong signal.
/// </summary>
[Category("Satellite Colors")]
[DefaultValue(typeof(Color), "Green")]
[Description("Controls the color inside of satellite icons with a strong signal.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public Color GoodSignalFillColor
{
get
{
return _satelliteGoodSignalFillColor;
}
set
{
if (_satelliteGoodSignalFillColor.Equals(value)) return;
_satelliteGoodSignalFillColor = value;
_pFillGood.StartColor = value;
_pFillModerate.EndColor = value;
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Controls the color inside of satellite icons with a very strong signal.
/// </summary>
[Category("Satellite Colors")]
[DefaultValue(typeof(Color), "LightGreen")]
[Description("Controls the color inside of satellite icons with a very strong signal.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public Color ExcellentSignalFillColor
{
get
{
return _satelliteExcellentSignalFillColor;
}
set
{
if (_satelliteExcellentSignalFillColor.Equals(value)) return;
_satelliteExcellentSignalFillColor = value;
_pFillGood.EndColor = value;
_pFillExcellent.StartColor = value;
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Controls the color around satellite icons with no signal.
/// </summary>
[Category("Satellite Colors")]
[DefaultValue(typeof(Color), "Transparent")]
[Description("Controls the color around satellite icons with no signal.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public Color NoSignalOutlineColor
{
get
{
return _satelliteNoSignalOutlineColor;
}
set
{
if (_satelliteNoSignalOutlineColor.Equals(value)) return;
_satelliteNoSignalOutlineColor = value;
_pOutlineNone.EndColor = value;
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Controls the color around satellite icons with a weak signal.
/// </summary>
[Category("Satellite Colors")]
[DefaultValue(typeof(Color), "Black")]
[Description("Controls the color around satellite icons with a weak signal.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public Color PoorSignalOutlineColor
{
get
{
return _satellitePoorSignalOutlineColor;
}
set
{
if (_satellitePoorSignalOutlineColor.Equals(value)) return;
_satellitePoorSignalOutlineColor = value;
_pOutlineNone.EndColor = value;
_pOutlinePoor.StartColor = value;
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Controls the color around satellite icons with a moderate signal.
/// </summary>
[Category("Satellite Colors")]
[DefaultValue(typeof(Color), "Black")]
[Description("Controls the color around satellite icons with a moderate signal.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public Color ModerateSignalOutlineColor
{
get
{
return _satelliteModerateSignalOutlineColor;
}
set
{
if (_satelliteModerateSignalOutlineColor.Equals(value)) return;
_satelliteModerateSignalOutlineColor = value;
_pOutlinePoor.EndColor = value;
_pOutlineModerate.StartColor = value;
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Controls the color around satellite icons with a strong signal.
/// </summary>
[Category("Satellite Colors")]
[DefaultValue(typeof(Color), "Black")]
[Description("Controls the color around satellite icons with a strong signal.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public Color GoodSignalOutlineColor
{
get
{
return _satelliteGoodSignalOutlineColor;
}
set
{
if (_satelliteGoodSignalOutlineColor.Equals(value)) return;
_satelliteGoodSignalOutlineColor = value;
_pOutlineModerate.EndColor = value;
_pOutlineGood.StartColor = value;
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Controls the color around satellite icons with a very strong signal.
/// </summary>
[Category("Satellite Colors")]
[DefaultValue(typeof(Color), "Black")]
[Description("Controls the color around satellite icons with a very strong signal.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public Color ExcellentSignalOutlineColor
{
get
{
return _satelliteExcellentSignalOutlineColor;
}
set
{
if (_satelliteExcellentSignalOutlineColor.Equals(value)) return;
_satelliteExcellentSignalOutlineColor = value;
_pOutlineGood.EndColor = value;
_pOutlineExcellent.StartColor = value;
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Controls the color of the ellipse drawn around fixed satellites.
/// </summary>
[Category("Satellite Colors")]
[DefaultValue(typeof(Color), "LimeGreen")]
[Description("Controls the color of the ellipse drawn around fixed satellites.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public Color FixColor
{
get
{
#if PocketPC
return _SatelliteFixBrush.Color;
#else
return _satelliteFixColor;
#endif
}
set
{
#if PocketPC
if (_SatelliteFixBrush.Color.Equals(value))
return;
_SatelliteFixBrush.Color = value;
#else
if (_satelliteFixColor.Equals(value)) return;
_satelliteFixColor = value;
#endif
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Controls which bearing points straight up on the screen.
/// </summary>
[Category("Behavior")]
[DefaultValue(typeof(RotationOrientation), "TrackUp")]
[Description("Controls which bearing points straight up on the screen.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public RotationOrientation RotationOrientation
{
get
{
return _rotationOrientation;
}
set
{
if (_rotationOrientation == value)
return;
_rotationOrientation = value;
// If this becomes active, set the current bearing
Rotation = _rotationOrientation == RotationOrientation.TrackUp ? new Angle(-Devices.Bearing.DecimalDegrees) : Angle.Empty;
//InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Contains the list of satellites drawn inside of the control.
/// </summary>
[Category("Satellites")]
[Description("Contains the list of satellites drawn inside of the control.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public List<Satellite> Satellites
{
get
{
return _satellites;
}
set
{
_satellites = value;
// Redraw the control
if (_satellites != null)
InvokeRepaint();
}
}
#if Framework20 && !PocketPC
/// <summary>
/// The Origin Azimuth angle
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override Azimuth Origin
{
get
{
return base.Origin;
}
set
{
base.Origin = value;
}
}
/// <summary>
/// The rotation angle
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override Angle Rotation
{
get
{
return base.Rotation;
}
set
{
base.Rotation = value;
}
}
#endif
/// <inheritdocs/>
protected override void OnPaintOffScreen(PaintEventArgs e)
{
PolarGraphics f = CreatePolarGraphics(e.Graphics);
// Cache drawing intervals and such to prevent a race condition
double minorInterval = _minorTickInterval.DecimalDegrees;
double majorInterval = _majorTickInterval.DecimalDegrees;
double directionInterval = _directionLabelInterval.DecimalDegrees;
// Draw tick marks
if (minorInterval > 0)
{
for (double angle = 0; angle < 360; angle += minorInterval)
{
// And draw a line
f.DrawLine(_minorTickPen, new PolarCoordinate(88.0f, angle),
new PolarCoordinate(90, angle));
}
}
// Draw tick marks
if (majorInterval > 0)
{
for (double angle = 0; angle < 360; angle += majorInterval)
{
// And draw a line
f.DrawLine(_majorTickPen, new PolarCoordinate(85.0f, angle), new PolarCoordinate(90, angle));
}
}
if (directionInterval > 0)
{
for (double angle = 0; angle < 360; angle += directionInterval)
{
// Get the coordinate of the line's start
PolarCoordinate start = new PolarCoordinate(70, angle, Azimuth.North, PolarCoordinateOrientation.Clockwise);
#if PocketPC
f.DrawCenteredString(((Azimuth)angle).ToString(_DirectionLabelFormat, CultureInfo.CurrentCulture), _DirectionLabelFont, _DirectionLabelBrush, start);
#else
f.DrawRotatedString(((Azimuth)angle).ToString(_directionLabelFormat, CultureInfo.CurrentCulture), _directionLabelFont, _directionLabelBrush, start);
#endif
}
}
// Draw an ellipse at the center
f.DrawEllipse(_halfwayUpPen, PolarCoordinate.Empty, 45);
// Now draw each satellite
int satelliteCount = 0;
if (Satellites != null)
{
satelliteCount = Satellites.Count;
#if !PocketPC
for (int index = 0; index < satelliteCount; index++)
{
Satellite satellite = _satellites[index];
// Don't draw if the satellite is stale
if (!satellite.IsActive && !DesignMode)
continue;
// Is the satellite transparent?
if (GetFillColor(satellite.SignalToNoiseRatio).A < _satelliteShadowBrush.Color.A)
continue;
// Get the coordinate for this satellite
PolarCoordinate center = new PolarCoordinate(Convert.ToSingle(90.0f - satellite.Elevation.DecimalDegrees),
satellite.Azimuth.DecimalDegrees, Azimuth.North, PolarCoordinateOrientation.Clockwise);
PointD centerPoint = f.ToPointD(center);
// Each icon is 30x30, so we'll translate it by half the distance
double pShadowSize = Math.Sin(Radian.FromDegrees(satellite.Elevation.DecimalDegrees).Value) * 7;
f.Graphics.TranslateTransform((float)(centerPoint.X - _iconCenter.X + pShadowSize), (float)(centerPoint.Y - _iconCenter.Y + pShadowSize));
// Draw each satellite
PointF[] satelliteIcon = new PointF[_icon.Length];
for (int iconIndex = 0; iconIndex < _icon.Length; iconIndex++)
{
satelliteIcon[iconIndex] = new PointF((float)_icon[iconIndex].X, (float)_icon[iconIndex].Y);
}
using (Matrix y = new Matrix())
{
y.RotateAt(Convert.ToSingle(satellite.Azimuth.DecimalDegrees - f.Rotation.DecimalDegrees + Origin.DecimalDegrees),
new PointF((float)_iconCenter.X, (float)_iconCenter.Y), MatrixOrder.Append);
y.TransformPoints(satelliteIcon);
}
f.Graphics.FillPolygon(_satelliteShadowBrush, satelliteIcon);
f.Graphics.ResetTransform();
}
#endif
}
// Now draw each satellite
if (_satellites != null)
{
List<Satellite> fixedSatellites = Satellite.GetFixedSatellites(_satellites);
int fixedSatelliteCount = fixedSatellites.Count;
for (int index = 0; index < fixedSatelliteCount; index++)
{
Satellite satellite = fixedSatellites[index];
if (LicenseManager.UsageMode != LicenseUsageMode.Designtime)
{
#if PocketPC
// Don't draw if the satellite is stale
if (!satellite.IsActive)
continue;
#else
// Don't draw if the satellite is stale
if (!satellite.IsActive && !DesignMode)
continue;
#endif
}
// Get the coordinate for this satellite
PolarCoordinate center = new PolarCoordinate(Convert.ToSingle(90.0 - satellite.Elevation.DecimalDegrees),
satellite.Azimuth.DecimalDegrees, Azimuth.North, PolarCoordinateOrientation.Clockwise);
#if PocketPC
f.FillEllipse(_SatelliteFixBrush, Center, 16);
#else
using (SolidBrush fixBrush = new SolidBrush(Color.FromArgb(Math.Min(255, fixedSatellites.Count * 20), _satelliteFixColor)))
{
f.FillEllipse(fixBrush, center, 16);
}
#endif
}
// Now draw each satellite
for (int index = 0; index < satelliteCount; index++)
{
Satellite satellite = _satellites[index];
if (LicenseManager.UsageMode != LicenseUsageMode.Designtime)
{
#if PocketPC
// Don't draw if the satellite is stale
if (!satellite.IsActive)
continue;
#else
// Don't draw if the satellite is stale
if (!satellite.IsActive && !DesignMode)
continue;
#endif
}
// Get the coordinate for this satellite
PolarCoordinate center = new PolarCoordinate(Convert.ToSingle(90.0 - satellite.Elevation.DecimalDegrees),
satellite.Azimuth.DecimalDegrees, Azimuth.North, PolarCoordinateOrientation.Clockwise);
PointD centerPoint = f.ToPointD(center);
#if PocketPC
// Manually rotate each point of the icon
Point[] SatelliteIcon = new Point[Icon.Length];
for (int index2 = 0; index2 < Icon.Length; index2++)
{
PointD point = Icon[index2]
.RotateAt(satellite.Azimuth.DecimalDegrees - Rotation.DecimalDegrees + Origin.DecimalDegrees, IconCenter)
.Add(CenterPoint.X - IconCenter.X, CenterPoint.Y - IconCenter.Y);
SatelliteIcon[index2] = new Point((int)point.X, (int)point.Y);
}
Color SatelliteColor = GetFillColor(satellite.SignalToNoiseRatio);
SolidBrush FillBrush = new SolidBrush(SatelliteColor);
f.Graphics.FillPolygon(FillBrush, SatelliteIcon);
FillBrush.Dispose();
#else
// Each icon is 30x30, so we'll translate it by half the distance
double pShadowSize = Math.Sin(Radian.FromDegrees(satellite.Elevation.DecimalDegrees).Value) * 7;
f.Graphics.TranslateTransform((float)(centerPoint.X - _iconCenter.X - pShadowSize * 0.1), (float)(centerPoint.Y - _iconCenter.Y - pShadowSize * 0.1));
// Draw each satellite
PointF[] satelliteIcon = new PointF[_icon.Length];
for (int iconIndex = 0; iconIndex < _icon.Length; iconIndex++)
{
satelliteIcon[iconIndex] = new PointF((float)_icon[iconIndex].X, (float)_icon[iconIndex].Y);
}
Matrix y = new Matrix();
y.RotateAt(Convert.ToSingle(satellite.Azimuth.DecimalDegrees - f.Rotation.DecimalDegrees + Origin.DecimalDegrees),
new PointF((float)_iconCenter.X, (float)_iconCenter.Y), MatrixOrder.Append);
y.TransformPoints(satelliteIcon);
y.Dispose();
SolidBrush fillBrush = new SolidBrush(GetFillColor(satellite.SignalToNoiseRatio));
f.Graphics.FillPolygon(fillBrush, satelliteIcon);
fillBrush.Dispose();
Pen fillPen = new Pen(GetOutlineColor(satellite.SignalToNoiseRatio), 1.0f);
f.Graphics.DrawPolygon(fillPen, satelliteIcon);
fillPen.Dispose();
f.Graphics.ResetTransform();
#endif
#if PocketPC
if (!SatelliteColor.Equals(Color.Transparent))
{
f.DrawCenteredString(satellite.PseudorandomNumber.ToString(), _PseudorandomNumberFont,
_PseudorandomNumberBrush, new PolarCoordinate(Center.R - 11, Center.Theta.DecimalDegrees,
Azimuth.North, PolarCoordinateOrientation.Clockwise));
}
#else
f.DrawRotatedString(satellite.PseudorandomNumber.ToString(CultureInfo.CurrentCulture), _pseudorandomNumberFont,
_pseudorandomNumberBrush, new PolarCoordinate(center.R - 11, center.Theta,
Azimuth.North, PolarCoordinateOrientation.Clockwise));
#endif
}
}
}
#if !PocketPC
/// <summary>
/// Controls the color of the shadow cast by satellite icons.
/// </summary>
[Category("Appearance")]
[DefaultValue(typeof(Color), "32, 0, 0, 0")]
[Description("Controls the color of the shadow cast by satellite icons.")]
public Color ShadowColor
{
get
{
return _satelliteShadowBrush.Color;
}
set
{
lock (_satelliteShadowBrush)
{
if (_satelliteShadowBrush.Color.Equals(value)) return;
_satelliteShadowBrush.Color = value;
}
InvokeRepaint();
}
}
#endif
#if !PocketPC || DesignTime
/// <summary>
/// Controls the font used to display the ID of each satellite.
/// </summary>
[Category("Satellite Colors")]
#if PocketPC
[DefaultValue(typeof(Font), "Tahoma, 7pt, style=Bold")]
#else
[DefaultValue(typeof(Font), "Tahoma, 9pt")]
#endif
[Description("Controls the font used to display the ID of each satellite.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public Font PseudorandomNumberFont
{
get
{
return _pseudorandomNumberFont;
}
set
{
if (_pseudorandomNumberFont.Equals(value)) return;
_pseudorandomNumberFont = value;
InvokeRepaint();
}
}
#if !PocketPC || DesignTime
/// <summary>
/// Controls the color used to display the ID of each satellite.
/// </summary>
[Category("Satellite Colors")]
[DefaultValue(typeof(Color), "Black")]
[Description("Controls the color used to display the ID of each satellite.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
[EditorBrowsable(EditorBrowsableState.Always)]
#endif
public Color PseudorandomNumberColor
{
get
{
return _pseudorandomNumberBrush.Color;
}
set
{
lock (_pseudorandomNumberBrush)
{
if (_pseudorandomNumberBrush.Color.Equals(value)) return;
_pseudorandomNumberBrush.Color = value;
}
Thread.Sleep(0);
InvokeRepaint();
}
}
private void Devices_CurrentSatellitesChanged(object sender, SatelliteListEventArgs e)
{
//TODO should this be done here or in a user defined event handler?
if (_isUsingRealTimeData) Satellites = (List<Satellite>)e.Satellites;
InvokeRepaint();
}
private void Devices_CurrentBearingChanged(object sender, AzimuthEventArgs e)
{
if (_isUsingRealTimeData && _rotationOrientation == RotationOrientation.TrackUp)
Rotation = new Angle(e.Azimuth.DecimalDegrees);
}
}
}
| |
// 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 Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.integeregererface01.integeregererface01
{
// <Title> CLS Compliance for Dynamic </Title>
// <Description> Types Rule : Interface Methods (Compiler)
// CLS-compliant language compilers must have syntax for the situation where a single type implements
// two interfaces and each of those interfaces requires the definition of a method with the same name and signature.
// Such methods must be considered distinct and need not have the same implementation.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
//[assembly: System.CLSCompliant(true)]
namespace MyNamespace
{
public interface MyInterface1
{
dynamic Method01(int n);
T Method02<T>(dynamic n);
dynamic Method03(byte b, ref dynamic n);
}
public interface MyInterface2
{
dynamic Method01(int n);
T Method02<T>(dynamic n);
dynamic Method03(byte b, ref dynamic n);
}
public class MyClass : MyInterface1, MyInterface2
{
dynamic MyInterface1.Method01(int n)
{
return default(dynamic);
}
T MyInterface1.Method02<T>(dynamic n)
{
return default(T);
}
dynamic MyInterface1.Method03(byte b, ref dynamic n)
{
return default(dynamic);
}
dynamic MyInterface2.Method01(int n)
{
return default(dynamic);
}
T MyInterface2.Method02<T>(dynamic n)
{
return default(T);
}
dynamic MyInterface2.Method03(byte b, ref dynamic n)
{
return default(dynamic);
}
}
public struct MyStruct : MyInterface1, MyInterface2
{
public dynamic Method01(int n)
{
return default(dynamic);
}
public T Method02<T>(dynamic n)
{
return default(T);
}
public dynamic Method03(byte b, ref dynamic n)
{
return default(dynamic);
}
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.mixedmode02.mixedmode02
{
// <Title> CLS Compliance for Dynamic </Title>
// <Description> Naming Rule : Characters and casing
// CLS-compliant language compilers must follow the rules of Annex 7 of Technical Report 15 of
// the Unicode Standard 3.0, which governs the set of characters that can start and be included in identifiers.
// This standard is available from the Web site of the Unicode Consortium.
// For two identifiers to be considered distinct, they must differ by more than just their case.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=warning>\(79,55\).*CS3022</Expects>
//<Expects Status=warning>\(80,55\).*CS3022</Expects>
//<Expects Status=warning>\(47,29\).*CS3026.*vd1</Expects>
//<Expects Status=warning>\(50,23\).*CS3002.*RefMethod01\<T\>\(ref dynamic, T\)</Expects>
//<Expects Status=warning>\(51,23\).*CS3002.*refMethod01\<T\></Expects>
//<Expects Status=warning>\(51,23\).*CS3005</Expects>
//<Expects Status=warning>\(65,13\).*CS3010.*MyInterface\<T,U,V\>.Method01</Expects>
//<Expects Status=warning>\(69,7\).*CS3005.*MyInterface\<T,U,V\>.method02</Expects>
//<Expects Status=warning>\(72,13\).*CS3005.*method03\<X,Y\></Expects>
//<Expects Status=warning>\(75,27\).*CS3010.*MyInterface\<T,U,V\>.MyEvent</Expects>
//<Expects Status=warning>\(75,27\).*CS3010</Expects>
//<Expects Status=warning>\(75,27\).*CS3010</Expects>
//<Expects Status=warning>\(80,22\).*CS3005.*myDelegate01\<T\></Expects>
//<Expects Status=success></Expects>
// <Code>
// <Expects Status=notin>CS3005.*outMethod01\<X\></Expects>
// <Expects Status=notin>CS3005.*method01\<X\></Expects>
// <Expects Status=notin>CS3005.*myDelegate02\<U,V\></Expects>
// <Code>
//[assembly: System.CLSCompliant(true)]
[type: System.CLSCompliant(false)]
public class MyClass<T>
{
public volatile dynamic vd;
public static T OutMethod01<X>(T t, ref X x, out dynamic d)
{
d = default(object);
return default(T);
}
public static T outMethod01<X>(T t, ref X x, out dynamic d)
{
d = default(object);
return default(T);
}
}
[type: System.CLSCompliant(true)]
public struct MyStruct<U, V>
{
public volatile dynamic vd1;
[method: System.CLSCompliant(true)]
public MyClass<T> RefMethod01<T>(ref dynamic d, T t)
{
d = default(object);
return new MyClass<T>();
}
public MyClass<T> refMethod01<T>(ref dynamic d, T t)
{
d = default(object);
return new MyClass<T>();
}
[property: System.CLSCompliant(false)]
public dynamic Prop
{
get;
set;
}
public dynamic prop
{
get;
set;
}
[field: System.CLSCompliant(false)]
public dynamic field;
public dynamic fielD;
}
public interface MyInterface<T, U, V>
{
[method: System.CLSCompliant(false)]
dynamic Method01<X>(X n);
dynamic method01<X>(X n);
T Method02(dynamic n, U u);
T method02(dynamic n, U u);
[method: System.CLSCompliant(true)]
dynamic Method03<X, Y>(out X x, ref Y y, dynamic n);
dynamic method03<X, Y>(out X x, ref Y y, dynamic n);
[event: System.CLSCompliant(false)]
event MyDelegate01<T> MyEvent;
event MyDelegate01<T> Myevent;
}
public delegate void MyDelegate01<T>(ref T t, [param: System.CLSCompliant(false)]
dynamic d, int n);
public delegate void myDelegate01<T>(ref T t, [param: System.CLSCompliant(true)]
dynamic d, int n);
[System.CLSCompliantAttribute(false)]
public delegate V MyDelegate02<U, V>(U u, params dynamic[] ary);
public delegate V myDelegate02<U, V>(U u, params dynamic[] ary);
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.namingchr02.namingchr02
{
// <Title> CLS Compliance for Dynamic </Title>
// <Description> Naming Rule : Characters and casing
// CLS-compliant language compilers must follow the rules of Annex 7 of Technical Report 15 of
// the Unicode Standard 3.0, which governs the set of characters that can start and be included in identifiers.
// This standard is available from the Web site of the Unicode Consortium.
// For two identifiers to be considered distinct, they must differ by more than just their case.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=warning>\(30,14\).*CS3005.*outMethod01\<X\></Expects>
//<Expects Status=warning>\(36,23\).*CS3005.*refMethod01\<T\></Expects>
//<Expects Status=warning>\(42,13\).*CS3005.*method01\<X\></Expects>
//<Expects Status=warning>\(45,7\).*CS3005.*MyInterface\<T,U,V\>.method02</Expects>
//<Expects Status=warning>\(48,13\).*CS3005.*method03\<X,Y\></Expects>
//<Expects Status=warning>\(52,22\).*CS3005.*myDelegate01\<T\></Expects>
//<Expects Status=warning>\(55,19\).*CS3005.*myDelegate02\<U,V\></Expects>
//<Expects Status=success></Expects>
// <Code>
// <Code>
//[assembly: System.CLSCompliant(true)]
public class MyClass<T>
{
public T OutMethod01<X>(T t, ref X x, out dynamic d)
{
d = default(object);
return default(T);
}
public T outMethod01<X>(T t, ref X x, out dynamic d)
{
d = default(object);
return default(T);
}
}
public struct MyStruct<U, V>
{
public MyClass<T> RefMethod01<T>(ref dynamic d, T t)
{
d = default(object);
return new MyClass<T>();
}
public MyClass<T> refMethod01<T>(ref dynamic d, T t)
{
d = default(object);
return new MyClass<T>();
}
}
public interface MyInterface<T, U, V>
{
dynamic Method01<X>(X n);
dynamic method01<X>(X n);
T Method02(dynamic n, U u);
T method02(dynamic n, U u);
dynamic Method03<X, Y>(out X x, ref Y y, dynamic n);
dynamic method03<X, Y>(out X x, ref Y y, dynamic n);
}
public delegate void MyDelegate01<T>(ref T t, dynamic d, int n);
public delegate void myDelegate01<T>(ref T t, dynamic d, int n);
public delegate V MyDelegate02<U, V>(U u, params dynamic[] ary);
public delegate V myDelegate02<U, V>(U u, params dynamic[] ary);
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.namingchr03.namingchr03
{
// <Title> CLS Compliance for Dynamic </Title>
// <Description> Naming Rule : Characters and casing
// CLS-compliant language compilers must follow the rules of Annex 7 of Technical Report 15 of
// the Unicode Standard 3.0, which governs the set of characters that can start and be included in identifiers.
// This standard is available from the Web site of the Unicode Consortium.
// For two identifiers to be considered distinct, they must differ by more than just their case.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=warning>\(57,24\).*CS0108</Expects>
//<Expects Status=warning>\(41,24\).*CS3005.*method01</Expects>
//<Expects Status=warning>\(42,18\).*CS3005.*method02\<T\></Expects>
//<Expects Status=warning>\(49,24\).*CS3005.*classIdentifier</Expects>
//<Expects Status=warning>\(50,24\).*CS3005.*MEthod01</Expects>
//<Expects Status=warning>\(51,18\).*CS3005.*mEthod02\<T\></Expects>
//<Expects Status=warning>\(52,24\).*CS3005.*method03\<X,Y></Expects>
//<Expects Status=warning>\(57,24\).*CS3005</Expects>
//<Expects Status=warning>\(58,24\).*CS3005.*MyClass3\<U,V\>\.Method01</Expects>
//<Expects Status=warning>\(59,24\).*CS3005.*MyClass3\<U,V\>\.Method03</Expects>
//<Expects Status=success></Expects>
// <Code>
// <Code>
//[assembly: System.CLSCompliant(true)]
namespace MyNamespace
{
public class MyBase
{
public dynamic Method01(int n, ref dynamic d)
{
return default(object);
}
public T Method02<T>(T t, out dynamic d)
{
d = default(object);
return default(T);
}
}
public class MyClass : MyBase
{
public dynamic ClassIdentifier;
public dynamic method01(int n, ref dynamic d)
{
return default(object);
}
public T method02<T>(T t, out dynamic d)
{
d = default(object);
return default(T);
}
public dynamic Method03<X, Y>(X x, ref Y y, params dynamic[] ary)
{
return default(object);
}
}
public class MyClass2 : MyClass
{
public dynamic classIdentifier;
public dynamic MEthod01(int n, ref dynamic d)
{
return default(object);
}
public T mEthod02<T>(T t, out dynamic d)
{
d = default(object);
return default(T);
}
public dynamic method03<X, Y>(X x, ref Y y, params dynamic[] ary)
{
return default(object);
}
}
public class MyClass3<U, V> : MyClass2
{
public dynamic ClassIdentifier;
public dynamic Method01(long n, ref dynamic d)
{
return default(object);
}
public dynamic Method03(U x, ref V y, params dynamic[] ary)
{
return default(object);
}
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.namingchr04.namingchr04
{
// <Title> CLS Compliance for Dynamic </Title>
// <Description> Visibility - CLS rules apply only to those parts of a type that are exposed outside the defining assembly.
// Naming Rule : Characters and casing
// CLS-compliant language compilers must follow the rules of Annex 7 of Technical Report 15 of
// the Unicode Standard 3.0, which governs the set of characters that can start and be included in identifiers.
// This standard is available from the Web site of the Unicode Consortium.
// For two identifiers to be considered distinct, they must differ by more than just their case.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=warning>\(31,17\).*CS0169</Expects>
//<Expects Status=warning>\(43,25\).*CS0169</Expects>
//<Expects Status=success></Expects>
// <Code>
//[assembly: System.CLSCompliant(true)]
namespace MyNamespace
{
public class MyBase
{
public dynamic[][][] array; //jagged array
private dynamic Method01(int n, ref dynamic d)
{
return default(object);
}
private T Method02<T>(T t, out dynamic d)
{
d = default(object);
return default(T);
}
}
public class MyClass : MyBase
{
private dynamic _classIdentifier;
internal dynamic method01(int n, ref dynamic d)
{
return default(object);
}
protected T method02<T>(T t, out dynamic d)
{
d = default(object);
return default(T);
}
private dynamic Method03<X, Y>(X x, ref Y y, params dynamic[] ary)
{
return default(object);
}
}
public class MyClass2 : MyClass
{
//public static dynamic[,,,] array1; //cube array
private dynamic _classIdentifier;
private dynamic MEthod01(int n, ref dynamic d)
{
return default(object);
}
private T mEthod02<T>(T t, out dynamic d)
{
d = default(object);
return default(T);
}
protected dynamic method03<X, Y>(X x, ref Y y, params dynamic[] ary)
{
return default(object);
}
}
public class MyClass3<U, V> : MyClass2
{
protected dynamic ClassIdentifier;
private dynamic Method01(long n, ref dynamic d)
{
return default(object);
}
protected internal dynamic method03(U x, ref V y, params dynamic[] ary)
{
return default(object);
}
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.namingkeyword01.namingkeyword01
{
// <Title> CLS Compliance for Dynamic </Title>
// <Description> Naming Rule : Keywords (Compiler)
// CLS-compliant language compilers supply a mechanism for referencing identifiers that coincide with keywords.
// CLS-compliant language compilers provide a mechanism for defining and overriding virtual methods
// with names that are keywords in the language.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
//[assembly: System.CLSCompliant(true)]
namespace MyNamespace
{
public class MyClass
{
public dynamic @dynamic;
public dynamic Method01(ref int @dynamic)
{
return default(dynamic);
}
}
public struct MyStruct
{
public dynamic @dynamic;
public void Method02(out dynamic @dynamic)
{
@dynamic = default(dynamic);
}
}
public interface MyInterface
{
dynamic Method01(int n, dynamic @dynamic);
dynamic @dynamic(string n, dynamic d);
}
public delegate void myDelegate02(params dynamic[] @dynamic);
public delegate int @dynamic(int n);
namespace MyNamespace11
{
public enum @dynamic
{
}
}
}
namespace MyNamespace1
{
public class @dynamic
{
private dynamic Method01(out int n, dynamic d)
{
n = 0;
return default(dynamic);
}
}
namespace MyNamespace2
{
public struct @dynamic
{
private dynamic Method01(int n, ref dynamic d)
{
return default(dynamic);
}
}
namespace MyNamespace3
{
public interface @dynamic
{
dynamic Method01(int n, ref dynamic d);
}
}
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.typegeneral01.typegeneral01
{
// <Title> CLS Compliance for Dynamic </Title>
// <Description> Types Rule : Interface Methods (Compiler)
// CLS-compliant language compilers must have syntax for the situation where a single type implements
// two interfaces and each of those interfaces requires the definition of a method with the same name and signature.
// Such methods must be considered distinct and need not have the same implementation.
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
//[assembly: System.CLSCompliant(true)]
namespace MyNamespace
{
public class MyClass
{
public dynamic Method01(int x, int y = 0, int z = 1)
{
return default(dynamic);
}
//
public T Method02<T>(dynamic d = default(dynamic), string s = "QQQ")
{
return default(T);
}
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MyClass c = new MyClass();
c.Method01(999);
c.Method01(9, 8);
c.Method01(9, 8, 7);
c.Method01(999, z: 888);
c.Method01(999, z: 888, y: 666);
c.Method02<byte>();
c.Method02<int>(default(dynamic));
c.Method02<long>(default(dynamic), "CCC");
var v = new MyStruct<dynamic>();
v.Method11();
v.Method11(default(dynamic));
v.Method11(default(object), default(object), default(object));
v.Method12<int, dynamic>();
v.Method12<int, dynamic>(100);
v.Method12<int, dynamic>(-9999, default(dynamic));
return 0;
}
}
public struct MyStruct<T>
{
public dynamic Method11(T t = default(T), params dynamic[] ary)
{
return default(dynamic);
}
public T Method12<U, V>(U u = default(U), V v = default(V))
{
return default(T);
}
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.bug89385_a.bug89385_a
{
// <Title> regression test</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Foo
{
public static void Method(string s)
{
if (s == "abc")
Test.Result++;
}
public string Prop
{
get;
set;
}
}
public class Test
{
public Foo Foo
{
get;
set;
}
public static void DoExample(dynamic d)
{
Foo.Method(d.Prop);
}
public static int Result = -1;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
try
{
DoExample(new Foo()
{
Prop = "abc"
}
);
}
catch (System.Exception)
{
Test.Result--;
}
return Test.Result;
}
}
}
| |
//-------------------------------------------------------------------------------
// <copyright file="EmbeddedResourceLoaderFacts.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.IO.Resources
{
using System;
using System.IO;
using System.Reflection;
using System.Xml.XPath;
using FluentAssertions;
using Xunit;
public class EmbeddedResourceLoaderFacts
{
/// <summary>
/// Name for a non-existing text resource
/// </summary>
private const string NoTextResourceName = "EmbeddedTestResources.NoResource.txt";
/// <summary>
/// Name for a non-existing XML resource
/// </summary>
private const string NoXmlResourceName = "EmbeddedTestResources.NoResource.xml";
/// <summary>
/// Name for an XML resource
/// </summary>
private const string XmlResourceName = "EmbeddedTestResources.XmlResource.xml";
/// <summary>
/// Name for a text resource
/// </summary>
private const string TextResourceName = "EmbeddedTestResources.StringResource.txt";
/// <summary>
/// The object under test
/// </summary>
private readonly EmbeddedResourceLoader testee;
public EmbeddedResourceLoaderFacts()
{
this.testee = new EmbeddedResourceLoader();
}
/// <summary>
/// When a non-existing resource is loaded an <see cref="ArgumentException"/> is thrown.
/// </summary>
[Fact]
public void LoadNotExistingStreamResourceFromAssembly()
{
Assert.Throws<ArgumentException>(
() => this.testee.LoadResourceAsString(
Assembly.GetExecutingAssembly(),
string.Format("{0}.{1}", typeof(EmbeddedResourceLoaderFacts).Namespace, NoTextResourceName)));
}
/// <summary>
/// When a non-existing resource is loaded an <see cref="ArgumentException"/> is thrown.
/// </summary>
[Fact]
public void LoadNotExistingStreamResourceFromType()
{
Assert.Throws<ArgumentException>(
() => this.testee.LoadResourceAsXml(typeof(EmbeddedResourceLoaderFacts), NoTextResourceName));
}
/// <summary>
/// When a non-existing resource is loaded an <see cref="ArgumentException"/> is thrown.
/// </summary>
[Fact]
public void LoadNotExistingStringResourceFromAssembly()
{
Assert.Throws<ArgumentException>(
() => this.testee.LoadResourceAsString(
Assembly.GetExecutingAssembly(),
string.Format("{0}.{1}", typeof(EmbeddedResourceLoaderFacts).Namespace, NoTextResourceName)));
}
/// <summary>
/// When a non-existing resource is loaded an <see cref="ArgumentException"/> is thrown.
/// </summary>
[Fact]
public void LoadNotExistingStringResourceFromType()
{
Assert.Throws<ArgumentException>(
() => this.testee.LoadResourceAsString(typeof(EmbeddedResourceLoaderFacts), NoTextResourceName));
}
/// <summary>
/// When a non-existing resource is loaded an <see cref="ArgumentException"/> is thrown.
/// </summary>
[Fact]
public void LoadNotExistingXmlResourceFromAssembly()
{
Assert.Throws<ArgumentException>(
() => this.testee.LoadResourceAsXml(
Assembly.GetExecutingAssembly(),
string.Format("{0}.{1}", typeof(EmbeddedResourceLoaderFacts).Namespace, NoTextResourceName)));
}
/// <summary>
/// When a non-existing resource is loaded an <see cref="ArgumentException"/> is thrown.
/// </summary>
[Fact]
public void LoadNotExistingXmlResourceFromType()
{
Assert.Throws<ArgumentException>(
() => this.testee.LoadResourceAsXml(typeof(EmbeddedResourceLoaderFacts), NoXmlResourceName));
}
/// <summary>
/// Loads a resource from assembly and verifies the size of the resulting stream
/// </summary>
[Fact]
public void LoadStreamResourceFromAssembly()
{
Stream stream = this.testee.LoadResourceAsStream(
Assembly.GetExecutingAssembly(),
string.Format("{0}.{1}", typeof(EmbeddedResourceLoaderFacts).Namespace, XmlResourceName));
stream.Length.Should().BeGreaterOrEqualTo(200);
stream.Position.Should().Be(0);
}
/// <summary>
/// Loads a resource from type and verifies the size of the resulting stream
/// </summary>
[Fact]
public void LoadStreamResourceFromType()
{
Stream stream = this.testee.LoadResourceAsStream(typeof(EmbeddedResourceLoaderFacts), XmlResourceName);
stream.Length.Should().BeGreaterOrEqualTo(200);
stream.Position.Should().Be(0);
}
[Fact]
public void LoadNotExistingResourceAsStream()
{
Assert.Throws<ArgumentException>(
() => this.testee.LoadResourceAsStream(typeof(EmbeddedResourceLoaderFacts), NoTextResourceName));
}
/// <summary>
/// Loads a string resource from assembly and verifies the string is correct
/// </summary>
[Fact]
public void LoadStringResourceFromAssembly()
{
string result = this.testee.LoadResourceAsString(
Assembly.GetExecutingAssembly(),
string.Format("{0}.{1}", typeof(EmbeddedResourceLoaderFacts).Namespace, TextResourceName));
Assert.Equal("MyString", result);
}
/// <summary>
/// Loads a string resource from type and verifies the string is correct
/// </summary>
[Fact]
public void LoadStringResourceFromType()
{
string result = this.testee.LoadResourceAsString(typeof(EmbeddedResourceLoaderFacts), TextResourceName);
Assert.Equal("MyString", result);
}
/// <summary>
/// Loads a XML resource from assembly and verifies it is correct.
/// </summary>
[Fact]
public void LoadXmlResourceFromAssembly()
{
IXPathNavigable xml =
this.testee.LoadResourceAsXml(
Assembly.GetExecutingAssembly(),
string.Format("{0}.{1}", typeof(EmbeddedResourceLoaderFacts).Namespace, XmlResourceName));
Assert.True(xml.CreateNavigator().HasChildren);
}
/// <summary>
/// Loads a XML resource from type and verifies it is correct
/// </summary>
[Fact]
public void LoadXmlResourceFromType()
{
IXPathNavigable xmlNode =
this.testee.LoadResourceAsXml(typeof(EmbeddedResourceLoaderFacts), XmlResourceName);
Assert.True(xmlNode.CreateNavigator().HasChildren);
}
}
}
| |
using System;
using System.Threading.Tasks;
using VerifyXunit;
using Xunit;
[UsesVerify]
public class RewritingMethods
{
[Fact]
public void HandlesMethodsWithManyParameters()
{
var sample = new ClassWithNullableContext1();
var exception = Assert.Throws<ArgumentNullException>(() => sample.MethodWithManyParameters("", null, "", ""));
Assert.Equal("nonNullArg2", exception.ParamName);
exception = Assert.Throws<ArgumentNullException>(() => sample.MethodWithManyParameters("", "", "", null));
Assert.Equal("nonNullArg4", exception.ParamName);
sample.MethodWithManyParameters(null, "", "", "");
sample.MethodWithManyParameters("", "", null, "");
}
[Fact]
public void AllowsNullRefReturnValueFromUnconstainedGeneric()
{
var sample = new ClassWithRefReturns.Generic<string>();
var ret = sample.GetMaybeNullUnconstrainedRef();
Assert.Null(ret);
}
[Fact]
public void AllowsNullRefReturnValue()
{
var sample = new ClassWithRefReturns();
var ret = sample.GetNullRef();
Assert.Null(ret);
}
[Fact]
public void RequiresNonNullRefReturnValue()
{
var sample = new ClassWithRefReturns();
var exception = Assert.Throws<InvalidOperationException>(() => { sample.GetNonNullRef(); });
}
[Fact]
public void RequiresNonNullRefReturnValueFromNonNullGeneric()
{
var sample = new ClassWithRefReturns.GenericNonNull<string>(null);
var exception = Assert.Throws<InvalidOperationException>(() => { sample.GetNonNullRef(); });
}
[Fact]
public void AllowsNonNullRefReturnValueFromNonNullGeneric()
{
var sample = new ClassWithRefReturns.GenericNonNull<string>(string.Empty);
sample.GetNonNullRef();
}
[Fact]
public void AllowsNullOutputForNestedGenericMaybeNullOutArgumentWhenFalse()
{
var sample = new ClassWithGenericNestedClass.NestedNotNull<string>();
var ret = sample.MaybeNullOutValueWhenFalse(out var result);
Assert.False(ret);
Assert.Null(result);
}
[Fact]
public void RequiresNotNullForNestedGenericDisallowNullRefArgument()
{
var sample = new ClassWithGenericNestedClass.NestedUnconstrained<string>();
var exception = Assert.Throws<ArgumentNullException>(() => {
string value = null;
sample.DisallowedNullAndNotNullRefValue(ref value);
});
Assert.Equal("nonNullArg", exception.ParamName);
}
[Fact]
public void RequiresNotNullForNestedGenericNotNullRefArgument()
{
var sample = new ClassWithGenericNestedClass.NestedUnconstrained<string>();
var exception = Assert.Throws<InvalidOperationException>(() => {
var value = "";
sample.DisallowedNullAndNotNullRefValue(ref value);
});
}
[Fact]
public void AllowsNullReturnValueForMaybeNullGenericReturnValue()
{
var sample = new ClassWithNullableContext1();
var result = sample.GenericMaybeNullReturnValue<string>();
Assert.Null(result);
}
[Fact]
public void AllowsNullArgumentAndReturnValueForClassConstrainedGenericWithNullableParameter()
{
var sample = new ClassWithNullableContext2();
var result = sample.GenericClassWithNullableParam<string>(null);
Assert.Null(result);
}
[Fact]
public void AllowsNullArgumentAndReturnValueForNullableClassConstrainedGeneric()
{
var sample = new ClassWithNullableContext2();
var result = sample.GenericNullableClassWithNotNullableParam<string>(null);
Assert.Null(result);
}
[Fact]
public void RequiresNonNullReturnForNotNullReturnValue()
{
var sample = new ClassWithNullableContext2();
var exception = Assert.Throws<InvalidOperationException>(() => { sample.GenericNotNullReturnValue<string>(); });
}
[Fact]
public void AllowsNullArgumentAndReturnValueForUnconstrainedGeneric()
{
var sample = new ClassWithNullableContext1();
var result = sample.UnconstrainedGeneric<string>(null);
Assert.Null(result);
}
[Fact]
public void RequiresNonNullArgumentForNonNullGenericConstraint()
{
var sample = new ClassWithNullableContext1();
var exception = Assert.Throws<ArgumentNullException>(() => { sample.NotNullGeneric<string>(null); });
Assert.Equal("nonNullArg", exception.ParamName);
}
[Fact]
public void RequiresNonNullReturnForNonNullGenericConstraint()
{
var sample = new ClassWithNullableContext1();
var exception = Assert.Throws<InvalidOperationException>(() => { sample.NotNullGeneric<string>(""); });
}
[Fact]
public void RequiresNonNullArgumentWhenNullableReferenceTypeNotUsedInClassWithNullableContext1()
{
var sample = new ClassWithNullableContext1();
var exception = Assert.Throws<ArgumentNullException>(() => { sample.SomeMethod(null, ""); });
Assert.Equal("nonNullArg", exception.ParamName);
}
[Fact]
public void RequiresNonNullArgumentWhenNullableReferenceTypeNotUsedInClassWithNullableContext2()
{
var sample = new ClassWithNullableContext2();
var exception = Assert.Throws<ArgumentNullException>(() => { sample.SomeMethod(null, ""); });
Assert.Equal("nonNullArg", exception.ParamName);
}
[Fact]
public void AllowsNullWhenNullableReferenceTypeUsed()
{
var sample = new ClassWithNullableContext1();
sample.SomeMethod("", null);
}
[Fact]
public void AllowsNullWhenNullableReferenceTypeUsedInClassWithNullableContext2()
{
var sample = new ClassWithNullableContext2();
sample.SomeMethod("", null);
}
[Fact]
public void AllowsNullWithoutAttributeWhenNullableReferenceTypeUsedInClassWithNullableContext2()
{
var sample = new ClassWithNullableContext2();
sample.MethodWillNullableArg(null);
}
[Fact]
public Task RequiresNonNullMethodReturnValueWhenNullableReferenceTypeNotUsedInClassWithNullableContext1()
{
var sample = new ClassWithNullableContext1();
var exception = Assert.Throws<InvalidOperationException>(() => sample.MethodWithReturnValue(true));
return Verifier.Verify(exception.Message);
}
[Fact]
public Task RequiresNonNullMethodReturnValueWhenNullableReferenceTypeNotUsedInClassWithNullableContext2()
{
var sample = new ClassWithNullableContext2();
var exception = Assert.Throws<InvalidOperationException>(() => sample.MethodWithReturnValue(true));
return Verifier.Verify(exception.Message);
}
[Fact]
public void AllowsNullReturnValueWhenNullableReferenceTypeUsedInClassWithNullableContext1()
{
var sample = new ClassWithNullableContext1();
sample.MethodAllowsNullReturnValue();
}
[Fact]
public void AllowsNullReturnValueWhenNullableReferenceTypeUsedInClassWithNullableContext2()
{
var sample = new ClassWithNullableContext2();
sample.MethodAllowsNullReturnValue();
}
[Fact]
public void AllowsNullReturnValueWhenNullableReferenceTypeUsedInClassWithNullableReferenceMethod()
{
var sample = new ClassWithNullableReferenceMethod();
Assert.Null(sample.MethodAllowsNullReturnValue(""));
}
[Fact]
public void AllowsNullReturnValueWhenNullableDisabledInClassWithNullableContext1()
{
var sample = new ClassWithNullableContext1();
Assert.Null(sample.MethodWithNullableContext0());
}
[Fact]
public void AllowsNullReturnValueWhenNullableDisabledInClassWithNullableContext2()
{
var sample = new ClassWithNullableContext2();
Assert.Null(sample.MethodWithNullableContext0());
}
[Fact]
public void AllowsNullReturnValueWhenStaticNullableReferenceTypeUsedInClassWithNullableContext1()
{
Assert.Null(ClassWithNullableContext1.StaticMethodAllowsNullReturnValue(""));
}
[Fact]
public void AllowsNullReturnValueWhenStaticNullableReferenceTypeUsedInClassWithNullableContext2()
{
Assert.Null(ClassWithNullableContext2.StaticMethodAllowsNullReturnValue(""));
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace Microsoft.Tools.ServiceModel.ComSvcConfig
{
using System;
using System.Diagnostics;
using System.Configuration;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;
using System.Security;
using System.ServiceModel;
using System.ServiceModel.Configuration;
using Microsoft.Tools.ServiceModel;
using Microsoft.Tools.ServiceModel.SvcUtil;
// Usage
//
// new AtomicFile
// GetCurrent(readOnly)+
// Delete (once), OR GetCurrent(forUpdate)+
// Prepare
// Commit or Abort
//
// Abort may also be called before Prepare
class AtomicFile
{
bool prepared;
string originalFileName;
bool originalFileExists;
string tempFileName;
string backupOfOriginalFileName;
bool deleteOriginalFile;
public string OriginalFileName
{
get { return this.originalFileName; }
}
public bool OriginalFileExists
{
get { return this.originalFileExists; }
}
public AtomicFile(string fileName)
{
this.originalFileName = fileName;
this.originalFileExists = File.Exists(this.originalFileName);
this.tempFileName = null;
this.backupOfOriginalFileName = null;
this.deleteOriginalFile = false;
this.prepared = false;
}
public bool CurrentExists()
{
if ((this.tempFileName != null))
{
return true;
}
else
{
return this.originalFileExists;
}
}
public void Delete()
{
if (this.tempFileName != null)
{
// once you make changes, you cant ask for delete (we have no scenario to relax this restriction..)
throw new InvalidOperationException();
}
if (!this.originalFileExists)
{
// cant delete if the original file didnt exist
throw new InvalidOperationException();
}
this.deleteOriginalFile = true;
}
public string GetCurrentFileName(bool readOnly)
{
if (this.deleteOriginalFile)
{
// once you delete, you cant ask for this.
throw new InvalidOperationException();
}
if (this.tempFileName != null)
{
return this.tempFileName;
}
else if (this.originalFileExists)
{
if (readOnly)
{
return this.originalFileName;
}
else
{
this.tempFileName = GetTempFileName();
File.Copy(this.originalFileName, this.tempFileName);
return this.tempFileName;
}
}
else // there is no original file
{
if (readOnly)
{
return null; // nothing to read, caller should tolerate this
}
else
{
// want to update, have no file yet, create one..
this.tempFileName = GetTempFileName();
return this.tempFileName;
}
}
}
// must be called before Preparing
public bool HasBeenModified()
{
return (this.tempFileName != null || (this.originalFileExists && this.deleteOriginalFile));
}
public void Prepare()
{
if (this.tempFileName != null)
{
if (this.originalFileExists)
{
this.backupOfOriginalFileName = GetTempFileName();
File.Copy(this.originalFileName, this.backupOfOriginalFileName);
SafeDeleteFile(this.originalFileName);
}
File.Copy(this.tempFileName, this.originalFileName);
SafeDeleteFile(this.tempFileName);
}
else if (this.deleteOriginalFile)
{
this.backupOfOriginalFileName = GetTempFileName();
File.Copy(this.originalFileName, this.backupOfOriginalFileName);
SafeDeleteFile(this.originalFileName);
}
this.prepared = true;
}
public void Commit()
{
if (!this.prepared)
{
throw new InvalidOperationException();
}
SafeDeleteFile(this.backupOfOriginalFileName);
}
// keep track of whether we had a "clean" prepare / abort, if not clean we shouldnt delete the backups/tempFiles and point the user to them
public void Abort()
{
if (this.originalFileExists)
{
if ((this.backupOfOriginalFileName != null) && File.Exists(this.backupOfOriginalFileName))
{
SafeDeleteFile(this.originalFileName);
File.Copy(this.backupOfOriginalFileName, this.originalFileName);
}
}
else
{
SafeDeleteFile(this.originalFileName);
}
SafeDeleteFile(this.backupOfOriginalFileName);
SafeDeleteFile(this.tempFileName);
}
// safe as in handles null, and checks for existence first
internal static void SafeDeleteFile(string fileName)
{
if ((!string.IsNullOrEmpty(fileName)) && File.Exists(fileName))
{
File.Delete(fileName);
}
}
// this function guarantees to return the name of a temp file that doesnt exist
string GetTempFileName()
{
return Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.IO
{
// A MemoryStream represents a Stream in memory (ie, it has no backing store).
// This stream may reduce the need for temporary buffers and files in
// an application.
//
// There are two ways to create a MemoryStream. You can initialize one
// from an unsigned byte array, or you can create an empty one. Empty
// memory streams are resizable, while ones created with a byte array provide
// a stream "view" of the data.
public class MemoryStream : Stream
{
private byte[] _buffer; // Either allocated internally or externally.
private int _origin; // For user-provided arrays, start at this origin
private int _position; // read/write head.
[ContractPublicPropertyName("Length")]
private int _length; // Number of bytes within the memory stream
private int _capacity; // length of usable portion of buffer for stream
// Note that _capacity == _buffer.Length for non-user-provided byte[]'s
private bool _expandable; // User-provided buffers aren't expandable.
private bool _writable; // Can user write to this stream?
private bool _exposable; // Whether the array can be returned to the user.
private bool _isOpen; // Is this stream open or closed?
// <TODO>In V2, if we get support for arrays of more than 2 GB worth of elements,
// consider removing this constraing, or setting it to Int64.MaxValue.</TODO>
private const int MemStreamMaxLength = int.MaxValue;
public MemoryStream()
: this(0)
{
}
public MemoryStream(int capacity)
{
if (capacity < 0)
{
throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_NegativeCapacity);
}
_buffer = new byte[capacity];
_capacity = capacity;
_expandable = true;
_writable = true;
_exposable = true;
_origin = 0; // Must be 0 for byte[]'s created by MemoryStream
_isOpen = true;
}
public MemoryStream(byte[] buffer)
: this(buffer, true)
{
}
public MemoryStream(byte[] buffer, bool writable)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer);
}
_buffer = buffer;
_length = _capacity = buffer.Length;
_writable = writable;
_exposable = false;
_origin = 0;
_isOpen = true;
}
public MemoryStream(byte[] buffer, int index, int count)
: this(buffer, index, count, true, false)
{
}
public MemoryStream(byte[] buffer, int index, int count, bool writable)
: this(buffer, index, count, writable, false)
{
}
public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer);
}
if (index < 0)
{
throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
_buffer = buffer;
_origin = _position = index;
_length = _capacity = index + count;
_writable = writable;
_exposable = publiclyVisible; // Can TryGetBuffer return the array?
_expandable = false;
_isOpen = true;
}
public override bool CanRead
{
[Pure]
get
{ return _isOpen; }
}
public override bool CanSeek
{
[Pure]
get
{ return _isOpen; }
}
public override bool CanWrite
{
[Pure]
get
{ return _writable; }
}
private void EnsureWriteable()
{
if (!CanWrite)
{
throw new NotSupportedException(SR.NotSupported_UnwritableStream);
}
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
_isOpen = false;
_writable = false;
_expandable = false;
// Don't set buffer to null - allow TryGetBuffer & ToArray to work.
}
}
finally
{
// Call base.Close() to cleanup async IO resources
base.Dispose(disposing);
}
}
// returns a bool saying whether we allocated a new array.
private bool EnsureCapacity(int value)
{
// Check for overflow
if (value < 0)
{
throw new IOException(SR.IO_IO_StreamTooLong);
}
if (value > _capacity)
{
int newCapacity = value;
if (newCapacity < 256)
{
newCapacity = 256;
}
if (newCapacity < _capacity * 2)
{
newCapacity = _capacity * 2;
}
Capacity = newCapacity;
return true;
}
return false;
}
public override void Flush()
{
}
#pragma warning disable 1998 //async method with no await operators
public override async Task FlushAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
Flush();
}
#pragma warning restore 1998
public virtual bool TryGetBuffer(out ArraySegment<byte> buffer)
{
if (!_exposable)
{
buffer = default(ArraySegment<byte>);
return false;
}
buffer = new ArraySegment<byte>(_buffer, offset: _origin, count: (_length - _origin));
return true;
}
// -------------- PERF: Internal functions for fast direct access of MemoryStream buffer (cf. BinaryReader for usage) ---------------
// PERF: Internal sibling of GetBuffer, always returns a buffer (cf. GetBuffer())
internal byte[] InternalGetBuffer()
{
return _buffer;
}
// PERF: True cursor position, we don't need _origin for direct access
internal int InternalGetPosition()
{
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
return _position;
}
// PERF: Takes out Int32 as fast as possible
internal int InternalReadInt32()
{
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
int pos = (_position += 4); // use temp to avoid race
if (pos > _length)
{
_position = _length;
throw new EndOfStreamException(SR.IO_EOF_ReadBeyondEOF);
}
return (int)(_buffer[pos - 4] | _buffer[pos - 3] << 8 | _buffer[pos - 2] << 16 | _buffer[pos - 1] << 24);
}
// PERF: Get actual length of bytes available for read; do sanity checks; shift position - i.e. everything except actual copying bytes
internal int InternalEmulateRead(int count)
{
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
int n = _length - _position;
if (n > count)
{
n = count;
}
if (n < 0)
{
n = 0;
}
Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1.
_position += n;
return n;
}
// Gets & sets the capacity (number of bytes allocated) for this stream.
// The capacity cannot be set to a value less than the current length
// of the stream.
//
public virtual int Capacity
{
get
{
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
return _capacity - _origin;
}
set
{
// Only update the capacity if the MS is expandable and the value is different than the current capacity.
// Special behavior if the MS isn't expandable: we don't throw if value is the same as the current capacity
if (value < Length)
{
throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_SmallCapacity);
}
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
if (!_expandable && (value != Capacity))
{
throw new NotSupportedException(SR.NotSupported_MemStreamNotExpandable);
}
// MemoryStream has this invariant: _origin > 0 => !expandable (see ctors)
if (_expandable && value != _capacity)
{
if (value > 0)
{
byte[] newBuffer = new byte[value];
if (_length > 0)
{
Buffer.BlockCopy(_buffer, 0, newBuffer, 0, _length);
}
_buffer = newBuffer;
}
else
{
_buffer = null;
}
_capacity = value;
}
}
}
public override long Length
{
get
{
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
return _length - _origin;
}
}
public override long Position
{
get
{
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
return _position - _origin;
}
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
if (value > MemStreamMaxLength)
{
throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_StreamLength);
}
_position = _origin + (int)value;
}
}
public override int Read(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer);
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - offset < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
int n = _length - _position;
if (n > count)
{
n = count;
}
if (n <= 0)
{
return 0;
}
Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1.
if (n <= 8)
{
int byteCount = n;
while (--byteCount >= 0)
buffer[offset + byteCount] = _buffer[_position + byteCount];
}
else
Buffer.BlockCopy(_buffer, _position, buffer, offset, n);
_position += n;
return n;
}
public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer);
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - offset < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
return ReadAsyncImpl(buffer, offset, count, cancellationToken);
}
#pragma warning disable 1998 //async method with no await operators
private async Task<int> ReadAsyncImpl(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
return Read(buffer, offset, count);
}
#pragma warning restore 1998
public override int ReadByte()
{
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
if (_position >= _length)
{
return -1;
}
return _buffer[_position++];
}
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
// This implementation offers beter performance compared to the base class version.
// The parameter checks must be in sync with the base version:
if (destination == null)
{
throw new ArgumentNullException("destination");
}
if (bufferSize <= 0)
{
throw new ArgumentOutOfRangeException("bufferSize", SR.ArgumentOutOfRange_NeedPosNum);
}
if (!CanRead && !CanWrite)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
if (!destination.CanRead && !destination.CanWrite)
{
throw new ObjectDisposedException("destination", SR.ObjectDisposed_StreamClosed);
}
if (!CanRead)
{
throw new NotSupportedException(SR.NotSupported_UnreadableStream);
}
if (!destination.CanWrite)
{
throw new NotSupportedException(SR.NotSupported_UnwritableStream);
}
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Read() or Write() which a subclass might have overriden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Read/Write) when we are not sure.
if (GetType() != typeof(MemoryStream))
{
return base.CopyToAsync(destination, bufferSize, cancellationToken);
}
return CopyToAsyncImpl(destination, bufferSize, cancellationToken);
}
private async Task CopyToAsyncImpl(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// Avoid copying data from this buffer into a temp buffer:
// (require that InternalEmulateRead does not throw,
// otherwise it needs to be wrapped into try-catch-Task.FromException like memStrDest.Write below)
int pos = _position;
int n = InternalEmulateRead(_length - _position);
// If destination is not a memory stream, write there asynchronously:
MemoryStream memStrDest = destination as MemoryStream;
if (memStrDest == null)
{
await destination.WriteAsync(_buffer, pos, n, cancellationToken).ConfigureAwait(false);
}
else
{
memStrDest.Write(_buffer, pos, n);
}
}
public override long Seek(long offset, SeekOrigin loc)
{
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
if (offset > MemStreamMaxLength)
{
throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_StreamLength);
}
switch (loc)
{
case SeekOrigin.Begin:
{
int tempPosition = unchecked(_origin + (int)offset);
if (offset < 0 || tempPosition < _origin)
{
throw new IOException(SR.IO_IO_SeekBeforeBegin);
}
_position = tempPosition;
break;
}
case SeekOrigin.Current:
{
int tempPosition = unchecked(_position + (int)offset);
if (unchecked(_position + offset) < _origin || tempPosition < _origin)
{
throw new IOException(SR.IO_IO_SeekBeforeBegin);
}
_position = tempPosition;
break;
}
case SeekOrigin.End:
{
int tempPosition = unchecked(_length + (int)offset);
if (unchecked(_length + offset) < _origin || tempPosition < _origin)
{
throw new IOException(SR.IO_IO_SeekBeforeBegin);
}
_position = tempPosition;
break;
}
default:
throw new ArgumentException(SR.Argument_InvalidSeekOrigin);
}
Debug.Assert(_position >= 0, "_position >= 0");
return _position;
}
// Sets the length of the stream to a given value. The new
// value must be nonnegative and less than the space remaining in
// the array, Int32.MaxValue - origin
// Origin is 0 in all cases other than a MemoryStream created on
// top of an existing array and a specific starting offset was passed
// into the MemoryStream constructor. The upper bounds prevents any
// situations where a stream may be created on top of an array then
// the stream is made longer than the maximum possible length of the
// array (Int32.MaxValue).
//
public override void SetLength(long value)
{
if (value < 0 || value > int.MaxValue)
{
throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_StreamLength);
}
EnsureWriteable();
// Origin wasn't publicly exposed above.
Debug.Assert(MemStreamMaxLength == int.MaxValue); // Check parameter validation logic in this method if this fails.
if (value > (int.MaxValue - _origin))
{
throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_StreamLength);
}
int newLength = _origin + (int)value;
bool allocatedNewArray = EnsureCapacity(newLength);
if (!allocatedNewArray && newLength > _length)
{
Array.Clear(_buffer, _length, newLength - _length);
}
_length = newLength;
if (_position > newLength)
{
_position = newLength;
}
}
public virtual byte[] ToArray()
{
//BCLDebug.Perf(_exposable, "MemoryStream::GetBuffer will let you avoid a copy.");
int count = _length - _origin;
if (count == 0)
{
return Array.Empty<byte>();
}
byte[] copy = new byte[count];
Buffer.BlockCopy(_buffer, _origin, copy, 0, _length - _origin);
return copy;
}
public override void Write(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer);
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - offset < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
EnsureWriteable();
int i = _position + count;
// Check for overflow
if (i < 0)
{
throw new IOException(SR.IO_IO_StreamTooLong);
}
if (i > _length)
{
bool mustZero = _position > _length;
if (i > _capacity)
{
bool allocatedNewArray = EnsureCapacity(i);
if (allocatedNewArray)
{
mustZero = false;
}
}
if (mustZero)
{
Array.Clear(_buffer, _length, i - _length);
}
_length = i;
}
if ((count <= 8) && (buffer != _buffer))
{
int byteCount = count;
while (--byteCount >= 0)
{
_buffer[_position + byteCount] = buffer[offset + byteCount];
}
}
else
{
Buffer.BlockCopy(buffer, offset, _buffer, _position, count);
}
_position = i;
}
public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer);
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - offset < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
return WriteAsyncImpl(buffer, offset, count, cancellationToken);
}
#pragma warning disable 1998 //async method with no await operators
private async Task WriteAsyncImpl(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
Write(buffer, offset, count);
}
#pragma warning restore 1998
public override void WriteByte(byte value)
{
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
EnsureWriteable();
if (_position >= _length)
{
int newLength = _position + 1;
bool mustZero = _position > _length;
if (newLength >= _capacity)
{
bool allocatedNewArray = EnsureCapacity(newLength);
if (allocatedNewArray)
{
mustZero = false;
}
}
if (mustZero)
{
Array.Clear(_buffer, _length, _position - _length);
}
_length = newLength;
}
_buffer[_position++] = value;
}
// Writes this MemoryStream to another stream.
public virtual void WriteTo(Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException("stream", SR.ArgumentNull_Stream);
}
if (!_isOpen)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
stream.Write(_buffer, _origin, _length - _origin);
}
}
}
| |
// <copyright file="ObservableMasterSlaveCollection{T}.cs" company="Adrian Mos">
// Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework.
// </copyright>
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Threading;
using IX.Observable.Adapters;
using IX.Observable.DebugAide;
using IX.Observable.UndoLevels;
using IX.StandardExtensions.Contracts;
using IX.StandardExtensions.Threading;
using JetBrains.Annotations;
namespace IX.Observable
{
/// <summary>
/// An observable collection created from a master collection (to which updates go) and many slave, read-only
/// collections.
/// </summary>
/// <typeparam name="T">The type of the item.</typeparam>
/// <seealso cref="IX.Observable.ObservableListBase{T}" />
/// <seealso cref="IList{T}" />
/// <seealso cref="IReadOnlyCollection{T}" />
/// <seealso cref="ICollection{T}" />
/// <seealso cref="ICollection" />
/// <seealso cref="IList" />
/// <seealso cref="Observable.ObservableCollectionBase{TItem}" />
[DebuggerDisplay("ObservableMasterSlaveCollection, Count = {" + nameof(Count) + "}")]
[DebuggerTypeProxy(typeof(CollectionDebugView<>))]
[PublicAPI]
public class ObservableMasterSlaveCollection<T> : ObservableListBase<T>
{
/// <summary>
/// Initializes a new instance of the <see cref="ObservableMasterSlaveCollection{T}" /> class.
/// </summary>
public ObservableMasterSlaveCollection()
: base(new MultiListMasterSlaveListAdapter<T>())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ObservableMasterSlaveCollection{T}" /> class.
/// </summary>
/// <param name="context">The synchronization context to use, if any.</param>
public ObservableMasterSlaveCollection(SynchronizationContext context)
: base(
new MultiListMasterSlaveListAdapter<T>(),
context)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ObservableMasterSlaveCollection{T}" /> class.
/// </summary>
/// <param name="suppressUndoable">If set to <see langword="true" />, suppresses undoable capabilities of this collection.</param>
public ObservableMasterSlaveCollection(bool suppressUndoable)
: base(
new MultiListMasterSlaveListAdapter<T>(),
suppressUndoable)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ObservableMasterSlaveCollection{T}" /> class.
/// </summary>
/// <param name="context">The synchronization context to use, if any.</param>
/// <param name="suppressUndoable">If set to <see langword="true" />, suppresses undoable capabilities of this collection.</param>
public ObservableMasterSlaveCollection(
SynchronizationContext context,
bool suppressUndoable)
: base(
new MultiListMasterSlaveListAdapter<T>(),
context,
suppressUndoable)
{
}
/// <summary>
/// Gets the count after an add operation. Used internally.
/// </summary>
/// <value>
/// The count after add.
/// </value>
protected override int CountAfterAdd =>
((MultiListMasterSlaveListAdapter<T>)this.InternalContainer).MasterCount;
/// <summary>
/// Sets the master list.
/// </summary>
/// <typeparam name="TList">The type of the list.</typeparam>
/// <param name="list">The list.</param>
public void SetMasterList<TList>(TList list)
where TList : class, IList<T>, INotifyCollectionChanged
{
this.RequiresNotDisposed();
using (this.WriteLock())
{
((MultiListMasterSlaveListAdapter<T>)this.InternalContainer).SetMaster(list);
}
this.RaiseCollectionReset();
this.RaisePropertyChanged(nameof(this.Count));
this.RaisePropertyChanged(Constants.ItemsName);
}
/// <summary>
/// Sets a slave list.
/// </summary>
/// <typeparam name="TList">The type of the list.</typeparam>
/// <param name="list">The list.</param>
public void SetSlaveList<TList>(TList list)
where TList : class, IEnumerable<T>, INotifyCollectionChanged
{
this.RequiresNotDisposed();
using (this.WriteLock())
{
((MultiListMasterSlaveListAdapter<T>)this.InternalContainer).SetSlave(list);
}
this.RaiseCollectionReset();
this.RaisePropertyChanged(nameof(this.Count));
this.RaisePropertyChanged(Constants.ItemsName);
}
/// <summary>
/// Removes a slave list.
/// </summary>
/// <typeparam name="TList">The type of the list.</typeparam>
/// <param name="list">The list.</param>
public void RemoveSlaveList<TList>(TList list)
where TList : class, IEnumerable<T>, INotifyCollectionChanged
{
this.RequiresNotDisposed();
using (this.WriteLock())
{
((MultiListMasterSlaveListAdapter<T>)this.InternalContainer).RemoveSlave(list);
}
this.RaiseCollectionReset();
this.RaisePropertyChanged(nameof(this.Count));
this.RaisePropertyChanged(Constants.ItemsName);
}
/// <summary>
/// Adds an item to the <see cref="T:IX.Observable.ObservableCollectionBase`1" />.
/// </summary>
/// <param name="item">The object to add to the <see cref="T:IX.Observable.ObservableCollectionBase`1" />.</param>
/// <remarks>On concurrent collections, this method is write-synchronized.</remarks>
public override void Add(T item)
{
this.IncreaseIgnoreMustResetCounter();
base.Add(item);
}
/// <summary>
/// Inserts an item at the specified index.
/// </summary>
/// <param name="index">The index at which to insert.</param>
/// <param name="item">The item.</param>
public override void Insert(
int index,
T item)
{
this.IncreaseIgnoreMustResetCounter();
base.Insert(
index,
item);
}
/// <summary>
/// Removes the first occurrence of a specific object from the
/// <see cref="T:IX.Observable.ObservableCollectionBase`1" />.
/// </summary>
/// <param name="item">The object to remove from the <see cref="T:IX.Observable.ObservableCollectionBase`1" />.</param>
/// <returns>
/// <see langword="true" /> if <paramref name="item" /> was successfully removed from the
/// <see cref="T:IX.Observable.ObservableCollectionBase`1" />; otherwise, <see langword="false" />.
/// This method also returns false if <paramref name="item" /> is not found in the original
/// <see cref="T:IX.Observable.ObservableCollectionBase`1" />.
/// </returns>
/// <remarks>On concurrent collections, this method is write-synchronized.</remarks>
public override bool Remove(T item)
{
this.IncreaseIgnoreMustResetCounter();
if (base.Remove(item))
{
return true;
}
this.IncreaseIgnoreMustResetCounter(-1);
return false;
}
/// <summary>
/// Removes an item at the specified index.
/// </summary>
/// <param name="index">The index at which to remove an item from.</param>
public override void RemoveAt(int index)
{
this.RequiresNotDisposed();
T item;
using (ReadWriteSynchronizationLocker lockContext = this.ReadWriteLock())
{
if (index >= this.InternalContainer.Count)
{
return;
}
lockContext.Upgrade();
item = this.InternalContainer[index];
this.IncreaseIgnoreMustResetCounter();
this.InternalContainer.RemoveAt(index);
this.PushUndoLevel(new RemoveUndoLevel<T> { Index = index, RemovedItem = item });
}
this.RaiseCollectionChangedRemove(
item,
index);
this.RaisePropertyChanged(nameof(this.Count));
this.ContentsMayHaveChanged();
}
/// <summary>
/// Removes all items from the <see cref="ObservableMasterSlaveCollection{T}" />.
/// </summary>
/// <returns>An array containing the original collection items.</returns>
/// <remarks>On concurrent collections, this method is write-synchronized.</remarks>
protected override T[] ClearInternal()
{
this.RequiresNotDisposed();
T[] originalArray;
using (this.WriteLock())
{
var container = (MultiListMasterSlaveListAdapter<T>)this.InternalContainer;
this.IncreaseIgnoreMustResetCounter(container.SlavesCount + 1);
originalArray = new T[container.MasterCount];
container.MasterCopyTo(
originalArray,
0);
this.InternalContainer.Clear();
this.PushUndoLevel(new ClearUndoLevel<T> { OriginalItems = originalArray });
}
this.RaiseCollectionReset();
this.RaisePropertyChanged(nameof(this.Count));
this.ContentsMayHaveChanged();
return originalArray;
}
/// <summary>
/// Called when the contents may have changed so that proper notifications can happen.
/// </summary>
protected override void ContentsMayHaveChanged() => this.RaisePropertyChanged(Constants.ItemsName);
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace DocuSign.eSign.Model
{
/// <summary>
/// BulkRecipientsResponse
/// </summary>
[DataContract]
public partial class BulkRecipientsResponse : IEquatable<BulkRecipientsResponse>, IValidatableObject
{
public BulkRecipientsResponse()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="BulkRecipientsResponse" /> class.
/// </summary>
/// <param name="BulkRecipients">A complex type containing information about the bulk recipients in the response..</param>
/// <param name="EndPosition">The last position in the result set. .</param>
/// <param name="NextUri">The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. .</param>
/// <param name="PreviousUri">The postal code for the billing address..</param>
/// <param name="ResultSetSize">The number of results returned in this response. .</param>
/// <param name="StartPosition">Starting position of the current result set..</param>
/// <param name="TotalSetSize">The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response..</param>
public BulkRecipientsResponse(List<BulkRecipient> BulkRecipients = default(List<BulkRecipient>), string EndPosition = default(string), string NextUri = default(string), string PreviousUri = default(string), string ResultSetSize = default(string), string StartPosition = default(string), string TotalSetSize = default(string))
{
this.BulkRecipients = BulkRecipients;
this.EndPosition = EndPosition;
this.NextUri = NextUri;
this.PreviousUri = PreviousUri;
this.ResultSetSize = ResultSetSize;
this.StartPosition = StartPosition;
this.TotalSetSize = TotalSetSize;
}
/// <summary>
/// A complex type containing information about the bulk recipients in the response.
/// </summary>
/// <value>A complex type containing information about the bulk recipients in the response.</value>
[DataMember(Name="bulkRecipients", EmitDefaultValue=false)]
public List<BulkRecipient> BulkRecipients { get; set; }
/// <summary>
/// The last position in the result set.
/// </summary>
/// <value>The last position in the result set. </value>
[DataMember(Name="endPosition", EmitDefaultValue=false)]
public string EndPosition { get; set; }
/// <summary>
/// The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null.
/// </summary>
/// <value>The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. </value>
[DataMember(Name="nextUri", EmitDefaultValue=false)]
public string NextUri { get; set; }
/// <summary>
/// The postal code for the billing address.
/// </summary>
/// <value>The postal code for the billing address.</value>
[DataMember(Name="previousUri", EmitDefaultValue=false)]
public string PreviousUri { get; set; }
/// <summary>
/// The number of results returned in this response.
/// </summary>
/// <value>The number of results returned in this response. </value>
[DataMember(Name="resultSetSize", EmitDefaultValue=false)]
public string ResultSetSize { get; set; }
/// <summary>
/// Starting position of the current result set.
/// </summary>
/// <value>Starting position of the current result set.</value>
[DataMember(Name="startPosition", EmitDefaultValue=false)]
public string StartPosition { get; set; }
/// <summary>
/// The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response.
/// </summary>
/// <value>The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response.</value>
[DataMember(Name="totalSetSize", EmitDefaultValue=false)]
public string TotalSetSize { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class BulkRecipientsResponse {\n");
sb.Append(" BulkRecipients: ").Append(BulkRecipients).Append("\n");
sb.Append(" EndPosition: ").Append(EndPosition).Append("\n");
sb.Append(" NextUri: ").Append(NextUri).Append("\n");
sb.Append(" PreviousUri: ").Append(PreviousUri).Append("\n");
sb.Append(" ResultSetSize: ").Append(ResultSetSize).Append("\n");
sb.Append(" StartPosition: ").Append(StartPosition).Append("\n");
sb.Append(" TotalSetSize: ").Append(TotalSetSize).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as BulkRecipientsResponse);
}
/// <summary>
/// Returns true if BulkRecipientsResponse instances are equal
/// </summary>
/// <param name="other">Instance of BulkRecipientsResponse to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(BulkRecipientsResponse other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.BulkRecipients == other.BulkRecipients ||
this.BulkRecipients != null &&
this.BulkRecipients.SequenceEqual(other.BulkRecipients)
) &&
(
this.EndPosition == other.EndPosition ||
this.EndPosition != null &&
this.EndPosition.Equals(other.EndPosition)
) &&
(
this.NextUri == other.NextUri ||
this.NextUri != null &&
this.NextUri.Equals(other.NextUri)
) &&
(
this.PreviousUri == other.PreviousUri ||
this.PreviousUri != null &&
this.PreviousUri.Equals(other.PreviousUri)
) &&
(
this.ResultSetSize == other.ResultSetSize ||
this.ResultSetSize != null &&
this.ResultSetSize.Equals(other.ResultSetSize)
) &&
(
this.StartPosition == other.StartPosition ||
this.StartPosition != null &&
this.StartPosition.Equals(other.StartPosition)
) &&
(
this.TotalSetSize == other.TotalSetSize ||
this.TotalSetSize != null &&
this.TotalSetSize.Equals(other.TotalSetSize)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.BulkRecipients != null)
hash = hash * 59 + this.BulkRecipients.GetHashCode();
if (this.EndPosition != null)
hash = hash * 59 + this.EndPosition.GetHashCode();
if (this.NextUri != null)
hash = hash * 59 + this.NextUri.GetHashCode();
if (this.PreviousUri != null)
hash = hash * 59 + this.PreviousUri.GetHashCode();
if (this.ResultSetSize != null)
hash = hash * 59 + this.ResultSetSize.GetHashCode();
if (this.StartPosition != null)
hash = hash * 59 + this.StartPosition.GetHashCode();
if (this.TotalSetSize != null)
hash = hash * 59 + this.TotalSetSize.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace Kooboo.Dynamic.Calculator.Support
{
public class DataTypeCheck
{
public static string[] ReservedWords = { "int", "long", "float", "decimal", "currency", "date", "value", "while", "for", "do", "break", "continue", "foreach", "next", "else", "end", "endif", "string", "text", "char", "list", "rule", "expression", "function", "macro", "express", "int", "integer", "list", "sub", "set", ":=" };
public static string[] OperandFunctions = { "avg", "abs", "iif", "lcase", "left", "len", "mid", "right", "round", "sqrt", "ucase", "isnullorempty", "istrueornull", "isfalseornull", "trim", "rtrim", "ltrim", "dateadd", "concat", "date", "rpad", "lpad", "join", "searchstring", "day", "month", "year", "substring", "numericmax", "numericmin", "datemax", "datemin", "stringmax", "stringmin", "contains", "between", "indexof", "now", "replace", "eval", "remove", "quote", "pcase", "sin", "cos", "not", "isalldigits" };
public static string[] ArithOperators = { "^", "*", "/", "%", "+", "-" };
public static string[] LogicalOperators = { "and", "or" };
public static string[] ComparisonOperators = { "<", "<=", ">", ">=", "<>", "=" };
public static string[] AssignmentOperators = { ":=" };
/// <summary>
/// All digits....no decimals, commas, or -
/// </summary>
/// <param name="CheckString"></param>
/// <returns></returns>
public static bool IsAllDigits(string CheckString)
{
if (String.IsNullOrEmpty(CheckString) == true) return false;
CheckString = CheckString.Trim();
bool allDigits = true;
foreach (char c in CheckString)
{
if (Char.IsDigit(c) == false)
{
allDigits = false;
break;
}
}
return allDigits;
}
/// <summary>
/// The number of '.' in a string
/// </summary>
/// <param name="CheckString"></param>
/// <returns></returns>
public static int DecimalCount(string CheckString)
{
if (String.IsNullOrEmpty(CheckString) == true) return 0;
CheckString = CheckString.Trim();
int decimalCount = 0;
foreach (char c in CheckString)
{
if (c == '.') decimalCount++;
}
return decimalCount;
}
/// <summary>
/// Text items are surronded by strings.
/// </summary>
/// <param name="CheckString"></param>
/// <returns></returns>
public static bool IsText(string CheckString)
{
if (String.IsNullOrEmpty(CheckString) == true) return false;
CheckString = CheckString.Trim();
if (CheckString.Length == 1) return false;
if (CheckString.StartsWith("\"") == false) return false;
if (CheckString.EndsWith("\"") == false) return false;
return true;
}
/// <summary>
/// integers have all digits and no decimals. they can also start with -
/// </summary>
/// <param name="Token"></param>
/// <returns></returns>
public static bool IsInteger(string CheckString)
{
if (String.IsNullOrEmpty(CheckString) == true) return false;
CheckString = CheckString.Trim();
bool isInteger = true; // assume the value is an integer
int intPosition = 0; // the current position we are checking
foreach (char c in CheckString)
{
if (Char.IsNumber(c) == false)
{
if (c != '-')
{
isInteger = false;
break;
}
else if (intPosition != 0)
{
isInteger = false;
break;
}
}
intPosition++;
}
return isInteger;
}
public static bool IsDate(string CheckString)
{
if (String.IsNullOrEmpty(CheckString) == true) return false;
CheckString = CheckString.Trim();
DateTime d = DateTime.MinValue;
return DateTime.TryParse(CheckString, out d);
}
public static bool IsDouble(string CheckString)
{
if (String.IsNullOrEmpty(CheckString) == true) return false;
CheckString = CheckString.Trim();
bool isDouble = true; // assume the item is a double
int decimalCount = 0; // the number of decimals
int intPosition = 0;
foreach (char c in CheckString)
{
if (Char.IsNumber(c) == false)
{
if (c == '.')
{
decimalCount++;
}
else if ((c == '-') && (intPosition == 0))
{
// this is valid, keep going
}
else
{
isDouble = false;
break;
}
}
intPosition++;
}
if (isDouble == true)
{
// make sure there is only 1 decimal
if (decimalCount <= 1)
return true;
else
return false;
}
else
return false;
}
public static bool IsReservedWord(string OperandText)
{
bool isReservedWord = false;
if (String.IsNullOrEmpty(OperandText) == true) return false;
OperandText = OperandText.Trim().ToLower();
if (String.IsNullOrEmpty(OperandText) == true) return false;
for (int i = 0; i < ReservedWords.Length; i++)
{
if (OperandText == ReservedWords[i])
{
isReservedWord = true;
break;
}
}
return isReservedWord;
}
public static bool AnyPuncuation(string Text, out Char PuncMark)
{
PuncMark = ' ';
foreach (char c in Text)
{
if (Char.IsPunctuation(c) == true)
{
PuncMark = c;
return true;
}
}
return false;
}
public static bool IsOperandFunction(string OperandText)
{
if (String.IsNullOrEmpty(OperandText) == true) return false;
OperandText = OperandText.Trim().ToLower();
bool isOperandFunnction = false;
for (int i = 0; i < OperandFunctions.Length; i++)
{
if (OperandText == OperandFunctions[i])
{
isOperandFunnction = true;
break;
}
}
return isOperandFunnction;
}
public static bool IsOperator(string OperatorText)
{
if (String.IsNullOrEmpty(OperatorText) == true) return false;
OperatorText = OperatorText.Trim().ToLower();
bool isOperator = false;
for (int i = 0; i < ArithOperators.Length; i++)
{
if (OperatorText == ArithOperators[i])
{
isOperator = true;
break;
}
}
if (isOperator == true) return isOperator;
for (int i = 0; i < LogicalOperators.Length; i++)
{
if (OperatorText == LogicalOperators[i])
{
isOperator = true;
break;
}
}
if (isOperator == true) return isOperator;
for (int i = 0; i < ComparisonOperators.Length; i++)
{
if (OperatorText == ComparisonOperators[i])
{
isOperator = true;
break;
}
}
if (isOperator == true) return isOperator;
for (int i = 0; i < AssignmentOperators.Length; i++)
{
if (OperatorText == AssignmentOperators[i])
{
isOperator = true;
break;
}
}
if (isOperator == true) return isOperator;
return false;
}
public static bool IsBoolean(string CheckString)
{
if (String.IsNullOrEmpty(CheckString) == true) return false;
CheckString = CheckString.Trim().ToLower();
if (CheckString == "true") return true;
if (CheckString == "false") return true;
return false;
}
public static string RemoveTextQuotes(string CheckString)
{
if (IsText(CheckString) == false) return CheckString;
return CheckString.Substring(1, CheckString.Length - 2);
}
public static void FunctionDescription(string FunctionName, out string Syntax, out string Description, out string Example)
{
Syntax = "Unknown function";
Description = "";
Example = "";
switch (FunctionName.Trim().ToLower())
{
case "cos":
Description = "Calculates the cosine of a number.";
Syntax = "cos[p1] where p1 can be converted to doubles.";
Example = "cos[90] < 0";
break;
case "avg":
Description = "Calculates the average of a list of numbers. The list items must be able to convert to doubles.";
Syntax = "avg[p1, ..., pn] where p1,...,pn can be converted to doubles.";
Example = "avg[1, 2, 3] = 2";
break;
case "abs":
Description = "Calculates the absolute value of a numeric parameter.";
Syntax = "abs[p1] where p1 can be converted to a double.";
Example = "abs[-10] = 10";
break;
case "iif":
Description = "Performs an if-else-end";
Syntax = "iif[c, a, b] where c is the condition and must evaluate to a boolean. The value a is returned if c is true, otherwise, the value b is returned.";
Example = "iif[year[now[]] = 2008, \"2008\", \"Not 2008\"]";
break;
case "lcase":
Description = "Converts a string to lower case";
Syntax = "LCase[a]";
Example = "LCase[\"TEST\"] = \"test\"";
break;
case "left":
Description = "Returns the left number of characters from a string parameter.";
Syntax = "left[s, n] where s is the string and n is the number of characters";
Example = "left[\"abcd\", 2] = \"ab\"";
break;
case "len":
Description = "Returns te length of a string";
Syntax = "len[a] where a is a string variable";
Example = "len[\"test\"] = 4";
break;
case "mid":
Description = "Calculates the median for a list of numbers";
Syntax = "mid[p1, ..., pn] where p1, ..., pn are numberic values";
Example = "mid[1, 4, 100] = 4";
break;
case "right":
Description = "Returns the right number of characters from a string parameter";
Syntax = "right[s, n] where s is the string and n is the number of characters.";
Example = "right[\"abcd\", 2] = \"cd\"";
break;
case "round":
Description = "Rounds a numeric value to the number of decimal places";
Syntax = "round[n, d] where n is the numberic value to be rounded, and d is the number of decimal places.";
Example = "round[123.45, 0] = 123";
break;
case "sqrt":
Description = "Calculates the square root of a number.";
Syntax = "sqrt[a] where a is a numberic parameter";
Example = "sqrt[25] = 5";
break;
case "ucase":
Description = "Converts a string to upper case";
Syntax = "ucase[a]";
Example = "ucase[\"test\"] = \"TEST\"";
break;
case "isnullorempty":
Description = "Indicates is the parameter is null or empty.";
Syntax = "IsNullOrEmpty[a]";
Example = "";
break;
case "istrueornull":
Description = "Indicates if the parameter has the value true or is null;";
Syntax = "isTrueorNull[a]";
Example = "";
break;
case "isfalseornull":
Description = "Indicates if the parameter has the value false or is null";
Syntax = "IsFalseOrNull[a]";
Example = "IIF[IsFalseOrNull[a], \"false\", \"not false\"]";
break;
case "trim":
Description = "Trims the spaces from the entire string";
Syntax = "trim[a]";
Example = "";
break;
case "rtrim":
Description = "Trims the spaces from the right of a string";
Syntax = "rtrim[a]";
Example = "";
break;
case "ltrim":
Description = "Trims the spaces from the left of a string";
Syntax = "ltrim[a]";
Example = "";
break;
case "dateadd":
Description = "Adds an amount to a date. Please note that the amount may be negative.";
Syntax = "dateadd[date, \"type\", amount] where date is a valid date, and type is \"y\", \"m\", \"d\" or \"b\" (representing year, month, day, or business days) and amount is an integer";
Example = "dateadd[now[], \"b\", 5]";
break;
case "concat":
Description = "This operand function concatenates the parameters together to make a string.";
Syntax = "concat[p1, ..., pn]";
Example = "concat[\"This\", \" \", \"is\", \" \", \"a\", \" \", \"test\"] = \"This is a test\"";
break;
case "date":
Description = "Create a new date data type";
Syntax = "date[m, d, y] where m is an integer and is the month, d is an integer and is the day, and y is an integer and is the year";
Example = "date[3, 20, 2007]";
break;
case "rpad":
Description = "Pads a string on the right with new values";
Syntax = "rpad[a, b, n] where a and b are string values and n is numeric. The parameter p will be appended to the right of parameter a, n times.";
Example = "rpad[\"test\", \".\", 10] = \"test..........\"";
break;
case "lpad":
Description = "Pads a string on the left with new values";
Syntax = "lpad[a, b, n] where a and b are string values and n is numeric. The parameter p will be appended to the left of parameter a, n times.";
Example = "lpad[\"test\", \".\", 10] = \"..........test\"";
break;
case "join":
Description = "Joins a list of items together using a delimiter";
Syntax = "join[a, b1, ..., bn] where a is the delimiter and b1, ..., bn are the items to be joined.";
Example = "join[\" \", \"This\", \"is\", \"a\", \"test\"] = \"This is a test\"";
break;
case "searchstring":
Description = "Searches for a string within another string at a specified starting position";
Syntax = "SearchString[a, n, b] where a is the string that is being searched, b is the string that is being sought, and n is the start position in a";
Example = "SearchString[\"abcdefghijk\", 0, \"efg\"] = 4";
break;
case "day":
Description = "Returns the day of a date";
Syntax = "day[d1] where d1 is a date value";
Example = "day[3.20.1999] = 20";
break;
case "month":
Description = "Returns the month of a date";
Syntax = "month[d1] where d1 is a date value";
Example = "month[now[]] returns the current month";
break;
case "year":
Description = "Returns the year of a date";
Syntax = "year[d1] where d1 is a date";
Example = "year[now[]] returns the current year";
break;
case "substring":
Description = "Extracts a substring from a string";
Syntax = "SubString[s, a, b] where s is the string, a is the starting point, and b is the number of characters extracted.";
Example = "substring[\"abcdefghijk\", 3, 5] = \"defgh\"";
break;
case "numericmax":
Description = "Finds the maximum numeric value in a list";
Syntax = "NumericMax[p1, ..., pn]";
Example = "";
break;
case "numericmin":
Description = "Finds the numeric minimum value in a list";
Syntax = "NumericMin[p1, ..., pn]";
Example = "";
break;
case "datemax":
Description = "Returns the maximum date in the list";
Syntax = "datemax[d1, ..., dn] where d1, ..., dn are dates";
Example = "datemax[ 3.20.1999, 3.20.2005, 3.20.2008] = 3.20.2008";
break;
case "datemin":
Description = "Returns the minimum date in the list.";
Syntax = "datemin[d1, ..., dn] where d1, ..., dn are dates.";
Example = "datemax[ 3.20.1999, 3.20.2005, 3.20.2008] = 3.20.1999";
break;
case "stringmax":
Description = "Finds the maximum string in the list";
Syntax = "StringMax[p1, ..., pn]";
Example = "StringMax[\"Apple\", \"Zebra\"] = \"Zebra\"";
break;
case "stringmin":
Description = "Finds the minimum string in the list";
Syntax = "StringMax[p1, ..., pn]";
Example = "StringMax[\"Apple\", \"Zebra\"] = \"Apple\"";
break;
case "contains":
Description = "Indicates if the item is contained in the list.";
Syntax = "contains[p1, p2, ...., pn] If p1 in in the list p2, ..., pn, this function returns \"true\" otherwise, this function returns \"false\".";
Example = "contains[state, \"NY\", \"WA\", \"CA\"] = true";
break;
case "between":
Description = "Indicates if a value is between the other values. Please note that the comparison is inclusive.";
Syntax = "between[var, val1, val2] where var, val1, and val2 are integers. if var >= val1 and var <= val2 then the function returns \"true\", otherwise, the function return \"false\".";
Example = "between[fico, 400, 700] Note that fico is a variable.";
break;
case "indexof":
Description = "Returns the index of a list item.";
Syntax = "indexof[a, b1, ..., bn] If the list b1, ..., bn contains the value a, the index of the value is returned, otherwise, -1 is returned. Pleaes note that this is zero based indexing";
Example = "iif[indexof[a, \"CA\", \"NY\", \"WA\"] >= 0, \"found state\", \"not found\"]";
break;
case "now":
Description = "Returns the current date";
Syntax = "now[] This operand function takes no parameters";
Example = "year[now[]] = 2008";
break;
case "replace":
Description = "Replaces one string with another string";
Syntax = "Replace[a, b, c] where a is the search string, b is the value being replaced, and c is the value that is being inserted";
Example = "replace[\"3.20.2008\", \".\", \"-\"] = \"3-20-2008\"";
break;
case "eval":
Description = "Evaluates a string rule";
Syntax = "eval[r] where r is any valid rule";
Example = "eval[concat[\"1\", \"+\", \"2\"]] = 3";
break;
case "remove":
Description = "Removes the specified characters from the string";
Syntax = "remove[a, b] where a and b are string";
Example = "InsertOnSubmit[\"....this...is..a...test...\", \".a\"] = \"thisistest\"";
break;
case "quote":
Description = "Returns a double quote";
Syntax = "quote[]";
Example = "quote[] = \"";
break;
case "pcase":
Description = "Converts a string to Proper Case";
Syntax = "pcase[a] where a is a string";
Example = "join[\" \", pcase[\"dave\"], pcase[\"SMITH\"] ] = \"Dave Smith\"";
break;
case "sin":
Description = "Calcuates the sin of a number";
Syntax = "sin[a]";
Example = "sin[45] = 0.85";
break;
case "isalldigits":
Description = "Determine if the parameter contains all digits.";
Syntax = "isalldigits[p1] where p1 is a string parameter";
Example = "isalldigits[\"12345\"] = true";
break;
case "not":
Description = "Performs a NOT on a boolean parameter.";
Syntax = "not[p1] where p1 is a boolean parameter";
Example = "not[5<10]=false";
break;
}
}
public static bool IsNULL(string CheckString)
{
if (String.IsNullOrEmpty(CheckString) == true) return false;
CheckString = CheckString.Trim().ToLower();
return (CheckString == "null");
}
public static bool ContainsOperator(string CheckString, out string sOperand, out string sOperator)
{
// initialize the outgoing variables
sOperand = "";
sOperator = "";
// clean the token
if (String.IsNullOrEmpty(CheckString) == true) return false;
CheckString = CheckString.Trim();
// loop through the arith. operators
bool containsOperator = false; // assume an operator is not in the opperand
for (int i = 0; i < Support.DataTypeCheck.ArithOperators.Length; i++)
{
if (CheckString.EndsWith(Support.DataTypeCheck.ArithOperators[i]) == true)
{
containsOperator = true;
sOperator = Support.DataTypeCheck.ArithOperators[i];
sOperand = CheckString.Substring(0, CheckString.Length - sOperator.Length);
break;
}
}
if (containsOperator == true) return true;
// loop through the comparison operators
for (int i = 0; i < Support.DataTypeCheck.ComparisonOperators.Length; i++)
{
if (CheckString.EndsWith(Support.DataTypeCheck.ComparisonOperators[i]) == true)
{
containsOperator = true;
sOperator = Support.DataTypeCheck.ComparisonOperators[i];
sOperand = CheckString.Substring(0, CheckString.Length - sOperator.Length);
break;
}
}
if (containsOperator == true) return true;
return false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using System.Net.Http;
using LRWarehouse.Business;
using ILPathways.Business;
using Isle.BizServices;
using LRWarehouse.Business.ResourceV2;
using ILPathways.Common;
using ILPathways.Utilities;
namespace Isle.BizServices
{
public class ContentAttachmentServices
{
List<UsageRights> usageRightsCodes = new List<UsageRights>();
List<CodeItem> privilegeCodes = new List<CodeItem>();
ContentServices contentServices = new ContentServices();
CurriculumServices curriculumServices = new CurriculumServices();
//Get a list of attachments for a given node
public List<AttachmentDto> GetAttachments( int nodeID, ref bool valid, ref string status )
{
//Validate permission
var access = GetValidatedUserForContent( nodeID );
HandleStandardResponse( access, false, ref valid, ref status );
if ( !valid )
{
return null;
}
//Get the codes
usageRightsCodes = new ResourceV2Services().GetUsageRightsList();
privilegeCodes = contentServices.ContentPrivilegeCodes_SelectList();
//Get the list
var list = new List<AttachmentDto>();
foreach ( var item in access.Content.ChildItems.OrderBy( m => m.SortOrder ).ThenBy( m => m.Id ).ToList() )
{
list.Add( GetAttachmentDtoFromContentItem( item ) );
}
return list;
}
//
//Get a single attachment
public AttachmentDto GetAttachment( int nodeID, int contentID, ref bool valid, ref string status )
{
//Validate permission
var access = GetValidatedUserForContent( nodeID );
HandleStandardResponse( access, false, ref valid, ref status );
if ( !valid )
{
return null;
}
//Do the get
var content = contentServices.Get( contentID );
if ( content == null || content.Id == 0 )
{
valid = false;
status = "Error: invalid content ID";
return null;
}
//Convert
usageRightsCodes = new ResourceV2Services().GetUsageRightsList();
privilegeCodes = contentServices.ContentPrivilegeCodes_SelectList();
valid = true;
status = "okay";
return GetAttachmentDtoFromContentItem( content );
}
//Move an item to a new place in the order
public List<AttachmentDto> SetSortOrder( int nodeID, int attachmentID, int targetOrder, ref bool valid, ref string status )
{
//Validate permission
var access = GetValidatedUserForContent( nodeID );
HandleStandardResponse( access, false, ref valid, ref status );
if ( !valid )
{
return null;
}
//Get the list
var list = access.Content.ChildItems.OrderBy( m => m.SortOrder ).ThenBy( m => m.Title ).ToList();
//Do the move
try
{
//Ensure the attachment to move is actually part of this content's children
var toMove = list.FirstOrDefault( m => m.Id == attachmentID );
if ( toMove == null )
{
valid = false;
status = "Invalid attachment";
return null;
}
//Move the attachment to just before or just after the target, depending on which direction the attachment is moving
var targetToInsertNear = list.ElementAt( targetOrder - 1 );
toMove.SortOrder = targetToInsertNear.SortOrder + ( toMove.SortOrder > targetToInsertNear.SortOrder ? -1 : 1 ); //If moving up, -1 else +1
//Now that the list is ordered, shift things around in the database
ResetSortOrders( list );
//Set ref values
return GetAttachments( nodeID, ref valid, ref status );
}
catch ( Exception ex )
{
valid = false;
status = ex.Message;
return null;
}
}
//
//Delete an attachment
public void DeleteAttachment( int nodeID, int attachmentID, ref bool valid, ref string status )
{
//Validate permission
var access = GetValidatedUserForContent( nodeID );
HandleStandardResponse( access, false, ref valid, ref status );
if ( !valid )
{
return;
}
//Do the delete
try
{
//Ensure the content item is actually a part of the list of children for the node ID for which the user has been authenticated
if ( access.Content.ChildItems.FirstOrDefault( m => m.Id == attachmentID ) != null )
{
valid = contentServices.Delete( attachmentID, access.User.Id, ref status );
}
else
{
status = "Error: That attachment is not a member of the current content's attachments.";
valid = false;
}
}
catch ( Exception e )
{
valid = false;
status = e.Message;
}
}
//
//Update an attachment
public AttachmentDto UpdateAttachment( int nodeID, AttachmentDto attachment, ref bool valid, ref string status )
{
//Validate permission
var access = GetValidatedUserForContent( nodeID );
HandleStandardResponse( access, false, ref valid, ref status );
if ( !valid )
{
return null;
}
//Inputs should already be validated
//Do the update
try
{
//Ensure the content item is actually a part of the list of children for the node ID for which the user has been authenticated
if ( access.Content.ChildItems.FirstOrDefault( m => m.Id == attachment.ContentId ) != null )
{
var existing = access.Content.ChildItems.FirstOrDefault( m => m.Id == attachment.ContentId );
if( existing == null )
{
valid = false;
status = "Error: invalid attachment ID";
return null;
}
//Handle basic stuff
existing.Title = attachment.Title;
existing.Summary = attachment.Summary;
existing.PrivilegeTypeId = attachment.PrivilegeTypeId;
existing.ConditionsOfUseId = attachment.UsageRights.CodeId;
existing.ConditionsOfUseUrl = attachment.UsageRights.Url;
//Handle keywords
foreach ( var item in attachment.Keywords )
{
var contentKeyword = new ContentKeyword()
{
ContentId = existing.Id,
Created = DateTime.Now,
CreatedById = access.User.Id,
Keyword = item
};
existing.ContentKeywords.Add( contentKeyword );
}
//Handle Standards
var existingStandards = CurriculumServices.ContentStandard_Select( existing.Id );
var newStandards = new List<ContentStandard>();
foreach ( var standard in attachment.Standards )
{
var matchedStandard = existingStandards.FirstOrDefault( m => m.StandardId == standard.StandardId );
if ( matchedStandard == null )
{
newStandards.Add( new ContentStandard()
{
StandardId = standard.StandardId,
AlignmentTypeCodeId = standard.AlignmentTypeId,
UsageTypeId = standard.UsageTypeId,
Created = DateTime.Now,
ContentId = attachment.ContentId
} );
}
else
{
curriculumServices.ContentStandard_Update( matchedStandard.StandardRecordId, standard.AlignmentTypeId, standard.UsageTypeId, access.User.Id, ref status );
}
}
curriculumServices.ContentStandard_Add( nodeID, access.User.Id, newStandards );
//Do the update
contentServices.Update( existing );
//Return a fresh attachment
return GetAttachment( nodeID, existing.Id, ref valid, ref status );
}
else
{
status = "Error: That attachment is not a member of the current content's attachments.";
valid = false;
return null;
}
}
catch ( Exception e )
{
valid = false;
status = e.Message;
return null;
}
}
//
//Remove attachment standard
public void RemoveAttachmentStandard( int nodeID, int contentID, int recordID, ref bool valid, ref string status )
{
//Validate permission
var access = GetValidatedUserForContent( nodeID );
HandleStandardResponse( access, false, ref valid, ref status );
if ( !valid )
{
return;
}
//Do the delete
if ( access.Content.ChildItems.FirstOrDefault( m => m.Id == contentID ) != null )
{
valid = contentServices.ContentStandard_Delete( contentID, access.User.Id, recordID, ref status );
}
}
//
//Add a new attachment via URL
public AttachmentDto AddUrl( int nodeID, string url, ref bool valid, ref string status )
{
//Validate permission
var access = GetValidatedUserForContent( nodeID );
HandleStandardResponse( access, false, ref valid, ref status );
if ( !valid )
{
return null;
}
//Construct the attachment
var content = new ContentItem()
{
Title = "Web URL: " + url,
FileName = url,
CreatedById = access.User.Id,
Created = DateTime.Now,
DocumentUrl = url,
ParentId = nodeID,
TypeId = 41, //URL
SortOrder = 5,
StatusId = ContentItem.INPROGRESS_STATUS
};
//Create the attachment
var contentID = contentServices.Create_ef( content, ref status );
if ( contentID == 0 )
{
valid = false;
return null;
}
//Update Sort Orders
var list = curriculumServices.GetCurriculumNodeForEdit( access.Content.Id, access.User ).ChildItems;
ResetSortOrders( list );
//Return a full representation of the attachment
return GetAttachment( nodeID, contentID, ref valid, ref status );
}
//
//Save a file uploaded from a device
public AttachmentDto UploadDeviceFile( int nodeID, HttpPostedFile file, string filePath, string savingUrl, ref bool valid, ref string status )
{
try
{
//Get the file bytes
var temp = new MemoryStream();
file.InputStream.Position = 0;
file.InputStream.CopyTo( temp );
var fileBytes = temp.ToArray();
temp.Dispose();
file.InputStream.Position = 0;
//Create the attachment file object
var attachment = new AttachmentFile(){
FileName = file.FileName,
MimeType = file.ContentType,
FileBytes = fileBytes,
FileStream = file.InputStream
};
//Do the save
var contentID = SaveNewAttachmentFile( nodeID, attachment, filePath, savingUrl, ref valid, ref status );
if ( contentID == 0 )
{
valid = false;
//Status already set
return null;
}
return GetAttachment( nodeID, contentID, ref valid, ref status );
}
catch ( Exception ex )
{
valid = false;
status = ex.Message;
return null;
}
}
//
//Save a file from Google Drive
public AttachmentDto UploadGoogleDriveFile( int nodeID, string name, string mimeType, string url, string token, string filePath, string savingUrl, ref bool valid, ref string status )
{
try
{
//Try to ensure the file has an extension
try
{
var exportFormat = url.Split( new string[] { "&exportFormat=" }, StringSplitOptions.RemoveEmptyEntries )[ 1 ];
if ( name.IndexOf( "." + exportFormat ) == -1 && exportFormat.Length > 0 )
{
name = name + "." + exportFormat;
}
}
catch { }
//Get the file bytes
var getter = new HttpClient();
getter.DefaultRequestHeaders.Add( "User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36" );
getter.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue( "Bearer", token );
var result = getter.GetAsync( url ).Result.Content;
//Create the attachment file object
var attachment = new AttachmentFile()
{
FileName = name,
MimeType = mimeType,
FileBytes = result.ReadAsByteArrayAsync().Result,
FileStream = result.ReadAsStreamAsync().Result
};
//Do the save
var contentID = SaveNewAttachmentFile( nodeID, attachment, filePath, savingUrl, ref valid, ref status );
if ( contentID == 0 )
{
valid = false;
//Status already set
return null;
}
return GetAttachment( nodeID, contentID, ref valid, ref status );
}
catch ( Exception ex )
{
valid = false;
status = ex.Message;
return null;
}
}
//
//Save a file and return its content ID
public int SaveNewAttachmentFile( int nodeID, AttachmentFile file, string filePath, string savingUrl, ref bool valid, ref string status )
{
//Validate permission
var access = GetValidatedUserForContent( nodeID );
HandleStandardResponse( access, false, ref valid, ref status );
if ( !valid )
{
return 0;
}
//Validate the file
ValidateFile( file.FileStream, ref valid, ref status );
if ( !valid )
{
return 0;
}
//Build content item
var attachment = new ContentItem()
{
ParentId = access.Content.Id,
Title = file.FileName,
StatusId = ContentItem.INPROGRESS_STATUS,
PrivilegeTypeId = ContentItem.PUBLIC_PRIVILEGE,
TypeId = ContentItem.DOCUMENT_CONTENT_ID,
MimeType = file.MimeType,
CreatedById = access.User.Id,
Created = DateTime.Now,
LastUpdatedById = access.User.Id,
SortOrder = 5
};
//Build the document object
var doc = new DocumentVersion()
{
RowId = new Guid(),
CreatedById = access.User.Id,
Created = DateTime.Now,
FileDate = DateTime.Now,
LastUpdatedById = access.User.Id,
FileName = FileSystemHelper.SanitizeFilename( Path.GetFileNameWithoutExtension( file.FileName ) + Path.GetExtension( file.FileName ).ToLower() ),
MimeType = file.MimeType,
FilePath = filePath,
};
doc.Title = Path.GetFileNameWithoutExtension( doc.FileName );
doc.ResourceUrl = savingUrl + "/" + doc.FileName;
//Save the file
try
{
FileSystemHelper.CreateDirectory( filePath );
var diskFile = filePath + "\\" + file.FileName;
File.WriteAllBytes( diskFile, file.FileBytes );
}
catch ( Exception ex )
{
valid = false;
status = ex.Message.ToString();
LoggingHelper.LogError( ex, "ContentAttachmentServices.SaveFile( " + filePath + ", " + file.FileName + ")" );
return 0;
}
//Set resource data
doc.SetResourceData( file.FileBytes.LongLength, file.FileBytes );
var docID = contentServices.DocumentVersionCreate( doc, ref status );
if ( string.IsNullOrWhiteSpace( docID ) )
{
valid = false;
status = "Error setting resource data";
return 0;
}
doc.RowId = new Guid( docID );
//Create new ContentItem
attachment.DocumentRowId = doc.RowId;
attachment.DocumentUrl = doc.ResourceUrl;
var fileID = contentServices.Create( attachment, ref status );
if ( fileID == 0 )
{
valid = false;
status = "Error updating content item after uploading document: " + status;
return 0;
}
//Fix sort orders
//Refresh the list of child items
var updatedNode = curriculumServices.GetCurriculumNodeForEdit( nodeID, access.User );
ResetSortOrders( updatedNode.ChildItems );
//Success
valid = true;
status = "okay";
return fileID;
}
//
//Get an attachment's image, or create it if necessary
public string GetAttachmentImage( int nodeID, int contentID, bool generateIfMissing, ref bool isBeingGenerated, ref bool valid, ref string status )
{
if ( generateIfMissing )
{
//Validate permission
var access = GetValidatedUserForContent( nodeID );
HandleStandardResponse( access, false, ref valid, ref status );
if ( !valid )
{
return "";
}
//Verify that the target attachment actually belongs to the node
var attachment = access.Content.ChildItems.FirstOrDefault( m => m.Id == contentID );
if ( attachment != null )
{
return DetermineImageUrl( attachment, true, true, ref isBeingGenerated );
}
else
{
valid = false;
status = "Error: invalid attachment.";
return "";
}
}
else
{
var attachment = contentServices.Get(contentID);
return DetermineImageUrl( attachment, false, false, ref isBeingGenerated );
}
}
#region Helper Methods
//Get AttachmentDto from ContentItem
protected AttachmentDto GetAttachmentDtoFromContentItem( ContentItem item )
{
//Prevent errors
if( usageRightsCodes == null || usageRightsCodes.Count() == 0 )
{
usageRightsCodes = new ResourceV2Services().GetUsageRightsList();
}
if( privilegeCodes == null || privilegeCodes.Count() == 0 )
{
privilegeCodes = contentServices.ContentPrivilegeCodes_SelectList();
}
//Assign the correct usage rights
UsageRights matchedRights = usageRightsCodes.FirstOrDefault( m => m.CodeId == item.ConditionsOfUseId ) ?? usageRightsCodes.FirstOrDefault( m => m.Unknown );
//Set the URL if using a custom URL
matchedRights.Url = item.ConditionsOfUseUrl;
var generatingImage = false;
var thumbnailUrl = DetermineImageUrl( item, true, true, ref generatingImage );
return new AttachmentDto()
{
ContentId = item.Id,
ResourceId = item.ResourceIntId,
Url = item.DocumentUrl,
SortOrder = item.SortOrder,
ContentTypeId = item.TypeId,
Title = item.Title,
FileName = item.FileName,
Summary = item.Summary,
Keywords = ( item.ContentKeywords ?? new List<ContentKeyword>() ).Select( m => m.Keyword ).ToList(),
PrivilegeTypeId = item.PrivilegeTypeId,
PrivilegeTypeTitle = privilegeCodes.FirstOrDefault( m => m.Id == item.PrivilegeTypeId ).Title,
UsageRights = matchedRights,
ImageUrl = thumbnailUrl,
ImageInProgress = generatingImage,
Standards = GetStandards( item )
};
}
//Arbitrarily reorder items
protected void ResetSortOrders( List<ContentItem> list )
{
//Ensure the list is ordered
list = list.OrderBy( m => m.SortOrder ).ThenBy( m => m.Title ).ToList();
//Assign arbitrary sort order to all items - have to do this to overcome default sort order
var order = 10;
var tracker = new Dictionary<int, int>();
foreach ( var item in list )
{
tracker.Add( item.Id, item.SortOrder ); //Track the item for comparison later
item.SortOrder = order;
order = order + 10;
}
//Save any applicable changes
foreach ( var item in list )
{
if ( tracker[ item.Id ] != item.SortOrder ) //Only update if we need to
{
contentServices.Update( item );
}
}
}
//
//Get a user and a content item along with the user's level of access to that item
public ValidationPermissions GetValidatedUserForContent( int contentID )
{
var permissions = new ValidationPermissions();
permissions.User = AccountServices.GetUserFromSession();
if ( permissions.User == null || permissions.User.Id == 0 )
{
return permissions;
}
permissions.Content = curriculumServices.GetCurriculumNodeForEdit( contentID, permissions.User );
if ( permissions.Content == null || permissions.Content.Id == 0 )
{
return permissions;
}
//Admin Check
//Hack for specific admin IDs removed
if ( permissions.User.TopAuthorization < ( int ) EUserRole.StateAdministrator )
{
permissions.CanRead = true;
permissions.CanWrite = true;
return permissions;
}
//Check to see if the user created the content
if ( permissions.Content.CreatedById == permissions.User.Id )
{
permissions.CanRead = true;
permissions.CanWrite = true;
return permissions;
}
//Check for partner association with top level node
var topNodeID = permissions.Content.ParentId > 0 ? curriculumServices.GetCurriculumIDForNode( permissions.Content ) : permissions.Content.Id;
var topPartner = ContentServices.ContentPartner_Get( topNodeID, permissions.User.Id );
if ( topPartner == null || topPartner.Id == 0 )
{
return permissions;
}
//Check third-party access privileges
var privileges = SecurityManager.GetGroupObjectPrivileges( permissions.User, "IOER.controls.Authoring" );
permissions.CanRead = topPartner.PartnerTypeId > 0;
permissions.CanWrite = topPartner.PartnerTypeId >= 2 || privileges.WritePrivilege > ( int ) ILPathways.Business.EPrivilegeDepth.Region;
return permissions;
}
//
//Run boilerplate checks and send a vanilla response to common problems
private void HandleStandardResponse( ValidationPermissions access, bool requireWriteAccess, ref bool valid, ref string status )
{
valid = false;
if ( access.User == null || access.User.Id == 0 )
{
status = "You must be logged in to do that.";
return;
}
if ( access.Content == null || access.Content.Id == 0 )
{
status = "Invalid Content Selected.";
return;
}
if ( access.CanRead == false )
{
status = "You are not authorized to access that.";
return;
}
if ( requireWriteAccess && access.CanWrite == false )
{
status = "You are not authorized to do that.";
return;
}
valid = true;
status = "okay";
return;
}
//
//Determine an image to use, ending with most preferable (if more than one URL is present)
public string DetermineImageUrl( ContentItem item, bool updateIfMissing, bool generateIfMissing, ref bool isBeingGenerated )
{
var url = "";
isBeingGenerated = false;
//Try to load from database
url = !string.IsNullOrWhiteSpace( item.ResourceThumbnailImageUrl ) ? item.ResourceThumbnailImageUrl : url;
url = !string.IsNullOrWhiteSpace( item.ResourceImageUrl ) ? item.ResourceImageUrl : url;
url = !string.IsNullOrWhiteSpace( item.ImageUrl ) ? item.ImageUrl : url;
if ( !string.IsNullOrWhiteSpace( url ) )
{
return url;
}
//Check file system and update the content item if necessary
var thumbnailFolder = UtilityManager.GetAppKeyValue( "serverThumbnailFolder", @"\\OERDATASTORE\OerThumbs\large\" );
if ( File.Exists( thumbnailFolder + "content-" + item.Id + "-large.png" ) )
{
var template = UtilityManager.GetAppKeyValue( "thumbnailTemplate", "//ioer.ilsharedlearning.org/OERThumbs/large/{0}-large.png" );
url = template.Replace( "{0}", "content-" + item.Id.ToString() );
if ( updateIfMissing )
{
item.ImageUrl = url;
contentServices.Update( item );
}
return url;
}
//Create the thumbnail if it isn't already queued up
if ( generateIfMissing )
{
var queued = ThumbnailServices.ExamineChain().FirstOrDefault( m => m.Url == item.DocumentUrl );
if ( queued == null )
{
ThumbnailServices.CreateThumbnail( "content-" + item.Id, item.DocumentUrl, true );
}
isBeingGenerated = true;
}
return url;
}
//
//Get a list of standards for a given Content Item
public List<StandardDto> GetStandards( ContentItem content )
{
var data = CurriculumServices.ContentStandard_Select( content.Id );
var output = new List<StandardDto>();
foreach ( var item in data )
{
var code = "Standard";
try
{
code = string.IsNullOrWhiteSpace( item.NotationCode ) ? item.Description.Substring( 0, 20 ) + "..." : item.NotationCode;
}
catch { }
output.Add( new StandardDto()
{
StandardId = item.StandardId,
RecordId = item.StandardRecordId,
Code = code,
Text = item.Description,
UsageTypeId = item.UsageTypeId,
AlignmentTypeId = item.AlignmentTypeCodeId
} );
}
return output;
}
//
//Validate file
public void ValidateFile( Stream inputStream, ref bool valid, ref string status )
{
//Check size
var max = UtilityManager.GetAppKeyValue( "maxDocumentSize", 35000000 );
if ( inputStream.Length > max )
{
valid = false;
status = "File is too large. Maximum allowed size is " + ( max / 1024 ) + " KB.";
return;
}
//Check for viruses
new VirusScanner().Scan( inputStream, ref valid, ref status );
}
//
#endregion
#region Helper Classes
public class AttachmentDto
{
public int ContentId { get; set; }
public int ResourceId { get; set; }
public string Url { get; set; }
public int SortOrder { get; set; }
public int ContentTypeId { get; set; }
public string Title { get; set; }
public string Summary { get; set; }
public string FileName { get; set; }
public List<string> Keywords { get; set; }
public int PrivilegeTypeId { get; set; }
public string PrivilegeTypeTitle { get; set; }
public UsageRights UsageRights { get; set; }
public string ImageUrl { get; set; }
public bool ImageInProgress { get; set; }
public List<StandardDto> Standards { get; set; }
}
//
public class StandardDto
{
public int RecordId { get; set; } //database row int ID
public int StandardId { get; set; } //ID of the standard in the standards table
public string Code { get; set; }
public string Text { get; set; }
public int UsageTypeId { get; set; }
public int AlignmentTypeId { get; set; }
}
//
public class ValidationPermissions
{
public Patron User { get; set; }
public ContentItem Content { get; set; }
public bool CanWrite { get; set; }
public bool CanRead { get; set; }
}
//
public class AttachmentFile
{
public string FileName { get; set; }
public string MimeType { get; set; }
public byte[] FileBytes { get; set; }
public Stream FileStream { get; set; }
}
#endregion
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the PnTransaccion class.
/// </summary>
[Serializable]
public partial class PnTransaccionCollection : ActiveList<PnTransaccion, PnTransaccionCollection>
{
public PnTransaccionCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>PnTransaccionCollection</returns>
public PnTransaccionCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
PnTransaccion o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the PN_transaccion table.
/// </summary>
[Serializable]
public partial class PnTransaccion : ActiveRecord<PnTransaccion>, IActiveRecord
{
#region .ctors and Default Settings
public PnTransaccion()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public PnTransaccion(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public PnTransaccion(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public PnTransaccion(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("PN_transaccion", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdTransac = new TableSchema.TableColumn(schema);
colvarIdTransac.ColumnName = "id_transac";
colvarIdTransac.DataType = DbType.Int32;
colvarIdTransac.MaxLength = 0;
colvarIdTransac.AutoIncrement = true;
colvarIdTransac.IsNullable = false;
colvarIdTransac.IsPrimaryKey = true;
colvarIdTransac.IsForeignKey = false;
colvarIdTransac.IsReadOnly = false;
colvarIdTransac.DefaultSetting = @"";
colvarIdTransac.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdTransac);
TableSchema.TableColumn colvarIdExpediente = new TableSchema.TableColumn(schema);
colvarIdExpediente.ColumnName = "id_expediente";
colvarIdExpediente.DataType = DbType.Int64;
colvarIdExpediente.MaxLength = 0;
colvarIdExpediente.AutoIncrement = false;
colvarIdExpediente.IsNullable = false;
colvarIdExpediente.IsPrimaryKey = false;
colvarIdExpediente.IsForeignKey = false;
colvarIdExpediente.IsReadOnly = false;
colvarIdExpediente.DefaultSetting = @"";
colvarIdExpediente.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdExpediente);
TableSchema.TableColumn colvarIdArea = new TableSchema.TableColumn(schema);
colvarIdArea.ColumnName = "id_area";
colvarIdArea.DataType = DbType.Int32;
colvarIdArea.MaxLength = 0;
colvarIdArea.AutoIncrement = false;
colvarIdArea.IsNullable = false;
colvarIdArea.IsPrimaryKey = false;
colvarIdArea.IsForeignKey = false;
colvarIdArea.IsReadOnly = false;
colvarIdArea.DefaultSetting = @"";
colvarIdArea.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdArea);
TableSchema.TableColumn colvarFechaMov = new TableSchema.TableColumn(schema);
colvarFechaMov.ColumnName = "fecha_mov";
colvarFechaMov.DataType = DbType.DateTime;
colvarFechaMov.MaxLength = 0;
colvarFechaMov.AutoIncrement = false;
colvarFechaMov.IsNullable = true;
colvarFechaMov.IsPrimaryKey = false;
colvarFechaMov.IsForeignKey = false;
colvarFechaMov.IsReadOnly = false;
colvarFechaMov.DefaultSetting = @"";
colvarFechaMov.ForeignKeyTableName = "";
schema.Columns.Add(colvarFechaMov);
TableSchema.TableColumn colvarEstado = new TableSchema.TableColumn(schema);
colvarEstado.ColumnName = "estado";
colvarEstado.DataType = DbType.AnsiStringFixedLength;
colvarEstado.MaxLength = 1;
colvarEstado.AutoIncrement = false;
colvarEstado.IsNullable = true;
colvarEstado.IsPrimaryKey = false;
colvarEstado.IsForeignKey = false;
colvarEstado.IsReadOnly = false;
colvarEstado.DefaultSetting = @"";
colvarEstado.ForeignKeyTableName = "";
schema.Columns.Add(colvarEstado);
TableSchema.TableColumn colvarComentario = new TableSchema.TableColumn(schema);
colvarComentario.ColumnName = "comentario";
colvarComentario.DataType = DbType.AnsiString;
colvarComentario.MaxLength = -1;
colvarComentario.AutoIncrement = false;
colvarComentario.IsNullable = true;
colvarComentario.IsPrimaryKey = false;
colvarComentario.IsForeignKey = false;
colvarComentario.IsReadOnly = false;
colvarComentario.DefaultSetting = @"";
colvarComentario.ForeignKeyTableName = "";
schema.Columns.Add(colvarComentario);
TableSchema.TableColumn colvarDebCred = new TableSchema.TableColumn(schema);
colvarDebCred.ColumnName = "deb_cred";
colvarDebCred.DataType = DbType.Int32;
colvarDebCred.MaxLength = 0;
colvarDebCred.AutoIncrement = false;
colvarDebCred.IsNullable = true;
colvarDebCred.IsPrimaryKey = false;
colvarDebCred.IsForeignKey = false;
colvarDebCred.IsReadOnly = false;
colvarDebCred.DefaultSetting = @"";
colvarDebCred.ForeignKeyTableName = "";
schema.Columns.Add(colvarDebCred);
TableSchema.TableColumn colvarNumTranf = new TableSchema.TableColumn(schema);
colvarNumTranf.ColumnName = "num_tranf";
colvarNumTranf.DataType = DbType.Int64;
colvarNumTranf.MaxLength = 0;
colvarNumTranf.AutoIncrement = false;
colvarNumTranf.IsNullable = true;
colvarNumTranf.IsPrimaryKey = false;
colvarNumTranf.IsForeignKey = false;
colvarNumTranf.IsReadOnly = false;
colvarNumTranf.DefaultSetting = @"";
colvarNumTranf.ForeignKeyTableName = "";
schema.Columns.Add(colvarNumTranf);
TableSchema.TableColumn colvarFechaInf = new TableSchema.TableColumn(schema);
colvarFechaInf.ColumnName = "fecha_inf";
colvarFechaInf.DataType = DbType.DateTime;
colvarFechaInf.MaxLength = 0;
colvarFechaInf.AutoIncrement = false;
colvarFechaInf.IsNullable = true;
colvarFechaInf.IsPrimaryKey = false;
colvarFechaInf.IsForeignKey = false;
colvarFechaInf.IsReadOnly = false;
colvarFechaInf.DefaultSetting = @"";
colvarFechaInf.ForeignKeyTableName = "";
schema.Columns.Add(colvarFechaInf);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("PN_transaccion",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdTransac")]
[Bindable(true)]
public int IdTransac
{
get { return GetColumnValue<int>(Columns.IdTransac); }
set { SetColumnValue(Columns.IdTransac, value); }
}
[XmlAttribute("IdExpediente")]
[Bindable(true)]
public long IdExpediente
{
get { return GetColumnValue<long>(Columns.IdExpediente); }
set { SetColumnValue(Columns.IdExpediente, value); }
}
[XmlAttribute("IdArea")]
[Bindable(true)]
public int IdArea
{
get { return GetColumnValue<int>(Columns.IdArea); }
set { SetColumnValue(Columns.IdArea, value); }
}
[XmlAttribute("FechaMov")]
[Bindable(true)]
public DateTime? FechaMov
{
get { return GetColumnValue<DateTime?>(Columns.FechaMov); }
set { SetColumnValue(Columns.FechaMov, value); }
}
[XmlAttribute("Estado")]
[Bindable(true)]
public string Estado
{
get { return GetColumnValue<string>(Columns.Estado); }
set { SetColumnValue(Columns.Estado, value); }
}
[XmlAttribute("Comentario")]
[Bindable(true)]
public string Comentario
{
get { return GetColumnValue<string>(Columns.Comentario); }
set { SetColumnValue(Columns.Comentario, value); }
}
[XmlAttribute("DebCred")]
[Bindable(true)]
public int? DebCred
{
get { return GetColumnValue<int?>(Columns.DebCred); }
set { SetColumnValue(Columns.DebCred, value); }
}
[XmlAttribute("NumTranf")]
[Bindable(true)]
public long? NumTranf
{
get { return GetColumnValue<long?>(Columns.NumTranf); }
set { SetColumnValue(Columns.NumTranf, value); }
}
[XmlAttribute("FechaInf")]
[Bindable(true)]
public DateTime? FechaInf
{
get { return GetColumnValue<DateTime?>(Columns.FechaInf); }
set { SetColumnValue(Columns.FechaInf, value); }
}
#endregion
//no foreign key tables defined (0)
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(long varIdExpediente,int varIdArea,DateTime? varFechaMov,string varEstado,string varComentario,int? varDebCred,long? varNumTranf,DateTime? varFechaInf)
{
PnTransaccion item = new PnTransaccion();
item.IdExpediente = varIdExpediente;
item.IdArea = varIdArea;
item.FechaMov = varFechaMov;
item.Estado = varEstado;
item.Comentario = varComentario;
item.DebCred = varDebCred;
item.NumTranf = varNumTranf;
item.FechaInf = varFechaInf;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdTransac,long varIdExpediente,int varIdArea,DateTime? varFechaMov,string varEstado,string varComentario,int? varDebCred,long? varNumTranf,DateTime? varFechaInf)
{
PnTransaccion item = new PnTransaccion();
item.IdTransac = varIdTransac;
item.IdExpediente = varIdExpediente;
item.IdArea = varIdArea;
item.FechaMov = varFechaMov;
item.Estado = varEstado;
item.Comentario = varComentario;
item.DebCred = varDebCred;
item.NumTranf = varNumTranf;
item.FechaInf = varFechaInf;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdTransacColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdExpedienteColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn IdAreaColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn FechaMovColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn EstadoColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn ComentarioColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn DebCredColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn NumTranfColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn FechaInfColumn
{
get { return Schema.Columns[8]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdTransac = @"id_transac";
public static string IdExpediente = @"id_expediente";
public static string IdArea = @"id_area";
public static string FechaMov = @"fecha_mov";
public static string Estado = @"estado";
public static string Comentario = @"comentario";
public static string DebCred = @"deb_cred";
public static string NumTranf = @"num_tranf";
public static string FechaInf = @"fecha_inf";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#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;
using System.Threading;
using Xunit;
namespace System.Runtime.Tests
{
public static class LazyInitializerTests
{
[Fact]
public static void TestConstructor()
{
// Make sure the default constructor does not throw
new Lazy<object>();
Assert.Throws<ArgumentNullException>(() => new Lazy<object>(null));
}
[Fact]
public static void TestToString()
{
Lazy<object> lazy = new Lazy<object>(() => (object)1);
Assert.NotEqual(1.ToString(), lazy.ToString());
Assert.False(lazy.IsValueCreated, "ToString shouldn't force allocation");
object tmp = lazy.Value;
Assert.Equal(1.ToString(), lazy.ToString());
}
[Fact]
public static void TestIsValueCreated()
{
Lazy<string> lazy = new Lazy<string>(() => "Test");
Assert.False(lazy.IsValueCreated, "Expected lazy to be uninitialized.");
string temp = lazy.Value;
Assert.True(lazy.IsValueCreated, "Expected lazy to be initialized.");
}
[Fact]
public static void TestValue()
{
string value = "Test";
Lazy<string> lazy = new Lazy<string>(() => value);
string lazilyAllocatedValue = lazy.Value;
Assert.Equal(value, lazilyAllocatedValue);
int valueInt = 99;
Lazy<int> LazyInt = new Lazy<int>(() => valueInt);
int lazilyAllocatedValueInt = LazyInt.Value;
Assert.Equal(valueInt, lazilyAllocatedValueInt);
lazy = new Lazy<string>(() => value, true);
lazilyAllocatedValue = lazy.Value;
Assert.Equal(value, lazilyAllocatedValue);
lazy = new Lazy<string>(() => null, false);
lazilyAllocatedValue = lazy.Value;
Assert.Null(lazilyAllocatedValue);
}
[Fact]
public static void TestValueExceptions()
{
string value = "Test";
Lazy<string> lazy = new Lazy<string>(() => value);
string lazilyAllocatedValue;
Assert.Throws<InvalidOperationException>(() =>
{
int x = 0;
lazy = new Lazy<string>(delegate
{
if (x++ < 5)
return lazy.Value;
else
return "Test";
}, true);
lazilyAllocatedValue = lazy.Value;
});
Assert.Throws<MissingMemberException>(() =>
{
lazy = new Lazy<string>();
lazilyAllocatedValue = lazy.Value;
});
}
[Fact]
public static void TestValueFactoryExceptions()
{
Lazy<string> l = new Lazy<string>(() =>
{
int zero = 0;
int x = 1 / zero;
return "";
}, true);
string s;
Assert.Throws<DivideByZeroException>(() => s = l.Value);
Assert.Throws<DivideByZeroException>(() => s = l.Value);
Assert.False(l.IsValueCreated, "Expected l to be uninitialized");
}
[Fact]
public static void TestLazyInitializerSimpleRefTypes()
{
HasDefaultCtor hdcTemplate = new HasDefaultCtor();
string strTemplate = "foo";
// Activator.CreateInstance (uninitialized).
HasDefaultCtor a = null;
Assert.NotNull(LazyInitializer.EnsureInitialized<HasDefaultCtor>(ref a));
Assert.NotNull(a);
// Activator.CreateInstance (already initialized).
HasDefaultCtor b = hdcTemplate;
Assert.Equal(hdcTemplate, LazyInitializer.EnsureInitialized<HasDefaultCtor>(ref b));
Assert.Equal(hdcTemplate, b);
// Func based initialization (uninitialized).
string c = null;
Assert.Equal(strTemplate, LazyInitializer.EnsureInitialized<string>(ref c, () => strTemplate));
Assert.Equal(strTemplate, c);
// Func based initialization (already initialized).
string d = strTemplate;
Assert.Equal(strTemplate, LazyInitializer.EnsureInitialized<string>(ref d, () => strTemplate + "bar"));
Assert.Equal(strTemplate, d);
// Func based initialization (nulls not permitted).
string e = null;
Assert.Throws<InvalidOperationException>(() => LazyInitializer.EnsureInitialized<string>(ref e, () => null));
// Activator.CreateInstance (for a type without a default ctor).
NoDefaultCtor ndc = null;
Assert.Throws<MissingMemberException>(() => LazyInitializer.EnsureInitialized<NoDefaultCtor>(ref ndc));
}
[Fact]
public static void TestLazyInitializerComplexRefTypes()
{
string strTemplate = "foo";
HasDefaultCtor hdcTemplate = new HasDefaultCtor();
// Activator.CreateInstance (uninitialized).
HasDefaultCtor a = null;
bool aInit = false;
object aLock = null;
Assert.NotNull(LazyInitializer.EnsureInitialized<HasDefaultCtor>(ref a, ref aInit, ref aLock));
Assert.NotNull(a);
// Activator.CreateInstance (already initialized).
HasDefaultCtor b = hdcTemplate;
bool bInit = true;
object bLock = null;
Assert.Equal(hdcTemplate, LazyInitializer.EnsureInitialized<HasDefaultCtor>(ref b, ref bInit, ref bLock));
Assert.Equal(hdcTemplate, b);
// Func based initialization (uninitialized).
string c = null;
bool cInit = false;
object cLock = null;
Assert.Equal(strTemplate, LazyInitializer.EnsureInitialized<string>(ref c, ref cInit, ref cLock, () => strTemplate));
Assert.Equal(strTemplate, c);
// Func based initialization (already initialized).
string d = strTemplate;
bool dInit = true;
object dLock = null;
Assert.Equal(strTemplate, LazyInitializer.EnsureInitialized<string>(ref d, ref dInit, ref dLock, () => strTemplate + "bar"));
Assert.Equal(strTemplate, d);
// Func based initialization (nulls *ARE* permitted).
string e = null;
bool einit = false;
object elock = null;
int initCount = 0;
Assert.Null(LazyInitializer.EnsureInitialized<string>(ref e, ref einit, ref elock, () => { initCount++; return null; }));
Assert.Null(e);
Assert.Equal(1, initCount);
Assert.Null(LazyInitializer.EnsureInitialized<string>(ref e, ref einit, ref elock, () => { initCount++; return null; }));
// Activator.CreateInstance (for a type without a default ctor).
NoDefaultCtor ndc = null;
bool ndcInit = false;
object ndcLock = null;
Assert.Throws<MissingMemberException>(() => LazyInitializer.EnsureInitialized<NoDefaultCtor>(ref ndc, ref ndcInit, ref ndcLock));
}
[Fact]
public static void TestLazyInitializerComplexValueTypes()
{
LIX empty = new LIX();
LIX template = new LIX(33);
// Activator.CreateInstance (uninitialized).
LIX a = default(LIX);
bool aInit = false;
object aLock = null;
LIX ensuredValA = LazyInitializer.EnsureInitialized<LIX>(ref a, ref aInit, ref aLock);
Assert.Equal(empty, ensuredValA);
Assert.Equal(empty, a);
// Activator.CreateInstance (already initialized).
LIX b = template;
bool bInit = true;
object bLock = null;
LIX ensuredValB = LazyInitializer.EnsureInitialized<LIX>(ref b, ref bInit, ref bLock);
Assert.Equal(template, ensuredValB);
Assert.Equal(template, b);
// Func based initialization (uninitialized).
LIX c = default(LIX);
bool cInit = false;
object cLock = null;
LIX ensuredValC = LazyInitializer.EnsureInitialized<LIX>(ref c, ref cInit, ref cLock, () => template);
Assert.Equal(template, c);
Assert.Equal(template, ensuredValC);
// Func based initialization (already initialized).
LIX d = template;
bool dInit = true;
object dLock = null;
LIX template2 = new LIX(template.f * 2);
LIX ensuredValD = LazyInitializer.EnsureInitialized<LIX>(ref d, ref dInit, ref dLock, () => template2);
Assert.Equal(template, ensuredValD);
Assert.Equal(template, d);
}
#region Helper Classes and Methods
private class HasDefaultCtor { }
private class NoDefaultCtor
{
public NoDefaultCtor(int x) { }
}
private struct LIX
{
internal int f;
public LIX(int f) { this.f = f; }
public override bool Equals(object other) { return other is LIX && ((LIX)other).f == f; }
public override int GetHashCode() { return f.GetHashCode(); }
public override string ToString() { return "LIX<" + f + ">"; }
}
#endregion
}
}
| |
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
using System;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Crypto.Encodings
{
/**
* this does your basic Pkcs 1 v1.5 padding - whether or not you should be using this
* depends on your application - see Pkcs1 Version 2 for details.
*/
public class Pkcs1Encoding
: IAsymmetricBlockCipher
{
/**
* some providers fail to include the leading zero in PKCS1 encoded blocks. If you need to
* work with one of these set the system property Org.BouncyCastle.Pkcs1.Strict to false.
*/
public const string StrictLengthEnabledProperty = "Org.BouncyCastle.Pkcs1.Strict";
private const int HeaderLength = 10;
/**
* The same effect can be achieved by setting the static property directly
* <p>
* The static property is checked during construction of the encoding object, it is set to
* true by default.
* </p>
*/
public static bool StrictLengthEnabled
{
get { return strictLengthEnabled[0]; }
set { strictLengthEnabled[0] = value; }
}
private static readonly bool[] strictLengthEnabled;
static Pkcs1Encoding()
{
//string strictProperty = Platform.GetEnvironmentVariable(StrictLengthEnabledProperty);
strictLengthEnabled = new bool[]{ true /*strictProperty == null || strictProperty.Equals("true")*/};
}
private SecureRandom random;
private IAsymmetricBlockCipher engine;
private bool forEncryption;
private bool forPrivateKey;
private bool useStrictLength;
private int pLen = -1;
private byte[] fallback = null;
/**
* Basic constructor.
* @param cipher
*/
public Pkcs1Encoding(
IAsymmetricBlockCipher cipher)
{
this.engine = cipher;
this.useStrictLength = StrictLengthEnabled;
}
/**
* Constructor for decryption with a fixed plaintext length.
*
* @param cipher The cipher to use for cryptographic operation.
* @param pLen Length of the expected plaintext.
*/
public Pkcs1Encoding(IAsymmetricBlockCipher cipher, int pLen)
{
this.engine = cipher;
this.useStrictLength = StrictLengthEnabled;
this.pLen = pLen;
}
/**
* Constructor for decryption with a fixed plaintext length and a fallback
* value that is returned, if the padding is incorrect.
*
* @param cipher
* The cipher to use for cryptographic operation.
* @param fallback
* The fallback value, we don't to a arraycopy here.
*/
public Pkcs1Encoding(IAsymmetricBlockCipher cipher, byte[] fallback)
{
this.engine = cipher;
this.useStrictLength = StrictLengthEnabled;
this.fallback = fallback;
this.pLen = fallback.Length;
}
public IAsymmetricBlockCipher GetUnderlyingCipher()
{
return engine;
}
public string AlgorithmName
{
get { return engine.AlgorithmName + "/PKCS1Padding"; }
}
public void Init(
bool forEncryption,
ICipherParameters parameters)
{
AsymmetricKeyParameter kParam;
if (parameters is ParametersWithRandom)
{
ParametersWithRandom rParam = (ParametersWithRandom)parameters;
this.random = rParam.Random;
kParam = (AsymmetricKeyParameter)rParam.Parameters;
}
else
{
this.random = new SecureRandom();
kParam = (AsymmetricKeyParameter)parameters;
}
engine.Init(forEncryption, parameters);
this.forPrivateKey = kParam.IsPrivate;
this.forEncryption = forEncryption;
}
public int GetInputBlockSize()
{
int baseBlockSize = engine.GetInputBlockSize();
return forEncryption
? baseBlockSize - HeaderLength
: baseBlockSize;
}
public int GetOutputBlockSize()
{
int baseBlockSize = engine.GetOutputBlockSize();
return forEncryption
? baseBlockSize
: baseBlockSize - HeaderLength;
}
public byte[] ProcessBlock(
byte[] input,
int inOff,
int length)
{
return forEncryption
? EncodeBlock(input, inOff, length)
: DecodeBlock(input, inOff, length);
}
private byte[] EncodeBlock(
byte[] input,
int inOff,
int inLen)
{
if (inLen > GetInputBlockSize())
throw new ArgumentException("input data too large", "inLen");
byte[] block = new byte[engine.GetInputBlockSize()];
if (forPrivateKey)
{
block[0] = 0x01; // type code 1
for (int i = 1; i != block.Length - inLen - 1; i++)
{
block[i] = (byte)0xFF;
}
}
else
{
random.NextBytes(block); // random fill
block[0] = 0x02; // type code 2
//
// a zero byte marks the end of the padding, so all
// the pad bytes must be non-zero.
//
for (int i = 1; i != block.Length - inLen - 1; i++)
{
while (block[i] == 0)
{
block[i] = (byte)random.NextInt();
}
}
}
block[block.Length - inLen - 1] = 0x00; // mark the end of the padding
Array.Copy(input, inOff, block, block.Length - inLen, inLen);
return engine.ProcessBlock(block, 0, block.Length);
}
/**
* Checks if the argument is a correctly PKCS#1.5 encoded Plaintext
* for encryption.
*
* @param encoded The Plaintext.
* @param pLen Expected length of the plaintext.
* @return Either 0, if the encoding is correct, or -1, if it is incorrect.
*/
private static int CheckPkcs1Encoding(byte[] encoded, int pLen)
{
int correct = 0;
/*
* Check if the first two bytes are 0 2
*/
correct |= (encoded[0] ^ 2);
/*
* Now the padding check, check for no 0 byte in the padding
*/
int plen = encoded.Length - (
pLen /* Lenght of the PMS */
+ 1 /* Final 0-byte before PMS */
);
for (int i = 1; i < plen; i++)
{
int tmp = encoded[i];
tmp |= tmp >> 1;
tmp |= tmp >> 2;
tmp |= tmp >> 4;
correct |= (tmp & 1) - 1;
}
/*
* Make sure the padding ends with a 0 byte.
*/
correct |= encoded[encoded.Length - (pLen + 1)];
/*
* Return 0 or 1, depending on the result.
*/
correct |= correct >> 1;
correct |= correct >> 2;
correct |= correct >> 4;
return ~((correct & 1) - 1);
}
/**
* Decode PKCS#1.5 encoding, and return a random value if the padding is not correct.
*
* @param in The encrypted block.
* @param inOff Offset in the encrypted block.
* @param inLen Length of the encrypted block.
* @param pLen Length of the desired output.
* @return The plaintext without padding, or a random value if the padding was incorrect.
*
* @throws InvalidCipherTextException
*/
private byte[] DecodeBlockOrRandom(byte[] input, int inOff, int inLen)
{
if (!forPrivateKey)
throw new InvalidCipherTextException("sorry, this method is only for decryption, not for signing");
byte[] block = engine.ProcessBlock(input, inOff, inLen);
byte[] random = null;
if (this.fallback == null)
{
random = new byte[this.pLen];
this.random.NextBytes(random);
}
else
{
random = fallback;
}
/*
* TODO: This is a potential dangerous side channel. However, you can
* fix this by changing the RSA engine in a way, that it will always
* return blocks of the same length and prepend them with 0 bytes if
* needed.
*/
if (block.Length < GetOutputBlockSize())
throw new InvalidCipherTextException("block truncated");
/*
* TODO: Potential side channel. Fix it by making the engine always
* return blocks of the correct length.
*/
if (useStrictLength && block.Length != engine.GetOutputBlockSize())
throw new InvalidCipherTextException("block incorrect size");
/*
* Check the padding.
*/
int correct = Pkcs1Encoding.CheckPkcs1Encoding(block, this.pLen);
/*
* Now, to a constant time constant memory copy of the decrypted value
* or the random value, depending on the validity of the padding.
*/
byte[] result = new byte[this.pLen];
for (int i = 0; i < this.pLen; i++)
{
result[i] = (byte)((block[i+(block.Length-pLen)]&(~correct)) | (random[i]&correct));
}
return result;
}
/**
* @exception InvalidCipherTextException if the decrypted block is not in Pkcs1 format.
*/
private byte[] DecodeBlock(
byte[] input,
int inOff,
int inLen)
{
/*
* If the length of the expected plaintext is known, we use a constant-time decryption.
* If the decryption fails, we return a random value.
*/
if (this.pLen != -1)
{
return this.DecodeBlockOrRandom(input, inOff, inLen);
}
byte[] block = engine.ProcessBlock(input, inOff, inLen);
if (block.Length < GetOutputBlockSize())
{
throw new InvalidCipherTextException("block truncated");
}
byte type = block[0];
if (type != 1 && type != 2)
{
throw new InvalidCipherTextException("unknown block type");
}
if (useStrictLength && block.Length != engine.GetOutputBlockSize())
{
throw new InvalidCipherTextException("block incorrect size");
}
//
// find and extract the message block.
//
int start;
for (start = 1; start != block.Length; start++)
{
byte pad = block[start];
if (pad == 0)
{
break;
}
if (type == 1 && pad != (byte)0xff)
{
throw new InvalidCipherTextException("block padding incorrect");
}
}
start++; // data should start at the next byte
if (start > block.Length || start < HeaderLength)
{
throw new InvalidCipherTextException("no data in block");
}
byte[] result = new byte[block.Length - start];
Array.Copy(block, start, result, 0, result.Length);
return result;
}
}
}
#endif
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Web.Security.Membership.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Web.Security
{
static public partial class Membership
{
#region Methods and constructors
public static MembershipUser CreateUser (string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, Object providerUserKey, out MembershipCreateStatus status)
{
status = default(MembershipCreateStatus);
return default(MembershipUser);
}
public static MembershipUser CreateUser (string username, string password)
{
Contract.Ensures (Contract.Result<System.Web.Security.MembershipUser>() != null);
return default(MembershipUser);
}
public static MembershipUser CreateUser (string username, string password, string email)
{
Contract.Ensures (Contract.Result<System.Web.Security.MembershipUser>() != null);
return default(MembershipUser);
}
public static MembershipUser CreateUser (string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, out MembershipCreateStatus status)
{
status = default(MembershipCreateStatus);
return default(MembershipUser);
}
public static bool DeleteUser (string username)
{
return default(bool);
}
public static bool DeleteUser (string username, bool deleteAllRelatedData)
{
return default(bool);
}
public static MembershipUserCollection FindUsersByEmail (string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
{
totalRecords = default(int);
return default(MembershipUserCollection);
}
public static MembershipUserCollection FindUsersByEmail (string emailToMatch)
{
return default(MembershipUserCollection);
}
public static MembershipUserCollection FindUsersByName (string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
{
totalRecords = default(int);
return default(MembershipUserCollection);
}
public static MembershipUserCollection FindUsersByName (string usernameToMatch)
{
return default(MembershipUserCollection);
}
public static string GeneratePassword (int length, int numberOfNonAlphanumericCharacters)
{
return default(string);
}
public static MembershipUserCollection GetAllUsers ()
{
return default(MembershipUserCollection);
}
public static MembershipUserCollection GetAllUsers (int pageIndex, int pageSize, out int totalRecords)
{
totalRecords = default(int);
return default(MembershipUserCollection);
}
public static int GetNumberOfUsersOnline ()
{
return default(int);
}
public static MembershipUser GetUser (string username)
{
return default(MembershipUser);
}
public static MembershipUser GetUser (bool userIsOnline)
{
return default(MembershipUser);
}
public static MembershipUser GetUser ()
{
return default(MembershipUser);
}
public static MembershipUser GetUser (string username, bool userIsOnline)
{
return default(MembershipUser);
}
public static MembershipUser GetUser (Object providerUserKey, bool userIsOnline)
{
return default(MembershipUser);
}
public static MembershipUser GetUser (Object providerUserKey)
{
return default(MembershipUser);
}
public static string GetUserNameByEmail (string emailToMatch)
{
return default(string);
}
public static void UpdateUser (MembershipUser user)
{
}
public static bool ValidateUser (string username, string password)
{
return default(bool);
}
#endregion
#region Properties and indexers
public static string ApplicationName
{
get
{
Contract.Ensures (Contract.Result<string>() == System.Web.Security.Membership.Provider.ApplicationName);
return default(string);
}
set
{
}
}
public static bool EnablePasswordReset
{
get
{
Contract.Ensures (Contract.Result<bool>() == System.Web.Security.Membership.Provider.EnablePasswordReset);
return default(bool);
}
}
public static bool EnablePasswordRetrieval
{
get
{
Contract.Ensures (Contract.Result<bool>() == System.Web.Security.Membership.Provider.EnablePasswordRetrieval);
return default(bool);
}
}
public static string HashAlgorithmType
{
get
{
return default(string);
}
}
public static int MaxInvalidPasswordAttempts
{
get
{
Contract.Ensures (Contract.Result<int>() == System.Web.Security.Membership.Provider.MaxInvalidPasswordAttempts);
return default(int);
}
}
public static int MinRequiredNonAlphanumericCharacters
{
get
{
Contract.Ensures (Contract.Result<int>() == System.Web.Security.Membership.Provider.MinRequiredNonAlphanumericCharacters);
return default(int);
}
}
public static int MinRequiredPasswordLength
{
get
{
Contract.Ensures (Contract.Result<int>() == System.Web.Security.Membership.Provider.MinRequiredPasswordLength);
return default(int);
}
}
public static int PasswordAttemptWindow
{
get
{
Contract.Ensures (Contract.Result<int>() == System.Web.Security.Membership.Provider.PasswordAttemptWindow);
return default(int);
}
}
public static string PasswordStrengthRegularExpression
{
get
{
Contract.Ensures (Contract.Result<string>() == System.Web.Security.Membership.Provider.PasswordStrengthRegularExpression);
return default(string);
}
}
public static MembershipProvider Provider
{
get
{
Contract.Ensures (Contract.Result<System.Web.Security.MembershipProvider>() != null);
return default(MembershipProvider);
}
}
public static MembershipProviderCollection Providers
{
get
{
Contract.Ensures (Contract.Result<System.Web.Security.MembershipProviderCollection>() != null);
return default(MembershipProviderCollection);
}
}
public static bool RequiresQuestionAndAnswer
{
get
{
Contract.Ensures (Contract.Result<bool>() == System.Web.Security.Membership.Provider.RequiresQuestionAndAnswer);
return default(bool);
}
}
public static int UserIsOnlineTimeWindow
{
get
{
return default(int);
}
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using OpenMetaverse;
using log4net;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Region.Framework.Scenes
{
public delegate void RestartSim(RegionInfo thisregion);
/// <summary>
/// Manager for adding, closing and restarting scenes.
/// </summary>
public class SceneManager
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public event RestartSim OnRestartSim;
private readonly List<Scene> m_localScenes;
private Scene m_currentScene = null;
public List<Scene> Scenes
{
get { return m_localScenes; }
}
public Scene CurrentScene
{
get { return m_currentScene; }
}
public Scene CurrentOrFirstScene
{
get
{
if (m_currentScene == null)
{
if (m_localScenes.Count > 0)
{
return m_localScenes[0];
}
else
{
return null;
}
}
else
{
return m_currentScene;
}
}
}
public SceneManager()
{
m_localScenes = new List<Scene>();
}
public void Close()
{
// collect known shared modules in sharedModules
Dictionary<string, IRegionModule> sharedModules = new Dictionary<string, IRegionModule>();
for (int i = 0; i < m_localScenes.Count; i++)
{
// extract known shared modules from scene
foreach (string k in m_localScenes[i].Modules.Keys)
{
if (m_localScenes[i].Modules[k].IsSharedModule &&
!sharedModules.ContainsKey(k))
sharedModules[k] = m_localScenes[i].Modules[k];
}
// close scene/region
m_localScenes[i].Close();
}
// all regions/scenes are now closed, we can now safely
// close all shared modules
foreach (IRegionModule mod in sharedModules.Values)
{
mod.Close();
}
}
public void Close(Scene cscene)
{
if (m_localScenes.Contains(cscene))
{
for (int i = 0; i < m_localScenes.Count; i++)
{
if (m_localScenes[i].Equals(cscene))
{
m_localScenes[i].Close();
}
}
}
}
public void Add(Scene scene)
{
scene.OnRestart += HandleRestart;
m_localScenes.Add(scene);
}
public void HandleRestart(RegionInfo rdata)
{
m_log.Error("[SCENEMANAGER]: Got Restart message for region:" + rdata.RegionName + " Sending up to main");
int RegionSceneElement = -1;
for (int i = 0; i < m_localScenes.Count; i++)
{
if (rdata.RegionName == m_localScenes[i].RegionInfo.RegionName)
{
RegionSceneElement = i;
}
}
// Now we make sure the region is no longer known about by the SceneManager
// Prevents duplicates.
if (RegionSceneElement >= 0)
{
m_localScenes.RemoveAt(RegionSceneElement);
}
// Send signal to main that we're restarting this sim.
OnRestartSim(rdata);
}
public void SendSimOnlineNotification(ulong regionHandle)
{
RegionInfo Result = null;
for (int i = 0; i < m_localScenes.Count; i++)
{
if (m_localScenes[i].RegionInfo.RegionHandle == regionHandle)
{
// Inform other regions to tell their avatar about me
Result = m_localScenes[i].RegionInfo;
}
}
if (Result != null)
{
for (int i = 0; i < m_localScenes.Count; i++)
{
if (m_localScenes[i].RegionInfo.RegionHandle != regionHandle)
{
// Inform other regions to tell their avatar about me
//m_localScenes[i].OtherRegionUp(Result);
}
}
}
else
{
m_log.Error("[REGION]: Unable to notify Other regions of this Region coming up");
}
}
/// <summary>
/// Save the prims in the current scene to an xml file in OpenSimulator's original 'xml' format
/// </summary>
/// <param name="filename"></param>
public void SaveCurrentSceneToXml(string filename)
{
IRegionSerialiserModule serialiser = CurrentOrFirstScene.RequestModuleInterface<IRegionSerialiserModule>();
if (serialiser != null)
serialiser.SavePrimsToXml(CurrentOrFirstScene, filename);
}
/// <summary>
/// Load an xml file of prims in OpenSimulator's original 'xml' file format to the current scene
/// </summary>
/// <param name="filename"></param>
/// <param name="generateNewIDs"></param>
/// <param name="loadOffset"></param>
public void LoadCurrentSceneFromXml(string filename, bool generateNewIDs, Vector3 loadOffset)
{
IRegionSerialiserModule serialiser = CurrentOrFirstScene.RequestModuleInterface<IRegionSerialiserModule>();
if (serialiser != null)
serialiser.LoadPrimsFromXml(CurrentOrFirstScene, filename, generateNewIDs, loadOffset);
}
/// <summary>
/// Save the prims in the current scene to an xml file in OpenSimulator's current 'xml2' format
/// </summary>
/// <param name="filename"></param>
public void SaveCurrentSceneToXml2(string filename)
{
IRegionSerialiserModule serialiser = CurrentOrFirstScene.RequestModuleInterface<IRegionSerialiserModule>();
if (serialiser != null)
serialiser.SavePrimsToXml2(CurrentOrFirstScene, filename);
}
public void SaveNamedPrimsToXml2(string primName, string filename)
{
IRegionSerialiserModule serialiser = CurrentOrFirstScene.RequestModuleInterface<IRegionSerialiserModule>();
if (serialiser != null)
serialiser.SaveNamedPrimsToXml2(CurrentOrFirstScene, primName, filename);
}
/// <summary>
/// Load an xml file of prims in OpenSimulator's current 'xml2' file format to the current scene
/// </summary>
public void LoadCurrentSceneFromXml2(string filename)
{
IRegionSerialiserModule serialiser = CurrentOrFirstScene.RequestModuleInterface<IRegionSerialiserModule>();
if (serialiser != null)
serialiser.LoadPrimsFromXml2(CurrentOrFirstScene, filename);
}
/// <summary>
/// Save the current scene to an OpenSimulator archive. This archive will eventually include the prim's assets
/// as well as the details of the prims themselves.
/// </summary>
/// <param name="filename"></param>
public void SaveCurrentSceneToArchive(string filename)
{
IRegionArchiverModule archiver = CurrentOrFirstScene.RequestModuleInterface<IRegionArchiverModule>();
if (archiver != null)
archiver.ArchiveRegion(filename);
}
/// <summary>
/// Load an OpenSim archive into the current scene. This will load both the shapes of the prims and upload
/// their assets to the asset service.
/// </summary>
/// <param name="filename"></param>
public void LoadArchiveToCurrentScene(string filename)
{
IRegionArchiverModule archiver = CurrentOrFirstScene.RequestModuleInterface<IRegionArchiverModule>();
if (archiver != null)
archiver.DearchiveRegion(filename);
}
public string SaveCurrentSceneMapToXmlString()
{
return CurrentOrFirstScene.Heightmap.SaveToXmlString();
}
public void LoadCurrenSceneMapFromXmlString(string mapData)
{
CurrentOrFirstScene.Heightmap.LoadFromXmlString(mapData);
}
public void SendCommandToPluginModules(string[] cmdparams)
{
ForEachCurrentScene(delegate(Scene scene) { scene.SendCommandToPlugins(cmdparams); });
}
public void SetBypassPermissionsOnCurrentScene(bool bypassPermissions)
{
ForEachCurrentScene(delegate(Scene scene) { scene.Permissions.SetBypassPermissions(bypassPermissions); });
}
private void ForEachCurrentScene(Action<Scene> func)
{
if (m_currentScene == null)
{
m_localScenes.ForEach(func);
}
else
{
func(m_currentScene);
}
}
public void RestartCurrentScene()
{
ForEachCurrentScene(delegate(Scene scene) { scene.RestartNow(); });
}
public void BackupCurrentScene()
{
ForEachCurrentScene(delegate(Scene scene) { scene.Backup(); });
}
public bool TrySetCurrentScene(string regionName)
{
if ((String.Compare(regionName, "root") == 0)
|| (String.Compare(regionName, "..") == 0)
|| (String.Compare(regionName, "/") == 0))
{
m_currentScene = null;
return true;
}
else
{
foreach (Scene scene in m_localScenes)
{
if (String.Compare(scene.RegionInfo.RegionName, regionName, true) == 0)
{
m_currentScene = scene;
return true;
}
}
return false;
}
}
public bool TrySetCurrentScene(UUID regionID)
{
m_log.Debug("Searching for Region: '" + regionID + "'");
foreach (Scene scene in m_localScenes)
{
if (scene.RegionInfo.RegionID == regionID)
{
m_currentScene = scene;
return true;
}
}
return false;
}
public bool TryGetScene(string regionName, out Scene scene)
{
foreach (Scene mscene in m_localScenes)
{
if (String.Compare(mscene.RegionInfo.RegionName, regionName, true) == 0)
{
scene = mscene;
return true;
}
}
scene = null;
return false;
}
public bool TryGetScene(UUID regionID, out Scene scene)
{
foreach (Scene mscene in m_localScenes)
{
if (mscene.RegionInfo.RegionID == regionID)
{
scene = mscene;
return true;
}
}
scene = null;
return false;
}
public bool TryGetScene(uint locX, uint locY, out Scene scene)
{
foreach (Scene mscene in m_localScenes)
{
if (mscene.RegionInfo.RegionLocX == locX &&
mscene.RegionInfo.RegionLocY == locY)
{
scene = mscene;
return true;
}
}
scene = null;
return false;
}
public bool TryGetScene(IPEndPoint ipEndPoint, out Scene scene)
{
foreach (Scene mscene in m_localScenes)
{
if ((mscene.RegionInfo.InternalEndPoint.Equals(ipEndPoint.Address)) &&
(mscene.RegionInfo.InternalEndPoint.Port == ipEndPoint.Port))
{
scene = mscene;
return true;
}
}
scene = null;
return false;
}
/// <summary>
/// Set the debug packet level on the current scene. This level governs which packets are printed out to the
/// console.
/// </summary>
/// <param name="newDebug"></param>
public void SetDebugPacketLevelOnCurrentScene(int newDebug)
{
ForEachCurrentScene(delegate(Scene scene)
{
List<ScenePresence> scenePresences = scene.GetScenePresences();
foreach (ScenePresence scenePresence in scenePresences)
{
if (!scenePresence.IsChildAgent)
{
m_log.ErrorFormat("Packet debug for {0} {1} set to {2}",
scenePresence.Firstname,
scenePresence.Lastname,
newDebug);
scenePresence.ControllingClient.SetDebugPacketLevel(newDebug);
}
}
});
}
public List<ScenePresence> GetCurrentSceneAvatars()
{
List<ScenePresence> avatars = new List<ScenePresence>();
ForEachCurrentScene(delegate(Scene scene)
{
List<ScenePresence> scenePresences = scene.GetScenePresences();
foreach (ScenePresence scenePresence in scenePresences)
{
if (!scenePresence.IsChildAgent)
{
avatars.Add(scenePresence);
}
}
});
return avatars;
}
public List<ScenePresence> GetCurrentScenePresences()
{
List<ScenePresence> presences = new List<ScenePresence>();
ForEachCurrentScene(delegate(Scene scene)
{
List<ScenePresence> scenePresences = scene.GetScenePresences();
presences.AddRange(scenePresences);
});
return presences;
}
public RegionInfo GetRegionInfo(ulong regionHandle)
{
foreach (Scene scene in m_localScenes)
{
if (scene.RegionInfo.RegionHandle == regionHandle)
{
return scene.RegionInfo;
}
}
return null;
}
public void ForceCurrentSceneClientUpdate()
{
ForEachCurrentScene(delegate(Scene scene) { scene.ForceClientUpdate(); });
}
public void HandleEditCommandOnCurrentScene(string[] cmdparams)
{
ForEachCurrentScene(delegate(Scene scene) { scene.HandleEditCommand(cmdparams); });
}
public bool TryGetAvatar(UUID avatarId, out ScenePresence avatar)
{
foreach (Scene scene in m_localScenes)
{
if (scene.TryGetAvatar(avatarId, out avatar))
{
return true;
}
}
avatar = null;
return false;
}
public bool TryGetAvatarsScene(UUID avatarId, out Scene scene)
{
ScenePresence avatar = null;
foreach (Scene mScene in m_localScenes)
{
if (mScene.TryGetAvatar(avatarId, out avatar))
{
scene = mScene;
return true;
}
}
scene = null;
return false;
}
public void CloseScene(Scene scene)
{
m_localScenes.Remove(scene);
scene.Close();
}
public bool TryGetAvatarByName(string avatarName, out ScenePresence avatar)
{
foreach (Scene scene in m_localScenes)
{
if (scene.TryGetAvatarByName(avatarName, out avatar))
{
return true;
}
}
avatar = null;
return false;
}
public void ForEachScene(Action<Scene> action)
{
m_localScenes.ForEach(action);
}
public void CacheJ2kDecode(int threads)
{
if (threads < 1) threads = 1;
IJ2KDecoder m_decoder = m_localScenes[0].RequestModuleInterface<IJ2KDecoder>();
List<UUID> assetRequestList = new List<UUID>();
#region AssetGathering!
foreach (Scene scene in m_localScenes)
{
List<EntityBase> entitles = scene.GetEntities();
foreach (EntityBase entity in entitles)
{
if (entity is SceneObjectGroup)
{
SceneObjectGroup sog = (SceneObjectGroup) entity;
foreach (SceneObjectPart part in sog.Children.Values)
{
if (part.Shape != null)
{
if (part.Shape.TextureEntry.Length > 0)
{
OpenMetaverse.Primitive.TextureEntry te =
new Primitive.TextureEntry(part.Shape.TextureEntry, 0,
part.Shape.TextureEntry.Length);
if (te.DefaultTexture != null) // this has been null for some reason...
{
if (te.DefaultTexture.TextureID != UUID.Zero)
assetRequestList.Add(te.DefaultTexture.TextureID);
}
for (int i=0; i<te.FaceTextures.Length; i++)
{
if (te.FaceTextures[i] != null)
{
if (te.FaceTextures[i].TextureID != UUID.Zero)
{
assetRequestList.Add(te.FaceTextures[i].TextureID);
}
}
}
}
if (part.Shape.SculptTexture != UUID.Zero)
{
assetRequestList.Add(part.Shape.SculptTexture);
}
}
}
}
}
}
#endregion
int entries_per_thread = (assetRequestList.Count / threads) + 1;
UUID[] arrAssetRequestList = assetRequestList.ToArray();
List<UUID[]> arrvalus = new List<UUID[]>();
//split into separate arrays
for (int j = 0; j < threads; j++)
{
List<UUID> val = new List<UUID>();
for (int k = j * entries_per_thread; k < ((j + 1) * entries_per_thread); k++)
{
if (k < arrAssetRequestList.Length)
{
val.Add(arrAssetRequestList[k]);
}
}
arrvalus.Add(val.ToArray());
}
for (int l = 0; l < arrvalus.Count; l++)
{
DecodeThreadContents threadworkItem = new DecodeThreadContents();
threadworkItem.sn = m_localScenes[0];
threadworkItem.j2kdecode = m_decoder;
threadworkItem.arrassets = arrvalus[l];
System.Threading.Thread decodethread =
new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(threadworkItem.run));
threadworkItem.SetThread(decodethread);
decodethread.Priority = System.Threading.ThreadPriority.Lowest;
decodethread.Name = "J2kCacheDecodeThread_" + l + 1;
ThreadTracker.Add(decodethread);
decodethread.Start();
}
}
}
public class DecodeThreadContents
{
public Scene sn;
public UUID[] arrassets;
public IJ2KDecoder j2kdecode;
private System.Threading.Thread thisthread;
public void run(object o)
{
for (int i=0;i<arrassets.Length;i++)
{
AssetBase ab = sn.AssetService.Get(arrassets[i].ToString());
if (ab != null && ab.Data != null)
{
j2kdecode.syncdecode(arrassets[i], ab.Data);
}
}
ThreadTracker.Remove(thisthread);
}
public void SetThread(System.Threading.Thread thr)
{
thisthread = thr;
}
}
}
| |
/*
*
* (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.Globalization;
using System.Linq;
using ASC.Collections;
using ASC.Common.Data.Sql;
using ASC.Common.Data.Sql.Expressions;
using ASC.Core.Tenants;
using ASC.ElasticSearch;
using ASC.Projects.Core.DataInterfaces;
using ASC.Projects.Core.Domain;
using ASC.Projects.Core.Services.NotifyService;
using ASC.Web.Projects;
using ASC.Web.Projects.Core.Search;
namespace ASC.Projects.Data.DAO
{
internal class CachedMessageDao : MessageDao
{
private readonly HttpRequestDictionary<Message> messageCache = new HttpRequestDictionary<Message>("message");
public CachedMessageDao(int tenant) : base(tenant)
{
}
public override Message GetById(int id)
{
return messageCache.Get(id.ToString(CultureInfo.InvariantCulture), () => GetBaseById(id));
}
private Message GetBaseById(int id)
{
return base.GetById(id);
}
public override Message Save(Message msg)
{
if (msg != null)
{
ResetCache(msg.ID);
}
return base.Save(msg);
}
public override void Delete(int id)
{
ResetCache(id);
base.Delete(id);
}
private void ResetCache(int messageId)
{
messageCache.Reset(messageId.ToString(CultureInfo.InvariantCulture));
}
}
class MessageDao : BaseDao, IMessageDao
{
private readonly Converter<object[], Message> converter;
public MessageDao(int tenant) : base(tenant)
{
converter = ToMessage;
}
public List<Message> GetAll()
{
return Db.ExecuteList(CreateQuery()).ConvertAll(converter);
}
public List<Message> GetByProject(int projectId)
{
return Db.ExecuteList(CreateQuery().Where("t.project_id", projectId).OrderBy("t.create_on", false))
.ConvertAll(converter);
}
public List<Message> GetMessages(int startIndex, int max)
{
var query = CreateQuery()
.OrderBy("t.create_on", false)
.SetFirstResult(startIndex)
.SetMaxResults(max);
return Db.ExecuteList(query).ConvertAll(converter);
}
public List<Message> GetRecentMessages(int offset, int max, params int[] projects)
{
var query = CreateQuery()
.SetFirstResult(offset)
.OrderBy("t.create_on", false)
.SetMaxResults(max);
if (projects != null && 0 < projects.Length)
{
query.Where(Exp.In("t.project_id", projects));
}
return Db.ExecuteList(query).ConvertAll(converter);
}
public List<Message> GetByFilter(TaskFilter filter, bool isAdmin, bool checkAccess)
{
var query = CreateQuery();
if (filter.Max > 0 && filter.Max < 150000)
{
query.SetFirstResult((int)filter.Offset);
query.SetMaxResults((int)filter.Max);
}
query.OrderBy("t.status", true);
if (!string.IsNullOrEmpty(filter.SortBy))
{
var sortColumns = filter.SortColumns["Message"];
sortColumns.Remove(filter.SortBy);
query.OrderBy(GetSortFilter(filter.SortBy), filter.SortOrder);
foreach (var sort in sortColumns.Keys)
{
query.OrderBy(GetSortFilter(sort), sortColumns[sort]);
}
}
CreateQueryFilter(query, filter, isAdmin, checkAccess);
return Db.ExecuteList(query).ConvertAll(converter);
}
public int GetByFilterCount(TaskFilter filter, bool isAdmin, bool checkAccess)
{
var query = new SqlQuery(MessagesTable + " t")
.InnerJoin(ProjectsTable + " p", Exp.EqColumns("t.project_id", "p.id") & Exp.EqColumns("t.tenant_id", "p.tenant_id"))
.Select("t.id")
.GroupBy("t.id")
.Where("t.tenant_id", Tenant);
query = CreateQueryFilter(query, filter, isAdmin, checkAccess);
var queryCount = new SqlQuery().SelectCount().From(query, "t1");
return Db.ExecuteScalar<int>(queryCount);
}
public List<Tuple<Guid, int, int>> GetByFilterCountForReport(TaskFilter filter, bool isAdmin, bool checkAccess)
{
filter = (TaskFilter)filter.Clone();
var query = new SqlQuery(MessagesTable + " t")
.InnerJoin(ProjectsTable + " p", Exp.EqColumns("t.project_id", "p.id") & Exp.EqColumns("t.tenant_id", "p.tenant_id"))
.Select("t.create_by", "t.project_id")
.Where("t.tenant_id", Tenant)
.Where(Exp.Between("t.create_on", filter.GetFromDate(), filter.GetToDate()));
if (filter.HasUserId)
{
query.Where(Exp.In("t.create_by", filter.GetUserIds()));
filter.UserId = Guid.Empty;
filter.DepartmentId = Guid.Empty;
}
query = CreateQueryFilter(query, filter, isAdmin, checkAccess);
var queryCount = new SqlQuery()
.SelectCount()
.Select("t1.create_by", "t1.project_id")
.GroupBy("create_by", "project_id")
.From(query, "t1");
return Db.ExecuteList(queryCount).ConvertAll(b => new Tuple<Guid, int, int>(Guid.Parse((string)b[1]), Convert.ToInt32(b[2]), Convert.ToInt32(b[0]))); ;
}
public virtual Message GetById(int id)
{
return Db.ExecuteList(CreateQuery().Where("t.id", id))
.ConvertAll(converter)
.SingleOrDefault();
}
public bool IsExists(int id)
{
var count = Db.ExecuteScalar<long>(Query(MessagesTable).SelectCount().Where("id", id));
return 0 < count;
}
public virtual Message Save(Message msg)
{
var insert = Insert(MessagesTable)
.InColumnValue("id", msg.ID)
.InColumnValue("project_id", msg.Project != null ? msg.Project.ID : 0)
.InColumnValue("title", msg.Title)
.InColumnValue("status", msg.Status)
.InColumnValue("create_by", msg.CreateBy.ToString())
.InColumnValue("create_on", TenantUtil.DateTimeToUtc(msg.CreateOn))
.InColumnValue("last_modified_by", msg.LastModifiedBy.ToString())
.InColumnValue("last_modified_on", TenantUtil.DateTimeToUtc(msg.LastModifiedOn))
.InColumnValue("content", msg.Description)
.Identity(1, 0, true);
msg.ID = Db.ExecuteScalar<int>(insert);
return msg;
}
public virtual void Delete(int id)
{
using (var tx = Db.BeginTransaction())
{
Db.ExecuteNonQuery(Delete(CommentsTable).Where("target_uniq_id", ProjectEntity.BuildUniqId<Message>(id)));
Db.ExecuteNonQuery(Delete(MessagesTable).Where("id", id));
tx.Commit();
}
}
private SqlQuery CreateQuery()
{
return new SqlQuery(MessagesTable + " t")
.InnerJoin(ProjectsTable + " p", Exp.EqColumns("t.project_id", "p.id") & Exp.EqColumns("t.tenant_id", "p.tenant_id"))
.LeftOuterJoin(CommentsTable + " pc", Exp.EqColumns("pc.target_uniq_id", "concat('Message_', cast(t.id as char))") & Exp.EqColumns("t.tenant_id", "pc.tenant_id"))
.Select(ProjectDao.ProjectColumns.Select(c => "p." + c).ToArray())
.Select("t.id", "t.title", "t.status", "t.create_by", "t.create_on", "t.last_modified_by", "t.last_modified_on", "t.content")
.Select("max(coalesce(pc.create_on, t.create_on)) comments")
.GroupBy("t.id")
.Where("t.tenant_id", Tenant);
}
private SqlQuery CreateQueryFilter(SqlQuery query, TaskFilter filter, bool isAdmin, bool checkAccess)
{
if (filter.Follow)
{
IEnumerable<string> objects = NotifySource.Instance.GetSubscriptionProvider().GetSubscriptions(NotifyConstants.Event_NewCommentForMessage, NotifySource.Instance.GetRecipientsProvider().GetRecipient(CurrentUserID.ToString()));
if (filter.ProjectIds.Count != 0)
{
objects = objects.Where(r => r.Split('_')[2] == filter.ProjectIds[0].ToString(CultureInfo.InvariantCulture));
}
var ids = objects.Select(r => r.Split('_')[1]).ToArray();
query.Where(Exp.In("t.id", ids));
}
if (filter.ProjectIds.Count != 0)
{
query.Where(Exp.In("t.project_id", filter.ProjectIds));
}
else
{
if (ProjectsCommonSettings.Load().HideEntitiesInPausedProjects)
{
query.Where(!Exp.Eq("p.status", ProjectStatus.Paused));
}
if (filter.MyProjects)
{
query.InnerJoin(ParticipantTable + " ppp", Exp.EqColumns("ppp.tenant", "t.tenant_id") & Exp.EqColumns("p.id", "ppp.project_id") & Exp.Eq("ppp.removed", false));
query.Where("ppp.participant_id", CurrentUserID);
}
}
if (filter.TagId != 0)
{
if (filter.TagId == -1)
{
query.LeftOuterJoin(ProjectTagTable + " pt", Exp.EqColumns("pt.project_id", "t.project_id"));
query.Where("pt.tag_id", null);
}
else
{
query.InnerJoin(ProjectTagTable + " pt", Exp.EqColumns("pt.project_id", "t.project_id"));
query.Where("pt.tag_id", filter.TagId);
}
}
if (filter.UserId != Guid.Empty)
{
query.Where("t.create_by", filter.UserId);
}
if (filter.DepartmentId != Guid.Empty)
{
query.InnerJoin("core_usergroup cug", Exp.EqColumns("cug.tenant", "t.tenant_id") & Exp.Eq("cug.removed", false) & Exp.EqColumns("cug.userid", "t.create_by"));
query.Where("cug.groupid", filter.DepartmentId);
}
if (!filter.FromDate.Equals(DateTime.MinValue) && !filter.ToDate.Equals(DateTime.MinValue) && !filter.ToDate.Equals(DateTime.MaxValue))
{
query.Where(Exp.Between("t.create_on", filter.FromDate, filter.ToDate.AddDays(1)));
}
if (filter.MessageStatus.HasValue)
{
query.Where("t.status", filter.MessageStatus.Value);
}
if (!string.IsNullOrEmpty(filter.SearchText))
{
List<int> mIds;
if (FactoryIndexer<DiscussionsWrapper>.TrySelectIds(s => s.MatchAll(filter.SearchText), out mIds))
{
query.Where(Exp.In("t.id", mIds));
}
else
{
query.Where(Exp.Like("t.title", filter.SearchText, SqlLike.AnyWhere));
}
}
if (checkAccess)
{
query.Where(Exp.Eq("p.private", false));
}
else if (!isAdmin)
{
var isInTeam = new SqlQuery(ParticipantTable).Select("security").Where(Exp.EqColumns("p.id", "project_id") & Exp.Eq("removed", false) & Exp.Eq("participant_id", CurrentUserID) & !Exp.Eq("security & " + (int)ProjectTeamSecurity.Messages, (int)ProjectTeamSecurity.Messages));
query.Where(Exp.Eq("p.private", false) | Exp.Eq("p.responsible_id", CurrentUserID) | (Exp.Eq("p.private", true) & Exp.Exists(isInTeam)));
}
return query;
}
private static string GetSortFilter(string sortBy)
{
if (sortBy != "comments") return "t." + sortBy;
return "comments";
}
private Message ToMessage(object[] r)
{
var offset = ProjectDao.ProjectColumns.Length;
return new Message
{
Project = r[0] != null ? ProjectDao.ToProject(r) : null,
ID = Convert.ToInt32(r[0 + offset]),
Title = (string)r[1 + offset],
Status = (MessageStatus)Convert.ToInt32(r[2 + offset]),
CreateBy = ToGuid(r[3 + offset]),
CreateOn = TenantUtil.DateTimeFromUtc(Convert.ToDateTime(r[4 + offset])),
LastModifiedBy = ToGuid(r[5 + offset]),
LastModifiedOn = TenantUtil.DateTimeFromUtc(Convert.ToDateTime(r[6 + offset])),
Description = (string)r[7 + offset]
};
}
public IEnumerable<Message> GetMessages(Exp where)
{
return Db.ExecuteList(CreateQuery().Where(where)).ConvertAll(converter);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.Serialization;
using System.IO;
using DDay.iCal.Serialization.iCalendar;
namespace DDay.iCal
{
/// <summary>
/// An iCalendar representation of the <c>RRULE</c> property.
/// </summary>
#if !SILVERLIGHT
[Serializable]
#endif
public partial class RecurrencePattern :
EncodableDataType,
IRecurrencePattern
{
#region Private Fields
#if !SILVERLIGHT
[NonSerialized]
#endif
private FrequencyType _Frequency;
private DateTime _Until = DateTime.MinValue;
private int _Count = int.MinValue;
private int _Interval = int.MinValue;
private IList<int> _BySecond = new List<int>();
private IList<int> _ByMinute = new List<int>();
private IList<int> _ByHour = new List<int>();
private IList<IWeekDay> _ByDay = new List<IWeekDay>();
private IList<int> _ByMonthDay = new List<int>();
private IList<int> _ByYearDay = new List<int>();
private IList<int> _ByWeekNo = new List<int>();
private IList<int> _ByMonth = new List<int>();
private IList<int> _BySetPosition = new List<int>();
private DayOfWeek _FirstDayOfWeek = DayOfWeek.Monday;
private RecurrenceRestrictionType? _RestrictionType = null;
private RecurrenceEvaluationModeType? _EvaluationMode = null;
#endregion
#region IRecurrencePattern Members
public FrequencyType Frequency
{
get { return _Frequency; }
set { _Frequency = value; }
}
public DateTime Until
{
get { return _Until; }
set { _Until = value; }
}
public int Count
{
get { return _Count; }
set { _Count = value; }
}
public int Interval
{
get
{
if (_Interval == int.MinValue)
return 1;
return _Interval;
}
set { _Interval = value; }
}
public IList<int> BySecond
{
get { return _BySecond; }
set { _BySecond = value; }
}
public IList<int> ByMinute
{
get { return _ByMinute; }
set { _ByMinute = value; }
}
public IList<int> ByHour
{
get { return _ByHour; }
set { _ByHour = value; }
}
public IList<IWeekDay> ByDay
{
get { return _ByDay; }
set { _ByDay = value; }
}
public IList<int> ByMonthDay
{
get { return _ByMonthDay; }
set { _ByMonthDay = value; }
}
public IList<int> ByYearDay
{
get { return _ByYearDay; }
set { _ByYearDay = value; }
}
public IList<int> ByWeekNo
{
get { return _ByWeekNo; }
set { _ByWeekNo = value; }
}
public IList<int> ByMonth
{
get { return _ByMonth; }
set { _ByMonth = value; }
}
public IList<int> BySetPosition
{
get { return _BySetPosition; }
set { _BySetPosition = value; }
}
public DayOfWeek FirstDayOfWeek
{
get { return _FirstDayOfWeek; }
set { _FirstDayOfWeek = value; }
}
public RecurrenceRestrictionType RestrictionType
{
get
{
// NOTE: Fixes bug #1924358 - Cannot evaluate Secondly patterns
if (_RestrictionType != null &&
_RestrictionType.HasValue)
return _RestrictionType.Value;
else if (Calendar != null)
return Calendar.RecurrenceRestriction;
else
return RecurrenceRestrictionType.Default;
}
set { _RestrictionType = value; }
}
public RecurrenceEvaluationModeType EvaluationMode
{
get
{
// NOTE: Fixes bug #1924358 - Cannot evaluate Secondly patterns
if (_EvaluationMode != null &&
_EvaluationMode.HasValue)
return _EvaluationMode.Value;
else if (Calendar != null)
return Calendar.RecurrenceEvaluationMode;
else
return RecurrenceEvaluationModeType.Default;
}
set { _EvaluationMode = value; }
}
///// <summary>
///// Returns the next occurrence of the pattern,
///// given a valid previous occurrence, <paramref name="lastOccurrence"/>.
///// As long as the recurrence pattern is valid, and
///// <paramref name="lastOccurrence"/> is a valid previous
///// occurrence within the pattern, this will return the
///// next occurrence. NOTE: This will not give accurate results
///// when COUNT or BYSETVAL are used.
///// </summary>
//virtual public IPeriod GetNextOccurrence(IDateTime lastOccurrence)
//{
// RecurrencePatternEvaluator evaluator = GetService<RecurrencePatternEvaluator>();
// if (evaluator != null)
// return evaluator.GetNext(lastOccurrence);
// return null;
//}
#endregion
#region Constructors
public RecurrencePattern()
{
Initialize();
}
public RecurrencePattern(FrequencyType frequency) : this(frequency, 1)
{
}
public RecurrencePattern(FrequencyType frequency, int interval) :
this()
{
Frequency = frequency;
Interval = interval;
}
public RecurrencePattern(string value) :
this()
{
if (value != null)
{
DDay.iCal.Serialization.iCalendar.RecurrencePatternSerializer serializer = new DDay.iCal.Serialization.iCalendar.RecurrencePatternSerializer();
CopyFrom(serializer.Deserialize(new StringReader(value)) as ICopyable);
}
}
void Initialize()
{
SetService(new RecurrencePatternEvaluator(this));
}
#endregion
#region Overrides
protected override void OnDeserializing(StreamingContext context)
{
base.OnDeserializing(context);
Initialize();
}
public override bool Equals(object obj)
{
if (obj is RecurrencePattern)
{
RecurrencePattern r = (RecurrencePattern)obj;
if (!CollectionEquals(r.ByDay, ByDay) ||
!CollectionEquals(r.ByHour, ByHour) ||
!CollectionEquals(r.ByMinute, ByMinute) ||
!CollectionEquals(r.ByMonth, ByMonth) ||
!CollectionEquals(r.ByMonthDay, ByMonthDay) ||
!CollectionEquals(r.BySecond, BySecond) ||
!CollectionEquals(r.BySetPosition, BySetPosition) ||
!CollectionEquals(r.ByWeekNo, ByWeekNo) ||
!CollectionEquals(r.ByYearDay, ByYearDay))
return false;
if (r.Count != Count) return false;
if (r.Frequency != Frequency) return false;
if (r.Interval != Interval) return false;
if (r.Until != DateTime.MinValue)
{
if (!r.Until.Equals(Until))
return false;
}
else if (Until != DateTime.MinValue)
return false;
if (r.FirstDayOfWeek != FirstDayOfWeek) return false;
return true;
}
return base.Equals(obj);
}
public override string ToString()
{
RecurrencePatternSerializer serializer = new RecurrencePatternSerializer();
return serializer.SerializeToString(this);
}
public override int GetHashCode()
{
int hashCode =
ByDay.GetHashCode() ^ ByHour.GetHashCode() ^ ByMinute.GetHashCode() ^
ByMonth.GetHashCode() ^ ByMonthDay.GetHashCode() ^ BySecond.GetHashCode() ^
BySetPosition.GetHashCode() ^ ByWeekNo.GetHashCode() ^ ByYearDay.GetHashCode() ^
Count.GetHashCode() ^ Frequency.GetHashCode();
if (Interval.Equals(1))
hashCode ^= 0x1;
else hashCode ^= Interval.GetHashCode();
hashCode ^= Until.GetHashCode();
hashCode ^= FirstDayOfWeek.GetHashCode();
return hashCode;
}
public override void CopyFrom(ICopyable obj)
{
base.CopyFrom(obj);
if (obj is IRecurrencePattern)
{
IRecurrencePattern r = (IRecurrencePattern)obj;
Frequency = r.Frequency;
Until = r.Until;
Count = r.Count;
Interval = r.Interval;
BySecond = new List<int>(r.BySecond);
ByMinute = new List<int>(r.ByMinute);
ByHour = new List<int>(r.ByHour);
ByDay = new List<IWeekDay>(r.ByDay);
ByMonthDay = new List<int>(r.ByMonthDay);
ByYearDay = new List<int>(r.ByYearDay);
ByWeekNo = new List<int>(r.ByWeekNo);
ByMonth = new List<int>(r.ByMonth);
BySetPosition = new List<int>(r.BySetPosition);
FirstDayOfWeek = r.FirstDayOfWeek;
RestrictionType = r.RestrictionType;
EvaluationMode = r.EvaluationMode;
}
}
private bool CollectionEquals<T>(IList<T> c1, IList<T> c2)
{
// NOTE: fixes a bug where collections weren't properly compared
if (c1 == null ||
c2 == null)
{
if (c1 == c2)
return true;
else return false;
}
if (!c1.Count.Equals(c2.Count))
return false;
IEnumerator e1 = c1.GetEnumerator();
IEnumerator e2 = c2.GetEnumerator();
while (e1.MoveNext() && e2.MoveNext())
{
if (!object.Equals(e1.Current, e2.Current))
return false;
}
return true;
}
#endregion
#region Protected Methods
#endregion
}
}
| |
//
// 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.
//
namespace NLog.LayoutRenderers
{
using System;
using System.Globalization;
using System.Text;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
/// <summary>
/// Render environmental information related to logging events.
/// </summary>
[NLogConfigurationItem]
public abstract class LayoutRenderer : ISupportsInitialize, IRenderable, IDisposable
{
private const int MaxInitialRenderBufferLength = 16384;
private int _maxRenderedLength;
private bool _isInitialized;
/// <summary>
/// Gets the logging configuration this target is part of.
/// </summary>
protected LoggingConfiguration LoggingConfiguration { get; private set; }
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
var lra = GetType().GetCustomAttribute<LayoutRendererAttribute>();
if (lra != null)
{
return $"Layout Renderer: ${{{lra.Name}}}";
}
return GetType().Name;
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Renders the the value of layout renderer in the context of the specified log event.
/// </summary>
/// <param name="logEvent">The log event.</param>
/// <returns>String representation of a layout renderer.</returns>
public string Render(LogEventInfo logEvent)
{
int initialLength = _maxRenderedLength;
if (initialLength > MaxInitialRenderBufferLength)
{
initialLength = MaxInitialRenderBufferLength;
}
var builder = new StringBuilder(initialLength);
RenderAppendBuilder(logEvent, builder);
if (builder.Length > _maxRenderedLength)
{
_maxRenderedLength = builder.Length;
}
return builder.ToString();
}
/// <summary>
/// Initializes this instance.
/// </summary>
/// <param name="configuration">The configuration.</param>
void ISupportsInitialize.Initialize(LoggingConfiguration configuration)
{
Initialize(configuration);
}
/// <summary>
/// Closes this instance.
/// </summary>
void ISupportsInitialize.Close()
{
Close();
}
/// <summary>
/// Initializes this instance.
/// </summary>
/// <param name="configuration">The configuration.</param>
internal void Initialize(LoggingConfiguration configuration)
{
if (LoggingConfiguration == null)
LoggingConfiguration = configuration;
if (!_isInitialized)
{
_isInitialized = true;
InitializeLayoutRenderer();
}
}
/// <summary>
/// Closes this instance.
/// </summary>
internal void Close()
{
if (_isInitialized)
{
LoggingConfiguration = null;
_isInitialized = false;
CloseLayoutRenderer();
}
}
/// <summary>
/// Renders the the value of layout renderer in the context of the specified log event.
/// </summary>
/// <param name="logEvent">The log event.</param>
/// <param name="builder">The layout render output is appended to builder</param>
internal void RenderAppendBuilder(LogEventInfo logEvent, StringBuilder builder)
{
if (!_isInitialized)
{
_isInitialized = true;
InitializeLayoutRenderer();
}
try
{
Append(builder, logEvent);
}
catch (Exception exception)
{
InternalLogger.Warn(exception, "Exception in layout renderer.");
if (exception.MustBeRethrown())
{
throw;
}
}
}
/// <summary>
/// Renders the specified environmental 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 abstract void Append(StringBuilder builder, LogEventInfo logEvent);
/// <summary>
/// Initializes the layout renderer.
/// </summary>
protected virtual void InitializeLayoutRenderer()
{
}
/// <summary>
/// Closes the layout renderer.
/// </summary>
protected virtual void CloseLayoutRenderer()
{
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing">True to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
Close();
}
}
/// <summary>
/// Get the <see cref="IFormatProvider"/> for rendering the messages to a <see cref="string"/>
/// </summary>
/// <param name="logEvent">LogEvent with culture</param>
/// <param name="layoutCulture">Culture in on Layout level</param>
/// <returns></returns>
protected IFormatProvider GetFormatProvider(LogEventInfo logEvent, IFormatProvider layoutCulture = null)
{
var culture = logEvent.FormatProvider ?? layoutCulture;
if (culture == null && LoggingConfiguration != null)
{
culture = LoggingConfiguration.DefaultCultureInfo;
}
return culture;
}
/// <summary>
/// Get the <see cref="CultureInfo"/> for rendering the messages to a <see cref="string"/>, needed for date and number formats
/// </summary>
/// <param name="logEvent">LogEvent with culture</param>
/// <param name="layoutCulture">Culture in on Layout level</param>
/// <returns></returns>
/// <remarks>
/// <see cref="GetFormatProvider"/> is preferred
/// </remarks>
protected CultureInfo GetCulture(LogEventInfo logEvent, CultureInfo layoutCulture = null)
{
var culture = logEvent.FormatProvider as CultureInfo ?? layoutCulture;
if (culture == null && LoggingConfiguration != null)
{
culture = LoggingConfiguration.DefaultCultureInfo;
}
return culture;
}
/// <summary>
/// Register a custom layout renderer.
/// </summary>
/// <remarks>Short-cut for registing to default <see cref="ConfigurationItemFactory"/></remarks>
/// <typeparam name="T"> Type of the layout renderer.</typeparam>
/// <param name="name"> Name of the layout renderer - without ${}.</param>
public static void Register<T>(string name)
where T: LayoutRenderer
{
var layoutRendererType = typeof(T);
Register(name, layoutRendererType);
}
/// <summary>
/// Register a custom layout renderer.
/// </summary>
/// <remarks>Short-cut for registing to default <see cref="ConfigurationItemFactory"/></remarks>
/// <param name="layoutRendererType"> Type of the layout renderer.</param>
/// <param name="name"> Name of the layout renderer - without ${}.</param>
public static void Register(string name, Type layoutRendererType)
{
ConfigurationItemFactory.Default.LayoutRenderers
.RegisterDefinition(name, layoutRendererType);
}
/// <summary>
/// Register a custom layout renderer with a callback function <paramref name="func"/>. The callback recieves the logEvent.
/// </summary>
/// <param name="name">Name of the layout renderer - without ${}.</param>
/// <param name="func">Callback that returns the value for the layout renderer.</param>
public static void Register(string name, Func<LogEventInfo, object> func)
{
Register(name, (info, configuration) => func(info));
}
/// <summary>
/// Register a custom layout renderer with a callback function <paramref name="func"/>. The callback recieves the logEvent and the current configuration.
/// </summary>
/// <param name="name">Name of the layout renderer - without ${}.</param>
/// <param name="func">Callback that returns the value for the layout renderer.</param>
public static void Register(string name, Func<LogEventInfo, LoggingConfiguration, object> func)
{
var layoutRenderer = new FuncLayoutRenderer(name, func);
ConfigurationItemFactory.Default.GetLayoutRenderers().RegisterFuncLayout(name, layoutRenderer);
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////
// ________ _____ __
// / _____/_______ _____ ____ ____ _/ ____\__ __ | |
// / \ ___\_ __ \\__ \ _/ ___\_/ __ \\ __\| | \| |
// \ \_\ \| | \/ / __ \_\ \___\ ___/ | | | | /| |__
// \______ /|__| (____ / \___ >\___ >|__| |____/ |____/
// \/ \/ \/ \/
// =============================================================================
// Designed & Developed by Brad Jones <brad @="bjc.id.au" />
// =============================================================================
////////////////////////////////////////////////////////////////////////////////
namespace Graceful.Query
{
using System;
using System.Linq;
using System.Data;
using Graceful.Utils;
using Graceful.Extensions;
using System.Data.SqlClient;
using System.Collections.Generic;
public class Helper
{
/**
* The instance of the Context that we will be using.
*/
protected readonly Context Db;
/**
* You must inject an instance of the Context so we
* can connect to the database and execute queries.
*/
public Helper(Context Db)
{
this.Db = Db;
}
/**
* Builds a new SqlCommand ready to be executed.
*
* ```cs
* var ctx = new Context();
* var helper = new Query.Helper(ctx);
* var cmd = helper.BuildCmd
* (
* "SELECT * FROM people WHERE surname = @surname AND age > @age",
* new Dictionary<string, object>
* {
* { "@surname", "Jones" },
* { "@age", 27 }
* }
* );
* ```
*
* > NOTE: You should dispose of the command once you have executed it.
*/
public SqlCommand BuildCmd(string query, Dictionary<string, object> parameters = null)
{
query = this.InlineSqlIds(query, parameters);
var cmd = new SqlCommand(query, this.Db.Connection);
if (parameters != null)
{
foreach(var parameter in parameters)
{
if (parameter.Value.GetType() == typeof(DBNull))
{
cmd.Parameters.AddWithValue
(
parameter.Key,
parameter.Value
);
}
else
{
cmd.Parameters.Add
(
parameterName: parameter.Key,
sqlDbType: TypeMapper.GetDBType(parameter.Value)
).Value = parameter.Value;
}
}
}
return cmd;
}
/**
* Returns a new SqlDataReader for your query.
*
* ```cs
* var ctx = new Context();
* var helper = new Query.Helper(ctx);
* using (var reader = helper.Read("SELECT * FROM Foo"))
* {
* ...read the reader...
* }
* ```
*
* > NOTE: Assuming you wrap the Query call in a "using" we will
* > automatically close and dispose of both the SqlCommand and the
* > SqlConnection used in the making of the reader.
*/
public SqlDataReader Read(string query, Dictionary<string, object> parameters = null)
{
using (var cmd = this.BuildCmd(query, parameters))
{
return this.GetReader(cmd);
}
}
/**
* Returns a loaded DataTable with your Query Results.
*
* ```cs
* var ctx = new Context();
* var helper = new Query.Helper(ctx);
* using (var dt = helper.ReadToDt("SELECT * FROM Bar"))
* {
* foreach (DataRow row in dt.Rows)
* {
* foreach (DataColumn column in dt.Columns)
* {
* var ColumnName = column.ColumnName;
* var ColumnData = row[column];
* }
* }
* }
* ```
*/
public DataTable ReadToDt(string query, Dictionary<string, object> parameters = null)
{
var dt = new DataTable();
using (var reader = this.Read(query, parameters))
{
dt.Load(reader);
}
return dt;
}
/**
* Returns the scalar result of your query.
*
* ```cs
* var ctx = new Context();
* var helper = new Query.Helper(ctx);
* var id = helper.ReadToScalar("SELECT id FROM foo WHERE x=y");
* ```
*
* > NOTE: The SqlCommand & SqlConnection are disposed of for you.
*/
public object ReadToScalar(string query, Dictionary<string, object> parameters = null)
{
object result;
using (var cmd = this.BuildCmd(query, parameters))
{
result = this.GetScalar(cmd);
}
return result;
}
/**
* Executes your query which acts on the db but does not query it.
* Eg: Inserting, Updating, Deleting, etc
*
* ```cs
* var ctx = new Context();
* var helper = new Query.Helper(ctx);
* var rowsEffected = helper.Execute("DELETE FROM foo WHERE x=y");
* ```
*
* > NOTE: The SqlCommand & SqlConnection are disposed of for you.
*/
public int Execute(string query, Dictionary<string, object> parameters = null)
{
int result;
using (var cmd = this.BuildCmd(query, parameters))
{
result = this.Execute(cmd);
}
return result;
}
/**
* Returns a list, where each row is represented by a Dictionary.
*
* ```cs
* var ctx = new Context();
* var helper = new Query.Helper(ctx);
* helper.GetRows("SELECT * FROM People").ForEach(row =>
* {
* row.Keys.ToList().ForEach(column =>
* {
* var value = row[column];
* });
* });
* ```
*/
public List<Dictionary<string, object>> GetRows(string query, Dictionary<string, object> parameters = null)
{
List<Dictionary<string, object>> list;
using (DataTable dt = this.ReadToDt(query, parameters))
{
list = this.GetRows(dt);
}
return list;
}
/**
* Returns the first row of a result set represented by a Dictionary.
*
* ```cs
* var ctx = new Context();
* var helper = new Query.Helper(ctx);
* var person = helper.GetRow("SELECT * FROM People WHERE Id = 10");
* ```
*/
public Dictionary<string, object> GetRow(string query, Dictionary<string, object> parameters = null)
{
return this.GetRows(query, parameters).First();
}
/**
* Check to see if the table exists in the database.
*
* ```cs
* var ctx = new Context();
* var helper = new Query.Helper(ctx);
* if (helper.TableExists("FooBar"))
* {
* // The Table FooBar exists
* }
* else
* {
* // The Table FooBar does not exist
* }
* ```
*/
public bool TableExists(string tableName)
{
return (int)this.ReadToScalar
(
"SELECT COUNT(*)\n" +
"FROM @dbName.[INFORMATION_SCHEMA].[TABLES]\n" +
"WHERE [TABLE_NAME] = @value",
new Dictionary<string, object>
{
{"@dbName", new SqlId(this.Db.DatabaseName)},
{"@value", tableName}
}
) > 0 ? true : false;
}
/**
* Check to see if the table is empty or not.
*
* ```cs
* var ctx = new Context();
* var helper = new Query.Helper(ctx);
* if (helper.TableEmpty("FooBar"))
* {
* // The table FooBar is Empty, contains no records.
* }
* else
* {
* // The table FooBar is not Empty, does contains some records.
* }
* ```
*/
public bool TableEmpty(string tableName)
{
return (int)this.ReadToScalar
(
"SELECT COUNT(*) FROM @value",
new Dictionary<string, object>
{
{"@value", new SqlId(tableName)}
}
) == 0 ? true : false;
}
/**
* Check to see if a column exists in a given table.
*
* ```cs
* var ctx = new Context();
* var helper = new Query.Helper(ctx);
* if (helper.ColumnExists("FooBar", "Baz"))
* {
* // The table FooBar contains the column Baz.
* }
* else
* {
* // The table FooBar does not contain the column Baz.
* }
* ```
*/
public bool ColumnExists(string tableName, string colName)
{
return (int)this.ReadToScalar
(
"SELECT COUNT(*)\n" +
"FROM @dbName.[INFORMATION_SCHEMA].[COLUMNS]\n" +
"WHERE [TABLE_NAME] = @tableName " +
"AND [COLUMN_NAME] = @colName",
new Dictionary<string, object>
{
{"@dbName", new SqlId(this.Db.DatabaseName)},
{"@tableName", tableName},
{"@colName", colName}
}
) > 0 ? true : false;
}
/**
* Returns the current SqlDbType of the given column.
*
* ```cs
* var ctx = new Context();
* var helper = new Query.Helper(ctx);
* var type = helper.ColumnDataType("FooBar", "Baz");
*
* // ie: SqlDbType.NVarChar
* ```
*/
public SqlDbType ColumnDataType(string tableName, string colName)
{
var dataType = (string)this.ReadToScalar
(
"SELECT data_type \n" +
"FROM information_schema.columns \n" +
"WHERE table_catalog = @dbName " +
"AND table_name = @tableName " +
"AND column_name = @colName",
new Dictionary<string, object>
{
{"@dbName", this.Db.DatabaseName},
{"@tableName", tableName},
{"@colName", colName}
}
);
return TypeMapper.GetSqlDbTypeFromString(dataType);
}
/**
* Inlines SqlId Parameters.
*
* > NOTE: See the Graceful.Query.SqlId class docs for more info.
*/
protected string InlineSqlIds(string query, Dictionary<string, object> parameters)
{
// If the query has no parameters then we don't have anything to do.
if (parameters == null || parameters.Count == 0) return query;
// Grab a list of parameters that are SqlIds.
parameters.Where
(
p =>
p.Value.GetType() == typeof(SqlId) ||
p.Value.GetType().IsSubclassOf(typeof(SqlId))
)
.ToList().ForEach(parameter =>
{
// And inline the SqlId Value into the query string,
// as an SqlId can not be sent as a SqlParameter.
query = query.Replace
(
parameter.Key,
((SqlId)parameter.Value).Value
);
// Remove the parameter from the original parameters dict.
parameters.Remove(parameter.Key);
});
return query;
}
/**
* Given a SqlCommand and a way to execute that command,
* we finally run the query. Used internally by GetReader, GetScarlar
* and Execute methods.
*
* ```cs
* var cmd = this.BuildCmd("SELECT * FROM Foo");
* this.RunQuery
* (
* cmd,
* query => query.ExecuteReader / ExecuteScalar / ExecuteNonQuery
* affected =>
* {
* // given the result from the above execute method
* // you then need to return the number of affected rows.
* },
* dispose: true // do you want the connection disposed afterwards
* );
* ```
*/
protected object RunQuery(SqlCommand cmd, Func<SqlCommand, object> query, Func<object, int> affected, bool dispose = true)
{
object results;
try
{
results = query.Invoke(cmd);
if (this.Db.LogWriter != null)
{
this.Db.LogWriter.WriteLine
(
cmd.ToTraceString
(
affected.Invoke(results)
)
);
}
}
catch
{
if (this.Db.LogWriter != null)
{
this.Db.LogWriter.WriteLine("-- !!!NEXT QUERY ERRORED!!!");
this.Db.LogWriter.WriteLine(cmd.ToTraceString());
}
throw;
}
finally
{
if (dispose) cmd.Connection.Dispose();
}
return results;
}
/**
* Given a SqlCommand, we will return a SqlReader.
*/
protected SqlDataReader GetReader(SqlCommand cmd)
{
return (SqlDataReader)this.RunQuery
(
cmd,
query => query.ExecuteReader(CommandBehavior.CloseConnection),
affected => ((SqlDataReader)affected).RecordsAffected,
dispose: false
);
}
/**
* Given a SqlCommand, we will run an ExecuteScalar Operation.
*/
protected object GetScalar(SqlCommand cmd)
{
return this.RunQuery
(
cmd,
query =>
{
var result = query.ExecuteScalar();
if (result is DBNull) return null;
return result;
},
affected => 0
);
}
/**
* Given a SqlCommand, we will run an ExecuteNonQuery Operation.
*/
protected int Execute(SqlCommand cmd)
{
return (int)this.RunQuery
(
cmd,
query => query.ExecuteNonQuery(),
affected => (int)affected
);
}
/**
* Given a DataTable, we will return a List of Dictionary<string, object>s.
*/
protected List<Dictionary<string, object>> GetRows(DataTable dt)
{
var list = new List<Dictionary<string, object>>();
foreach (DataRow row in dt.Rows)
{
var result = new Dictionary<string, object>();
foreach (DataColumn column in dt.Columns)
{
if (!(row[column] is DBNull))
{
result.Add(column.ColumnName, row[column]);
}
}
list.Add(result);
}
return list;
}
}
}
| |
//---------------------------------------------------------------------------------
// Copyright 2013 Ceton Corp
// Copyright 2013-2015 Tomasz Cielecki (tomasz@ostebaronen.dk)
// 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
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED,
// INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR
// CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing
// permissions and limitations under the License.
//---------------------------------------------------------------------------------
using System;
using Android.Content;
using Android.Preferences;
using Cheesebaron.MvxPlugins.Settings.Interfaces;
using Cirrious.CrossCore;
using Cirrious.CrossCore.Droid;
namespace Cheesebaron.MvxPlugins.Settings.Droid
{
public class Settings : ISettings
{
private static string _settingsFileName;
private readonly object _locker = new object();
private static ISharedPreferences SharedPreferences
{
get
{
var context = Mvx.Resolve<IMvxAndroidGlobals>().ApplicationContext;
//If file name is empty use defaults
if(string.IsNullOrEmpty(_settingsFileName))
return PreferenceManager.GetDefaultSharedPreferences(context);
return context.ApplicationContext.GetSharedPreferences(_settingsFileName,
FileCreationMode.Append);
}
}
public Settings(string settingsFileName = null) { _settingsFileName = settingsFileName; }
public T GetValue<T>(string key, T defaultValue = default(T), bool roaming = false)
{
if (string.IsNullOrEmpty(key))
throw new ArgumentException("Key must have a value", "key");
lock (_locker)
{
var type = typeof(T);
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
type = Nullable.GetUnderlyingType(type);
using (var sharedPrefs = SharedPreferences)
{
object returnVal;
switch (Type.GetTypeCode(type))
{
case TypeCode.Boolean:
returnVal = sharedPrefs.GetBoolean(key, Convert.ToBoolean(defaultValue));
break;
case TypeCode.Int64:
returnVal = sharedPrefs.GetLong(key, Convert.ToInt64(defaultValue));
break;
case TypeCode.Int32:
returnVal = sharedPrefs.GetInt(key, Convert.ToInt32(defaultValue));
break;
case TypeCode.Single:
returnVal = sharedPrefs.GetFloat(key, Convert.ToSingle(defaultValue));
break;
case TypeCode.String:
returnVal = sharedPrefs.GetString(key, Convert.ToString(defaultValue));
break;
case TypeCode.DateTime:
{
var ticks = sharedPrefs.GetLong(key, -1);
if (ticks == -1)
returnVal = defaultValue;
else
returnVal = new DateTime(ticks);
break;
}
default:
if (type.Name == typeof(DateTimeOffset).Name)
{
var ticks = sharedPrefs.GetString(key, "");
if (string.IsNullOrEmpty(ticks))
returnVal = defaultValue;
else
returnVal = DateTimeOffset.Parse(ticks);
break;
}
if (type.Name == typeof(Guid).Name)
{
var guid = sharedPrefs.GetString(key, "");
if (!string.IsNullOrEmpty(guid))
{
Guid outGuid;
Guid.TryParse(guid, out outGuid);
returnVal = outGuid;
}
else
returnVal = defaultValue;
break;
}
throw new ArgumentException(string.Format("Type {0} is not supported", type),
"defaultValue");
}
return (T)returnVal;
}
}
}
public bool AddOrUpdateValue<T>(string key, T value = default(T), bool roaming = false)
{
if (string.IsNullOrEmpty(key))
throw new ArgumentException("Key must have a value", "key");
lock (_locker)
{
using (var sharedPrefs = SharedPreferences)
using (var editor = sharedPrefs.Edit())
{
var type = value.GetType();
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof (Nullable<>))
type = Nullable.GetUnderlyingType(type);
switch (Type.GetTypeCode(type))
{
case TypeCode.Boolean:
editor.PutBoolean(key, Convert.ToBoolean(value));
break;
case TypeCode.Int64:
editor.PutLong(key, Convert.ToInt64(value));
break;
case TypeCode.Int32:
editor.PutInt(key, Convert.ToInt32(value));
break;
case TypeCode.Single:
editor.PutFloat(key, Convert.ToSingle(value));
break;
case TypeCode.String:
editor.PutString(key, Convert.ToString(value));
break;
case TypeCode.DateTime:
editor.PutLong(key, ((DateTime) (object) value).Ticks);
break;
default:
if (type.Name == typeof (DateTimeOffset).Name)
{
editor.PutString(key, ((DateTimeOffset) (object) value).ToString("o"));
break;
}
if (type.Name == typeof (Guid).Name)
{
var g = value as Guid?;
if (g.HasValue)
editor.PutString(key, g.Value.ToString());
break;
}
throw new ArgumentException(
string.Format("Type {0} is not supported", type), "value");
}
return editor.Commit();
}
}
}
public bool DeleteValue(string key, bool roaming = false)
{
if (string.IsNullOrEmpty(key))
throw new ArgumentException("Key must have a value", "key");
lock (_locker)
{
using (var sharedPrefs = SharedPreferences)
using (var editor = sharedPrefs.Edit())
{
editor.Remove(key);
return editor.Commit();
}
}
}
public bool Contains(string key, bool roaming = false)
{
if (string.IsNullOrEmpty(key))
throw new ArgumentException("Key must have a value", "key");
lock (_locker)
{
using (var sharedPrefs = SharedPreferences)
return sharedPrefs.Contains(key);
}
}
public bool ClearAllValues(bool roaming = false)
{
lock (_locker)
{
using (var sharedPrefs = SharedPreferences)
using (var editor = sharedPrefs.Edit())
{
editor.Clear();
return editor.Commit();
}
}
}
}
}
| |
using System;
using System.Drawing;
using System.Collections.Generic;
using System.Text;
namespace Scintilla.Forms.Configuration
{
public class ColorHandler
{
// Handle conversions between RGB and HSV
// (and Color types, as well).
public struct RGB
{
// All values are between 0 and 255.
public int Red;
public int Green;
public int Blue;
public RGB(int R, int G, int B)
{
Red = R;
Green = G;
Blue = B;
}
public override string ToString()
{
return String.Format("({0}, {1}, {2})", Red, Green, Blue);
}
}
public struct HSV
{
// All values are between 0 and 255.
public int Hue;
public int Saturation;
public int value;
public HSV(int H, int S, int V)
{
Hue = H;
Saturation = S;
value = V;
}
public override string ToString()
{
return String.Format("({0}, {1}, {2})", Hue, Saturation, value);
}
}
public static RGB HSVtoRGB(int H, int S, int V)
{
// H, S, and V must all be between 0 and 255.
return HSVtoRGB(new HSV(H, S, V));
}
public static Color HSVtoColor(HSV hsv)
{
RGB RGB = HSVtoRGB(hsv);
return Color.FromArgb(RGB.Red, RGB.Green, RGB.Blue);
}
public static Color HSVtoColor(int H, int S, int V)
{
return HSVtoColor(new HSV(H, S, V));
}
public static RGB HSVtoRGB(HSV HSV)
{
// HSV contains values scaled as in the color wheel:
// that is, all from 0 to 255.
// for ( this code to work, HSV.Hue needs
// to be scaled from 0 to 360 (it//s the angle of the selected
// point within the circle). HSV.Saturation and HSV.value must be
// scaled to be between 0 and 1.
double h;
double s;
double v;
double r = 0;
double g = 0;
double b = 0;
// Scale Hue to be between 0 and 360. Saturation
// and value scale to be between 0 and 1.
h = ((double)HSV.Hue / 255 * 360) % 360;
s = (double)HSV.Saturation / 255;
v = (double)HSV.value / 255;
if (s == 0)
{
// If s is 0, all colors are the same.
// This is some flavor of gray.
r = v;
g = v;
b = v;
}
else
{
double p;
double q;
double t;
double fractionalSector;
int sectorNumber;
double sectorPos;
// The color wheel consists of 6 sectors.
// Figure out which sector you//re in.
sectorPos = h / 60;
sectorNumber = (int)(Math.Floor(sectorPos));
// get the fractional part of the sector.
// That is, how many degrees into the sector
// are you?
fractionalSector = sectorPos - sectorNumber;
// Calculate values for the three axes
// of the color.
p = v * (1 - s);
q = v * (1 - (s * fractionalSector));
t = v * (1 - (s * (1 - fractionalSector)));
// Assign the fractional colors to r, g, and b
// based on the sector the angle is in.
switch (sectorNumber)
{
case 0:
r = v;
g = t;
b = p;
break;
case 1:
r = q;
g = v;
b = p;
break;
case 2:
r = p;
g = v;
b = t;
break;
case 3:
r = p;
g = q;
b = v;
break;
case 4:
r = t;
g = p;
b = v;
break;
case 5:
r = v;
g = p;
b = q;
break;
}
}
// return an RGB structure, with values scaled
// to be between 0 and 255.
return new RGB((int)(r * 255), (int)(g * 255), (int)(b * 255));
}
public static HSV RGBtoHSV(RGB RGB)
{
// In this function, R, G, and B values must be scaled
// to be between 0 and 1.
// HSV.Hue will be a value between 0 and 360, and
// HSV.Saturation and value are between 0 and 1.
// The code must scale these to be between 0 and 255 for
// the purposes of this application.
double min;
double max;
double delta;
double r = (double)RGB.Red / 255;
double g = (double)RGB.Green / 255;
double b = (double)RGB.Blue / 255;
double h;
double s;
double v;
min = Math.Min(Math.Min(r, g), b);
max = Math.Max(Math.Max(r, g), b);
v = max;
delta = max - min;
if (max == 0 || delta == 0)
{
// R, G, and B must be 0, or all the same.
// In this case, S is 0, and H is undefined.
// Using H = 0 is as good as any...
s = 0;
h = 0;
}
else
{
s = delta / max;
if (r == max)
{
// Between Yellow and Magenta
h = (g - b) / delta;
}
else if (g == max)
{
// Between Cyan and Yellow
h = 2 + (b - r) / delta;
}
else
{
// Between Magenta and Cyan
h = 4 + (r - g) / delta;
}
}
// Scale h to be between 0 and 360.
// This may require adding 360, if the value
// is negative.
h *= 60;
if (h < 0)
{
h += 360;
}
// Scale to the requirements of this
// application. All values are between 0 and 255.
return new HSV((int)(h / 360 * 255), (int)(s * 255), (int)(v * 255));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using DotLiquid.Exceptions;
using DotLiquid.Types;
namespace DotLiquid
{
internal class ScaliderStrainer : Strainer
{
private readonly IDictionary<string, IList<FilterInfo>> _filters = new Dictionary<string, IList<FilterInfo>>();
public ScaliderStrainer(Context context)
: base(context)
{
}
/// <inheritdoc />
public override IEnumerable<MethodInfo> Methods
=> _filters.Values.SelectMany(t => t.Select(x => x.MethodInfo));
/// <inheritdoc />
public override void Extend(Type type)
{
// From what I can tell, calls to Extend should replace existing filters. So be it.
var methods = type.GetRuntimeMethods().Where(m => m.IsPublic && m.IsStatic);
var methodsArray = methods.ToArray();
var methodNames = methodsArray.Select(m => Template.NamingConvention.GetMemberName(m.Name));
foreach (var methodName in methodNames)
_filters.Remove(methodName);
foreach (var methodInfo in methodsArray)
AddMethodInfo(methodInfo.Name, null, methodInfo);
}
/// <inheritdoc />
public override bool RespondTo(string method)
=> !string.IsNullOrWhiteSpace(method) && _filters.ContainsKey(method) && _filters[method].Count > 0;
/// <inheritdoc />
public override void AddMethodInfo(string rawName, object target, MethodInfo method)
{
var name = Template.NamingConvention.GetMemberName(rawName);
if (!_filters.TryGetValue(name, out var filterList))
{
// This is the first time the filter is being registered, so create an empty list for it
filterList = new List<FilterInfo>();
_filters[name] = filterList;
}
// Add the filter to our filter list
filterList.Add(new FilterInfo(target, method));
}
/// <inheritdoc />
public override object Invoke(string method, List<object> args)
{
var callingObj = GetCallingObject(args);
var callingObjType = callingObj == null ? typeof(object) : callingObj.GetType();
var filterInfo = GetPossibleFilterForMethod(method, callingObjType, args);
if (!filterInfo.IsValid)
{
// No suitable filter found, we'll just ignore the invokation
return callingObj;
}
// Determine whether needs to append default values to missing parameters
if (filterInfo.ParametersCount > args.Count)
{
for (var i = args.Count; i < filterInfo.ParametersCount; ++i)
{
var param = filterInfo[i];
if (!param.IsOptional)
{
// The parameter is optional, use the default value instead
throw new SyntaxException(
Liquid.ResourceManager.GetString("StrainerFilterHasNoValueException"),
method,
param.Name
);
}
args.Add(param.DefaultValue);
}
}
//
for (var i = 0; i < args.Count; i++)
{
var argValue = args[i];
var argType = argValue == null ? typeof(object) : args[i].GetType();
if (argValue != null && !filterInfo[i].IsCastableFrom(argType))
args[i] = filterInfo[i].ChangeType(args[i], Context.FormatProvider);
}
//
try
{
if (filterInfo.IsFirstParameterContext)
args.Insert(0, Context);
return filterInfo.MethodInfo.Invoke(filterInfo.Target, args.ToArray());
}
catch (TargetInvocationException ex)
{
throw ex.InnerException ?? ex;
}
}
private static object GetCallingObject(IReadOnlyList<object> args)
{
if (args == null || args.Count == 0)
return null;
var firstArg = args[0];
return firstArg is DropBase dropBase ? dropBase.GetObject() : firstArg;
}
private FilterInfo GetPossibleFilterForMethod(string method, Type callingObjType, IReadOnlyList<object> args)
{
var filters = _filters[method];
var argsCount = args.Count;
//
var possibleFilters = filters
.Where(t => t.FirstParameterType != null)
.Where(t => t[0].IsAssignableFrom(callingObjType))
.Where(t => t.ParametersCount >= argsCount)
.OrderBy(t => t.ParametersCount)
.ToArray();
// Determine whether more than one filter was found
var orderedPossibleFilters = new List<FilterInfo>();
if (possibleFilters.Length > 1)
{
// More than one filter was found, order them following the next rule:
// First are the filters whose first parameter is an exact match to the argument type
orderedPossibleFilters.AddRange(possibleFilters.Where(t => t.FirstParameterType == callingObjType));
// Then, append the filters whose first character is not an exact match to the argument type,
// but can be assigned to that type regardless (for example, short can be assigned to int),
// ignoring the filters that met the first condition
orderedPossibleFilters.AddRange(
possibleFilters
.Except(orderedPossibleFilters)
.Where(
t => t.FirstParameterType != typeof(object) && t[0].IsAssignableFrom(callingObjType)
)
);
// Finally, append the filters that doesn't match any of the previous conditions
orderedPossibleFilters.AddRange(possibleFilters.Except(orderedPossibleFilters));
}
else if (possibleFilters.Length == 1)
orderedPossibleFilters.Add(possibleFilters[0]);
else
return default;
//
foreach (var filter in orderedPossibleFilters)
{
var isValidFilter = true;
var validArgumentsCount = 1;
for (var i = 1; i < argsCount; ++i)
{
var arg = args[i];
var argType = arg == null ? typeof(object) : arg.GetType();
var param = filter[i];
if (param.IsAssignableFrom(argType))
{
// The argument is valid for the parameter at the given position
validArgumentsCount++;
continue;
}
isValidFilter = false;
break;
}
// Determine whether we got all the parameters for the filter
if (filter.ParametersCount > validArgumentsCount)
{
// We are missing some parameters, determine whether those are optional, if one or more isn't
// optional, then we should ignore this filter
for (var i = validArgumentsCount; i < filter.ParametersCount; ++i)
{
var param = filter[i];
if (param.IsOptional)
continue;
// The parameter isn't optional, we should ignore this filter
isValidFilter = false;
break;
}
}
// Determine whether the filter is valid, and if so, return it here
if (isValidFilter)
return filter;
}
// We couldn't find a valid filter
return default;
}
private readonly struct FilterInfo
{
public FilterInfo(object target, MethodInfo methodInfo)
{
IsValid = true;
Target = target;
MethodInfo = methodInfo;
Parameters = methodInfo.GetParameters();
if (Parameters.Length > 0)
{
if (typeof(Context) == Parameters[0].ParameterType)
{
IsFirstParameterContext = true;
ParametersCount = Parameters.Length - 1;
FirstParameterType = Parameters.Length > 1 ? Parameters[1].ParameterType : null;
}
else
{
IsFirstParameterContext = false;
ParametersCount = Parameters.Length;
FirstParameterType = Parameters[0].ParameterType;
}
}
else
{
IsFirstParameterContext = false;
ParametersCount = Parameters.Length;
FirstParameterType = Parameters.Length > 0 ? Parameters[0].ParameterType : null;
}
}
public bool IsValid { get; }
public object Target { get; }
public MethodInfo MethodInfo { get; }
public ParameterInfo[] Parameters { get; }
public int ParametersCount { get; }
public Type FirstParameterType { get; }
public bool IsFirstParameterContext { get; }
public ParameterInfo this[int index] => Parameters[(IsFirstParameterContext ? 1 : 0) + index];
}
}
}
| |
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))
{
var basePath = Platform.IsMac ? "/Users/Shared" : 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.IsUnix && !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 System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using GrandTheftMultiplayer.Server.API;
using GrandTheftMultiplayer.Server.Constant;
using GrandTheftMultiplayer.Server.Elements;
using GrandTheftMultiplayer.Server.Managers;
using GrandTheftMultiplayer.Shared;
using GrandTheftMultiplayer.Shared.Math;
public class FreeroamScript : Script
{
public FreeroamScript()
{
API.onClientEventTrigger += onClientEventTrigger;
API.onPlayerConnected += API_onPlayerConnected;
}
private static Random Rnd = new Random();
public Dictionary<Client, List<NetHandle>> VehicleHistory = new Dictionary<Client, List<NetHandle>>();
public Dictionary<string, string> AnimationList = new Dictionary<string, string>
{
{"finger", "mp_player_intfinger mp_player_int_finger"},
{"guitar", "anim@mp_player_intcelebrationmale@air_guitar air_guitar"},
{"shagging", "anim@mp_player_intcelebrationmale@air_shagging air_shagging"},
{"synth", "anim@mp_player_intcelebrationmale@air_synth air_synth"},
{"kiss", "anim@mp_player_intcelebrationmale@blow_kiss blow_kiss"},
{"bro", "anim@mp_player_intcelebrationmale@bro_love bro_love"},
{"chicken", "anim@mp_player_intcelebrationmale@chicken_taunt chicken_taunt"},
{"chin", "anim@mp_player_intcelebrationmale@chin_brush chin_brush"},
{"dj", "anim@mp_player_intcelebrationmale@dj dj"},
{"dock", "anim@mp_player_intcelebrationmale@dock dock"},
{"facepalm", "anim@mp_player_intcelebrationmale@face_palm face_palm"},
{"fingerkiss", "anim@mp_player_intcelebrationmale@finger_kiss finger_kiss"},
{"freakout", "anim@mp_player_intcelebrationmale@freakout freakout"},
{"jazzhands", "anim@mp_player_intcelebrationmale@jazz_hands jazz_hands"},
{"knuckle", "anim@mp_player_intcelebrationmale@knuckle_crunch knuckle_crunch"},
{"nose", "anim@mp_player_intcelebrationmale@nose_pick nose_pick"},
{"no", "anim@mp_player_intcelebrationmale@no_way no_way"},
{"peace", "anim@mp_player_intcelebrationmale@peace peace"},
{"photo", "anim@mp_player_intcelebrationmale@photography photography"},
{"rock", "anim@mp_player_intcelebrationmale@rock rock"},
{"salute", "anim@mp_player_intcelebrationmale@salute salute"},
{"shush", "anim@mp_player_intcelebrationmale@shush shush"},
{"slowclap", "anim@mp_player_intcelebrationmale@slow_clap slow_clap"},
{"surrender", "anim@mp_player_intcelebrationmale@surrender surrender"},
{"thumbs", "anim@mp_player_intcelebrationmale@thumbs_up thumbs_up"},
{"taunt", "anim@mp_player_intcelebrationmale@thumb_on_ears thumb_on_ears"},
{"vsign", "anim@mp_player_intcelebrationmale@v_sign v_sign"},
{"wank", "anim@mp_player_intcelebrationmale@wank wank"},
{"wave", "anim@mp_player_intcelebrationmale@wave wave"},
{"loco", "anim@mp_player_intcelebrationmale@you_loco you_loco"},
{"handsup", "missminuteman_1ig_2 handsup_base"},
};
public List<VehicleHash> BannedVehicles = new List<VehicleHash>
{
VehicleHash.CargoPlane,
};
public List<Vector3> SpawnPositions = new List<Vector3>
{
new Vector3(-237.172, -650.3887, 33.30411),
new Vector3(-276.9281, -642.3959, 33.20348),
new Vector3(-284.7394, -679.6924, 33.27827),
new Vector3(-219.5132, -697.4506, 33.67715),
new Vector3(-172.2065, -666.7617, 40.48457),
new Vector3(-344.8585, -691.2588, 32.73247),
};
public void onClientEventTrigger(Client sender, string name, object[] args)
{
if (name == "CREATE_VEHICLE")
{
int model = (int)args[0];
if (!Enum.IsDefined(typeof(VehicleHash), model))
return;
var rot = API.getEntityRotation(sender.handle);
var veh = API.createVehicle((VehicleHash)model, sender.position, new Vector3(0, 0, rot.Z), 0, 0);
if (VehicleHistory.ContainsKey(sender))
{
VehicleHistory[sender].Add(veh);
if (VehicleHistory[sender].Count > 3)
{
API.deleteEntity(VehicleHistory[sender][0]);
VehicleHistory[sender].RemoveAt(0);
}
}
else
{
VehicleHistory.Add(sender, new List<NetHandle> { veh });
}
API.setPlayerIntoVehicle(sender, veh, -1);
}
else if (name == "REQUEST_WEAPON")
{
int hash = (int)args[0];
API.givePlayerWeapon(sender, (WeaponHash)hash, 100, false);
}
}
private void API_onPlayerConnected(Client player)
{
var vals = Enum.GetValues(typeof(PedHash)).OfType<PedHash>();
var randomSkin = vals.ElementAt(Rnd.Next(vals.Count()));
player.setSkin(randomSkin);
player.position = SpawnPositions[Rnd.Next(SpawnPositions.Count)];
}
[Command("me", GreedyArg = true)]
public void MeCommand(Client sender, string text)
{
API.sendChatMessageToAll("~#C2A2DA~", sender.name + " " + text);
}
[Command("spec")]
public void SpectatorCommand(Client sender, Client target)
{
API.setPlayerToSpectatePlayer(sender, target);
}
[Command("unspec")]
public void StopSpectatingCommand(Client sender)
{
API.unspectatePlayer(sender);
}
[Command("loadipl")]
public void LoadIplCommand(Client sender, string ipl)
{
API.requestIpl(ipl);
API.consoleOutput("LOADED IPL " + ipl);
API.sendChatMessageToPlayer(sender, "Loaded IPL ~b~" + ipl + "~w~.");
}
[Command("removeipl")]
public void RemoveIplCommand(Client sender, string ipl)
{
API.removeIpl(ipl);
API.consoleOutput("REMOVED IPL " + ipl);
API.sendChatMessageToPlayer(sender, "Removed IPL ~b~" + ipl + "~w~.");
}
[Command("blackout")]
public void BlackoutCommand(Client sender, bool blackout)
{
API.sendNativeToAllPlayers(0x1268615ACE24D504, blackout);
}
[Command("dimension")]
public void ChangeDimension(Client sender, int dimension)
{
API.setEntityDimension(sender.handle, dimension);
}
[Command("mod")]
public void SetCarModificationCommand(Client sender, int modIndex, int modVar)
{
if (!sender.vehicle.IsNull)
{
API.setVehicleMod(sender.vehicle, modIndex, modVar);
API.sendChatMessageToPlayer(sender, "Mod applied successfully!");
}
else
{
API.sendChatMessageToPlayer(sender, "~r~ERROR: ~w~You're not in a vehicle!");
}
}
[Command("clothes")]
public void SetPedClothesCommand(Client sender, int slot, int drawable, int texture)
{
API.setPlayerClothes(sender, slot, drawable, texture);
API.sendChatMessageToPlayer(sender, "Clothes applied successfully!");
}
[Command("props")]
public void SetPedAccessoriesCommand(Client sender, int slot, int drawable, int texture)
{
API.setPlayerAccessory(sender, slot, drawable, texture);
API.sendChatMessageToPlayer(sender, "Props applied successfully!");
}
[Command("colors")]
public void GameVehicleColorsCommand(Client sender, int primaryColor, int secondaryColor)
{
if (!sender.vehicle.IsNull)
{
API.setVehiclePrimaryColor(sender.vehicle, primaryColor);
API.setVehicleSecondaryColor(sender.vehicle, secondaryColor);
API.sendChatMessageToPlayer(sender, "Colors applied successfully!");
}
else
{
API.sendChatMessageToPlayer(sender, "~r~ERROR: ~w~You're not in a vehicle!");
}
}
private Dictionary<Client, NetHandle> cars = new Dictionary<Client, NetHandle>();
private Dictionary<Client, NetHandle> shields = new Dictionary<Client, NetHandle>();
[Command("detach")]
public void detachtest(Client sender)
{
if (cars.ContainsKey(sender))
{
API.deleteEntity(cars[sender]);
cars.Remove(sender);
}
if (labels.ContainsKey(sender))
{
API.deleteEntity(labels[sender]);
labels.Remove(sender);
}
if (shields.ContainsKey(sender))
{
API.deleteEntity(shields[sender]);
shields.Remove(sender);
}
}
[Command("attachveh")]
public void attachtest2(Client sender, VehicleHash veh)
{
if (cars.ContainsKey(sender))
{
API.deleteEntity(cars[sender]);
cars.Remove(sender);
}
var prop = API.createVehicle(veh, API.getEntityPosition(sender.handle), new Vector3(), 0, 0);
API.attachEntityToEntity(prop, sender.handle, null,
new Vector3(), new Vector3());
cars.Add(sender, prop);
}
private Dictionary<Client, NetHandle> labels = new Dictionary<Client, NetHandle>();
[Command("attachlabel")]
public void attachtest3(Client sender, string message)
{
if (labels.ContainsKey(sender))
{
API.deleteEntity(labels[sender]);
labels.Remove(sender);
}
var prop = API.createTextLabel(message, API.getEntityPosition(sender.handle), 50f, 0.4f, true);
API.attachEntityToEntity(prop, sender.handle, null,
new Vector3(0, 0, 1f), new Vector3());
labels.Add(sender, prop);
}
[Command("attachmarker")]
public void attachtest4(Client sender)
{
var prop = API.createMarker(0, API.getEntityPosition(sender.handle), new Vector3(), new Vector3(), new Vector3(1f, 1f, 1f), 255, 255, 255, 255);
API.attachEntityToEntity(prop, sender.handle, null,
new Vector3(), new Vector3());
}
[Command("shield")]
public void attachtest5(Client sender)
{
if (shields.ContainsKey(sender))
{
API.deleteEntity(shields[sender]);
shields.Remove(sender);
}
var prop = API.createObject(API.getHashKey("prop_riot_shield"), API.getEntityPosition(sender.handle), new Vector3());
API.attachEntityToEntity(prop, sender.handle, "SKEL_L_Hand",
new Vector3(0, 0, 0), new Vector3(0f, 0f, 0f));
shields.Add(sender, prop);
}
[Command("attachrpg")]
public void attachtest1(Client sender)
{
var prop = API.createObject(API.getHashKey("w_lr_rpg"), API.getEntityPosition(sender.handle), new Vector3());
API.attachEntityToEntity(prop, sender.handle, "SKEL_SPINE3",
new Vector3(-0.13f, -0.231f, 0.07f), new Vector3(0f, 200f, 10f));
}
[Command("colorsrgb")]
public void CustomVehicleColorsCommand(Client sender, int primaryRed, int primaryGreen, int primaryBlue, int secondaryRed, int secondaryGreen, int secondaryBlue)
{
if (!sender.vehicle.IsNull)
{
API.setVehicleCustomPrimaryColor(sender.vehicle, primaryRed, primaryGreen, primaryBlue);
API.setVehicleCustomSecondaryColor(sender.vehicle, secondaryRed, secondaryGreen, secondaryBlue);
API.sendChatMessageToPlayer(sender, "Colors applied successfully!");
}
else
{
API.sendChatMessageToPlayer(sender, "~r~ERROR: ~w~You're not in a vehicle!");
}
}
[Command("anim", "~y~USAGE: ~w~/anim [animation]\n" +
"~y~USAGE: ~w~/anim help for animation list.\n" +
"~y~USAGE: ~w~/anim stop to stop current animation.")]
public void SetPlayerAnim(Client sender, string animation)
{
if (animation == "help")
{
string helpText = AnimationList.Aggregate(new StringBuilder(),
(sb, kvp) => sb.Append(kvp.Key + " "), sb => sb.ToString());
API.sendChatMessageToPlayer(sender, "~b~Available animations:");
var split = helpText.Split();
for (int i = 0; i < split.Length; i += 5)
{
string output = "";
if (split.Length > i)
output += split[i] + " ";
if (split.Length > i + 1)
output += split[i + 1] + " ";
if (split.Length > i + 2)
output += split[i + 2] + " ";
if (split.Length > i + 3)
output += split[i + 3] + " ";
if (split.Length > i + 4)
output += split[i + 4] + " ";
if (!string.IsNullOrWhiteSpace(output))
API.sendChatMessageToPlayer(sender, "~b~>> ~w~" + output);
}
}
else if (animation == "stop")
{
API.stopPlayerAnimation(sender);
}
else if (!AnimationList.ContainsKey(animation))
{
API.sendChatMessageToPlayer(sender, "~r~ERROR: ~w~Animation not found!");
}
else
{
var flag = 0;
if (animation == "handsup") flag = 1;
API.playPlayerAnimation(sender, flag, AnimationList[animation].Split()[0], AnimationList[animation].Split()[1]);
}
}
private Client getVehicleOwner(NetHandle vehicle)
{
foreach (var client in VehicleHistory.Keys)
{
foreach (var v in VehicleHistory[client])
{
if (v.Value == vehicle.Value)
return client;
}
}
return null;
}
private string getRandomNumberPlate(Client client = null)
{
if (client != null)
{
string strClientName = client.name;
if (strClientName.Length <= 8)
return strClientName.ToUpper();
}
string strCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
string strRet = "";
for (int i = 0; i < 8; i++)
{
strRet += strCharacters[Rnd.Next(strCharacters.Length)];
}
return strRet;
}
[Command("car", Alias = "v")]
public void SpawnCarCommand(Client sender, VehicleHash model)
{
if (BannedVehicles.Contains(model))
{
sender.sendChatMessage("The vehicle ~r~" + model.ToString() + "~s~ is ~r~banned~s~!");
return;
}
if (sender.vehicle != null && sender.vehicleSeat == -1)
{
NetHandle hv = sender.vehicle.handle;
var owner = getVehicleOwner(hv);
if (owner != null && VehicleHistory.ContainsKey(owner))
{
VehicleHistory[owner].Remove(hv);
}
sender.vehicle.delete();
}
var veh = API.createVehicle(model, sender.position, new Vector3(0, 0, sender.rotation.Z), 0, 0);
veh.primaryColor = Rnd.Next(158);
veh.secondaryColor = Rnd.Next(158);
veh.numberPlate = getRandomNumberPlate(sender);
veh.numberPlateStyle = Rnd.Next(6);
if (VehicleHistory.ContainsKey(sender))
{
VehicleHistory[sender].Add(veh);
if (VehicleHistory[sender].Count > 3)
{
API.deleteEntity(VehicleHistory[sender][0]);
VehicleHistory[sender].RemoveAt(0);
}
}
else
{
VehicleHistory.Add(sender, new List<NetHandle> { veh });
}
API.setPlayerIntoVehicle(sender, veh, -1);
}
[Command("repair", Alias = "r")]
public void RepairCarCommand(Client sender)
{
var veh = sender.vehicle;
if (veh == null)
return;
veh.repair();
}
[Command("clearvehicles", Alias = "vc")]
public void ClearVehiclesCommand(Client sender)
{
if (!VehicleHistory.ContainsKey(sender))
return;
foreach (var veh in VehicleHistory[sender])
API.deleteEntity(veh);
VehicleHistory[sender].Clear();
}
[Command("skin")]
public void ChangeSkinCommand(Client sender, PedHash model)
{
API.setPlayerSkin(sender, model);
API.sendNativeToPlayer(sender, Hash.SET_PED_DEFAULT_COMPONENT_VARIATION, sender.handle);
}
[Command("pic")]
public void SpawnPickupCommand(Client sender, PickupHash pickup)
{
API.createPickup(pickup, new Vector3(sender.position.X + 10, sender.position.Y, sender.position.Z), new Vector3(), 100, 0);
}
[Command("countdown")]
public void StartGlobalCountdownCommand(Client sender)
{
API.triggerClientEventForAll("startCountdown");
}
[Command("tp")]
public void TeleportPlayerToPlayerCommand(Client sender, Client target)
{
var pos = API.getEntityPosition(sender.handle);
API.createParticleEffectOnPosition("scr_rcbarry1", "scr_alien_teleport", pos, new Vector3(), 1f);
API.setEntityPosition(sender.handle, API.getEntityPosition(target.handle));
}
[Command("weapon", Alias = "w,gun")]
public void GiveWeaponCommand(Client sender, WeaponHash weapon)
{
API.givePlayerWeapon(sender, weapon, 9999, true);
}
[Command("weaponcomponent", Alias = "wcomp,wc")]
public void GiveWeaponComponentCmd(Client sender, WeaponComponent component)
{
API.givePlayerWeaponComponent(sender, API.getPlayerCurrentWeapon(sender), component);
}
[Command("weapontint", Alias = "wtint")]
public void SetWeaponTintCmd(Client sender, WeaponTint tint)
{
API.setPlayerWeaponTint(sender, API.getPlayerCurrentWeapon(sender), tint);
}
}
| |
// 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 log4net.Appender;
namespace Alachisoft.NCache.Common.Util
{
public static class NCacheLog
{
public const int bufferDefaultSize = 1;
static DateTime _timeFired = DateTime.Now;
static object syncLock = new object();
static private string s_config = "";
private const string DIRNAME = @"bin\service";
static NCacheLog()
{
#if !NETCORE && !NETCOREAPP2_0
string serverconfig ="Alachisoft.NCache.Service.exe.config";
#else
string serverconfig = "Alachisoft.NCache.Daemon.dll.config";
#endif
}
public static void SetLevel(string cacheName, Level level)
{
if (cacheName == null || cacheName == string.Empty)
{
NCacheLog.LogLoggingError("Cache Name is null");
return;
}
string loggerName = LoggingInformation.GetLoggerName(cacheName);
if (loggerName != null && loggerName.Length > 0)
{
lock (NCacheLog.syncLock)
{
log4net.Core.Level lvl;
switch (level.ToString().ToLower())
{
case "all":
lvl = log4net.Core.Level.All;
break;
case "error":
lvl = log4net.Core.Level.Error;
break;
case "fatal":
lvl = log4net.Core.Level.Fatal;
break;
case "info":
lvl = log4net.Core.Level.Info;
break;
case "debug":
lvl = log4net.Core.Level.Debug;
break;
case "warn":
lvl = log4net.Core.Level.Warn;
break;
case "off":
lvl = log4net.Core.Level.Off;
break;
default:
lvl = log4net.Core.Level.All;
break;
}
//If the logger doesnot exist it will create one else fetches one
log4net.ILog log = log4net.LogManager.GetLogger(Log4net.LogRepository.Name, loggerName);
//adds the logger as a seperate hierchy, not dependant on any other logger
log4net.Repository.Hierarchy.Logger l = (log4net.Repository.Hierarchy.Logger)log.Logger;
//Applies the logger threshold level
l.Level = l.Hierarchy.LevelMap[level.ToString()];
IAppender[] appenderCol = log.Logger.Repository.GetAppenders();
for (int i = 0; i < appenderCol.Length; i++)
{
IAppender appender = appenderCol[i];
if (appender != null)
{
if (appender is BufferingForwardingAppender)
{
((BufferingForwardingAppender)appender).Threshold = lvl;
}
if (appender is RollingFileAppender)
{
((RollingFileAppender)appender).Threshold = lvl;
}
}
}
}
}
}
static void SetBufferSize(int bufferSize)
{
lock (NCacheLog.syncLock)
{
#if !NETCORE
foreach (log4net.Appender.IAppender appender in log4net.LogManager.GetRepository().GetAppenders())
#elif NETCORE
//TODO: ALACHISOFT (Adding Repository directly here for now)
foreach (log4net.Appender.IAppender appender in log4net.LogManager.GetRepository(Log4net.LogRepository.Name).GetAppenders())
#endif
{
BufferingAppenderSkeleton buffered = appender as BufferingAppenderSkeleton;
if (buffered is BufferingForwardingAppender)
{
buffered.BufferSize = bufferSize;
buffered.ActivateOptions();
}
}
}
}
#region Main Loggers
public static void Error(string cacheName, string message)
{
if (cacheName == null || cacheName == string.Empty)
{
NCacheLog.LogLoggingError("Cache Name is null");
return;
}
string loggerName = LoggingInformation.GetLoggerName(cacheName);
if (loggerName != null && loggerName.Length > 0)
{
log4net.ILog log = log4net.LogManager.GetLogger(Log4net.LogRepository.Name, loggerName);
if (message.Contains(Environment.NewLine))
message = message + "\r\n";
log.Error(message);
}
else
{
NCacheLog.LogLoggingError("loggerName != null && loggerName.Length > 0");
}
}
public static void Fatal(string cacheName, string message)
{
if (cacheName == null || cacheName == string.Empty)
{
NCacheLog.LogLoggingError("Cache Name is null");
return;
}
string loggerName = LoggingInformation.GetLoggerName(cacheName);
if (loggerName != null && loggerName.Length > 0)
{
log4net.ILog log = log4net.LogManager.GetLogger(Log4net.LogRepository.Name, loggerName);
if (message.Contains(Environment.NewLine))
message = message + "\r\n";
log.Fatal(message);
}
else
{
NCacheLog.LogLoggingError("loggerName != null && loggerName.Length > 0");
}
}
public static void CriticalInfo(string cacheName, string message)
{
if (cacheName == null || cacheName == string.Empty)
{
NCacheLog.LogLoggingError("Cache Name is null");
return;
}
string loggerName = LoggingInformation.GetLoggerName(cacheName);
if (loggerName != null && loggerName.Length > 0)
{
log4net.ILog log = log4net.LogManager.GetLogger(Log4net.LogRepository.Name, loggerName);
if (message.Contains(Environment.NewLine))
message = message + "\r\n";
log.Logger.Log(null, Log4net.criticalInfo, message, null);
}
else
{
NCacheLog.LogLoggingError("loggerName != null && loggerName.Length > 0");
}
}
public static void Info(string cacheName, string message)
{
if (cacheName == null || cacheName == string.Empty)
{
NCacheLog.LogLoggingError("Cache Name is null");
return;
}
string loggerName = LoggingInformation.GetLoggerName(cacheName);
if (loggerName != null && loggerName.Length > 0)
{
log4net.ILog log = log4net.LogManager.GetLogger(Log4net.LogRepository.Name, loggerName);
if (message.Contains(Environment.NewLine))
message = message + "\r\n";
log.Info(message);
}
else
{
NCacheLog.LogLoggingError("loggerName != null && loggerName.Length > 0");
}
}
public static void Debug(string cacheName, string message)
{
if (cacheName == null || cacheName == string.Empty)
{
NCacheLog.LogLoggingError("Cache Name is null");
return;
}
string loggerName = LoggingInformation.GetLoggerName(cacheName);
if (loggerName != null && loggerName.Length > 0)
{
log4net.ILog log = log4net.LogManager.GetLogger(Log4net.LogRepository.Name, loggerName);
if (message.Contains(Environment.NewLine))
message = message + "\r\n";
log.Debug(message);
}
else
{
NCacheLog.LogLoggingError("loggerName != null && loggerName.Length > 0");
}
}
public static void Warn(string cacheName, string message)
{
if (cacheName == null || cacheName == string.Empty)
{
NCacheLog.LogLoggingError("Cache Name is null");
return;
}
string loggerName = LoggingInformation.GetLoggerName(cacheName);
if (loggerName != null && loggerName.Length > 0)
{
log4net.ILog log = log4net.LogManager.GetLogger(Log4net.LogRepository.Name, loggerName);
if (message.Contains(Environment.NewLine))
message = message + "\r\n";
log.Warn(message);
}
else
{
NCacheLog.LogLoggingError("loggerName != null && loggerName.Length > 0");
}
}
#endregion
#region IfEnabled
public static bool IsInfoEnabled(string cacheName)
{
#region isEnalbedLogic
if (cacheName == null || cacheName == string.Empty)
{
NCacheLog.LogLoggingError("Cache Name is null");
return false;
}
string loggerName = LoggingInformation.GetLoggerName(cacheName);
if (loggerName != null && loggerName.Length > 0)
{
log4net.ILog log = log4net.LogManager.GetLogger(Log4net.LogRepository.Name, loggerName);
return log.IsInfoEnabled;
}
else
{
NCacheLog.LogLoggingError("loggerName != null && loggerName.Length > 0");
}
return false;
#endregion
return true;
}
public static bool IsErrorEnabled(string cacheName)
{
#region isEnabledLogic
#endregion
return true;
}
public static bool IsWarnEnabled(string cacheName)
{
#region isEnabledLogic
if (cacheName == null || cacheName == string.Empty)
{
NCacheLog.LogLoggingError("Cache Name is null");
return false;
}
string loggerName = LoggingInformation.GetLoggerName(cacheName);
if (loggerName != null && loggerName.Length > 0)
{
log4net.ILog log = log4net.LogManager.GetLogger(Log4net.LogRepository.Name, loggerName);
return log.IsInfoEnabled;
}
else
{
NCacheLog.LogLoggingError("loggerName != null && loggerName.Length > 0");
}
return false;
#endregion
return true;
}
public static bool IsDebugEnabled(string cacheName)
{
#region isEnabledLogic
if (cacheName == null || cacheName == string.Empty)
{
NCacheLog.LogLoggingError("Cache Name is null");
return false;
}
string loggerName = LoggingInformation.GetLoggerName(cacheName);
if (loggerName != null && loggerName.Length > 0)
{
log4net.ILog log = log4net.LogManager.GetLogger(Log4net.LogRepository.Name, loggerName);
return log.IsInfoEnabled;
}
else
{
NCacheLog.LogLoggingError("loggerName != null && loggerName.Length > 0");
}
return false;
#endregion
return true;
}
public static bool IsFatalEnabled(string cacheName)
{
#region isEnabledLogic
#endregion
return true;
}
#endregion
#region Enum Overloads
public static void SetLevel(LoggerNames loggerEnum, Level level)
{
string loggerName = LoggingInformation.GetLoggerName(LoggingInformation.GetStaticLoggerName(loggerEnum.ToString()));
if (loggerName != null && loggerName.Length > 0)
{
lock (NCacheLog.syncLock)
{
log4net.Core.Level lvl;
switch (level.ToString().ToLower())
{
case "all":
lvl = log4net.Core.Level.All;
break;
case "error":
lvl = log4net.Core.Level.Error;
break;
case "fatal":
lvl = log4net.Core.Level.Fatal;
break;
case "info":
lvl = log4net.Core.Level.Info;
break;
case "debug":
lvl = log4net.Core.Level.Debug;
break;
case "warn":
lvl = log4net.Core.Level.Warn;
break;
case "off":
lvl = log4net.Core.Level.Off;
break;
default:
lvl = log4net.Core.Level.All;
break;
}
//If the logger doesnot exist it will create one else fetches one
log4net.ILog log = log4net.LogManager.GetLogger(Log4net.LogRepository.Name, loggerName);
//adds the logger as a seperate hierchy, not dependant on any other logger
log4net.Repository.Hierarchy.Logger l = (log4net.Repository.Hierarchy.Logger)log.Logger;
//Applies the logger threshold level
l.Level = l.Hierarchy.LevelMap[level.ToString()];
IAppender[] appenderCol = log.Logger.Repository.GetAppenders();
for (int i = 0; i < appenderCol.Length; i++)
{
IAppender appender = appenderCol[i];
if (appender != null)
{
if (appender is BufferingForwardingAppender)
{
((BufferingForwardingAppender)appender).Threshold = lvl;
}
if (appender is RollingFileAppender)
{
((RollingFileAppender)appender).Threshold = lvl;
}
}
}
}
}
else
{
NCacheLog.LogLoggingError("loggerName != null && loggerName.Length > 0");
}
}
#region Enabled Enum Methods
public static bool IsInfoEnabled(NCacheLog.LoggerNames loggerEnum)
{
#region isEnabledLogic
string temp = LoggingInformation.GetStaticLoggerName(loggerEnum.ToString());
if (temp != null && temp.Length > 0)
{
string loggerName = LoggingInformation.GetLoggerName(temp);
if (loggerName != null && loggerName.Length > 0)
{
log4net.ILog log = log4net.LogManager.GetLogger(Log4net.LogRepository.Name, loggerName);
return log.IsInfoEnabled;
}
else
{
NCacheLog.LogLoggingError("loggerName != null && loggerName.Length > 0");
}
}
return false;
#endregion
}
public static bool IsErrorEnabled(NCacheLog.LoggerNames loggerEnum)
{
#region isEnabledLogic
#endregion
return true;
}
public static bool IsWarnEnabled(NCacheLog.LoggerNames loggerEnum)
{
#region isEnabledLogic
#endregion
return true;
}
public static bool IsDebugEnabled(NCacheLog.LoggerNames loggerEnum)
{
#region isEnabledLogic
string temp = LoggingInformation.GetStaticLoggerName(loggerEnum.ToString());
if (temp != null && temp.Length > 0)
{
string loggerName = LoggingInformation.GetLoggerName(temp);
if (loggerName != null && loggerName.Length > 0)
{
log4net.ILog log = log4net.LogManager.GetLogger(Log4net.LogRepository.Name, loggerName);
return log.IsDebugEnabled;
}
else
{
NCacheLog.LogLoggingError("loggerName != null && loggerName.Length > 0");
}
}
return false;
#endregion
}
public static bool IsFatalEnabled(NCacheLog.LoggerNames loggerEnum)
{
#region isEnabledLogic
#endregion
return true;
}
#endregion
public static void Error(NCacheLog.LoggerNames loggerName, string message)
{
string name = loggerName.ToString();
if (loggerName != LoggerNames.ClientLogs)
name = LoggingInformation.GetStaticLoggerName(loggerName.ToString());
Error(name, message);
}
public static void Fatal(NCacheLog.LoggerNames loggerName, string message)
{
string name = loggerName.ToString(); ;
if (loggerName != LoggerNames.ClientLogs)
name = LoggingInformation.GetStaticLoggerName(loggerName.ToString());
Fatal(name, message);
}
public static void CriticalInfo(NCacheLog.LoggerNames loggerName, string message)
{
string name = loggerName.ToString(); ;
if (loggerName != LoggerNames.ClientLogs)
name = LoggingInformation.GetStaticLoggerName(loggerName.ToString());
CriticalInfo(name, message);
}
public static void Info(NCacheLog.LoggerNames loggerName, string message)
{
string name = loggerName.ToString(); ;
if (loggerName != LoggerNames.ClientLogs)
name = LoggingInformation.GetStaticLoggerName(loggerName.ToString());
Info(name, message);
}
public static void Debug(NCacheLog.LoggerNames loggerName, string message)
{
string name = loggerName.ToString(); ;
if (loggerName != LoggerNames.ClientLogs)
name = LoggingInformation.GetStaticLoggerName(loggerName.ToString());
Debug(name, message);
}
public static void Warn(NCacheLog.LoggerNames loggerName, string message)
{
string name = loggerName.ToString(); ;
if (loggerName != LoggerNames.ClientLogs)
name = LoggingInformation.GetStaticLoggerName(loggerName.ToString());
Warn(name, message);
}
//------------------------------------------------------------------------------------------------
public static void Error(NCacheLog.LoggerNames loggerName, String module, String message)
{
string name = loggerName.ToString(); ;
if (loggerName != LoggerNames.ClientLogs)
name = LoggingInformation.GetStaticLoggerName(loggerName.ToString());
Error(name, module, message);
}
public static void Fatal(NCacheLog.LoggerNames loggerName, String module, String message)
{
string name = loggerName.ToString(); ;
if (loggerName != LoggerNames.ClientLogs)
name = LoggingInformation.GetStaticLoggerName(loggerName.ToString());
Fatal(name, module, message);
}
public static void CriticalInfo(NCacheLog.LoggerNames loggerName, String module, String message)
{
string name = loggerName.ToString(); ;
if (loggerName != LoggerNames.ClientLogs)
name = LoggingInformation.GetStaticLoggerName(loggerName.ToString());
CriticalInfo(name, module, message);
}
public static void Info(NCacheLog.LoggerNames loggerName, String module, String message)
{
string name = loggerName.ToString(); ;
if (loggerName != LoggerNames.ClientLogs)
name = LoggingInformation.GetStaticLoggerName(loggerName.ToString());
Info(name, module, message);
}
public static void Debug(NCacheLog.LoggerNames loggerName, String module, String message)
{
string name = loggerName.ToString(); ;
if (loggerName != LoggerNames.ClientLogs)
name = LoggingInformation.GetStaticLoggerName(loggerName.ToString());
Debug(name, module, message);
}
public static void Warn(NCacheLog.LoggerNames loggerName, String module, String message)
{
string name = loggerName.ToString(); ;
if (loggerName != LoggerNames.ClientLogs)
name = LoggingInformation.GetStaticLoggerName(loggerName.ToString());
Warn(name, module, message);
}
#endregion
#region Overloaded Logging Methods
public static void Error(string cacheName, String module, String message)
{
int space1 = 8;
int space2 = 40;
if (module.Length == 0)
space2 = 4;
string line = null;
line = module.PadRight(space2, ' ') + message;
Error(cacheName, line);
}
public static void Fatal(string cacheName, String module, String message)
{
int space1 = 8;
int space2 = 40;
if (module.Length == 0)
space2 = 4;
string line = null;
line = module.PadRight(space2, ' ') + message;
Fatal(cacheName, line);
}
public static void CriticalInfo(string cacheName, String module, String message)
{
int space1 = 8;
int space2 = 40;
if (module.Length == 0)
space2 = 4;
string line = null;
line = module.PadRight(space2, ' ') + message;
CriticalInfo(cacheName, line);
}
public static void Info(string cacheName, String module, String message)
{
int space1 = 8;
int space2 = 40;
if (module.Length == 0)
space2 = 4;
string line = null;
line = module.PadRight(space2, ' ') + message;
Info(cacheName, line);
}
public static void Debug(string cacheName, String module, String message)
{
int space1 = 8;
int space2 = 40;
if (module.Length == 0)
space2 = 4;
string line = null;
line = module.PadRight(space2, ' ') + message;
Debug(cacheName, line);
}
public static void Warn(string cacheName, String module, String message)
{
int space1 = 8;
int space2 = 40;
if (module.Length == 0)
space2 = 4;
string line = null;
line = module.PadRight(space2, ' ') + message;
Warn(cacheName, line);
}
#endregion
public enum Level
{
ERROR,
INFO,
WARNING,
DEBUG,
ALL,
OFF
}
public enum LoggerNames
{
OutputCache,
HttpModule,
SessionStoreProvider,
Licence,
SocketServerLogs,
ClientLogs
}
public static void OnChange()
{
bool[] logLevel = new bool[2];
int bufferSize = bufferDefaultSize;
lock (syncLock)
{
if (_timeFired != null)
{
if (DateTime.Now.Subtract(_timeFired).TotalMilliseconds < 50) return;
}
_timeFired = DateTime.Now;
System.Configuration.ConfigurationManager.RefreshSection("appSettings");
logLevel = ReadConfig(out bufferSize);
}
string loggerName = LoggingInformation.GetStaticLoggerName(LoggerNames.SocketServerLogs.ToString());
if (loggerName != null)
{
log4net.ILog log = log4net.LogManager.GetLogger(Log4net.LogRepository.Name, loggerName);
log4net.Repository.Hierarchy.Logger l = (log4net.Repository.Hierarchy.Logger)log.Logger;
BufferingAppenderSkeleton buffered = (BufferingAppenderSkeleton)l.GetAppender("BufferingForwardingAppender" + loggerName);
if (buffered is BufferingForwardingAppender)
{
((BufferingForwardingAppender)buffered).Flush();
}
}
//if not already initialized
Log4net.Initialize(LoggerNames.SocketServerLogs);
NCacheLog.SetLevel(LoggerNames.SocketServerLogs.ToString(), logLevel[1] == true ? NCacheLog.Level.ALL : logLevel[0] == true ? NCacheLog.Level.INFO : NCacheLog.Level.OFF);
if (bufferSize < 1)
bufferSize = bufferDefaultSize;
NCacheLog.SetBufferSize(bufferSize);
}
public static bool[] ReadConfig(out int bufferAppender)
{
try
{
string EnableLogs = System.Configuration.ConfigurationManager.AppSettings["EnableLogs"];
string EnableDetailedLogs = System.Configuration.ConfigurationManager.AppSettings["EnableDetailedLogs"];
string BufferSize = System.Configuration.ConfigurationManager.AppSettings["BufferSize"];
try
{
if (BufferSize != null)
{
bufferAppender = Convert.ToInt32(BufferSize);
}
else
bufferAppender = bufferDefaultSize;
}
catch (Exception)
{
bufferAppender = bufferDefaultSize;
}
if (EnableDetailedLogs == null && EnableLogs == null)
{
return new bool[2] { false, false };
}
else if (EnableDetailedLogs != null && EnableLogs == null)
{
return new bool[2] { false, Convert.ToBoolean(EnableDetailedLogs) };
}
else if (EnableDetailedLogs == null && EnableLogs != null)
{
return new bool[2] { Convert.ToBoolean(EnableLogs), false };
}
else
{
return new bool[2] { Convert.ToBoolean(EnableLogs), Convert.ToBoolean(EnableDetailedLogs) };
}
}
catch (Exception ex)
{
bufferAppender = bufferDefaultSize;
return new bool[2] { false, false };
NCacheLog.LogLoggingError(ex.Message);
}
}
public static void OnClientChange(object _o, FileSystemEventArgs _a)
{
bool[] logLevel = new bool[2];
int bufferSize = bufferDefaultSize;
lock (syncLock)
{
if (_timeFired != null)
{
if (DateTime.Now.Subtract(_timeFired).TotalMilliseconds < 50) return;
}
_timeFired = DateTime.Now;
System.Configuration.ConfigurationManager.RefreshSection("appSettings");
logLevel = ReadClientConfig(out bufferSize);
}
//if not already initialized
foreach (string loggerName in LoggingInformation.cacheLogger.Values)
{
NCacheLog.SetLevel(loggerName, logLevel[1] == true ? NCacheLog.Level.ALL : logLevel[0] == true ? NCacheLog.Level.INFO : NCacheLog.Level.OFF);
}
if (bufferSize < 1)
bufferSize = bufferDefaultSize;
NCacheLog.SetBufferSize(bufferSize);
}
public static bool[] ReadClientConfig(out int bufferAppender)
{
try
{
string EnableLogs = System.Configuration.ConfigurationManager.AppSettings["EnableNCWebLogs"];
string EnableDetailedLogs = System.Configuration.ConfigurationManager.AppSettings["EnableDetailedNCWebLogs"];
string BufferSize = System.Configuration.ConfigurationManager.AppSettings["BufferSize"];
try
{
if (BufferSize != null)
{
bufferAppender = Convert.ToInt32(BufferSize);
}
else
bufferAppender = bufferDefaultSize;
}
catch (Exception)
{
bufferAppender = bufferDefaultSize;
}
if (EnableDetailedLogs == null && EnableLogs == null)
{
return new bool[2] { false, false };
}
else if (EnableDetailedLogs != null && EnableLogs == null)
{
return new bool[2] { false, Convert.ToBoolean(EnableDetailedLogs) };
}
else if (EnableDetailedLogs == null && EnableLogs != null)
{
return new bool[2] { Convert.ToBoolean(EnableLogs), false };
}
else
{
return new bool[2] { Convert.ToBoolean(EnableLogs), Convert.ToBoolean(EnableDetailedLogs) };
}
}
catch (Exception ex)
{
bufferAppender = bufferDefaultSize;
return new bool[2] { false, false };
NCacheLog.LogLoggingError(ex.Message);
}
}
#region IDisposable Members
public static void Flush()
{
//bug id- 1431 Problem was occuring because the Appender enumeration was modifying during iterations
#if !NETCORE
IAppender[] logAppenders = log4net.LogManager.GetRepository().GetAppenders();
#elif NETCORE
//TODO: ALACHISOFT (Direct edit to code for now. It should be removed later on)
IAppender[] logAppenders = log4net.LogManager.GetRepository(Log4net.LogRepository.Name).GetAppenders();
#endif
foreach (log4net.Appender.IAppender appender in logAppenders)
{
if (appender != null)
{
BufferingAppenderSkeleton buffered = appender as BufferingAppenderSkeleton;
if (buffered is BufferingForwardingAppender)
{
((BufferingForwardingAppender)buffered).Flush();
}
}
}
}
#endregion
public static void LogLoggingError(string msg)
{
}
}
}
| |
namespace ZetaHtmlEditControl.Code.PInvoke
{
using System;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Security;
public sealed class UnsafeNativeMethods
{
[DllImport( @"user32.dll", CharSet = CharSet.Auto, ExactSpelling = true )]
public static extern int MapWindowPoints( HandleRef hWndFrom, HandleRef hWndTo, [In, Out] NativeMethods.POINT pt, int cPoints );
[ComImport, InterfaceType( ComInterfaceType.InterfaceIsIUnknown ),
Guid( @"3050f3f0-98b5-11cf-bb82-00aa00bdce0b" )]
internal interface ICustomDoc
{
[PreserveSig]
void SetUIHandler( IDocHostUIHandler pUIHandler );
}
[ComImport, Guid( @"BD3F23C0-D43E-11CF-893B-00AA00BDCE1A" ), ComVisible( true ), InterfaceType( ComInterfaceType.InterfaceIsIUnknown )]
public interface IDocHostUIHandler
{
[return: MarshalAs( UnmanagedType.I4 )]
[PreserveSig]
int ShowContextMenu( [In, MarshalAs( UnmanagedType.U4 )] int dwID, [In] NativeMethods.POINT pt, [In, MarshalAs( UnmanagedType.Interface )] object pcmdtReserved, [In, MarshalAs( UnmanagedType.Interface )] object pdispReserved );
[return: MarshalAs( UnmanagedType.I4 )]
[PreserveSig]
int GetHostInfo( [In, Out] NativeMethods.DOCHOSTUIINFO info );
[return: MarshalAs( UnmanagedType.I4 )]
[PreserveSig]
int ShowUI( [In, MarshalAs( UnmanagedType.I4 )] int dwID, [In] IOleInPlaceActiveObject activeObject, [In] NativeMethods.IOleCommandTarget commandTarget, [In] IOleInPlaceFrame frame, [In] IOleInPlaceUIWindow doc );
[return: MarshalAs( UnmanagedType.I4 )]
[PreserveSig]
int HideUI();
[return: MarshalAs( UnmanagedType.I4 )]
[PreserveSig]
int UpdateUI();
[return: MarshalAs( UnmanagedType.I4 )]
[PreserveSig]
int EnableModeless( [In, MarshalAs( UnmanagedType.Bool )] bool fEnable );
[return: MarshalAs( UnmanagedType.I4 )]
[PreserveSig]
int OnDocWindowActivate( [In, MarshalAs( UnmanagedType.Bool )] bool fActivate );
[return: MarshalAs( UnmanagedType.I4 )]
[PreserveSig]
int OnFrameWindowActivate( [In, MarshalAs( UnmanagedType.Bool )] bool fActivate );
[return: MarshalAs( UnmanagedType.I4 )]
[PreserveSig]
int ResizeBorder( [In] NativeMethods.COMRECT rect, [In] IOleInPlaceUIWindow doc, bool fFrameWindow );
[return: MarshalAs( UnmanagedType.I4 )]
[PreserveSig]
int TranslateAccelerator( [In] ref NativeMethods.MSG msg, [In] ref Guid group, [In, MarshalAs( UnmanagedType.I4 )] int nCmdID );
[return: MarshalAs( UnmanagedType.I4 )]
[PreserveSig]
int GetOptionKeyPath( [Out, MarshalAs( UnmanagedType.LPArray )] string[] pbstrKey, [In, MarshalAs( UnmanagedType.U4 )] int dw );
[return: MarshalAs( UnmanagedType.I4 )]
[PreserveSig]
int GetDropTarget( [In, MarshalAs( UnmanagedType.Interface )] IOleDropTarget pDropTarget, [MarshalAs( UnmanagedType.Interface )] out IOleDropTarget ppDropTarget );
[return: MarshalAs( UnmanagedType.I4 )]
[PreserveSig]
int GetExternal( [MarshalAs( UnmanagedType.Interface )] out object ppDispatch );
[return: MarshalAs( UnmanagedType.I4 )]
[PreserveSig]
int TranslateUrl( [In, MarshalAs( UnmanagedType.U4 )] int dwTranslate, [In, MarshalAs( UnmanagedType.LPWStr )] string strURLIn, [MarshalAs( UnmanagedType.LPWStr )] out string pstrURLOut );
[return: MarshalAs( UnmanagedType.I4 )]
[PreserveSig]
int FilterDataObject( IDataObject pDO, out IDataObject ppDORet );
}
[ComImport, ComVisible(true)]
[Guid(@"00000118-0000-0000-C000-000000000046")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IOleClientSite
{
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int SaveObject();
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int GetMoniker(
[In, MarshalAs(UnmanagedType.U4)] uint dwAssign,
[In, MarshalAs(UnmanagedType.U4)] uint dwWhichMoniker,
[Out, MarshalAs(UnmanagedType.Interface)] out IMoniker ppmk);
//[return: MarshalAs(UnmanagedType.I4)]
//[PreserveSig]
//int GetContainer(
// [Out, MarshalAs(UnmanagedType.Interface)] out IOleContainer ppContainer);
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int ShowObject();
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int OnShowWindow([In, MarshalAs(UnmanagedType.Bool)] bool fShow);
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int RequestNewObjectLayout();
}
/* [Serializable]
public enum UnmanagedType
{
// Fields
AnsiBStr = 0x23,
AsAny = 40,
Bool = 2,
BStr = 0x13,
ByValArray = 30,
ByValTStr = 0x17,
Currency = 15,
CustomMarshaler = 0x2c,
Error = 0x2d,
FunctionPtr = 0x26,
I1 = 3,
I2 = 5,
I4 = 7,
I8 = 9,
IDispatch = 0x1a,
Interface = 0x1c,
IUnknown = 0x19,
LPArray = 0x2a,
LPStr = 20,
LPStruct = 0x2b,
LPTStr = 0x16,
LPWStr = 0x15,
R4 = 11,
R8 = 12,
SafeArray = 0x1d,
Struct = 0x1b,
SysInt = 0x1f,
SysUInt = 0x20,
TBStr = 0x24,
U1 = 4,
U2 = 6,
U4 = 8,
U8 = 10,
VariantBool = 0x25,
VBByRefStr = 0x22
}
*/
[ComImport, Guid( @"00000122-0000-0000-C000-000000000046" ), InterfaceType( ComInterfaceType.InterfaceIsIUnknown )]
public interface IOleDropTarget
{
[PreserveSig]
int OleDragEnter( [In, MarshalAs( UnmanagedType.Interface )] object pDataObj, [In, MarshalAs( UnmanagedType.U4 )] int grfKeyState, [In, MarshalAs( UnmanagedType.U8 )] long pt, [In, Out] ref int pdwEffect );
[PreserveSig]
int OleDragOver( [In, MarshalAs( UnmanagedType.U4 )] int grfKeyState, [In, MarshalAs( UnmanagedType.U8 )] long pt, [In, Out] ref int pdwEffect );
[PreserveSig]
int OleDragLeave();
[PreserveSig]
int OleDrop( [In, MarshalAs( UnmanagedType.Interface )] object pDataObj, [In, MarshalAs( UnmanagedType.U4 )] int grfKeyState, [In, MarshalAs( UnmanagedType.U8 )] long pt, [In, Out] ref int pdwEffect );
}
[ComImport, Guid( @"00000117-0000-0000-C000-000000000046" ), SuppressUnmanagedCodeSecurity, InterfaceType( ComInterfaceType.InterfaceIsIUnknown )]
public interface IOleInPlaceActiveObject
{
[PreserveSig]
int GetWindow( out IntPtr hwnd );
void ContextSensitiveHelp( int fEnterMode );
[PreserveSig]
int TranslateAccelerator( [In] ref NativeMethods.MSG lpmsg );
void OnFrameWindowActivate( bool fActivate );
void OnDocWindowActivate( int fActivate );
void ResizeBorder( [In] NativeMethods.COMRECT prcBorder, [In] IOleInPlaceUIWindow pUIWindow, bool fFrameWindow );
void EnableModeless( int fEnable );
}
[ComImport, Guid( @"00000116-0000-0000-C000-000000000046" ), InterfaceType( ComInterfaceType.InterfaceIsIUnknown )]
public interface IOleInPlaceFrame
{
IntPtr GetWindow();
[PreserveSig]
int ContextSensitiveHelp( int fEnterMode );
[PreserveSig]
int GetBorder( [Out] NativeMethods.COMRECT lprectBorder );
[PreserveSig]
int RequestBorderSpace( [In] NativeMethods.COMRECT pborderwidths );
[PreserveSig]
int SetBorderSpace( [In] NativeMethods.COMRECT pborderwidths );
[PreserveSig]
int SetActiveObject( [In, MarshalAs( UnmanagedType.Interface )] IOleInPlaceActiveObject pActiveObject, [In, MarshalAs( UnmanagedType.LPWStr )] string pszObjName );
[PreserveSig]
int InsertMenus( [In] IntPtr hmenuShared, [In, Out] NativeMethods.tagOleMenuGroupWidths lpMenuWidths );
[PreserveSig]
int SetMenu( [In] IntPtr hmenuShared, [In] IntPtr holemenu, [In] IntPtr hwndActiveObject );
[PreserveSig]
int RemoveMenus( [In] IntPtr hmenuShared );
[PreserveSig]
int SetStatusText( [In, MarshalAs( UnmanagedType.LPWStr )] string pszStatusText );
[PreserveSig]
int EnableModeless( bool fEnable );
[PreserveSig]
int TranslateAccelerator( [In] ref NativeMethods.MSG lpmsg, [In, MarshalAs( UnmanagedType.U2 )] short wID );
}
[ComImport, InterfaceType( ComInterfaceType.InterfaceIsIUnknown ), Guid( @"00000115-0000-0000-C000-000000000046" )]
public interface IOleInPlaceUIWindow
{
IntPtr GetWindow();
[PreserveSig]
int ContextSensitiveHelp( int fEnterMode );
[PreserveSig]
int GetBorder( [Out] NativeMethods.COMRECT lprectBorder );
[PreserveSig]
int RequestBorderSpace( [In] NativeMethods.COMRECT pborderwidths );
[PreserveSig]
int SetBorderSpace( [In] NativeMethods.COMRECT pborderwidths );
void SetActiveObject( [In, MarshalAs( UnmanagedType.Interface )] IOleInPlaceActiveObject pActiveObject, [In, MarshalAs( UnmanagedType.LPWStr )] string pszObjName );
}
[ComImport, ComVisible(true)]
[Guid(@"00000112-0000-0000-C000-000000000046")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IOleObject
{
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int SetClientSite(
[In, MarshalAs(UnmanagedType.Interface)] IOleClientSite pClientSite);
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int GetClientSite(
[Out, MarshalAs(UnmanagedType.Interface)] out IOleClientSite site);
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int SetHostNames(
[In, MarshalAs(UnmanagedType.LPWStr)] string szContainerApp,
[In, MarshalAs(UnmanagedType.LPWStr)] string szContainerObj);
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int Close([In, MarshalAs(UnmanagedType.U4)] uint dwSaveOption);
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int SetMoniker(
[In, MarshalAs(UnmanagedType.U4)] int dwWhichMoniker,
[In, MarshalAs(UnmanagedType.Interface)] IMoniker pmk);
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int GetMoniker(
[In, MarshalAs(UnmanagedType.U4)] uint dwAssign,
[In, MarshalAs(UnmanagedType.U4)] uint dwWhichMoniker,
[Out, MarshalAs(UnmanagedType.Interface)] out IMoniker moniker);
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int InitFromData(
[In, MarshalAs(UnmanagedType.Interface)] IDataObject pDataObject,
[In, MarshalAs(UnmanagedType.Bool)] bool fCreation,
[In, MarshalAs(UnmanagedType.U4)] uint dwReserved);
int GetClipboardData(
[In, MarshalAs(UnmanagedType.U4)] uint dwReserved,
[Out, MarshalAs(UnmanagedType.Interface)] out IDataObject data);
//[return: MarshalAs(UnmanagedType.I4)]
//[PreserveSig]
//int DoVerb(
// [In, MarshalAs(UnmanagedType.I4)] int iVerb,
// [In, MarshalAs(UnmanagedType.Struct)] ref tagMSG lpmsg,
// //or [In] IntPtr lpmsg,
// [In, MarshalAs(UnmanagedType.Interface)] IOleClientSite pActiveSite,
// [In, MarshalAs(UnmanagedType.I4)] int lindex,
// [In] IntPtr hwndParent,
// [In, MarshalAs(UnmanagedType.Struct)] ref tagRECT lprcPosRect);
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int EnumVerbs([Out, MarshalAs(UnmanagedType.Interface)] out Object e);
//int EnumVerbs(out IEnumOLEVERB e);
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int OleUpdate();
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int IsUpToDate();
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int GetUserClassID([In, Out] ref Guid pClsid);
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int GetUserType(
[In, MarshalAs(UnmanagedType.U4)] uint dwFormOfType,
[Out, MarshalAs(UnmanagedType.LPWStr)] out string userType);
//[return: MarshalAs(UnmanagedType.I4)]
//[PreserveSig]
//int SetExtent(
// [In, MarshalAs(UnmanagedType.U4)] uint dwDrawAspect,
// [In, MarshalAs(UnmanagedType.Struct)] ref tagSIZEL pSizel);
//[return: MarshalAs(UnmanagedType.I4)]
//[PreserveSig]
//int GetExtent(
// [In, MarshalAs(UnmanagedType.U4)] uint dwDrawAspect,
// [In, Out, MarshalAs(UnmanagedType.Struct)] ref tagSIZEL pSizel);
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int Advise(
[In, MarshalAs(UnmanagedType.Interface)] IAdviseSink pAdvSink,
out int cookie);
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int Unadvise(
[In, MarshalAs(UnmanagedType.U4)] uint dwConnection);
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int EnumAdvise(out IEnumSTATDATA e);
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int GetMiscStatus(
[In, MarshalAs(UnmanagedType.U4)] uint dwAspect,
out int misc);
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int SetColorScheme([In, MarshalAs(UnmanagedType.Struct)] ref object pLogpal);
}
[ComImport, ComVisible(true)]
[Guid(@"6d5140c1-7436-11ce-8034-00aa006009fa")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IServiceProvider
{
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int QueryService(
[In] ref Guid guidService,
[In] ref Guid riid,
[Out] out IntPtr ppvObject);
//This does not work i.e.-> ppvObject = (INewWindowManager)this
//[Out, MarshalAs(UnmanagedType.Interface)] out object ppvObject);
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Xml;
using log4net;
using Nini.Config;
using OpenSim.Framework;
namespace OpenSim
{
/// <summary>
/// Loads the Configuration files into nIni
/// </summary>
public class ConfigurationLoader
{
/// <summary>
/// Various Config settings the region needs to start
/// Physics Engine, Mesh Engine, GridMode, PhysicsPrim allowed, Neighbor,
/// StorageDLL, Storage Connection String, Estate connection String, Client Stack
/// Standalone settings.
/// </summary>
protected ConfigSettings m_configSettings;
/// <summary>
/// A source of Configuration data
/// </summary>
protected OpenSimConfigSource m_config;
/// <summary>
/// Grid Service Information. This refers to classes and addresses of the grid service
/// </summary>
protected NetworkServersInfo m_networkServersInfo;
/// <summary>
/// Console logger
/// </summary>
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
public ConfigurationLoader()
{
}
/// <summary>
/// Loads the region configuration
/// </summary>
/// <param name="argvSource">Parameters passed into the process when started</param>
/// <param name="configSettings"></param>
/// <param name="networkInfo"></param>
/// <returns>A configuration that gets passed to modules</returns>
public OpenSimConfigSource LoadConfigSettings(
IConfigSource argvSource, out ConfigSettings configSettings,
out NetworkServersInfo networkInfo)
{
m_configSettings = configSettings = new ConfigSettings();
m_networkServersInfo = networkInfo = new NetworkServersInfo();
bool iniFileExists = false;
IConfig startupConfig = argvSource.Configs["Startup"];
List<string> sources = new List<string>();
string masterFileName =
startupConfig.GetString("inimaster", String.Empty);
if (IsUri(masterFileName))
{
if (!sources.Contains(masterFileName))
sources.Add(masterFileName);
}
else
{
string masterFilePath = Path.GetFullPath(
Path.Combine(Util.configDir(), masterFileName));
if (masterFileName != String.Empty &&
File.Exists(masterFilePath) &&
(!sources.Contains(masterFilePath)))
sources.Add(masterFilePath);
}
string iniFileName =
startupConfig.GetString("inifile", "OpenSim.ini");
if (IsUri(iniFileName))
{
if (!sources.Contains(iniFileName))
sources.Add(iniFileName);
Application.iniFilePath = iniFileName;
}
else
{
Application.iniFilePath = Path.GetFullPath(
Path.Combine(Util.configDir(), iniFileName));
if (!File.Exists(Application.iniFilePath))
{
iniFileName = "OpenSim.xml";
Application.iniFilePath = Path.GetFullPath(
Path.Combine(Util.configDir(), iniFileName));
}
if (File.Exists(Application.iniFilePath))
{
if (!sources.Contains(Application.iniFilePath))
sources.Add(Application.iniFilePath);
}
}
string iniDirName =
startupConfig.GetString("inidirectory", "config");
string iniDirPath =
Path.Combine(Util.configDir(), iniDirName);
if (Directory.Exists(iniDirPath))
{
m_log.InfoFormat("Searching folder {0} for config ini files",
iniDirPath);
string[] fileEntries = Directory.GetFiles(iniDirName);
foreach (string filePath in fileEntries)
{
if (Path.GetExtension(filePath).ToLower() == ".ini")
{
if (!sources.Contains(Path.GetFullPath(filePath)))
sources.Add(Path.GetFullPath(filePath));
}
}
}
m_config = new OpenSimConfigSource();
m_config.Source = new IniConfigSource();
m_config.Source.Merge(DefaultConfig());
m_log.Info("[CONFIG]: Reading configuration settings");
if (sources.Count == 0)
{
m_log.FatalFormat("[CONFIG]: Could not load any configuration");
m_log.FatalFormat("[CONFIG]: Did you copy the OpenSim.ini.example file to OpenSim.ini?");
Environment.Exit(1);
}
for (int i = 0 ; i < sources.Count ; i++)
{
if (ReadConfig(sources[i]))
iniFileExists = true;
AddIncludes(sources);
}
if (!iniFileExists)
{
m_log.FatalFormat("[CONFIG]: Could not load any configuration");
m_log.FatalFormat("[CONFIG]: Configuration exists, but there was an error loading it!");
Environment.Exit(1);
}
// Make sure command line options take precedence
//
m_config.Source.Merge(argvSource);
ReadConfigSettings();
return m_config;
}
/// <summary>
/// Adds the included files as ini configuration files
/// </summary>
/// <param name="sources">List of URL strings or filename strings</param>
private void AddIncludes(List<string> sources)
{
//loop over config sources
foreach (IConfig config in m_config.Source.Configs)
{
// Look for Include-* in the key name
string[] keys = config.GetKeys();
foreach (string k in keys)
{
if (k.StartsWith("Include-"))
{
// read the config file to be included.
string file = config.GetString(k);
if (IsUri(file))
{
if (!sources.Contains(file))
sources.Add(file);
}
else
{
string basepath = Path.GetFullPath(Util.configDir());
string path = Path.Combine(basepath, file);
string[] paths = Util.Glob(path);
foreach (string p in paths)
{
if (!sources.Contains(p))
sources.Add(p);
}
}
}
}
}
}
/// <summary>
/// Check if we can convert the string to a URI
/// </summary>
/// <param name="file">String uri to the remote resource</param>
/// <returns>true if we can convert the string to a Uri object</returns>
bool IsUri(string file)
{
Uri configUri;
return Uri.TryCreate(file, UriKind.Absolute,
out configUri) && configUri.Scheme == Uri.UriSchemeHttp;
}
/// <summary>
/// Provide same ini loader functionality for standard ini and master ini - file system or XML over http
/// </summary>
/// <param name="iniPath">Full path to the ini</param>
/// <returns></returns>
private bool ReadConfig(string iniPath)
{
bool success = false;
if (!IsUri(iniPath))
{
m_log.InfoFormat("[CONFIG]: Reading configuration file {0}", Path.GetFullPath(iniPath));
m_config.Source.Merge(new IniConfigSource(iniPath));
success = true;
}
else
{
m_log.InfoFormat("[CONFIG]: {0} is a http:// URI, fetching ...", iniPath);
// The ini file path is a http URI
// Try to read it
try
{
XmlReader r = XmlReader.Create(iniPath);
XmlConfigSource cs = new XmlConfigSource(r);
m_config.Source.Merge(cs);
success = true;
}
catch (Exception e)
{
m_log.FatalFormat("[CONFIG]: Exception reading config from URI {0}\n" + e.ToString(), iniPath);
Environment.Exit(1);
}
}
return success;
}
/// <summary>
/// Setup a default config values in case they aren't present in the ini file
/// </summary>
/// <returns>A Configuration source containing the default configuration</returns>
private static IConfigSource DefaultConfig()
{
IConfigSource defaultConfig = new IniConfigSource();
{
IConfig config = defaultConfig.Configs["Startup"];
if (null == config)
config = defaultConfig.AddConfig("Startup");
config.Set("region_info_source", "filesystem");
config.Set("gridmode", false);
config.Set("physics", "OpenDynamicsEngine");
config.Set("meshing", "Meshmerizer");
config.Set("physical_prim", true);
config.Set("see_into_this_sim_from_neighbor", true);
config.Set("serverside_object_permissions", false);
config.Set("storage_plugin", "OpenSim.Data.SQLite.dll");
config.Set("storage_connection_string", "URI=file:OpenSim.db,version=3");
config.Set("storage_prim_inventories", true);
config.Set("startup_console_commands_file", String.Empty);
config.Set("shutdown_console_commands_file", String.Empty);
config.Set("DefaultScriptEngine", "XEngine");
config.Set("clientstack_plugin", "OpenSim.Region.ClientStack.LindenUDP.dll");
// life doesn't really work without this
config.Set("EventQueue", true);
}
{
IConfig config = defaultConfig.Configs["StandAlone"];
if (null == config)
config = defaultConfig.AddConfig("StandAlone");
config.Set("accounts_authenticate", true);
config.Set("welcome_message", "Welcome to OpenSimulator");
config.Set("inventory_plugin", "OpenSim.Data.SQLite.dll");
config.Set("inventory_source", "");
config.Set("userDatabase_plugin", "OpenSim.Data.SQLite.dll");
config.Set("user_source", "");
config.Set("LibrariesXMLFile", string.Format(".{0}inventory{0}Libraries.xml", Path.DirectorySeparatorChar));
}
{
IConfig config = defaultConfig.Configs["Network"];
if (null == config)
config = defaultConfig.AddConfig("Network");
config.Set("default_location_x", 1000);
config.Set("default_location_y", 1000);
config.Set("http_listener_port", ConfigSettings.DefaultRegionHttpPort);
config.Set("remoting_listener_port", ConfigSettings.DefaultRegionRemotingPort);
config.Set("grid_server_url", "http://127.0.0.1:" + ConfigSettings.DefaultGridServerHttpPort.ToString());
config.Set("grid_send_key", "null");
config.Set("grid_recv_key", "null");
config.Set("user_server_url", "http://127.0.0.1:" + ConfigSettings.DefaultUserServerHttpPort.ToString());
config.Set("user_send_key", "null");
config.Set("user_recv_key", "null");
config.Set("asset_server_url", "http://127.0.0.1:" + ConfigSettings.DefaultAssetServerHttpPort.ToString());
config.Set("inventory_server_url", "http://127.0.0.1:" + ConfigSettings.DefaultInventoryServerHttpPort.ToString());
config.Set("secure_inventory_server", "true");
}
return defaultConfig;
}
/// <summary>
/// Read initial region settings from the ConfigSource
/// </summary>
protected virtual void ReadConfigSettings()
{
IConfig startupConfig = m_config.Source.Configs["Startup"];
if (startupConfig != null)
{
m_configSettings.Standalone = !startupConfig.GetBoolean("gridmode", false);
m_configSettings.PhysicsEngine = startupConfig.GetString("physics");
m_configSettings.MeshEngineName = startupConfig.GetString("meshing");
m_configSettings.PhysicalPrim = startupConfig.GetBoolean("physical_prim", true);
m_configSettings.See_into_region_from_neighbor = startupConfig.GetBoolean("see_into_this_sim_from_neighbor", true);
m_configSettings.StorageDll = startupConfig.GetString("storage_plugin");
if (m_configSettings.StorageDll == "OpenSim.DataStore.MonoSqlite.dll")
{
m_configSettings.StorageDll = "OpenSim.Data.SQLite.dll";
m_log.Warn("WARNING: OpenSim.DataStore.MonoSqlite.dll is deprecated. Set storage_plugin to OpenSim.Data.SQLite.dll.");
Thread.Sleep(3000);
}
m_configSettings.StorageConnectionString
= startupConfig.GetString("storage_connection_string");
m_configSettings.EstateConnectionString
= startupConfig.GetString("estate_connection_string", m_configSettings.StorageConnectionString);
m_configSettings.ClientstackDll
= startupConfig.GetString("clientstack_plugin", "OpenSim.Region.ClientStack.LindenUDP.dll");
}
IConfig standaloneConfig = m_config.Source.Configs["StandAlone"];
if (standaloneConfig != null)
{
m_configSettings.StandaloneAuthenticate = standaloneConfig.GetBoolean("accounts_authenticate", true);
m_configSettings.StandaloneWelcomeMessage = standaloneConfig.GetString("welcome_message");
m_configSettings.StandaloneInventoryPlugin = standaloneConfig.GetString("inventory_plugin");
m_configSettings.StandaloneInventorySource = standaloneConfig.GetString("inventory_source");
m_configSettings.StandaloneUserPlugin = standaloneConfig.GetString("userDatabase_plugin");
m_configSettings.StandaloneUserSource = standaloneConfig.GetString("user_source");
m_configSettings.LibrariesXMLFile = standaloneConfig.GetString("LibrariesXMLFile");
}
m_networkServersInfo.loadFromConfiguration(m_config.Source);
}
}
}
| |
// Copyright (c) Microsoft Corporation
// 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
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
namespace Microsoft.WindowsAzure.Management.HDInsight.Tests.Scenario
{
using System;
using System.Collections.ObjectModel;
using System.Data.SqlClient;
using Microsoft.Hadoop.Hive;
using Microsoft.WindowsAzure.Management.Framework;
using Microsoft.WindowsAzure.Management.Framework.InversionOfControl;
using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.RestClient;
using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning.Client;
using Microsoft.WindowsAzure.Management.HDInsight.ClusterProvisioning;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.WindowsAzure.Management.HDInsight.TestUtilities;
using Microsoft.WindowsAzure.Management.HDInsight.TestUtilities.RestSimulator;
using Microsoft.WindowsAzure.Management.HDInsight.Tests.ConnectionCredentials;
using Microsoft.WindowsAzure.Management.HDInsight.Tests.RestSimulator;
[TestClass]
public class SyncClientScenarioTests : IntegrationTestBase
{
[TestInitialize]
public override void Initialize()
{
base.Initialize();
}
[TestCleanup]
public override void TestCleanup()
{
base.TestCleanup();
}
[TestMethod]
[TestCategory("CheckIn")]
[TestCategory("Scenario")]
[Timeout(30 * 1000)] // ms
public void CreateDeleteContainer_SyncClientWithTimeouts()
{
// Creates the client
IHDInsightCertificateConnectionCredentials credentials = IntegrationTestBase.GetValidCredentials();
var client = new HDInsightSyncClient(credentials.SubscriptionId, credentials.Certificate);
client.PollingInterval = TimeSpan.FromMilliseconds(100);
TestValidAdvancedCluster(
client.ListContainers,
client.ListContainer,
cluster => client.CreateContainer(cluster, TimeSpan.FromMinutes(25)),
dnsName => client.DeleteContainer(dnsName, TimeSpan.FromMinutes(5)));
}
[TestMethod]
[TestCategory("CheckIn")]
[TestCategory("Scenario")]
[Timeout(30 * 1000)] // ms
public void CreateDeleteContainer_SyncClient()
{
// Creates the client
IHDInsightCertificateConnectionCredentials credentials = IntegrationTestBase.GetValidCredentials();
var client = new HDInsightSyncClient(credentials.SubscriptionId, credentials.Certificate);
client.PollingInterval = TimeSpan.FromMilliseconds(100);
TestValidAdvancedCluster(
client.ListContainers,
client.ListContainer,
client.CreateContainer,
client.DeleteContainer);
}
[TestMethod]
[TestCategory("CheckIn")]
[TestCategory("Scenario")]
[Timeout(30 * 1000)] // ms
public void CreateDeleteContainer_AsyncClient()
{
// Creates the client
IHDInsightCertificateConnectionCredentials credentials = IntegrationTestBase.GetValidCredentials();
var client = new ClusterProvisioningClient(credentials.SubscriptionId, credentials.Certificate);
client.PollingInterval = TimeSpan.FromMilliseconds(100);
TestValidAdvancedCluster(
() => client.ListContainers().WaitForResult(),
dnsName => client.ListContainer(dnsName).WaitForResult(),
cluster => client.CreateContainer(cluster).WaitForResult(),
dnsName => client.DeleteContainer(dnsName).WaitForResult());
}
[TestMethod]
[TestCategory("CheckIn")]
[TestCategory("Scenario")]
[Timeout(30 * 1000)] // ms
public void CreateDeleteContainer_BasicClusterAsyncClient()
{
// Creates the client
IHDInsightCertificateConnectionCredentials credentials = IntegrationTestBase.GetValidCredentials();
var client = new ClusterProvisioningClient(credentials.SubscriptionId, credentials.Certificate);
client.PollingInterval = TimeSpan.FromMilliseconds(100);
TestClusterEndToEnd(
base.GetRandomCluster(),
() => client.ListContainers().WaitForResult(),
dnsName => client.ListContainer(dnsName).WaitForResult(),
cluster => client.CreateContainer(cluster).WaitForResult(),
dnsName => client.DeleteContainer(dnsName).WaitForResult());
}
[TestMethod]
[TestCategory("Manual")]
[TestCategory("Scenario")]
[TestCategory("LongRunning")]
[Timeout(30 * 60 * 1000)] // ms
public void CreateDeleteContainer_SyncClient_AgainstManualEnvironment()
{
// Dissables the simulator
this.ApplyIndividualTestMockingOnly();
// Sets the simulator
var runManager = ServiceLocator.Instance.Locate<IServiceLocationIndividualTestManager>();
runManager.Override<IConnectionCredentialsFactory>(new AlternativeEnvironmentConnectionCredentialsFactory());
// Creates the client
if (IntegrationTestBase.TestCredentials.AlternativeEnvironment == null)
Assert.Inconclusive("Alternative Azure Endpoint wasn't set up");
var client = new HDInsightSyncClient(
IntegrationTestBase.TestCredentials.AlternativeEnvironment.SubscriptionId,
IntegrationTestBase.GetValidCredentials().Certificate);
client.PollingInterval = TimeSpan.FromSeconds(1);
// Runs the test
TestValidAdvancedCluster(
client.ListContainers,
client.ListContainer,
client.CreateContainer,
client.DeleteContainer);
}
[TestMethod]
[TestCategory("CheckIn")]
[TestCategory("Scenario")]
[Timeout(30 * 1000)] // ms
[ExpectedException(typeof(OperationCanceledException))]
public void InvalidCreateDeleteContainer_FailsOnSdk_AgainstAzure()
{
this.ApplyIndividualTestMockingOnly();
InvalidCreateDeleteContainer_FailsOnSdk();
}
[TestMethod]
[TestCategory("CheckIn")]
[TestCategory("Scenario")]
[Timeout(30 * 1000)] // ms
[ExpectedException(typeof(OperationCanceledException))]
public void InvalidCreateDeleteContainer_FailsOnSdk()
{
var clusterRequest = base.GetRandomCluster();
clusterRequest.HiveMetastore = new ComponentMetastore(TestCredentials.HiveStores[0].SqlServer,
TestCredentials.HiveStores[0].Database,
TestCredentials.HiveStores[0].Username,
TestCredentials.HiveStores[0].Password);
IHDInsightCertificateConnectionCredentials credentials = IntegrationTestBase.GetValidCredentials();
var client = new ClusterProvisioningClient(credentials.SubscriptionId, credentials.Certificate);
client.PollingInterval = TimeSpan.FromMilliseconds(100);
TestClusterEndToEnd(
clusterRequest,
() => client.ListContainers().WaitForResult(),
dnsName => client.ListContainer(dnsName).WaitForResult(),
cluster => client.CreateContainer(cluster).WaitForResult(),
dnsName => client.DeleteContainer(dnsName).WaitForResult());
}
[TestMethod]
[TestCategory("CheckIn")]
[TestCategory("Scenario")]
[Timeout(30 * 1000)] // ms
[ExpectedException(typeof(InvalidOperationException))]
public void InvalidCreateDeleteContainer_FailsOnServer_AgainstAzure()
{
this.ApplyIndividualTestMockingOnly();
InvalidCreateDeleteContainer_FailsOnServer();
}
[TestMethod]
[TestCategory("CheckIn")]
[TestCategory("Scenario")]
[Timeout(30 * 1000)] // ms
[ExpectedException(typeof(InvalidOperationException))]
public void InvalidCreateDeleteContainer_FailsOnServer()
{
var clusterRequest = base.GetRandomCluster();
clusterRequest.AsvAccounts.Add(new AsvAccountConfiguration("invalid", TestCredentials.AdditionalStorageAccounts[0].Key));
IHDInsightCertificateConnectionCredentials credentials = IntegrationTestBase.GetValidCredentials();
var client = new HDInsightSyncClient(credentials.SubscriptionId, credentials.Certificate);
client.PollingInterval = TimeSpan.FromMilliseconds(100);
TestClusterEndToEnd(
clusterRequest,
client.ListContainers,
client.ListContainer,
client.CreateContainer,
client.DeleteContainer);
}
private void TestValidAdvancedCluster(
Func<Collection<ListClusterContainerResult>> getClusters,
Func<string, ListClusterContainerResult> getCluster,
Func<CreateClusterRequest, ListClusterContainerResult> createCluster,
Action<string> deleteCluster)
{
// ClusterName
var cluster = base.GetRandomCluster();
cluster.AsvAccounts.Add(new AsvAccountConfiguration(TestCredentials.AdditionalStorageAccounts[0].Name, TestCredentials.AdditionalStorageAccounts[0].Key));
cluster.OozieMetastore = new ComponentMetastore(TestCredentials.OozieStores[0].SqlServer,
TestCredentials.OozieStores[0].Database,
TestCredentials.OozieStores[0].Username,
TestCredentials.OozieStores[0].Password);
cluster.HiveMetastore = new ComponentMetastore(TestCredentials.HiveStores[0].SqlServer,
TestCredentials.HiveStores[0].Database,
TestCredentials.HiveStores[0].Username,
TestCredentials.HiveStores[0].Password);
this.TestClusterEndToEnd(cluster, getClusters, getCluster, createCluster, deleteCluster);
}
private void TestClusterEndToEnd(
CreateClusterRequest cluster,
Func<Collection<ListClusterContainerResult>> getClusters,
Func<string, ListClusterContainerResult> getCluster,
Func<CreateClusterRequest, ListClusterContainerResult> createCluster,
Action<string> deleteCluster)
{
// Identifies if it needs to validate Metastores
var restClientType = ServiceLocator.Instance.Locate<IHDInsightManagementRestClientFactory>().GetType();
var validateMetastores = cluster.OozieMetastore != null && cluster.HiveMetastore != null &&
restClientType != typeof(HDInsightManagementRestSimulatorClientFactory);
//// Deletes previous metastore schema data
//if (validateMetastores)
//{
// DeleteAllTables(cluster.OozieMetastore);
// DeleteAllTables(cluster.HiveMetastore);
//}
//// Verifies it doesn't exist
//var listResult = getClusters();
//int matchingContainers = listResult.Count(container => container.DnsName.Equals(cluster.DnsName));
//Assert.AreEqual(0, matchingContainers);
cluster.DnsName = "clitest-pudev2-050100-106c62b3f1c644f4a5f747d428985547";
cluster.ClusterUserPassword = "a5521F627F524ba980107894a8b47aE1forTest!";
var result = getCluster(cluster.DnsName);
//// Creates the cluster
//var result = createCluster(cluster);
//Assert.IsNotNull(result);
//Assert.IsNotNull(getCluster(cluster.DnsName));
// Validates the cluster
var tableName = "newtable" + Guid.NewGuid().ToString("N");
CreateTable(tableName, result.ConnectionUrl, cluster.ClusterUserName, cluster.ClusterUserPassword, cluster.DefaultAsvAccountName, cluster.DefaultAsvAccountKey);
RunJob(tableName, result.ConnectionUrl, cluster.ClusterUserName, cluster.ClusterUserPassword, cluster.DefaultAsvAccountName, cluster.DefaultAsvAccountKey);
if (validateMetastores)
{
Assert.AreNotEqual(0, GetTables(cluster.HiveMetastore).Count);
Assert.AreNotEqual(0, GetTables(cluster.OozieMetastore).Count);
ValidateTable(tableName, cluster.HiveMetastore);
}
// Deletes the cluster
deleteCluster(cluster.DnsName);
// Verifies it doesn't exist
Assert.IsNull(getCluster(cluster.DnsName));
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Helper method that creates a connection")]
private SqlConnection CreateDbConnection(ComponentMetastore metastore)
{
SqlConnectionStringBuilder connectionString = new SqlConnectionStringBuilder
{
DataSource = metastore.Server,
InitialCatalog = metastore.Database,
UserID = metastore.User,
Password = metastore.Password,
IntegratedSecurity = false,
};
var connection = new SqlConnection(connectionString.ConnectionString);
connection.Open();
return connection;
}
private Collection<string> GetTables(ComponentMetastore componentMetastore)
{
var tables = new Collection<string>();
using (var connection = CreateDbConnection(componentMetastore))
using (var command = new SqlCommand("select name from sys.objects where type = 'U'", connection))
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
tables.Add(reader.GetString(0));
}
}
return tables;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:Review SQL queries for security vulnerabilities", Justification = "Not Needed")]
private void DeleteAllTables(ComponentMetastore componentMetastore)
{
var tables = this.GetTables(componentMetastore);
using (var connection = CreateDbConnection(componentMetastore))
{
foreach (var table in tables)
using (var command = new SqlCommand(string.Format("DROP TABLE {0}", table), connection))
{
command.ExecuteNonQuery();
}
}
}
private void RunJob(string tableName, string clusterUrl, string username, string password, string storage, string key)
{
string command = string.Format(@"SELECT COUNT(*), column1 FROM {0} GROUP BY column1", tableName);
using (var hiveConnection = new HiveConnection(new Uri(clusterUrl), username, password, storage, key))
{
hiveConnection.ExecuteHiveQuery(command).WaitForResult();
}
}
private void CreateTable(string tableName, string clusterUrl, string username, string password, string storage, string key)
{
string command = string.Format(@"CREATE TABLE {0} (column1 STRING, column2 STRING, column3 STRING) STORED AS TEXTFILE", tableName);
using (var hiveConnection = new HiveConnection(new Uri(clusterUrl), username, password, storage, key))
{
hiveConnection.ExecuteHiveQuery(command).WaitForResult();
}
}
private void ValidateTable(string tableName, ComponentMetastore componentMetastore)
{
throw new NotImplementedException();
}
// Negative tests mocking the Create\List\Delete poco layers and making sure I don't get AggregateExceptions with WaitForResult or await
// Negative tests mocking the Create\List\Delete poco layers and making sure I don't get AggregateExceptions
}
}
| |
/*
* Copyright 2012 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Text;
namespace ZXing.PDF417.Internal.EC
{
/// <summary>
/// <see cref="com.google.zxing.common.reedsolomon.GenericGFPoly"/>
/// </summary>
/// <author>Sean Owen</author>
internal sealed class ModulusPoly
{
private readonly ModulusGF field;
private readonly int[] coefficients;
public ModulusPoly(ModulusGF field, int[] coefficients)
{
if (coefficients.Length == 0)
{
throw new ArgumentException();
}
this.field = field;
int coefficientsLength = coefficients.Length;
if (coefficientsLength > 1 && coefficients[0] == 0)
{
// Leading term must be non-zero for anything except the constant polynomial "0"
int firstNonZero = 1;
while (firstNonZero < coefficientsLength && coefficients[firstNonZero] == 0)
{
firstNonZero++;
}
if (firstNonZero == coefficientsLength)
{
this.coefficients = new int[]{0};
}
else
{
this.coefficients = new int[coefficientsLength - firstNonZero];
Array.Copy(coefficients,
firstNonZero,
this.coefficients,
0,
this.coefficients.Length);
}
}
else
{
this.coefficients = coefficients;
}
}
/// <summary>
/// Gets the coefficients.
/// </summary>
/// <value>The coefficients.</value>
internal int[] Coefficients
{
get { return coefficients; }
}
/// <summary>
/// degree of this polynomial
/// </summary>
internal int Degree
{
get
{
return coefficients.Length - 1;
}
}
/// <summary>
/// Gets a value indicating whether this instance is zero.
/// </summary>
/// <value>true if this polynomial is the monomial "0"
/// </value>
internal bool isZero
{
get { return coefficients[0] == 0; }
}
/// <summary>
/// coefficient of x^degree term in this polynomial
/// </summary>
/// <param name="degree">The degree.</param>
/// <returns>coefficient of x^degree term in this polynomial</returns>
internal int getCoefficient(int degree)
{
return coefficients[coefficients.Length - 1 - degree];
}
/// <summary>
/// evaluation of this polynomial at a given point
/// </summary>
/// <param name="a">A.</param>
/// <returns>evaluation of this polynomial at a given point</returns>
internal int evaluateAt(int a)
{
if (a == 0)
{
// Just return the x^0 coefficient
return getCoefficient(0);
}
int size = coefficients.Length;
int result = 0;
if (a == 1)
{
// Just the sum of the coefficients
foreach (var coefficient in coefficients)
{
result = field.add(result, coefficient);
}
return result;
}
result = coefficients[0];
for (int i = 1; i < size; i++)
{
result = field.add(field.multiply(a, result), coefficients[i]);
}
return result;
}
/// <summary>
/// Adds another Modulus
/// </summary>
/// <param name="other">Other.</param>
internal ModulusPoly add(ModulusPoly other)
{
if (!field.Equals(other.field))
{
throw new ArgumentException("ModulusPolys do not have same ModulusGF field");
}
if (isZero)
{
return other;
}
if (other.isZero)
{
return this;
}
int[] smallerCoefficients = this.coefficients;
int[] largerCoefficients = other.coefficients;
if (smallerCoefficients.Length > largerCoefficients.Length)
{
int[] temp = smallerCoefficients;
smallerCoefficients = largerCoefficients;
largerCoefficients = temp;
}
int[] sumDiff = new int[largerCoefficients.Length];
int lengthDiff = largerCoefficients.Length - smallerCoefficients.Length;
// Copy high-order terms only found in higher-degree polynomial's coefficients
Array.Copy(largerCoefficients, 0, sumDiff, 0, lengthDiff);
for (int i = lengthDiff; i < largerCoefficients.Length; i++)
{
sumDiff[i] = field.add(smallerCoefficients[i - lengthDiff], largerCoefficients[i]);
}
return new ModulusPoly(field, sumDiff);
}
/// <summary>
/// Subtract another Modulus
/// </summary>
/// <param name="other">Other.</param>
internal ModulusPoly subtract(ModulusPoly other)
{
if (!field.Equals(other.field))
{
throw new ArgumentException("ModulusPolys do not have same ModulusGF field");
}
if (other.isZero)
{
return this;
}
return add(other.getNegative());
}
/// <summary>
/// Multiply by another Modulus
/// </summary>
/// <param name="other">Other.</param>
internal ModulusPoly multiply(ModulusPoly other)
{
if (!field.Equals(other.field))
{
throw new ArgumentException("ModulusPolys do not have same ModulusGF field");
}
if (isZero || other.isZero)
{
return field.Zero;
}
int[] aCoefficients = this.coefficients;
int aLength = aCoefficients.Length;
int[] bCoefficients = other.coefficients;
int bLength = bCoefficients.Length;
int[] product = new int[aLength + bLength - 1];
for (int i = 0; i < aLength; i++)
{
int aCoeff = aCoefficients[i];
for (int j = 0; j < bLength; j++)
{
product[i + j] = field.add(product[i + j], field.multiply(aCoeff, bCoefficients[j]));
}
}
return new ModulusPoly(field, product);
}
/// <summary>
/// Returns a Negative version of this instance
/// </summary>
internal ModulusPoly getNegative()
{
int size = coefficients.Length;
int[] negativeCoefficients = new int[size];
for (int i = 0; i < size; i++)
{
negativeCoefficients[i] = field.subtract(0, coefficients[i]);
}
return new ModulusPoly(field, negativeCoefficients);
}
/// <summary>
/// Multiply by a Scalar.
/// </summary>
/// <param name="scalar">Scalar.</param>
internal ModulusPoly multiply(int scalar)
{
if (scalar == 0)
{
return field.Zero;
}
if (scalar == 1)
{
return this;
}
int size = coefficients.Length;
int[] product = new int[size];
for (int i = 0; i < size; i++)
{
product[i] = field.multiply(coefficients[i], scalar);
}
return new ModulusPoly(field, product);
}
/// <summary>
/// Multiplies by a Monomial
/// </summary>
/// <returns>The by monomial.</returns>
/// <param name="degree">Degree.</param>
/// <param name="coefficient">Coefficient.</param>
internal ModulusPoly multiplyByMonomial(int degree, int coefficient)
{
if (degree < 0)
{
throw new ArgumentException();
}
if (coefficient == 0)
{
return field.Zero;
}
int size = coefficients.Length;
int[] product = new int[size + degree];
for (int i = 0; i < size; i++)
{
product[i] = field.multiply(coefficients[i], coefficient);
}
return new ModulusPoly(field, product);
}
/// <summary>
/// Divide by another modulus
/// </summary>
/// <param name="other">Other.</param>
internal ModulusPoly[] divide(ModulusPoly other)
{
if (!field.Equals(other.field))
{
throw new ArgumentException("ModulusPolys do not have same ModulusGF field");
}
if (other.isZero)
{
throw new DivideByZeroException();
}
ModulusPoly quotient = field.Zero;
ModulusPoly remainder = this;
int denominatorLeadingTerm = other.getCoefficient(other.Degree);
int inverseDenominatorLeadingTerm = field.inverse(denominatorLeadingTerm);
while (remainder.Degree >= other.Degree && !remainder.isZero)
{
int degreeDifference = remainder.Degree - other.Degree;
int scale = field.multiply(remainder.getCoefficient(remainder.Degree), inverseDenominatorLeadingTerm);
ModulusPoly term = other.multiplyByMonomial(degreeDifference, scale);
ModulusPoly iterationQuotient = field.buildMonomial(degreeDifference, scale);
quotient = quotient.add(iterationQuotient);
remainder = remainder.subtract(term);
}
return new ModulusPoly[] { quotient, remainder };
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents the current <see cref="ZXing.PDF417.Internal.EC.ModulusPoly"/>.
/// </summary>
/// <returns>A <see cref="System.String"/> that represents the current <see cref="ZXing.PDF417.Internal.EC.ModulusPoly"/>.</returns>
public override String ToString()
{
var result = new StringBuilder(8 * Degree);
for (int degree = Degree; degree >= 0; degree--)
{
int coefficient = getCoefficient(degree);
if (coefficient != 0)
{
if (coefficient < 0)
{
result.Append(" - ");
coefficient = -coefficient;
}
else
{
if (result.Length > 0)
{
result.Append(" + ");
}
}
if (degree == 0 || coefficient != 1)
{
result.Append(coefficient);
}
if (degree != 0)
{
if (degree == 1)
{
result.Append('x');
}
else
{
result.Append("x^");
result.Append(degree);
}
}
}
}
return result.ToString();
}
}
}
| |
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Runtime.InteropServices;
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\InterpToMovementComponent.h:61
namespace UnrealEngine
{
[ManageType("ManageInterpToMovementComponent")]
public partial class ManageInterpToMovementComponent : UInterpToMovementComponent, IManageWrapper
{
public ManageInterpToMovementComponent(IntPtr adress)
: base(adress)
{
}
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_UpdateControlPoints(IntPtr self, bool inForceUpdate);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_OnTeleported(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_SetPlaneConstraintEnabled(IntPtr self, bool bEnabled);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_SnapUpdatedComponentToPlane(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_StopMovementImmediately(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_UpdateComponentVelocity(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_UpdateTickRegistration(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_Activate(IntPtr self, bool bReset);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_BeginPlay(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_CreateRenderState_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_Deactivate(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_DestroyComponent(IntPtr self, bool bPromoteChildren);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_DestroyRenderState_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_InitializeComponent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_InvalidateLightingCacheDetailed(IntPtr self, bool bInvalidateBuildEnqueuedLighting, bool bTranslationOnly);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_OnActorEnableCollisionChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_OnComponentCreated(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_OnComponentDestroyed(IntPtr self, bool bDestroyingHierarchy);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_OnCreatePhysicsState(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_OnDestroyPhysicsState(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_OnRegister(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_OnRep_IsActive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_OnUnregister(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_RegisterComponentTickFunctions(IntPtr self, bool bRegister);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_SendRenderDynamicData_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_SendRenderTransform_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_SetActive(IntPtr self, bool bNewActive, bool bReset);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_SetAutoActivate(IntPtr self, bool bNewAutoActivate);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_SetComponentTickEnabled(IntPtr self, bool bEnabled);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_SetComponentTickEnabledAsync(IntPtr self, bool bEnabled);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_ToggleActive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_UninitializeComponent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_BeginDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_FinishDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_MarkAsEditorOnlySubobject(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_PostCDOContruct(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_PostEditImport(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_PostInitProperties(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_PostLoad(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_PostNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_PostRepNotifies(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_PostSaveRoot(IntPtr self, bool bCleanupIsRequired);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_PreDestroyFromReplication(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_PreNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_ShutdownAfterError(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_CreateCluster(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UInterpToMovementComponent_OnClusterMarkedAsPendingKill(IntPtr self);
#endregion
#region Methods
protected override void UpdateControlPoints(bool inForceUpdate)
=> E__Supper__UInterpToMovementComponent_UpdateControlPoints(this, inForceUpdate);
/// <summary>
/// Called by owning Actor upon successful teleport from AActor::TeleportTo().
/// </summary>
public override void OnTeleported()
=> E__Supper__UInterpToMovementComponent_OnTeleported(this);
/// <summary>
/// Sets whether or not the plane constraint is enabled.
/// </summary>
public override void SetPlaneConstraintEnabled(bool bEnabled)
=> E__Supper__UInterpToMovementComponent_SetPlaneConstraintEnabled(this, bEnabled);
/// <summary>
/// Snap the updated component to the plane constraint, if enabled.
/// </summary>
public override void SnapUpdatedComponentToPlane()
=> E__Supper__UInterpToMovementComponent_SnapUpdatedComponentToPlane(this);
/// <summary>
/// Stops movement immediately (zeroes velocity, usually zeros acceleration for components with acceleration).
/// </summary>
public override void StopMovementImmediately()
=> E__Supper__UInterpToMovementComponent_StopMovementImmediately(this);
/// <summary>
/// Update ComponentVelocity of UpdatedComponent. This needs to be called by derived classes at the end of an update whenever Velocity has changed.
/// </summary>
public override void UpdateComponentVelocity()
=> E__Supper__UInterpToMovementComponent_UpdateComponentVelocity(this);
/// <summary>
/// Update tick registration state, determined by bAutoUpdateTickRegistration. Called by SetUpdatedComponent.
/// </summary>
public override void UpdateTickRegistration()
=> E__Supper__UInterpToMovementComponent_UpdateTickRegistration(this);
/// <summary>
/// Activates the SceneComponent, should be overridden by native child classes.
/// </summary>
/// <param name="bReset">Whether the activation should happen even if ShouldActivate returns false.</param>
public override void Activate(bool bReset)
=> E__Supper__UInterpToMovementComponent_Activate(this, bReset);
/// <summary>
/// BeginsPlay for the component. Occurs at level startup or actor spawn. This is before BeginPlay (Actor or Component).
/// <para>All Components (that want initialization) in the level will be Initialized on load before any </para>
/// Actor/Component gets BeginPlay.
/// <para>Requires component to be registered and initialized. </para>
/// </summary>
public override void BeginPlay()
=> E__Supper__UInterpToMovementComponent_BeginPlay(this);
/// <summary>
/// Used to create any rendering thread information for this component
/// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para>
/// </summary>
protected override void CreateRenderState_Concurrent()
=> E__Supper__UInterpToMovementComponent_CreateRenderState_Concurrent(this);
/// <summary>
/// Deactivates the SceneComponent.
/// </summary>
public override void Deactivate()
=> E__Supper__UInterpToMovementComponent_Deactivate(this);
/// <summary>
/// Unregister the component, remove it from its outer Actor's Components array and mark for pending kill.
/// </summary>
public override void DestroyComponent(bool bPromoteChildren)
=> E__Supper__UInterpToMovementComponent_DestroyComponent(this, bPromoteChildren);
/// <summary>
/// Used to shut down any rendering thread structure for this component
/// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para>
/// </summary>
protected override void DestroyRenderState_Concurrent()
=> E__Supper__UInterpToMovementComponent_DestroyRenderState_Concurrent(this);
/// <summary>
/// Initializes the component. Occurs at level startup or actor spawn. This is before BeginPlay (Actor or Component).
/// <para>All Components in the level will be Initialized on load before any Actor/Component gets BeginPlay </para>
/// Requires component to be registered, and bWantsInitializeComponent to be true.
/// </summary>
public override void InitializeComponent()
=> E__Supper__UInterpToMovementComponent_InitializeComponent(this);
/// <summary>
/// Called when this actor component has moved, allowing it to discard statically cached lighting information.
/// </summary>
public override void InvalidateLightingCacheDetailed(bool bInvalidateBuildEnqueuedLighting, bool bTranslationOnly)
=> E__Supper__UInterpToMovementComponent_InvalidateLightingCacheDetailed(this, bInvalidateBuildEnqueuedLighting, bTranslationOnly);
/// <summary>
/// Called on each component when the Actor's bEnableCollisionChanged flag changes
/// </summary>
public override void OnActorEnableCollisionChanged()
=> E__Supper__UInterpToMovementComponent_OnActorEnableCollisionChanged(this);
/// <summary>
/// Called when a component is created (not loaded). This can happen in the editor or during gameplay
/// </summary>
public override void OnComponentCreated()
=> E__Supper__UInterpToMovementComponent_OnComponentCreated(this);
/// <summary>
/// Called when a component is destroyed
/// </summary>
/// <param name="bDestroyingHierarchy">True if the entire component hierarchy is being torn down, allows avoiding expensive operations</param>
public override void OnComponentDestroyed(bool bDestroyingHierarchy)
=> E__Supper__UInterpToMovementComponent_OnComponentDestroyed(this, bDestroyingHierarchy);
/// <summary>
/// Used to create any physics engine information for this component
/// </summary>
protected override void OnCreatePhysicsState()
=> E__Supper__UInterpToMovementComponent_OnCreatePhysicsState(this);
/// <summary>
/// Used to shut down and physics engine structure for this component
/// </summary>
protected override void OnDestroyPhysicsState()
=> E__Supper__UInterpToMovementComponent_OnDestroyPhysicsState(this);
/// <summary>
/// Called when a component is registered, after Scene is set, but before CreateRenderState_Concurrent or OnCreatePhysicsState are called.
/// </summary>
protected override void OnRegister()
=> E__Supper__UInterpToMovementComponent_OnRegister(this);
public override void OnRep_IsActive()
=> E__Supper__UInterpToMovementComponent_OnRep_IsActive(this);
/// <summary>
/// Called when a component is unregistered. Called after DestroyRenderState_Concurrent and OnDestroyPhysicsState are called.
/// </summary>
protected override void OnUnregister()
=> E__Supper__UInterpToMovementComponent_OnUnregister(this);
/// <summary>
/// Virtual call chain to register all tick functions
/// </summary>
/// <param name="bRegister">true to register, false, to unregister</param>
protected override void RegisterComponentTickFunctions(bool bRegister)
=> E__Supper__UInterpToMovementComponent_RegisterComponentTickFunctions(this, bRegister);
/// <summary>
/// Called to send dynamic data for this component to the rendering thread
/// </summary>
protected override void SendRenderDynamicData_Concurrent()
=> E__Supper__UInterpToMovementComponent_SendRenderDynamicData_Concurrent(this);
/// <summary>
/// Called to send a transform update for this component to the rendering thread
/// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para>
/// </summary>
protected override void SendRenderTransform_Concurrent()
=> E__Supper__UInterpToMovementComponent_SendRenderTransform_Concurrent(this);
/// <summary>
/// Sets whether the component is active or not
/// </summary>
/// <param name="bNewActive">The new active state of the component</param>
/// <param name="bReset">Whether the activation should happen even if ShouldActivate returns false.</param>
public override void SetActive(bool bNewActive, bool bReset)
=> E__Supper__UInterpToMovementComponent_SetActive(this, bNewActive, bReset);
/// <summary>
/// Sets whether the component should be auto activate or not. Only safe during construction scripts.
/// </summary>
/// <param name="bNewAutoActivate">The new auto activate state of the component</param>
public override void SetAutoActivate(bool bNewAutoActivate)
=> E__Supper__UInterpToMovementComponent_SetAutoActivate(this, bNewAutoActivate);
/// <summary>
/// Set this component's tick functions to be enabled or disabled. Only has an effect if the function is registered
/// </summary>
/// <param name="bEnabled">Whether it should be enabled or not</param>
public override void SetComponentTickEnabled(bool bEnabled)
=> E__Supper__UInterpToMovementComponent_SetComponentTickEnabled(this, bEnabled);
/// <summary>
/// Spawns a task on GameThread that will call SetComponentTickEnabled
/// </summary>
/// <param name="bEnabled">Whether it should be enabled or not</param>
public override void SetComponentTickEnabledAsync(bool bEnabled)
=> E__Supper__UInterpToMovementComponent_SetComponentTickEnabledAsync(this, bEnabled);
/// <summary>
/// Toggles the active state of the component
/// </summary>
public override void ToggleActive()
=> E__Supper__UInterpToMovementComponent_ToggleActive(this);
/// <summary>
/// Handle this component being Uninitialized.
/// <para>Called from AActor::EndPlay only if bHasBeenInitialized is true </para>
/// </summary>
public override void UninitializeComponent()
=> E__Supper__UInterpToMovementComponent_UninitializeComponent(this);
/// <summary>
/// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an
/// <para>asynchronous cleanup process. </para>
/// </summary>
public override void BeginDestroy()
=> E__Supper__UInterpToMovementComponent_BeginDestroy(this);
/// <summary>
/// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed.
/// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para>
/// </summary>
public override void FinishDestroy()
=> E__Supper__UInterpToMovementComponent_FinishDestroy(this);
/// <summary>
/// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds
/// </summary>
public override void MarkAsEditorOnlySubobject()
=> E__Supper__UInterpToMovementComponent_MarkAsEditorOnlySubobject(this);
/// <summary>
/// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion
/// <para>in the construction of the default materials </para>
/// </summary>
public override void PostCDOContruct()
=> E__Supper__UInterpToMovementComponent_PostCDOContruct(this);
/// <summary>
/// Called after importing property values for this object (paste, duplicate or .t3d import)
/// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para>
/// are unsupported by the script serialization
/// </summary>
public override void PostEditImport()
=> E__Supper__UInterpToMovementComponent_PostEditImport(this);
/// <summary>
/// Called after the C++ constructor and after the properties have been initialized, including those loaded from config.
/// <para>This is called before any serialization or other setup has happened. </para>
/// </summary>
public override void PostInitProperties()
=> E__Supper__UInterpToMovementComponent_PostInitProperties(this);
/// <summary>
/// Do any object-specific cleanup required immediately after loading an object.
/// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para>
/// </summary>
public override void PostLoad()
=> E__Supper__UInterpToMovementComponent_PostLoad(this);
/// <summary>
/// Called right after receiving a bunch
/// </summary>
public override void PostNetReceive()
=> E__Supper__UInterpToMovementComponent_PostNetReceive(this);
/// <summary>
/// Called right after calling all OnRep notifies (called even when there are no notifies)
/// </summary>
public override void PostRepNotifies()
=> E__Supper__UInterpToMovementComponent_PostRepNotifies(this);
/// <summary>
/// Called from within SavePackage on the passed in base/root object.
/// <para>This function is called after the package has been saved and can perform cleanup. </para>
/// </summary>
/// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param>
public override void PostSaveRoot(bool bCleanupIsRequired)
=> E__Supper__UInterpToMovementComponent_PostSaveRoot(this, bCleanupIsRequired);
/// <summary>
/// Called right before being marked for destruction due to network replication
/// </summary>
public override void PreDestroyFromReplication()
=> E__Supper__UInterpToMovementComponent_PreDestroyFromReplication(this);
/// <summary>
/// Called right before receiving a bunch
/// </summary>
public override void PreNetReceive()
=> E__Supper__UInterpToMovementComponent_PreNetReceive(this);
/// <summary>
/// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources.
/// </summary>
public override void ShutdownAfterError()
=> E__Supper__UInterpToMovementComponent_ShutdownAfterError(this);
/// <summary>
/// Called after PostLoad to create UObject cluster
/// </summary>
public override void CreateCluster()
=> E__Supper__UInterpToMovementComponent_CreateCluster(this);
/// <summary>
/// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it.
/// </summary>
public override void OnClusterMarkedAsPendingKill()
=> E__Supper__UInterpToMovementComponent_OnClusterMarkedAsPendingKill(this);
#endregion
public static implicit operator IntPtr(ManageInterpToMovementComponent self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator ManageInterpToMovementComponent(ObjectPointerDescription PtrDesc)
{
return NativeManager.GetWrapper<ManageInterpToMovementComponent>(PtrDesc);
}
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// Description: Static methods for all TextElementCollection<T> instances.
//
//---------------------------------------------------------------------------
namespace System.Windows.Documents
{
// This class maintains a static list of "clean" TextElementCollection
// instances. Clean in this sense means guarantee not to have been
// modified in a way that could invalidate their _indexCache members.
//
// The cache is a simple list of WeakReferences to collections.
// The size of the list limits the number of collections
// that can be used to modify content simultaneously with good IList
// performance. The scenario we're concerned about is the parser,
// which will allocate one collection for each scoping TextElement
// in a document: <Paragraph><Italic><Run>hello world</Run></Italic></Paragraph>
// requires a minimum cache size of 3 to keep load times O(n).
internal static class TextElementCollectionHelper
{
//-------------------------------------------------------------------
//
// Internal Methods
//
//-------------------------------------------------------------------
#region Internal Methods
// Invalidates any collection tracking parent's children.
// Called by the TextContainer.
internal static void MarkDirty(DependencyObject parent)
{
if (parent == null)
{
return;
}
lock (_cleanParentList)
{
for (int i = 0; i < _cleanParentList.Length; i++)
{
if (_cleanParentList[i] != null)
{
ParentCollectionPair pair = (ParentCollectionPair)_cleanParentList[i].Target;
if (pair == null || pair.Parent == parent)
{
_cleanParentList[i] = null;
}
}
}
}
}
// Tags a parent/collection as synchronized.
// Since we use a most-recently-used algorithm, it's useful
// to call this any time a collection is touched, even if it is
// only read.
internal static void MarkClean(DependencyObject parent, object collection)
{
lock (_cleanParentList)
{
int firstFreeIndex;
int index = GetCleanParentIndex(parent, collection, out firstFreeIndex);
if (index == -1)
{
index = firstFreeIndex >= 0 ? firstFreeIndex : _cleanParentList.Length - 1;
_cleanParentList[index] = new WeakReference(new ParentCollectionPair(parent, collection));
}
TouchCleanParent(index);
}
}
// Returns true if the parent/collection pair are clean.
// Since we use a most-recently-used algorithm, it's useful
// to call this any time a collection is touched, even if it is
// only read.
internal static bool IsCleanParent(DependencyObject parent, object collection)
{
int index = -1;
lock (_cleanParentList)
{
int firstFreeIndex;
index = GetCleanParentIndex(parent, collection, out firstFreeIndex);
if (index >= 0)
{
TouchCleanParent(index);
}
}
return (index >= 0);
}
#endregion Internal Methods
//-------------------------------------------------------------------
//
// Private Methods
//
//-------------------------------------------------------------------
#region Private Methods
// Moves an entry to the top of the most-recently-used list.
// Caller must hold a lock on _cleanParentList!
private static void TouchCleanParent(int index)
{
WeakReference parentReference = _cleanParentList[index];
// Shift preceding parents down, dropping the last parent.
Array.Copy(_cleanParentList, 0, _cleanParentList, 1, index);
// Put the mru parent at the head.
_cleanParentList[0] = parentReference;
}
// Returns the index of an entry in the list, or -1 if not present.
// Caller must hold a lock on _cleanParentList!
private static int GetCleanParentIndex(DependencyObject parent, object collection, out int firstFreeIndex)
{
int index = -1;
firstFreeIndex = -1;
for (int i = 0; i < _cleanParentList.Length; i++)
{
if (_cleanParentList[i] == null)
{
if (firstFreeIndex == -1)
{
firstFreeIndex = i;
}
}
else
{
ParentCollectionPair pair = (ParentCollectionPair)_cleanParentList[i].Target;
if (pair == null)
{
// WeakReference is dead, remove it.
_cleanParentList[i] = null;
if (firstFreeIndex == -1)
{
firstFreeIndex = i;
}
}
else if (pair.Parent == parent && pair.Collection == collection)
{
// Found a match. Keep going to clean up any dead WeakReferences
// or set firstFreeIndex.
index = i;
}
}
}
return index;
}
#endregion Private Methods
//-------------------------------------------------------------------
//
// Private Types
//
//-------------------------------------------------------------------
#region Private Types
// A parent/collection entry.
private class ParentCollectionPair
{
internal ParentCollectionPair(DependencyObject parent, object collection)
{
_parent = parent;
_collection = collection;
}
internal DependencyObject Parent { get { return _parent; } }
internal object Collection { get { return _collection; } }
private readonly DependencyObject _parent;
private readonly object _collection;
}
#endregion Private Types
//-------------------------------------------------------------------
//
// Private Fields
//
//-------------------------------------------------------------------
#region Private Fields
// Static list of clean parent/collection pairs.
private static readonly WeakReference []_cleanParentList = new WeakReference[10];
#endregion Private Fields
}
}
| |
//----------------------------------------------------
// Downloaded From
// Visual C# Kicks - http://www.vcskicks.com/
//----------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Data;
using System.Text;
using System.Windows.Forms;
namespace ExtendedExplorer
{
[DefaultEvent("Click")] //Already built-in
public partial class CommandLink : UserControl
{
public CommandLink()
{
InitializeComponent();
this.DoubleBuffered = true; //Smooth redrawing
}
#region Fields---------------------------------
public enum State
{
Normal,
Hover,
Pushed,
Disabled
}
public enum VerticalAlign
{
Top,
Middle,
Bottom
}
private State state = State.Normal;
private int offset = 0;
private string headerText = "Header Text";
private string descriptionText = "Description";
private Bitmap image;
private Bitmap grayImage;
private Size imageSize = new Size(24, 24);
private VerticalAlign imageAlign = VerticalAlign.Top;
private Font descriptFont;
private DialogResult diagResult = DialogResult.None;
#endregion
#region Properties----------------------------
[Category("Command Appearance"),
Browsable(true),
DefaultValue("Header Text")]
public string HeaderText
{
get
{
return headerText;
}
set
{
headerText = value;
this.Refresh();
}
}
[Category("Command Appearance"),
Browsable(true),
DefaultValue("Description")]
public string DescriptionText
{
get
{
return descriptionText;
}
set
{
descriptionText = value;
this.Refresh();
}
}
[Category("Command Appearance"),
Browsable(true),
DefaultValue(null)]
public Bitmap Image
{
get
{
return image;
}
set
{
//Clean up
if (image != null)
image.Dispose();
if (grayImage != null)
grayImage.Dispose();
image = value;
if (image != null)
grayImage = GetGrayscale(image); //generate image for disabled state
else
grayImage = null;
this.Refresh();
}
}
[Category("Command Appearance"),
Browsable(true),
DefaultValue(typeof(Size), "24,24")]
public Size ImageScalingSize
{
get
{
return imageSize;
}
set
{
imageSize = value;
this.Refresh();
}
}
[Category("Command Appearance"),
Browsable(true),
DefaultValue(VerticalAlign.Top)]
public VerticalAlign ImageVerticalAlign
{
get
{
return imageAlign;
}
set
{
imageAlign = value;
this.Refresh();
}
}
[Category("Command Appearance")]
public override Font Font
{
get
{
return base.Font;
}
set
{
base.Font = value;
//Clean up
if (descriptFont != null)
descriptFont.Dispose();
//Update the description font, which is the same just 3 sizes smaller
descriptFont = new Font(this.Font.FontFamily, this.Font.Size - 3);
}
}
[Category("Behavior"),
DefaultValue(DialogResult.None)]
public DialogResult DialogResult
{
get
{
return diagResult;
}
set
{
diagResult = value;
}
}
#endregion
#region Events-----------------------------------
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e); //draws the regular background stuff
if (this.Focused && state == State.Normal)
DrawHighlight(e.Graphics);
switch (state)
{
case State.Normal:
DrawNormalState(e.Graphics);
break;
case State.Hover:
DrawHoverState(e.Graphics);
break;
case State.Pushed:
DrawPushedState(e.Graphics);
break;
case State.Disabled:
DrawNormalState(e.Graphics); //DrawForeground takes care of drawing the disabled state
break;
default:
break;
}
}
protected override void OnClick(EventArgs e)
{
base.OnClick(e);
if (diagResult != DialogResult.None)
{
this.ParentForm.DialogResult = diagResult;
this.ParentForm.Close();
}
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (e.KeyChar == Convert.ToChar(Keys.Enter))
this.PerformClick();
base.OnKeyPress(e);
}
protected override void OnGotFocus(EventArgs e)
{
this.Refresh();
base.OnGotFocus(e);
}
protected override void OnLostFocus(EventArgs e)
{
this.Refresh();
base.OnLostFocus(e);
}
protected override void OnMouseEnter(EventArgs e)
{
if (this.Enabled)
state = State.Hover;
this.Refresh();
base.OnMouseEnter(e);
}
protected override void OnMouseLeave(EventArgs e)
{
if (this.Enabled)
state = State.Normal;
this.Refresh();
base.OnMouseLeave(e);
}
protected override void OnMouseDown(MouseEventArgs e)
{
if (this.Enabled)
state = State.Pushed;
this.Refresh();
base.OnMouseDown(e);
}
protected override void OnMouseUp(MouseEventArgs e)
{
if (this.Enabled)
{
if (this.RectangleToScreen(this.ClientRectangle).Contains(Cursor.Position))
state = State.Hover;
else
state = State.Normal;
}
this.Refresh();
base.OnMouseUp(e);
}
protected override void OnEnabledChanged(EventArgs e)
{
if (this.Enabled)
state = State.Normal;
else
state = State.Disabled;
this.Refresh();
base.OnEnabledChanged(e);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
image.Dispose();
grayImage.Dispose();
descriptFont.Dispose();
}
base.Dispose(disposing);
}
#endregion
#region Drawing Methods-------------------------
//Draws the light-blue rectangle around the button when it is focused (by Tab for example)
private void DrawHighlight(Graphics g)
{
//The outline is drawn inside the button
GraphicsPath innerRegion = RoundedRect(this.Width - 3, this.Height - 3, 3);
//----Shift the inner region inwards
Matrix translate = new Matrix();
translate.Translate(1, 1);
innerRegion.Transform(translate);
translate.Dispose();
//-----
Pen inlinePen = new Pen(Color.FromArgb(192, 233, 243)); //Light-blue
g.SmoothingMode = SmoothingMode.AntiAlias;
g.DrawPath(inlinePen, innerRegion);
//Clean-up
inlinePen.Dispose();
innerRegion.Dispose();
}
//Draws the button when the mouse is over it
private void DrawHoverState(Graphics g)
{
GraphicsPath outerRegion = RoundedRect(this.Width - 1, this.Height - 1, 3);
GraphicsPath innerRegion = RoundedRect(this.Width - 3, this.Height - 3, 2);
//----Shift the inner region inwards
Matrix translate = new Matrix();
translate.Translate(1, 1);
innerRegion.Transform(translate);
translate.Dispose();
//-----
Rectangle backgroundRect = new Rectangle(1, 1, this.Width - 2, (int)(this.Height * 0.75f) - 2);
Pen outlinePen = new Pen(Color.FromArgb(189, 189, 189)); //SystemColors.ControlDark
Pen inlinePen = new Pen(Color.FromArgb(245, 255, 255, 255)); //Slightly transparent white
//Gradient brush for the background, goes from white to transparent 75% of the way down
LinearGradientBrush backBrush = new LinearGradientBrush(new Point(0, 0), new Point(0, backgroundRect.Height), Color.White, Color.Transparent);
backBrush.WrapMode = WrapMode.TileFlipX; //keeps the gradient smooth incase of the glitch where there's an extra gradient line
g.SmoothingMode = SmoothingMode.AntiAlias;
g.FillRectangle(backBrush, backgroundRect);
g.DrawPath(inlinePen, innerRegion);
g.DrawPath(outlinePen, outerRegion);
//Text/Image
offset = 0; //Text/Image doesn't move
DrawForeground(g);
//Clean up
outlinePen.Dispose();
inlinePen.Dispose();
outerRegion.Dispose();
innerRegion.Dispose();
}
//Draws the button when it's clicked down
private void DrawPushedState(Graphics g)
{
GraphicsPath outerRegion = RoundedRect(this.Width - 1, this.Height - 1, 3);
GraphicsPath innerRegion = RoundedRect(this.Width - 3, this.Height - 3, 2);
//----Shift the inner region inwards
Matrix translate = new Matrix();
translate.Translate(1, 1);
innerRegion.Transform(translate);
translate.Dispose();
//-----
Rectangle backgroundRect = new Rectangle(1, 1, this.Width - 3, this.Height - 3);
Pen outlinePen = new Pen(Color.FromArgb(167, 167, 167)); //Outline is darker than normal
Pen inlinePen = new Pen(Color.FromArgb(227, 227, 227)); //Darker white
SolidBrush backBrush = new SolidBrush(Color.FromArgb(234, 234, 234)); //SystemColors.ControlLight
g.SmoothingMode = SmoothingMode.AntiAlias;
g.FillRectangle(backBrush, backgroundRect);
g.DrawPath(inlinePen, innerRegion);
g.DrawPath(outlinePen, outerRegion);
//Text/Image
offset = 1; //moves image inwards 1 pixel (x and y) to create the illusion that the button was pushed
DrawForeground(g);
//Clean up
outlinePen.Dispose();
inlinePen.Dispose();
outerRegion.Dispose();
innerRegion.Dispose();
}
//Draws the button in it's regular state
private void DrawNormalState(Graphics g)
{
//Nothing needs to be drawn but the text and image
//Text/Image
offset = 0; //Text/Image doesn't move
DrawForeground(g);
}
//Draws Text and Image
private void DrawForeground(Graphics g)
{
//Make sure drawing is of good quality
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
//Image Coordinates-------------------------------
int imageLeft = 9;
int imageTop = 0;
//
//Text Layout--------------------------------
//Gets the width/height of the text once it's drawn out
SizeF headerLayout = g.MeasureString(headerText, this.Font);
SizeF descriptLayout = g.MeasureString(descriptionText, descriptFont);
//Merge the two sizes into one big rectangle
Rectangle totalRect = new Rectangle(0, 0, (int)Math.Max(headerLayout.Width, descriptLayout.Width), (int)(headerLayout.Height + descriptLayout.Height) - 4);
//Align the total rectangle-------------------------
if (image != null)
totalRect.X = imageLeft + imageSize.Width + 5; //consider the image is there
else
totalRect.X = 20;
totalRect.Y = (this.Height / 2) - (totalRect.Height / 2); //center vertically
//---------------------------------------------------
//Align the top of the image---------------------
if (image != null)
{
switch (imageAlign)
{
case VerticalAlign.Top:
imageTop = totalRect.Y;
break;
case VerticalAlign.Middle:
imageTop = totalRect.Y + (totalRect.Height / 2) - (imageSize.Height / 2);
break;
case VerticalAlign.Bottom:
imageTop = totalRect.Y + totalRect.Height - imageSize.Height;
break;
default:
break;
}
}
//-----------------------------------------------
//Brushes--------------------------------
// Determine text color depending on whether the control is enabled or not
Color textColor = this.ForeColor;
if (!this.Enabled)
textColor = SystemColors.GrayText;
SolidBrush textBrush = new SolidBrush(textColor);
//------------------------------------------
g.DrawString(headerText, this.Font, textBrush, totalRect.Left + offset, totalRect.Top + offset);
g.DrawString(DescriptionText, descriptFont, textBrush, totalRect.Left + 1 + offset, totalRect.Bottom - (int)descriptLayout.Height + offset);
//Note: the + 1 in "totalRect.Left + 1 + offset" compensates for GDI+ inconsistency
if (image != null)
{
if (this.Enabled)
g.DrawImage(image, new Rectangle(imageLeft + offset, imageTop + offset, imageSize.Width, imageSize.Height));
else
{
//make sure there is a gray-image
if (grayImage == null)
grayImage = GetGrayscale(image); //generate grayscale now
g.DrawImage(grayImage, new Rectangle(imageLeft + offset, imageTop + offset, imageSize.Width, imageSize.Height));
}
}
//Clean-up
textBrush.Dispose();
}
#endregion
#region Helper Methods--------------------------
private static GraphicsPath RoundedRect(int width, int height, int radius)
{
RectangleF baseRect = new RectangleF(0, 0, width, height);
float diameter = radius * 2.0f;
SizeF sizeF = new SizeF(diameter, diameter);
RectangleF arc = new RectangleF(baseRect.Location, sizeF);
GraphicsPath path = new GraphicsPath();
// top left arc
path.AddArc(arc, 180, 90);
// top right arc
arc.X = baseRect.Right - diameter;
path.AddArc(arc, 270, 90);
// bottom right arc
arc.Y = baseRect.Bottom - diameter;
path.AddArc(arc, 0, 90);
// bottom left arc
arc.X = baseRect.Left;
path.AddArc(arc, 90, 90);
path.CloseFigure();
return path;
}
private static Bitmap GetGrayscale(Image original)
{
//Set up the drawing surface
Bitmap grayscale = new Bitmap(original.Width, original.Height);
Graphics g = Graphics.FromImage(grayscale);
//Grayscale Color Matrix
ColorMatrix colorMatrix = new ColorMatrix(new float[][]
{
new float[] {0.3f, 0.3f, 0.3f, 0, 0},
new float[] {0.59f, 0.59f, 0.59f, 0, 0},
new float[] {0.11f, 0.11f, 0.11f, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {0, 0, 0, 0, 1}
});
//Create attributes
ImageAttributes att = new ImageAttributes();
att.SetColorMatrix(colorMatrix);
//Draw the image with the new attributes
g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, att);
//Clean up
g.Dispose();
return grayscale;
}
public void PerformClick()
{
this.OnClick(null);
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections.Generic;
using Pathfinding.Serialization;
namespace Pathfinding {
public delegate void GraphNodeDelegate (GraphNode node);
public delegate bool GraphNodeDelegateCancelable (GraphNode node);
public abstract class GraphNode {
/** Internal unique index */
private int nodeIndex;
/** Bitpacked field holding several pieces of data.
* \see Walkable
* \see Area
* \see GraphIndex
* \see Tag
*/
protected uint flags;
/** Penalty cost for walking on this node.
* This can be used to make it harder/slower to walk over certain nodes.
*
* A penalty of 1000 (Int3.Precision) corresponds to the cost of walking one world unit.
*/
private uint penalty;
/** Constructor for a graph node. */
protected GraphNode (AstarPath astar) {
if (!System.Object.ReferenceEquals(astar, null)) {
this.nodeIndex = astar.GetNewNodeIndex();
astar.InitializeNode(this);
} else {
throw new System.Exception("No active AstarPath object to bind to");
}
}
/** Destroys the node.
* Cleans up any temporary pathfinding data used for this node.
* The graph is responsible for calling this method on nodes when they are destroyed, including when the whole graph is destoyed.
* Otherwise memory leaks might present themselves.
*
* Once called the #Destroyed property will return true and subsequent calls to this method will not do anything.
*
* \note Assumes the current active AstarPath instance is the same one that created this node.
*
* \warning Should only be called by graph classes on their own nodes
*/
public void Destroy () {
//Already destroyed
if (Destroyed) return;
ClearConnections(true);
if (AstarPath.active != null) {
AstarPath.active.DestroyNode(this);
}
nodeIndex = -1;
}
public bool Destroyed {
get {
return nodeIndex == -1;
}
}
/** Internal unique index.
* Every node will get a unique index.
* This index is not necessarily correlated with e.g the position of the node in the graph.
*/
public int NodeIndex { get { return nodeIndex; } }
/** Position of the node in world space.
* \note The position is stored as an Int3, not a Vector3.
* You can convert an Int3 to a Vector3 using an explicit conversion.
* \code var v3 = (Vector3)node.position; \endcode
*/
public Int3 position;
#region Constants
/** Position of the walkable bit. \see Walkable */
const int FlagsWalkableOffset = 0;
/** Mask of the walkable bit. \see Walkable */
const uint FlagsWalkableMask = 1 << FlagsWalkableOffset;
/** Start of area bits. \see Area */
const int FlagsAreaOffset = 1;
/** Mask of area bits. \see Area */
const uint FlagsAreaMask = (131072-1) << FlagsAreaOffset;
/** Start of graph index bits. \see GraphIndex */
const int FlagsGraphOffset = 24;
/** Mask of graph index bits. \see GraphIndex */
const uint FlagsGraphMask = (256u-1) << FlagsGraphOffset;
public const uint MaxAreaIndex = FlagsAreaMask >> FlagsAreaOffset;
/** Max number of graphs-1 */
public const uint MaxGraphIndex = FlagsGraphMask >> FlagsGraphOffset;
/** Start of tag bits. \see Tag */
const int FlagsTagOffset = 19;
/** Mask of tag bits. \see Tag */
const uint FlagsTagMask = (32-1) << FlagsTagOffset;
#endregion
#region Properties
/** Holds various bitpacked variables.
*/
public uint Flags {
get {
return flags;
}
set {
flags = value;
}
}
/** Penalty cost for walking on this node. This can be used to make it harder/slower to walk over certain areas. */
public uint Penalty {
get {
return penalty;
}
set {
if (value > 0xFFFFFF)
Debug.LogWarning("Very high penalty applied. Are you sure negative values haven't underflowed?\n" +
"Penalty values this high could with long paths cause overflows and in some cases infinity loops because of that.\n" +
"Penalty value applied: "+value);
penalty = value;
}
}
/** True if the node is traversable */
public bool Walkable {
get {
return (flags & FlagsWalkableMask) != 0;
}
set {
flags = flags & ~FlagsWalkableMask | (value ? 1U : 0U) << FlagsWalkableOffset;
}
}
public uint Area {
get {
return (flags & FlagsAreaMask) >> FlagsAreaOffset;
}
set {
flags = (flags & ~FlagsAreaMask) | (value << FlagsAreaOffset);
}
}
public uint GraphIndex {
get {
return (flags & FlagsGraphMask) >> FlagsGraphOffset;
}
set {
flags = flags & ~FlagsGraphMask | value << FlagsGraphOffset;
}
}
public uint Tag {
get {
return (flags & FlagsTagMask) >> FlagsTagOffset;
}
set {
flags = flags & ~FlagsTagMask | value << FlagsTagOffset;
}
}
#endregion
public void UpdateG (Path path, PathNode pathNode) {
#if ASTAR_NO_TRAVERSAL_COST
pathNode.G = pathNode.parent.G + pathNode.cost;
#else
pathNode.G = pathNode.parent.G + pathNode.cost + path.GetTraversalCost(this);
#endif
}
public virtual void UpdateRecursiveG (Path path, PathNode pathNode, PathHandler handler) {
//Simple but slow default implementation
UpdateG(path, pathNode);
handler.PushNode(pathNode);
GetConnections(delegate(GraphNode other) {
PathNode otherPN = handler.GetPathNode(other);
if (otherPN.parent == pathNode && otherPN.pathID == handler.PathID) other.UpdateRecursiveG(path, otherPN, handler);
});
}
public virtual void FloodFill (Stack<GraphNode> stack, uint region) {
//Simple but slow default implementation
GetConnections(delegate(GraphNode other) {
if (other.Area != region) {
other.Area = region;
stack.Push(other);
}
});
}
/** Calls the delegate with all connections from this node */
public abstract void GetConnections (GraphNodeDelegate del);
public abstract void AddConnection (GraphNode node, uint cost);
public abstract void RemoveConnection (GraphNode node);
/** Remove all connections from this node.
* \param alsoReverse if true, neighbours will be requested to remove connections to this node.
*/
public abstract void ClearConnections (bool alsoReverse);
/** Checks if this node has a connection to the specified node */
public virtual bool ContainsConnection (GraphNode node) {
// Simple but slow default implementation
bool contains = false;
GetConnections(neighbour => {
contains |= neighbour == node;
});
return contains;
}
/** Recalculates all connection costs from this node.
* Depending on the node type, this may or may not be supported.
* Nothing will be done if the operation is not supported
* \todo Use interface?
*/
public virtual void RecalculateConnectionCosts () {
}
/** Add a portal from this node to the specified node.
* This function should add a portal to the left and right lists which is connecting the two nodes (\a this and \a other).
*
* \param other The node which is on the other side of the portal (strictly speaking it does not actually have to be on the other side of the portal though).
* \param left List of portal points on the left side of the funnel
* \param right List of portal points on the right side of the funnel
* \param backwards If this is true, the call was made on a node with the \a other node as the node before this one in the path.
* In this case you may choose to do nothing since a similar call will be made to the \a other node with this node referenced as \a other (but then with backwards = true).
* You do not have to care about switching the left and right lists, that is done for you already.
*
* \returns True if the call was deemed successful. False if some unknown case was encountered and no portal could be added.
* If both calls to node1.GetPortal (node2,...) and node2.GetPortal (node1,...) return false, the funnel modifier will fall back to adding to the path
* the positions of the node.
*
* The default implementation simply returns false.
*
* This function may add more than one portal if necessary.
*
* \see http://digestingduck.blogspot.se/2010/03/simple-stupid-funnel-algorithm.html
*/
public virtual bool GetPortal (GraphNode other, List<Vector3> left, List<Vector3> right, bool backwards) {
return false;
}
/** Open the node */
public abstract void Open (Path path, PathNode pathNode, PathHandler handler);
public virtual void SerializeNode (GraphSerializationContext ctx) {
//Write basic node data.
ctx.writer.Write(Penalty);
ctx.writer.Write(Flags);
}
public virtual void DeserializeNode (GraphSerializationContext ctx) {
Penalty = ctx.reader.ReadUInt32();
Flags = ctx.reader.ReadUInt32();
// Set the correct graph index (which might have changed, e.g if loading additively)
GraphIndex = ctx.graphIndex;
}
/** Used to serialize references to other nodes e.g connections.
* Use the GraphSerializationContext.GetNodeIdentifier and
* GraphSerializationContext.GetNodeFromIdentifier methods
* for serialization and deserialization respectively.
*
* Nodes must override this method and serialize their connections.
* Graph generators do not need to call this method, it will be called automatically on all
* nodes at the correct time by the serializer.
*/
public virtual void SerializeReferences (GraphSerializationContext ctx) {
}
/** Used to deserialize references to other nodes e.g connections.
* Use the GraphSerializationContext.GetNodeIdentifier and
* GraphSerializationContext.GetNodeFromIdentifier methods
* for serialization and deserialization respectively.
*
* Nodes must override this method and serialize their connections.
* Graph generators do not need to call this method, it will be called automatically on all
* nodes at the correct time by the serializer.
*/
public virtual void DeserializeReferences (GraphSerializationContext ctx) {
}
}
public abstract class MeshNode : GraphNode {
protected MeshNode (AstarPath astar) : base(astar) {
}
public GraphNode[] connections;
public uint[] connectionCosts;
public abstract Int3 GetVertex (int i);
public abstract int GetVertexCount ();
public abstract Vector3 ClosestPointOnNode (Vector3 p);
public abstract Vector3 ClosestPointOnNodeXZ (Vector3 p);
public override void ClearConnections (bool alsoReverse) {
// Remove all connections to this node from our neighbours
if (alsoReverse && connections != null) {
for (int i = 0; i < connections.Length; i++) {
connections[i].RemoveConnection(this);
}
}
connections = null;
connectionCosts = null;
}
public override void GetConnections (GraphNodeDelegate del) {
if (connections == null) return;
for (int i = 0; i < connections.Length; i++) del(connections[i]);
}
public override void FloodFill (Stack<GraphNode> stack, uint region) {
//Faster, more specialized implementation to override the slow default implementation
if (connections == null) return;
// Iterate through all connections, set the area and push the neighbour to the stack
// This is a simple DFS (https://en.wikipedia.org/wiki/Depth-first_search)
for (int i = 0; i < connections.Length; i++) {
GraphNode other = connections[i];
if (other.Area != region) {
other.Area = region;
stack.Push(other);
}
}
}
public override bool ContainsConnection (GraphNode node) {
for (int i = 0; i < connections.Length; i++) if (connections[i] == node) return true;
return false;
}
public override void UpdateRecursiveG (Path path, PathNode pathNode, PathHandler handler) {
UpdateG(path, pathNode);
handler.PushNode(pathNode);
for (int i = 0; i < connections.Length; i++) {
GraphNode other = connections[i];
PathNode otherPN = handler.GetPathNode(other);
if (otherPN.parent == pathNode && otherPN.pathID == handler.PathID) {
other.UpdateRecursiveG(path, otherPN, handler);
}
}
}
/** Add a connection from this node to the specified node.
* If the connection already exists, the cost will simply be updated and
* no extra connection added.
*
* \note Only adds a one-way connection. Consider calling the same function on the other node
* to get a two-way connection.
*/
public override void AddConnection (GraphNode node, uint cost) {
if (node == null) throw new System.ArgumentNullException();
// Check if we already have a connection to the node
if (connections != null) {
for (int i = 0; i < connections.Length; i++) {
if (connections[i] == node) {
// Just update the cost for the existing connection
connectionCosts[i] = cost;
return;
}
}
}
// Create new arrays which include the new connection
int connLength = connections != null ? connections.Length : 0;
var newconns = new GraphNode[connLength+1];
var newconncosts = new uint[connLength+1];
for (int i = 0; i < connLength; i++) {
newconns[i] = connections[i];
newconncosts[i] = connectionCosts[i];
}
newconns[connLength] = node;
newconncosts[connLength] = cost;
connections = newconns;
connectionCosts = newconncosts;
}
/** Removes any connection from this node to the specified node.
* If no such connection exists, nothing will be done.
*
* \note This only removes the connection from this node to the other node.
* You may want to call the same function on the other node to remove its eventual connection
* to this node.
*/
public override void RemoveConnection (GraphNode node) {
if (connections == null) return;
// Iterate through all connections and check if there are any to the node
for (int i = 0; i < connections.Length; i++) {
if (connections[i] == node) {
// Create new arrays which have the specified node removed
int connLength = connections.Length;
var newconns = new GraphNode[connLength-1];
var newconncosts = new uint[connLength-1];
for (int j = 0; j < i; j++) {
newconns[j] = connections[j];
newconncosts[j] = connectionCosts[j];
}
for (int j = i+1; j < connLength; j++) {
newconns[j-1] = connections[j];
newconncosts[j-1] = connectionCosts[j];
}
connections = newconns;
connectionCosts = newconncosts;
return;
}
}
}
/** Checks if \a p is inside the node in XZ space
*
* The default implementation uses XZ space and is in large part got from the website linked below
* \author http://unifycommunity.com/wiki/index.php?title=PolyContainsPoint (Eric5h5)
*
* The TriangleMeshNode overrides this and implements faster code for that case.
*/
public virtual bool ContainsPoint (Int3 p) {
bool inside = false;
int count = GetVertexCount();
for (int i = 0, j = count-1; i < count; j = i++) {
if (((GetVertex(i).z <= p.z && p.z < GetVertex(j).z) || (GetVertex(j).z <= p.z && p.z < GetVertex(i).z)) &&
(p.x < (GetVertex(j).x - GetVertex(i).x) * (p.z - GetVertex(i).z) / (GetVertex(j).z - GetVertex(i).z) + GetVertex(i).x))
inside = !inside;
}
return inside;
}
public override void SerializeReferences (GraphSerializationContext ctx) {
if (connections == null) {
ctx.writer.Write(-1);
} else {
ctx.writer.Write(connections.Length);
for (int i = 0; i < connections.Length; i++) {
ctx.SerializeNodeReference(connections[i]);
ctx.writer.Write(connectionCosts[i]);
}
}
}
public override void DeserializeReferences (GraphSerializationContext ctx) {
int count = ctx.reader.ReadInt32();
if (count == -1) {
connections = null;
connectionCosts = null;
} else {
connections = new GraphNode[count];
connectionCosts = new uint[count];
for (int i = 0; i < count; i++) {
connections[i] = ctx.DeserializeNodeReference();
connectionCosts[i] = ctx.reader.ReadUInt32();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using log4net;
using Mail2Bug.ExceptionClasses;
using Mail2Bug.Helpers;
using Mail2Bug.MessageProcessingStrategies;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
namespace Mail2Bug.WorkItemManagement
{
public class TFSWorkItemManager : IWorkItemManager, IDisposable
{
public SortedList<string, int> WorkItemsCache { get; private set; }
public TFSWorkItemManager(Config.InstanceConfig config)
{
ValidateConfig(config);
_config = config;
// Init TFS service objects
_tfsServer = ConnectToTfsCollection();
Logger.InfoFormat("Connected to TFS. Getting TFS WorkItemStore");
_tfsStore = _tfsServer.GetService<WorkItemStore>();
if (_tfsStore == null)
{
Logger.ErrorFormat("Cannot initialize TFS Store");
throw new Exception("Cannot initialize TFS Store");
}
Logger.InfoFormat("Geting TFS Project");
_tfsProject = _tfsStore.Projects[config.TfsServerConfig.Project];
Logger.InfoFormat("Initializing WorkItems Cache");
InitWorkItemsCache();
_nameResolver = InitNameResolver();
}
private TfsTeamProjectCollection ConnectToTfsCollection()
{
var tfsCredentials = GetTfsCredentials();
foreach (var credentials in tfsCredentials)
{
try
{
Logger.InfoFormat("Connecting to TFS {0} using {1} credentials", _config.TfsServerConfig.CollectionUri, credentials);
var tfsServer = new TfsTeamProjectCollection(new Uri(_config.TfsServerConfig.CollectionUri), credentials);
tfsServer.EnsureAuthenticated();
Logger.InfoFormat("Successfully connected to TFS");
return tfsServer;
}
catch (Exception ex)
{
Logger.WarnFormat("TFS connection attempt failed.\n Exception: {0}", ex);
}
}
Logger.ErrorFormat("All TFS connection attempts failed");
throw new Exception("Cannot connect to TFS");
}
/// <summary>
/// Depending on the specific setup of the TFS server, it may or may not accept credentials of specific type. To accommodate for that
/// without making the configuration more complicated (by making the user explicitly set which type of credentials to use), we just
/// provide a list of all the relevant credential types we support in order of priority, and when connecting to TFS, we can try them
/// in order and just go with the first one that succeeds.
///
/// If ServiceIdentityUsername and ServiceIdentityPasswordFile are set correctly, then we'll try to use those credentials first. Even
/// then, though, they can be wrapped in different ways (e.g. SimpleWebTokenCredneitals, WindowsCredentials), and different servers
/// may prefer one over the other.
///
/// As a last resort, we always try the default credentials as well
/// </summary>
private IEnumerable<TfsClientCredentials> GetTfsCredentials()
{
var credentials = new List<TfsClientCredentials>();
credentials.AddRange(GetOAuthCredentials());
credentials.AddRange(GetServiceIdentityCredentials());
credentials.Add(new TfsClientCredentials(true));
return credentials;
}
private IEnumerable<TfsClientCredentials> GetOAuthCredentials()
{
try
{
var usernameAndPassword = GetUsernameAndPasswordFromConfig();
if (usernameAndPassword == null ||
string.IsNullOrEmpty(_config.TfsServerConfig.OAuthClientId) ||
string.IsNullOrEmpty(_config.TfsServerConfig.OAuthContext) ||
string.IsNullOrEmpty(_config.TfsServerConfig.OAuthResourceId))
{
return new List<TfsClientCredentials>();
}
var userCredential = new UserCredential(usernameAndPassword.Item1, usernameAndPassword.Item2);
var authContext = new AuthenticationContext(_config.TfsServerConfig.OAuthContext);
var result = authContext.AcquireToken(_config.TfsServerConfig.OAuthResourceId, _config.TfsServerConfig.OAuthClientId, userCredential);
var oauthToken = new OAuthTokenCredential(result.AccessToken);
return new List<TfsClientCredentials>()
{
new TfsClientCredentials(oauthToken)
};
}
catch (Exception ex)
{
Logger.WarnFormat("Error trying to generate OAuth Token for TFS connection\n{0}", ex);
return new List<TfsClientCredentials>();
}
}
private IEnumerable<TfsClientCredentials> GetServiceIdentityCredentials()
{
var usernameAndPassword = GetUsernameAndPasswordFromConfig();
if (usernameAndPassword == null)
{
return new List<TfsClientCredentials>();
}
return new List<TfsClientCredentials>
{
new TfsClientCredentials(
new SimpleWebTokenCredential(usernameAndPassword.Item1, usernameAndPassword.Item2)),
new TfsClientCredentials(
new WindowsCredential(
new NetworkCredential(usernameAndPassword.Item1, usernameAndPassword.Item2)))
};
}
private Tuple<string,string> GetUsernameAndPasswordFromConfig()
{
if (string.IsNullOrWhiteSpace(_config.TfsServerConfig.ServiceIdentityUsername)
|| string.IsNullOrWhiteSpace(_config.TfsServerConfig.ServiceIdentityPasswordFile))
{
return null;
}
if (!File.Exists(_config.TfsServerConfig.ServiceIdentityPasswordFile))
{
throw new BadConfigException("ServiceIdentityPasswordFile", "Password file doesn't exist");
}
return new Tuple<string, string>(_config.TfsServerConfig.ServiceIdentityUsername,
DPAPIHelper.ReadDataFromFile(_config.TfsServerConfig.ServiceIdentityPasswordFile));
}
public void AttachFiles(int workItemId, List<string> fileList)
{
if (workItemId <= 0) return;
try
{
WorkItem workItem = _tfsStore.GetWorkItem(workItemId);
workItem.Open();
fileList.ForEach(file => workItem.Attachments.Add(new Attachment(file)));
ValidateAndSaveWorkItem(workItem);
}
catch (Exception exception)
{
Logger.Error(exception.ToString());
}
}
/// <param name="values">The list of fields and their desired values to apply to the work item</param>
/// <returns>Work item ID of the newly created work item</returns>
public int CreateWorkItem(Dictionary<string, string> values)
{
if (values == null)
{
throw new ArgumentNullException("values", "Must supply field values when creating new work item");
}
//create a work item
var workItemType = _tfsProject.WorkItemTypes[_config.TfsServerConfig.WorkItemTemplate];
var workItem = new WorkItem(workItemType);
workItem.Open();
foreach (var key in values.Keys)
{
TryApplyFieldValue(workItem, key, values[key]);
}
// Workaround for TFS issue - if you change the "Assigned To" field, and then you change the "Activated by" field, the "Assigned To" field reverts
// to its original setting. To prevent that, we reapply the "Assigned To" field in case it's in the list of values to change.
if (values.ContainsKey(AssignedToFieldKey))
{
TryApplyFieldValue(workItem, AssignedToFieldKey, values[AssignedToFieldKey]);
}
ValidateAndSaveWorkItem(workItem);
CacheWorkItem(workItem);
return workItem.Id;
}
/// <param name="workItemId">The ID of the work item to modify </param>
/// <param name="comment">Comment to add to description</param>
/// <param name="values">List of fields to change</param>
public void ModifyWorkItem(int workItemId, string comment, Dictionary<string, string> values)
{
if (workItemId <= 0) return;
var workItem = _tfsStore.GetWorkItem(workItemId);
workItem.Open();
workItem.History = comment.Replace("\n", "<br>");
foreach (var key in values.Keys)
{
TryApplyFieldValue(workItem, key, values[key]);
}
ValidateAndSaveWorkItem(workItem);
workItem.Save();
}
#region Work item caching
public void CacheWorkItem(int workItemId)
{
if (WorkItemsCache.ContainsValue(workItemId)) return; // Work item already cached - nothing to do
// It is important that we don't just get the conversation ID from the caller and update the cache with the work item
// ID and conversation ID, because if the work item already exists, the conversation ID will be different (probably shorter
// than the one the caller currently has)
// That's why we get the work item from TFS and get the conversation ID from there
CacheWorkItem(_tfsStore.GetWorkItem(workItemId));
}
/// <returns>Sorted List of FieldValue's with ConversationIndex as the key</returns>
private void InitWorkItemsCache()
{
Logger.InfoFormat("Initializing work items cache");
WorkItemsCache = new SortedList<string, int>();
//search TFS to get list
var itemsToCache = _tfsStore.Query(_config.TfsServerConfig.CacheQuery);
Logger.InfoFormat("{0} items retrieved by TFS cache query", itemsToCache.Count);
foreach (WorkItem workItem in itemsToCache)
{
try
{
CacheWorkItem(workItem);
}
catch (Exception ex)
{
Logger.ErrorFormat("Exception caught while caching work item with id {0}\n{1}", workItem.Id, ex);
}
}
}
private void CacheWorkItem(WorkItem workItem)
{
var keyField = _config.WorkItemSettings.ConversationIndexFieldName;
if (!workItem.Fields.Contains(keyField))
{
Logger.WarnFormat("Item {0} doesn't contain the key field {1}. Not caching", workItem.Id, keyField);
return;
}
var keyFieldValue = workItem.Fields[keyField].Value.ToString().Trim();
Logger.DebugFormat("Work item {0} conversation ID is {1}", workItem.Id, keyFieldValue);
if (string.IsNullOrEmpty(keyFieldValue))
{
Logger.WarnFormat("Problem caching work item {0}. Field '{1}' is empty - using ID instead.", workItem.Id, keyField);
WorkItemsCache[workItem.Id.ToString(CultureInfo.InvariantCulture)] = workItem.Id;
}
WorkItemsCache[keyFieldValue] = workItem.Id;
}
#endregion
public INameResolver GetNameResolver()
{
return _nameResolver;
}
private static void ValidateAndSaveWorkItem(WorkItem workItem)
{
if (!workItem.IsValid())
{
var invalidFields = workItem.Validate();
var sb = new StringBuilder();
sb.AppendLine("Can't save item because the following fields are invalid: ");
foreach (Field field in invalidFields)
{
sb.AppendFormat("{0}: '{1}'", field.Name, field.Value).AppendLine();
}
Logger.ErrorFormat(sb.ToString());
return;
}
workItem.Save();
}
private NameResolver InitNameResolver()
{
var workItemType = _tfsProject.WorkItemTypes[_config.TfsServerConfig.WorkItemTemplate];
var fieldDef = workItemType.FieldDefinitions[_config.TfsServerConfig.NamesListFieldName];
return new NameResolver(fieldDef.AllowedValues.Cast<string>());
}
/// <summary>
/// Try to apply the value for a specific field
/// </summary>
/// <param name="workItem">The work item to which we'll try to apply the value</param>
/// <param name="key">The field to which the value should be applied</param>
/// <param name="value">The actual value</param>
private static void TryApplyFieldValue(WorkItem workItem, string key, string value)
{
try
{
// Take the default value from the workItem - use empty string if it's null
var field = workItem.Fields[key];
var defaultFieldValue = field.Value ?? "";
if (value == null)
{
Logger.ErrorFormat("Attempting to set the value of {0} to null", key);
return;
}
if (field.FieldDefinition.FieldType == FieldType.Html)
{
value = value.Replace("\n", "<br>");
}
field.Value = value;
// If this value is not valid, try to "guess" the value from the allowed values list
if (!field.IsValid)
{
Logger.WarnFormat("'{0}' is an invalid value for {1}. Trying to find approximate value.", value, key);
var approximateValue = GetApproximateAllowedValue(field, value);
Logger.InfoFormat("Approximate value is {0}", approximateValue);
field.Value = approximateValue;
}
// Couldn't approximate the value either - give up
if (!field.IsValid)
{
Logger.ErrorFormat("Attempt to set field value of {0}; reverting to default {1}", key, defaultFieldValue);
field.Value = defaultFieldValue;
}
}
catch (FieldDefinitionNotExistException ex)
{
Logger.ErrorFormat("Exception caught while trying to set value of field '{0}'\n{1}", key, ex);
}
}
// If this field has a list of allowed values, returns the first allowed value that begins
// with 'value'. If not such approximate value is found, returns null.
private static string GetApproximateAllowedValue(Field field, string value)
{
if (!field.HasAllowedValuesList)
{
return null;
}
var allowedValues = field.AllowedValues.Cast<string>();
var relevantValues = allowedValues.Where(x => x.StartsWith(value));
return relevantValues.FirstOrDefault();
}
public void Dispose()
{
_tfsServer.Dispose();
}
~TFSWorkItemManager()
{
Dispose();
}
#region Config validation
private static void ValidateConfig(Config.InstanceConfig config)
{
if (config == null) throw new ArgumentNullException("config");
// Temp variable used for shorthand writing below
var tfsConfig = config.TfsServerConfig;
ValidateConfigString(tfsConfig.CollectionUri, "TfsServerConfig.CollectionUri");
ValidateConfigString(tfsConfig.Project, "TfsServerConfig.Project");
ValidateConfigString(tfsConfig.WorkItemTemplate, "TfsServerConfig.WorkItemTemplate");
ValidateConfigString(tfsConfig.CacheQuery, "TfsServerConfig.CacheQuery");
ValidateConfigString(tfsConfig.NamesListFieldName, "TfsServerConfig.NamesListFieldName");
ValidateConfigString(config.WorkItemSettings.ConversationIndexFieldName,
"WorkItemSettings.ConversationIndexFieldName");
}
// ReSharper disable UnusedParameter.Local
private static void ValidateConfigString(string value, string configValueName)
// ReSharper restore UnusedParameter.Local
{
if (string.IsNullOrEmpty(value)) throw new BadConfigException(configValueName);
}
#endregion
#region Consts
private const string AssignedToFieldKey = "Assigned To";
#endregion
private readonly WorkItemStore _tfsStore;
private readonly Project _tfsProject;
private readonly NameResolver _nameResolver;
private readonly Config.InstanceConfig _config;
private static readonly ILog Logger = LogManager.GetLogger(typeof(TFSWorkItemManager));
private readonly TfsTeamProjectCollection _tfsServer;
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Versions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.TodoComments
{
internal partial class TodoCommentIncrementalAnalyzer : IIncrementalAnalyzer
{
public const string Name = "Todo Comment Document Worker";
private readonly TodoCommentIncrementalAnalyzerProvider _owner;
private readonly Workspace _workspace;
private readonly IOptionService _optionService;
private readonly TodoCommentTokens _todoCommentTokens;
private readonly TodoCommentState _state;
public TodoCommentIncrementalAnalyzer(Workspace workspace, IOptionService optionService, TodoCommentIncrementalAnalyzerProvider owner, TodoCommentTokens todoCommentTokens)
{
_workspace = workspace;
_optionService = optionService;
_owner = owner;
_todoCommentTokens = todoCommentTokens;
_state = new TodoCommentState();
}
public Task DocumentResetAsync(Document document, CancellationToken cancellationToken)
{
// remove cache
_state.Remove(document.Id);
return _state.PersistAsync(document, new Data(VersionStamp.Default, VersionStamp.Default, ImmutableArray<ITaskItem>.Empty), cancellationToken);
}
public async Task AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken)
{
Contract.ThrowIfFalse(document.IsFromPrimaryBranch());
// it has an assumption that this will not be called concurrently for same document.
// in fact, in current design, it won't be even called concurrently for different documents.
// but, can be called concurrently for different documents in future if we choose to.
if (!_optionService.GetOption(InternalFeatureOnOffOptions.TodoComments))
{
return;
}
// use tree version so that things like compiler option changes are considered
var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false);
var syntaxVersion = await document.GetSyntaxVersionAsync(cancellationToken).ConfigureAwait(false);
var existingData = await _state.TryGetExistingDataAsync(document, cancellationToken).ConfigureAwait(false);
if (existingData != null)
{
// check whether we can use the data as it is (can happen when re-using persisted data from previous VS session)
if (CheckVersions(document, textVersion, syntaxVersion, existingData))
{
Contract.Requires(_workspace == document.Project.Solution.Workspace);
RaiseTaskListUpdated(_workspace, document.Id, existingData.Items);
return;
}
}
var service = document.GetLanguageService<ITodoCommentService>();
if (service == null)
{
return;
}
var comments = await service.GetTodoCommentsAsync(document, _todoCommentTokens.GetTokens(_workspace), cancellationToken).ConfigureAwait(false);
var items = await CreateItemsAsync(document, comments, cancellationToken).ConfigureAwait(false);
var data = new Data(textVersion, syntaxVersion, items);
await _state.PersistAsync(document, data, cancellationToken).ConfigureAwait(false);
// * NOTE * cancellation can't throw after this point.
if (existingData == null || existingData.Items.Length > 0 || data.Items.Length > 0)
{
Contract.Requires(_workspace == document.Project.Solution.Workspace);
RaiseTaskListUpdated(_workspace, document.Id, data.Items);
}
}
private async Task<ImmutableArray<ITaskItem>> CreateItemsAsync(Document document, IList<TodoComment> comments, CancellationToken cancellationToken)
{
var items = ImmutableArray.CreateBuilder<ITaskItem>();
if (comments != null)
{
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var syntaxTree = document.SupportsSyntaxTree ? await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false) : null;
foreach (var comment in comments)
{
items.Add(CreateItem(document, text, syntaxTree, comment));
}
}
return items.ToImmutable();
}
private ITaskItem CreateItem(Document document, SourceText text, SyntaxTree tree, TodoComment comment)
{
var textSpan = new TextSpan(comment.Position, 0);
var location = tree == null ? Location.Create(document.FilePath, textSpan, text.Lines.GetLinePositionSpan(textSpan)) : tree.GetLocation(textSpan);
var originalLineInfo = location.GetLineSpan();
var mappedLineInfo = location.GetMappedLineSpan();
return new TodoTaskItem(
comment.Descriptor.Priority,
comment.Message,
document.Project.Solution.Workspace,
document.Id,
mappedLine: mappedLineInfo.StartLinePosition.Line,
originalLine: originalLineInfo.StartLinePosition.Line,
mappedColumn: mappedLineInfo.StartLinePosition.Character,
originalColumn: originalLineInfo.StartLinePosition.Character,
mappedFilePath: mappedLineInfo.HasMappedPath ? mappedLineInfo.Path : null,
originalFilePath: document.FilePath);
}
public ImmutableArray<ITaskItem> GetTodoItems(Workspace workspace, DocumentId id, CancellationToken cancellationToken)
{
var document = workspace.CurrentSolution.GetDocument(id);
if (document == null)
{
return ImmutableArray<ITaskItem>.Empty;
}
// TODO let's think about what to do here. for now, let call it synchronously. also, there is no actual asynch-ness for the
// TryGetExistingDataAsync, API just happen to be async since our persistent API is async API. but both caller and implementor are
// actually not async.
var existingData = _state.TryGetExistingDataAsync(document, cancellationToken).WaitAndGetResult(cancellationToken);
if (existingData == null)
{
return ImmutableArray<ITaskItem>.Empty;
}
return existingData.Items;
}
private static bool CheckVersions(Document document, VersionStamp textVersion, VersionStamp syntaxVersion, Data existingData)
{
// first check full version to see whether we can reuse data in same session, if we can't, check timestamp only version to see whether
// we can use it cross-session.
return document.CanReusePersistedTextVersion(textVersion, existingData.TextVersion) &&
document.CanReusePersistedSyntaxTreeVersion(syntaxVersion, existingData.SyntaxVersion);
}
internal ImmutableArray<ITaskItem> GetItems_TestingOnly(DocumentId documentId)
{
return _state.GetItems_TestingOnly(documentId);
}
private void RaiseTaskListUpdated(Workspace workspace, DocumentId documentId, ImmutableArray<ITaskItem> items)
{
if (_owner != null)
{
_owner.RaiseTaskListUpdated(documentId, workspace, documentId.ProjectId, documentId, items);
}
}
public void RemoveDocument(DocumentId documentId)
{
_state.Remove(documentId);
RaiseTaskListUpdated(_workspace, documentId, ImmutableArray<ITaskItem>.Empty);
}
public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e)
{
return e.Option == TodoCommentOptions.TokenList;
}
private class Data
{
public readonly VersionStamp TextVersion;
public readonly VersionStamp SyntaxVersion;
public readonly ImmutableArray<ITaskItem> Items;
public Data(VersionStamp textVersion, VersionStamp syntaxVersion, ImmutableArray<ITaskItem> items)
{
this.TextVersion = textVersion;
this.SyntaxVersion = syntaxVersion;
this.Items = items;
}
}
#region not used
public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public Task AnalyzeProjectAsync(Project project, bool semanticsChanged, CancellationToken cancellationToken)
{
return SpecializedTasks.EmptyTask;
}
public void RemoveProject(ProjectId projectId)
{
}
#endregion
}
}
| |
//
// AssemblyNameReference.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2011 Jb Evain
//
// 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.Globalization;
using System.Security.Cryptography;
using System.Text;
namespace Mono.Cecil {
public class AssemblyNameReference : IMetadataScope {
string name;
string culture;
Version version;
uint attributes;
byte [] public_key;
byte [] public_key_token;
AssemblyHashAlgorithm hash_algorithm;
byte [] hash;
internal MetadataToken token;
string full_name;
public string Name {
get { return name; }
set {
name = value;
full_name = null;
}
}
public string Culture {
get { return culture; }
set {
culture = value;
full_name = null;
}
}
public Version Version {
get { return version; }
set {
version = value;
full_name = null;
}
}
public AssemblyAttributes Attributes {
get { return (AssemblyAttributes) attributes; }
set { attributes = (uint) value; }
}
public bool HasPublicKey {
get { return attributes.GetAttributes ((uint) AssemblyAttributes.PublicKey); }
set { attributes = attributes.SetAttributes ((uint) AssemblyAttributes.PublicKey, value); }
}
public bool IsSideBySideCompatible {
get { return attributes.GetAttributes ((uint) AssemblyAttributes.SideBySideCompatible); }
set { attributes = attributes.SetAttributes ((uint) AssemblyAttributes.SideBySideCompatible, value); }
}
public bool IsRetargetable {
get { return attributes.GetAttributes ((uint) AssemblyAttributes.Retargetable); }
set { attributes = attributes.SetAttributes ((uint) AssemblyAttributes.Retargetable, value); }
}
public bool IsWindowsRuntime {
get { return attributes.GetAttributes ((uint) AssemblyAttributes.WindowsRuntime); }
set { attributes = attributes.SetAttributes ((uint) AssemblyAttributes.WindowsRuntime, value); }
}
public byte [] PublicKey {
get { return public_key ?? Empty<byte>.Array; }
set {
public_key = value;
HasPublicKey = !public_key.IsNullOrEmpty ();
public_key_token = Empty<byte>.Array;
full_name = null;
}
}
public byte [] PublicKeyToken {
get {
if (public_key_token.IsNullOrEmpty () && !public_key.IsNullOrEmpty ()) {
var hash = HashPublicKey ();
// we need the last 8 bytes in reverse order
byte[] local_public_key_token = new byte [8];
Array.Copy (hash, (hash.Length - 8), local_public_key_token, 0, 8);
Array.Reverse (local_public_key_token, 0, 8);
public_key_token = local_public_key_token; // publish only once finished (required for thread-safety)
}
return public_key_token ?? Empty<byte>.Array;
}
set {
public_key_token = value;
full_name = null;
}
}
byte [] HashPublicKey ()
{
HashAlgorithm algorithm;
switch (hash_algorithm) {
case AssemblyHashAlgorithm.Reserved:
#if SILVERLIGHT
throw new NotSupportedException ();
#else
algorithm = MD5.Create ();
break;
#endif
default:
// None default to SHA1
#if SILVERLIGHT
algorithm = new SHA1Managed ();
break;
#else
algorithm = SHA1.Create ();
break;
#endif
}
using (algorithm)
return algorithm.ComputeHash (public_key);
}
public virtual MetadataScopeType MetadataScopeType {
get { return MetadataScopeType.AssemblyNameReference; }
}
public string FullName {
get {
if (full_name != null)
return full_name;
const string sep = ", ";
var builder = new StringBuilder ();
builder.Append (name);
if (version != null) {
builder.Append (sep);
builder.Append ("Version=");
builder.Append (version.ToString ());
}
builder.Append (sep);
builder.Append ("Culture=");
builder.Append (string.IsNullOrEmpty (culture) ? "neutral" : culture);
builder.Append (sep);
builder.Append ("PublicKeyToken=");
var pk_token = PublicKeyToken;
if (!pk_token.IsNullOrEmpty () && pk_token.Length > 0) {
for (int i = 0 ; i < pk_token.Length ; i++) {
builder.Append (pk_token [i].ToString ("x2"));
}
} else
builder.Append ("null");
return full_name = builder.ToString ();
}
}
public static AssemblyNameReference Parse (string fullName)
{
if (fullName == null)
throw new ArgumentNullException ("fullName");
if (fullName.Length == 0)
throw new ArgumentException ("Name can not be empty");
var name = new AssemblyNameReference ();
var tokens = fullName.Split (',');
for (int i = 0; i < tokens.Length; i++) {
var token = tokens [i].Trim ();
if (i == 0) {
name.Name = token;
continue;
}
var parts = token.Split ('=');
if (parts.Length != 2)
throw new ArgumentException ("Malformed name");
switch (parts [0].ToLowerInvariant ()) {
case "version":
name.Version = new Version (parts [1]);
break;
case "culture":
name.Culture = parts [1];
break;
case "publickeytoken":
var pk_token = parts [1];
if (pk_token == "null")
break;
name.PublicKeyToken = new byte [pk_token.Length / 2];
for (int j = 0; j < name.PublicKeyToken.Length; j++)
name.PublicKeyToken [j] = Byte.Parse (pk_token.Substring (j * 2, 2), NumberStyles.HexNumber);
break;
}
}
return name;
}
public AssemblyHashAlgorithm HashAlgorithm {
get { return hash_algorithm; }
set { hash_algorithm = value; }
}
public virtual byte [] Hash {
get { return hash; }
set { hash = value; }
}
public MetadataToken MetadataToken {
get { return token; }
set { token = value; }
}
internal AssemblyNameReference ()
{
}
public AssemblyNameReference (string name, Version version)
{
if (name == null)
throw new ArgumentNullException ("name");
this.name = name;
this.version = version;
this.hash_algorithm = AssemblyHashAlgorithm.None;
this.token = new MetadataToken (TokenType.AssemblyRef);
}
public override string ToString ()
{
return this.FullName;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using SIL.Keyboarding;
using SIL.Reporting;
using SIL.WritingSystems;
namespace SIL.Windows.Forms.WritingSystems
{
public partial class WSSortControl : UserControl
{
private WritingSystemSetupModel _model;
private readonly Hashtable _sortUsingValueMap;
private Hashtable _languageOptionMap;
private bool _changingModel;
private IKeyboardDefinition _defaultKeyboard;
private string _defaultFontName;
private float _defaultFontSize;
public event EventHandler UserWantsHelpWithCustomSorting;
public WSSortControl()
{
InitializeComponent();
_sortUsingValueMap = new Hashtable();
foreach (KeyValuePair<string, string> sortUsingOption in WritingSystemSetupModel.SortUsingOptions)
{
int index = _sortUsingComboBox.Items.Add(sortUsingOption.Value);
_sortUsingValueMap[sortUsingOption.Key] = index;
_sortUsingValueMap[index] = sortUsingOption.Key;
}
_defaultFontName = _sortRulesTextBox.Font.Name;
_defaultFontSize = _sortRulesTextBox.Font.SizeInPoints;
// default text for testing the sort rules
_testSortText.Text = string.Join(Environment.NewLine, "pear", "apple", "orange", "mango", "peach");
}
public void BindToModel(WritingSystemSetupModel model)
{
if (_model != null)
{
_model.SelectionChanged -= ModelSelectionChanged;
_model.CurrentItemUpdated -= ModelCurrentItemUpdated;
}
_model = model;
if (_model != null)
{
UpdateFromModel();
_model.SelectionChanged += ModelSelectionChanged;
_model.CurrentItemUpdated += ModelCurrentItemUpdated;
}
this.Disposed += OnDisposed;
}
void OnDisposed(object sender, EventArgs e)
{
if (_model != null)
{
_model.SelectionChanged -= ModelSelectionChanged;
_model.CurrentItemUpdated -= ModelCurrentItemUpdated;
}
}
private void ModelSelectionChanged(object sender, EventArgs e)
{
UpdateFromModel();
}
private void ModelCurrentItemUpdated(object sender, EventArgs e)
{
if (_changingModel)
{
return;
}
UpdateFromModel();
}
private void UpdateFromModel()
{
if (!_model.HasCurrentSelection)
{
_sortrules_panel.Visible = false;
_languagecombo_panel.Visible = false;
Enabled = false;
return;
}
Enabled = true;
LoadLanguageChoicesFromModel();
if (_sortUsingValueMap.ContainsKey(_model.CurrentCollationRulesType))
{
_sortUsingComboBox.SelectedIndex = (int)_sortUsingValueMap[_model.CurrentCollationRulesType];
}
else
{
_sortUsingComboBox.SelectedIndex = -1;
}
SetControlFonts();
}
private void LoadLanguageChoicesFromModel()
{
_languageComboBox.Items.Clear();
_languageOptionMap = new Hashtable();
foreach (KeyValuePair<string, string> languageOption in _model.SortLanguageOptions)
{
int index = _languageComboBox.Items.Add(languageOption.Value);
_languageOptionMap[index] = languageOption.Key;
_languageOptionMap[languageOption.Key] = index;
}
_sortUsingComboBox.SelectedIndex = -1;
}
private void _sortRulesTextBox_TextChanged(object sender, EventArgs e)
{
if (ValidateSortRules())
{
_changingModel = true;
try
{
_model.CurrentCollationRules = _sortRulesTextBox.Text;
}
finally
{
_changingModel = false;
}
}
}
private void _sortUsingComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
_sortrules_panel.Visible = false;
_languagecombo_panel.Visible = false;
if (_sortUsingComboBox.SelectedIndex == -1)
{
return;
}
string newValue = (string)_sortUsingValueMap[_sortUsingComboBox.SelectedIndex];
_changingModel = true;
try
{
_model.CurrentCollationRulesType = newValue;
}
finally
{
_changingModel = false;
}
if (newValue == "OtherLanguage")
{
_sortrules_panel.Visible = true;
_languagecombo_panel.Visible = true;
if (_languageOptionMap.ContainsKey(_model.CurrentCollationRules))
{
_languageComboBox.SelectedIndex = (int)_languageOptionMap[_model.CurrentCollationRules];
}
}
else if (newValue == "CustomSimple" || newValue == "CustomIcu")
{
_sortrules_panel.Visible = true;
_sortRulesTextBox.Text = _model.CurrentCollationRules;
}
}
private void _languageComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (_languageComboBox.SelectedIndex == -1)
{
return;
}
string newValue = (string) _languageOptionMap[_languageComboBox.SelectedIndex];
_changingModel = true;
try
{
_model.CurrentCollationRules = newValue;
}
finally
{
_changingModel = false;
}
}
private void _testSortButton_Click(object sender, EventArgs e)
{
try
{
if (ValidateSortRules())
{
_testSortResult.Text = _model.TestSort(_testSortText.Text);
}
}
catch (ApplicationException ex)
{
ErrorReport.NotifyUserOfProblem("Unable to sort test text: {0}", ex.Message);
}
}
private void SetControlFonts()
{
float fontSize = _model.CurrentDefaultFontSize;
if (fontSize <= 0 || float.IsNaN(fontSize) || float.IsInfinity(fontSize))
{
fontSize = _defaultFontSize;
}
string fontName = _model.CurrentDefaultFontName;
if (string.IsNullOrEmpty(fontName))
{
fontName = _defaultFontName;
}
Font customFont = new Font(fontName, fontSize);
_sortRulesTextBox.Font = customFont;
// We are not setting the RightToLeft property for the sort rules because the ICU syntax is inherently left-to-right.
_testSortText.Font = customFont;
_testSortText.RightToLeft = _model.CurrentRightToLeftScript ? RightToLeft.Yes : RightToLeft.No;
_testSortResult.Font = customFont;
_testSortResult.RightToLeft = _model.CurrentRightToLeftScript ? RightToLeft.Yes : RightToLeft.No;
}
private void TextControl_Enter(object sender, EventArgs e)
{
if (_model == null)
{
return;
}
_defaultKeyboard = Keyboard.Controller.ActiveKeyboard;
_model.ActivateCurrentKeyboard();
}
private void TextControl_Leave(object sender, EventArgs e)
{
if (_model == null)
{
return;
}
_defaultKeyboard.Activate();
ValidateSortRules();
}
private bool ValidateSortRules()
{
CollationDefinition cd;
switch (_model.CurrentCollationRulesType)
{
case "CustomIcu":
{
cd = new IcuRulesCollationDefinition((IcuRulesCollationDefinition)_model.CurrentDefinition.DefaultCollation)
{
IcuRules = _sortRulesTextBox.Text
};
break;
}
case "CustomSimple":
{
cd = new SimpleRulesCollationDefinition((SimpleRulesCollationDefinition)_model.CurrentDefinition.DefaultCollation)
{
SimpleRules = _sortRulesTextBox.Text
};
break;
}
default:
{
return false;
}
}
string message;
const string prefixToMessage = "SORT RULES WILL NOT BE SAVED\r\n";
if (!cd.Validate(out message))
{
_testSortResult.Text = prefixToMessage + (message ?? String.Empty);
_testSortResult.ForeColor = Color.Red;
return false;
}
if (_testSortResult.Text.StartsWith(prefixToMessage))
{
_testSortResult.Text = String.Empty;
_testSortResult.ForeColor = Color.Black;
}
return true;
}
private void OnHelpLabelClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
if (UserWantsHelpWithCustomSorting != null)
UserWantsHelpWithCustomSorting(sender, e);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading.Tasks;
namespace Orleans.Runtime.Configuration
{
/// <summary>
/// Utilities class for handling configuration.
/// </summary>
public static class ConfigUtilities
{
// Time spans are entered as a string of decimal digits, optionally followed by a unit string: "ms", "s", "m", "hr"
internal static TimeSpan ParseTimeSpan(string input, string errorMessage)
{
long unitSize;
string numberInput;
var trimmedInput = input.Trim().ToLowerInvariant();
if (trimmedInput.EndsWith("ms", StringComparison.Ordinal))
{
unitSize = 10000;
numberInput = trimmedInput.Remove(trimmedInput.Length - 2).Trim();
}
else if (trimmedInput.EndsWith("s", StringComparison.Ordinal))
{
unitSize = 1000 * 10000;
numberInput = trimmedInput.Remove(trimmedInput.Length - 1).Trim();
}
else if (trimmedInput.EndsWith("m", StringComparison.Ordinal))
{
unitSize = 60 * 1000 * 10000;
numberInput = trimmedInput.Remove(trimmedInput.Length - 1).Trim();
}
else if (trimmedInput.EndsWith("hr", StringComparison.Ordinal))
{
unitSize = 60 * 60 * 1000 * 10000L;
numberInput = trimmedInput.Remove(trimmedInput.Length - 2).Trim();
}
else
{
unitSize = 1000 * 10000; // Default is seconds
numberInput = trimmedInput;
}
decimal rawTimeSpan;
if (!decimal.TryParse(numberInput, NumberStyles.Any, CultureInfo.InvariantCulture, out rawTimeSpan))
{
throw new FormatException(errorMessage + ". Tried to parse " + input);
}
return TimeSpan.FromTicks((long)(rawTimeSpan * unitSize));
}
internal static async Task<IPAddress> ResolveIPAddress(string addrOrHost, byte[] subnet, AddressFamily family)
{
var loopback = family == AddressFamily.InterNetwork ? IPAddress.Loopback : IPAddress.IPv6Loopback;
IList<IPAddress> nodeIps;
// if the address is an empty string, just enumerate all ip addresses available
// on this node
if (string.IsNullOrEmpty(addrOrHost))
{
nodeIps = NetworkInterface.GetAllNetworkInterfaces()
.Where(iface => iface.OperationalStatus == OperationalStatus.Up)
.SelectMany(iface => iface.GetIPProperties().UnicastAddresses)
.Select(addr => addr.Address)
.Where(addr => addr.AddressFamily == family && !IPAddress.IsLoopback(addr))
.ToList();
}
else
{
// Fix StreamFilteringTests_SMS tests
if (addrOrHost.Equals("loopback", StringComparison.OrdinalIgnoreCase))
{
return loopback;
}
// check if addrOrHost is a valid IP address including loopback (127.0.0.0/8, ::1) and any (0.0.0.0/0, ::) addresses
IPAddress address;
if (IPAddress.TryParse(addrOrHost, out address))
{
return address;
}
// Get IP address from DNS. If addrOrHost is localhost will
// return loopback IPv4 address (or IPv4 and IPv6 addresses if OS is supported IPv6)
nodeIps = await Dns.GetHostAddressesAsync(addrOrHost);
}
var candidates = new List<IPAddress>();
foreach (var nodeIp in nodeIps.Where(x => x.AddressFamily == family))
{
// If the subnet does not match - we can't resolve this address.
// If subnet is not specified - pick smallest address deterministically.
if (subnet == null)
{
candidates.Add(nodeIp);
}
else
{
var ip = nodeIp;
if (subnet.Select((b, i) => ip.GetAddressBytes()[i] == b).All(x => x))
{
candidates.Add(nodeIp);
}
}
}
if (candidates.Count > 0)
{
return PickIPAddress(candidates);
}
var subnetStr = Utils.EnumerableToString(subnet, null, ".", false);
throw new ArgumentException("Hostname '" + addrOrHost + "' with subnet " + subnetStr + " and family " + family + " is not a valid IP address or DNS name");
}
private static IPAddress PickIPAddress(IReadOnlyList<IPAddress> candidates)
{
IPAddress chosen = null;
foreach (IPAddress addr in candidates)
{
if (chosen == null)
{
chosen = addr;
}
else
{
if (CompareIPAddresses(addr, chosen)) // pick smallest address deterministically
chosen = addr;
}
}
return chosen;
// returns true if lhs is "less" (in some repeatable sense) than rhs
static bool CompareIPAddresses(IPAddress lhs, IPAddress rhs)
{
byte[] lbytes = lhs.GetAddressBytes();
byte[] rbytes = rhs.GetAddressBytes();
if (lbytes.Length != rbytes.Length) return lbytes.Length < rbytes.Length;
// compare starting from most significant octet.
// 10.68.20.21 < 10.98.05.04
for (int i = 0; i < lbytes.Length; i++)
{
if (lbytes[i] != rbytes[i])
{
return lbytes[i] < rbytes[i];
}
}
// They're equal
return false;
}
}
/// <summary>
/// Gets the address of the local server.
/// If there are multiple addresses in the correct family in the server's DNS record, the first will be returned.
/// </summary>
/// <returns>The server's IPv4 address.</returns>
internal static IPAddress GetLocalIPAddress(AddressFamily family = AddressFamily.InterNetwork, string interfaceName = null)
{
var loopback = (family == AddressFamily.InterNetwork) ? IPAddress.Loopback : IPAddress.IPv6Loopback;
// get list of all network interfaces
NetworkInterface[] netInterfaces = NetworkInterface.GetAllNetworkInterfaces();
var candidates = new List<IPAddress>();
// loop through interfaces
for (int i = 0; i < netInterfaces.Length; i++)
{
NetworkInterface netInterface = netInterfaces[i];
if (netInterface.OperationalStatus != OperationalStatus.Up)
{
// Skip network interfaces that are not operational
continue;
}
if (!string.IsNullOrWhiteSpace(interfaceName) &&
!netInterface.Name.StartsWith(interfaceName, StringComparison.Ordinal)) continue;
bool isLoopbackInterface = (netInterface.NetworkInterfaceType == NetworkInterfaceType.Loopback);
// get list of all unicast IPs from current interface
UnicastIPAddressInformationCollection ipAddresses = netInterface.GetIPProperties().UnicastAddresses;
// loop through IP address collection
foreach (UnicastIPAddressInformation ip in ipAddresses)
{
if (ip.Address.AddressFamily == family) // Picking the first address of the requested family for now. Will need to revisit later
{
//don't pick loopback address, unless we were asked for a loopback interface
if (!(isLoopbackInterface && ip.Address.Equals(loopback)))
{
candidates.Add(ip.Address); // collect all candidates.
}
}
}
}
if (candidates.Count > 0) return PickIPAddress(candidates);
throw new OrleansException("Failed to get a local IP address.");
}
/// <summary>
/// Prints the DataConnectionString,
/// without disclosing any credential info
/// such as the Azure Storage AccountKey, SqlServer password or AWS SecretKey.
/// </summary>
/// <param name="connectionString">The connection string to print.</param>
/// <returns>The string representation of the DataConnectionString with account credential info redacted.</returns>
public static string RedactConnectionStringInfo(string connectionString)
{
string[] secretKeys =
{
"AccountKey=", // Azure Storage
"SharedAccessSignature=", // Many Azure services
"SharedAccessKey=", "SharedSecretValue=", // ServiceBus
"Password=", // SQL
"SecretKey=", "SessionToken=", // DynamoDb
};
var mark = "<--SNIP-->";
if (String.IsNullOrEmpty(connectionString)) return "null";
//if connection string format doesn't contain any secretKey, then return just <--SNIP-->
if (!secretKeys.Any(key => connectionString.Contains(key))) return mark;
string connectionInfo = connectionString;
// Remove any secret keys from connection string info written to log files
foreach (var secretKey in secretKeys)
{
int keyPos = connectionInfo.IndexOf(secretKey, StringComparison.OrdinalIgnoreCase);
if (keyPos >= 0)
{
connectionInfo = connectionInfo.Remove(keyPos + secretKey.Length) + mark;
}
}
return connectionInfo;
}
}
}
| |
// Copyright 2016 Google Inc. 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.
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.IO;
using System.Linq;
// Disable unused variable warnings.
#pragma warning disable 414
/// <summary>
/// Updates non-native versions of Unity with additional GVR library imports if those files
/// do not exist. Otherwise, if this is Unity 5.4 and there are legacy libraries or
/// AndroidManifest.xml, they are removed.
/// </summary>
[InitializeOnLoad]
public class GvrCompatibilityChecker {
// Asset subpaths.
private static string PLUGINS_ANDROID_PATH = Application.dataPath + "/Plugins/Android/";
private static string PLUGINS_IOS_PATH = Application.dataPath + "/Plugins/iOS/";
private static string ARMEABI_PATH = "libs/armeabi-v7a/";
private static string X86_PATH = "libs/x86/";
private static string IGNORE_MANIFEST_MERGE_CHECK_PATH = "GvrIgnoreManifestMergeCheck.txt";
private static string IGNORE_COMPATIBILITY_CHECK_PATH = "GvrIgnoreCompatibilityCheck.txt";
// Files for backwards compatibility.
private static string ANDROID_MANIFEST = "AndroidManifest.xml";
private static string ANDROID_MANIFEST_CARDBOARD = "AndroidManifest-Cardboard.xml";
private static string NATIVE_LIB = "libgvrunity.so";
private static string[] BACK_COMPAT_FILE_PATHS = new string[] {
PLUGINS_ANDROID_PATH + ARMEABI_PATH + NATIVE_LIB,
PLUGINS_ANDROID_PATH + X86_PATH + NATIVE_LIB,
PLUGINS_ANDROID_PATH + "gvr_android_common.aar",
PLUGINS_ANDROID_PATH + "unitygvractivity.aar",
PLUGINS_IOS_PATH + "libgvrunity.a",
PLUGINS_IOS_PATH + "CardboardAppController.h",
PLUGINS_IOS_PATH + "CardboardAppController.mm",
};
private static string[] BACK_COMPAT_DIR_PATHS = new string[] {
PLUGINS_IOS_PATH + "CardboardSDK.bundle",
PLUGINS_IOS_PATH + "GoogleKitCore.bundle",
PLUGINS_IOS_PATH + "GoogleKitDialogs.bundle",
PLUGINS_IOS_PATH + "GoogleKitHUD.bundle",
PLUGINS_IOS_PATH + "MaterialRobotoFontLoader.bundle",
};
// Files for native integration compatibility.
private static string IOS_AUDIO_LIB = "libaudioplugingvrunity.a";
// GVR backwards-compatible package.
private static string BACK_COMPAT_PACKAGE_PATH =
"/GoogleVR/GVRBackwardsCompatibility.unitypackage";
// iOS native integration-compatible package.
private static string IOS_NATIVE_COMPAT_PACKAGE_PATH =
"/GoogleVR/GVRiOSNativeCompatibility.unitypackage";
// Path elements.
private static string ASSET_PATH_PREFIX = "Assets";
private static string META_EXT = ".meta";
// Dialog text.
private static string BACK_COMPAT_FILES_FOUND_TITLE = "File Removal Required";
private static string BACK_COMPAT_FILES_FOUND_MESSAGE =
"Detected GVR libraries targeting a pre-5.4 build of Unity.\n\n" +
"The following files must be removed to avoid project compilation discrepancies:\n\n";
private static string IMPORT_REQUIRED_TITLE = "Package Import Required";
private static string IMPORT_REQUIRED_MESSAGE =
"Assets/GoogleVR/GVRBackwardsCompatibility.unitypackage must be imported for GVR to be " +
"compatible with this version of Unity, which does not have the GVR native integration.\n" +
"Please download this file from github.com/gvr-unity-sdk if it is not already in your project.";
private static string MANIFEST_UPDATE_WARNING_TITLE = "AndroidManifest.xml Merge Required";
private static string MERGE_MANIFEST_WARNING_MESSAGE =
"Please merge the existing AndroidManifest.xml with AndroidManifest-Cardboard.xml.";
private static string UNMERGE_MANIFEST_WARNING_MESSAGE =
"Please remove all Cardboard and/or Daydream-specific attributes or tags from " +
"AndroidManifest.xml. Delete this file if it consists only of a subset of " +
"AndroidManifest-Cardboard.xml and/or AndroidManifest-Daydream.xml.";
private static string PACKAGE_NOT_FOUND_TITLE = "Package not found";
private static string REENABLE_COMPATIBILITY_CHECK_TITLE = "Skipping Compatibility Checks";
private static string REENABLE_COMPATIBILITY_CHECK_MESSAGE =
"Compatibility checks can be re-enabled by deleting " + IGNORE_COMPATIBILITY_CHECK_PATH;
// Button text/
private static string CANCEL_BUTTON = "Cancel";
private static string CANCEL_DO_NOT_CHECK_AGAIN_BUTTON = "Cancel and Do Not Show Again";
private static string IMPORT_PACKAGE_BUTTON = "Import Package";
private static string OK_BUTTON = "OK";
private static string REMOVE_FILES_BUTTON = "Remove Files";
// Only perform compatibility check if current build platform is Android or iOS.
#if UNITY_ANDROID || UNITY_IOS
static GvrCompatibilityChecker() {
// No need to run the backwards compatibility checker GVR is natively integrated into Unity.
#if !UNITY_HAS_GOOGLEVR
if (!IgnoreCompatibilityCheck() &&
!AllBackwardsCompatibilityFilesExist()) {
RemoveiOSNativeIntegrationFiles();
ImportBackwardsCompatibilityPackage();
}
#else
RemoveAnyBackwardsCompatibleFiles();
AndroidManifestCompatibilityUpdate();
#if UNITY_IOS
ImportiOSNativeCompatibilityPackage();
#endif // UNITY_IOS
#endif // !UNITY_HAS_GOOGLEVR
}
#endif // UNITY_ANDROID || UNITY_IOS
private static bool AllBackwardsCompatibilityFilesExist() {
return !BACK_COMPAT_FILE_PATHS.Where(filePath => !File.Exists(filePath)).Any() &&
!BACK_COMPAT_DIR_PATHS.Where(dirPath => !Directory.Exists(dirPath)).Any();
}
private static void ImportiOSNativeCompatibilityPackage() {
string iOSAudioLib = PLUGINS_IOS_PATH + IOS_AUDIO_LIB;
if (File.Exists(iOSAudioLib)) {
return;
}
string packagePath = Application.dataPath + IOS_NATIVE_COMPAT_PACKAGE_PATH;
AssetDatabase.ImportPackage(packagePath, true);
AssetDatabase.Refresh();
}
private static void ImportBackwardsCompatibilityPackage() {
int option = EditorUtility.DisplayDialogComplex(IMPORT_REQUIRED_TITLE,
IMPORT_REQUIRED_MESSAGE,
IMPORT_PACKAGE_BUTTON,
CANCEL_DO_NOT_CHECK_AGAIN_BUTTON,
CANCEL_BUTTON);
switch (option) {
case 0: // Import the package.
string packagePath = Application.dataPath + BACK_COMPAT_PACKAGE_PATH;
if (File.Exists(IGNORE_MANIFEST_MERGE_CHECK_PATH)) {
File.Delete(IGNORE_MANIFEST_MERGE_CHECK_PATH);
}
if (!File.Exists(packagePath)) {
EditorUtility.DisplayDialog(PACKAGE_NOT_FOUND_TITLE, null, OK_BUTTON);
return;
}
AssetDatabase.ImportPackage(packagePath, true);
AssetDatabase.Refresh();
AndroidManifestCompatibilityUpdate();
return;
case 1: // Do not import, and do not check again.
File.Create(IGNORE_COMPATIBILITY_CHECK_PATH);
File.Create(IGNORE_MANIFEST_MERGE_CHECK_PATH);
EditorUtility.DisplayDialog(REENABLE_COMPATIBILITY_CHECK_TITLE,
REENABLE_COMPATIBILITY_CHECK_MESSAGE, OK_BUTTON);
AndroidManifestCompatibilityUpdate();
return;
case 2: // Do not import.
// Fall through.
default:
return;
}
}
private static void RemoveAnyBackwardsCompatibleFiles() {
IEnumerable<string> backCompatFiles = BACK_COMPAT_FILE_PATHS.AsEnumerable();
backCompatFiles = backCompatFiles.Where(filePath => File.Exists(filePath));
IEnumerable<string> iOSBackCompatDirs = BACK_COMPAT_DIR_PATHS.AsEnumerable();
iOSBackCompatDirs = iOSBackCompatDirs.Where(dirPath => Directory.Exists(dirPath));
if (backCompatFiles.Count() == 0 && iOSBackCompatDirs.Count() == 0) {
return;
}
int dataPathLen = Application.dataPath.Length;
string filesToRemove = "";
foreach (string file in backCompatFiles) {
filesToRemove += string.Format("\t{0}\n", file.Substring(dataPathLen + 1));
}
foreach (string dir in iOSBackCompatDirs) {
filesToRemove += string.Format("\t{0}\n", dir.Substring(dataPathLen + 1));
}
bool removeBackwardsCompatibleFiles = EditorUtility.DisplayDialog(
BACK_COMPAT_FILES_FOUND_TITLE,
string.Format("{0}{1}", BACK_COMPAT_FILES_FOUND_MESSAGE, filesToRemove),
REMOVE_FILES_BUTTON, CANCEL_BUTTON);
if (!removeBackwardsCompatibleFiles) {
return;
}
// Remove files.
foreach (string file in backCompatFiles) {
AssetDatabase.DeleteAsset(ASSET_PATH_PREFIX + file.Substring(dataPathLen));
if (File.Exists(file)) {
File.Delete(file);
}
if (File.Exists(file + META_EXT)) {
File.Delete(file + META_EXT);
}
AssetDatabase.Refresh();
}
// Remove iOS bundles.
foreach (string dir in iOSBackCompatDirs) {
AssetDatabase.DeleteAsset(ASSET_PATH_PREFIX + dir.Substring(dataPathLen));
// AssetDatabase may not fully delete files in versions < 5.6.
if (Directory.Exists(dir)) {
Directory.Delete(dir, true);
}
if (File.Exists(dir + META_EXT)) {
File.Delete(dir + META_EXT);
}
AssetDatabase.Refresh();
}
}
private static void RemoveiOSNativeIntegrationFiles() {
string iOSAudioLib = PLUGINS_IOS_PATH + IOS_AUDIO_LIB;
if (!File.Exists(iOSAudioLib)) {
return;
}
AssetDatabase.DeleteAsset(
ASSET_PATH_PREFIX + iOSAudioLib.Substring(Application.dataPath.Length));
File.Delete(iOSAudioLib);
File.Delete(iOSAudioLib + META_EXT);
AssetDatabase.Refresh();
}
private static bool IgnoreCompatibilityCheck() {
return File.Exists(IGNORE_COMPATIBILITY_CHECK_PATH);
}
private static void AndroidManifestCompatibilityUpdate() {
#if !UNITY_HAS_GOOGLEVR
if (File.Exists(PLUGINS_ANDROID_PATH + ANDROID_MANIFEST)) {
// Show warning dialog.
EditorUtility.DisplayDialog(MANIFEST_UPDATE_WARNING_TITLE,
MERGE_MANIFEST_WARNING_MESSAGE, OK_BUTTON);
} else {
FileUtil.CopyFileOrDirectory(PLUGINS_ANDROID_PATH + ANDROID_MANIFEST_CARDBOARD,
PLUGINS_ANDROID_PATH + ANDROID_MANIFEST);
}
#else
if (!File.Exists(IGNORE_MANIFEST_MERGE_CHECK_PATH) &&
File.Exists(PLUGINS_ANDROID_PATH + ANDROID_MANIFEST)) {
EditorUtility.DisplayDialog(MANIFEST_UPDATE_WARNING_TITLE,
UNMERGE_MANIFEST_WARNING_MESSAGE, OK_BUTTON);
}
#endif // UNITY_HAS_GOOGLEVR
File.Create(IGNORE_MANIFEST_MERGE_CHECK_PATH);
}
}
#pragma warning restore 414
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: A wrapper class for the primitive type float.
**
**
===========================================================*/
using System.Globalization;
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Diagnostics.Contracts;
namespace System
{
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
public struct Single : IComparable, IFormattable, IComparable<Single>, IEquatable<Single>, IConvertible
{
private float _value;
//
// Public constants
//
public const float MinValue = (float)-3.40282346638528859e+38;
public const float Epsilon = (float)1.4e-45;
public const float MaxValue = (float)3.40282346638528859e+38;
public const float PositiveInfinity = (float)1.0 / (float)0.0;
public const float NegativeInfinity = (float)-1.0 / (float)0.0;
public const float NaN = (float)0.0 / (float)0.0;
[Pure]
public static unsafe bool IsInfinity(float f)
{
return (*(int*)(&f) & 0x7FFFFFFF) == 0x7F800000;
}
[Pure]
public static unsafe bool IsPositiveInfinity(float f)
{
return *(int*)(&f) == 0x7F800000;
}
[Pure]
public static unsafe bool IsNegativeInfinity(float f)
{
return *(int*)(&f) == unchecked((int)0xFF800000);
}
[Pure]
public static unsafe bool IsNaN(float f)
{
return (*(int*)(&f) & 0x7FFFFFFF) > 0x7F800000;
}
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type Single, this method throws an ArgumentException.
//
public int CompareTo(Object value)
{
if (value == null)
{
return 1;
}
if (value is Single)
{
float f = (float)value;
if (_value < f) return -1;
if (_value > f) return 1;
if (_value == f) return 0;
// At least one of the values is NaN.
if (IsNaN(_value))
return (IsNaN(f) ? 0 : -1);
else // f is NaN.
return 1;
}
throw new ArgumentException(SR.Arg_MustBeSingle);
}
public int CompareTo(Single value)
{
if (_value < value) return -1;
if (_value > value) return 1;
if (_value == value) return 0;
// At least one of the values is NaN.
if (IsNaN(_value))
return (IsNaN(value) ? 0 : -1);
else // f is NaN.
return 1;
}
public static bool operator ==(Single left, Single right)
{
return left == right;
}
public static bool operator !=(Single left, Single right)
{
return left != right;
}
public static bool operator <(Single left, Single right)
{
return left < right;
}
public static bool operator >(Single left, Single right)
{
return left > right;
}
public static bool operator <=(Single left, Single right)
{
return left <= right;
}
public static bool operator >=(Single left, Single right)
{
return left >= right;
}
public override bool Equals(Object obj)
{
if (!(obj is Single))
{
return false;
}
float temp = ((Single)obj)._value;
if (temp == _value)
{
return true;
}
return IsNaN(temp) && IsNaN(_value);
}
public bool Equals(Single obj)
{
if (obj == _value)
{
return true;
}
return IsNaN(obj) && IsNaN(_value);
}
public unsafe override int GetHashCode()
{
float f = _value;
if (f == 0)
{
// Ensure that 0 and -0 have the same hash code
return 0;
}
int v = *(int*)(&f);
return v;
}
public override String ToString()
{
Contract.Ensures(Contract.Result<String>() != null);
return FormatProvider.FormatSingle(_value, null, null);
}
public String ToString(IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return FormatProvider.FormatSingle(_value, null, provider);
}
public String ToString(String format)
{
Contract.Ensures(Contract.Result<String>() != null);
return FormatProvider.FormatSingle(_value, format, null);
}
public String ToString(String format, IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return FormatProvider.FormatSingle(_value, format, provider);
}
// Parses a float from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
//
// This method will not throw an OverflowException, but will return
// PositiveInfinity or NegativeInfinity for a number that is too
// large or too small.
//
public static float Parse(String s)
{
return Parse(s, NumberStyles.Float | NumberStyles.AllowThousands, null);
}
public static float Parse(String s, NumberStyles style)
{
Decimal.ValidateParseStyleFloatingPoint(style);
return Parse(s, style, null);
}
public static float Parse(String s, IFormatProvider provider)
{
return Parse(s, NumberStyles.Float | NumberStyles.AllowThousands, provider);
}
public static float Parse(String s, NumberStyles style, IFormatProvider provider)
{
Decimal.ValidateParseStyleFloatingPoint(style);
return FormatProvider.ParseSingle(s, style, provider);
}
public static Boolean TryParse(String s, out Single result)
{
return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, null, out result);
}
public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out Single result)
{
Decimal.ValidateParseStyleFloatingPoint(style);
if (s == null)
{
result = 0;
return false;
}
bool success = FormatProvider.TryParseSingle(s, style, provider, out result);
if (!success)
{
String sTrim = s.Trim();
if (FormatProvider.IsPositiveInfinity(sTrim, provider))
{
result = PositiveInfinity;
}
else if (FormatProvider.IsNegativeInfinity(sTrim, provider))
{
result = NegativeInfinity;
}
else if (FormatProvider.IsNaNSymbol(sTrim, provider))
{
result = NaN;
}
else
return false; // We really failed
}
return true;
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.Single;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(_value);
}
char IConvertible.ToChar(IFormatProvider provider)
{
throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Single", "Char"));
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(_value);
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(_value);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(_value);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(_value);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(_value);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(_value);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(_value);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(_value);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return _value;
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(_value);
}
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(_value);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Single", "DateTime"));
}
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.