context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using System.Xml.Schema; namespace System.Xml.Xsl { /// <summary> /// XmlQueryType contains static type information that describes the structure and possible values of dynamic /// instances of the Xml data model. /// /// Every XmlQueryType is composed of a Prime type and a cardinality. The Prime type itself may be a union /// between several item types. The XmlQueryType IList<XmlQueryType/> implementation allows callers /// to enumerate the item types. Other properties expose other information about the type. /// </summary> internal abstract class XmlQueryType : ListBase<XmlQueryType> { private static readonly BitMatrix s_typeCodeDerivation; private int _hashCode; //----------------------------------------------- // Static Constructor //----------------------------------------------- static XmlQueryType() { s_typeCodeDerivation = new BitMatrix(s_baseTypeCodes.Length); // Build derivation matrix for (int i = 0; i < s_baseTypeCodes.Length; i++) { int nextAncestor = i; while (true) { s_typeCodeDerivation[i, nextAncestor] = true; if ((int)s_baseTypeCodes[nextAncestor] == nextAncestor) break; nextAncestor = (int)s_baseTypeCodes[nextAncestor]; } } } //----------------------------------------------- // ItemType, OccurrenceIndicator Properties //----------------------------------------------- /// <summary> /// Static data type code. The dynamic type is guaranteed to be this type or a subtype of this code. /// This type code includes support for XQuery types that are not part of Xsd, such as Item, /// Node, AnyAtomicType, and Comment. /// </summary> public abstract XmlTypeCode TypeCode { get; } /// <summary> /// Set of allowed names for element, document{element}, attribute and PI /// Returns XmlQualifiedName.Wildcard for all other types /// </summary> public abstract XmlQualifiedNameTest NameTest { get; } /// <summary> /// Static Xsd schema type. The dynamic type is guaranteed to be this type or a subtype of this type. /// SchemaType will follow these rules: /// 1. If TypeCode is an atomic type code, then SchemaType will be the corresponding non-null simple type /// 2. If TypeCode is Element or Attribute, then SchemaType will be the non-null content type /// 3. If TypeCode is Item, Node, Comment, PI, Text, Document, Namespace, None, then SchemaType will be AnyType /// </summary> public abstract XmlSchemaType SchemaType { get; } /// <summary> /// Permits the element or document{element} node to have the nilled property. /// Returns false for all other types /// </summary> public abstract bool IsNillable { get; } /// <summary> /// This property is always XmlNodeKindFlags.None unless TypeCode = XmlTypeCode.Node, in which case this /// property lists all node kinds that instances of this type may be. /// </summary> public abstract XmlNodeKindFlags NodeKinds { get; } /// <summary> /// If IsStrict is true, then the dynamic type is guaranteed to be the exact same as the static type, and /// will therefore never be a subtype of the static type. /// </summary> public abstract bool IsStrict { get; } /// <summary> /// This property specifies the possible cardinalities that instances of this type may have. /// </summary> public abstract XmlQueryCardinality Cardinality { get; } /// <summary> /// This property returns this type's Prime type, which is always cardinality One. /// </summary> public abstract XmlQueryType Prime { get; } /// <summary> /// True if dynamic data type of all items in this sequence is guaranteed to be not a subtype of Rtf. /// </summary> public abstract bool IsNotRtf { get; } /// <summary> /// True if items in the sequence are guaranteed to be nodes in document order with no duplicates. /// </summary> public abstract bool IsDod { get; } /// <summary> /// The XmlValueConverter maps each XmlQueryType to various Clr types which are capable of representing it. /// </summary> public abstract XmlValueConverter ClrMapping { get; } //----------------------------------------------- // Type Operations //----------------------------------------------- /// <summary> /// Returns true if every possible dynamic instance of this type is also an instance of "baseType". /// </summary> public bool IsSubtypeOf(XmlQueryType baseType) { XmlQueryType thisPrime, basePrime; // Check cardinality sub-typing rules if (!(Cardinality <= baseType.Cardinality) || (!IsDod && baseType.IsDod)) return false; if (!IsDod && baseType.IsDod) return false; // Check early for common case that two types are the same object thisPrime = Prime; basePrime = baseType.Prime; if ((object)thisPrime == (object)basePrime) return true; // Check early for common case that two prime types are item types if (thisPrime.Count == 1 && basePrime.Count == 1) return thisPrime.IsSubtypeOfItemType(basePrime); // Check that each item type in this type is a subtype of some item type in "baseType" foreach (XmlQueryType thisItem in thisPrime) { bool match = false; foreach (XmlQueryType baseItem in basePrime) { if (thisItem.IsSubtypeOfItemType(baseItem)) { match = true; break; } } if (match == false) return false; } return true; } /// <summary> /// Returns true if a dynamic instance (type None never has an instance) of this type can never be a subtype of "baseType". /// </summary> public bool NeverSubtypeOf(XmlQueryType baseType) { // Check cardinalities if (Cardinality.NeverSubset(baseType.Cardinality)) return true; // If both this type and "other" type might be empty, it doesn't matter what the prime types are if (MaybeEmpty && baseType.MaybeEmpty) return false; // None is subtype of every other type if (Count == 0) return false; // Check item types foreach (XmlQueryType typThis in this) { foreach (XmlQueryType typThat in baseType) { if (typThis.HasIntersectionItemType(typThat)) return false; } } return true; } /// <summary> /// Strongly-typed Equals that returns true if this type and "that" type are equivalent. /// </summary> public bool Equals(XmlQueryType that) { if (that == null) return false; // Check cardinality and DocOrderDistinct property if (Cardinality != that.Cardinality || IsDod != that.IsDod) return false; // Check early for common case that two types are the same object XmlQueryType thisPrime = Prime; XmlQueryType thatPrime = that.Prime; if ((object)thisPrime == (object)thatPrime) return true; // Check that count of item types is equal if (thisPrime.Count != thatPrime.Count) return false; // Check early for common case that two prime types are item types if (thisPrime.Count == 1) { return (thisPrime.TypeCode == thatPrime.TypeCode && thisPrime.NameTest == thatPrime.NameTest && thisPrime.SchemaType == thatPrime.SchemaType && thisPrime.IsStrict == thatPrime.IsStrict && thisPrime.IsNotRtf == thatPrime.IsNotRtf); } // Check that each item type in this type is equal to some item type in "baseType" // (string | int) should be the same type as (int | string) foreach (XmlQueryType thisItem in this) { bool match = false; foreach (XmlQueryType thatItem in that) { if (thisItem.TypeCode == thatItem.TypeCode && thisItem.NameTest == thatItem.NameTest && thisItem.SchemaType == thatItem.SchemaType && thisItem.IsStrict == thatItem.IsStrict && thisItem.IsNotRtf == thatItem.IsNotRtf) { // Found match so proceed to next type match = true; break; } } if (match == false) return false; } return true; } /// <summary> /// Overload == operator to call Equals rather than do reference equality. /// </summary> public static bool operator ==(XmlQueryType left, XmlQueryType right) { if ((object)left == null) return ((object)right == null); return left.Equals(right); } /// <summary> /// Overload != operator to call Equals rather than do reference inequality. /// </summary> public static bool operator !=(XmlQueryType left, XmlQueryType right) { if ((object)left == null) return ((object)right != null); return !left.Equals(right); } //----------------------------------------------- // Convenience Properties //----------------------------------------------- /// <summary> /// True if dynamic cardinality of this sequence is guaranteed to be 0. /// </summary> public bool IsEmpty { get { return Cardinality <= XmlQueryCardinality.Zero; } } /// <summary> /// True if dynamic cardinality of this sequence is guaranteed to be 1. /// </summary> public bool IsSingleton { get { return Cardinality <= XmlQueryCardinality.One; } } /// <summary> /// True if dynamic cardinality of this sequence might be 0. /// </summary> public bool MaybeEmpty { get { return XmlQueryCardinality.Zero <= Cardinality; } } /// <summary> /// True if dynamic cardinality of this sequence might be >1. /// </summary> public bool MaybeMany { get { return XmlQueryCardinality.More <= Cardinality; } } /// <summary> /// True if dynamic data type of all items in this sequence is guaranteed to be a subtype of Node. /// Equivalent to calling IsSubtypeOf(TypeFactory.NodeS). /// </summary> public bool IsNode { get { return (s_typeCodeToFlags[(int)TypeCode] & TypeFlags.IsNode) != 0; } } /// <summary> /// True if dynamic data type of all items in this sequence is guaranteed to be a subtype of AnyAtomicType. /// Equivalent to calling IsSubtypeOf(TypeFactory.AnyAtomicTypeS). /// </summary> public bool IsAtomicValue { get { return (s_typeCodeToFlags[(int)TypeCode] & TypeFlags.IsAtomicValue) != 0; } } /// <summary> /// True if dynamic data type of all items in this sequence is guaranteed to be a subtype of Decimal, Double, or Float. /// Equivalent to calling IsSubtypeOf(TypeFactory.NumericS). /// </summary> public bool IsNumeric { get { return (s_typeCodeToFlags[(int)TypeCode] & TypeFlags.IsNumeric) != 0; } } //----------------------------------------------- // System.Object implementation //----------------------------------------------- /// <summary> /// True if "obj" is an XmlQueryType, and this type is the exact same static type. /// </summary> public override bool Equals(object obj) { XmlQueryType that = obj as XmlQueryType; if (that == null) return false; return Equals(that); } /// <summary> /// Return hash code of this instance. /// </summary> public override int GetHashCode() { if (_hashCode == 0) { int hash; XmlSchemaType schemaType; hash = (int)TypeCode; schemaType = SchemaType; unchecked { if (schemaType != null) hash += (hash << 7) ^ schemaType.GetHashCode(); hash += (hash << 7) ^ (int)NodeKinds; hash += (hash << 7) ^ Cardinality.GetHashCode(); hash += (hash << 7) ^ (IsStrict ? 1 : 0); // Mix hash code a bit more hash -= hash >> 17; hash -= hash >> 11; hash -= hash >> 5; } // Save hashcode. Don't save 0, so that it won't ever be recomputed. _hashCode = (hash == 0) ? 1 : hash; } return _hashCode; } /// <summary> /// Return a user-friendly string representation of the XmlQueryType. /// </summary> public override string ToString() { return ToString("G"); } /// <summary> /// Return a string representation of the XmlQueryType using the specified format. The following formats are /// supported: /// /// "G" (General): This is the default mode, and is used if no other format is recognized. This format is /// easier to read than the canonical format, since it excludes redundant information. /// (e.g. element instead of element(*, xs:anyType)) /// /// "X" (XQuery): Return the canonical XQuery representation, which excludes Qil specific information and /// includes extra, redundant information, such as fully specified types. /// (e.g. element(*, xs:anyType) instead of element) /// /// "S" (Serialized): This format is used to serialize parts of the type which can be serialized easily, in /// a format that is easy to parse. Only the cardinality, type code, and strictness flag /// are serialized. User-defined type information and element/attribute content types /// are lost. /// (e.g. One;Attribute|String|Int;true) /// /// </summary> public string ToString(string format) { string[] sa; StringBuilder sb; bool isXQ; if (format == "S") { sb = new StringBuilder(); sb.Append(Cardinality.ToString(format)); sb.Append(';'); for (int i = 0; i < Count; i++) { if (i != 0) sb.Append("|"); sb.Append(this[i].TypeCode.ToString()); } sb.Append(';'); sb.Append(IsStrict); return sb.ToString(); } isXQ = (format == "X"); if (Cardinality == XmlQueryCardinality.None) { return "none"; } else if (Cardinality == XmlQueryCardinality.Zero) { return "empty"; } sb = new StringBuilder(); switch (Count) { case 0: // This assert depends on the way we are going to represent None sb.Append("none"); break; case 1: sb.Append(this[0].ItemTypeToString(isXQ)); break; default: sa = new string[Count]; for (int i = 0; i < Count; i++) sa[i] = this[i].ItemTypeToString(isXQ); Array.Sort(sa); sb = new StringBuilder(); sb.Append('('); sb.Append(sa[0]); for (int i = 1; i < sa.Length; i++) { sb.Append(" | "); sb.Append(sa[i]); } sb.Append(')'); break; } sb.Append(Cardinality.ToString()); if (!isXQ && IsDod) sb.Append('#'); return sb.ToString(); } //----------------------------------------------- // Serialization //----------------------------------------------- /// <summary> /// Serialize the object to BinaryWriter. /// </summary> public abstract void GetObjectData(BinaryWriter writer); //----------------------------------------------- // Helpers //----------------------------------------------- /// <summary> /// Returns true if this item type is a subtype of another item type. /// </summary> private bool IsSubtypeOfItemType(XmlQueryType baseType) { Debug.Assert(Count == 1 && IsSingleton, "This method should only be called for item types."); Debug.Assert(baseType.Count == 1 && baseType.IsSingleton, "This method should only be called for item types."); Debug.Assert(!IsDod && !baseType.IsDod, "Singleton types may not have DocOrderDistinct property"); XmlSchemaType baseSchemaType = baseType.SchemaType; if (TypeCode != baseType.TypeCode) { // If "baseType" is strict, then IsSubtypeOf must be false if (baseType.IsStrict) return false; // If type codes are not the same, then IsSubtypeOf can return true *only* if "baseType" is a built-in type XmlSchemaType builtInType = XmlSchemaType.GetBuiltInSimpleType(baseType.TypeCode); if (builtInType != null && baseSchemaType != builtInType) return false; // Now check whether TypeCode is derived from baseType.TypeCode return s_typeCodeDerivation[TypeCode, baseType.TypeCode]; } else if (baseType.IsStrict) { // only atomic values can be strict Debug.Assert(IsAtomicValue && baseType.IsAtomicValue); // If schema types are not the same, then IsSubtype is false if "baseType" is strict return IsStrict && SchemaType == baseSchemaType; } else { // Otherwise, check derivation tree return (IsNotRtf || !baseType.IsNotRtf) && NameTest.IsSubsetOf(baseType.NameTest) && (baseSchemaType == XmlSchemaComplexType.AnyType || XmlSchemaType.IsDerivedFrom(SchemaType, baseSchemaType, /* except:*/XmlSchemaDerivationMethod.Empty)) && (!IsNillable || baseType.IsNillable); } } /// <summary> /// Returns true if the intersection between this item type and "other" item type is not empty. /// </summary> private bool HasIntersectionItemType(XmlQueryType other) { Debug.Assert(this.Count == 1 && this.IsSingleton, "this should be an item"); Debug.Assert(other.Count == 1 && other.IsSingleton, "other should be an item"); if (this.TypeCode == other.TypeCode && (this.NodeKinds & (XmlNodeKindFlags.Document | XmlNodeKindFlags.Element | XmlNodeKindFlags.Attribute)) != 0) { if (this.TypeCode == XmlTypeCode.Node) return true; // Intersect name tests if (!this.NameTest.HasIntersection(other.NameTest)) return false; if (!XmlSchemaType.IsDerivedFrom(this.SchemaType, other.SchemaType, /* except:*/XmlSchemaDerivationMethod.Empty) && !XmlSchemaType.IsDerivedFrom(other.SchemaType, this.SchemaType, /* except:*/XmlSchemaDerivationMethod.Empty)) { return false; } return true; } else if (this.IsSubtypeOf(other) || other.IsSubtypeOf(this)) { return true; } return false; } /// <summary> /// Return the string representation of an item type (cannot be a union or a sequence). /// </summary> private string ItemTypeToString(bool isXQ) { string s; Debug.Assert(Count == 1, "Do not pass a Union type to this method."); Debug.Assert(IsSingleton, "Do not pass a Sequence type to this method."); if (IsNode) { // Map TypeCode to string s = s_typeNames[(int)TypeCode]; switch (TypeCode) { case XmlTypeCode.Document: if (!isXQ) goto case XmlTypeCode.Element; s += "{(element" + NameAndType(true) + "?&text?&comment?&processing-instruction?)*}"; break; case XmlTypeCode.Element: case XmlTypeCode.Attribute: s += NameAndType(isXQ); break; } } else if (SchemaType != XmlSchemaComplexType.AnyType) { // Get QualifiedName from SchemaType if (SchemaType.QualifiedName.IsEmpty) s = "<:" + s_typeNames[(int)TypeCode]; else s = QNameToString(SchemaType.QualifiedName); } else { // Map TypeCode to string s = s_typeNames[(int)TypeCode]; } if (!isXQ && IsStrict) s += "="; return s; } /// <summary> /// Return "(name-test, type-name)" for this type. If isXQ is false, normalize xs:anySimpleType and /// xs:anyType to "*". /// </summary> private string NameAndType(bool isXQ) { string nodeName = NameTest.ToString(); string typeName = "*"; if (SchemaType.QualifiedName.IsEmpty) { typeName = "typeof(" + nodeName + ")"; } else { if (isXQ || (SchemaType != XmlSchemaComplexType.AnyType && SchemaType != DatatypeImplementation.AnySimpleType)) typeName = QNameToString(SchemaType.QualifiedName); } if (IsNillable) typeName += " nillable"; // Normalize "(*, *)" to "" if (nodeName == "*" && typeName == "*") return ""; return "(" + nodeName + ", " + typeName + ")"; } /// <summary> /// Convert an XmlQualifiedName to a string, using somewhat different rules than XmlQualifiedName.ToString(): /// 1. Empty QNames are assumed to be wildcard names, so return "*" /// 2. Recognize the built-in xs: and xdt: namespaces and print the short prefix rather than the long namespace /// 3. Use brace characters "{", "}" around the namespace portion of the QName /// </summary> private static string QNameToString(XmlQualifiedName name) { if (name.IsEmpty) { return "*"; } else if (name.Namespace.Length == 0) { return name.Name; } else if (name.Namespace == XmlReservedNs.NsXs) { return "xs:" + name.Name; } else if (name.Namespace == XmlReservedNs.NsXQueryDataType) { return "xdt:" + name.Name; } else { return "{" + name.Namespace + "}" + name.Name; } } #region TypeFlags private enum TypeFlags { None = 0, IsNode = 1, IsAtomicValue = 2, IsNumeric = 4, } #endregion #region TypeCodeToFlags private static readonly TypeFlags[] s_typeCodeToFlags = { /* XmlTypeCode.None */ TypeFlags.IsNode | TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.Item */ TypeFlags.None, /* XmlTypeCode.Node */ TypeFlags.IsNode, /* XmlTypeCode.Document */ TypeFlags.IsNode, /* XmlTypeCode.Element */ TypeFlags.IsNode, /* XmlTypeCode.Attribute */ TypeFlags.IsNode, /* XmlTypeCode.Namespace */ TypeFlags.IsNode, /* XmlTypeCode.ProcessingInstruction */ TypeFlags.IsNode, /* XmlTypeCode.Comment */ TypeFlags.IsNode, /* XmlTypeCode.Text */ TypeFlags.IsNode, /* XmlTypeCode.AnyAtomicType */ TypeFlags.IsAtomicValue, /* XmlTypeCode.UntypedAtomic */ TypeFlags.IsAtomicValue, /* XmlTypeCode.String */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Boolean */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Decimal */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.Float */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.Double */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.Duration */ TypeFlags.IsAtomicValue, /* XmlTypeCode.DateTime */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Time */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Date */ TypeFlags.IsAtomicValue, /* XmlTypeCode.GYearMonth */ TypeFlags.IsAtomicValue, /* XmlTypeCode.GYear */ TypeFlags.IsAtomicValue, /* XmlTypeCode.GMonthDay */ TypeFlags.IsAtomicValue, /* XmlTypeCode.GDay */ TypeFlags.IsAtomicValue, /* XmlTypeCode.GMonth */ TypeFlags.IsAtomicValue, /* XmlTypeCode.HexBinary */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Base64Binary */ TypeFlags.IsAtomicValue, /* XmlTypeCode.AnyUri */ TypeFlags.IsAtomicValue, /* XmlTypeCode.QName */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Notation */ TypeFlags.IsAtomicValue, /* XmlTypeCode.NormalizedString */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Token */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Language */ TypeFlags.IsAtomicValue, /* XmlTypeCode.NmToken */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Name */ TypeFlags.IsAtomicValue, /* XmlTypeCode.NCName */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Id */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Idref */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Entity */ TypeFlags.IsAtomicValue, /* XmlTypeCode.Integer */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.NonPositiveInteger */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.NegativeInteger */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.Long */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.Int */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.Short */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.Byte */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.NonNegativeInteger */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.UnsignedLong */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.UnsignedInt */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.UnsignedShort */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.UnsignedByte */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.PositiveInteger */ TypeFlags.IsAtomicValue | TypeFlags.IsNumeric, /* XmlTypeCode.YearMonthDuration */ TypeFlags.IsAtomicValue, /* XmlTypeCode.DayTimeDuration */ TypeFlags.IsAtomicValue, }; private static readonly XmlTypeCode[] s_baseTypeCodes = { /* None */ XmlTypeCode.None, /* Item */ XmlTypeCode.Item, /* Node */ XmlTypeCode.Item, /* Document */ XmlTypeCode.Node, /* Element */ XmlTypeCode.Node, /* Attribute */ XmlTypeCode.Node, /* Namespace */ XmlTypeCode.Node, /* ProcessingInstruction */ XmlTypeCode.Node, /* Comment */ XmlTypeCode.Node, /* Text */ XmlTypeCode.Node, /* AnyAtomicType */ XmlTypeCode.Item, /* UntypedAtomic */ XmlTypeCode.AnyAtomicType, /* String */ XmlTypeCode.AnyAtomicType, /* Boolean */ XmlTypeCode.AnyAtomicType, /* Decimal */ XmlTypeCode.AnyAtomicType, /* Float */ XmlTypeCode.AnyAtomicType, /* Double */ XmlTypeCode.AnyAtomicType, /* Duration */ XmlTypeCode.AnyAtomicType, /* DateTime */ XmlTypeCode.AnyAtomicType, /* Time */ XmlTypeCode.AnyAtomicType, /* Date */ XmlTypeCode.AnyAtomicType, /* GYearMonth */ XmlTypeCode.AnyAtomicType, /* GYear */ XmlTypeCode.AnyAtomicType, /* GMonthDay */ XmlTypeCode.AnyAtomicType, /* GDay */ XmlTypeCode.AnyAtomicType, /* GMonth */ XmlTypeCode.AnyAtomicType, /* HexBinary */ XmlTypeCode.AnyAtomicType, /* Base64Binary */ XmlTypeCode.AnyAtomicType, /* AnyUri */ XmlTypeCode.AnyAtomicType, /* QName */ XmlTypeCode.AnyAtomicType, /* Notation */ XmlTypeCode.AnyAtomicType, /* NormalizedString */ XmlTypeCode.String, /* Token */ XmlTypeCode.NormalizedString, /* Language */ XmlTypeCode.Token, /* NmToken */ XmlTypeCode.Token, /* Name */ XmlTypeCode.Token, /* NCName */ XmlTypeCode.Name, /* Id */ XmlTypeCode.NCName, /* Idref */ XmlTypeCode.NCName, /* Entity */ XmlTypeCode.NCName, /* Integer */ XmlTypeCode.Decimal, /* NonPositiveInteger */ XmlTypeCode.Integer, /* NegativeInteger */ XmlTypeCode.NonPositiveInteger, /* Long */ XmlTypeCode.Integer, /* Int */ XmlTypeCode.Long, /* Short */ XmlTypeCode.Int, /* Byte */ XmlTypeCode.Short, /* NonNegativeInteger */ XmlTypeCode.Integer, /* UnsignedLong */ XmlTypeCode.NonNegativeInteger, /* UnsignedInt */ XmlTypeCode.UnsignedLong, /* UnsignedShort */ XmlTypeCode.UnsignedInt, /* UnsignedByte */ XmlTypeCode.UnsignedShort, /* PositiveInteger */ XmlTypeCode.NonNegativeInteger, /* YearMonthDuration */ XmlTypeCode.Duration, /* DayTimeDuration */ XmlTypeCode.Duration, }; private static readonly string[] s_typeNames = { /* None */ "none", /* Item */ "item", /* Node */ "node", /* Document */ "document", /* Element */ "element", /* Attribute */ "attribute", /* Namespace */ "namespace", /* ProcessingInstruction */ "processing-instruction", /* Comment */ "comment", /* Text */ "text", /* AnyAtomicType */ "xdt:anyAtomicType", /* UntypedAtomic */ "xdt:untypedAtomic", /* String */ "xs:string", /* Boolean */ "xs:boolean", /* Decimal */ "xs:decimal", /* Float */ "xs:float", /* Double */ "xs:double", /* Duration */ "xs:duration", /* DateTime */ "xs:dateTime", /* Time */ "xs:time", /* Date */ "xs:date", /* GYearMonth */ "xs:gYearMonth", /* GYear */ "xs:gYear", /* GMonthDay */ "xs:gMonthDay", /* GDay */ "xs:gDay", /* GMonth */ "xs:gMonth", /* HexBinary */ "xs:hexBinary", /* Base64Binary */ "xs:base64Binary", /* AnyUri */ "xs:anyUri", /* QName */ "xs:QName", /* Notation */ "xs:NOTATION", /* NormalizedString */ "xs:normalizedString", /* Token */ "xs:token", /* Language */ "xs:language", /* NmToken */ "xs:NMTOKEN", /* Name */ "xs:Name", /* NCName */ "xs:NCName", /* Id */ "xs:ID", /* Idref */ "xs:IDREF", /* Entity */ "xs:ENTITY", /* Integer */ "xs:integer", /* NonPositiveInteger */ "xs:nonPositiveInteger", /* NegativeInteger */ "xs:negativeInteger", /* Long */ "xs:long", /* Int */ "xs:int", /* Short */ "xs:short", /* Byte */ "xs:byte", /* NonNegativeInteger */ "xs:nonNegativeInteger", /* UnsignedLong */ "xs:unsignedLong", /* UnsignedInt */ "xs:unsignedInt", /* UnsignedShort */ "xs:unsignedShort", /* UnsignedByte */ "xs:unsignedByte", /* PositiveInteger */ "xs:positiveInteger", /* YearMonthDuration */ "xdt:yearMonthDuration", /* DayTimeDuration */ "xdt:dayTimeDuration", }; #endregion /// <summary> /// Implements an NxN bit matrix. /// </summary> private sealed class BitMatrix { private ulong[] _bits; /// <summary> /// Create NxN bit matrix, where N = count. /// </summary> public BitMatrix(int count) { Debug.Assert(count < 64, "BitMatrix currently only handles up to 64x64 matrix."); _bits = new ulong[count]; } // /// <summary> // /// Return the number of rows and columns in the matrix. // /// </summary> // public int Size { // get { return bits.Length; } // } // /// <summary> /// Get or set a bit in the matrix at position (index1, index2). /// </summary> public bool this[int index1, int index2] { get { Debug.Assert(index1 < _bits.Length && index2 < _bits.Length, "Index out of range."); return (_bits[index1] & ((ulong)1 << index2)) != 0; } set { Debug.Assert(index1 < _bits.Length && index2 < _bits.Length, "Index out of range."); if (value == true) { _bits[index1] |= (ulong)1 << index2; } else { _bits[index1] &= ~((ulong)1 << index2); } } } /// <summary> /// Strongly typed indexer. /// </summary> public bool this[XmlTypeCode index1, XmlTypeCode index2] { get { return this[(int)index1, (int)index2]; } // set { // this[(int)index1, (int)index2] = value; // } } } } }
--- /dev/null 2016-03-04 14:30:57.000000000 -0500 +++ src/System.Collections/src/SR.cs 2016-03-04 14:31:54.296448000 -0500 @@ -0,0 +1,408 @@ +using System.Resources; + +namespace FxResources.System.Collections +{ + internal class SR + { + } +} + +namespace System +{ + internal static class SR + { + private static ResourceManager s_resourceManager; + + private const string s_resourcesName = "FxResources.System.Collections.SR"; + + internal static string SortedSet_LowerValueGreaterThanUpperValue + { + get + { + return SR.GetResourceString("SortedSet_LowerValueGreaterThanUpperValue", null); + } + } + + internal static string Arg_ArrayLengthsDiffer + { + get + { + return SR.GetResourceString("Arg_ArrayLengthsDiffer", null); + } + } + + internal static string Arg_ArrayPlusOffTooSmall + { + get + { + return SR.GetResourceString("Arg_ArrayPlusOffTooSmall", null); + } + } + + internal static string Arg_BitArrayTypeUnsupported + { + get + { + return SR.GetResourceString("Arg_BitArrayTypeUnsupported", null); + } + } + + internal static string Arg_HSCapacityOverflow + { + get + { + return SR.GetResourceString("Arg_HSCapacityOverflow", null); + } + } + + internal static string Arg_HTCapacityOverflow + { + get + { + return SR.GetResourceString("Arg_HTCapacityOverflow", null); + } + } + + internal static string Arg_InsufficientSpace + { + get + { + return SR.GetResourceString("Arg_InsufficientSpace", null); + } + } + + internal static string Arg_MultiRank + { + get + { + return SR.GetResourceString("Arg_MultiRank", null); + } + } + + internal static string Arg_NonZeroLowerBound + { + get + { + return SR.GetResourceString("Arg_NonZeroLowerBound", null); + } + } + + internal static string Arg_RankMultiDimNotSupported + { + get + { + return SR.GetResourceString("Arg_RankMultiDimNotSupported", null); + } + } + + internal static string Arg_WrongType + { + get + { + return SR.GetResourceString("Arg_WrongType", null); + } + } + + internal static string Argument_AddingDuplicate + { + get + { + return SR.GetResourceString("Argument_AddingDuplicate", null); + } + } + + internal static string Argument_ArrayTooLarge + { + get + { + return SR.GetResourceString("Argument_ArrayTooLarge", null); + } + } + + internal static string Argument_ImplementIComparable + { + get + { + return SR.GetResourceString("Argument_ImplementIComparable", null); + } + } + + internal static string Argument_InvalidArgumentForComparison + { + get + { + return SR.GetResourceString("Argument_InvalidArgumentForComparison", null); + } + } + + internal static string Argument_InvalidArrayType + { + get + { + return SR.GetResourceString("Argument_InvalidArrayType", null); + } + } + + internal static string Argument_InvalidOffLen + { + get + { + return SR.GetResourceString("Argument_InvalidOffLen", null); + } + } + + internal static string ArgumentOutOfRange_BiggerThanCollection + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_BiggerThanCollection", null); + } + } + + internal static string ArgumentOutOfRange_Count + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_Count", null); + } + } + + internal static string ArgumentOutOfRange_Index + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_Index", null); + } + } + + internal static string ArgumentOutOfRange_ListInsert + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_ListInsert", null); + } + } + + internal static string ArgumentOutOfRange_NeedNonNegNum + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_NeedNonNegNum", null); + } + } + + internal static string ArgumentOutOfRange_NeedNonNegNumRequired + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_NeedNonNegNumRequired", null); + } + } + + internal static string ArgumentOutOfRange_SmallCapacity + { + get + { + return SR.GetResourceString("ArgumentOutOfRange_SmallCapacity", null); + } + } + + internal static string ExternalLinkedListNode + { + get + { + return SR.GetResourceString("ExternalLinkedListNode", null); + } + } + + internal static string IndexOutOfRange + { + get + { + return SR.GetResourceString("IndexOutOfRange", null); + } + } + + internal static string Invalid_Array_Type + { + get + { + return SR.GetResourceString("Invalid_Array_Type", null); + } + } + + internal static string InvalidOperation_EmptyQueue + { + get + { + return SR.GetResourceString("InvalidOperation_EmptyQueue", null); + } + } + + internal static string InvalidOperation_EmptyStack + { + get + { + return SR.GetResourceString("InvalidOperation_EmptyStack", null); + } + } + + internal static string InvalidOperation_EnumEnded + { + get + { + return SR.GetResourceString("InvalidOperation_EnumEnded", null); + } + } + + internal static string InvalidOperation_EnumFailedVersion + { + get + { + return SR.GetResourceString("InvalidOperation_EnumFailedVersion", null); + } + } + + internal static string InvalidOperation_EnumNotStarted + { + get + { + return SR.GetResourceString("InvalidOperation_EnumNotStarted", null); + } + } + + internal static string InvalidOperation_EnumOpCantHappen + { + get + { + return SR.GetResourceString("InvalidOperation_EnumOpCantHappen", null); + } + } + + internal static string LinkedListEmpty + { + get + { + return SR.GetResourceString("LinkedListEmpty", null); + } + } + + internal static string LinkedListNodeIsAttached + { + get + { + return SR.GetResourceString("LinkedListNodeIsAttached", null); + } + } + + internal static string NotSupported_KeyCollectionSet + { + get + { + return SR.GetResourceString("NotSupported_KeyCollectionSet", null); + } + } + + internal static string NotSupported_SortedListNestedWrite + { + get + { + return SR.GetResourceString("NotSupported_SortedListNestedWrite", null); + } + } + + internal static string NotSupported_ValueCollectionSet + { + get + { + return SR.GetResourceString("NotSupported_ValueCollectionSet", null); + } + } + + private static ResourceManager ResourceManager + { + get + { + if (SR.s_resourceManager == null) + { + SR.s_resourceManager = new ResourceManager(SR.ResourceType); + } + return SR.s_resourceManager; + } + } + + internal static Type ResourceType + { + get + { + return typeof(FxResources.System.Collections.SR); + } + } + + internal static string Format(string resourceFormat, params object[] args) + { + if (args == null) + { + return resourceFormat; + } + if (!SR.UsingResourceKeys()) + { + return string.Format(resourceFormat, args); + } + return string.Concat(resourceFormat, string.Join(", ", args)); + } + + internal static string Format(string resourceFormat, object p1) + { + if (!SR.UsingResourceKeys()) + { + return string.Format(resourceFormat, p1); + } + return string.Join(", ", new object[] { resourceFormat, p1 }); + } + + internal static string Format(string resourceFormat, object p1, object p2) + { + if (!SR.UsingResourceKeys()) + { + return string.Format(resourceFormat, p1, p2); + } + return string.Join(", ", new object[] { resourceFormat, p1, p2 }); + } + + internal static string Format(string resourceFormat, object p1, object p2, object p3) + { + if (!SR.UsingResourceKeys()) + { + return string.Format(resourceFormat, p1, p2, p3); + } + return string.Join(", ", new object[] { resourceFormat, p1, p2, p3 }); + } + + internal static string GetResourceString(string resourceKey, string defaultString) + { + string str = null; + try + { + str = SR.ResourceManager.GetString(resourceKey); + } + catch (MissingManifestResourceException missingManifestResourceException) + { + } + if (defaultString != null && resourceKey.Equals(str)) + { + return defaultString; + } + if (str == null) + { + throw new MissingManifestResourceException(string.Concat("Unable to find resource for the key ", resourceKey, ".")); + } + return str; + } + + private static bool UsingResourceKeys() + { + return false; + } + } +}
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace Core.TimerJobs.Samples.OverrideJob { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// This method is deprecated because the autohosted option is no longer available. /// </summary> [ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)] public string GetDatabaseConnectionString() { throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available."); } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; bool contextTokenExpired = false; try { if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } } catch (SecurityTokenExpiredException) { contextTokenExpired = true; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]) && !contextTokenExpired) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
// // 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 System; namespace Cassandra { /// <summary> /// <para>Represents the options related to connection pooling.</para> /// <para> /// For each host selected by the load balancing policy, the driver keeps a core amount of /// connections open at all times /// (<see cref="PoolingOptions.GetCoreConnectionsPerHost(HostDistance)"/>). /// If the use of those connections reaches a configurable threshold /// (<see cref="PoolingOptions.GetMaxSimultaneousRequestsPerConnectionTreshold(HostDistance)"/>), /// more connections are created up to the configurable maximum number of connections /// (<see cref="PoolingOptions.GetMaxConnectionPerHost(HostDistance)"/>). /// </para> /// <para> /// The driver uses connections in an asynchronous manner and multiple requests can be /// submitted on the same connection at the same time without waiting for a response. /// This means that the driver only needs to maintain a relatively small number of connections /// to each Cassandra host. The <see cref="PoolingOptions"/> allows you to to control how many /// connections are kept per host. /// </para> /// <para> /// Each of these parameters can be separately set for <see cref="HostDistance.Local"/> and /// <see cref="HostDistance.Remote"/> hosts. For <see cref="HostDistance.Ignored"/> hosts, /// the default for all those settings is 0 and cannot be changed. /// </para> /// <para> /// The default amount of connections depend on the Cassandra version of the Cluster, as newer /// versions of Cassandra (2.1 and above) support a higher number of in-flight requests. /// </para> /// <para>For Cassandra 2.1 and above, the default amount of connections per host are:</para> /// <list type="bullet"> /// <item>Local datacenter: 1 core connection per host, with 2 connections as maximum if the simultaneous requests threshold is reached.</item> /// <item>Remote datacenter: 1 core connection per host (being 1 also max).</item> /// </list> /// <para>For older Cassandra versions (1.2 and 2.0), the default amount of connections per host are:</para> /// <list type="bullet"> /// <item>Local datacenter: 2 core connection per host, with 8 connections as maximum if the simultaneous requests threshold is reached.</item> /// <item>Remote datacenter: 1 core connection per host (being 2 the maximum).</item> /// </list> /// </summary> public class PoolingOptions { //the defaults target small number concurrent requests (protocol 1 and 2) and multiple connections to a host private const int DefaultMinRequests = 25; private const int DefaultMaxRequests = 128; private const int DefaultCorePoolLocal = 2; private const int DefaultCorePoolRemote = 1; private const int DefaultMaxPoolLocal = 8; private const int DefaultMaxPoolRemote = 2; /// <summary> /// The default heartbeat interval in milliseconds: 30000. /// </summary> public const int DefaultHeartBeatInterval = 30000; private int _coreConnectionsForLocal = DefaultCorePoolLocal; private int _coreConnectionsForRemote = DefaultCorePoolRemote; private int _maxConnectionsForLocal = DefaultMaxPoolLocal; private int _maxConnectionsForRemote = DefaultMaxPoolRemote; private int _maxSimultaneousRequestsForLocal = DefaultMaxRequests; private int _maxSimultaneousRequestsForRemote = DefaultMaxRequests; private int _minSimultaneousRequestsForLocal = DefaultMinRequests; private int _minSimultaneousRequestsForRemote = DefaultMinRequests; private int _heartBeatInterval = DefaultHeartBeatInterval; /// <summary> /// Number of simultaneous requests on a connection below which connections in /// excess are reclaimed. <p> If an opened connection to an host at distance /// <c>distance</c> handles less than this number of simultaneous requests /// and there is more than <link>#GetCoreConnectionsPerHost</link> connections /// open to this host, the connection is closed. </p><p> The default value for this /// option is 25 for <c>Local</c> and <c>Remote</c> hosts.</p> /// </summary> /// <param name="distance"> the <c>HostDistance</c> for which to return this threshold.</param> /// <returns>the configured threshold, or the default one if none have been set.</returns> public int GetMinSimultaneousRequestsPerConnectionTreshold(HostDistance distance) { switch (distance) { case HostDistance.Local: return _minSimultaneousRequestsForLocal; case HostDistance.Remote: return _minSimultaneousRequestsForRemote; default: return 0; } } /// <summary> /// Sets the number of simultaneous requests on a connection below which /// connections in excess are reclaimed. /// </summary> /// <param name="distance"> the <see cref="HostDistance"/> for which to configure this /// threshold. </param> /// <param name="minSimultaneousRequests"> the value to set. </param> /// /// <returns>this <c>PoolingOptions</c>. </returns> public PoolingOptions SetMinSimultaneousRequestsPerConnectionTreshold(HostDistance distance, int minSimultaneousRequests) { switch (distance) { case HostDistance.Local: _minSimultaneousRequestsForLocal = minSimultaneousRequests; break; case HostDistance.Remote: _minSimultaneousRequestsForRemote = minSimultaneousRequests; break; default: throw new ArgumentOutOfRangeException("Cannot set min streams per connection threshold for " + distance + " hosts"); } return this; } /// <summary> /// <para> /// Number of simultaneous requests on all connections to an host after which more /// connections are created. /// </para> /// <para> /// If all the connections opened to an host at <see cref="HostDistance"/> connection are /// handling more than this number of simultaneous requests and there is less than /// <see cref="GetMaxConnectionPerHost"/> connections open to this host, a new connection /// is open. /// </para> /// </summary> /// <param name="distance"> the <see cref="HostDistance"/> for which to return this threshold.</param> /// <returns>the configured threshold, or the default one if none have been set.</returns> public int GetMaxSimultaneousRequestsPerConnectionTreshold(HostDistance distance) { switch (distance) { case HostDistance.Local: return _maxSimultaneousRequestsForLocal; case HostDistance.Remote: return _maxSimultaneousRequestsForRemote; default: return 0; } } /// <summary> /// Sets number of simultaneous requests on all connections to an host after /// which more connections are created. /// </summary> /// <param name="distance">The <see cref="HostDistance"/> for which to configure this /// threshold. </param> /// <param name="maxSimultaneousRequests"> the value to set. </param> /// <returns>this <c>PoolingOptions</c>. </returns> /// <throws name="IllegalArgumentException"> if <c>distance == HostDistance.Ignore</c>.</throws> public PoolingOptions SetMaxSimultaneousRequestsPerConnectionTreshold(HostDistance distance, int maxSimultaneousRequests) { switch (distance) { case HostDistance.Local: _maxSimultaneousRequestsForLocal = maxSimultaneousRequests; break; case HostDistance.Remote: _maxSimultaneousRequestsForRemote = maxSimultaneousRequests; break; default: throw new ArgumentOutOfRangeException("Cannot set max streams per connection threshold for " + distance + " hosts"); } return this; } /// <summary> /// <para> /// The core number of connections per host. /// </para> /// <para> /// For the provided <see cref="HostDistance"/>, this correspond to the number of /// connections initially created and kept open to each host of that distance. /// </para> /// </summary> /// <param name="distance">The <see cref="HostDistance"/> for which to return this threshold.</param> /// <returns>the core number of connections per host at distance <see cref="HostDistance"/>.</returns> public int GetCoreConnectionsPerHost(HostDistance distance) { switch (distance) { case HostDistance.Local: return _coreConnectionsForLocal; case HostDistance.Remote: return _coreConnectionsForRemote; default: return 0; } } /// <summary> /// Sets the core number of connections per host. /// </summary> /// <param name="distance"> the <see cref="HostDistance"/> for which to set this threshold.</param> /// <param name="coreConnections"> the value to set </param> /// <returns>this <c>PoolingOptions</c>. </returns> /// <throws name="IllegalArgumentException"> if <c>distance == HostDistance.Ignored</c>.</throws> public PoolingOptions SetCoreConnectionsPerHost(HostDistance distance, int coreConnections) { switch (distance) { case HostDistance.Local: _coreConnectionsForLocal = coreConnections; break; case HostDistance.Remote: _coreConnectionsForRemote = coreConnections; break; default: throw new ArgumentOutOfRangeException("Cannot set core connections per host for " + distance + " hosts"); } return this; } /// <summary> /// The maximum number of connections per host. <p> For the provided /// <c>distance</c>, this correspond to the maximum number of connections /// that can be created per host at that distance.</p> /// </summary> /// <param name="distance"> the <c>HostDistance</c> for which to return this threshold. /// </param> /// /// <returns>the maximum number of connections per host at distance /// <c>distance</c>.</returns> public int GetMaxConnectionPerHost(HostDistance distance) { switch (distance) { case HostDistance.Local: return _maxConnectionsForLocal; case HostDistance.Remote: return _maxConnectionsForRemote; default: return 0; } } /// <summary> /// Sets the maximum number of connections per host. /// </summary> /// <param name="distance"> the <c>HostDistance</c> for which to set this threshold. /// </param> /// <param name="maxConnections"> the value to set </param> /// /// <returns>this <c>PoolingOptions</c>. </returns> public PoolingOptions SetMaxConnectionsPerHost(HostDistance distance, int maxConnections) { switch (distance) { case HostDistance.Local: _maxConnectionsForLocal = maxConnections; break; case HostDistance.Remote: _maxConnectionsForRemote = maxConnections; break; default: throw new ArgumentOutOfRangeException("Cannot set max connections per host for " + distance + " hosts"); } return this; } /// <summary> /// Gets the amount of idle time in milliseconds that has to pass /// before the driver issues a request on an active connection to avoid /// idle time disconnections. /// <remarks> /// A value of <c>0</c> or <c>null</c> means that the heartbeat /// functionality at connection level is disabled. /// </remarks> /// </summary> public int? GetHeartBeatInterval() { return _heartBeatInterval; } /// <summary> /// Sets the amount of idle time in milliseconds that has to pass /// before the driver issues a request on an active connection to avoid /// idle time disconnections. /// <remarks> /// When set to <c>0</c> the heartbeat functionality at connection /// level is disabled. /// </remarks> /// </summary> public PoolingOptions SetHeartBeatInterval(int value) { _heartBeatInterval = value; return this; } /// <summary> /// Gets the default protocol options by protocol version /// </summary> internal static PoolingOptions GetDefault(byte protocolVersion) { if (protocolVersion < 3) { //New instance of pooling options with default values return new PoolingOptions(); } //New instance of pooling options with default values for high number of concurrent requests return new PoolingOptions() .SetCoreConnectionsPerHost(HostDistance.Local, 1) .SetMaxConnectionsPerHost(HostDistance.Local, 2) .SetMaxConnectionsPerHost(HostDistance.Remote, 1) .SetMaxConnectionsPerHost(HostDistance.Remote, 1) .SetMaxSimultaneousRequestsPerConnectionTreshold(HostDistance.Local, 1500) .SetMaxSimultaneousRequestsPerConnectionTreshold(HostDistance.Remote, 1500); } } }
using System; using System.IO; using System.Linq; using NUnit.Framework; using SIL.Lift.Options; using SIL.TestUtilities; using SIL.WritingSystems; using SIL.WritingSystems.Tests; namespace SIL.Lift.Tests.Options { [TestFixture] [OfflineSldr] public class WritingSystemsInOptionsListFileHelperTests { private class TestEnvironment : IDisposable { private readonly TemporaryFolder _folder; private readonly IO.TempFile _optionListFile; public TestEnvironment(string rfctag) : this(rfctag, "x-dontcare") { } public TestEnvironment(string rfctag, string rfctag2) { _folder = new TemporaryFolder("WritingSystemsInoptionListFileHelper"); var pathtoOptionsListFile1 = Path.Combine(_folder.Path, "test1.xml"); _optionListFile = new IO.TempFile(String.Format(_optionListFileContent, rfctag, rfctag2)); _optionListFile.MoveTo(pathtoOptionsListFile1); } #region LongFileContent private readonly string _optionListFileContent = @"<?xml version='1.0' encoding='utf-8'?> <optionsList> <options> <option> <key>Verb</key> <name> <form lang='{0}'>verb</form> <form lang='{1}'>verbe</form> </name> <abbreviation> <form lang='{0}'>verb</form> </abbreviation> <description> <form lang='{1}'>verbe</form> </description> </option> <option> <key>Noun</key> <name> <form lang='{0}'>noun</form> <form lang='{1}'>nom</form> </name> <abbreviation> <form lang='{0}'>noun</form> <form lang='{1}'>nom</form> </abbreviation> <description> <form lang='{0}'>noun</form> <form lang='{1}'>nom</form> </description> </option> </options> </optionsList>".Replace("'", "\""); private WritingSystemsInOptionsListFileHelper _helper; #endregion private void CreateWritingSystemRepository() { WritingSystemRepository = new TestLdmlInFolderWritingSystemRepository(WritingSystemsPath); } private string ProjectPath { get { return _folder.Path; } } public WritingSystemsInOptionsListFileHelper Helper { get { if (_helper == null) { if (WritingSystemRepository == null) { CreateWritingSystemRepository(); } _helper = new WritingSystemsInOptionsListFileHelper(WritingSystemRepository, _optionListFile.Path); } return _helper; } } public void Dispose() { _optionListFile.Dispose(); _folder.Dispose(); } private IWritingSystemRepository WritingSystemRepository { get; set; } public string WritingSystemsPath { get { return Path.Combine(ProjectPath, "WritingSystems"); } } public string PathToOptionsListFile { get { return _optionListFile.Path; } } public string GetLdmlFileforWs(string id) { return Path.Combine(WritingSystemsPath, String.Format("{0}.ldml", id)); } } [Test] public void CreateNonExistentWritingSystemsFoundInOptionsList_OptionsListFileContainsNonConformantRfcTag_CreatesConformingWritingSystem() { using (var e = new TestEnvironment("en", "fr")) { e.Helper.CreateNonExistentWritingSystemsFoundInFile(); Assert.That(File.Exists(e.GetLdmlFileforWs("en"))); Assert.That(File.Exists(e.GetLdmlFileforWs("fr"))); } } [Test] public void CreateNonExistentWritingSystemsFoundInOptionsList_OptionsListFileContainsNonConformantRfcTag_WsIdChangeLogUpdated() { using (var e = new TestEnvironment("x-bogusws1", "audio")) { e.Helper.CreateNonExistentWritingSystemsFoundInFile(); Assert.That(File.Exists(e.GetLdmlFileforWs("qaa-x-bogusws1"))); Assert.That(File.Exists(e.GetLdmlFileforWs("qaa-Zxxx-x-audio"))); string idChangeLogFilePath = Path.Combine(e.WritingSystemsPath, "idchangelog.xml"); AssertThatXmlIn.File(idChangeLogFilePath).HasAtLeastOneMatchForXpath("/WritingSystemChangeLog/Changes[Add/Id/text()='qaa-x-bogusws1' and Add/Id/text()='qaa-Zxxx-x-audio']"); } } [Test] public void CreateNonExistentWritingSystemsFoundInOptionsList_OptionsListFileContainsNonConformantRfcTag_UpdatesRfcTagInOptionsListFile() { using (var environment = new TestEnvironment("Zxxx-x-bogusws1", "audio")) { environment.Helper.CreateNonExistentWritingSystemsFoundInFile(); AssertThatXmlIn.File(environment.PathToOptionsListFile).HasAtLeastOneMatchForXpath("/optionsList/options/option/name/form[@lang='qaa-x-Zxxx-bogusws1']"); AssertThatXmlIn.File(environment.PathToOptionsListFile).HasAtLeastOneMatchForXpath("/optionsList/options/option/name/form[@lang='qaa-Zxxx-x-audio']"); } } [Test] public void CreateNonExistentWritingSystemsFoundInOptionsList_OptionsListFileContainsNonConformantRfcTagWithDuplicates_UpdatesRfcTagInOptionsListFile() { using (var environment = new TestEnvironment("wee", "x-wee")) { environment.Helper.CreateNonExistentWritingSystemsFoundInFile(); AssertThatXmlIn.File(environment.PathToOptionsListFile).HasAtLeastOneMatchForXpath("/optionsList/options/option/name/form[@lang='qaa-x-wee-dupl0']"); AssertThatXmlIn.File(environment.PathToOptionsListFile).HasAtLeastOneMatchForXpath("/optionsList/options/option/name/form[@lang='qaa-x-wee']"); } } [Test] public void CreateNonExistentWritingSystemsFoundInOptionsList_OptionsListFileContainsConformantRfcTagWithNoCorrespondingLdml_CreatesLdml() { using (var e = new TestEnvironment("de", "x-dontcare")) { e.Helper.CreateNonExistentWritingSystemsFoundInFile(); AssertThatXmlIn.File(e.PathToOptionsListFile).HasAtLeastOneMatchForXpath("/optionsList/options/option/name/form[@lang='de']"); Assert.That(File.Exists(e.GetLdmlFileforWs("de")), Is.True); AssertThatXmlIn.File(e.GetLdmlFileforWs("de")).HasAtLeastOneMatchForXpath("/ldml/identity/language[@type='de']"); AssertThatXmlIn.File(e.GetLdmlFileforWs("de")).HasNoMatchForXpath("/ldml/identity/script"); AssertThatXmlIn.File(e.GetLdmlFileforWs("de")).HasNoMatchForXpath("/ldml/identity/territory"); AssertThatXmlIn.File(e.GetLdmlFileforWs("de")).HasNoMatchForXpath("/ldml/identity/variant"); } } [Test] public void CreateNonExistentWritingSystemsFoundInOptionsList_OptionsListFileContainsEntirelyPrivateUseRfcTagThatDoesNotExistInRepo_RfcTagIsMigrated() { using (var e = new TestEnvironment("x-blah")) { e.Helper.CreateNonExistentWritingSystemsFoundInFile(); Assert.That(File.Exists(e.GetLdmlFileforWs("qaa-x-blah")), Is.True); AssertThatXmlIn.File(e.PathToOptionsListFile).HasAtLeastOneMatchForXpath("/optionsList/options/option/name/form[@lang='qaa-x-blah']"); } } [Test] //This test makes sure that nonexisting private use tags are migrated if necessary public void CreateNonExistentWritingSystemsFoundInOptionsList_OptionsListFileContainsAudioTagThatDoesNotExistInRepo_RfcTagIsMigrated() { using (var e = new TestEnvironment("x-audio")) { e.Helper.CreateNonExistentWritingSystemsFoundInFile(); Assert.That(File.Exists(e.GetLdmlFileforWs("x-audio")), Is.False); Assert.That(File.Exists(e.GetLdmlFileforWs("qaa-Zxxx-x-audio")), Is.True); AssertThatXmlIn.File(e.PathToOptionsListFile).HasNoMatchForXpath("/optionsList/options/option/name/form[@lang='x-audio']"); AssertThatXmlIn.File(e.PathToOptionsListFile).HasAtLeastOneMatchForXpath("/optionsList/options/option/name/form[@lang='qaa-Zxxx-x-audio']"); } } [Test] public void CreateNonExistentWritingSystemsFoundInOptionsList_OptionsListFileContainsNonConformantRfcTagWithDuplicatesContainingduplicateMarker_UpdatesRfcTagInOptionsListFile() { using (var environment = new TestEnvironment("wee-dupl1", "x-wee-dupl1")) { environment.Helper.CreateNonExistentWritingSystemsFoundInFile(); AssertThatXmlIn.File(environment.PathToOptionsListFile).HasAtLeastOneMatchForXpath("/optionsList/options/option/name/form[@lang='qaa-x-wee-dupl1']"); AssertThatXmlIn.File(environment.PathToOptionsListFile).HasAtLeastOneMatchForXpath("/optionsList/options/option/name/form[@lang='qaa-x-wee-dupl1-dupl0']"); } } [Test] public void Ctr_FileIsNotXml_MethodsBehave() { using (var environment = new TestEnvironment("wee-dupl1", "x-wee-dupl1")) { File.WriteAllText(environment.PathToOptionsListFile, "text"); environment.Helper.CreateNonExistentWritingSystemsFoundInFile(); environment.Helper.ReplaceWritingSystemId("text", "test"); Assert.That(environment.Helper.WritingSystemsInUse.Count(), Is.EqualTo(0)); Assert.That(File.ReadAllText(environment.PathToOptionsListFile), Is.EqualTo("text")); } } [Test] public void Ctr_FileIsXmlButNotOptionList_MethodsBehave() { using (var environment = new TestEnvironment("wee-dupl1", "x-wee-dupl1")) { File.WriteAllText(environment.PathToOptionsListFile, "<?xml version='1.0' encoding='utf-8'?>\r\n<form>yo</form>".Replace("'", "\"")); environment.Helper.CreateNonExistentWritingSystemsFoundInFile(); environment.Helper.ReplaceWritingSystemId("text", "test"); Assert.That(environment.Helper.WritingSystemsInUse.Count(), Is.EqualTo(0)); Assert.That(File.ReadAllText(environment.PathToOptionsListFile), Is.EqualTo("<?xml version='1.0' encoding='utf-8'?>\r\n<form>yo</form>".Replace("'", "\""))); } } [Test] public void ReplaceWritingSystemId_FormForNewWritingSystemAlreadyExists_RemoveOldWritingSystemForm() { using (var environment = new TestEnvironment("th", "de")) { environment.Helper.CreateNonExistentWritingSystemsFoundInFile(); environment.Helper.ReplaceWritingSystemId("th", "de"); Assert.That(environment.Helper.WritingSystemsInUse.Count(), Is.EqualTo(1)); AssertThatXmlIn.File(environment.PathToOptionsListFile).HasNoMatchForXpath("//form[@lang='th']"); AssertThatXmlIn.File(environment.PathToOptionsListFile).HasNoMatchForXpath("/optionsList/options/option/name/form[@lang='de'][text()='verb']"); AssertThatXmlIn.File(environment.PathToOptionsListFile).HasSpecifiedNumberOfMatchesForXpath("/optionsList/options/option/name/form[@lang='de'][text()='verbe']", 1); AssertThatXmlIn.File(environment.PathToOptionsListFile).HasSpecifiedNumberOfMatchesForXpath("/optionsList/options/option/abbreviation/form[@lang='de'][text()='verb']", 1); AssertThatXmlIn.File(environment.PathToOptionsListFile).HasSpecifiedNumberOfMatchesForXpath("/optionsList/options/option/description/form[@lang='de'][text()='verbe']", 1); AssertThatXmlIn.File(environment.PathToOptionsListFile).HasSpecifiedNumberOfMatchesForXpath("/optionsList/options/option/name/form[@lang='de'][text()='nom']", 1); AssertThatXmlIn.File(environment.PathToOptionsListFile).HasNoMatchForXpath("/optionsList/options/option/name/form[@lang='de'][text()='noun']"); AssertThatXmlIn.File(environment.PathToOptionsListFile).HasSpecifiedNumberOfMatchesForXpath("/optionsList/options/option/abbreviation/form[@lang='de'][text()='nom']", 1); AssertThatXmlIn.File(environment.PathToOptionsListFile).HasNoMatchForXpath("/optionsList/options/option/abbreviation/form[@lang='de'][text()='noun']"); AssertThatXmlIn.File(environment.PathToOptionsListFile).HasSpecifiedNumberOfMatchesForXpath("/optionsList/options/option/description/form[@lang='de'][text()='nom']", 1); AssertThatXmlIn.File(environment.PathToOptionsListFile).HasNoMatchForXpath("/optionsList/options/option/description/form[@lang='de'][text()='noun']"); } } [Test] public void DeleteWritingSystemId_FormForNewWritingSystemAlreadyExists_RemoveOldWritingSystemForm() { using (var environment = new TestEnvironment("th", "de")) { environment.Helper.CreateNonExistentWritingSystemsFoundInFile(); environment.Helper.DeleteWritingSystemId("th"); Assert.That(environment.Helper.WritingSystemsInUse.Count(), Is.EqualTo(1)); AssertThatXmlIn.File(environment.PathToOptionsListFile).HasNoMatchForXpath("//form[@lang='th']"); AssertThatXmlIn.File(environment.PathToOptionsListFile).HasNoMatchForXpath("/optionsList/options/option/name/form[@lang='th'][text()='verb']"); AssertThatXmlIn.File(environment.PathToOptionsListFile).HasSpecifiedNumberOfMatchesForXpath("/optionsList/options/option/name/form[@lang='de'][text()='verbe']", 1); AssertThatXmlIn.File(environment.PathToOptionsListFile).HasNoMatchForXpath("/optionsList/options/option/abbreviation/form[@lang='th'][text()='verb']"); AssertThatXmlIn.File(environment.PathToOptionsListFile).HasSpecifiedNumberOfMatchesForXpath("/optionsList/options/option/description/form[@lang='de'][text()='verbe']", 1); AssertThatXmlIn.File(environment.PathToOptionsListFile).HasSpecifiedNumberOfMatchesForXpath("/optionsList/options/option/name/form[@lang='de'][text()='nom']", 1); AssertThatXmlIn.File(environment.PathToOptionsListFile).HasNoMatchForXpath("/optionsList/options/option/name/form[@lang='th'][text()='noun']"); AssertThatXmlIn.File(environment.PathToOptionsListFile).HasSpecifiedNumberOfMatchesForXpath("/optionsList/options/option/abbreviation/form[@lang='de'][text()='nom']", 1); AssertThatXmlIn.File(environment.PathToOptionsListFile).HasNoMatchForXpath("/optionsList/options/option/abbreviation/form[@lang='th'][text()='noun']"); AssertThatXmlIn.File(environment.PathToOptionsListFile).HasSpecifiedNumberOfMatchesForXpath("/optionsList/options/option/description/form[@lang='de'][text()='nom']", 1); AssertThatXmlIn.File(environment.PathToOptionsListFile).HasNoMatchForXpath("/optionsList/options/option/description/form[@lang='th'][text()='noun']"); } } } }
// // TextLayout.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // Lytico (http://limada.sourceforge.net) // // Copyright (c) 2011 Xamarin 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 System; using Xwt.Backends; using System.Collections.Generic; namespace Xwt.Drawing { public sealed class TextLayout: XwtObject, IDisposable { TextLayoutBackendHandler handler; Font font; string text; double width = -1; double height = -1; TextTrimming textTrimming; List<TextAttribute> attributes; public TextLayout () { handler = ToolkitEngine.TextLayoutBackendHandler; Backend = handler.Create (); Font = Font.SystemFont; Setup (); } public TextLayout (Canvas canvas) { ToolkitEngine = canvas.Surface.ToolkitEngine; handler = ToolkitEngine.TextLayoutBackendHandler; Backend = handler.Create (); Font = canvas.Font; Setup (); } internal TextLayout (Toolkit tk) { ToolkitEngine = tk; handler = ToolkitEngine.TextLayoutBackendHandler; Backend = handler.Create (); Setup (); } void Setup () { if (handler.DisposeHandleOnUiThread) ResourceManager.RegisterResource (Backend, handler.Dispose); else GC.SuppressFinalize (this); } public void Dispose () { if (handler.DisposeHandleOnUiThread) { GC.SuppressFinalize (this); ResourceManager.FreeResource (Backend); } else handler.Dispose (Backend); } ~TextLayout () { ResourceManager.FreeResource (Backend); } internal TextLayoutData GetData () { return new TextLayoutData () { Width = width, Height = height, Text = text, Font = font, TextTrimming = textTrimming, Attributes = attributes != null ? new List<TextAttribute> (attributes) : null }; } public Font Font { get { return font; } set { font = value; handler.SetFont (Backend, value); } } public string Text { get { return text; } set { text = value; handler.SetText (Backend, text); } } /// <summary> /// Gets or sets the desired width. /// </summary> /// <value> /// The width. A value of -1 uses GetSize().Width on drawings /// </value> public double Width { get { return width; } set { width = value; handler.SetWidth (Backend, value); } } /// <summary> /// Gets or sets desired Height. /// </summary> /// <value> /// The Height. A value of -1 uses GetSize().Height on drawings /// </value> public double Height { get { return this.height; } set { this.height = value; handler.SetHeight (Backend, value); } } /// <summary> /// measures the text /// if Width is other than -1, it measures the height according to Width /// Height is ignored /// </summary> /// <returns> /// The size. /// </returns> public Size GetSize () { return handler.GetSize (Backend); } public TextTrimming Trimming { get { return textTrimming; } set { textTrimming = value; handler.SetTrimming (Backend, value); } } /// <summary> /// Converts from a X and Y position within the layout to the character at this position. /// </summary> /// <returns>The index of the character.</returns> /// <param name="x">The x coordinate.</param> /// <param name="y">The y coordinate.</param> public int GetIndexFromCoordinates (double x, double y) { return handler.GetIndexFromCoordinates (Backend, x, y); } /// <summary> /// Converts from a Position within the layout to the character at this position. /// </summary> /// <returns>The index of the character.</returns> /// <param name="p">The position.</param> public int GetIndexFromCoordinates (Point p) { return handler.GetIndexFromCoordinates (Backend, p.X, p.Y); } /// <summary> /// Obtains the graphical coordinate of an character in the layout. /// </summary> /// <returns>The extends from the character at index.</returns> /// <param name="index">The index of the character.</param> public Point GetCoordinateFromIndex (int index) { return handler.GetCoordinateFromIndex (Backend, index); } List<TextAttribute> Attributes { get { if (attributes == null) attributes = new List<TextAttribute> (); return attributes; } } string markup; public string Markup { get { return markup; } set { markup = value; var t = FormattedText.FromMarkup (markup); Text = t.Text; ClearAttributes (); foreach (var at in t.Attributes) AddAttribute (at); } } public void AddAttribute (TextAttribute attribute) { Attributes.Add (attribute.Clone ()); handler.AddAttribute (Backend, attribute); } public void ClearAttributes () { Attributes.Clear (); handler.ClearAttributes (Backend); } /// <summary> /// Sets the foreground color of a part of text inside the <see cref="T:Xwt.Drawing.TextLayout"/> object. /// </summary> /// <param name="color">The color of the text.</param> /// <param name="startIndex">Start index of the first character to apply the foreground color to.</param> /// <param name="count">The number of characters to apply the foreground color to.</param> public void SetForeground (Color color, int startIndex, int count) { AddAttribute (new ColorTextAttribute () { StartIndex = startIndex, Count = count, Color = color }); } /// <summary> /// Sets the background color of a part of text inside the <see cref="T:Xwt.Drawing.TextLayout"/> object. /// </summary> /// <param name="color">The color of the text background.</param> /// <param name="startIndex">Start index of the first character to apply the background color to.</param> /// <param name="count">The number of characters to apply the background color to.</param> public void SetBackground (Color color, int startIndex, int count) { AddAttribute (new BackgroundTextAttribute () { StartIndex = startIndex, Count = count, Color = color }); } /// <summary> /// Sets the font weight of a part of text inside the <see cref="T:Xwt.Drawing.TextLayout"/> object. /// </summary> /// <param name="weight">The font weight of the text.</param> /// <param name="startIndex">Start index of the first character to apply the font weight to.</param> /// <param name="count">The number of characters to apply the font weight to.</param> public void SetFontWeight (FontWeight weight, int startIndex, int count) { AddAttribute (new FontWeightTextAttribute () { StartIndex = startIndex, Count = count, Weight = weight }); } /// <summary> /// Sets the font style of a part of text inside the <see cref="T:Xwt.Drawing.TextLayout"/> object. /// </summary> /// <param name="style">The font style of the text.</param> /// <param name="startIndex">Start index of the first character to apply the font style to.</param> /// <param name="count">The number of characters to apply the font style to.</param> public void SetFontStyle (FontStyle style, int startIndex, int count) { AddAttribute (new FontStyleTextAttribute () { StartIndex = startIndex, Count = count, Style = style }); } /// <summary> /// Underlines a part of text inside the <see cref="T:Xwt.Drawing.TextLayout"/> object. /// </summary> /// <param name="startIndex">Start index of the first character to underline.</param> /// <param name="count">The number of characters to underline.</param> public void SetUnderline (int startIndex, int count) { AddAttribute (new UnderlineTextAttribute () { StartIndex = startIndex, Count = count}); } /// <summary> /// Adds a strike-through to a part of text inside the <see cref="T:Xwt.Drawing.TextLayout"/> object. /// </summary> /// <param name="startIndex">Start index of the first character to strike-through.</param> /// <param name="count">The number of characters to strike-through.</param> public void SetStrikethrough (int startIndex, int count) { AddAttribute (new StrikethroughTextAttribute () { StartIndex = startIndex, Count = count}); } } public enum TextTrimming { Word, WordElipsis } class TextLayoutData { public double Width = -1; public double Height = -1; public string Text; public Font Font; public TextTrimming TextTrimming; public List<TextAttribute> Attributes; public void InitLayout (TextLayout la) { if (Width != -1) la.Width = Width; if (Height != -1) la.Height = Height; if (Text != null) la.Text = Text; if (Font != null) la.Font = Font; if (TextTrimming != default(TextTrimming)) la.Trimming = TextTrimming; if (Attributes != null) { foreach (var at in Attributes) la.AddAttribute (at); } } public bool Equals (TextLayoutData other) { if (Width != other.Width || Height != other.Height || Text != other.Text || Font != other.Font || TextTrimming != other.TextTrimming) return false; if (Attributes == null && other.Attributes == null) return true; if (Attributes != null || other.Attributes != null) return false; if (Attributes.Count != other.Attributes.Count) return false; for (int n=0; n<Attributes.Count; n++) if (!Attributes [n].Equals (other.Attributes [n])) return false; return true; } } }
// 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.Runtime.CompilerServices; using System.Runtime.Versioning; #if BIT64 using nuint = System.UInt64; using nint = System.Int64; #else using nuint = System.UInt32; using nint = System.Int32; #endif // // The implementations of most the methods in this file are provided as intrinsics. // In CoreCLR, the body of the functions are replaced by the EE with unsafe code. See see getILIntrinsicImplementationForUnsafe for details. // In CoreRT, see Internal.IL.Stubs.UnsafeIntrinsics for details. // namespace Internal.Runtime.CompilerServices { // // Subsetted clone of System.Runtime.CompilerServices.Unsafe for internal runtime use. // Keep in sync with https://github.com/dotnet/corefx/tree/master/src/System.Runtime.CompilerServices.Unsafe. // /// <summary> /// For internal use only. Contains generic, low-level functionality for manipulating pointers. /// </summary> [CLSCompliant(false)] public static unsafe class Unsafe { /// <summary> /// Returns a pointer to the given by-ref parameter. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void* AsPointer<T>(ref T value) { throw new PlatformNotSupportedException(); // ldarg.0 // conv.u // ret } /// <summary> /// Returns the size of an object of the given type parameter. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int SizeOf<T>() { #if CORECLR typeof(T).ToString(); // Type token used by the actual method body #endif throw new PlatformNotSupportedException(); // sizeof !!0 // ret } /// <summary> /// Casts the given object to the specified type, performs no dynamic type checking. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T As<T>(object value) where T : class { throw new PlatformNotSupportedException(); // ldarg.0 // ret } /// <summary> /// Reinterprets the given reference as a reference to a value of type <typeparamref name="TTo"/>. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref TTo As<TFrom, TTo>(ref TFrom source) { throw new PlatformNotSupportedException(); // ldarg.0 // ret } /// <summary> /// Adds an element offset to the given reference. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T Add<T>(ref T source, int elementOffset) { #if CORECLR typeof(T).ToString(); // Type token used by the actual method body throw new PlatformNotSupportedException(); #else return ref AddByteOffset(ref source, (IntPtr)(elementOffset * (nint)SizeOf<T>())); #endif } /// <summary> /// Adds an element offset to the given reference. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T Add<T>(ref T source, IntPtr elementOffset) { #if CORECLR typeof(T).ToString(); // Type token used by the actual method body throw new PlatformNotSupportedException(); #else return ref AddByteOffset(ref source, (IntPtr)((nint)elementOffset * (nint)SizeOf<T>())); #endif } /// <summary> /// Adds an element offset to the given pointer. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void* Add<T>(void* source, int elementOffset) { #if CORECLR typeof(T).ToString(); // Type token used by the actual method body throw new PlatformNotSupportedException(); #else return (byte*)source + (elementOffset * (nint)SizeOf<T>()); #endif } /// <summary> /// Adds an element offset to the given reference. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static ref T AddByteOffset<T>(ref T source, nuint byteOffset) { return ref AddByteOffset(ref source, (IntPtr)(void*)byteOffset); } /// <summary> /// Determines whether the specified references point to the same location. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool AreSame<T>(ref T left, ref T right) { throw new PlatformNotSupportedException(); // ldarg.0 // ldarg.1 // ceq // ret } /// <summary> /// Initializes a block of memory at the given location with a given initial value /// without assuming architecture dependent alignment of the address. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void InitBlockUnaligned(ref byte startAddress, byte value, uint byteCount) { for (uint i = 0; i < byteCount; i++) AddByteOffset(ref startAddress, i) = value; } /// <summary> /// Reads a value of type <typeparamref name="T"/> from the given location. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T ReadUnaligned<T>(void* source) { #if CORECLR typeof(T).ToString(); // Type token used by the actual method body throw new PlatformNotSupportedException(); #else return Unsafe.As<byte, T>(ref *(byte*)source); #endif } /// <summary> /// Reads a value of type <typeparamref name="T"/> from the given location. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T ReadUnaligned<T>(ref byte source) { #if CORECLR typeof(T).ToString(); // Type token used by the actual method body throw new PlatformNotSupportedException(); #else return Unsafe.As<byte, T>(ref source); #endif } /// <summary> /// Writes a value of type <typeparamref name="T"/> to the given location. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteUnaligned<T>(void* destination, T value) { #if CORECLR typeof(T).ToString(); // Type token used by the actual method body throw new PlatformNotSupportedException(); #else Unsafe.As<byte, T>(ref *(byte*)destination) = value; #endif } /// <summary> /// Writes a value of type <typeparamref name="T"/> to the given location. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteUnaligned<T>(ref byte destination, T value) { #if CORECLR typeof(T).ToString(); // Type token used by the actual method body throw new PlatformNotSupportedException(); #else Unsafe.As<byte, T>(ref destination) = value; #endif } /// <summary> /// Adds an element offset to the given reference. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T AddByteOffset<T>(ref T source, IntPtr byteOffset) { // This method is implemented by the toolchain throw new PlatformNotSupportedException(); // ldarg.0 // ldarg.1 // add // ret } /// <summary> /// Reads a value of type <typeparamref name="T"/> from the given location. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T Read<T>(void* source) { return Unsafe.As<byte, T>(ref *(byte*)source); } /// <summary> /// Reads a value of type <typeparamref name="T"/> from the given location. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T Read<T>(ref byte source) { return Unsafe.As<byte, T>(ref source); } /// <summary> /// Writes a value of type <typeparamref name="T"/> to the given location. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Write<T>(void* destination, T value) { Unsafe.As<byte, T>(ref *(byte*)destination) = value; } /// <summary> /// Writes a value of type <typeparamref name="T"/> to the given location. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Write<T>(ref byte destination, T value) { Unsafe.As<byte, T>(ref destination) = value; } /// <summary> /// Reinterprets the given location as a reference to a value of type <typeparamref name="T"/>. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T AsRef<T>(void* source) { return ref Unsafe.As<byte, T>(ref *(byte*)source); } /// <summary> /// Determines the byte offset from origin to target from the given references. /// </summary> [Intrinsic] [NonVersionable] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static IntPtr ByteOffset<T>(ref T origin, ref T target) { throw new PlatformNotSupportedException(); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. extern alias core; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading.Tasks; using core::Roslyn.Utilities; using EnvDTE; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Interactive; using Microsoft.VisualStudio; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.InteractiveWindow; using Microsoft.VisualStudio.InteractiveWindow.Shell; using VSLangProj; using Project = EnvDTE.Project; using System.Collections.Immutable; namespace Microsoft.VisualStudio.LanguageServices.Interactive { internal sealed class ResetInteractive { private readonly DTE _dte; private readonly IComponentModel _componentModel; private readonly IVsMonitorSelection _monitorSelection; private readonly IVsSolutionBuildManager _buildManager; private readonly Func<string, string> _createReference; private readonly Func<string, string> _createImport; internal ResetInteractive(DTE dte, IComponentModel componentModel, IVsMonitorSelection monitorSelection, IVsSolutionBuildManager buildManager, Func<string, string> createReference, Func<string, string> createImport) { _dte = dte; _componentModel = componentModel; _monitorSelection = monitorSelection; _buildManager = buildManager; _createReference = createReference; _createImport = createImport; } internal void Execute(IVsInteractiveWindow vsInteractiveWindow, string title) { var hierarchyPointer = default(IntPtr); var selectionContainerPointer = default(IntPtr); try { uint itemid; IVsMultiItemSelect multiItemSelectPointer; Marshal.ThrowExceptionForHR(_monitorSelection.GetCurrentSelection( out hierarchyPointer, out itemid, out multiItemSelectPointer, out selectionContainerPointer)); if (hierarchyPointer != IntPtr.Zero) { List<string> references, referenceSearchPaths, sourceSearchPaths, namespacesToImport; string projectDirectory; GetProjectProperties(hierarchyPointer, out references, out referenceSearchPaths, out sourceSearchPaths, out namespacesToImport, out projectDirectory); // Now, we're going to do a bunch of async operations. So create a wait // indicator so the user knows something is happening, and also so they cancel. var waitIndicator = _componentModel.GetService<IWaitIndicator>(); var waitContext = waitIndicator.StartWait(title, ServicesVSResources.BuildingProject, allowCancel: true); var resetInteractiveTask = ResetInteractiveAsync( vsInteractiveWindow, references.ToImmutableArray(), referenceSearchPaths.ToImmutableArray(), sourceSearchPaths.ToImmutableArray(), namespacesToImport.ToImmutableArray(), projectDirectory, waitContext); // Once we're done resetting, dismiss the wait indicator and focus the REPL window. resetInteractiveTask.SafeContinueWith( _ => { waitContext.Dispose(); // We have to set focus to the Interactive Window *after* the wait indicator is dismissed. vsInteractiveWindow.Show(focus: true); }, TaskScheduler.FromCurrentSynchronizationContext()); } } finally { SafeRelease(hierarchyPointer); SafeRelease(selectionContainerPointer); } } private async Task ResetInteractiveAsync( IVsInteractiveWindow vsInteractiveWindow, ImmutableArray<string> referencePaths, ImmutableArray<string> referenceSearchPaths, ImmutableArray<string> sourceSearchPaths, ImmutableArray<string> namespacesToImport, string projectDirectory, IWaitContext waitContext) { // First, open the repl window. var engine = (InteractiveEvaluator)vsInteractiveWindow.InteractiveWindow.Evaluator; // If the user hits the cancel button on the wait indicator, then we want to stop the // build. waitContext.CancellationToken.Register(() => _dte.ExecuteCommand("Build.Cancel"), useSynchronizationContext: true); // First, start a build await BuildProject().ConfigureAwait(true); // Then reset the REPL waitContext.Message = ServicesVSResources.ResettingInteractive; await vsInteractiveWindow.InteractiveWindow.Operations.ResetAsync(initialize: false).ConfigureAwait(true); // Now send the reference paths we've collected to the repl. await engine.SetPathsAsync(referenceSearchPaths, sourceSearchPaths, projectDirectory).ConfigureAwait(true); await vsInteractiveWindow.InteractiveWindow.SubmitAsync(new[] { referencePaths.Select(_createReference).Join("\r\n"), namespacesToImport.Select(_createImport).Join("\r\n") }).ConfigureAwait(true); } private static void GetProjectProperties( IntPtr hierarchyPointer, out List<string> references, out List<string> referenceSearchPaths, out List<string> sourceSearchPaths, out List<string> namespacesToImport, out string projectDirectory) { var hierarchy = (IVsHierarchy)Marshal.GetObjectForIUnknown(hierarchyPointer); object extensibilityObject; Marshal.ThrowExceptionForHR( hierarchy.GetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID.VSHPROPID_ExtObject, out extensibilityObject)); // TODO: Revert this back to using dynamic for web projects, since they have copies of these interfaces. var project = (Project)extensibilityObject; var vsProject = (VSProject)project.Object; references = new List<string>(); referenceSearchPaths = new List<string>(); sourceSearchPaths = new List<string>(); namespacesToImport = new List<string>(); var projectDir = (string)project.Properties.Item("FullPath").Value; var outputFileName = (string)project.Properties.Item("OutputFileName").Value; var defaultNamespace = (string)project.Properties.Item("DefaultNamespace").Value; var relativeOutputPath = (string)project.ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath").Value; Debug.Assert(!string.IsNullOrEmpty(projectDir)); Debug.Assert(!string.IsNullOrEmpty(outputFileName)); Debug.Assert(!string.IsNullOrEmpty(relativeOutputPath)); var scriptsDir = Path.Combine(projectDir, "Scripts"); var outputDir = Path.Combine(projectDir, relativeOutputPath); projectDirectory = projectDir; referenceSearchPaths.Add(outputDir); referenceSearchPaths.Add(RuntimeEnvironment.GetRuntimeDirectory()); foreach (Reference reference in vsProject.References) { var str = GetReferenceString(reference); if (str != null) { references.Add(str); } } references.Add(outputFileName); // TODO (tomat): project Scripts dir sourceSearchPaths.Add(Directory.Exists(scriptsDir) ? scriptsDir : projectDir); if (!string.IsNullOrEmpty(defaultNamespace)) { namespacesToImport.Add(defaultNamespace); } } private static string GetReferenceString(Reference reference) { if (!reference.StrongName) { return reference.Path; } string name = reference.Name; if (name == "mscorlib") { // mscorlib is always loaded return null; } // TODO: This shouldn't directly depend on GAC, rather we should have some kind of "reference simplifier". var possibleGacNames = GlobalAssemblyCache.GetAssemblyIdentities(name).ToArray(); if (possibleGacNames.Length == 0) { // no assembly with simple "name" found in GAC, use path to identify the reference: return reference.Path; } string version = reference.Version; string culture = reference.Culture; string publicKeyToken = reference.PublicKeyToken; var fullName = string.Concat( name, ", Version=", version, ", Culture=", (culture == "") ? "neutral" : culture, ", PublicKeyToken=", publicKeyToken.ToLowerInvariant()); AssemblyIdentity identity; if (!AssemblyIdentity.TryParseDisplayName(fullName, out identity)) { // ignore invalid names: return null; } var foundEquivalent = false; var foundNonEquivalent = false; foreach (var possibleGacName in possibleGacNames) { if (DesktopAssemblyIdentityComparer.Default.ReferenceMatchesDefinition(identity, possibleGacName)) { foundEquivalent = true; } else { foundNonEquivalent = true; } if (foundEquivalent && foundNonEquivalent) { break; } } if (!foundEquivalent) { // The reference name isn't equivalent to any GAC name. // The assembly is strong named but not GAC'd, so we need to load it from path: return reference.Path; } if (foundNonEquivalent) { // We found some equivalent assemblies but also some non-equivalent. // So simple name doesn't identify the reference uniquely. return fullName; } // We found a single simple name match that is equivalent to the given reference. // We can use the simple name to load the GAC'd assembly. return name; } private static void SafeRelease(IntPtr pointer) { if (pointer != IntPtr.Zero) { Marshal.Release(pointer); } } private Task<bool> BuildProject() { var taskSource = new TaskCompletionSource<bool>(); var updateSolutionEvents = new VsUpdateSolutionEvents(_buildManager, taskSource); // Build the project. When project build is done, set the task source as being done. // (Either succeeded, cancelled, or failed). _dte.ExecuteCommand("Build.BuildSelection"); return taskSource.Task; } } }
// ---------------------------------------------------------------------------- // <copyright file="PhotonAnimatorViewEditor.cs" company="Exit Games GmbH"> // PhotonNetwork Framework for Unity - Copyright (C) 2018 Exit Games GmbH // </copyright> // <summary> // This is a custom editor for the AnimatorView component. // </summary> // <author>developer@exitgames.com</author> // ---------------------------------------------------------------------------- namespace Photon.Pun { using System.Collections.Generic; using UnityEditor; using UnityEditor.Animations; using UnityEngine; [CustomEditor(typeof(PhotonAnimatorView))] public class PhotonAnimatorViewEditor : Editor { private Animator m_Animator; private PhotonAnimatorView m_Target; private AnimatorController m_Controller; public override void OnInspectorGUI() { //base.OnInspectorGUI(); if (this.m_Animator == null) { GUILayout.BeginVertical(GUI.skin.box); GUILayout.Label("GameObject doesn't have an Animator component to synchronize"); GUILayout.EndVertical(); return; } this.DrawWeightInspector(); if (this.GetLayerCount() == 0) { GUILayout.BeginVertical(GUI.skin.box); GUILayout.Label("Animator doesn't have any layers setup to synchronize"); GUILayout.EndVertical(); } this.DrawParameterInspector(); if (this.GetParameterCount() == 0) { GUILayout.BeginVertical(GUI.skin.box); GUILayout.Label("Animator doesn't have any parameters setup to synchronize"); GUILayout.EndVertical(); } this.serializedObject.ApplyModifiedProperties(); //GUILayout.Label( "m_SynchronizeLayers " + serializedObject.FindProperty( "m_SynchronizeLayers" ).arraySize ); //GUILayout.Label( "m_SynchronizeParameters " + serializedObject.FindProperty( "m_SynchronizeParameters" ).arraySize ); } private int GetLayerCount() { return (this.m_Controller == null) ? 0 : this.m_Controller.layers.Length; } private int GetParameterCount() { return (this.m_Controller == null) ? 0 : this.m_Controller.parameters.Length; } private AnimatorControllerParameter GetAnimatorControllerParameter(int i) { return this.m_Controller.parameters[i]; } private RuntimeAnimatorController GetEffectiveController(Animator animator) { RuntimeAnimatorController controller = animator.runtimeAnimatorController; AnimatorOverrideController overrideController = controller as AnimatorOverrideController; while (overrideController != null) { controller = overrideController.runtimeAnimatorController; overrideController = controller as AnimatorOverrideController; } return controller; } private void OnEnable() { this.m_Target = (PhotonAnimatorView)this.target; this.m_Animator = this.m_Target.GetComponent<Animator>(); this.m_Controller = this.GetEffectiveController(this.m_Animator) as AnimatorController; this.CheckIfStoredParametersExist(); } private void DrawWeightInspector() { SerializedProperty foldoutProperty = this.serializedObject.FindProperty("ShowLayerWeightsInspector"); foldoutProperty.boolValue = PhotonGUI.ContainerHeaderFoldout("Synchronize Layer Weights", foldoutProperty.boolValue); if (foldoutProperty.boolValue == false) { return; } float lineHeight = 20; Rect containerRect = PhotonGUI.ContainerBody(this.GetLayerCount() * lineHeight); for (int i = 0; i < this.GetLayerCount(); ++i) { if (this.m_Target.DoesLayerSynchronizeTypeExist(i) == false) { this.m_Target.SetLayerSynchronized(i, PhotonAnimatorView.SynchronizeType.Disabled); } PhotonAnimatorView.SynchronizeType syncType = this.m_Target.GetLayerSynchronizeType(i); Rect elementRect = new Rect(containerRect.xMin, containerRect.yMin + i * lineHeight, containerRect.width, lineHeight); Rect labelRect = new Rect(elementRect.xMin + 5, elementRect.yMin + 2, EditorGUIUtility.labelWidth - 5, elementRect.height); GUI.Label(labelRect, "Layer " + i); Rect popupRect = new Rect(elementRect.xMin + EditorGUIUtility.labelWidth, elementRect.yMin + 2, elementRect.width - EditorGUIUtility.labelWidth - 5, EditorGUIUtility.singleLineHeight); syncType = (PhotonAnimatorView.SynchronizeType)EditorGUI.EnumPopup(popupRect, syncType); if (i < this.GetLayerCount() - 1) { Rect splitterRect = new Rect(elementRect.xMin + 2, elementRect.yMax, elementRect.width - 4, 1); PhotonGUI.DrawSplitter(splitterRect); } if (syncType != this.m_Target.GetLayerSynchronizeType(i)) { Undo.RecordObject(this.target, "Modify Synchronize Layer Weights"); this.m_Target.SetLayerSynchronized(i, syncType); } } } private bool DoesParameterExist(string name) { for (int i = 0; i < this.GetParameterCount(); ++i) { if (this.GetAnimatorControllerParameter(i).name == name) { return true; } } return false; } private void CheckIfStoredParametersExist() { var syncedParams = this.m_Target.GetSynchronizedParameters(); List<string> paramsToRemove = new List<string>(); for (int i = 0; i < syncedParams.Count; ++i) { string parameterName = syncedParams[i].Name; if (this.DoesParameterExist(parameterName) == false) { Debug.LogWarning("Parameter '" + this.m_Target.GetSynchronizedParameters()[i].Name + "' doesn't exist anymore. Removing it from the list of synchronized parameters"); paramsToRemove.Add(parameterName); } } if (paramsToRemove.Count > 0) { foreach (string param in paramsToRemove) { this.m_Target.GetSynchronizedParameters().RemoveAll(item => item.Name == param); } } } private void DrawParameterInspector() { // flag to expose a note in Interface if one or more trigger(s) are synchronized bool isUsingTriggers = false; SerializedProperty foldoutProperty = this.serializedObject.FindProperty("ShowParameterInspector"); foldoutProperty.boolValue = PhotonGUI.ContainerHeaderFoldout("Synchronize Parameters", foldoutProperty.boolValue); if (foldoutProperty.boolValue == false) { return; } float lineHeight = 20; Rect containerRect = PhotonGUI.ContainerBody(this.GetParameterCount() * lineHeight); for (int i = 0; i < this.GetParameterCount(); i++) { AnimatorControllerParameter parameter = null; parameter = this.GetAnimatorControllerParameter(i); string defaultValue = ""; if (parameter.type == AnimatorControllerParameterType.Bool) { if (Application.isPlaying && this.m_Animator.gameObject.activeInHierarchy) { defaultValue += this.m_Animator.GetBool(parameter.name); } else { defaultValue += parameter.defaultBool.ToString(); } } else if (parameter.type == AnimatorControllerParameterType.Float) { if (Application.isPlaying && this.m_Animator.gameObject.activeInHierarchy) { defaultValue += this.m_Animator.GetFloat(parameter.name).ToString("0.00"); } else { defaultValue += parameter.defaultFloat.ToString(); } } else if (parameter.type == AnimatorControllerParameterType.Int) { if (Application.isPlaying && this.m_Animator.gameObject.activeInHierarchy) { defaultValue += this.m_Animator.GetInteger(parameter.name); } else { defaultValue += parameter.defaultInt.ToString(); } } else if (parameter.type == AnimatorControllerParameterType.Trigger) { if (Application.isPlaying && this.m_Animator.gameObject.activeInHierarchy) { defaultValue += this.m_Animator.GetBool(parameter.name); } else { defaultValue += parameter.defaultBool.ToString(); } } if (this.m_Target.DoesParameterSynchronizeTypeExist(parameter.name) == false) { this.m_Target.SetParameterSynchronized(parameter.name, (PhotonAnimatorView.ParameterType)parameter.type, PhotonAnimatorView.SynchronizeType.Disabled); } PhotonAnimatorView.SynchronizeType value = this.m_Target.GetParameterSynchronizeType(parameter.name); // check if using trigger and actually synchronizing it if (value != PhotonAnimatorView.SynchronizeType.Disabled && parameter.type == AnimatorControllerParameterType.Trigger) { isUsingTriggers = true; } Rect elementRect = new Rect(containerRect.xMin, containerRect.yMin + i * lineHeight, containerRect.width, lineHeight); Rect labelRect = new Rect(elementRect.xMin + 5, elementRect.yMin + 2, EditorGUIUtility.labelWidth - 5, elementRect.height); GUI.Label(labelRect, parameter.name + " (" + defaultValue + ")"); Rect popupRect = new Rect(elementRect.xMin + EditorGUIUtility.labelWidth, elementRect.yMin + 2, elementRect.width - EditorGUIUtility.labelWidth - 5, EditorGUIUtility.singleLineHeight); value = (PhotonAnimatorView.SynchronizeType)EditorGUI.EnumPopup(popupRect, value); if (i < this.GetParameterCount() - 1) { Rect splitterRect = new Rect(elementRect.xMin + 2, elementRect.yMax, elementRect.width - 4, 1); PhotonGUI.DrawSplitter(splitterRect); } if (value != this.m_Target.GetParameterSynchronizeType(parameter.name)) { Undo.RecordObject(this.target, "Modify Synchronize Parameter " + parameter.name); this.m_Target.SetParameterSynchronized(parameter.name, (PhotonAnimatorView.ParameterType)parameter.type, value); } } // display note when synchronized triggers are detected. if (isUsingTriggers) { GUILayout.BeginHorizontal(GUI.skin.box); GUILayout.Label("When using triggers, make sure this component is last in the stack"); GUILayout.EndHorizontal(); } } } }
using NUnit.Framework; using SIL.WritingSystems.Migration; namespace SIL.WritingSystems.Tests.Migration { [TestFixture] public class IetfLanguageTagCleanerTests { [Test] public void CompleteTagConstructor_HasInvalidLanguageName_MovedToPrivateUse() { var cleaner = new IetfLanguageTagCleaner("234"); cleaner.Clean(); Assert.That(cleaner.GetCompleteTag(), Is.EqualTo("qaa-x-234")); } [Test] public void CompleteTagConstructor_HasLanguageNameAndOtherName_OtherNameMovedToPrivateUse() { var cleaner = new IetfLanguageTagCleaner("abc-123"); cleaner.Clean(); Assert.That(cleaner.GetCompleteTag(), Is.EqualTo("abc-x-123")); } [Test] public void CompleteTagConstructor_LanguageNameWithAudio_GetZxxxAdded() { var cleaner = new IetfLanguageTagCleaner("aaa-x-audio"); cleaner.Clean(); Assert.That(cleaner.GetCompleteTag(), Is.EqualTo("aaa-Zxxx-x-audio")); } [Test] public void CompleteTagConstructor_InvalidLanguageNameWithScript_QaaAdded() { var cleaner = new IetfLanguageTagCleaner("wee-Latn"); cleaner.Clean(); Assert.That(cleaner.GetCompleteTag(), Is.EqualTo("qaa-Latn-x-wee")); // Also when initially "Latn" is properly in the Script field. cleaner = new IetfLanguageTagCleaner("wee", "Latn", "", "", ""); cleaner.Clean(); Assert.That(cleaner.GetCompleteTag(), Is.EqualTo("qaa-Latn-x-wee")); } [Test] public void CompleteTagConstructor_XDashBeforeValidLanguageNameInVariant_NoChange() { var cleaner = new IetfLanguageTagCleaner("", "", "", "x-de", ""); cleaner.Clean(); Assert.That(cleaner.GetCompleteTag(), Is.EqualTo("x-de")); } [Test] public void ValidLanguageCodeMarkedPrivate_InsertsQaa() { var cleaner = new IetfLanguageTagCleaner("x-de", "", "", "", ""); cleaner.Clean(); VerifyRfcCleaner(cleaner, "qaa", "", "", "", "qaa-x-de"); } [Test] public void Language_XDashBeforeString_AddsQaa() { var cleaner = new IetfLanguageTagCleaner("x-blah"); cleaner.Clean(); Assert.That(cleaner.GetCompleteTag(), Is.EqualTo("qaa-x-blah")); } [Test] public void CompleteTagConstructor_QaaWithXDashBeforeValidLanguageName_NoChange() { var cleaner = new IetfLanguageTagCleaner("qaa-x-th"); cleaner.Clean(); Assert.That(cleaner.GetCompleteTag(), Is.EqualTo("qaa-x-th")); Assert.That(cleaner.Language, Is.EqualTo("qaa")); Assert.That(cleaner.PrivateUse, Is.EqualTo("th")); } [Test] public void CompleteTagConstructor_TagContainsPrivateUseWithAdditionalXDash_RedundantXDashRemoved() { var cleaner = new IetfLanguageTagCleaner("en-x-some-x-whatever"); cleaner.Clean(); Assert.That(cleaner.GetCompleteTag(), Is.EqualTo("en-x-some-whatever")); } [Test] public void CompleteTagConstructor_TagContainsOnlyPrivateUseWithAdditionalXDash_RedundantXDashRemoved() { var cleaner = new IetfLanguageTagCleaner("x-some-x-whatever"); cleaner.Clean(); Assert.That(cleaner.GetCompleteTag(), Is.EqualTo("qaa-x-some-whatever")); } [Test] public void CompleteTagConstructor_PrivateUseWithAudioAndDuplicateX_MakesAudioTag() { var cleaner = new IetfLanguageTagCleaner("x-en-Zxxx-x-audio"); cleaner.Clean(); Assert.That(cleaner.GetCompleteTag(), Is.EqualTo("qaa-Zxxx-x-en-Zxxx-audio")); } [Test] public void CompleteTagConstructor_ValidRfctagWithPrivateUseElements_NoChange() { var cleaner = new IetfLanguageTagCleaner("qaa-Zxxx-x-Zxxx-AUDIO"); cleaner.Clean(); Assert.That(cleaner.GetCompleteTag(), Is.EqualTo("qaa-Zxxx-x-Zxxx-AUDIO")); // Except, it should have moved things from Language, where the constructor puts them, to the appropriate places. Assert.That(cleaner.Language, Is.EqualTo("qaa")); Assert.That(cleaner.Script, Is.EqualTo("Zxxx")); Assert.That(cleaner.PrivateUse, Is.EqualTo("Zxxx-AUDIO")); } [Test] public void CompleteTagConstructor_ValidRfctagWithLegacyIso3Code_MigratesToRfc2LetterCode() { var cleaner = new IetfLanguageTagCleaner("eng"); cleaner.Clean(); Assert.That(cleaner.GetCompleteTag(), Is.EqualTo("en")); } [Test] public void CompleteTagConstructor_ValidRfctagWithLegacyIso3CodeAndPrivateUse_MigratesToRfc2LetterCodeAndPrivateUse() { var cleaner = new IetfLanguageTagCleaner("eng-bogus"); cleaner.Clean(); Assert.That(cleaner.GetCompleteTag(), Is.EqualTo("en-x-bogus")); } [Test] public void AllPrivateComponents_InsertsStandardPrivateCodes() { var cleaner = new IetfLanguageTagCleaner("x-kal", "x-script", "x-RG", "fonipa-x-etic", ""); cleaner.Clean(); VerifyRfcCleaner(cleaner, "qaa", "Qaaa", "QM", "fonipa", "qaa-Qaaa-QM-fonipa-x-kal-script-RG-etic"); } [Test] public void PrivateScriptKnownLanguage_InsertsPrivateScriptCode() { var cleaner = new IetfLanguageTagCleaner("fr", "x-script", "", "", ""); cleaner.Clean(); VerifyRfcCleaner(cleaner, "fr", "Qaaa", "", "", "fr-Qaaa-x-script"); } [Test] public void PrivateScriptKnownLanguageAndRegion_InsertsPrivateScriptCode() { var cleaner = new IetfLanguageTagCleaner("fr", "x-script", "NO", "", ""); cleaner.Clean(); VerifyRfcCleaner(cleaner, "fr", "Qaaa", "NO", "", "fr-Qaaa-NO-x-script"); } [Test] public void PrivateRegionKnownLanguageAndScript_InsertsPrivateRegionCode() { var cleaner = new IetfLanguageTagCleaner("fr", "Latn", "x-ZY", "", ""); cleaner.Clean(); VerifyRfcCleaner(cleaner, "fr", "Latn", "QM", "", "fr-Latn-QM-x-ZY"); } [Test] public void PrivateRegionMultiPartVariant_InsertsPrivateRegionCode() { var cleaner = new IetfLanguageTagCleaner("fr", "", "x-ZY", "fonipa-x-etic", ""); cleaner.Clean(); VerifyRfcCleaner(cleaner, "fr", "", "QM", "fonipa", "fr-QM-fonipa-x-ZY-etic"); } [Test] public void MultiPartVariantWithoutX_InsertsX() { var cleaner = new IetfLanguageTagCleaner("fr", "", "", "fonipa-etic", ""); cleaner.Clean(); VerifyRfcCleaner(cleaner, "fr", "", "", "fonipa", "fr-fonipa-x-etic"); } [Test] public void ZhNoRegion_InsertsRegionCN() { var cleaner = new IetfLanguageTagCleaner("zh", "", "", "", ""); cleaner.Clean(); VerifyRfcCleaner(cleaner, "zh", "", "CN", "", "zh-CN"); } [Test] public void CmnNoRegion_BecomesZhCN() { var cleaner = new IetfLanguageTagCleaner("cmn", "", "", "", ""); cleaner.Clean(); VerifyRfcCleaner(cleaner, "zh", "", "CN", "", "zh-CN"); } [Test] public void Pes_BecomesFa() { var cleaner = new IetfLanguageTagCleaner("pes", "Latn", "", "", ""); cleaner.Clean(); VerifyRfcCleaner(cleaner, "fa", "Latn", "", "", "fa-Latn"); } [Test] public void Arb_BecomesAr() { var cleaner = new IetfLanguageTagCleaner("arb", "", "x-ZG", "", ""); cleaner.Clean(); VerifyRfcCleaner(cleaner, "ar", "", "QM", "", "ar-QM-x-ZG"); } [Test] public void ZhRegion_NoChange() { var cleaner = new IetfLanguageTagCleaner("zh", "", "NO", "", ""); cleaner.Clean(); VerifyRfcCleaner(cleaner, "zh", "", "NO", "", "zh-NO"); cleaner = new IetfLanguageTagCleaner("zh", "", "x-ZK", "", ""); cleaner.Clean(); VerifyRfcCleaner(cleaner, "zh", "", "QM", "", "zh-QM-x-ZK"); } /// <summary> /// JohnT: I have no idea why tpi gets moved to the end of the private-use section. This behavior was copied /// from the LdmlInFolderWritingSystemRepositoryMigratorTests test with a similar name, which indicated /// that such a re-ordering was expected, and I have apparently not broken it, so didn't worry. /// </summary> [Test] public void LanguageSubtagContainsMultipleValidLanguageSubtagsAsWellAsDataThatIsNotValidLanguageScriptRegionOrVariant_AllSubtagsButFirstValidLanguageSubtagAreMovedToPrivateUse() { var cleaner = new IetfLanguageTagCleaner("bogus-en-audio-tpi-bogus2-x-", "", "", "", ""); cleaner.Clean(); VerifyRfcCleaner(cleaner, "en", "Zxxx", "", "", "en-Zxxx-x-bogus-audio-bogus2-tpi"); } [Test] public void CmnRegion_BecomesZh() { var cleaner = new IetfLanguageTagCleaner("cmn", "", "NO", "", ""); cleaner.Clean(); VerifyRfcCleaner(cleaner, "zh", "", "NO", "", "zh-NO"); } [Test] public void EticWithoutFonipa_AddsFonipa() { var cleaner = new IetfLanguageTagCleaner("en", "", "", "x-etic", ""); cleaner.Clean(); VerifyRfcCleaner(cleaner, "en", "", "", "fonipa", "en-fonipa-x-etic"); } [Test] public void EmicWithoutFonipa_AddsFonipa() { var cleaner = new IetfLanguageTagCleaner("en", "", "", "x-emic", ""); cleaner.Clean(); VerifyRfcCleaner(cleaner, "en", "", "", "fonipa", "en-fonipa-x-emic"); } [Test] public void PrivateUseVariantLanguageCode_IsNotShortened() { var cleaner = new IetfLanguageTagCleaner("qaa", "", "", "", "x-kal"); cleaner.Clean(); VerifyRfcCleaner(cleaner, "qaa", "", "", "", "qaa-x-kal"); } [Test] public void LanguageCodeAfterX_IsNotShortened() { var cleaner = new IetfLanguageTagCleaner("qaa-x-kal"); cleaner.Clean(); VerifyRfcCleaner(cleaner, "qaa", "", "", "", "qaa-x-kal"); } [Test] public void NewTagWithPrivateLanguage_IsNotModified() { var cleaner = new IetfLanguageTagCleaner("qaa-Qaaa-QM-x-kal-Mysc-YY"); cleaner.Clean(); VerifyRfcCleaner(cleaner, "qaa", "Qaaa", "QM", "", "qaa-Qaaa-QM-x-kal-Mysc-YY"); } [Test] public void NewTag_IsNotModified() { var cleaner = new IetfLanguageTagCleaner("fr-Qaaa-QM-x-Mysc-YY"); cleaner.Clean(); VerifyRfcCleaner(cleaner, "fr", "Qaaa", "QM", "", "fr-Qaaa-QM-x-Mysc-YY"); } [Test] public void RegionCodesThatMatchLanguageCodesNotMovedToPrivateUse() { var cleaner = new IetfLanguageTagCleaner("rwr-IN"); cleaner.Clean(); VerifyRfcCleaner(cleaner, "rwr", "", "IN", "", "rwr-IN"); } [Test] public void CleanMarksCustomScriptMovedToPrivateUse() { var cleaner = new IetfLanguageTagCleaner("en-Zyxw"); cleaner.Clean(); VerifyRfcCleaner(cleaner, "en", "Qaaa", "", "", "en-Qaaa-x-Zyxw"); } [Test] public void ScriptEndingWithX_IsHandledCorrectly() { var cleaner = new IetfLanguageTagCleaner("zh-Phnx-CN-fonipa-x-emic"); cleaner.Clean(); VerifyRfcCleaner(cleaner, "zh", "Phnx", "CN", "fonipa", "zh-Phnx-CN-fonipa-x-emic"); } [Test] public void GetFullCode_CaseCleaning_Lang_Script_Region_Works() { var cleaner = new IetfLanguageTagCleaner("EN-latn-us-x-NotCHang"); cleaner.Clean(); VerifyRfcCleaner(cleaner, "en", "Latn", "US", "", "en-Latn-US-x-NotCHang"); } [Test] public void GetFullCode_CaseCleaning_AudioWs_PrivateUseIsChanged() { var cleaner = new IetfLanguageTagCleaner("EN-Zxxx-x-AudIO"); cleaner.Clean(); VerifyRfcCleaner(cleaner, "en", "Zxxx", "", "", "en-Zxxx-x-audio"); } void VerifyRfcCleaner(IetfLanguageTagCleaner cleaner, string language, string script, string region, string variant, string completeTag) { Assert.That(cleaner.Language, Is.EqualTo(language)); Assert.That(cleaner.Script, Is.EqualTo(script)); Assert.That(cleaner.Region, Is.EqualTo(region)); Assert.That(cleaner.Variant, Is.EqualTo(variant)); Assert.That(cleaner.GetCompleteTag(), Is.EqualTo(completeTag)); } } }
// // Copyright (c) Microsoft and contributors. 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. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using Microsoft.Azure.Management.Compute.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; namespace Microsoft.Azure.Commands.Compute.Automation { [Cmdlet("New", "AzureRmContainerServiceConfig")] [OutputType(typeof(ContainerService))] public class NewAzureRmContainerServiceConfigCommand : Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet { [Parameter( Mandatory = false, Position = 0, ValueFromPipelineByPropertyName = true)] public string Location { get; set; } [Parameter( Mandatory = false, Position = 1, ValueFromPipelineByPropertyName = true)] public Hashtable Tag { get; set; } [Parameter( Mandatory = false, Position = 2, ValueFromPipelineByPropertyName = true)] public ContainerServiceOchestratorTypes? OrchestratorType { get; set; } [Parameter( Mandatory = false, Position = 3, ValueFromPipelineByPropertyName = true)] public int? MasterCount { get; set; } [Parameter( Mandatory = false, Position = 4, ValueFromPipelineByPropertyName = true)] public string MasterDnsPrefix { get; set; } [Parameter( Mandatory = false, Position = 5, ValueFromPipelineByPropertyName = true)] public ContainerServiceAgentPoolProfile[] AgentPoolProfile { get; set; } [Parameter( Mandatory = false, Position = 6, ValueFromPipelineByPropertyName = true)] public string WindowsProfileAdminUsername { get; set; } [Parameter( Mandatory = false, Position = 7, ValueFromPipelineByPropertyName = true)] public string WindowsProfileAdminPassword { get; set; } [Parameter( Mandatory = false, Position = 8, ValueFromPipelineByPropertyName = true)] public string AdminUsername { get; set; } [Parameter( Mandatory = false, Position = 9, ValueFromPipelineByPropertyName = true)] public string[] SshPublicKey { get; set; } [Parameter( Mandatory = false, Position = 10, ValueFromPipelineByPropertyName = true)] public bool? VmDiagnosticsEnabled { get; set; } protected override void ProcessRecord() { // OrchestratorProfile Microsoft.Azure.Management.Compute.Models.ContainerServiceOrchestratorProfile vOrchestratorProfile = null; // MasterProfile Microsoft.Azure.Management.Compute.Models.ContainerServiceMasterProfile vMasterProfile = null; // WindowsProfile Microsoft.Azure.Management.Compute.Models.ContainerServiceWindowsProfile vWindowsProfile = null; // LinuxProfile Microsoft.Azure.Management.Compute.Models.ContainerServiceLinuxProfile vLinuxProfile = null; // DiagnosticsProfile Microsoft.Azure.Management.Compute.Models.ContainerServiceDiagnosticsProfile vDiagnosticsProfile = null; if (this.OrchestratorType != null) { if (vOrchestratorProfile == null) { vOrchestratorProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceOrchestratorProfile(); } vOrchestratorProfile.OrchestratorType = this.OrchestratorType; } if (this.MasterCount != null) { if (vMasterProfile == null) { vMasterProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceMasterProfile(); } vMasterProfile.Count = this.MasterCount; } if (this.MasterDnsPrefix != null) { if (vMasterProfile == null) { vMasterProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceMasterProfile(); } vMasterProfile.DnsPrefix = this.MasterDnsPrefix; } if (this.WindowsProfileAdminUsername != null) { if (vWindowsProfile == null) { vWindowsProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceWindowsProfile(); } vWindowsProfile.AdminUsername = this.WindowsProfileAdminUsername; } if (this.WindowsProfileAdminPassword != null) { if (vWindowsProfile == null) { vWindowsProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceWindowsProfile(); } vWindowsProfile.AdminPassword = this.WindowsProfileAdminPassword; } if (this.AdminUsername != null) { if (vLinuxProfile == null) { vLinuxProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceLinuxProfile(); } vLinuxProfile.AdminUsername = this.AdminUsername; } if (this.SshPublicKey != null) { if (vLinuxProfile == null) { vLinuxProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceLinuxProfile(); } if (vLinuxProfile.Ssh == null) { vLinuxProfile.Ssh = new Microsoft.Azure.Management.Compute.Models.ContainerServiceSshConfiguration(); } if (vLinuxProfile.Ssh.PublicKeys == null) { vLinuxProfile.Ssh.PublicKeys = new List<Microsoft.Azure.Management.Compute.Models.ContainerServiceSshPublicKey>(); } foreach (var element in this.SshPublicKey) { var vPublicKeys = new Microsoft.Azure.Management.Compute.Models.ContainerServiceSshPublicKey(); vPublicKeys.KeyData = element; vLinuxProfile.Ssh.PublicKeys.Add(vPublicKeys); } } if (this.VmDiagnosticsEnabled != null) { if (vDiagnosticsProfile == null) { vDiagnosticsProfile = new Microsoft.Azure.Management.Compute.Models.ContainerServiceDiagnosticsProfile(); } if (vDiagnosticsProfile.VmDiagnostics == null) { vDiagnosticsProfile.VmDiagnostics = new Microsoft.Azure.Management.Compute.Models.ContainerServiceVMDiagnostics(); } vDiagnosticsProfile.VmDiagnostics.Enabled = this.VmDiagnosticsEnabled; } var vContainerService = new ContainerService { Location = this.Location, Tags = (this.Tag == null) ? null : this.Tag.Cast<DictionaryEntry>().ToDictionary(ht => (string)ht.Key, ht => (string)ht.Value), AgentPoolProfiles = this.AgentPoolProfile, OrchestratorProfile = vOrchestratorProfile, MasterProfile = vMasterProfile, WindowsProfile = vWindowsProfile, LinuxProfile = vLinuxProfile, DiagnosticsProfile = vDiagnosticsProfile, }; WriteObject(vContainerService); } } }
// 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 Microsoft.Azure.Search { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// Client that can be used to query an Azure Search index and upload, /// merge, or delete documents. /// </summary> public partial class SearchIndexClient : ServiceClient<SearchIndexClient>, ISearchIndexClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Client Api Version. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IDocumentsOperations. /// </summary> public virtual IDocumentsOperations Documents { get; private set; } /// <summary> /// Initializes a new instance of the SearchIndexClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected SearchIndexClient(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the SearchIndexClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected SearchIndexClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the SearchIndexClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected SearchIndexClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the SearchIndexClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected SearchIndexClient(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the SearchIndexClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public SearchIndexClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the SearchIndexClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public SearchIndexClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the SearchIndexClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public SearchIndexClient(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the SearchIndexClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public SearchIndexClient(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.Documents = new DocumentsOperations(this); this.BaseUri = new Uri("http://localhost"); this.ApiVersion = "2015-02-28-Preview"; this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; #if !(NET20 || NET35 || PORTABLE) using System.Numerics; #endif using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Tests.TestObjects; #if !NETFX_CORE using NUnit.Framework; #else using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; #endif using Newtonsoft.Json.Linq; using System.IO; using System.Collections; #if !NETFX_CORE using System.Web.UI; #endif #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Tests.Linq { [TestFixture] public class JObjectTests : TestFixtureBase { #if !(NET35 || NET20 || PORTABLE40) [Test] public void EmbedJValueStringInNewJObject() { string s = null; var v = new JValue(s); dynamic o = JObject.FromObject(new { title = v }); string output = o.ToString(); StringAssert.AreEqual(@"{ ""title"": null }", output); Assert.AreEqual(null, v.Value); Assert.IsNull((string)o.title); } #endif [Test] public void JObjectWithComments() { string json = @"{ /*comment2*/ ""Name"": /*comment3*/ ""Apple"" /*comment4*/, /*comment5*/ ""ExpiryDate"": ""\/Date(1230422400000)\/"", ""Price"": 3.99, ""Sizes"": /*comment6*/ [ /*comment7*/ ""Small"", /*comment8*/ ""Medium"" /*comment9*/, /*comment10*/ ""Large"" /*comment11*/ ] /*comment12*/ } /*comment13*/"; JToken o = JToken.Parse(json); Assert.AreEqual("Apple", (string) o["Name"]); } [Test] public void WritePropertyWithNoValue() { var o = new JObject(); o.Add(new JProperty("novalue")); StringAssert.AreEqual(@"{ ""novalue"": null }", o.ToString()); } [Test] public void Keys() { var o = new JObject(); var d = (IDictionary<string, JToken>)o; Assert.AreEqual(0, d.Keys.Count); o["value"] = true; Assert.AreEqual(1, d.Keys.Count); } [Test] public void TryGetValue() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, o.Children().Count()); JToken t; Assert.AreEqual(false, o.TryGetValue("sdf", out t)); Assert.AreEqual(null, t); Assert.AreEqual(false, o.TryGetValue(null, out t)); Assert.AreEqual(null, t); Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(new JValue(1), t)); } [Test] public void DictionaryItemShouldSet() { JObject o = new JObject(); o["PropertyNameValue"] = new JValue(1); Assert.AreEqual(1, o.Children().Count()); JToken t; Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(new JValue(1), t)); o["PropertyNameValue"] = new JValue(2); Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(new JValue(2), t)); o["PropertyNameValue"] = null; Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(true, o.TryGetValue("PropertyNameValue", out t)); Assert.AreEqual(true, JToken.DeepEquals(JValue.CreateNull(), t)); } [Test] public void Remove() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(false, o.Remove("sdf")); Assert.AreEqual(false, o.Remove(null)); Assert.AreEqual(true, o.Remove("PropertyNameValue")); Assert.AreEqual(0, o.Children().Count()); } [Test] public void GenericCollectionRemove() { JValue v = new JValue(1); JObject o = new JObject(); o.Add("PropertyNameValue", v); Assert.AreEqual(1, o.Children().Count()); Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1)))); Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2)))); Assert.AreEqual(false, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1)))); Assert.AreEqual(true, ((ICollection<KeyValuePair<string, JToken>>)o).Remove(new KeyValuePair<string, JToken>("PropertyNameValue", v))); Assert.AreEqual(0, o.Children().Count()); } [Test] public void DuplicatePropertyNameShouldThrow() { ExceptionAssert.Throws<ArgumentException>(() => { JObject o = new JObject(); o.Add("PropertyNameValue", null); o.Add("PropertyNameValue", null); }, "Can not add property PropertyNameValue to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object."); } [Test] public void GenericDictionaryAdd() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, (int)o["PropertyNameValue"]); o.Add("PropertyNameValue1", null); Assert.AreEqual(null, ((JValue)o["PropertyNameValue1"]).Value); Assert.AreEqual(2, o.Children().Count()); } [Test] public void GenericCollectionAdd() { JObject o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).Add(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1))); Assert.AreEqual(1, (int)o["PropertyNameValue"]); Assert.AreEqual(1, o.Children().Count()); } [Test] public void GenericCollectionClear() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, o.Children().Count()); JProperty p = (JProperty)o.Children().ElementAt(0); ((ICollection<KeyValuePair<string, JToken>>)o).Clear(); Assert.AreEqual(0, o.Children().Count()); Assert.AreEqual(null, p.Parent); } [Test] public void GenericCollectionContains() { JValue v = new JValue(1); JObject o = new JObject(); o.Add("PropertyNameValue", v); Assert.AreEqual(1, o.Children().Count()); bool contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(1))); Assert.AreEqual(false, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", v)); Assert.AreEqual(true, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue", new JValue(2))); Assert.AreEqual(false, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(new KeyValuePair<string, JToken>("PropertyNameValue1", new JValue(1))); Assert.AreEqual(false, contains); contains = ((ICollection<KeyValuePair<string, JToken>>)o).Contains(default(KeyValuePair<string, JToken>)); Assert.AreEqual(false, contains); } [Test] public void GenericDictionaryContains() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); Assert.AreEqual(1, o.Children().Count()); bool contains = ((IDictionary<string, JToken>)o).ContainsKey("PropertyNameValue"); Assert.AreEqual(true, contains); } [Test] public void GenericCollectionCopyTo() { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); o.Add("PropertyNameValue3", new JValue(3)); Assert.AreEqual(3, o.Children().Count()); KeyValuePair<string, JToken>[] a = new KeyValuePair<string, JToken>[5]; ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(a, 1); Assert.AreEqual(default(KeyValuePair<string, JToken>), a[0]); Assert.AreEqual("PropertyNameValue", a[1].Key); Assert.AreEqual(1, (int)a[1].Value); Assert.AreEqual("PropertyNameValue2", a[2].Key); Assert.AreEqual(2, (int)a[2].Value); Assert.AreEqual("PropertyNameValue3", a[3].Key); Assert.AreEqual(3, (int)a[3].Value); Assert.AreEqual(default(KeyValuePair<string, JToken>), a[4]); } [Test] public void GenericCollectionCopyToNullArrayShouldThrow() { ExceptionAssert.Throws<ArgumentException>(() => { JObject o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(null, 0); }, @"Value cannot be null. Parameter name: array"); } [Test] public void GenericCollectionCopyToNegativeArrayIndexShouldThrow() { ExceptionAssert.Throws<ArgumentOutOfRangeException>(() => { JObject o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], -1); }, @"arrayIndex is less than 0. Parameter name: arrayIndex"); } [Test] public void GenericCollectionCopyToArrayIndexEqualGreaterToArrayLengthShouldThrow() { ExceptionAssert.Throws<ArgumentException>(() => { JObject o = new JObject(); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[1], 1); }, @"arrayIndex is equal to or greater than the length of array."); } [Test] public void GenericCollectionCopyToInsufficientArrayCapacity() { ExceptionAssert.Throws<ArgumentException>(() => { JObject o = new JObject(); o.Add("PropertyNameValue", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); o.Add("PropertyNameValue3", new JValue(3)); ((ICollection<KeyValuePair<string, JToken>>)o).CopyTo(new KeyValuePair<string, JToken>[3], 1); }, @"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array."); } [Test] public void FromObjectRaw() { PersonRaw raw = new PersonRaw { FirstName = "FirstNameValue", RawContent = new JRaw("[1,2,3,4,5]"), LastName = "LastNameValue" }; JObject o = JObject.FromObject(raw); Assert.AreEqual("FirstNameValue", (string)o["first_name"]); Assert.AreEqual(JTokenType.Raw, ((JValue)o["RawContent"]).Type); Assert.AreEqual("[1,2,3,4,5]", (string)o["RawContent"]); Assert.AreEqual("LastNameValue", (string)o["last_name"]); } [Test] public void JTokenReader() { PersonRaw raw = new PersonRaw { FirstName = "FirstNameValue", RawContent = new JRaw("[1,2,3,4,5]"), LastName = "LastNameValue" }; JObject o = JObject.FromObject(raw); JsonReader reader = new JTokenReader(o); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.String, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.Raw, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.String, reader.TokenType); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.EndObject, reader.TokenType); Assert.IsFalse(reader.Read()); } [Test] public void DeserializeFromRaw() { PersonRaw raw = new PersonRaw { FirstName = "FirstNameValue", RawContent = new JRaw("[1,2,3,4,5]"), LastName = "LastNameValue" }; JObject o = JObject.FromObject(raw); JsonReader reader = new JTokenReader(o); JsonSerializer serializer = new JsonSerializer(); raw = (PersonRaw)serializer.Deserialize(reader, typeof(PersonRaw)); Assert.AreEqual("FirstNameValue", raw.FirstName); Assert.AreEqual("LastNameValue", raw.LastName); Assert.AreEqual("[1,2,3,4,5]", raw.RawContent.Value); } [Test] public void Parse_ShouldThrowOnUnexpectedToken() { ExceptionAssert.Throws<JsonReaderException>(() => { string json = @"[""prop""]"; JObject.Parse(json); }, "Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1."); } [Test] public void ParseJavaScriptDate() { string json = @"[new Date(1207285200000)]"; JArray a = (JArray)JsonConvert.DeserializeObject(json); JValue v = (JValue)a[0]; Assert.AreEqual(DateTimeUtils.ConvertJavaScriptTicksToDateTime(1207285200000), (DateTime)v); } [Test] public void GenericValueCast() { string json = @"{""foo"":true}"; JObject o = (JObject)JsonConvert.DeserializeObject(json); bool? value = o.Value<bool?>("foo"); Assert.AreEqual(true, value); json = @"{""foo"":null}"; o = (JObject)JsonConvert.DeserializeObject(json); value = o.Value<bool?>("foo"); Assert.AreEqual(null, value); } [Test] public void Blog() { ExceptionAssert.Throws<JsonReaderException>(() => { JObject.Parse(@"{ ""name"": ""James"", ]!#$THIS IS: BAD JSON![{}}}}] }"); }, "Invalid property identifier character: ]. Path 'name', line 3, position 5."); } [Test] public void RawChildValues() { JObject o = new JObject(); o["val1"] = new JRaw("1"); o["val2"] = new JRaw("1"); string json = o.ToString(); StringAssert.AreEqual(@"{ ""val1"": 1, ""val2"": 1 }", json); } [Test] public void Iterate() { JObject o = new JObject(); o.Add("PropertyNameValue1", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); JToken t = o; int i = 1; foreach (JProperty property in t) { Assert.AreEqual("PropertyNameValue" + i, property.Name); Assert.AreEqual(i, (int)property.Value); i++; } } [Test] public void KeyValuePairIterate() { JObject o = new JObject(); o.Add("PropertyNameValue1", new JValue(1)); o.Add("PropertyNameValue2", new JValue(2)); int i = 1; foreach (KeyValuePair<string, JToken> pair in o) { Assert.AreEqual("PropertyNameValue" + i, pair.Key); Assert.AreEqual(i, (int)pair.Value); i++; } } [Test] public void WriteObjectNullStringValue() { string s = null; JValue v = new JValue(s); Assert.AreEqual(null, v.Value); Assert.AreEqual(JTokenType.String, v.Type); JObject o = new JObject(); o["title"] = v; string output = o.ToString(); StringAssert.AreEqual(@"{ ""title"": null }", output); } [Test] public void Example() { string json = @"{ ""Name"": ""Apple"", ""Expiry"": new Date(1230422400000), ""Price"": 3.99, ""Sizes"": [ ""Small"", ""Medium"", ""Large"" ] }"; JObject o = JObject.Parse(json); string name = (string)o["Name"]; // Apple JArray sizes = (JArray)o["Sizes"]; string smallest = (string)sizes[0]; // Small Console.WriteLine(name); Console.WriteLine(smallest); } [Test] public void DeserializeClassManually() { string jsonText = @"{ ""short"": { ""original"":""http://www.foo.com/"", ""short"":""krehqk"", ""error"": { ""code"":0, ""msg"":""No action taken"" } } }"; JObject json = JObject.Parse(jsonText); Shortie shortie = new Shortie { Original = (string)json["short"]["original"], Short = (string)json["short"]["short"], Error = new ShortieException { Code = (int)json["short"]["error"]["code"], ErrorMessage = (string)json["short"]["error"]["msg"] } }; Console.WriteLine(shortie.Original); // http://www.foo.com/ Console.WriteLine(shortie.Error.ErrorMessage); // No action taken Assert.AreEqual("http://www.foo.com/", shortie.Original); Assert.AreEqual("krehqk", shortie.Short); Assert.AreEqual(null, shortie.Shortened); Assert.AreEqual(0, shortie.Error.Code); Assert.AreEqual("No action taken", shortie.Error.ErrorMessage); } [Test] public void JObjectContainingHtml() { JObject o = new JObject(); o["rc"] = new JValue(200); o["m"] = new JValue(""); o["o"] = new JValue(@"<div class='s1'>" + StringUtils.CarriageReturnLineFeed + @"</div>"); StringAssert.AreEqual(@"{ ""rc"": 200, ""m"": """", ""o"": ""<div class='s1'>\r\n</div>"" }", o.ToString()); } [Test] public void ImplicitValueConversions() { JObject moss = new JObject(); moss["FirstName"] = new JValue("Maurice"); moss["LastName"] = new JValue("Moss"); moss["BirthDate"] = new JValue(new DateTime(1977, 12, 30)); moss["Department"] = new JValue("IT"); moss["JobTitle"] = new JValue("Support"); Console.WriteLine(moss.ToString()); //{ // "FirstName": "Maurice", // "LastName": "Moss", // "BirthDate": "\/Date(252241200000+1300)\/", // "Department": "IT", // "JobTitle": "Support" //} JObject jen = new JObject(); jen["FirstName"] = "Jen"; jen["LastName"] = "Barber"; jen["BirthDate"] = new DateTime(1978, 3, 15); jen["Department"] = "IT"; jen["JobTitle"] = "Manager"; Console.WriteLine(jen.ToString()); //{ // "FirstName": "Jen", // "LastName": "Barber", // "BirthDate": "\/Date(258721200000+1300)\/", // "Department": "IT", // "JobTitle": "Manager" //} } [Test] public void ReplaceJPropertyWithJPropertyWithSameName() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); JObject o = new JObject(p1, p2); IList l = o; Assert.AreEqual(p1, l[0]); Assert.AreEqual(p2, l[1]); JProperty p3 = new JProperty("Test1", "III"); p1.Replace(p3); Assert.AreEqual(null, p1.Parent); Assert.AreEqual(l, p3.Parent); Assert.AreEqual(p3, l[0]); Assert.AreEqual(p2, l[1]); Assert.AreEqual(2, l.Count); Assert.AreEqual(2, o.Properties().Count()); JProperty p4 = new JProperty("Test4", "IV"); p2.Replace(p4); Assert.AreEqual(null, p2.Parent); Assert.AreEqual(l, p4.Parent); Assert.AreEqual(p3, l[0]); Assert.AreEqual(p4, l[1]); } #if !(NET20 || NETFX_CORE || PORTABLE || PORTABLE40) [Test] public void PropertyChanging() { object changing = null; object changed = null; int changingCount = 0; int changedCount = 0; JObject o = new JObject(); o.PropertyChanging += (sender, args) => { JObject s = (JObject)sender; changing = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null; changingCount++; }; o.PropertyChanged += (sender, args) => { JObject s = (JObject)sender; changed = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null; changedCount++; }; o["StringValue"] = "value1"; Assert.AreEqual(null, changing); Assert.AreEqual("value1", changed); Assert.AreEqual("value1", (string)o["StringValue"]); Assert.AreEqual(1, changingCount); Assert.AreEqual(1, changedCount); o["StringValue"] = "value1"; Assert.AreEqual(1, changingCount); Assert.AreEqual(1, changedCount); o["StringValue"] = "value2"; Assert.AreEqual("value1", changing); Assert.AreEqual("value2", changed); Assert.AreEqual("value2", (string)o["StringValue"]); Assert.AreEqual(2, changingCount); Assert.AreEqual(2, changedCount); o["StringValue"] = null; Assert.AreEqual("value2", changing); Assert.AreEqual(null, changed); Assert.AreEqual(null, (string)o["StringValue"]); Assert.AreEqual(3, changingCount); Assert.AreEqual(3, changedCount); o["NullValue"] = null; Assert.AreEqual(null, changing); Assert.AreEqual(null, changed); Assert.AreEqual(JValue.CreateNull(), o["NullValue"]); Assert.AreEqual(4, changingCount); Assert.AreEqual(4, changedCount); o["NullValue"] = null; Assert.AreEqual(4, changingCount); Assert.AreEqual(4, changedCount); } #endif [Test] public void PropertyChanged() { object changed = null; int changedCount = 0; JObject o = new JObject(); o.PropertyChanged += (sender, args) => { JObject s = (JObject)sender; changed = (s[args.PropertyName] != null) ? ((JValue)s[args.PropertyName]).Value : null; changedCount++; }; o["StringValue"] = "value1"; Assert.AreEqual("value1", changed); Assert.AreEqual("value1", (string)o["StringValue"]); Assert.AreEqual(1, changedCount); o["StringValue"] = "value1"; Assert.AreEqual(1, changedCount); o["StringValue"] = "value2"; Assert.AreEqual("value2", changed); Assert.AreEqual("value2", (string)o["StringValue"]); Assert.AreEqual(2, changedCount); o["StringValue"] = null; Assert.AreEqual(null, changed); Assert.AreEqual(null, (string)o["StringValue"]); Assert.AreEqual(3, changedCount); o["NullValue"] = null; Assert.AreEqual(null, changed); Assert.AreEqual(JValue.CreateNull(), o["NullValue"]); Assert.AreEqual(4, changedCount); o["NullValue"] = null; Assert.AreEqual(4, changedCount); } [Test] public void IListContains() { JProperty p = new JProperty("Test", 1); IList l = new JObject(p); Assert.IsTrue(l.Contains(p)); Assert.IsFalse(l.Contains(new JProperty("Test", 1))); } [Test] public void IListIndexOf() { JProperty p = new JProperty("Test", 1); IList l = new JObject(p); Assert.AreEqual(0, l.IndexOf(p)); Assert.AreEqual(-1, l.IndexOf(new JProperty("Test", 1))); } [Test] public void IListClear() { JProperty p = new JProperty("Test", 1); IList l = new JObject(p); Assert.AreEqual(1, l.Count); l.Clear(); Assert.AreEqual(0, l.Count); } [Test] public void IListCopyTo() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); object[] a = new object[l.Count]; l.CopyTo(a, 0); Assert.AreEqual(p1, a[0]); Assert.AreEqual(p2, a[1]); } [Test] public void IListAdd() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Add(p3); Assert.AreEqual(3, l.Count); Assert.AreEqual(p3, l[2]); } [Test] public void IListAddBadToken() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); l.Add(new JValue("Bad!")); }, "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject."); } [Test] public void IListAddBadValue() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); l.Add("Bad!"); }, "Argument is not a JToken."); } [Test] public void IListAddPropertyWithExistingName() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test2", "II"); l.Add(p3); }, "Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object."); } [Test] public void IListRemove() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); // won't do anything l.Remove(p3); Assert.AreEqual(2, l.Count); l.Remove(p1); Assert.AreEqual(1, l.Count); Assert.IsFalse(l.Contains(p1)); Assert.IsTrue(l.Contains(p2)); l.Remove(p2); Assert.AreEqual(0, l.Count); Assert.IsFalse(l.Contains(p2)); Assert.AreEqual(null, p2.Parent); } [Test] public void IListRemoveAt() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); // won't do anything l.RemoveAt(0); l.Remove(p1); Assert.AreEqual(1, l.Count); l.Remove(p2); Assert.AreEqual(0, l.Count); } [Test] public void IListInsert() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Insert(1, p3); Assert.AreEqual(l, p3.Parent); Assert.AreEqual(p1, l[0]); Assert.AreEqual(p3, l[1]); Assert.AreEqual(p2, l[2]); } [Test] public void IListIsReadOnly() { IList l = new JObject(); Assert.IsFalse(l.IsReadOnly); } [Test] public void IListIsFixedSize() { IList l = new JObject(); Assert.IsFalse(l.IsFixedSize); } [Test] public void IListSetItem() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; Assert.AreEqual(p3, l[0]); Assert.AreEqual(p2, l[1]); } [Test] public void IListSetItemAlreadyExists() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; l[1] = p3; }, "Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object."); } [Test] public void IListSetItemInvalid() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); l[0] = new JValue(true); }, @"Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject."); } [Test] public void IListSyncRoot() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); Assert.IsNotNull(l.SyncRoot); } [Test] public void IListIsSynchronized() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList l = new JObject(p1, p2); Assert.IsFalse(l.IsSynchronized); } [Test] public void GenericListJTokenContains() { JProperty p = new JProperty("Test", 1); IList<JToken> l = new JObject(p); Assert.IsTrue(l.Contains(p)); Assert.IsFalse(l.Contains(new JProperty("Test", 1))); } [Test] public void GenericListJTokenIndexOf() { JProperty p = new JProperty("Test", 1); IList<JToken> l = new JObject(p); Assert.AreEqual(0, l.IndexOf(p)); Assert.AreEqual(-1, l.IndexOf(new JProperty("Test", 1))); } [Test] public void GenericListJTokenClear() { JProperty p = new JProperty("Test", 1); IList<JToken> l = new JObject(p); Assert.AreEqual(1, l.Count); l.Clear(); Assert.AreEqual(0, l.Count); } [Test] public void GenericListJTokenCopyTo() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JToken[] a = new JToken[l.Count]; l.CopyTo(a, 0); Assert.AreEqual(p1, a[0]); Assert.AreEqual(p2, a[1]); } [Test] public void GenericListJTokenAdd() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Add(p3); Assert.AreEqual(3, l.Count); Assert.AreEqual(p3, l[2]); } [Test] public void GenericListJTokenAddBadToken() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); l.Add(new JValue("Bad!")); }, "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject."); } [Test] public void GenericListJTokenAddBadValue() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); // string is implicitly converted to JValue l.Add("Bad!"); }, "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject."); } [Test] public void GenericListJTokenAddPropertyWithExistingName() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test2", "II"); l.Add(p3); }, "Can not add property Test2 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object."); } [Test] public void GenericListJTokenRemove() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); // won't do anything Assert.IsFalse(l.Remove(p3)); Assert.AreEqual(2, l.Count); Assert.IsTrue(l.Remove(p1)); Assert.AreEqual(1, l.Count); Assert.IsFalse(l.Contains(p1)); Assert.IsTrue(l.Contains(p2)); Assert.IsTrue(l.Remove(p2)); Assert.AreEqual(0, l.Count); Assert.IsFalse(l.Contains(p2)); Assert.AreEqual(null, p2.Parent); } [Test] public void GenericListJTokenRemoveAt() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); // won't do anything l.RemoveAt(0); l.Remove(p1); Assert.AreEqual(1, l.Count); l.Remove(p2); Assert.AreEqual(0, l.Count); } [Test] public void GenericListJTokenInsert() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l.Insert(1, p3); Assert.AreEqual(l, p3.Parent); Assert.AreEqual(p1, l[0]); Assert.AreEqual(p3, l[1]); Assert.AreEqual(p2, l[2]); } [Test] public void GenericListJTokenIsReadOnly() { IList<JToken> l = new JObject(); Assert.IsFalse(l.IsReadOnly); } [Test] public void GenericListJTokenSetItem() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; Assert.AreEqual(p3, l[0]); Assert.AreEqual(p2, l[1]); } [Test] public void GenericListJTokenSetItemAlreadyExists() { ExceptionAssert.Throws<ArgumentException>(() => { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); IList<JToken> l = new JObject(p1, p2); JProperty p3 = new JProperty("Test3", "III"); l[0] = p3; l[1] = p3; }, "Can not add property Test3 to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object."); } #if !(NETFX_CORE || PORTABLE || PORTABLE40) [Test] public void IBindingListSortDirection() { IBindingList l = new JObject(); Assert.AreEqual(ListSortDirection.Ascending, l.SortDirection); } [Test] public void IBindingListSortProperty() { IBindingList l = new JObject(); Assert.AreEqual(null, l.SortProperty); } [Test] public void IBindingListSupportsChangeNotification() { IBindingList l = new JObject(); Assert.AreEqual(true, l.SupportsChangeNotification); } [Test] public void IBindingListSupportsSearching() { IBindingList l = new JObject(); Assert.AreEqual(false, l.SupportsSearching); } [Test] public void IBindingListSupportsSorting() { IBindingList l = new JObject(); Assert.AreEqual(false, l.SupportsSorting); } [Test] public void IBindingListAllowEdit() { IBindingList l = new JObject(); Assert.AreEqual(true, l.AllowEdit); } [Test] public void IBindingListAllowNew() { IBindingList l = new JObject(); Assert.AreEqual(true, l.AllowNew); } [Test] public void IBindingListAllowRemove() { IBindingList l = new JObject(); Assert.AreEqual(true, l.AllowRemove); } [Test] public void IBindingListAddIndex() { IBindingList l = new JObject(); // do nothing l.AddIndex(null); } [Test] public void IBindingListApplySort() { ExceptionAssert.Throws<NotSupportedException>(() => { IBindingList l = new JObject(); l.ApplySort(null, ListSortDirection.Ascending); }, "Specified method is not supported."); } [Test] public void IBindingListRemoveSort() { ExceptionAssert.Throws<NotSupportedException>(() => { IBindingList l = new JObject(); l.RemoveSort(); }, "Specified method is not supported."); } [Test] public void IBindingListRemoveIndex() { IBindingList l = new JObject(); // do nothing l.RemoveIndex(null); } [Test] public void IBindingListFind() { ExceptionAssert.Throws<NotSupportedException>(() => { IBindingList l = new JObject(); l.Find(null, null); }, "Specified method is not supported."); } [Test] public void IBindingListIsSorted() { IBindingList l = new JObject(); Assert.AreEqual(false, l.IsSorted); } [Test] public void IBindingListAddNew() { ExceptionAssert.Throws<JsonException>(() => { IBindingList l = new JObject(); l.AddNew(); }, "Could not determine new value to add to 'Newtonsoft.Json.Linq.JObject'."); } [Test] public void IBindingListAddNewWithEvent() { JObject o = new JObject(); o._addingNew += (s, e) => e.NewObject = new JProperty("Property!"); IBindingList l = o; object newObject = l.AddNew(); Assert.IsNotNull(newObject); JProperty p = (JProperty)newObject; Assert.AreEqual("Property!", p.Name); Assert.AreEqual(o, p.Parent); } [Test] public void ITypedListGetListName() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); ITypedList l = new JObject(p1, p2); Assert.AreEqual(string.Empty, l.GetListName(null)); } [Test] public void ITypedListGetItemProperties() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); ITypedList l = new JObject(p1, p2); PropertyDescriptorCollection propertyDescriptors = l.GetItemProperties(null); Assert.IsNull(propertyDescriptors); } [Test] public void ListChanged() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); JObject o = new JObject(p1, p2); ListChangedType? changedType = null; int? index = null; o.ListChanged += (s, a) => { changedType = a.ListChangedType; index = a.NewIndex; }; JProperty p3 = new JProperty("Test3", "III"); o.Add(p3); Assert.AreEqual(changedType, ListChangedType.ItemAdded); Assert.AreEqual(index, 2); Assert.AreEqual(p3, ((IList<JToken>)o)[index.Value]); JProperty p4 = new JProperty("Test4", "IV"); ((IList<JToken>)o)[index.Value] = p4; Assert.AreEqual(changedType, ListChangedType.ItemChanged); Assert.AreEqual(index, 2); Assert.AreEqual(p4, ((IList<JToken>)o)[index.Value]); Assert.IsFalse(((IList<JToken>)o).Contains(p3)); Assert.IsTrue(((IList<JToken>)o).Contains(p4)); o["Test1"] = 2; Assert.AreEqual(changedType, ListChangedType.ItemChanged); Assert.AreEqual(index, 0); Assert.AreEqual(2, (int)o["Test1"]); } #endif #if !(NET20 || NET35 || PORTABLE40) [Test] public void CollectionChanged() { JProperty p1 = new JProperty("Test1", 1); JProperty p2 = new JProperty("Test2", "Two"); JObject o = new JObject(p1, p2); NotifyCollectionChangedAction? changedType = null; int? index = null; o._collectionChanged += (s, a) => { changedType = a.Action; index = a.NewStartingIndex; }; JProperty p3 = new JProperty("Test3", "III"); o.Add(p3); Assert.AreEqual(changedType, NotifyCollectionChangedAction.Add); Assert.AreEqual(index, 2); Assert.AreEqual(p3, ((IList<JToken>)o)[index.Value]); JProperty p4 = new JProperty("Test4", "IV"); ((IList<JToken>)o)[index.Value] = p4; Assert.AreEqual(changedType, NotifyCollectionChangedAction.Replace); Assert.AreEqual(index, 2); Assert.AreEqual(p4, ((IList<JToken>)o)[index.Value]); Assert.IsFalse(((IList<JToken>)o).Contains(p3)); Assert.IsTrue(((IList<JToken>)o).Contains(p4)); o["Test1"] = 2; Assert.AreEqual(changedType, NotifyCollectionChangedAction.Replace); Assert.AreEqual(index, 0); Assert.AreEqual(2, (int)o["Test1"]); } #endif [Test] public void GetGeocodeAddress() { string json = @"{ ""name"": ""Address: 435 North Mulford Road Rockford, IL 61107"", ""Status"": { ""code"": 200, ""request"": ""geocode"" }, ""Placemark"": [ { ""id"": ""p1"", ""address"": ""435 N Mulford Rd, Rockford, IL 61107, USA"", ""AddressDetails"": { ""Accuracy"" : 8, ""Country"" : { ""AdministrativeArea"" : { ""AdministrativeAreaName"" : ""IL"", ""SubAdministrativeArea"" : { ""Locality"" : { ""LocalityName"" : ""Rockford"", ""PostalCode"" : { ""PostalCodeNumber"" : ""61107"" }, ""Thoroughfare"" : { ""ThoroughfareName"" : ""435 N Mulford Rd"" } }, ""SubAdministrativeAreaName"" : ""Winnebago"" } }, ""CountryName"" : ""USA"", ""CountryNameCode"" : ""US"" } }, ""ExtendedData"": { ""LatLonBox"": { ""north"": 42.2753076, ""south"": 42.2690124, ""east"": -88.9964645, ""west"": -89.0027597 } }, ""Point"": { ""coordinates"": [ -88.9995886, 42.2721596, 0 ] } } ] }"; JObject o = JObject.Parse(json); string searchAddress = (string)o["Placemark"][0]["AddressDetails"]["Country"]["AdministrativeArea"]["SubAdministrativeArea"]["Locality"]["Thoroughfare"]["ThoroughfareName"]; Assert.AreEqual("435 N Mulford Rd", searchAddress); } [Test] public void SetValueWithInvalidPropertyName() { ExceptionAssert.Throws<ArgumentException>(() => { JObject o = new JObject(); o[0] = new JValue(3); }, "Set JObject values with invalid key value: 0. Object property name expected."); } [Test] public void SetValue() { object key = "TestKey"; JObject o = new JObject(); o[key] = new JValue(3); Assert.AreEqual(3, (int)o[key]); } [Test] public void ParseMultipleProperties() { string json = @"{ ""Name"": ""Name1"", ""Name"": ""Name2"" }"; JObject o = JObject.Parse(json); string value = (string)o["Name"]; Assert.AreEqual("Name2", value); } #if !(NETFX_CORE || PORTABLE || PORTABLE40) [Test] public void WriteObjectNullDBNullValue() { DBNull dbNull = DBNull.Value; JValue v = new JValue(dbNull); Assert.AreEqual(DBNull.Value, v.Value); Assert.AreEqual(JTokenType.Null, v.Type); JObject o = new JObject(); o["title"] = v; string output = o.ToString(); StringAssert.AreEqual(@"{ ""title"": null }", output); } #endif [Test] public void InvalidValueCastExceptionMessage() { ExceptionAssert.Throws<ArgumentException>(() => { string json = @"{ ""responseData"": {}, ""responseDetails"": null, ""responseStatus"": 200 }"; JObject o = JObject.Parse(json); string name = (string)o["responseData"]; }, "Can not convert Object to String."); } [Test] public void InvalidPropertyValueCastExceptionMessage() { ExceptionAssert.Throws<ArgumentException>(() => { string json = @"{ ""responseData"": {}, ""responseDetails"": null, ""responseStatus"": 200 }"; JObject o = JObject.Parse(json); string name = (string)o.Property("responseData"); }, "Can not convert Object to String."); } [Test] public void ParseIncomplete() { ExceptionAssert.Throws<Exception>(() => { JObject.Parse("{ foo:"); }, "Unexpected end of content while loading JObject. Path 'foo', line 1, position 6."); } [Test] public void LoadFromNestedObject() { string jsonText = @"{ ""short"": { ""error"": { ""code"":0, ""msg"":""No action taken"" } } }"; JsonReader reader = new JsonTextReader(new StringReader(jsonText)); reader.Read(); reader.Read(); reader.Read(); reader.Read(); reader.Read(); JObject o = (JObject)JToken.ReadFrom(reader); Assert.IsNotNull(o); StringAssert.AreEqual(@"{ ""code"": 0, ""msg"": ""No action taken"" }", o.ToString(Formatting.Indented)); } [Test] public void LoadFromNestedObjectIncomplete() { ExceptionAssert.Throws<JsonReaderException>(() => { string jsonText = @"{ ""short"": { ""error"": { ""code"":0"; JsonReader reader = new JsonTextReader(new StringReader(jsonText)); reader.Read(); reader.Read(); reader.Read(); reader.Read(); reader.Read(); JToken.ReadFrom(reader); }, "Unexpected end of content while loading JObject. Path 'short.error.code', line 6, position 15."); } #if !(NETFX_CORE || PORTABLE || PORTABLE40) [Test] public void GetProperties() { JObject o = JObject.Parse("{'prop1':12,'prop2':'hi!','prop3':null,'prop4':[1,2,3]}"); ICustomTypeDescriptor descriptor = o; PropertyDescriptorCollection properties = descriptor.GetProperties(); Assert.AreEqual(4, properties.Count); PropertyDescriptor prop1 = properties[0]; Assert.AreEqual("prop1", prop1.Name); Assert.AreEqual(typeof(object), prop1.PropertyType); Assert.AreEqual(typeof(JObject), prop1.ComponentType); Assert.AreEqual(false, prop1.CanResetValue(o)); Assert.AreEqual(false, prop1.ShouldSerializeValue(o)); PropertyDescriptor prop2 = properties[1]; Assert.AreEqual("prop2", prop2.Name); Assert.AreEqual(typeof(object), prop2.PropertyType); Assert.AreEqual(typeof(JObject), prop2.ComponentType); Assert.AreEqual(false, prop2.CanResetValue(o)); Assert.AreEqual(false, prop2.ShouldSerializeValue(o)); PropertyDescriptor prop3 = properties[2]; Assert.AreEqual("prop3", prop3.Name); Assert.AreEqual(typeof(object), prop3.PropertyType); Assert.AreEqual(typeof(JObject), prop3.ComponentType); Assert.AreEqual(false, prop3.CanResetValue(o)); Assert.AreEqual(false, prop3.ShouldSerializeValue(o)); PropertyDescriptor prop4 = properties[3]; Assert.AreEqual("prop4", prop4.Name); Assert.AreEqual(typeof(object), prop4.PropertyType); Assert.AreEqual(typeof(JObject), prop4.ComponentType); Assert.AreEqual(false, prop4.CanResetValue(o)); Assert.AreEqual(false, prop4.ShouldSerializeValue(o)); } #endif [Test] public void ParseEmptyObjectWithComment() { JObject o = JObject.Parse("{ /* A Comment */ }"); Assert.AreEqual(0, o.Count); } [Test] public void FromObjectTimeSpan() { JValue v = (JValue)JToken.FromObject(TimeSpan.FromDays(1)); Assert.AreEqual(v.Value, TimeSpan.FromDays(1)); Assert.AreEqual("1.00:00:00", v.ToString()); } [Test] public void FromObjectUri() { JValue v = (JValue)JToken.FromObject(new Uri("http://www.stuff.co.nz")); Assert.AreEqual(v.Value, new Uri("http://www.stuff.co.nz")); Assert.AreEqual("http://www.stuff.co.nz/", v.ToString()); } [Test] public void FromObjectGuid() { JValue v = (JValue)JToken.FromObject(new Guid("9065ACF3-C820-467D-BE50-8D4664BEAF35")); Assert.AreEqual(v.Value, new Guid("9065ACF3-C820-467D-BE50-8D4664BEAF35")); Assert.AreEqual("9065acf3-c820-467d-be50-8d4664beaf35", v.ToString()); } [Test] public void ParseAdditionalContent() { ExceptionAssert.Throws<JsonReaderException>(() => { string json = @"{ ""Name"": ""Apple"", ""Expiry"": new Date(1230422400000), ""Price"": 3.99, ""Sizes"": [ ""Small"", ""Medium"", ""Large"" ] }, 987987"; JObject o = JObject.Parse(json); }, "Additional text encountered after finished reading JSON content: ,. Path '', line 10, position 2."); } [Test] public void DeepEqualsIgnoreOrder() { JObject o1 = new JObject( new JProperty("null", null), new JProperty("integer", 1), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("array", new JArray(1, 2))); Assert.IsTrue(o1.DeepEquals(o1)); JObject o2 = new JObject( new JProperty("null", null), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("integer", 1), new JProperty("array", new JArray(1, 2))); Assert.IsTrue(o1.DeepEquals(o2)); JObject o3 = new JObject( new JProperty("null", null), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("integer", 2), new JProperty("array", new JArray(1, 2))); Assert.IsFalse(o1.DeepEquals(o3)); JObject o4 = new JObject( new JProperty("null", null), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("integer", 1), new JProperty("array", new JArray(2, 1))); Assert.IsFalse(o1.DeepEquals(o4)); JObject o5 = new JObject( new JProperty("null", null), new JProperty("string", "string!"), new JProperty("decimal", 0.5m), new JProperty("integer", 1)); Assert.IsFalse(o1.DeepEquals(o5)); Assert.IsFalse(o1.DeepEquals(null)); } [Test] public void ToListOnEmptyObject() { JObject o = JObject.Parse(@"{}"); IList<JToken> l1 = o.ToList<JToken>(); Assert.AreEqual(0, l1.Count); IList<KeyValuePair<string, JToken>> l2 = o.ToList<KeyValuePair<string, JToken>>(); Assert.AreEqual(0, l2.Count); o = JObject.Parse(@"{'hi':null}"); l1 = o.ToList<JToken>(); Assert.AreEqual(1, l1.Count); l2 = o.ToList<KeyValuePair<string, JToken>>(); Assert.AreEqual(1, l2.Count); } [Test] public void EmptyObjectDeepEquals() { Assert.IsTrue(JToken.DeepEquals(new JObject(), new JObject())); JObject a = new JObject(); JObject b = new JObject(); b.Add("hi", "bye"); b.Remove("hi"); Assert.IsTrue(JToken.DeepEquals(a, b)); Assert.IsTrue(JToken.DeepEquals(b, a)); } [Test] public void GetValueBlogExample() { JObject o = JObject.Parse(@"{ 'name': 'Lower', 'NAME': 'Upper' }"); string exactMatch = (string)o.GetValue("NAME", StringComparison.OrdinalIgnoreCase); // Upper string ignoreCase = (string)o.GetValue("Name", StringComparison.OrdinalIgnoreCase); // Lower Assert.AreEqual("Upper", exactMatch); Assert.AreEqual("Lower", ignoreCase); } [Test] public void GetValue() { JObject a = new JObject(); a["Name"] = "Name!"; a["name"] = "name!"; a["title"] = "Title!"; Assert.AreEqual(null, a.GetValue("NAME", StringComparison.Ordinal)); Assert.AreEqual(null, a.GetValue("NAME")); Assert.AreEqual(null, a.GetValue("TITLE")); Assert.AreEqual("Name!", (string)a.GetValue("NAME", StringComparison.OrdinalIgnoreCase)); Assert.AreEqual("name!", (string)a.GetValue("name", StringComparison.Ordinal)); Assert.AreEqual(null, a.GetValue(null, StringComparison.Ordinal)); Assert.AreEqual(null, a.GetValue(null)); JToken v; Assert.IsFalse(a.TryGetValue("NAME", StringComparison.Ordinal, out v)); Assert.AreEqual(null, v); Assert.IsFalse(a.TryGetValue("NAME", out v)); Assert.IsFalse(a.TryGetValue("TITLE", out v)); Assert.IsTrue(a.TryGetValue("NAME", StringComparison.OrdinalIgnoreCase, out v)); Assert.AreEqual("Name!", (string)v); Assert.IsTrue(a.TryGetValue("name", StringComparison.Ordinal, out v)); Assert.AreEqual("name!", (string)v); Assert.IsFalse(a.TryGetValue(null, StringComparison.Ordinal, out v)); } public class FooJsonConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var token = JToken.FromObject(value, new JsonSerializer { ContractResolver = new CamelCasePropertyNamesContractResolver() }); if (token.Type == JTokenType.Object) { var o = (JObject)token; o.AddFirst(new JProperty("foo", "bar")); o.WriteTo(writer); } else token.WriteTo(writer); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotSupportedException("This custom converter only supportes serialization and not deserialization."); } public override bool CanRead { get { return false; } } public override bool CanConvert(Type objectType) { return true; } } [Test] public void FromObjectInsideConverterWithCustomSerializer() { var p = new Person { Name = "Daniel Wertheim", }; var settings = new JsonSerializerSettings { Converters = new List<JsonConverter> { new FooJsonConverter() }, ContractResolver = new CamelCasePropertyNamesContractResolver() }; var json = JsonConvert.SerializeObject(p, settings); Assert.AreEqual(@"{""foo"":""bar"",""name"":""Daniel Wertheim"",""birthDate"":""0001-01-01T00:00:00"",""lastModified"":""0001-01-01T00:00:00""}", json); } } }
using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Globalization; using System.Linq; using System.Xml; using System.Xml.Linq; using System.Xml.Schema; using System.Xml.Serialization; using MathNet.Numerics.LinearAlgebra; using MathNet.Spatial.Units; namespace MathNet.Spatial.Euclidean { /// <summary> /// A unit vector, this is used to describe a direction in 3D /// </summary> [Serializable] public struct UnitVector3D : IXmlSerializable, IEquatable<UnitVector3D>, IEquatable<Vector3D>, IFormattable { /// <summary> /// Using public fields cos: http://blogs.msdn.com/b/ricom/archive/2006/08/31/performance-quiz-11-ten-questions-on-value-based-programming.aspx /// </summary> public readonly double X; /// <summary> /// Using public fields cos: http://blogs.msdn.com/b/ricom/archive/2006/08/31/performance-quiz-11-ten-questions-on-value-based-programming.aspx /// </summary> public readonly double Y; /// <summary> /// Using public fields cos: http://blogs.msdn.com/b/ricom/archive/2006/08/31/performance-quiz-11-ten-questions-on-value-based-programming.aspx /// </summary> public readonly double Z; public UnitVector3D(double x, double y, double z) { var l = Math.Sqrt((x*x) + (y*y) + (z*z)); if (l < float.Epsilon) { throw new ArgumentException("l < float.Epsilon"); } this.X = x/l; this.Y = y/l; this.Z = z/l; } public UnitVector3D(IEnumerable<double> data) : this(data.ToArray()) { } public UnitVector3D(double[] data) : this(data[0], data[1], data[2]) { if (data.Length != 3) { throw new ArgumentException("Size must be 3"); } } /// <summary> /// A vector orthogonbal to this /// </summary> public UnitVector3D Orthogonal { get { if (-this.X - this.Y > 0.1) { return new UnitVector3D(this.Z, this.Z, -this.X - this.Y); } return new UnitVector3D(-this.Y - this.Z, this.X, this.X); } } /// <summary> /// Creates a UnitVector3D from its string representation /// </summary> /// <param name="s">The string representation of the UnitVector3D</param> /// <returns></returns> public static UnitVector3D Parse(string s) { var doubles = Parser.ParseItem3D(s); return new UnitVector3D(doubles); } public static bool operator ==(UnitVector3D left, UnitVector3D right) { return left.Equals(right); } public static bool operator ==(Vector3D left, UnitVector3D right) { return left.Equals(right); } public static bool operator ==(UnitVector3D left, Vector3D right) { return left.Equals(right); } public static bool operator !=(UnitVector3D left, UnitVector3D right) { return !left.Equals(right); } public static bool operator !=(Vector3D left, UnitVector3D right) { return !left.Equals(right); } public static bool operator !=(UnitVector3D left, Vector3D right) { return !left.Equals(right); } [Obsolete("Not sure this is nice")] public static Vector<double> operator *(Matrix<double> left, UnitVector3D right) { return left*right.ToVector(); } [Obsolete("Not sure this is nice")] public static Vector<double> operator *(UnitVector3D left, Matrix<double> right) { return left.ToVector()*right; } public static double operator *(UnitVector3D left, UnitVector3D right) { return left.DotProduct(right); } public override string ToString() { return this.ToString(null, CultureInfo.InvariantCulture); } public string ToString(IFormatProvider provider) { return this.ToString(null, provider); } public string ToString(string format, IFormatProvider provider = null) { var numberFormatInfo = provider != null ? NumberFormatInfo.GetInstance(provider) : CultureInfo.InvariantCulture.NumberFormat; string separator = numberFormatInfo.NumberDecimalSeparator == "," ? ";" : ","; return string.Format("({0}{1} {2}{1} {3})", this.X.ToString(format, numberFormatInfo), separator, this.Y.ToString(format, numberFormatInfo), this.Z.ToString(format, numberFormatInfo)); } public bool Equals(Vector3D other) { // ReSharper disable CompareOfFloatsByEqualityOperator return this.X == other.X && this.Y == other.Y && this.Z == other.Z; // ReSharper restore CompareOfFloatsByEqualityOperator } public bool Equals(UnitVector3D other) { // ReSharper disable CompareOfFloatsByEqualityOperator return this.X == other.X && this.Y == other.Y && this.Z == other.Z; // ReSharper restore CompareOfFloatsByEqualityOperator } public bool Equals(UnitVector3D other, double tolerance) { if (tolerance < 0) { throw new ArgumentException("epsilon < 0"); } return Math.Abs(other.X - this.X) < tolerance && Math.Abs(other.Y - this.Y) < tolerance && Math.Abs(other.Z - this.Z) < tolerance; } public bool Equals(Vector3D other, double tolerance) { if (tolerance < 0) { throw new ArgumentException("epsilon < 0"); } return Math.Abs(other.X - this.X) < tolerance && Math.Abs(other.Y - this.Y) < tolerance && Math.Abs(other.Z - this.Z) < tolerance; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } return (obj is UnitVector3D && this.Equals((UnitVector3D)obj)) || (obj is Vector3D && this.Equals((Vector3D)obj)); } public override int GetHashCode() { unchecked { var hashCode = this.X.GetHashCode(); hashCode = (hashCode*397) ^ this.Y.GetHashCode(); hashCode = (hashCode*397) ^ this.Z.GetHashCode(); return hashCode; } } /// <summary> /// This method is reserved and should not be used. When implementing the IXmlSerializable interface, you should return null (Nothing in Visual Basic) from this method, and instead, if specifying a custom schema is required, apply the <see cref="T:System.Xml.Serialization.XmlSchemaProviderAttribute"/> to the class. /// </summary> /// <returns> /// An <see cref="T:System.Xml.Schema.XmlSchema"/> that describes the XML representation of the object that is produced by the <see cref="M:System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)"/> method and consumed by the <see cref="M:System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)"/> method. /// </returns> public XmlSchema GetSchema() { return null; } /// <summary> /// Generates an object from its XML representation. /// </summary> /// <param name="reader">The <see cref="T:System.Xml.XmlReader"/> stream from which the object is deserialized. </param> public void ReadXml(XmlReader reader) { reader.MoveToContent(); var e = (XElement)XNode.ReadFrom(reader); // Hacking set readonly fields here, can't think of a cleaner workaround XmlExt.SetReadonlyField(ref this, x => x.X, XmlConvert.ToDouble(e.ReadAttributeOrElementOrDefault("X"))); XmlExt.SetReadonlyField(ref this, x => x.Y, XmlConvert.ToDouble(e.ReadAttributeOrElementOrDefault("Y"))); XmlExt.SetReadonlyField(ref this, x => x.Z, XmlConvert.ToDouble(e.ReadAttributeOrElementOrDefault("Z"))); } /// <summary> /// Converts an object into its XML representation. /// </summary> /// <param name="writer">The <see cref="T:System.Xml.XmlWriter"/> stream to which the object is serialized. </param> public void WriteXml(XmlWriter writer) { writer.WriteAttribute("X", this.X); writer.WriteAttribute("Y", this.Y); writer.WriteAttribute("Z", this.Z); } public static UnitVector3D ReadFrom(XmlReader reader) { var v = new UnitVector3D(); v.ReadXml(reader); return v; } public static UnitVector3D XAxis { get { return new UnitVector3D(1, 0, 0); } } public static UnitVector3D YAxis { get { return new UnitVector3D(0, 1, 0); } } public static UnitVector3D ZAxis { get { return new UnitVector3D(0, 0, 1); } } internal Matrix<double> CrossProductMatrix { get { return Matrix<double>.Build.Dense(3, 3, new[] { 0d, Z, -Y, -Z, 0d, X, Y, -X, 0d }); } } /// <summary> /// The length of the vector not the count of elements /// </summary> public double Length { get { return 1; } } public static Vector3D operator +(UnitVector3D v1, UnitVector3D v2) { return new Vector3D(v1.X + v2.X, v1.Y + v2.Y, v1.Z + v2.Z); } public static Vector3D operator +(Vector3D v1, UnitVector3D v2) { return new Vector3D(v1.X + v2.X, v1.Y + v2.Y, v1.Z + v2.Z); } public static Vector3D operator +(UnitVector3D v1, Vector3D v2) { return new Vector3D(v1.X + v2.X, v1.Y + v2.Y, v1.Z + v2.Z); } public static Vector3D operator -(UnitVector3D v1, UnitVector3D v2) { return new Vector3D(v1.X - v2.X, v1.Y - v2.Y, v1.Z - v2.Z); } public static Vector3D operator -(Vector3D v1, UnitVector3D v2) { return new Vector3D(v1.X - v2.X, v1.Y - v2.Y, v1.Z - v2.Z); } public static Vector3D operator -(UnitVector3D v1, Vector3D v2) { return new Vector3D(v1.X - v2.X, v1.Y - v2.Y, v1.Z - v2.Z); } public static Vector3D operator -(UnitVector3D v) { return new Vector3D(-1*v.X, -1*v.Y, -1*v.Z); } public static Vector3D operator *(double d, UnitVector3D v) { return new Vector3D(d*v.X, d*v.Y, d*v.Z); } // Commented out because the d * v reads nicer than v *d ////public static Vector3D operator *(Vector3D v,double d) ////{ //// return d*v; ////} public static Vector3D operator /(UnitVector3D v, double d) { return new Vector3D(v.X/d, v.Y/d, v.Z/d); } ////public static explicit operator UnitVector3D(System.Windows.Media.Media3D.Vector3D v) ////{ //// return new UnitVector3D(v.X, v.Y, v.Z); ////} ////public static explicit operator System.Windows.Media.Media3D.Vector3D(UnitVector3D p) ////{ //// return new System.Windows.Media.Media3D.Vector3D(p.X, p.Y, p.Z); ////} public Vector3D ScaleBy(double scaleFactor) { return scaleFactor*this; } [Pure] public Ray3D ProjectOn(Plane planeToProjectOn) { return planeToProjectOn.Project(this.ToVector3D()); } public Vector3D ProjectOn(UnitVector3D uv) { double pd = DotProduct(uv); return pd*this; } [Pure] public bool IsParallelTo(Vector3D othervector, double tolerance = 1e-6) { var other = othervector.Normalize(); var dp = Math.Abs(this.DotProduct(other)); return Math.Abs(1 - dp) < tolerance; } [Pure] public bool IsParallelTo(UnitVector3D othervector, double tolerance = 1e-6) { var dp = Math.Abs(this.DotProduct(othervector)); return Math.Abs(1 - dp) < tolerance; } [Pure] public bool IsPerpendicularTo(Vector3D othervector, double tolerance = 1e-6) { var other = othervector.Normalize(); return Math.Abs(this.DotProduct(other)) < tolerance; } [Pure] public bool IsPerpendicularTo(UnitVector3D othervector, double tolerance = 1e-6) { return Math.Abs(this.DotProduct(othervector)) < tolerance; } [Pure] public UnitVector3D Negate() { return new UnitVector3D(-1*this.X, -1*this.Y, -1*this.Z); } [Pure] public double DotProduct(Vector3D v) { return (this.X*v.X) + (this.Y*v.Y) + (this.Z*v.Z); } [Pure] public double DotProduct(UnitVector3D v) { var dp = (this.X*v.X) + (this.Y*v.Y) + (this.Z*v.Z); return Math.Max(-1, Math.Min(dp, 1)); } [Obsolete("Use - instead")] public Vector3D Subtract(UnitVector3D v) { return new Vector3D(this.X - v.X, this.Y - v.Y, this.Z - v.Z); } [Obsolete("Use + instead")] public Vector3D Add(UnitVector3D v) { return new Vector3D(this.X + v.X, this.Y + v.Y, this.Z + v.Z); } public UnitVector3D CrossProduct(UnitVector3D inVector3D) { var x = (this.Y*inVector3D.Z) - (this.Z*inVector3D.Y); var y = (this.Z*inVector3D.X) - (this.X*inVector3D.Z); var z = (this.X*inVector3D.Y) - (this.Y*inVector3D.X); var v = new UnitVector3D(x, y, z); return v; } public Vector3D CrossProduct(Vector3D inVector3D) { var x = (this.Y*inVector3D.Z) - (this.Z*inVector3D.Y); var y = (this.Z*inVector3D.X) - (this.X*inVector3D.Z); var z = (this.X*inVector3D.Y) - (this.Y*inVector3D.X); var v = new Vector3D(x, y, z); return v; } public Matrix<double> GetUnitTensorProduct() { // unitTensorProduct:matrix([ux^2,ux*uy,ux*uz],[ux*uy,uy^2,uy*uz],[ux*uz,uy*uz,uz^2]), double xy = X*Y; double xz = X*Z; double yz = Y*Z; return Matrix<double>.Build.Dense(3, 3, new[] { X*X, xy, xz, xy, Y*Y, yz, xz, yz, Z*Z }); } /// <summary> /// Returns signed angle /// </summary> /// <param name="v">The fromVector3D to calculate the signed angle to </param> /// <param name="about">The vector around which to rotate to get the correct sign</param> public Angle SignedAngleTo(Vector3D v, UnitVector3D about) { return SignedAngleTo(v.Normalize(), about); } /// <summary> /// Returns signed angle /// </summary> /// <param name="v">The fromVector3D to calculate the signed angle to </param> /// <param name="about">The vector around which to rotate to get the correct sign</param> public Angle SignedAngleTo(UnitVector3D v, UnitVector3D about) { if (IsParallelTo(about)) { throw new ArgumentException("FromVector paralell to aboutVector"); } if (v.IsParallelTo(about)) { throw new ArgumentException("FromVector paralell to aboutVector"); } var rp = new Plane(new Point3D(0, 0, 0), about); var pfv = ProjectOn(rp).Direction; var ptv = v.ProjectOn(rp).Direction; var dp = pfv.DotProduct(ptv); if (Math.Abs(dp - 1) < 1E-15) { return new Angle(0, AngleUnit.Radians); } if (Math.Abs(dp + 1) < 1E-15) { return new Angle(Math.PI, AngleUnit.Radians); } var angle = Math.Acos(dp); var cpv = pfv.CrossProduct(ptv); var sign = cpv.DotProduct(rp.Normal); var signedAngle = sign*angle; return new Angle(signedAngle, AngleUnit.Radians); } /// <summary> /// The nearest angle between the vectors /// </summary> /// <param name="v">The other vector</param> /// <returns>The angle</returns> public Angle AngleTo(Vector3D v) { return AngleTo(v.Normalize()); } /// <summary> /// The nearest angle between the vectors /// </summary> /// <param name="v">The other vector</param> /// <returns>The angle</returns> public Angle AngleTo(UnitVector3D v) { var dp = this.DotProduct(v); var angle = Math.Acos(dp); return new Angle(angle, AngleUnit.Radians); } /// <summary> /// Returns a vector that is this vector rotated the signed angle around the about vector /// </summary> /// <param name="about"></param> /// <param name="angle"></param> /// <returns></returns> public UnitVector3D Rotate<T>(UnitVector3D about, double angle, T angleUnit) where T : IAngleUnit { return this.Rotate(about, Angle.From(angle, angleUnit)); } /// <summary> /// Returns a vector that is this vector rotated the signed angle around the about vector /// </summary> /// <param name="about"></param> /// <param name="angle"></param> /// <returns></returns> public UnitVector3D Rotate(UnitVector3D about, Angle angle) { var cs = CoordinateSystem.Rotation(angle, about); return cs.Transform(this).Normalize(); } public Point3D ToPoint3D() { return new Point3D(this.X, this.Y, this.Z); } [Pure] public Vector3D ToVector3D() { return new Vector3D(this.X, this.Y, this.Z); } public Vector3D TransformBy(CoordinateSystem coordinateSystem) { return coordinateSystem.Transform(this.ToVector3D()); } public Vector3D TransformBy(Matrix<double> m) { return new Vector3D(m.Multiply(this.ToVector())); } /// <summary> /// Convert to a Math.NET Numerics dense vector of length 3. /// </summary> public Vector<double> ToVector() { return Vector<double>.Build.Dense(new[] { X, Y, Z }); } } }
/* * Copyright (C) Sony Computer Entertainment America LLC. * All Rights Reserved. */ using System; using Sce.Sled.Shared.Dom; namespace Sce.Sled.Shared.Services { /// <summary> /// Types of SLED breakpoint changes /// </summary> public enum SledBreakpointChangeType { /// <summary> /// Line number change /// </summary> LineNumber, /// <summary> /// Breakpoint is now enabled (previously disabled) /// </summary> Enabled, /// <summary> /// Breakpoint is now disabled (previously enabled) /// </summary> Disabled, /// <summary> /// Condition change /// </summary> Condition, /// <summary> /// Condition is now enabled (previously disabled) /// </summary> ConditionEnabled, /// <summary> /// Condition is now disabled (previously enabled) /// </summary> ConditionDisabled, /// <summary> /// Condition result will now be evaluated against the value "true" (previously "false") /// </summary> ConditionResultTrue, /// <summary> /// Condition result will now be evaluated against the value "false" (previously "true") /// </summary> ConditionResultFalse, /// <summary> /// Use the function's environment table as the function environment when checking conditional breakpoints /// </summary> UseFunctionEnvironmentTrue, /// <summary> /// Use the global table as the function environment when checking conditional breakpoints /// </summary> UseFunctionEnvironmentFalse, } /// <summary> /// SLED breakpoint service breakpoint EventArgs class /// </summary> public class SledBreakpointServiceBreakpointEventArgs : EventArgs { /// <summary> /// Constructor /// </summary> /// <param name="bp">Breakpoint type</param> public SledBreakpointServiceBreakpointEventArgs(SledProjectFilesBreakpointType bp) { Breakpoint = bp; } /// <summary> /// Get breakpoint type /// </summary> public SledProjectFilesBreakpointType Breakpoint { get; private set; } } /// <summary> /// SLED breakpoint changing event arguments class /// <remarks>This class has various constructors for different types of breakpoint changes</remarks> /// </summary> public class SledBreakpointServiceBreakpointChangingEventArgs : EventArgs { /// <summary> /// Constructor /// </summary> /// <param name="changeType">Breakpoint change type</param> /// <param name="bp">Breakpoint type</param> public SledBreakpointServiceBreakpointChangingEventArgs(SledBreakpointChangeType changeType, SledProjectFilesBreakpointType bp) : this(changeType, bp, -1, -1, null, null) { } /// <summary> /// Constructor /// </summary> /// <param name="changeType">Breakpoint change type</param> /// <param name="bp">Breakpoint type</param> /// <param name="iOldLine">Old breakpoint line number</param> /// <param name="iNewLine">New breakpoint line number</param> public SledBreakpointServiceBreakpointChangingEventArgs(SledBreakpointChangeType changeType, SledProjectFilesBreakpointType bp, int iOldLine, int iNewLine) : this(changeType, bp, iOldLine, iNewLine, null, null) { } /// <summary> /// Constructor /// </summary> /// <param name="changeType">Breakpoint change type</param> /// <param name="bp">Breakpoint type</param> /// <param name="oldCondition">Old breakpoint condition</param> /// <param name="newCondition">New breakpoint condition</param> public SledBreakpointServiceBreakpointChangingEventArgs(SledBreakpointChangeType changeType, SledProjectFilesBreakpointType bp, string oldCondition, string newCondition) : this(changeType, bp, -1, -1, oldCondition, newCondition) { } private SledBreakpointServiceBreakpointChangingEventArgs(SledBreakpointChangeType changeType, SledProjectFilesBreakpointType bp, int iOldLine, int iNewLine, string oldCondition, string newCondition) { ChangeType = changeType; Breakpoint = bp; OldLine = iOldLine; NewLine = iNewLine; OldCondition = oldCondition; NewCondition = newCondition; } /// <summary> /// Get breakpoint change type /// </summary> public SledBreakpointChangeType ChangeType { get; private set; } /// <summary> /// Gets the breakpoint being changed /// </summary> public SledProjectFilesBreakpointType Breakpoint { get; private set; } /// <summary> /// Get old breakpoint line number /// </summary> public int OldLine { get; private set; } /// <summary> /// Gets new breakpoint line number /// </summary> public int NewLine { get; private set; } /// <summary> /// Get old breakpoint condition /// </summary> public string OldCondition { get; private set; } /// <summary> /// Get new breakpoint condition /// </summary> public string NewCondition { get; private set; } } /// <summary> /// SLED breakpoint service interface /// </summary> public interface ISledBreakpointService { /// <summary> /// Event triggered when a breakpoint has been added /// </summary> event EventHandler<SledBreakpointServiceBreakpointEventArgs> Added; /// <summary> /// Event triggered when a breakpoint has been silently added /// </summary> event EventHandler<SledBreakpointServiceBreakpointEventArgs> SilentAdded; /// <summary> /// Event triggered when a breakpoint is being removed /// </summary> event EventHandler<SledBreakpointServiceBreakpointEventArgs> Removing; /// <summary> /// Event triggered when a breakpoint is about to be changed /// </summary> event EventHandler<SledBreakpointServiceBreakpointChangingEventArgs> Changing; /// <summary> /// Event triggered after a breakpoint has changed /// </summary> event EventHandler<SledBreakpointServiceBreakpointChangingEventArgs> Changed; /// <summary> /// Add a breakpoint to a file /// </summary> /// <param name="file">File to add breakpoint to</param> /// <param name="lineNumber">Line number</param> void AddBreakpoint(SledProjectFilesFileType file, int lineNumber); /// <summary> /// Add a breakpoint to a file, supplying a condition /// </summary> /// <param name="file">File to add breakpoint to</param> /// <param name="lineNumber">Line number</param> /// <param name="condition">Breakpoint condition</param> /// <param name="bConditionResult">Whether condition evaluates to true or false</param> void AddBreakpoint(SledProjectFilesFileType file, int lineNumber, string condition, bool bConditionResult); /// <summary> /// Add a breakpoint to a file supplying a condition /// </summary> /// <param name="file">File to add breakpoint to</param> /// <param name="lineNumber">Breakpoint line number</param> /// <param name="condition">Breakpoint condition</param> /// <param name="bConditionResult">Whether breakpoint condition evaluates to true or false</param> /// <param name="bUseFunctionEnvironment">Whether to use the current function's environment or _G when checking the breakpoint condition (if any)</param> void AddBreakpoint(SledProjectFilesFileType file, int lineNumber, string condition, bool bConditionResult, bool bUseFunctionEnvironment); /// <summary> /// Add a breakpoint to a file supplying a condition /// </summary> /// <param name="file">File to add breakpoint to</param> /// <param name="lineNumber">Line number</param> /// <param name="condition">Breakpoint condition</param> /// <param name="conditionResult">Whether breakpoint condition evaluates to true or false</param> /// <param name="conditionEnabled">Whether the breakpoint condition is enabled or not</param> /// <param name="useFunctionEnvironment">Whether to use the current function's environment or _G when checking the breakpoint condition (if any)</param> /// <param name="breakpoint">The breakpoint if it was added, otherwise null</param> /// <returns>Whether the breakpoint was added or not</returns> bool AddBreakpoint(SledProjectFilesFileType file, int lineNumber, string condition, bool conditionResult, bool conditionEnabled, bool useFunctionEnvironment, out SledProjectFilesBreakpointType breakpoint); /// <summary> /// Remove a breakpoint from a file /// </summary> /// <param name="file">File to remove breakpoint from</param> /// <param name="lineNumber">Line number breakpoint is on</param> void RemoveBreakpoint(SledProjectFilesFileType file, int lineNumber); } }
// 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.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; using System.Threading; using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; namespace System.IO.Pipes { public abstract partial class PipeStream : Stream { internal const bool CheckOperationsRequiresSetHandle = true; internal ThreadPoolBoundHandle _threadPoolBinding; internal static string GetPipePath(string serverName, string pipeName) { string normalizedPipePath = Path.GetFullPath(@"\\" + serverName + @"\pipe\" + pipeName); if (String.Equals(normalizedPipePath, @"\\.\pipe\" + AnonymousPipeName, StringComparison.OrdinalIgnoreCase)) { throw new ArgumentOutOfRangeException(nameof(pipeName), SR.ArgumentOutOfRange_AnonymousReserved); } return normalizedPipePath; } /// <summary>Throws an exception if the supplied handle does not represent a valid pipe.</summary> /// <param name="safePipeHandle">The handle to validate.</param> internal void ValidateHandleIsPipe(SafePipeHandle safePipeHandle) { // Check that this handle is infact a handle to a pipe. if (Interop.mincore.GetFileType(safePipeHandle) != Interop.mincore.FileTypes.FILE_TYPE_PIPE) { throw new IOException(SR.IO_InvalidPipeHandle); } } /// <summary>Initializes the handle to be used asynchronously.</summary> /// <param name="handle">The handle.</param> private void InitializeAsyncHandle(SafePipeHandle handle) { // If the handle is of async type, bind the handle to the ThreadPool so that we can use // the async operations (it's needed so that our native callbacks get called). _threadPoolBinding = ThreadPoolBoundHandle.BindHandle(handle); } private void UninitializeAsyncHandle() { if (_threadPoolBinding != null) _threadPoolBinding.Dispose(); } [SecurityCritical] private unsafe int ReadCore(byte[] buffer, int offset, int count) { int errorCode = 0; int r = ReadFileNative(_handle, buffer, offset, count, null, out errorCode); if (r == -1) { // If the other side has broken the connection, set state to Broken and return 0 if (errorCode == Interop.mincore.Errors.ERROR_BROKEN_PIPE || errorCode == Interop.mincore.Errors.ERROR_PIPE_NOT_CONNECTED) { State = PipeState.Broken; r = 0; } else { throw Win32Marshal.GetExceptionForWin32Error(errorCode, String.Empty); } } _isMessageComplete = (errorCode != Interop.mincore.Errors.ERROR_MORE_DATA); Debug.Assert(r >= 0, "PipeStream's ReadCore is likely broken."); return r; } [SecuritySafeCritical] private Task<int> ReadAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { var completionSource = new ReadWriteCompletionSource(this, buffer, cancellationToken, isWrite: false); // Queue an async ReadFile operation and pass in a packed overlapped int errorCode = 0; int r; unsafe { r = ReadFileNative(_handle, buffer, offset, count, completionSource.Overlapped, out errorCode); } // ReadFile, the OS version, will return 0 on failure, but this ReadFileNative wrapper // returns -1. This will return the following: // - On error, r==-1. // - On async requests that are still pending, r==-1 w/ hr==ERROR_IO_PENDING // - On async requests that completed sequentially, r==0 // // You will NEVER RELIABLY be able to get the number of buffer read back from this call // when using overlapped structures! You must not pass in a non-null lpNumBytesRead to // ReadFile when using overlapped structures! This is by design NT behavior. if (r == -1) { switch (errorCode) { // One side has closed its handle or server disconnected. // Set the state to Broken and do some cleanup work case Interop.mincore.Errors.ERROR_BROKEN_PIPE: case Interop.mincore.Errors.ERROR_PIPE_NOT_CONNECTED: State = PipeState.Broken; unsafe { // Clear the overlapped status bit for this special case. Failure to do so looks // like we are freeing a pending overlapped. completionSource.Overlapped->InternalLow = IntPtr.Zero; } completionSource.ReleaseResources(); UpdateMessageCompletion(true); return s_zeroTask; case Interop.mincore.Errors.ERROR_IO_PENDING: break; default: throw Win32Marshal.GetExceptionForWin32Error(errorCode); } } completionSource.RegisterForCancellation(); return completionSource.Task; } [SecurityCritical] private unsafe void WriteCore(byte[] buffer, int offset, int count) { int errorCode = 0; int r = WriteFileNative(_handle, buffer, offset, count, null, out errorCode); if (r == -1) { throw WinIOError(errorCode); } Debug.Assert(r >= 0, "PipeStream's WriteCore is likely broken."); } [SecuritySafeCritical] private Task WriteAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { var completionSource = new ReadWriteCompletionSource(this, buffer, cancellationToken, isWrite: true); int errorCode = 0; // Queue an async WriteFile operation and pass in a packed overlapped int r; unsafe { r = WriteFileNative(_handle, buffer, offset, count, completionSource.Overlapped, out errorCode); } // WriteFile, the OS version, will return 0 on failure, but this WriteFileNative // wrapper returns -1. This will return the following: // - On error, r==-1. // - On async requests that are still pending, r==-1 w/ hr==ERROR_IO_PENDING // - On async requests that completed sequentially, r==0 // // You will NEVER RELIABLY be able to get the number of buffer written back from this // call when using overlapped structures! You must not pass in a non-null // lpNumBytesWritten to WriteFile when using overlapped structures! This is by design // NT behavior. if (r == -1 && errorCode != Interop.mincore.Errors.ERROR_IO_PENDING) { completionSource.ReleaseResources(); throw WinIOError(errorCode); } completionSource.RegisterForCancellation(); return completionSource.Task; } // Blocks until the other end of the pipe has read in all written buffer. [SecurityCritical] public void WaitForPipeDrain() { CheckWriteOperations(); if (!CanWrite) { throw Error.GetWriteNotSupported(); } // Block until other end of the pipe has read everything. if (!Interop.mincore.FlushFileBuffers(_handle)) { throw WinIOError(Marshal.GetLastWin32Error()); } } // Gets the transmission mode for the pipe. This is virtual so that subclassing types can // override this in cases where only one mode is legal (such as anonymous pipes) public virtual PipeTransmissionMode TransmissionMode { [SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")] get { CheckPipePropertyOperations(); if (_isFromExistingHandle) { int pipeFlags; if (!Interop.mincore.GetNamedPipeInfo(_handle, out pipeFlags, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero)) { throw WinIOError(Marshal.GetLastWin32Error()); } if ((pipeFlags & Interop.mincore.PipeOptions.PIPE_TYPE_MESSAGE) != 0) { return PipeTransmissionMode.Message; } else { return PipeTransmissionMode.Byte; } } else { return _transmissionMode; } } } // Gets the buffer size in the inbound direction for the pipe. This checks if pipe has read // access. If that passes, call to GetNamedPipeInfo will succeed. public virtual int InBufferSize { [SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] get { CheckPipePropertyOperations(); if (!CanRead) { throw new NotSupportedException(SR.NotSupported_UnreadableStream); } int inBufferSize; if (!Interop.mincore.GetNamedPipeInfo(_handle, IntPtr.Zero, IntPtr.Zero, out inBufferSize, IntPtr.Zero)) { throw WinIOError(Marshal.GetLastWin32Error()); } return inBufferSize; } } // Gets the buffer size in the outbound direction for the pipe. This uses cached version // if it's an outbound only pipe because GetNamedPipeInfo requires read access to the pipe. // However, returning cached is good fallback, especially if user specified a value in // the ctor. public virtual int OutBufferSize { [SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")] get { CheckPipePropertyOperations(); if (!CanWrite) { throw new NotSupportedException(SR.NotSupported_UnwritableStream); } int outBufferSize; // Use cached value if direction is out; otherwise get fresh version if (_pipeDirection == PipeDirection.Out) { outBufferSize = _outBufferSize; } else if (!Interop.mincore.GetNamedPipeInfo(_handle, IntPtr.Zero, out outBufferSize, IntPtr.Zero, IntPtr.Zero)) { throw WinIOError(Marshal.GetLastWin32Error()); } return outBufferSize; } } public virtual PipeTransmissionMode ReadMode { [SecurityCritical] get { CheckPipePropertyOperations(); // get fresh value if it could be stale if (_isFromExistingHandle || IsHandleExposed) { UpdateReadMode(); } return _readMode; } [SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")] set { // Nothing fancy here. This is just a wrapper around the Win32 API. Note, that NamedPipeServerStream // and the AnonymousPipeStreams override this. CheckPipePropertyOperations(); if (value < PipeTransmissionMode.Byte || value > PipeTransmissionMode.Message) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_TransmissionModeByteOrMsg); } unsafe { int pipeReadType = (int)value << 1; if (!Interop.mincore.SetNamedPipeHandleState(_handle, &pipeReadType, IntPtr.Zero, IntPtr.Zero)) { throw WinIOError(Marshal.GetLastWin32Error()); } else { _readMode = value; } } } } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- [SecurityCritical] private unsafe int ReadFileNative(SafePipeHandle handle, byte[] buffer, int offset, int count, NativeOverlapped* overlapped, out int errorCode) { DebugAssertReadWriteArgs(buffer, offset, count, handle); Debug.Assert((_isAsync && overlapped != null) || (!_isAsync && overlapped == null), "Async IO parameter screwup in call to ReadFileNative."); // You can't use the fixed statement on an array of length 0. Note that async callers // check to avoid calling this first, so they can call user's callback if (buffer.Length == 0) { errorCode = 0; return 0; } int r = 0; int numBytesRead = 0; fixed (byte* p = buffer) { if (_isAsync) { r = Interop.mincore.ReadFile(handle, p + offset, count, IntPtr.Zero, overlapped); } else { r = Interop.mincore.ReadFile(handle, p + offset, count, out numBytesRead, IntPtr.Zero); } } if (r == 0) { errorCode = Marshal.GetLastWin32Error(); // In message mode, the ReadFile can inform us that there is more data to come. if (errorCode == Interop.mincore.Errors.ERROR_MORE_DATA) { return numBytesRead; } return -1; } else { errorCode = 0; } return numBytesRead; } [SecurityCritical] private unsafe int WriteFileNative(SafePipeHandle handle, byte[] buffer, int offset, int count, NativeOverlapped* overlapped, out int errorCode) { DebugAssertReadWriteArgs(buffer, offset, count, handle); Debug.Assert((_isAsync && overlapped != null) || (!_isAsync && overlapped == null), "Async IO parameter screwup in call to WriteFileNative."); // You can't use the fixed statement on an array of length 0. Note that async callers // check to avoid calling this first, so they can call user's callback if (buffer.Length == 0) { errorCode = 0; return 0; } int numBytesWritten = 0; int r = 0; fixed (byte* p = buffer) { if (_isAsync) { r = Interop.mincore.WriteFile(handle, p + offset, count, IntPtr.Zero, overlapped); } else { r = Interop.mincore.WriteFile(handle, p + offset, count, out numBytesWritten, IntPtr.Zero); } } if (r == 0) { errorCode = Marshal.GetLastWin32Error(); return -1; } else { errorCode = 0; } return numBytesWritten; } [SecurityCritical] internal unsafe static Interop.mincore.SECURITY_ATTRIBUTES GetSecAttrs(HandleInheritability inheritability) { Interop.mincore.SECURITY_ATTRIBUTES secAttrs = default(Interop.mincore.SECURITY_ATTRIBUTES); if ((inheritability & HandleInheritability.Inheritable) != 0) { secAttrs = new Interop.mincore.SECURITY_ATTRIBUTES(); secAttrs.nLength = (uint)sizeof(Interop.mincore.SECURITY_ATTRIBUTES); secAttrs.bInheritHandle = Interop.BOOL.TRUE; } return secAttrs; } /// <summary> /// Determine pipe read mode from Win32 /// </summary> [SecurityCritical] private void UpdateReadMode() { int flags; if (!Interop.mincore.GetNamedPipeHandleState(SafePipeHandle, out flags, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, 0)) { throw WinIOError(Marshal.GetLastWin32Error()); } if ((flags & Interop.mincore.PipeOptions.PIPE_READMODE_MESSAGE) != 0) { _readMode = PipeTransmissionMode.Message; } else { _readMode = PipeTransmissionMode.Byte; } } /// <summary> /// Filter out all pipe related errors and do some cleanup before calling Error.WinIOError. /// </summary> /// <param name="errorCode"></param> [SecurityCritical] internal Exception WinIOError(int errorCode) { switch (errorCode) { case Interop.mincore.Errors.ERROR_BROKEN_PIPE: case Interop.mincore.Errors.ERROR_PIPE_NOT_CONNECTED: case Interop.mincore.Errors.ERROR_NO_DATA: // Other side has broken the connection _state = PipeState.Broken; return new IOException(SR.IO_PipeBroken, Win32Marshal.MakeHRFromErrorCode(errorCode)); case Interop.mincore.Errors.ERROR_HANDLE_EOF: return Error.GetEndOfFile(); case Interop.mincore.Errors.ERROR_INVALID_HANDLE: // For invalid handles, detect the error and mark our handle // as invalid to give slightly better error messages. Also // help ensure we avoid handle recycling bugs. _handle.SetHandleAsInvalid(); _state = PipeState.Broken; break; } return Win32Marshal.GetExceptionForWin32Error(errorCode); } } }
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Infoplus.Model { /// <summary> /// /// </summary> [DataContract] public partial class ItemProductCode : IEquatable<ItemProductCode> { /// <summary> /// Initializes a new instance of the <see cref="ItemProductCode" /> class. /// Initializes a new instance of the <see cref="ItemProductCode" />class. /// </summary> /// <param name="LobId">LobId (required).</param> /// <param name="Id">Id (required).</param> /// <param name="Name">Name (required).</param> /// <param name="CustomFields">CustomFields.</param> public ItemProductCode(int? LobId = null, string Id = null, string Name = null, Dictionary<string, Object> CustomFields = null) { // to ensure "LobId" is required (not null) if (LobId == null) { throw new InvalidDataException("LobId is a required property for ItemProductCode and cannot be null"); } else { this.LobId = LobId; } // to ensure "Id" is required (not null) if (Id == null) { throw new InvalidDataException("Id is a required property for ItemProductCode and cannot be null"); } else { this.Id = Id; } // to ensure "Name" is required (not null) if (Name == null) { throw new InvalidDataException("Name is a required property for ItemProductCode and cannot be null"); } else { this.Name = Name; } this.CustomFields = CustomFields; } /// <summary> /// Gets or Sets LobId /// </summary> [DataMember(Name="lobId", EmitDefaultValue=false)] public int? LobId { get; set; } /// <summary> /// Gets or Sets InternalId /// </summary> [DataMember(Name="internalId", EmitDefaultValue=false)] public int? InternalId { get; private set; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public string Id { get; set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// Gets or Sets CustomFields /// </summary> [DataMember(Name="customFields", EmitDefaultValue=false)] public Dictionary<string, Object> CustomFields { 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 ItemProductCode {\n"); sb.Append(" LobId: ").Append(LobId).Append("\n"); sb.Append(" InternalId: ").Append(InternalId).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" CustomFields: ").Append(CustomFields).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 ItemProductCode); } /// <summary> /// Returns true if ItemProductCode instances are equal /// </summary> /// <param name="other">Instance of ItemProductCode to be compared</param> /// <returns>Boolean</returns> public bool Equals(ItemProductCode other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.LobId == other.LobId || this.LobId != null && this.LobId.Equals(other.LobId) ) && ( this.InternalId == other.InternalId || this.InternalId != null && this.InternalId.Equals(other.InternalId) ) && ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.CustomFields == other.CustomFields || this.CustomFields != null && this.CustomFields.SequenceEqual(other.CustomFields) ); } /// <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.LobId != null) hash = hash * 59 + this.LobId.GetHashCode(); if (this.InternalId != null) hash = hash * 59 + this.InternalId.GetHashCode(); if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.Name != null) hash = hash * 59 + this.Name.GetHashCode(); if (this.CustomFields != null) hash = hash * 59 + this.CustomFields.GetHashCode(); return hash; } } } }
#if UNITY_STANDALONE || UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX #define COHERENT_UNITY_STANDALONE #endif #if UNITY_NACL || UNITY_WEBPLAYER #define COHERENT_UNITY_UNSUPPORTED_PLATFORM #endif //#if UNITY_EDITOR && (UNITY_IPHONE || UNITY_ANDROID) //#define COHERENT_SIMULATE_MOBILE_IN_EDITOR //#endif using UnityEngine; using System.Collections.Generic; #if COHERENT_UNITY_STANDALONE || COHERENT_UNITY_UNSUPPORTED_PLATFORM namespace Coherent.UI #elif UNITY_IPHONE || UNITY_ANDROID namespace Coherent.UI.Mobile #endif { #if COHERENT_UNITY_STANDALONE || COHERENT_UNITY_UNSUPPORTED_PLATFORM public class UnityViewListener : BrowserViewListener #elif UNITY_IPHONE || UNITY_ANDROID public class UnityViewListener : ViewListener #endif { public UnityViewListener(CoherentUIView component, int width, int height) { m_ViewComponent = component; #if COHERENT_UNITY_STANDALONE m_Width = width; m_Height = height; #endif m_ObjectsToDestroy = new List<Object>(); HasModalDialogOpen = false; this.ViewCreated += new CoherentUI_OnViewCreated(OnViewCreatedHandler); if (component.ShowJavaScriptDialogs) { this.JavaScriptMessage += new CoherentUI_OnJavaScriptMessage(OnJavaScriptMessageHandler); #if COHERENT_UNITY_STANDALONE this.GetAuthCredentials += new CoherentUI_OnGetAuthCredentials(OnGetAuthCredentialsHandler); #endif } #if COHERENT_SIMULATE_MOBILE_IN_EDITOR || COHERENT_SIMULATE_MOBILE_IN_PLAYER this.ReadyForBindings += (frameId, path, isMainFrame) => { m_View.BindCall("__couiTouchEvent", (System.Action<int, int, int, int>)this.NewTouchEventHandler); }; #endif #if UNITY_ANDROID && !UNITY_EDITOR this.FailLoad += (frame, path, isMain, errorMsg) => { if (FailLoadSubscribersCount() > 1) { // The user is handling FailLoads return; } if (!path.StartsWith("coui")) { Debug.LogError("URL \"" + path + "\" failed loading!"); return; } if (m_View == null) { Debug.LogError("Coherent UI View is null inside " + "FailLoad handler for url \" + path +\"!"); return; } string escapedData = System.Uri.EscapeUriString( "<!DOCTYPE html>" + "<html lang=\"en\">" + "<head><title>Resource not available</title></head>" + "<body style=\"background-color: rgba(0, 0, 0, 0);" + "color: #e35;\">" + "<h1>Unable to find coui resource to be loaded!</h1>" + "<br/><br/>" + "<div style=\"font-size: 140%;\">" + "Please ensure that you didn't use 'Build & run' since " + "this function is not supported. Use 'Build' or an " + "Eclipse project instead." + "<br/><br/>" + "If you're building on a Mac, please also make sure that " + "the aapt executable in the <b>Assets/CoherentUI/Editor/" + "apktool-1.5.2</b> folder has executable permissions so " + "the repack step is successful." + "</div>" + "</body></html>"); m_View.Load("data:text/html;charset=utf-8," + escapedData); }; #endif } #if COHERENT_SIMULATE_MOBILE_IN_EDITOR || COHERENT_SIMULATE_MOBILE_IN_PLAYER private void NewTouchEventHandler(int id, int phase, int x, int y) { InputManager.ProcessTouchEvent(id, phase, x, y); } #endif public void OnViewCreatedHandler(View view) { m_View = view; #if COHERENT_UNITY_STANDALONE m_View.SetFocus(); var cameraComponent = m_ViewComponent.gameObject.camera; var id = m_View.GetId(); if(cameraComponent) { ViewRenderer = cameraComponent.gameObject.AddComponent("CoherentUIViewRenderer") as CoherentUIViewRenderer; // this is only supported for Views directly attached to cameras ViewRenderer.DrawAfterPostEffects = (m_ViewComponent.DrawAfterPostEffects == CoherentUIView.DrawOrder.AfterPostEffects); // make sure added components are destroyed too m_ObjectsToDestroy.Add(ViewRenderer); } else { var renderingCamera = new GameObject("CoherentRenderingCamera" + id); var newCameraComponent = renderingCamera.AddComponent("Camera") as Camera; newCameraComponent.clearFlags = CameraClearFlags.SolidColor; newCameraComponent.backgroundColor = new Color(0, 0, 0, 0); ViewRenderer = renderingCamera.AddComponent("CoherentUIViewRenderer") as CoherentUIViewRenderer; m_ObjectsToDestroy.Add(renderingCamera); RTTexture = new RenderTexture(m_Width, m_Height, 1, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default); m_ObjectsToDestroy.Add(RTTexture); RTTexture.name = "CoherentRenderingRTT" + id; newCameraComponent.targetTexture = RTTexture; newCameraComponent.cullingMask = 0; Shader shader = null; if(m_ViewComponent.IsIndependentOfZBuffer) { shader = Shader.Find(m_ViewComponent.IsTransparent ? "CoherentUI/TransparentDiffuseIgnoreZ" : "CoherentUI/DiffuseIgnoreZ"); } else { shader = Shader.Find(m_ViewComponent.IsTransparent ? "Transparent/Diffuse" : "Diffuse"); } if (shader == null) { throw new System.ApplicationException("Unable to find shader for generated material!"); } var RTMaterial = new Material(shader); m_ObjectsToDestroy.Add(RTMaterial); RTMaterial.mainTexture = RTTexture; RTMaterial.name = "CoherentMaterialRTT" + id; m_ViewComponent.gameObject.renderer.material = RTMaterial; renderingCamera.transform.parent = m_ViewComponent.gameObject.transform; } ViewRenderer.ViewId = (short)id; var flipY = m_ViewComponent.FlipY; ViewRenderer.FlipY = m_ViewComponent.ForceInvertY() ? !flipY : flipY; ViewRenderer.ShouldCorrectGamma = m_ViewComponent.CorrectGamma; ViewRenderer.FilteringMode = m_ViewComponent.Filtering; #endif } public void ResizeTexture(int width, int height) { #if COHERENT_UNITY_STANDALONE GameObject viewCamObject = GameObject.Find("Main Camera"); Camera secondCamera = null; if (viewCamObject == null) { if (Camera.main != null) { viewCamObject = Camera.main.gameObject; } if (viewCamObject == null) { secondCamera = GameObject.FindObjectOfType(typeof(Camera)) as Camera; } if (viewCamObject == null && !secondCamera) { return; } } Camera viewCamComponent = null; CameraClearFlags clearFlags = CameraClearFlags.Skybox; if(viewCamObject != null || secondCamera) { viewCamComponent = viewCamObject ? viewCamObject.GetComponent<Camera>() : secondCamera; //Cache the current clear flags of the main camera and set //them to Nothing. This will prevent visual artifacts //when the render texutre is changed. clearFlags = viewCamComponent.clearFlags; viewCamComponent.clearFlags = CameraClearFlags.Nothing; } else { //Unable to find camera, abort the resizing return; } m_ObjectsToDestroy.Remove(RTTexture); RTTexture.Release(); var id = m_View.GetId(); var renderingCamera = GameObject.Find("CoherentRenderingCamera" + id); var camComponent = renderingCamera.GetComponent("Camera") as Camera; RTTexture = new RenderTexture(width, height, 1, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default); RTTexture.name = "CoherentRenderingRTT" + id; RTTexture.Create(); m_ObjectsToDestroy.Add(RTTexture); camComponent.targetTexture = RTTexture; m_ViewComponent.gameObject.renderer.material.mainTexture = RTTexture; //Restore the previously cached clear flags viewCamComponent.clearFlags = clearFlags; #endif } public void OnJavaScriptMessageHandler(string message, string defaultPrompt, string frameUrl, int messageType) { if (HasModalDialogOpen) { Debug.Log (m_ViewComponent.name + " trying to open a javascript message dialog while having another dialog open!"); return; } ++s_InternalDialogId; HasModalDialogOpen = true; var gameObject = new GameObject("CoherentUIJavaScriptMessage_" + s_InternalDialogId + "_" + frameUrl); var dialogComponent = gameObject.AddComponent("CoherentUIDialog") as CoherentUIDialog; dialogComponent.m_ViewListener = this; switch (messageType) { case 0: dialogComponent.m_Type = CoherentUIDialog.DialogType.Alert; dialogComponent.AlertMessage = message; break; case 1: dialogComponent.m_Type = CoherentUIDialog.DialogType.Confirm; dialogComponent.ConfirmMessage = message; break; case 2: dialogComponent.m_Type = CoherentUIDialog.DialogType.Prompt; dialogComponent.PromptMessage = message; dialogComponent.PromptReply = defaultPrompt; break; } } public void OnGetAuthCredentialsHandler(bool isProxy, string host, uint port, string realm, string scheme) { #if COHERENT_UNITY_STANDALONE // Do not show the auth dialog is the user is handling the authentication too if(base.AuthSubscribersCount() > 1) return; #endif ShowAuthCredentialsDialog(isProxy, host, port, realm, scheme); } public void ShowAuthCredentialsDialog(bool isProxy, string host, uint port, string realm, string scheme) { if (HasModalDialogOpen) { Debug.Log (m_ViewComponent.name + " trying to open an authentication dialog while having another dialog open!"); return; } ++s_InternalDialogId; HasModalDialogOpen = true; var gameObject = new GameObject("CoherentUIGetAuthCredentials_" + s_InternalDialogId + "_" + host); var dialogComponent = gameObject.AddComponent("CoherentUIDialog") as CoherentUIDialog; dialogComponent.m_ViewListener = this; dialogComponent.m_Type = CoherentUIDialog.DialogType.Authentication; dialogComponent.AuthenticationMessage = "The server " + host + ":" + port + " requires a username and password. The server says: " + realm; } public void Destroy() { if (m_View != null) { m_View.Destroy(); foreach(var o in m_ObjectsToDestroy) { Object.Destroy(o); } m_ObjectsToDestroy.Clear(); RTTexture = null; } } public override void Release() { base.Release(); Dispose(); } public View View { get { return m_View; } } internal CoherentUIView ViewComponent { get { return m_ViewComponent; } } private View m_View; private CoherentUIView m_ViewComponent; #if COHERENT_UNITY_STANDALONE private int m_Width; private int m_Height; #endif private List<Object> m_ObjectsToDestroy; internal CoherentUIViewRenderer ViewRenderer; internal RenderTexture RTTexture; internal bool HasModalDialogOpen; private static int s_InternalDialogId = 0; } }
//! \file ArcBIN.cs //! \date Thu Jul 21 21:10:31 2016 //! \brief Patisserie resource archive. // // Copyright (C) 2016 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.IO; using System.Linq; using GameRes.Compression; namespace GameRes.Formats.Patisserie { [Export(typeof(ArchiveFormat))] public class BinOpener : ArchiveFormat { public override string Tag { get { return "BIN/OZ"; } } public override string Description { get { return "Patisserie resource archive"; } } public override uint Signature { get { return 0x01005A4F; } } // 'OZ' public override bool IsHierarchic { get { return false; } } public override bool CanWrite { get { return false; } } public BinOpener () { Extensions = new string[] { "bin" }; } public override ArcFile TryOpen (ArcView file) { if (!file.View.AsciiEqual (4, "OFST")) return null; int index_size = file.View.ReadInt32 (8); int count = index_size / 4; if (!IsSaneCount (count)) return null; var base_name = Path.GetFileNameWithoutExtension (file.Name); string content_ext = "", content_type = ""; if (base_name.EndsWith ("flac", StringComparison.OrdinalIgnoreCase)) { content_ext = "flac"; content_type = "audio"; base_name = base_name.Substring (0, base_name.Length-4); } else if (base_name.EndsWith ("ogg", StringComparison.OrdinalIgnoreCase)) { content_ext = "ogg"; content_type = "audio"; base_name = base_name.Substring (0, base_name.Length-3); } var filenames = GetFileNames (file.Name); if (null == filenames) filenames = new List<string> (count); for (int i = filenames.Count; i < count; ++i) filenames.Add (string.Format ("{0}#{1:D5}", base_name, i)); uint index_offset = 0xC; var dir = new List<Entry> (count); uint next_offset = file.View.ReadUInt32 (index_offset); for (int i = 0; i < count; ++i) { index_offset += 4; var entry = new PackedEntry { Name = filenames[i] }; entry.Offset = next_offset; next_offset = i+1 < count ? file.View.ReadUInt32 (index_offset) : (uint)file.MaxOffset; entry.Size = next_offset - (uint)entry.Offset; if (entry.Size > 0 && !entry.CheckPlacement (file.MaxOffset)) return null; if (!string.IsNullOrEmpty (content_type)) { entry.Type = content_type; entry.Name = Path.ChangeExtension (entry.Name, content_ext); } dir.Add (entry); } foreach (PackedEntry entry in dir.Where (e => e.Size > 4)) { entry.IsPacked = file.View.AsciiEqual (entry.Offset, "DFLT"); if (entry.IsPacked) { entry.Size = file.View.ReadUInt32 (entry.Offset+4); entry.UnpackedSize = file.View.ReadUInt32 (entry.Offset+8); entry.Offset += 12; } else if (file.View.AsciiEqual (entry.Offset, "DATA")) { entry.Size = file.View.ReadUInt32 (entry.Offset+4); entry.UnpackedSize = entry.Size; entry.Offset += 8; if (string.IsNullOrEmpty (entry.Type)) { uint signature = file.View.ReadUInt32 (entry.Offset); if (0x43614C66 == signature) // 'fLaC' { entry.Type = "audio"; entry.Name = Path.ChangeExtension (entry.Name, "flac"); } else { var res = AutoEntry.DetectFileType (signature); if (null != res) entry.ChangeType (res); } } } } return new ArcFile (file, this, dir); } public override Stream OpenEntry (ArcFile arc, Entry entry) { var input = arc.File.CreateStream (entry.Offset, entry.Size); var pent = entry as PackedEntry; if (null == pent || !pent.IsPacked) return input; return new ZLibStream (input, CompressionMode.Decompress); } IList<string> ReadListFile (string lst_name) { return File.ReadAllLines (lst_name, Encodings.cp932); } IList<string> GetFileNames (string arc_name) { var dir_name = VFS.GetDirectoryName (arc_name); var lst_name = Path.ChangeExtension (arc_name, ".lst"); if (VFS.FileExists (lst_name)) return ReadListFile (lst_name); var lists_lst_name = VFS.CombinePath (dir_name, "lists.lst"); if (!VFS.FileExists (lists_lst_name)) return null; var base_name = Path.GetFileNameWithoutExtension (arc_name); var arcs = ReadListFile (lists_lst_name); var arc_no = arcs.IndexOf (base_name); if (-1 == arc_no) return null; var lists_bin_name = VFS.CombinePath (dir_name, "lists.bin"); using (var lists_bin = VFS.OpenView (lists_bin_name)) return ReadFileNames (lists_bin, arc_no); } IList<string> ReadFileNames (ArcView index, int arc_no) { if (index.View.ReadUInt32 (0) != Signature) return null; if (!index.View.AsciiEqual (4, "OFST")) return null; int index_size = index.View.ReadInt32 (8); int arc_count = index_size / 4; if (arc_no >= arc_count) return null; uint index_offset = index.View.ReadUInt32 (0xC + arc_no * 4); if (index_offset >= index.MaxOffset) return null; Stream input; if (index.View.AsciiEqual (index_offset, "DFLT")) { uint packed_size = index.View.ReadUInt32 (index_offset+4); input = index.CreateStream (index_offset+12, packed_size); input = new ZLibStream (input, CompressionMode.Decompress); } else if (index.View.AsciiEqual (index_offset, "DATA")) { uint data_size = index.View.ReadUInt32 (index_offset+4); input = index.CreateStream (index_offset+8, data_size); } else return null; using (input) using (var reader = new StreamReader (input, Encodings.cp932)) { var list = new List<string>(); string line; while ((line = reader.ReadLine()) != null) list.Add (line.Trim()); return list; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace HookFromGeorge.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// 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 Internal.Cryptography; using Internal.Cryptography.Pal; using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Globalization; using System.Runtime.Serialization; using System.Text; namespace System.Security.Cryptography.X509Certificates { public class X509Certificate : IDisposable, IDeserializationCallback, ISerializable { private volatile byte[] _lazyCertHash; private volatile string _lazyIssuer; private volatile string _lazySubject; private volatile byte[] _lazySerialNumber; private volatile string _lazyKeyAlgorithm; private volatile byte[] _lazyKeyAlgorithmParameters; private volatile byte[] _lazyPublicKey; private DateTime _lazyNotBefore = DateTime.MinValue; private DateTime _lazyNotAfter = DateTime.MinValue; public virtual void Reset() { _lazyCertHash = null; _lazyIssuer = null; _lazySubject = null; _lazySerialNumber = null; _lazyKeyAlgorithm = null; _lazyKeyAlgorithmParameters = null; _lazyPublicKey = null; _lazyNotBefore = DateTime.MinValue; _lazyNotAfter = DateTime.MinValue; ICertificatePalCore pal = Pal; if (pal != null) { Pal = null; pal.Dispose(); } } public X509Certificate() { } public X509Certificate(byte[] data) { if (data != null && data.Length != 0) { // For compat reasons, this constructor treats passing a null or empty data set as the same as calling the nullary constructor. using (var safePasswordHandle = new SafePasswordHandle((string)null)) { Pal = CertificatePal.FromBlob(data, safePasswordHandle, X509KeyStorageFlags.DefaultKeySet); } } } public X509Certificate(byte[] rawData, string password) : this(rawData, password, X509KeyStorageFlags.DefaultKeySet) { } [System.CLSCompliantAttribute(false)] public X509Certificate(byte[] rawData, SecureString password) : this(rawData, password, X509KeyStorageFlags.DefaultKeySet) { } public X509Certificate(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) { if (rawData == null || rawData.Length == 0) throw new ArgumentException(SR.Arg_EmptyOrNullArray, nameof(rawData)); ValidateKeyStorageFlags(keyStorageFlags); using (var safePasswordHandle = new SafePasswordHandle(password)) { Pal = CertificatePal.FromBlob(rawData, safePasswordHandle, keyStorageFlags); } } [System.CLSCompliantAttribute(false)] public X509Certificate(byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags) { if (rawData == null || rawData.Length == 0) throw new ArgumentException(SR.Arg_EmptyOrNullArray, nameof(rawData)); ValidateKeyStorageFlags(keyStorageFlags); using (var safePasswordHandle = new SafePasswordHandle(password)) { Pal = CertificatePal.FromBlob(rawData, safePasswordHandle, keyStorageFlags); } } public X509Certificate(IntPtr handle) { Pal = CertificatePal.FromHandle(handle); } internal X509Certificate(ICertificatePalCore pal) { Debug.Assert(pal != null); Pal = pal; } public X509Certificate(string fileName) : this(fileName, (string)null, X509KeyStorageFlags.DefaultKeySet) { } public X509Certificate(string fileName, string password) : this(fileName, password, X509KeyStorageFlags.DefaultKeySet) { } [System.CLSCompliantAttribute(false)] public X509Certificate(string fileName, SecureString password) : this(fileName, password, X509KeyStorageFlags.DefaultKeySet) { } public X509Certificate(string fileName, string password, X509KeyStorageFlags keyStorageFlags) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); ValidateKeyStorageFlags(keyStorageFlags); using (var safePasswordHandle = new SafePasswordHandle(password)) { Pal = CertificatePal.FromFile(fileName, safePasswordHandle, keyStorageFlags); } } [System.CLSCompliantAttribute(false)] public X509Certificate(string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags) : this() { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); ValidateKeyStorageFlags(keyStorageFlags); using (var safePasswordHandle = new SafePasswordHandle(password)) { Pal = CertificatePal.FromFile(fileName, safePasswordHandle, keyStorageFlags); } } public X509Certificate(X509Certificate cert) { if (cert == null) throw new ArgumentNullException(nameof(cert)); if (cert.Pal != null) { Pal = CertificatePal.FromOtherCert(cert); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2229", Justification = "Public API has already shipped.")] public X509Certificate(SerializationInfo info, StreamingContext context) : this() { throw new PlatformNotSupportedException(); } public static X509Certificate CreateFromCertFile(string filename) { return new X509Certificate(filename); } public static X509Certificate CreateFromSignedFile(string filename) { return new X509Certificate(filename); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } void IDeserializationCallback.OnDeserialization(object sender) { throw new PlatformNotSupportedException(); } public IntPtr Handle { get { if (Pal == null) return IntPtr.Zero; else return Pal.Handle; } } public string Issuer { get { ThrowIfInvalid(); string issuer = _lazyIssuer; if (issuer == null) issuer = _lazyIssuer = Pal.Issuer; return issuer; } } public string Subject { get { ThrowIfInvalid(); string subject = _lazySubject; if (subject == null) subject = _lazySubject = Pal.Subject; return subject; } } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { Reset(); } } public override bool Equals(object obj) { X509Certificate other = obj as X509Certificate; if (other == null) return false; return Equals(other); } public virtual bool Equals(X509Certificate other) { if (other == null) return false; if (Pal == null) return other.Pal == null; if (!Issuer.Equals(other.Issuer)) return false; byte[] thisSerialNumber = GetRawSerialNumber(); byte[] otherSerialNumber = other.GetRawSerialNumber(); if (thisSerialNumber.Length != otherSerialNumber.Length) return false; for (int i = 0; i < thisSerialNumber.Length; i++) { if (thisSerialNumber[i] != otherSerialNumber[i]) return false; } return true; } public virtual byte[] Export(X509ContentType contentType) { return Export(contentType, (string)null); } public virtual byte[] Export(X509ContentType contentType, string password) { VerifyContentType(contentType); if (Pal == null) throw new CryptographicException(ErrorCode.E_POINTER); // Not the greatest error, but needed for backward compat. using (var safePasswordHandle = new SafePasswordHandle(password)) { return Pal.Export(contentType, safePasswordHandle); } } [System.CLSCompliantAttribute(false)] public virtual byte[] Export(X509ContentType contentType, SecureString password) { VerifyContentType(contentType); if (Pal == null) throw new CryptographicException(ErrorCode.E_POINTER); // Not the greatest error, but needed for backward compat. using (var safePasswordHandle = new SafePasswordHandle(password)) { return Pal.Export(contentType, safePasswordHandle); } } public virtual string GetRawCertDataString() { ThrowIfInvalid(); return GetRawCertData().ToHexStringUpper(); } public virtual byte[] GetCertHash() { ThrowIfInvalid(); return GetRawCertHash().CloneByteArray(); } public virtual byte[] GetCertHash(HashAlgorithmName hashAlgorithm) { ThrowIfInvalid(); using (IncrementalHash hasher = IncrementalHash.CreateHash(hashAlgorithm)) { hasher.AppendData(Pal.RawData); return hasher.GetHashAndReset(); } } public virtual bool TryGetCertHash( HashAlgorithmName hashAlgorithm, Span<byte> destination, out int bytesWritten) { ThrowIfInvalid(); using (IncrementalHash hasher = IncrementalHash.CreateHash(hashAlgorithm)) { hasher.AppendData(Pal.RawData); return hasher.TryGetHashAndReset(destination, out bytesWritten); } } public virtual string GetCertHashString() { ThrowIfInvalid(); return GetRawCertHash().ToHexStringUpper(); } public virtual string GetCertHashString(HashAlgorithmName hashAlgorithm) { ThrowIfInvalid(); return GetCertHash(hashAlgorithm).ToHexStringUpper(); } // Only use for internal purposes when the returned byte[] will not be mutated private byte[] GetRawCertHash() { return _lazyCertHash ?? (_lazyCertHash = Pal.Thumbprint); } public virtual string GetEffectiveDateString() { return GetNotBefore().ToString(); } public virtual string GetExpirationDateString() { return GetNotAfter().ToString(); } public virtual string GetFormat() { return "X509"; } public virtual string GetPublicKeyString() { return GetPublicKey().ToHexStringUpper(); } public virtual byte[] GetRawCertData() { ThrowIfInvalid(); return Pal.RawData.CloneByteArray(); } public override int GetHashCode() { if (Pal == null) return 0; byte[] thumbPrint = GetRawCertHash(); int value = 0; for (int i = 0; i < thumbPrint.Length && i < 4; ++i) { value = value << 8 | thumbPrint[i]; } return value; } public virtual string GetKeyAlgorithm() { ThrowIfInvalid(); string keyAlgorithm = _lazyKeyAlgorithm; if (keyAlgorithm == null) keyAlgorithm = _lazyKeyAlgorithm = Pal.KeyAlgorithm; return keyAlgorithm; } public virtual byte[] GetKeyAlgorithmParameters() { ThrowIfInvalid(); byte[] keyAlgorithmParameters = _lazyKeyAlgorithmParameters; if (keyAlgorithmParameters == null) keyAlgorithmParameters = _lazyKeyAlgorithmParameters = Pal.KeyAlgorithmParameters; return keyAlgorithmParameters.CloneByteArray(); } public virtual string GetKeyAlgorithmParametersString() { ThrowIfInvalid(); byte[] keyAlgorithmParameters = GetKeyAlgorithmParameters(); return keyAlgorithmParameters.ToHexStringUpper(); } public virtual byte[] GetPublicKey() { ThrowIfInvalid(); byte[] publicKey = _lazyPublicKey; if (publicKey == null) publicKey = _lazyPublicKey = Pal.PublicKeyValue; return publicKey.CloneByteArray(); } public virtual byte[] GetSerialNumber() { ThrowIfInvalid(); byte[] serialNumber = GetRawSerialNumber().CloneByteArray(); // PAL always returns big-endian, GetSerialNumber returns little-endian Array.Reverse(serialNumber); return serialNumber; } public virtual string GetSerialNumberString() { ThrowIfInvalid(); // PAL always returns big-endian, GetSerialNumberString returns big-endian too return GetRawSerialNumber().ToHexStringUpper(); } // Only use for internal purposes when the returned byte[] will not be mutated private byte[] GetRawSerialNumber() { return _lazySerialNumber ?? (_lazySerialNumber = Pal.SerialNumber); } [Obsolete("This method has been deprecated. Please use the Subject property instead. https://go.microsoft.com/fwlink/?linkid=14202")] public virtual string GetName() { ThrowIfInvalid(); return Pal.LegacySubject; } [Obsolete("This method has been deprecated. Please use the Issuer property instead. https://go.microsoft.com/fwlink/?linkid=14202")] public virtual string GetIssuerName() { ThrowIfInvalid(); return Pal.LegacyIssuer; } public override string ToString() { return ToString(fVerbose: false); } public virtual string ToString(bool fVerbose) { if (fVerbose == false || Pal == null) return GetType().ToString(); StringBuilder sb = new StringBuilder(); // Subject sb.AppendLine("[Subject]"); sb.Append(" "); sb.AppendLine(Subject); // Issuer sb.AppendLine(); sb.AppendLine("[Issuer]"); sb.Append(" "); sb.AppendLine(Issuer); // Serial Number sb.AppendLine(); sb.AppendLine("[Serial Number]"); sb.Append(" "); byte[] serialNumber = GetSerialNumber(); Array.Reverse(serialNumber); sb.Append(serialNumber.ToHexArrayUpper()); sb.AppendLine(); // NotBefore sb.AppendLine(); sb.AppendLine("[Not Before]"); sb.Append(" "); sb.AppendLine(FormatDate(GetNotBefore())); // NotAfter sb.AppendLine(); sb.AppendLine("[Not After]"); sb.Append(" "); sb.AppendLine(FormatDate(GetNotAfter())); // Thumbprint sb.AppendLine(); sb.AppendLine("[Thumbprint]"); sb.Append(" "); sb.Append(GetRawCertHash().ToHexArrayUpper()); sb.AppendLine(); return sb.ToString(); } public virtual void Import(byte[] rawData) { throw new PlatformNotSupportedException(SR.NotSupported_ImmutableX509Certificate); } public virtual void Import(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) { throw new PlatformNotSupportedException(SR.NotSupported_ImmutableX509Certificate); } [System.CLSCompliantAttribute(false)] public virtual void Import(byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags) { throw new PlatformNotSupportedException(SR.NotSupported_ImmutableX509Certificate); } public virtual void Import(string fileName) { throw new PlatformNotSupportedException(SR.NotSupported_ImmutableX509Certificate); } public virtual void Import(string fileName, string password, X509KeyStorageFlags keyStorageFlags) { throw new PlatformNotSupportedException(SR.NotSupported_ImmutableX509Certificate); } [System.CLSCompliantAttribute(false)] public virtual void Import(string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags) { throw new PlatformNotSupportedException(SR.NotSupported_ImmutableX509Certificate); } internal ICertificatePalCore Pal { get; private set; } internal DateTime GetNotAfter() { ThrowIfInvalid(); DateTime notAfter = _lazyNotAfter; if (notAfter == DateTime.MinValue) notAfter = _lazyNotAfter = Pal.NotAfter; return notAfter; } internal DateTime GetNotBefore() { ThrowIfInvalid(); DateTime notBefore = _lazyNotBefore; if (notBefore == DateTime.MinValue) notBefore = _lazyNotBefore = Pal.NotBefore; return notBefore; } internal void ThrowIfInvalid() { if (Pal == null) throw new CryptographicException(SR.Format(SR.Cryptography_InvalidHandle, "m_safeCertContext")); // Keeping "m_safeCertContext" string for backward compat sake. } /// <summary> /// Convert a date to a string. /// /// Some cultures, specifically using the Um-AlQura calendar cannot convert dates far into /// the future into strings. If the expiration date of an X.509 certificate is beyond the range /// of one of these cases, we need to fall back to a calendar which can express the dates /// </summary> protected static string FormatDate(DateTime date) { CultureInfo culture = CultureInfo.CurrentCulture; if (!culture.DateTimeFormat.Calendar.IsValidDay(date.Year, date.Month, date.Day, 0)) { // The most common case of culture failing to work is in the Um-AlQuara calendar. In this case, // we can fall back to the Hijri calendar, otherwise fall back to the invariant culture. if (culture.DateTimeFormat.Calendar is UmAlQuraCalendar) { culture = culture.Clone() as CultureInfo; culture.DateTimeFormat.Calendar = new HijriCalendar(); } else { culture = CultureInfo.InvariantCulture; } } return date.ToString(culture); } internal static void ValidateKeyStorageFlags(X509KeyStorageFlags keyStorageFlags) { if ((keyStorageFlags & ~KeyStorageFlagsAll) != 0) throw new ArgumentException(SR.Argument_InvalidFlag, nameof(keyStorageFlags)); const X509KeyStorageFlags EphemeralPersist = X509KeyStorageFlags.EphemeralKeySet | X509KeyStorageFlags.PersistKeySet; X509KeyStorageFlags persistenceFlags = keyStorageFlags & EphemeralPersist; if (persistenceFlags == EphemeralPersist) { throw new ArgumentException( SR.Format(SR.Cryptography_X509_InvalidFlagCombination, persistenceFlags), nameof(keyStorageFlags)); } } private void VerifyContentType(X509ContentType contentType) { if (!(contentType == X509ContentType.Cert || contentType == X509ContentType.SerializedCert || contentType == X509ContentType.Pkcs12)) throw new CryptographicException(SR.Cryptography_X509_InvalidContentType); } internal const X509KeyStorageFlags KeyStorageFlagsAll = X509KeyStorageFlags.UserKeySet | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.UserProtected | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.EphemeralKeySet; } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using HTTPApp.Areas.HelpPage.Models; namespace HTTPApp.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
/* * OANDA v20 REST API * * The full OANDA v20 REST API Specification. This specification defines how to interact with v20 Accounts, Trades, Orders, Pricing and more. * * OpenAPI spec version: 3.0.15 * Contact: api@oanda.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 Oanda.RestV20.Model { /// <summary> /// A ResetResettablePLTransaction represents the resetting of the Account&#39;s resettable PL counters. /// </summary> [DataContract] public partial class ResetResettablePLTransaction : IEquatable<ResetResettablePLTransaction>, IValidatableObject { /// <summary> /// The Type of the Transaction. Always set to \"RESET_RESETTABLE_PL\" for a ResetResettablePLTransaction. /// </summary> /// <value>The Type of the Transaction. Always set to \"RESET_RESETTABLE_PL\" for a ResetResettablePLTransaction.</value> [JsonConverter(typeof(StringEnumConverter))] public enum TypeEnum { /// <summary> /// Enum CREATE for "CREATE" /// </summary> [EnumMember(Value = "CREATE")] CREATE, /// <summary> /// Enum CLOSE for "CLOSE" /// </summary> [EnumMember(Value = "CLOSE")] CLOSE, /// <summary> /// Enum REOPEN for "REOPEN" /// </summary> [EnumMember(Value = "REOPEN")] REOPEN, /// <summary> /// Enum CLIENTCONFIGURE for "CLIENT_CONFIGURE" /// </summary> [EnumMember(Value = "CLIENT_CONFIGURE")] CLIENTCONFIGURE, /// <summary> /// Enum CLIENTCONFIGUREREJECT for "CLIENT_CONFIGURE_REJECT" /// </summary> [EnumMember(Value = "CLIENT_CONFIGURE_REJECT")] CLIENTCONFIGUREREJECT, /// <summary> /// Enum TRANSFERFUNDS for "TRANSFER_FUNDS" /// </summary> [EnumMember(Value = "TRANSFER_FUNDS")] TRANSFERFUNDS, /// <summary> /// Enum TRANSFERFUNDSREJECT for "TRANSFER_FUNDS_REJECT" /// </summary> [EnumMember(Value = "TRANSFER_FUNDS_REJECT")] TRANSFERFUNDSREJECT, /// <summary> /// Enum MARKETORDER for "MARKET_ORDER" /// </summary> [EnumMember(Value = "MARKET_ORDER")] MARKETORDER, /// <summary> /// Enum MARKETORDERREJECT for "MARKET_ORDER_REJECT" /// </summary> [EnumMember(Value = "MARKET_ORDER_REJECT")] MARKETORDERREJECT, /// <summary> /// Enum LIMITORDER for "LIMIT_ORDER" /// </summary> [EnumMember(Value = "LIMIT_ORDER")] LIMITORDER, /// <summary> /// Enum LIMITORDERREJECT for "LIMIT_ORDER_REJECT" /// </summary> [EnumMember(Value = "LIMIT_ORDER_REJECT")] LIMITORDERREJECT, /// <summary> /// Enum STOPORDER for "STOP_ORDER" /// </summary> [EnumMember(Value = "STOP_ORDER")] STOPORDER, /// <summary> /// Enum STOPORDERREJECT for "STOP_ORDER_REJECT" /// </summary> [EnumMember(Value = "STOP_ORDER_REJECT")] STOPORDERREJECT, /// <summary> /// Enum MARKETIFTOUCHEDORDER for "MARKET_IF_TOUCHED_ORDER" /// </summary> [EnumMember(Value = "MARKET_IF_TOUCHED_ORDER")] MARKETIFTOUCHEDORDER, /// <summary> /// Enum MARKETIFTOUCHEDORDERREJECT for "MARKET_IF_TOUCHED_ORDER_REJECT" /// </summary> [EnumMember(Value = "MARKET_IF_TOUCHED_ORDER_REJECT")] MARKETIFTOUCHEDORDERREJECT, /// <summary> /// Enum TAKEPROFITORDER for "TAKE_PROFIT_ORDER" /// </summary> [EnumMember(Value = "TAKE_PROFIT_ORDER")] TAKEPROFITORDER, /// <summary> /// Enum TAKEPROFITORDERREJECT for "TAKE_PROFIT_ORDER_REJECT" /// </summary> [EnumMember(Value = "TAKE_PROFIT_ORDER_REJECT")] TAKEPROFITORDERREJECT, /// <summary> /// Enum STOPLOSSORDER for "STOP_LOSS_ORDER" /// </summary> [EnumMember(Value = "STOP_LOSS_ORDER")] STOPLOSSORDER, /// <summary> /// Enum STOPLOSSORDERREJECT for "STOP_LOSS_ORDER_REJECT" /// </summary> [EnumMember(Value = "STOP_LOSS_ORDER_REJECT")] STOPLOSSORDERREJECT, /// <summary> /// Enum TRAILINGSTOPLOSSORDER for "TRAILING_STOP_LOSS_ORDER" /// </summary> [EnumMember(Value = "TRAILING_STOP_LOSS_ORDER")] TRAILINGSTOPLOSSORDER, /// <summary> /// Enum TRAILINGSTOPLOSSORDERREJECT for "TRAILING_STOP_LOSS_ORDER_REJECT" /// </summary> [EnumMember(Value = "TRAILING_STOP_LOSS_ORDER_REJECT")] TRAILINGSTOPLOSSORDERREJECT, /// <summary> /// Enum ORDERFILL for "ORDER_FILL" /// </summary> [EnumMember(Value = "ORDER_FILL")] ORDERFILL, /// <summary> /// Enum ORDERCANCEL for "ORDER_CANCEL" /// </summary> [EnumMember(Value = "ORDER_CANCEL")] ORDERCANCEL, /// <summary> /// Enum ORDERCANCELREJECT for "ORDER_CANCEL_REJECT" /// </summary> [EnumMember(Value = "ORDER_CANCEL_REJECT")] ORDERCANCELREJECT, /// <summary> /// Enum ORDERCLIENTEXTENSIONSMODIFY for "ORDER_CLIENT_EXTENSIONS_MODIFY" /// </summary> [EnumMember(Value = "ORDER_CLIENT_EXTENSIONS_MODIFY")] ORDERCLIENTEXTENSIONSMODIFY, /// <summary> /// Enum ORDERCLIENTEXTENSIONSMODIFYREJECT for "ORDER_CLIENT_EXTENSIONS_MODIFY_REJECT" /// </summary> [EnumMember(Value = "ORDER_CLIENT_EXTENSIONS_MODIFY_REJECT")] ORDERCLIENTEXTENSIONSMODIFYREJECT, /// <summary> /// Enum TRADECLIENTEXTENSIONSMODIFY for "TRADE_CLIENT_EXTENSIONS_MODIFY" /// </summary> [EnumMember(Value = "TRADE_CLIENT_EXTENSIONS_MODIFY")] TRADECLIENTEXTENSIONSMODIFY, /// <summary> /// Enum TRADECLIENTEXTENSIONSMODIFYREJECT for "TRADE_CLIENT_EXTENSIONS_MODIFY_REJECT" /// </summary> [EnumMember(Value = "TRADE_CLIENT_EXTENSIONS_MODIFY_REJECT")] TRADECLIENTEXTENSIONSMODIFYREJECT, /// <summary> /// Enum MARGINCALLENTER for "MARGIN_CALL_ENTER" /// </summary> [EnumMember(Value = "MARGIN_CALL_ENTER")] MARGINCALLENTER, /// <summary> /// Enum MARGINCALLEXTEND for "MARGIN_CALL_EXTEND" /// </summary> [EnumMember(Value = "MARGIN_CALL_EXTEND")] MARGINCALLEXTEND, /// <summary> /// Enum MARGINCALLEXIT for "MARGIN_CALL_EXIT" /// </summary> [EnumMember(Value = "MARGIN_CALL_EXIT")] MARGINCALLEXIT, /// <summary> /// Enum DELAYEDTRADECLOSURE for "DELAYED_TRADE_CLOSURE" /// </summary> [EnumMember(Value = "DELAYED_TRADE_CLOSURE")] DELAYEDTRADECLOSURE, /// <summary> /// Enum DAILYFINANCING for "DAILY_FINANCING" /// </summary> [EnumMember(Value = "DAILY_FINANCING")] DAILYFINANCING, /// <summary> /// Enum RESETRESETTABLEPL for "RESET_RESETTABLE_PL" /// </summary> [EnumMember(Value = "RESET_RESETTABLE_PL")] RESETRESETTABLEPL } /// <summary> /// The Type of the Transaction. Always set to \"RESET_RESETTABLE_PL\" for a ResetResettablePLTransaction. /// </summary> /// <value>The Type of the Transaction. Always set to \"RESET_RESETTABLE_PL\" for a ResetResettablePLTransaction.</value> [DataMember(Name="type", EmitDefaultValue=false)] public TypeEnum? Type { get; set; } /// <summary> /// Initializes a new instance of the <see cref="ResetResettablePLTransaction" /> class. /// </summary> /// <param name="Id">The Transaction&#39;s Identifier..</param> /// <param name="Time">The date/time when the Transaction was created..</param> /// <param name="UserID">The ID of the user that initiated the creation of the Transaction..</param> /// <param name="AccountID">The ID of the Account the Transaction was created for..</param> /// <param name="BatchID">The ID of the \&quot;batch\&quot; that the Transaction belongs to. Transactions in the same batch are applied to the Account simultaneously..</param> /// <param name="RequestID">The Request ID of the request which generated the transaction..</param> /// <param name="Type">The Type of the Transaction. Always set to \&quot;RESET_RESETTABLE_PL\&quot; for a ResetResettablePLTransaction..</param> public ResetResettablePLTransaction(string Id = default(string), string Time = default(string), int? UserID = default(int?), string AccountID = default(string), string BatchID = default(string), string RequestID = default(string), TypeEnum? Type = default(TypeEnum?)) { this.Id = Id; this.Time = Time; this.UserID = UserID; this.AccountID = AccountID; this.BatchID = BatchID; this.RequestID = RequestID; this.Type = Type; } /// <summary> /// The Transaction&#39;s Identifier. /// </summary> /// <value>The Transaction&#39;s Identifier.</value> [DataMember(Name="id", EmitDefaultValue=false)] public string Id { get; set; } /// <summary> /// The date/time when the Transaction was created. /// </summary> /// <value>The date/time when the Transaction was created.</value> [DataMember(Name="time", EmitDefaultValue=false)] public string Time { get; set; } /// <summary> /// The ID of the user that initiated the creation of the Transaction. /// </summary> /// <value>The ID of the user that initiated the creation of the Transaction.</value> [DataMember(Name="userID", EmitDefaultValue=false)] public int? UserID { get; set; } /// <summary> /// The ID of the Account the Transaction was created for. /// </summary> /// <value>The ID of the Account the Transaction was created for.</value> [DataMember(Name="accountID", EmitDefaultValue=false)] public string AccountID { get; set; } /// <summary> /// The ID of the \&quot;batch\&quot; that the Transaction belongs to. Transactions in the same batch are applied to the Account simultaneously. /// </summary> /// <value>The ID of the \&quot;batch\&quot; that the Transaction belongs to. Transactions in the same batch are applied to the Account simultaneously.</value> [DataMember(Name="batchID", EmitDefaultValue=false)] public string BatchID { get; set; } /// <summary> /// The Request ID of the request which generated the transaction. /// </summary> /// <value>The Request ID of the request which generated the transaction.</value> [DataMember(Name="requestID", EmitDefaultValue=false)] public string RequestID { 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 ResetResettablePLTransaction {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Time: ").Append(Time).Append("\n"); sb.Append(" UserID: ").Append(UserID).Append("\n"); sb.Append(" AccountID: ").Append(AccountID).Append("\n"); sb.Append(" BatchID: ").Append(BatchID).Append("\n"); sb.Append(" RequestID: ").Append(RequestID).Append("\n"); sb.Append(" Type: ").Append(Type).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 ResetResettablePLTransaction); } /// <summary> /// Returns true if ResetResettablePLTransaction instances are equal /// </summary> /// <param name="other">Instance of ResetResettablePLTransaction to be compared</param> /// <returns>Boolean</returns> public bool Equals(ResetResettablePLTransaction other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.Time == other.Time || this.Time != null && this.Time.Equals(other.Time) ) && ( this.UserID == other.UserID || this.UserID != null && this.UserID.Equals(other.UserID) ) && ( this.AccountID == other.AccountID || this.AccountID != null && this.AccountID.Equals(other.AccountID) ) && ( this.BatchID == other.BatchID || this.BatchID != null && this.BatchID.Equals(other.BatchID) ) && ( this.RequestID == other.RequestID || this.RequestID != null && this.RequestID.Equals(other.RequestID) ) && ( this.Type == other.Type || this.Type != null && this.Type.Equals(other.Type) ); } /// <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.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.Time != null) hash = hash * 59 + this.Time.GetHashCode(); if (this.UserID != null) hash = hash * 59 + this.UserID.GetHashCode(); if (this.AccountID != null) hash = hash * 59 + this.AccountID.GetHashCode(); if (this.BatchID != null) hash = hash * 59 + this.BatchID.GetHashCode(); if (this.RequestID != null) hash = hash * 59 + this.RequestID.GetHashCode(); if (this.Type != null) hash = hash * 59 + this.Type.GetHashCode(); return hash; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
#region license // Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org) // 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 Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using Boo.Lang.Compiler.TypeSystem.Internal; namespace Boo.Lang.Compiler.Steps { using System.Diagnostics; using Boo.Lang.Compiler.Ast; using Boo.Lang.Compiler.TypeSystem; public class ImplementICallableOnCallableDefinitions : AbstractVisitorCompilerStep { override public void OnModule(Module node) { Visit(node.Members, NodeType.ClassDefinition); } override public void OnClassDefinition(ClassDefinition node) { Visit(node.Members, NodeType.ClassDefinition); InternalCallableType type = node.Entity as InternalCallableType; if (null != type) { ImplementICallableCall(type, node); } } int GetByRefParamCount(CallableSignature signature) { int count = 0; foreach (IParameter param in signature.Parameters) { if (param.IsByRef) ++count; } return count; } void ImplementICallableCall(InternalCallableType type, ClassDefinition node) { Method call = (Method)node.Members["Call"]; Debug.Assert(null != call); Debug.Assert(call.Body.IsEmpty); CallableSignature signature = type.GetSignature(); int byRefCount = GetByRefParamCount(signature); if (byRefCount > 0) { ImplementByRefICallableCall(call, type, node, signature, byRefCount); } else { ImplementRegularICallableCall(call, type, node, signature); } } void ImplementByRefICallableCall( Method call, InternalCallableType type, ClassDefinition node, CallableSignature signature, int byRefCount) { MethodInvocationExpression mie = CreateInvokeInvocation(type); IParameter[] parameters = signature.Parameters; ReferenceExpression args = CodeBuilder.CreateReference(call.Parameters[0]); InternalLocal[] temporaries = new InternalLocal[byRefCount]; int byRefIndex = 0; for (int i=0; i<parameters.Length; ++i) { SlicingExpression slice = CodeBuilder.CreateSlicing(args.CloneNode(), i); IParameter parameter = parameters[i]; if (parameter.IsByRef) { IType tempType = parameter.Type; if (tempType.IsByRef) { tempType = tempType.ElementType; } temporaries[byRefIndex] = CodeBuilder.DeclareLocal(call, "__temp_" + parameter.Name, tempType); call.Body.Add( CodeBuilder.CreateAssignment( CodeBuilder.CreateReference(temporaries[byRefIndex]), CodeBuilder.CreateCast( tempType, slice))); mie.Arguments.Add( CodeBuilder.CreateReference( temporaries[byRefIndex])); ++byRefIndex; } else { mie.Arguments.Add(slice); } } if (TypeSystemServices.VoidType == signature.ReturnType) { call.Body.Add(mie); PropagateByRefParameterChanges(call, parameters, temporaries); } else { InternalLocal invokeReturnValue = CodeBuilder.DeclareLocal(call, "__returnValue", signature.ReturnType); call.Body.Add( CodeBuilder.CreateAssignment( CodeBuilder.CreateReference(invokeReturnValue), mie)); PropagateByRefParameterChanges(call, parameters, temporaries); call.Body.Add( new ReturnStatement( CodeBuilder.CreateReference(invokeReturnValue))); } } void PropagateByRefParameterChanges(Method call, IParameter[] parameters, InternalLocal[] temporaries) { int byRefIndex = 0; for (int i=0; i<parameters.Length; ++i) { if (!parameters[i].IsByRef) continue; SlicingExpression slice = CodeBuilder.CreateSlicing( CodeBuilder.CreateReference(call.Parameters[0]), i); call.Body.Add( CodeBuilder.CreateAssignment( slice, CodeBuilder.CreateReference(temporaries[byRefIndex]))); ++byRefIndex; } } void ImplementRegularICallableCall( Method call, InternalCallableType type, ClassDefinition node, CallableSignature signature) { MethodInvocationExpression mie = CreateInvokeInvocation(type); IParameter[] parameters = signature.Parameters; int fixedParametersLength = signature.AcceptVarArgs ? parameters.Length - 1 : parameters.Length; for (int i=0; i<fixedParametersLength; ++i) { SlicingExpression slice = CodeBuilder.CreateSlicing( CodeBuilder.CreateReference(call.Parameters[0]), i); mie.Arguments.Add(slice); } if (signature.AcceptVarArgs) { if (parameters.Length == 1) { mie.Arguments.Add(CodeBuilder.CreateReference(call.Parameters[0])); } else { mie.Arguments.Add( CodeBuilder.CreateMethodInvocation( RuntimeServices_GetRange1, CodeBuilder.CreateReference(call.Parameters[0]), CodeBuilder.CreateIntegerLiteral(fixedParametersLength))); } } if (TypeSystemServices.VoidType == signature.ReturnType) { call.Body.Add(mie); } else { call.Body.Add(new ReturnStatement(mie)); } } MethodInvocationExpression CreateInvokeInvocation(InternalCallableType type) { return CodeBuilder.CreateMethodInvocation( CodeBuilder.CreateSelfReference(type), type.GetInvokeMethod()); } IMethod _RuntimeServices_GetRange1; IMethod RuntimeServices_GetRange1 { get { if (null == _RuntimeServices_GetRange1) { _RuntimeServices_GetRange1 = NameResolutionService.ResolveMethod(TypeSystemServices.RuntimeServicesType, "GetRange1"); } return _RuntimeServices_GetRange1; } } } }
using System; using System.IO; using System.Drawing; using System.Windows.Forms; using System.Drawing.Drawing2D; namespace RanjuSoft.Utilities { class GViewPanel : Panel { private PieData data = null; public BorderLabel lblStatus = new BorderLabel(); private Button btnUp = new Button(); private Point ptDelta = new Point( 0, 0 ); private TipForm frmTip = new TipForm(); private Point BASE_OFFSET_HACK = new Point( 0, 52 ); public GViewPanel() { this.SuspendLayout(); this.SetStyle( ControlStyles.ResizeRedraw | ControlStyles.AllPaintingInWmPaint, true ); // // initialize label // lblStatus.BorderColor = Color.FromArgb( 208, 212, 228 ); lblStatus.BackColor = Color.FromArgb( 238, 242, 255 ); lblStatus.Size = new System.Drawing.Size( 418, 40 ); lblStatus.Location = new Point( BASE_OFFSET_HACK.X + 5, BASE_OFFSET_HACK.Y + 2 ); lblStatus.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); lblStatus.Text = "Ready."; this.Controls.Add( lblStatus ); // // initialize button // btnUp.Text = "U&p"; btnUp.Location = new Point( 300, 106 ); btnUp.Size = new Size( 35, 20 ); btnUp.Enabled = false; btnUp.Click += new EventHandler( btnUp_Click ); this.Controls.Add( btnUp ); this.ResumeLayout(); } protected override void OnSizeChanged( EventArgs e ) { base.OnSizeChanged( e ); //btnUp.Location = new Point( ClientRectangle.Width - ptDelta.X, ptDelta.Y ); } protected override void OnMouseDown( MouseEventArgs e ) { base.OnMouseDown( e ); if( data == null ) return; // // iterate through the child items of the current item // and see if this co-ord falls in a region // bool bFound = false; Point pt = new Point( e.X, e.Y ); Graphics g = CreateGraphics(); Item subitem = null; foreach( Item item in PieData.CurrentItem.SubItems ) { if( item.Region == null ) continue; if( item.Region.IsVisible( pt, g ) ) { subitem = item; bFound = true; break; } } g.Dispose(); // // ok, item has been found, now descend if the item // has sub-items // if( bFound ) { if( subitem.SubItems.Count > 0 ) { PieData.CurrentItem = subitem; btnUp.Enabled = true; Refresh(); lblStatus.Text = FormatCurrentItem(); lblStatus.Refresh(); } } } private void btnUp_Click( object sender, EventArgs e ) { PieData.CurrentItem = PieData.CurrentItem.Parent; if( PieData.CurrentItem == PieData.Root ) btnUp.Enabled = false; Refresh(); lblStatus.Text = FormatCurrentItem(); lblStatus.Refresh(); } protected override void OnMouseMove( MouseEventArgs e ) { base.OnMouseMove( e ); if( data == null ) return; // // iterate through the child items of the current item // and see if this co-ord falls in a region // bool bFound = false; Point pt = new Point( e.X, e.Y ); Graphics g = CreateGraphics(); foreach( Item item in PieData.CurrentItem.SubItems ) { if( item.Region == null ) continue; if( item.Region.IsVisible( pt, g ) ) { frmTip.Tip = FormatSubItem( item ); frmTip.Location = PointToScreen( new Point( pt.X, pt.Y - ( frmTip.Size.Height + 15 ) ) ); if( !frmTip.Visible ) frmTip.Show(); this.Focus(); RenderPie( g ); bFound = true; break; } } if( !bFound ) { frmTip.Hide(); RenderPie( g ); } g.Dispose(); } protected override void OnPaint( PaintEventArgs e ) { base.OnPaint( e ); Bitmap bmp = new Bitmap( ClientRectangle.Width, ClientRectangle.Height ); Graphics g = Graphics.FromImage( bmp ); // // paint the background colour // g.FillRectangle( new SolidBrush( Color.FromArgb( 228, 232, 248 ) ), Bounds ); // // if there's nothing to draw then return // if( data == null ) { // // draw the bitmap // e.Graphics.DrawImage( bmp, 0, 0 ); e.Graphics.Dispose(); return; } // // render the pie // RenderPie( g ); g.Dispose(); // // draw the bitmap // e.Graphics.DrawImage( bmp, 0, 0 ); e.Graphics.Dispose(); bmp.Dispose(); } private void RenderPie( Graphics g ) { float fAngle; float fStartAngle = 0; Rectangle rcPie = Rectangle.Inflate( ClientRectangle, -( ( ClientRectangle.Width * 25 ) / 100 ), -( ( ClientRectangle.Height * 25 ) / 100 ) ); Random random = new Random(); // // iterate over all the children in PieData.CurrentItem; // compute the percent occupied by each child in that item // and compute the width of the angle for that item // foreach( Item item in PieData.CurrentItem.SubItems ) { // // compute the angle // fAngle = (float)( item.Quantity * 360 ) / (float)PieData.CurrentItem.Quantity; // // create the path with the pie // GraphicsPath path = new GraphicsPath(); path.AddPie( rcPie, fStartAngle, fAngle ); fStartAngle += fAngle; // // create a region with this path // if( item.Region != null ) item.Region.Dispose(); item.Region = new Region( path ); path.Dispose(); // // fill the region with a random colour // item.Color = ( item.Color == Color.Empty ) ? Color.FromArgb( random.Next( 255 ), random.Next( 255 ), random.Next( 255 ) ) : item.Color; SolidBrush br = new SolidBrush( item.Color ); g.FillRegion( br, item.Region ); br.Dispose(); } } private void DisposeItems( Item item ) { if( item.Region != null ) item.Region.Dispose(); foreach( Item itm in item.SubItems ) DisposeItems( itm ); } private string FormatSubItem( Item item ) { System.Diagnostics.Debug.Assert( item.Parent != null ); return String.Format( "{0}\r\nType: {1}\r\n{2} ({3}%)", item.Name, ( item.SubItems.Count > 0 ) ? "Folder" : "File", FormatSize( item.Quantity ), ( (float)( item.Quantity * 100 ) / (float)item.Parent.Quantity ) ); } private string FormatCurrentItem() { return String.Format( "{0}\r\nSize: {1}\r\n{2} objects.", PieData.CurrentItem.Name, FormatSize( PieData.CurrentItem.Quantity ), PieData.CurrentItem.SubItems.Count ); } private string FormatSize( long lSize ) { // // the input is in bytes; the following logic is followed // // -> if the size is less than 1024 bytes then we show in bytes // -> if the size is greater than 1024 but less than 1048576 then we show // in KB // -> if the size is greater than 1048576 then we show in MB // if( lSize < 1024 ) return String.Format( "{0} bytes", lSize ); else if( lSize < ( 1024 * 1024 ) ) return String.Format( "{0} KB", ( (float)lSize / 1024 ) ); else return String.Format( "{0} MB", ( (float)lSize / 1024 ) / 1024 ); } public PieData PieData { set { if( data != null ) DisposeItems( data.Root ); data = value; btnUp.Enabled = false; Refresh(); if( data != null ) { lblStatus.Text = FormatCurrentItem(); lblStatus.Refresh(); } } get { return data; } } } public class Item { public string Name; public long Quantity; public ItemsCollection SubItems; public Item Parent; public Region Region; public Color Color; public Item() { Name = string.Empty; Quantity = 0; SubItems = new ItemsCollection(); Parent = null; Region = null; Color = Color.Empty; } } public class PieData { public Item Root; public Item CurrentItem; public PieData() { Root = new Item(); CurrentItem = Root; } } }
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.RecoveryServices.Backup { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// ProtectionContainerRefreshOperationResultsOperations operations. /// </summary> internal partial class ProtectionContainerRefreshOperationResultsOperations : Microsoft.Rest.IServiceOperations<RecoveryServicesBackupClient>, IProtectionContainerRefreshOperationResultsOperations { /// <summary> /// Initializes a new instance of the ProtectionContainerRefreshOperationResultsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ProtectionContainerRefreshOperationResultsOperations(RecoveryServicesBackupClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the RecoveryServicesBackupClient /// </summary> public RecoveryServicesBackupClient Client { get; private set; } /// <summary> /// Provides the result of the refresh operation triggered by the BeginRefresh /// operation. /// </summary> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='fabricName'> /// Fabric name associated with the container. /// </param> /// <param name='operationId'> /// Operation ID associated with the operation whose result needs to be /// fetched. /// </param> /// <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> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> GetWithHttpMessagesAsync(string vaultName, string resourceGroupName, string fabricName, string operationId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (vaultName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "vaultName"); } if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (fabricName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "fabricName"); } if (operationId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "operationId"); } string apiVersion = "2016-06-01"; // 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("apiVersion", apiVersion); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("operationId", operationId); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupFabrics/{fabricName}/operationResults/{operationId}").ToString(); _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName)); _url = _url.Replace("{operationId}", System.Uri.EscapeDataString(operationId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + 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("GET"); _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 != 202 && (int)_statusCode != 204) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } 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(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { 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 Xunit; namespace System.Tests { public abstract class ConvertTestBase<TOutput> { /// <summary> /// Verify that the provided convert delegate produces expectedValues given testValues. /// </summary> protected void Verify<TInput>(Func<TInput, TOutput> convert, TInput[] testValues, TOutput[] expectedValues) { Assert.Equal(expectedValues.Length, testValues.Length); for (int i = 0; i < testValues.Length; i++) { TOutput result = convert(testValues[i]); Assert.Equal(expectedValues[i], result); if (testValues[i] is IConvertible convertible) { Assert.Equal(expectedValues[i], convertible.ToType(typeof(TOutput), null)); switch (expectedValues[i]) { case bool expected: Assert.Equal(expected, convertible.ToBoolean(null)); break; case char expected: Assert.Equal(expected, convertible.ToChar(null)); break; case sbyte expected: Assert.Equal(expected, convertible.ToSByte(null)); break; case byte expected: Assert.Equal(expected, convertible.ToByte(null)); break; case short expected: Assert.Equal(expected, convertible.ToInt16(null)); break; case ushort expected: Assert.Equal(expected, convertible.ToUInt16(null)); break; case int expected: Assert.Equal(expected, convertible.ToInt32(null)); break; case uint expected: Assert.Equal(expected, convertible.ToUInt32(null)); break; case long expected: Assert.Equal(expected, convertible.ToInt64(null)); break; case ulong expected: Assert.Equal(expected, convertible.ToUInt64(null)); break; case float expected: Assert.Equal(expected, convertible.ToSingle(null)); break; case double expected: Assert.Equal(expected, convertible.ToDouble(null)); break; case decimal expected: Assert.Equal(expected, convertible.ToDecimal(null)); break; case DateTime expected: Assert.Equal(expected, convertible.ToDateTime(null)); break; case string expected: Assert.Equal(expected, convertible.ToString(null)); break; } } } } /// <summary> /// Verify that the provided convert delegates produce expectedValues given testValues /// </summary> protected void VerifyFromString(Func<string, TOutput> convert, Func<string, IFormatProvider, TOutput> convertWithFormatProvider, string[] testValues, TOutput[] expectedValues) { Verify<string>(convert, testValues, expectedValues); Verify<string>(input => convertWithFormatProvider(input, TestFormatProvider.s_instance), testValues, expectedValues); } /// <summary> /// Verify that the provided convert delegates produce expectedValues given testValues /// </summary> protected void VerifyFromObject(Func<object, TOutput> convert, Func<object, IFormatProvider, TOutput> convertWithFormatProvider, object[] testValues, TOutput[] expectedValues) { Verify<object>(convert, testValues, expectedValues); Verify<object>(input => convertWithFormatProvider(input, TestFormatProvider.s_instance), testValues, expectedValues); } /// <summary> /// Verify that the provided convert delegate produces expectedValues given testValues and testBases /// </summary> protected void VerifyFromStringWithBase(Func<string, int, TOutput> convert, string[] testValues, int[] testBases, TOutput[] expectedValues) { Assert.Equal(testValues.Length, testBases.Length); Assert.Equal(testValues.Length, expectedValues.Length); for (int i = 0; i < testValues.Length; i++) { TOutput result = convert(testValues[i], testBases[i]); Assert.Equal(expectedValues[i], result); } } /// <summary> /// Verify that the provided convert delegate throws an exception of type TException given testValues and testBases /// </summary> protected void VerifyFromStringWithBaseThrows<TException>(Func<string, int, TOutput> convert, string[] testValues, int[] testBases) where TException : Exception { Assert.Equal(testValues.Length, testBases.Length); for (int i = 0; i < testValues.Length; i++) { try { Assert.Throws<TException>(() => convert(testValues[i], testBases[i])); } catch (Exception e) { string message = string.Format("Expected {0} converting '{1}' (base {2}) to '{3}'", typeof(TException).FullName, testValues[i], testBases[i], typeof(TOutput).FullName); throw new AggregateException(message, e); } } } /// <summary> /// Verify that the provided convert delegate throws an exception of type TException given testValues /// </summary> protected void VerifyThrows<TException, TInput>(Func<TInput, TOutput> convert, TInput[] testValues) where TException : Exception { for (int i = 0; i < testValues.Length; i++) { try { Assert.Throws<TException>(() => convert(testValues[i])); if (testValues[i] is IConvertible convertible) { Assert.Throws<TException>(() => convertible.ToType(typeof(TOutput), null)); switch (default(TOutput)) { case bool _: Assert.Throws<TException>(() => convertible.ToBoolean(null)); break; case char _: Assert.Throws<TException>(() => convertible.ToChar(null)); break; case sbyte _: Assert.Throws<TException>(() => convertible.ToSByte(null)); break; case byte _: Assert.Throws<TException>(() => convertible.ToByte(null)); break; case short _: Assert.Throws<TException>(() => convertible.ToInt16(null)); break; case ushort _: Assert.Throws<TException>(() => convertible.ToUInt16(null)); break; case int _: Assert.Throws<TException>(() => convertible.ToInt32(null)); break; case uint _: Assert.Throws<TException>(() => convertible.ToUInt32(null)); break; case long _: Assert.Throws<TException>(() => convertible.ToInt64(null)); break; case ulong _: Assert.Throws<TException>(() => convertible.ToUInt64(null)); break; case float _: Assert.Throws<TException>(() => convertible.ToSingle(null)); break; case double _: Assert.Throws<TException>(() => convertible.ToDouble(null)); break; case decimal _: Assert.Throws<TException>(() => convertible.ToDecimal(null)); break; case DateTime _: Assert.Throws<TException>(() => convertible.ToDateTime(null)); break; case string _: Assert.Throws<TException>(() => convertible.ToString(null)); break; } } } catch (Exception e) { string message = string.Format("Expected {0} converting '{1}' ({2}) to {3}", typeof(TException).FullName, testValues[i], typeof(TInput).FullName, typeof(TOutput).FullName); throw new AggregateException(message, e); } } } /// <summary> /// Verify that the provided convert delegates throws an exception of type TException given testValues /// </summary> protected void VerifyFromStringThrows<TException>(Func<string, TOutput> convert, Func<string, IFormatProvider, TOutput> convertWithFormatProvider, string[] testValues) where TException : Exception { VerifyThrows<TException, string>(convert, testValues); VerifyThrows<TException, string>(input => convertWithFormatProvider(input, TestFormatProvider.s_instance), testValues); } /// <summary> /// Verify that the provided convert delegates throw exception of type TException given testValues /// </summary> protected void VerifyFromObjectThrows<TException>(Func<object, TOutput> convert, Func<object, IFormatProvider, TOutput> convertWithFormatProvider, object[] testValues) where TException : Exception { VerifyThrows<TException, object>(convert, testValues); VerifyThrows<TException, object>(input => convertWithFormatProvider(input, TestFormatProvider.s_instance), testValues); } /// <summary> /// Helper class to test that the IFormatProvider is being called. /// </summary> protected class TestFormatProvider : IFormatProvider, ICustomFormatter { public static readonly TestFormatProvider s_instance = new TestFormatProvider(); private TestFormatProvider() { } public object GetFormat(Type formatType) { return this; } public string Format(string format, object arg, IFormatProvider formatProvider) { return arg.ToString(); } } } }
using System; using NBitcoin.BouncyCastle.Crypto.Digests; using NBitcoin.BouncyCastle.Crypto.Modes; using NBitcoin.BouncyCastle.Crypto.Parameters; using NBitcoin.BouncyCastle.Security; using NBitcoin.BouncyCastle.Utilities; namespace NBitcoin.BouncyCastle.Crypto.Engines { /** * Wrap keys according to * <a href="http://www.ietf.org/internet-drafts/draft-ietf-smime-key-wrap-01.txt"> * draft-ietf-smime-key-wrap-01.txt</a>. * <p> * Note: * <ul> * <li>this is based on a draft, and as such is subject to change - don't use this class for anything requiring long term storage.</li> * <li>if you are using this to wrap triple-des keys you need to set the * parity bits on the key and, if it's a two-key triple-des key, pad it * yourself.</li> * </ul> * </p> */ public class DesEdeWrapEngine : IWrapper { /** Field engine */ private CbcBlockCipher engine; /** Field param */ private KeyParameter param; /** Field paramPlusIV */ private ParametersWithIV paramPlusIV; /** Field iv */ private byte[] iv; /** Field forWrapping */ private bool forWrapping; /** Field IV2 */ private static readonly byte[] IV2 = { (byte) 0x4a, (byte) 0xdd, (byte) 0xa2, (byte) 0x2c, (byte) 0x79, (byte) 0xe8, (byte) 0x21, (byte) 0x05 }; // // checksum digest // private readonly IDigest sha1 = new Sha1Digest(); private readonly byte[] digest = new byte[20]; /** * Method init * * @param forWrapping * @param param */ public void Init( bool forWrapping, ICipherParameters parameters) { this.forWrapping = forWrapping; this.engine = new CbcBlockCipher(new DesEdeEngine()); SecureRandom sr; if (parameters is ParametersWithRandom) { ParametersWithRandom pr = (ParametersWithRandom) parameters; parameters = pr.Parameters; sr = pr.Random; } else { sr = new SecureRandom(); } if (parameters is KeyParameter) { this.param = (KeyParameter) parameters; if (this.forWrapping) { // Hm, we have no IV but we want to wrap ?!? // well, then we have to create our own IV. this.iv = new byte[8]; sr.NextBytes(iv); this.paramPlusIV = new ParametersWithIV(this.param, this.iv); } } else if (parameters is ParametersWithIV) { if (!forWrapping) throw new ArgumentException("You should not supply an IV for unwrapping"); this.paramPlusIV = (ParametersWithIV) parameters; this.iv = this.paramPlusIV.GetIV(); this.param = (KeyParameter) this.paramPlusIV.Parameters; if (this.iv.Length != 8) throw new ArgumentException("IV is not 8 octets", "parameters"); } } /** * Method GetAlgorithmName * * @return */ public string AlgorithmName { get { return "DESede"; } } /** * Method wrap * * @param in * @param inOff * @param inLen * @return */ public byte[] Wrap( byte[] input, int inOff, int length) { if (!forWrapping) { throw new InvalidOperationException("Not initialized for wrapping"); } byte[] keyToBeWrapped = new byte[length]; Array.Copy(input, inOff, keyToBeWrapped, 0, length); // Compute the CMS Key Checksum, (section 5.6.1), call this CKS. byte[] CKS = CalculateCmsKeyChecksum(keyToBeWrapped); // Let WKCKS = WK || CKS where || is concatenation. byte[] WKCKS = new byte[keyToBeWrapped.Length + CKS.Length]; Array.Copy(keyToBeWrapped, 0, WKCKS, 0, keyToBeWrapped.Length); Array.Copy(CKS, 0, WKCKS, keyToBeWrapped.Length, CKS.Length); // Encrypt WKCKS in CBC mode using KEK as the key and IV as the // initialization vector. Call the results TEMP1. int blockSize = engine.GetBlockSize(); if (WKCKS.Length % blockSize != 0) throw new InvalidOperationException("Not multiple of block length"); engine.Init(true, paramPlusIV); byte [] TEMP1 = new byte[WKCKS.Length]; for (int currentBytePos = 0; currentBytePos != WKCKS.Length; currentBytePos += blockSize) { engine.ProcessBlock(WKCKS, currentBytePos, TEMP1, currentBytePos); } // Let TEMP2 = IV || TEMP1. byte[] TEMP2 = new byte[this.iv.Length + TEMP1.Length]; Array.Copy(this.iv, 0, TEMP2, 0, this.iv.Length); Array.Copy(TEMP1, 0, TEMP2, this.iv.Length, TEMP1.Length); // Reverse the order of the octets in TEMP2 and call the result TEMP3. byte[] TEMP3 = reverse(TEMP2); // Encrypt TEMP3 in CBC mode using the KEK and an initialization vector // of 0x 4a dd a2 2c 79 e8 21 05. The resulting cipher text is the desired // result. It is 40 octets long if a 168 bit key is being wrapped. ParametersWithIV param2 = new ParametersWithIV(this.param, IV2); this.engine.Init(true, param2); for (int currentBytePos = 0; currentBytePos != TEMP3.Length; currentBytePos += blockSize) { engine.ProcessBlock(TEMP3, currentBytePos, TEMP3, currentBytePos); } return TEMP3; } /** * Method unwrap * * @param in * @param inOff * @param inLen * @return * @throws InvalidCipherTextException */ public byte[] Unwrap( byte[] input, int inOff, int length) { if (forWrapping) { throw new InvalidOperationException("Not set for unwrapping"); } if (input == null) { throw new InvalidCipherTextException("Null pointer as ciphertext"); } int blockSize = engine.GetBlockSize(); if (length % blockSize != 0) { throw new InvalidCipherTextException("Ciphertext not multiple of " + blockSize); } /* // Check if the length of the cipher text is reasonable given the key // type. It must be 40 bytes for a 168 bit key and either 32, 40, or // 48 bytes for a 128, 192, or 256 bit key. If the length is not supported // or inconsistent with the algorithm for which the key is intended, // return error. // // we do not accept 168 bit keys. it has to be 192 bit. int lengthA = (estimatedKeyLengthInBit / 8) + 16; int lengthB = estimatedKeyLengthInBit % 8; if ((lengthA != keyToBeUnwrapped.Length) || (lengthB != 0)) { throw new XMLSecurityException("empty"); } */ // Decrypt the cipher text with TRIPLedeS in CBC mode using the KEK // and an initialization vector (IV) of 0x4adda22c79e82105. Call the output TEMP3. ParametersWithIV param2 = new ParametersWithIV(this.param, IV2); this.engine.Init(false, param2); byte [] TEMP3 = new byte[length]; for (int currentBytePos = 0; currentBytePos != TEMP3.Length; currentBytePos += blockSize) { engine.ProcessBlock(input, inOff + currentBytePos, TEMP3, currentBytePos); } // Reverse the order of the octets in TEMP3 and call the result TEMP2. byte[] TEMP2 = reverse(TEMP3); // Decompose TEMP2 into IV, the first 8 octets, and TEMP1, the remaining octets. this.iv = new byte[8]; byte[] TEMP1 = new byte[TEMP2.Length - 8]; Array.Copy(TEMP2, 0, this.iv, 0, 8); Array.Copy(TEMP2, 8, TEMP1, 0, TEMP2.Length - 8); // Decrypt TEMP1 using TRIPLedeS in CBC mode using the KEK and the IV // found in the previous step. Call the result WKCKS. this.paramPlusIV = new ParametersWithIV(this.param, this.iv); this.engine.Init(false, this.paramPlusIV); byte[] WKCKS = new byte[TEMP1.Length]; for (int currentBytePos = 0; currentBytePos != WKCKS.Length; currentBytePos += blockSize) { engine.ProcessBlock(TEMP1, currentBytePos, WKCKS, currentBytePos); } // Decompose WKCKS. CKS is the last 8 octets and WK, the wrapped key, are // those octets before the CKS. byte[] result = new byte[WKCKS.Length - 8]; byte[] CKStoBeVerified = new byte[8]; Array.Copy(WKCKS, 0, result, 0, WKCKS.Length - 8); Array.Copy(WKCKS, WKCKS.Length - 8, CKStoBeVerified, 0, 8); // Calculate a CMS Key Checksum, (section 5.6.1), over the WK and compare // with the CKS extracted in the above step. If they are not equal, return error. if (!CheckCmsKeyChecksum(result, CKStoBeVerified)) { throw new InvalidCipherTextException( "Checksum inside ciphertext is corrupted"); } // WK is the wrapped key, now extracted for use in data decryption. return result; } /** * Some key wrap algorithms make use of the Key Checksum defined * in CMS [CMS-Algorithms]. This is used to provide an integrity * check value for the key being wrapped. The algorithm is * * - Compute the 20 octet SHA-1 hash on the key being wrapped. * - Use the first 8 octets of this hash as the checksum value. * * @param key * @return * @throws Exception * @see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum */ private byte[] CalculateCmsKeyChecksum( byte[] key) { sha1.BlockUpdate(key, 0, key.Length); sha1.DoFinal(digest, 0); byte[] result = new byte[8]; Array.Copy(digest, 0, result, 0, 8); return result; } /** * @param key * @param checksum * @return * @see http://www.w3.org/TR/xmlenc-core/#sec-CMSKeyChecksum */ private bool CheckCmsKeyChecksum( byte[] key, byte[] checksum) { return Arrays.ConstantTimeAreEqual(CalculateCmsKeyChecksum(key), checksum); } private static byte[] reverse(byte[] bs) { byte[] result = new byte[bs.Length]; for (int i = 0; i < bs.Length; i++) { result[i] = bs[bs.Length - (i + 1)]; } return result; } } }
//----------------------------------------------------------------------- // Copyright (c) Microsoft Open Technologies, Inc. // All Rights Reserved // Apache License 2.0 // // 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 Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.IdentityModel.Protocols.WSTrust; using System.IdentityModel.Tokens; using System.Security.Claims; using SamlSecurityTokenHandler = Microsoft.IdentityModel.Tokens.SamlSecurityTokenHandler; namespace Microsoft.IdentityModel.Test { /// <summary> /// /// </summary> [TestClass] public class SamlSecurityTokenHandlerTests { public TestContext TestContext { get; set; } [ClassInitialize] public static void ClassSetup(TestContext testContext) { } [ClassCleanup] public static void ClassCleanup() { } [TestInitialize] public void Initialize() { } [TestMethod] [TestProperty("TestCaseID", "cc3fff9a-ef48-4818-8c25-b814a9888cfe")] [Description("Tests: Constructors")] public void SamlSecurityTokenHandler_Constructors() { SamlSecurityTokenHandler samlSecurityTokenHandler = new SamlSecurityTokenHandler(); } [TestMethod] [TestProperty("TestCaseID", "c97d3f29-5032-4d63-88c3-9863be253b6d")] [Description("Tests: Defaults")] public void SamlSecurityTokenHandler_Defaults() { SamlSecurityTokenHandler samlSecurityTokenHandler = new SamlSecurityTokenHandler(); Assert.IsTrue(samlSecurityTokenHandler.MaximumTokenSizeInBytes == TokenValidationParameters.DefaultMaximumTokenSizeInBytes, "MaximumTokenSizeInBytes"); } [TestMethod] [TestProperty("TestCaseID", "d739cd25-b7fa-4191-b0be-e60fa8cf8651")] [Description("Tests: GetSets")] public void SamlSecurityTokenHandler_GetSets() { SamlSecurityTokenHandler samlSecurityTokenHandler = new SamlSecurityTokenHandler(); TestUtilities.SetGet(samlSecurityTokenHandler, "MaximumTokenSizeInBytes", (object)0, ExpectedException.ArgumentOutOfRangeException(substringExpected: "IDX10101")); TestUtilities.SetGet(samlSecurityTokenHandler, "MaximumTokenSizeInBytes", (object)1, ExpectedException.NoExceptionExpected); } [TestMethod] [TestProperty("TestCaseID", "9D11B4D9-957F-4E30-9420-AD0683A5BF87")] [Description("Tests: Protected")] public void SamlSecurityTokenHandler_Protected() { CreateClaims(); } private void CreateClaims() { PublicSamlSecurityTokenHandler samlSecurityTokenHandler = new PublicSamlSecurityTokenHandler(); ExpectedException expectedException = ExpectedException.ArgumentNullException(substringExpected: "samlToken"); CreateClaims(null, "issuer", new TokenValidationParameters(), samlSecurityTokenHandler: samlSecurityTokenHandler, expectedException: expectedException); } private void CreateClaims(SamlSecurityToken samlToken, string issuer, TokenValidationParameters validationParameters, PublicSamlSecurityTokenHandler samlSecurityTokenHandler, ExpectedException expectedException) { try { samlSecurityTokenHandler.CreateClaimsPublic(samlToken, issuer, validationParameters ); expectedException.ProcessNoException(); } catch (Exception exception) { expectedException.ProcessException(exception); } } [TestMethod] [TestProperty("TestCaseID", "82db9de3-7c75-4721-b1bb-b38fe097c398")] [Description("Tests: Publics")] public void SamlSecurityTokenHandler_Publics() { CanReadToken(); ValidateIssuer(); ValidateToken(); } private void CanReadToken() { // CanReadToken SamlSecurityTokenHandler samlSecurityTokenHandler = new SamlSecurityTokenHandler(); Assert.IsFalse(CanReadToken(securityToken: null, samlSecurityTokenHandler: samlSecurityTokenHandler, expectedException: ExpectedException.NoExceptionExpected)); string samlString = new string('S', TokenValidationParameters.DefaultMaximumTokenSizeInBytes + 1); Assert.IsFalse(CanReadToken(securityToken: samlString, samlSecurityTokenHandler: samlSecurityTokenHandler, expectedException: ExpectedException.NoExceptionExpected)); samlString = new string('S', TokenValidationParameters.DefaultMaximumTokenSizeInBytes); Assert.IsFalse(CanReadToken(securityToken: samlString, samlSecurityTokenHandler: samlSecurityTokenHandler, expectedException: ExpectedException.NoExceptionExpected)); samlString = IdentityUtilities.CreateSamlToken(); Assert.IsTrue(CanReadToken(securityToken: samlString, samlSecurityTokenHandler: samlSecurityTokenHandler, expectedException: ExpectedException.NoExceptionExpected)); } private bool CanReadToken(string securityToken, SamlSecurityTokenHandler samlSecurityTokenHandler, ExpectedException expectedException) { bool canReadToken = false; try { canReadToken = samlSecurityTokenHandler.CanReadToken(securityToken); expectedException.ProcessNoException(); } catch (Exception exception) { expectedException.ProcessException(exception); } return canReadToken; } private void ValidateIssuer() { PublicSamlSecurityTokenHandler samlSecurityTokenHandler = new PublicSamlSecurityTokenHandler(); SamlSecurityToken samlToken = IdentityUtilities.CreateSamlSecurityToken(); ValidateIssuer(IdentityUtilities.DefaultIssuer, null, samlToken, samlSecurityTokenHandler, ExpectedException.ArgumentNullException(substringExpected: "name: validationParameters")); ValidateIssuer("bob", null, samlToken, samlSecurityTokenHandler, ExpectedException.ArgumentNullException(substringExpected: "name: validationParameters")); ValidateIssuer("bob", new TokenValidationParameters { ValidateIssuer = false }, samlToken, samlSecurityTokenHandler, ExpectedException.NoExceptionExpected); ValidateIssuer("bob", new TokenValidationParameters { }, samlToken, samlSecurityTokenHandler, ExpectedException.SecurityTokenInvalidIssuerException(substringExpected: "IDX10204")); ValidateIssuer(IdentityUtilities.DefaultIssuer, new TokenValidationParameters { ValidIssuer = IdentityUtilities.DefaultIssuer }, samlToken, samlSecurityTokenHandler, ExpectedException.NoExceptionExpected); ValidateIssuer("bob", new TokenValidationParameters { ValidIssuer = "frank" }, samlToken, samlSecurityTokenHandler, ExpectedException.SecurityTokenInvalidIssuerException(substringExpected: "IDX10205")); List<string> validIssuers = new List<string> { "john", "paul", "george", "ringo" }; ValidateIssuer("bob", new TokenValidationParameters { ValidIssuers = validIssuers }, samlToken, samlSecurityTokenHandler, ExpectedException.SecurityTokenInvalidIssuerException(substringExpected: "IDX10205")); ValidateIssuer("bob", new TokenValidationParameters { ValidateIssuer = false }, samlToken, samlSecurityTokenHandler, ExpectedException.NoExceptionExpected); validIssuers.Add(IdentityUtilities.DefaultIssuer); string issuer = ValidateIssuer(IdentityUtilities.DefaultIssuer, new TokenValidationParameters { ValidIssuers = validIssuers }, samlToken, samlSecurityTokenHandler, ExpectedException.NoExceptionExpected); Assert.IsTrue(issuer == IdentityUtilities.DefaultIssuer, "issuer mismatch"); TokenValidationParameters validationParameters = new TokenValidationParameters { ValidateAudience = false, IssuerValidator = IdentityUtilities.IssuerValidatorEcho, }; ValidateIssuer("bob", validationParameters, samlToken, samlSecurityTokenHandler, ExpectedException.SecurityTokenInvalidIssuerException(substringExpected: "IDX10204")); validationParameters.ValidateIssuer = false; validationParameters.IssuerValidator = IdentityUtilities.IssuerValidatorThrows; ValidateIssuer("bob", validationParameters, samlToken, samlSecurityTokenHandler, ExpectedException.NoExceptionExpected); } private string ValidateIssuer(string issuer, TokenValidationParameters validationParameters, SamlSecurityToken samlToken, PublicSamlSecurityTokenHandler samlSecurityTokenHandler, ExpectedException expectedException) { string returnVal = string.Empty; try { returnVal = samlSecurityTokenHandler.ValidateIssuerPublic(issuer, samlToken, validationParameters); expectedException.ProcessNoException(); } catch (Exception exception) { expectedException.ProcessException(exception); } return returnVal; } private void ValidateToken() { // parameter validation SamlSecurityTokenHandler tokenHandler = new SamlSecurityTokenHandler(); ExpectedException expectedException = ExpectedException.ArgumentNullException(substringExpected: "name: securityToken"); TestUtilities.ValidateToken(securityToken: null, validationParameters: new TokenValidationParameters(), tokenValidator: tokenHandler, expectedException: expectedException); expectedException = ExpectedException.ArgumentNullException(substringExpected: "name: validationParameters"); TestUtilities.ValidateToken(securityToken: "s", validationParameters: null, tokenValidator: tokenHandler, expectedException: expectedException); expectedException = ExpectedException.ArgumentException(substringExpected: "IDX10209"); tokenHandler.MaximumTokenSizeInBytes = 1; TestUtilities.ValidateToken(securityToken: "ss", validationParameters: new TokenValidationParameters(), tokenValidator: tokenHandler, expectedException: expectedException); tokenHandler.MaximumTokenSizeInBytes = TokenValidationParameters.DefaultMaximumTokenSizeInBytes; string samlToken = IdentityUtilities.CreateSamlToken(); ValidateAudience(); SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor { AppliesToAddress = IdentityUtilities.DefaultAudience, Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow + TimeSpan.FromHours(1)), SigningCredentials = KeyingMaterial.DefaultAsymmetricSigningCreds_2048_RsaSha2_Sha2, Subject = IdentityUtilities.DefaultClaimsIdentity, TokenIssuerName = IdentityUtilities.DefaultIssuer, }; samlToken = IdentityUtilities.CreateSamlToken(tokenDescriptor); TokenValidationParameters validationParameters = new TokenValidationParameters { IssuerSigningToken = KeyingMaterial.DefaultAsymmetricX509Token_2048, ValidAudience = IdentityUtilities.DefaultAudience, ValidIssuer = IdentityUtilities.DefaultIssuer, }; TestUtilities.ValidateTokenReplay(samlToken, tokenHandler, validationParameters); TestUtilities.ValidateToken(samlToken, validationParameters, tokenHandler, ExpectedException.NoExceptionExpected); validationParameters.LifetimeValidator = (nb, exp, st, tvp) => { return false; }; TestUtilities.ValidateToken(samlToken, validationParameters, tokenHandler, new ExpectedException(typeExpected: typeof(SecurityTokenInvalidLifetimeException), substringExpected: "IDX10230:")); validationParameters.ValidateLifetime = false; validationParameters.LifetimeValidator = IdentityUtilities.LifetimeValidatorThrows; TestUtilities.ValidateToken(securityToken: samlToken, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: ExpectedException.NoExceptionExpected); } private void ValidateAudience() { SamlSecurityTokenHandler tokenHandler = new SamlSecurityTokenHandler(); ExpectedException expectedException; string samlString = IdentityUtilities.CreateSamlToken(); TokenValidationParameters validationParameters = new TokenValidationParameters { ValidIssuer = IdentityUtilities.DefaultIssuer, IssuerSigningToken = IdentityUtilities.DefaultAsymmetricSigningToken, }; // Do not validate audience validationParameters.ValidateAudience = false; expectedException = ExpectedException.NoExceptionExpected; TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: ExpectedException.NoExceptionExpected); validationParameters.ValidateAudience = true; expectedException = ExpectedException.SecurityTokenInvalidAudienceException(); TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: expectedException); validationParameters.ValidateAudience = true; validationParameters.ValidAudience = "John"; expectedException = ExpectedException.SecurityTokenInvalidAudienceException(substringExpected: "IDX10214:"); TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: expectedException); // UriKind.Absolute, no match. validationParameters.ValidateAudience = true; validationParameters.ValidAudience = IdentityUtilities.NotDefaultAudience; expectedException = ExpectedException.SecurityTokenInvalidAudienceException(substringExpected: "IDX10214:"); TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: expectedException); expectedException = ExpectedException.NoExceptionExpected; validationParameters.ValidAudience = IdentityUtilities.DefaultAudience; validationParameters.ValidAudiences = null; TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: expectedException); // !UriKind.Absolute List<string> audiences = new List<string> { "John", "Paul", "George", "Ringo" }; validationParameters.ValidAudience = null; validationParameters.ValidAudiences = audiences; validationParameters.ValidateAudience = false; expectedException = ExpectedException.NoExceptionExpected; TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: expectedException); // UriKind.Absolute, no match audiences = new List<string> { "http://www.John.com", "http://www.Paul.com", "http://www.George.com", "http://www.Ringo.com", " " }; validationParameters.ValidAudience = null; validationParameters.ValidAudiences = audiences; validationParameters.ValidateAudience = false; expectedException = ExpectedException.NoExceptionExpected; TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: expectedException); validationParameters.ValidateAudience = true; expectedException = ExpectedException.SecurityTokenInvalidAudienceException(substringExpected: "IDX10214"); TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: expectedException); validationParameters.ValidateAudience = true; expectedException = ExpectedException.NoExceptionExpected; audiences.Add(IdentityUtilities.DefaultAudience); TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: expectedException); validationParameters.AudienceValidator = (aud, token, tvp) => { return false; }; expectedException = new ExpectedException(typeExpected: typeof(SecurityTokenInvalidAudienceException), substringExpected: "IDX10231:"); TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: expectedException); validationParameters.ValidateAudience = false; validationParameters.AudienceValidator = IdentityUtilities.AudienceValidatorThrows; TestUtilities.ValidateToken(securityToken: samlString, validationParameters: validationParameters, tokenValidator: tokenHandler, expectedException: ExpectedException.NoExceptionExpected); } private class PublicSamlSecurityTokenHandler : SamlSecurityTokenHandler { public ClaimsIdentity CreateClaimsPublic(SamlSecurityToken samlToken, string issuer, TokenValidationParameters validationParameters) { return base.CreateClaimsIdentity(samlToken, issuer, validationParameters); } public string ValidateIssuerPublic(string issuer, SamlSecurityToken samlToken, TokenValidationParameters validationParameters) { return base.ValidateIssuer(issuer, samlToken, validationParameters); } } } }
using System; using System.Collections.Generic; using System.Data; using System.Drawing; using System.Globalization; using System.Windows.Forms; using Blade.Data; using Blade.Collections; using Blade; namespace Maui.Data.Recognition.Html { /// <summary> /// Extensions for the Windows.Forms.HtmlDocument class. /// </summary> public static class HtmlDocumentExtensions { /// <summary> /// Returns the element specified by the given <see cref="HtmlPath"/>. /// </summary> public static IHtmlElement GetElementByPath( this IHtmlDocument doc, HtmlPath path ) { doc.Require( d => doc != null ); path.Require( p => path != null ); var root = doc.Body.GetRoot(); if ( root == null ) { return null; } foreach ( var element in path.Elements ) { root = root.GetChildAt( element.TagName, element.Position ); if ( root == null ) { return null; } } return root; } /// <summary> /// Gets the text of the element specified by the given <see cref="HtmlPath"/>. /// </summary> public static string GetTextByPath( this IHtmlDocument doc, HtmlPath path ) { var e = doc.GetElementByPath( path ); if ( e == null ) { return null; } return e.InnerText; } /// <summary> /// Gets the HtmlTable the given path is pointing to. /// If the path is pointing into a table, the embedding table is returned. /// If the path is not pointing to a table element null is returned. /// </summary> public static HtmlTable GetTableByPath( this IHtmlDocument doc, HtmlPath path ) { var start = doc.GetElementByPath( path ); if ( start == null ) { return null; } return start.FindEmbeddingTable(); } public static HtmlForm GetFormByName( this IHtmlDocument document, string formName ) { return new HtmlForm( document.Body.GetFormByName( formName ) ); } private static IHtmlElement GetFormByName( this IHtmlElement element, string formName ) { foreach ( var child in element.Children ) { if ( child.TagName.EqualsI( "form" ) && child.GetAttribute( "name" ).EqualsI( formName ) ) { return child; } else { var form = child.GetFormByName( formName ); if ( form != null ) { return form; } } } return null; } /// <summary> /// Extracts the complete html table the given path is pointing to. If the path points /// to a cell of a table the complete table is extracted still. /// <remarks> /// Returns null if table not found by path. Currently we cannot handle thead /// and tfoot. The number of the column is defined by the html table row with the most /// html columns /// </remarks> /// </summary> /// <param name="doc">the HTML document</param> /// <param name="path">the path to the table</param> /// <param name="textOnly">set this to true to get only the text of the cell, otherwise the /// cell itself as HtmlElement is returned</param> public static FallibleActionResult<DataTable> ExtractTable( this IHtmlDocument doc, HtmlPath path, bool textOnly ) { doc.Require( x => doc != null ); path.Require( x => path != null ); HtmlTable htmlTable = doc.GetTableByPath( path ); if ( htmlTable == null ) { return FallibleActionResult<DataTable>.CreateFailureResult( "Could not get table by path" ); } DataTable table = new DataTable(); // TODO: should we get the culture from the HTML page somehow? table.Locale = CultureInfo.InvariantCulture; Func<IHtmlElement, object> GetContent = element => (textOnly ? (object)element.InnerText : element); foreach ( var tr in htmlTable.Rows ) { var htmlRow = new List<IHtmlElement>(); foreach ( var td in tr.Children ) { if ( td.TagName == "TD" || td.TagName == "TH" ) { htmlRow.Add( td ); } } // add columns if necessary if ( htmlRow.Count > table.Columns.Count ) { (htmlRow.Count - table.Columns.Count).Times( x => table.Columns.Add( string.Empty, typeof( object ) ) ); } // add new row to table DataRow row = table.NewRow(); table.Rows.Add( row ); table.AcceptChanges(); // add data htmlRow.ForeachIndex( ( element, idx ) => row[ idx ] = GetContent( element ) ); } if ( table.Rows.Count == 0 ) { table.Dispose(); return FallibleActionResult<DataTable>.CreateFailureResult( "Table was empty" ); } return FallibleActionResult<DataTable>.CreateSuccessResult( table ); } /// <summary> /// Extracts a cell or a series of the html table the given path is pointing to. /// If the path points to the table element itself instead of a cell the whole table will be /// extracted. /// The series to be extracted is always arranged in a column (independed of the original layout /// in the html table). The first column contains the values, the second the series header (if /// any defined). The series name is stored in the ColumnName of the first column. /// <remarks> /// Returns null if table not found by path. Currently we cannot handle thead /// and tfoot. /// </remarks> /// </summary> /// <param name="path">points to a cell or the body of a table (pointers to TR elements are invalid)</param> /// <param name="doc">the HTML document</param> /// <param name="htmlSettings">the HTML settings used to configure the extraction process</param> /// <param name="tableSettings">the table specific configuration</param> public static FallibleActionResult<DataTable> ExtractTable( this IHtmlDocument doc, HtmlPath path, TableExtractionSettings tableSettings, HtmlExtractionSettings htmlSettings ) { if ( !path.PointsToTable && !path.PointsToTableCell ) { throw new InvalidExpressionException( "Path neither points to table nor to cell" ); } FallibleActionResult<DataTable> result = ExtractTable( doc, path, !htmlSettings.ExtractLinkUrl ); if ( !result.Success ) { // pass throu failure result return result; } // path points to whole table => return whole table if ( path.PointsToTable ) { return result; } // get the x,y position of the cell the path is pointing to Point cellCoords = path.GetTableCellPosition(); if ( cellCoords.X < 0 || cellCoords.Y < 0 ) { throw new InvalidExpressionException( "Path expression corrupt: cell position in table could not be calculated" ); } // get the value of the raw cell. extract the link url if configured. Func<object, object> GetValue = e => { if ( htmlSettings.ExtractLinkUrl ) { return ((IHtmlElement)e).FirstLinkOrInnerText(); } else { return e; } }; var t = result.Value.ExtractSeries( cellCoords, GetValue, tableSettings ); if ( t == null ) { return FallibleActionResult<DataTable>.CreateFailureResult( "Could not extract series specified" ); } return FallibleActionResult<DataTable>.CreateSuccessResult( t ); } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Searchservice { using Microsoft.Rest; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Indexers operations. /// </summary> public partial interface IIndexers { /// <summary> /// Resets the change tracking state associated with an Azure Search /// indexer. /// <see href="https://msdn.microsoft.com/library/azure/dn946897.aspx" /> /// </summary> /// <param name='indexerName'> /// The name of the indexer to reset. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse> ResetWithHttpMessagesAsync(string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Runs an Azure Search indexer on-demand. /// <see href="https://msdn.microsoft.com/library/azure/dn946885.aspx" /> /// </summary> /// <param name='indexerName'> /// The name of the indexer to run. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse> RunWithHttpMessagesAsync(string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates a new Azure Search indexer or updates an indexer if it /// already exists. /// <see href="https://msdn.microsoft.com/library/azure/dn946899.aspx" /> /// </summary> /// <param name='indexerName'> /// The name of the indexer to create or update. /// </param> /// <param name='indexer'> /// The definition of the indexer to create or update. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse<Indexer>> CreateOrUpdateWithHttpMessagesAsync(string indexerName, Indexer indexer, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes an Azure Search indexer. /// <see href="https://msdn.microsoft.com/library/azure/dn946898.aspx" /> /// </summary> /// <param name='indexerName'> /// The name of the indexer to delete. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse> DeleteWithHttpMessagesAsync(string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Retrieves an indexer definition from Azure Search. /// <see href="https://msdn.microsoft.com/library/azure/dn946874.aspx" /> /// </summary> /// <param name='indexerName'> /// The name of the indexer to retrieve. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse<Indexer>> GetWithHttpMessagesAsync(string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all indexers available for an Azure Search service. /// <see href="https://msdn.microsoft.com/library/azure/dn946883.aspx" /> /// </summary> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse<IndexerListResult>> ListWithHttpMessagesAsync(SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates a new Azure Search indexer. /// <see href="https://msdn.microsoft.com/library/azure/dn946899.aspx" /> /// </summary> /// <param name='indexer'> /// The definition of the indexer to create. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse<Indexer>> CreateWithHttpMessagesAsync(Indexer indexer, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns the current status and execution history of an indexer. /// <see href="https://msdn.microsoft.com/library/azure/dn946884.aspx" /> /// </summary> /// <param name='indexerName'> /// The name of the indexer for which to retrieve status. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse<IndexerExecutionInfo>> GetStatusWithHttpMessagesAsync(string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
//Copyright 2014 Spin Services Limited //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. // ------------------------------------------------------------------------------ // <auto-generated> // This code was generated by SpecFlow (http://www.specflow.org/). // SpecFlow Version:1.9.0.77 // SpecFlow Generator Version:1.9.0.0 // Runtime Version:4.0.30319.18444 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> // ------------------------------------------------------------------------------ #region Designer generated code #pragma warning disable namespace SS.Integration.Adapter.Specs { using TechTalk.SpecFlow; [System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "1.9.0.77")] [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [NUnit.Framework.TestFixtureAttribute()] [NUnit.Framework.DescriptionAttribute("MarketFilters")] public partial class MarketFiltersFeature { private static TechTalk.SpecFlow.ITestRunner testRunner; #line 1 "MarketFilters.feature" #line hidden [NUnit.Framework.TestFixtureSetUpAttribute()] public virtual void FeatureSetup() { testRunner = TechTalk.SpecFlow.TestRunnerManager.GetTestRunner(); TechTalk.SpecFlow.FeatureInfo featureInfo = new TechTalk.SpecFlow.FeatureInfo(new System.Globalization.CultureInfo("en-US"), "MarketFilters", "In order to avoid redundant updates\t\r\nI want to be able to filter updates that ha" + "ven\'t change a market state", ProgrammingLanguage.CSharp, ((string[])(null))); testRunner.OnFeatureStart(featureInfo); } [NUnit.Framework.TestFixtureTearDownAttribute()] public virtual void FeatureTearDown() { testRunner.OnFeatureEnd(); testRunner = null; } [NUnit.Framework.SetUpAttribute()] public virtual void TestInitialize() { } [NUnit.Framework.TearDownAttribute()] public virtual void ScenarioTearDown() { testRunner.OnScenarioEnd(); } public virtual void ScenarioSetup(TechTalk.SpecFlow.ScenarioInfo scenarioInfo) { testRunner.OnScenarioStart(scenarioInfo); } public virtual void ScenarioCleanup() { testRunner.CollectScenarioErrors(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Market has 3 active selections")] public virtual void MarketHas3ActiveSelections() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Market has 3 active selections", ((string[])(null))); #line 5 this.ScenarioSetup(scenarioInfo); #line hidden TechTalk.SpecFlow.Table table1 = new TechTalk.SpecFlow.Table(new string[] { "Id", "Name", "Status", "Tradable"}); table1.AddRow(new string[] { "1", "Home", "1", "true"}); table1.AddRow(new string[] { "2", "Away", "1", "true"}); table1.AddRow(new string[] { "3", "Draw", "1", "true"}); #line 6 testRunner.Given("Market with the following selections", ((string)(null)), table1, "Given "); #line 11 testRunner.When("Market filters are initiated", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 12 testRunner.Then("Market IsSuspended is false", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line hidden this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Market has 3 suspended selections")] public virtual void MarketHas3SuspendedSelections() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Market has 3 suspended selections", ((string[])(null))); #line 14 this.ScenarioSetup(scenarioInfo); #line hidden TechTalk.SpecFlow.Table table2 = new TechTalk.SpecFlow.Table(new string[] { "Id", "Name", "Status", "Tradable"}); table2.AddRow(new string[] { "1", "Home", "1", "false"}); table2.AddRow(new string[] { "2", "Away", "1", "false"}); table2.AddRow(new string[] { "3", "Draw", "1", "false"}); #line 15 testRunner.Given("Market with the following selections", ((string)(null)), table2, "Given "); #line 20 testRunner.When("Market filters are initiated", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 21 testRunner.And("Market filters are applied", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 22 testRunner.Then("Market IsSuspended is true", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line hidden this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Market update was rolled back")] public virtual void MarketUpdateWasRolledBack() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Market update was rolled back", ((string[])(null))); #line 24 this.ScenarioSetup(scenarioInfo); #line hidden TechTalk.SpecFlow.Table table3 = new TechTalk.SpecFlow.Table(new string[] { "Id", "Name", "Status", "Tradable"}); table3.AddRow(new string[] { "1", "Home", "1", "false"}); table3.AddRow(new string[] { "2", "Away", "1", "false"}); table3.AddRow(new string[] { "3", "Draw", "1", "false"}); #line 25 testRunner.Given("Market with the following selections", ((string)(null)), table3, "Given "); #line 30 testRunner.When("Market filters are initiated", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 31 testRunner.And("Market filters are applied", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden TechTalk.SpecFlow.Table table4 = new TechTalk.SpecFlow.Table(new string[] { "Id", "Name", "Status", "Tradable"}); table4.AddRow(new string[] { "1", "Home", "0", "false"}); table4.AddRow(new string[] { "2", "Away", "0", "false"}); table4.AddRow(new string[] { "3", "Draw", "0", "false"}); #line 32 testRunner.And("Update Arrives", ((string)(null)), table4, "And "); #line 37 testRunner.And("Market filters are applied", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 38 testRunner.And("Rollback change", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden TechTalk.SpecFlow.Table table5 = new TechTalk.SpecFlow.Table(new string[] { "Id", "Name", "Status", "Tradable"}); table5.AddRow(new string[] { "1", "Home", "0", "false"}); table5.AddRow(new string[] { "2", "Away", "0", "false"}); table5.AddRow(new string[] { "3", "Draw", "0", "false"}); #line 39 testRunner.And("Update Arrives", ((string)(null)), table5, "And "); #line 44 testRunner.And("Market filters are applied", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 45 testRunner.And("Commit change", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 46 testRunner.Then("Market with id=TestId is not removed from snapshot", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line 47 testRunner.And("Market IsSuspended is true", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Market receives duplicated update after the first update was commited")] public virtual void MarketReceivesDuplicatedUpdateAfterTheFirstUpdateWasCommited() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Market receives duplicated update after the first update was commited", ((string[])(null))); #line 49 this.ScenarioSetup(scenarioInfo); #line hidden TechTalk.SpecFlow.Table table6 = new TechTalk.SpecFlow.Table(new string[] { "Id", "Name", "Status", "Tradable"}); table6.AddRow(new string[] { "1", "Home", "0", "false"}); table6.AddRow(new string[] { "2", "Away", "0", "false"}); table6.AddRow(new string[] { "3", "Draw", "0", "false"}); #line 50 testRunner.Given("Market with the following selections", ((string)(null)), table6, "Given "); #line 55 testRunner.When("Market filters are initiated", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 56 testRunner.And("Market filters are applied", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 57 testRunner.And("Commit change", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden TechTalk.SpecFlow.Table table7 = new TechTalk.SpecFlow.Table(new string[] { "Id", "Name", "Status", "Tradable"}); table7.AddRow(new string[] { "1", "Home", "0", "false"}); table7.AddRow(new string[] { "2", "Away", "0", "false"}); table7.AddRow(new string[] { "3", "Draw", "0", "false"}); #line 58 testRunner.And("Update Arrives", ((string)(null)), table7, "And "); #line 63 testRunner.And("Market filters are applied", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 64 testRunner.Then("Market with id=TestId is removed from snapshot", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line hidden this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Market initially has all selections active and later recieved an update with susp" + "ended selection")] public virtual void MarketInitiallyHasAllSelectionsActiveAndLaterRecievedAnUpdateWithSuspendedSelection() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Market initially has all selections active and later recieved an update with susp" + "ended selection", ((string[])(null))); #line 67 this.ScenarioSetup(scenarioInfo); #line hidden TechTalk.SpecFlow.Table table8 = new TechTalk.SpecFlow.Table(new string[] { "Id", "Name", "Status", "Tradable"}); table8.AddRow(new string[] { "1", "Home", "1", "true"}); table8.AddRow(new string[] { "2", "Away", "1", "true"}); table8.AddRow(new string[] { "3", "Draw", "1", "true"}); #line 68 testRunner.Given("Market with the following selections", ((string)(null)), table8, "Given "); #line 73 testRunner.When("Market filters are initiated", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 74 testRunner.And("Market filters are applied", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 75 testRunner.And("Commit change", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden TechTalk.SpecFlow.Table table9 = new TechTalk.SpecFlow.Table(new string[] { "Id", "Name", "Status", "Tradable"}); table9.AddRow(new string[] { "2", "Away", "1", "false"}); #line 76 testRunner.And("Update Arrives", ((string)(null)), table9, "And "); #line 79 testRunner.And("Market filters are applied", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 80 testRunner.Then("Market IsSuspended is false", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line hidden this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Market initially has all selections active and later receives update making it al" + "l suspended")] public virtual void MarketInitiallyHasAllSelectionsActiveAndLaterReceivesUpdateMakingItAllSuspended() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Market initially has all selections active and later receives update making it al" + "l suspended", ((string[])(null))); #line 82 this.ScenarioSetup(scenarioInfo); #line hidden TechTalk.SpecFlow.Table table10 = new TechTalk.SpecFlow.Table(new string[] { "Id", "Name", "Status", "Tradable"}); table10.AddRow(new string[] { "1", "Home", "1", "true"}); table10.AddRow(new string[] { "2", "Away", "1", "true"}); table10.AddRow(new string[] { "3", "Draw", "1", "true"}); #line 83 testRunner.Given("Market with the following selections", ((string)(null)), table10, "Given "); #line 88 testRunner.When("Market filters are initiated", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 89 testRunner.And("Market filters are applied", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 90 testRunner.And("Commit change", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden TechTalk.SpecFlow.Table table11 = new TechTalk.SpecFlow.Table(new string[] { "Id", "Name", "Status", "Tradable"}); table11.AddRow(new string[] { "1", "Home", "1", "false"}); table11.AddRow(new string[] { "2", "Away", "1", "false"}); table11.AddRow(new string[] { "3", "Draw", "1", "false"}); #line 91 testRunner.And("Update Arrives", ((string)(null)), table11, "And "); #line 96 testRunner.And("Market filters are applied", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 97 testRunner.Then("Market IsSuspended is true", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line hidden this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Market becomes partially void")] public virtual void MarketBecomesPartiallyVoid() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Market becomes partially void", ((string[])(null))); #line 99 this.ScenarioSetup(scenarioInfo); #line hidden TechTalk.SpecFlow.Table table12 = new TechTalk.SpecFlow.Table(new string[] { "Id", "Name", "Status", "Tradable"}); table12.AddRow(new string[] { "1", "Home", "1", "true"}); table12.AddRow(new string[] { "2", "Away", "1", "true"}); table12.AddRow(new string[] { "3", "Draw", "1", "true"}); #line 100 testRunner.Given("Market with the following selections", ((string)(null)), table12, "Given "); #line 105 testRunner.When("Market filters are initiated", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line hidden TechTalk.SpecFlow.Table table13 = new TechTalk.SpecFlow.Table(new string[] { "Id", "Name", "Status", "Tradable"}); table13.AddRow(new string[] { "1", "Home", "3", "false"}); table13.AddRow(new string[] { "2", "Away", "1", "true"}); table13.AddRow(new string[] { "3", "Draw", "3", "false"}); #line 106 testRunner.And("Update Arrives", ((string)(null)), table13, "And "); #line 111 testRunner.Then("Market IsSuspended is false", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line hidden this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Market becomes partially void and is suspended")] public virtual void MarketBecomesPartiallyVoidAndIsSuspended() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Market becomes partially void and is suspended", ((string[])(null))); #line 113 this.ScenarioSetup(scenarioInfo); #line hidden TechTalk.SpecFlow.Table table14 = new TechTalk.SpecFlow.Table(new string[] { "Id", "Name", "Status", "Tradable"}); table14.AddRow(new string[] { "1", "Home", "1", "true"}); table14.AddRow(new string[] { "2", "Away", "1", "true"}); table14.AddRow(new string[] { "3", "Draw", "1", "true"}); #line 114 testRunner.Given("Market with the following selections", ((string)(null)), table14, "Given "); #line 119 testRunner.When("Market filters are initiated", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 120 testRunner.And("Market filters are applied", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 121 testRunner.And("Commit change", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden TechTalk.SpecFlow.Table table15 = new TechTalk.SpecFlow.Table(new string[] { "Id", "Name", "Status", "Tradable"}); table15.AddRow(new string[] { "1", "Home", "3", "false"}); table15.AddRow(new string[] { "2", "Away", "1", "false"}); table15.AddRow(new string[] { "3", "Draw", "3", "false"}); #line 122 testRunner.And("Update Arrives", ((string)(null)), table15, "And "); #line 127 testRunner.And("Market filters are applied", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 128 testRunner.Then("Market IsSuspended is true", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line hidden this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Market is partially settled")] public virtual void MarketIsPartiallySettled() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Market is partially settled", ((string[])(null))); #line 130 this.ScenarioSetup(scenarioInfo); #line hidden TechTalk.SpecFlow.Table table16 = new TechTalk.SpecFlow.Table(new string[] { "Id", "Name", "Status", "Tradable"}); table16.AddRow(new string[] { "1", "Home", "1", "true"}); table16.AddRow(new string[] { "2", "Away", "1", "true"}); table16.AddRow(new string[] { "3", "Draw", "0", "false"}); #line 131 testRunner.Given("Market with the following selections", ((string)(null)), table16, "Given "); #line 136 testRunner.When("Market filters are initiated", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 137 testRunner.And("Market filters are applied", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 138 testRunner.And("Commit change", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden TechTalk.SpecFlow.Table table17 = new TechTalk.SpecFlow.Table(new string[] { "Id", "Name", "Status", "Tradable", "Price"}); table17.AddRow(new string[] { "1", "Home", "2", "false", "1.0"}); table17.AddRow(new string[] { "2", "Away", "2", "false", "0"}); #line 139 testRunner.And("Update Arrives", ((string)(null)), table17, "And "); #line 143 testRunner.And("Market filters are applied", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 144 testRunner.And("Commit change", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden TechTalk.SpecFlow.Table table18 = new TechTalk.SpecFlow.Table(new string[] { "Id", "Name", "Status", "Tradable", "Price"}); table18.AddRow(new string[] { "1", "Home", "2", "false", "1.0"}); table18.AddRow(new string[] { "2", "Away", "2", "false", "0"}); table18.AddRow(new string[] { "3", "Draw", "2", "false", "0"}); #line 145 testRunner.And("Update Arrives", ((string)(null)), table18, "And "); #line 150 testRunner.And("Market filters are applied", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 151 testRunner.And("Commit change", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 152 testRunner.Then("Market with id=TestId is not removed from snapshot", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line hidden this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Voiding markets should not be applied markets that were previously active")] public virtual void VoidingMarketsShouldNotBeAppliedMarketsThatWerePreviouslyActive() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Voiding markets should not be applied markets that were previously active", ((string[])(null))); #line 154 this.ScenarioSetup(scenarioInfo); #line hidden TechTalk.SpecFlow.Table table19 = new TechTalk.SpecFlow.Table(new string[] { "Id", "Name", "Status", "Tradable"}); table19.AddRow(new string[] { "1", "Home", "1", "true"}); table19.AddRow(new string[] { "2", "Away", "1", "true"}); table19.AddRow(new string[] { "3", "Draw", "1", "true"}); #line 155 testRunner.Given("Market with the following selections", ((string)(null)), table19, "Given "); #line 160 testRunner.When("Market filters are initiated", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 161 testRunner.And("Market filters are applied", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 162 testRunner.And("Fixture is over", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 163 testRunner.And("Market filters are applied", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 164 testRunner.Then("Market Voided=false", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line hidden this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Voiding markets should be applied to markets which have never been active")] public virtual void VoidingMarketsShouldBeAppliedToMarketsWhichHaveNeverBeenActive() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Voiding markets should be applied to markets which have never been active", ((string[])(null))); #line 166 this.ScenarioSetup(scenarioInfo); #line hidden TechTalk.SpecFlow.Table table20 = new TechTalk.SpecFlow.Table(new string[] { "Id", "Name", "Status", "Tradable"}); table20.AddRow(new string[] { "1", "Home", "0", "false"}); table20.AddRow(new string[] { "2", "Away", "0", "false"}); table20.AddRow(new string[] { "3", "Draw", "0", "false"}); #line 167 testRunner.Given("Market with the following selections", ((string)(null)), table20, "Given "); #line 172 testRunner.When("Market filters are initiated", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 173 testRunner.And("Market filters are applied", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 174 testRunner.And("Commit change", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 175 testRunner.And("Fixture is over", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 176 testRunner.And("Market filters are applied", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 177 testRunner.Then("Market Voided=true", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line hidden this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Voiding markets should be applied even when deleted market rule is applied")] public virtual void VoidingMarketsShouldBeAppliedEvenWhenDeletedMarketRuleIsApplied() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Voiding markets should be applied even when deleted market rule is applied", ((string[])(null))); #line 179 this.ScenarioSetup(scenarioInfo); #line hidden TechTalk.SpecFlow.Table table21 = new TechTalk.SpecFlow.Table(new string[] { "Id", "Name", "Status", "Tradable"}); table21.AddRow(new string[] { "1", "Home", "0", "false"}); table21.AddRow(new string[] { "2", "Away", "0", "false"}); table21.AddRow(new string[] { "3", "Draw", "0", "false"}); #line 180 testRunner.Given("Market with the following selections", ((string)(null)), table21, "Given "); #line 185 testRunner.When("Market filters are initiated", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line 186 testRunner.And("Market filters are applied", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 187 testRunner.And("Commit change", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 188 testRunner.And("Fixture is over", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 189 testRunner.And("Fixture has no markets", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 190 testRunner.And("Market filters are applied", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 191 testRunner.And("Commit change", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line 192 testRunner.Then("Market Voided=true", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line 193 testRunner.And("Market is not duplicated", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Market rule solver must resolve correctly any conflicts")] public virtual void MarketRuleSolverMustResolveCorrectlyAnyConflicts() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Market rule solver must resolve correctly any conflicts", ((string[])(null))); #line 195 this.ScenarioSetup(scenarioInfo); #line hidden TechTalk.SpecFlow.Table table22 = new TechTalk.SpecFlow.Table(new string[] { "Market", "Name"}); table22.AddRow(new string[] { "1", "One"}); table22.AddRow(new string[] { "2", "Two"}); table22.AddRow(new string[] { "3", "Three"}); table22.AddRow(new string[] { "4", "Four"}); table22.AddRow(new string[] { "5", "Five"}); table22.AddRow(new string[] { "6", "Six"}); table22.AddRow(new string[] { "7", "Seven"}); table22.AddRow(new string[] { "8", "Eight"}); table22.AddRow(new string[] { "9", "Nine"}); #line 196 testRunner.Given("a fixture with the following markets", ((string)(null)), table22, "Given "); #line hidden TechTalk.SpecFlow.Table table23 = new TechTalk.SpecFlow.Table(new string[] { "Rule"}); table23.AddRow(new string[] { "A"}); table23.AddRow(new string[] { "B"}); table23.AddRow(new string[] { "C"}); table23.AddRow(new string[] { "D"}); #line 207 testRunner.And("A market rule with the have the following rules", ((string)(null)), table23, "And "); #line hidden TechTalk.SpecFlow.Table table24 = new TechTalk.SpecFlow.Table(new string[] { "Rule", "Market", "Result"}); table24.AddRow(new string[] { "A", "1", "R"}); table24.AddRow(new string[] { "B", "1", "!R"}); table24.AddRow(new string[] { "C", "1", "E"}); table24.AddRow(new string[] { "D", "1", "!E"}); table24.AddRow(new string[] { "A", "2", "E"}); table24.AddRow(new string[] { "B", "2", "!E"}); table24.AddRow(new string[] { "A", "3", "R"}); table24.AddRow(new string[] { "B", "3", "E"}); table24.AddRow(new string[] { "A", "4", "!E"}); table24.AddRow(new string[] { "B", "4", "R"}); table24.AddRow(new string[] { "A", "5", "E"}); table24.AddRow(new string[] { "B", "5", "E"}); table24.AddRow(new string[] { "A", "6", "!E"}); table24.AddRow(new string[] { "B", "6", "!R"}); table24.AddRow(new string[] { "A", "7", "E"}); table24.AddRow(new string[] { "B", "7", "E"}); table24.AddRow(new string[] { "C", "7", "!E"}); table24.AddRow(new string[] { "D", "7", "E"}); table24.AddRow(new string[] { "A", "8", "!R"}); table24.AddRow(new string[] { "B", "8", "E"}); table24.AddRow(new string[] { "A", "9", "R"}); table24.AddRow(new string[] { "B", "9", "!R"}); #line 213 testRunner.And("the market rules return the following intents", ((string)(null)), table24, "And "); #line 237 testRunner.When("I apply the rules", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line hidden TechTalk.SpecFlow.Table table25 = new TechTalk.SpecFlow.Table(new string[] { "Market", "Name", "Exists"}); table25.AddRow(new string[] { "1", "One", "true"}); table25.AddRow(new string[] { "2", "Two", "true"}); table25.AddRow(new string[] { "3", "Three - E: B", "true"}); table25.AddRow(new string[] { "4", "Four", "true"}); table25.AddRow(new string[] { "5", "Five - E: A - E: B", "true"}); table25.AddRow(new string[] { "6", "Six", "true"}); table25.AddRow(new string[] { "7", "Seven", "true"}); table25.AddRow(new string[] { "8", "Eight - E: B", "true"}); table25.AddRow(new string[] { "9", "Nine", "true"}); #line 238 testRunner.Then("I must see these changes", ((string)(null)), table25, "Then "); #line hidden this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Market rule solver must resolve correctly any edit conflicts")] public virtual void MarketRuleSolverMustResolveCorrectlyAnyEditConflicts() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Market rule solver must resolve correctly any edit conflicts", ((string[])(null))); #line 251 this.ScenarioSetup(scenarioInfo); #line hidden TechTalk.SpecFlow.Table table26 = new TechTalk.SpecFlow.Table(new string[] { "Market", "Name", "Selections"}); table26.AddRow(new string[] { "1", "One", "3"}); table26.AddRow(new string[] { "2", "Two", "2"}); table26.AddRow(new string[] { "3", "Three", "1"}); table26.AddRow(new string[] { "4", "Four", "1"}); table26.AddRow(new string[] { "5", "Five", "0"}); table26.AddRow(new string[] { "6", "Six", "0"}); table26.AddRow(new string[] { "7", "Seven", "0"}); #line 252 testRunner.Given("a fixture with the following markets", ((string)(null)), table26, "Given "); #line hidden TechTalk.SpecFlow.Table table27 = new TechTalk.SpecFlow.Table(new string[] { "Rule"}); table27.AddRow(new string[] { "A"}); table27.AddRow(new string[] { "B"}); table27.AddRow(new string[] { "C"}); table27.AddRow(new string[] { "D"}); #line 261 testRunner.And("A market rule with the have the following rules", ((string)(null)), table27, "And "); #line hidden TechTalk.SpecFlow.Table table28 = new TechTalk.SpecFlow.Table(new string[] { "Rule", "Market", "Result"}); table28.AddRow(new string[] { "A", "1", "CS"}); table28.AddRow(new string[] { "B", "1", "AS"}); table28.AddRow(new string[] { "C", "1", "RS"}); table28.AddRow(new string[] { "D", "1", "CD"}); table28.AddRow(new string[] { "A", "2", "CS"}); table28.AddRow(new string[] { "B", "2", "RS"}); table28.AddRow(new string[] { "A", "3", "CS"}); table28.AddRow(new string[] { "B", "3", "CD"}); table28.AddRow(new string[] { "A", "4", "AS"}); table28.AddRow(new string[] { "B", "4", "RS"}); table28.AddRow(new string[] { "A", "5", "AS"}); table28.AddRow(new string[] { "B", "5", "CD"}); table28.AddRow(new string[] { "A", "6", "CD"}); table28.AddRow(new string[] { "B", "6", "RS"}); table28.AddRow(new string[] { "A", "7", "RS"}); table28.AddRow(new string[] { "B", "7", "RS"}); #line 267 testRunner.And("the market rules return the following intents", ((string)(null)), table28, "And "); #line 285 testRunner.When("I apply the rules", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line hidden TechTalk.SpecFlow.Table table29 = new TechTalk.SpecFlow.Table(new string[] { "Market", "Name", "NumberOfSelections", "Names"}); table29.AddRow(new string[] { "1", "OneD", "4", "One1A, One2A, One3A, One4B"}); table29.AddRow(new string[] { "2", "Two", "2", "Two1A, Two2A"}); table29.AddRow(new string[] { "3", "ThreeB", "1", "Three1A"}); table29.AddRow(new string[] { "4", "Four", "1", "Four1A"}); table29.AddRow(new string[] { "5", "FiveB", "1", "Five1A"}); table29.AddRow(new string[] { "6", "SixA", "0", ""}); table29.AddRow(new string[] { "7", "Seven", "0", ""}); #line 286 testRunner.Then("I must see these selection changes", ((string)(null)), table29, "Then "); #line hidden this.ScenarioCleanup(); } } } #pragma warning restore #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. using Xunit; namespace System.SpanTests { public static partial class ReadOnlySpanTests { [Fact] public static void ZeroLengthIndexOfAny_TwoInteger() { var sp = new ReadOnlySpan<int>(Array.Empty<int>()); int idx = sp.IndexOfAny(0, 0); Assert.Equal(-1, idx); } [Fact] public static void DefaultFilledIndexOfAny_TwoInteger() { var rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { var a = new int[length]; var span = new ReadOnlySpan<int>(a); int[] targets = { default, 99 }; for (int i = 0; i < length; i++) { int index = rnd.Next(0, 2) == 0 ? 0 : 1; int target0 = targets[index]; int target1 = targets[(index + 1) % 2]; int idx = span.IndexOfAny(target0, target1); Assert.Equal(0, idx); } } } [Fact] public static void TestMatchIndexOfAny_TwoInteger() { var rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { var a = new int[length]; for (int i = 0; i < length; i++) { a[i] = i + 1; } var span = new ReadOnlySpan<int>(a); for (int targetIndex = 0; targetIndex < length; targetIndex++) { int target0 = a[targetIndex]; int target1 = 0; int idx = span.IndexOfAny(target0, target1); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 1; targetIndex++) { int index = rnd.Next(0, 2) == 0 ? 0 : 1; int target0 = a[targetIndex + index]; int target1 = a[targetIndex + (index + 1) % 2]; int idx = span.IndexOfAny(target0, target1); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length; targetIndex++) { int target0 = 0; int target1 = a[targetIndex]; int idx = span.IndexOfAny(target0, target1); Assert.Equal(targetIndex, idx); } } } [Fact] public static void TestNoMatchIndexOfAny_TwoInteger() { var rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { var a = new int[length]; int target0 = rnd.Next(1, 256); int target1 = rnd.Next(1, 256); var span = new ReadOnlySpan<int>(a); int idx = span.IndexOfAny(target0, target1); Assert.Equal(-1, idx); } } [Fact] public static void TestMultipleMatchIndexOfAny_TwoInteger() { for (int length = 3; length < byte.MaxValue; length++) { var a = new int[length]; for (int i = 0; i < length; i++) { int val = i + 1; a[i] = val == 200 ? 201 : val; } a[length - 1] = 200; a[length - 2] = 200; a[length - 3] = 200; var span = new ReadOnlySpan<int>(a); int idx = span.IndexOfAny(200, 200); Assert.Equal(length - 3, idx); } } [Fact] public static void MakeSureNoChecksGoOutOfRangeIndexOfAny_TwoInteger() { for (int length = 1; length < byte.MaxValue; length++) { var a = new int[length + 2]; a[0] = 99; a[length + 1] = 98; var span = new ReadOnlySpan<int>(a, 1, length - 1); int index = span.IndexOfAny(99, 98); Assert.Equal(-1, index); } for (int length = 1; length < byte.MaxValue; length++) { var a = new int[length + 2]; a[0] = 99; a[length + 1] = 99; var span = new ReadOnlySpan<int>(a, 1, length - 1); int index = span.IndexOfAny(99, 99); Assert.Equal(-1, index); } } [Fact] public static void ZeroLengthIndexOfAny_ThreeInteger() { var sp = new ReadOnlySpan<int>(Array.Empty<int>()); int idx = sp.IndexOfAny(0, 0, 0); Assert.Equal(-1, idx); } [Fact] public static void DefaultFilledIndexOfAny_ThreeInteger() { var rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { var a = new int[length]; var span = new ReadOnlySpan<int>(a); int[] targets = { default, 99, 98 }; for (int i = 0; i < length; i++) { int index = rnd.Next(0, 3); int target0 = targets[index]; int target1 = targets[(index + 1) % 2]; int target2 = targets[(index + 1) % 3]; int idx = span.IndexOfAny(target0, target1, target2); Assert.Equal(0, idx); } } } [Fact] public static void TestMatchIndexOfAny_ThreeInteger() { var rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { var a = new int[length]; for (int i = 0; i < length; i++) { a[i] = i + 1; } var span = new ReadOnlySpan<int>(a); for (int targetIndex = 0; targetIndex < length; targetIndex++) { int target0 = a[targetIndex]; int target1 = 0; int target2 = 0; int idx = span.IndexOfAny(target0, target1, target2); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 2; targetIndex++) { int index = rnd.Next(0, 3); int target0 = a[targetIndex + index]; int target1 = a[targetIndex + (index + 1) % 2]; int target2 = a[targetIndex + (index + 1) % 3]; int idx = span.IndexOfAny(target0, target1, target2); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length; targetIndex++) { int target0 = 0; int target1 = 0; int target2 = a[targetIndex]; int idx = span.IndexOfAny(target0, target1, target2); Assert.Equal(targetIndex, idx); } } } [Fact] public static void TestNoMatchIndexOfAny_ThreeInteger() { var rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { var a = new int[length]; int target0 = rnd.Next(1, 256); int target1 = rnd.Next(1, 256); int target2 = rnd.Next(1, 256); var span = new ReadOnlySpan<int>(a); int idx = span.IndexOfAny(target0, target1, target2); Assert.Equal(-1, idx); } } [Fact] public static void TestMultipleMatchIndexOfAny_ThreeInteger() { for (int length = 4; length < byte.MaxValue; length++) { var a = new int[length]; for (int i = 0; i < length; i++) { int val = i + 1; a[i] = val == 200 ? 201 : val; } a[length - 1] = 200; a[length - 2] = 200; a[length - 3] = 200; a[length - 4] = 200; var span = new ReadOnlySpan<int>(a); int idx = span.IndexOfAny(200, 200, 200); Assert.Equal(length - 4, idx); } } [Fact] public static void MakeSureNoChecksGoOutOfRangeIndexOfAny_ThreeInteger() { for (int length = 1; length < byte.MaxValue; length++) { var a = new int[length + 2]; a[0] = 99; a[length + 1] = 98; var span = new ReadOnlySpan<int>(a, 1, length - 1); int index = span.IndexOfAny(99, 98, 99); Assert.Equal(-1, index); } for (int length = 1; length < byte.MaxValue; length++) { var a = new int[length + 2]; a[0] = 99; a[length + 1] = 99; var span = new ReadOnlySpan<int>(a, 1, length - 1); int index = span.IndexOfAny(99, 99, 99); Assert.Equal(-1, index); } } [Fact] public static void ZeroLengthIndexOfAny_ManyInteger() { var sp = new ReadOnlySpan<int>(Array.Empty<int>()); var values = new ReadOnlySpan<int>(new int[] { 0, 0, 0, 0 }); int idx = sp.IndexOfAny(values); Assert.Equal(-1, idx); values = new ReadOnlySpan<int>(new int[] { }); idx = sp.IndexOfAny(values); Assert.Equal(-1, idx); } [Fact] public static void DefaultFilledIndexOfAny_ManyInteger() { for (int length = 0; length < byte.MaxValue; length++) { var a = new int[length]; var span = new ReadOnlySpan<int>(a); var values = new ReadOnlySpan<int>(new int[] { default, 99, 98, 0 }); for (int i = 0; i < length; i++) { int idx = span.IndexOfAny(values); Assert.Equal(0, idx); } } } [Fact] public static void TestMatchIndexOfAny_ManyInteger() { var rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { var a = new int[length]; for (int i = 0; i < length; i++) { a[i] = i + 1; } var span = new ReadOnlySpan<int>(a); for (int targetIndex = 0; targetIndex < length; targetIndex++) { var values = new ReadOnlySpan<int>(new int[] { a[targetIndex], 0, 0, 0 }); int idx = span.IndexOfAny(values); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 3; targetIndex++) { int index = rnd.Next(0, 4) == 0 ? 0 : 1; var values = new ReadOnlySpan<int>(new int[] { a[targetIndex + index], a[targetIndex + (index + 1) % 2], a[targetIndex + (index + 1) % 3], a[targetIndex + (index + 1) % 4] }); int idx = span.IndexOfAny(values); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length; targetIndex++) { var values = new ReadOnlySpan<int>(new int[] { 0, 0, 0, a[targetIndex] }); int idx = span.IndexOfAny(values); Assert.Equal(targetIndex, idx); } } } [Fact] public static void TestMatchValuesLargerIndexOfAny_ManyInteger() { var rnd = new Random(42); for (int length = 2; length < byte.MaxValue; length++) { var a = new int[length]; int expectedIndex = length / 2; for (int i = 0; i < length; i++) { if (i == expectedIndex) { continue; } a[i] = 255; } var span = new ReadOnlySpan<int>(a); var targets = new int[length * 2]; for (int i = 0; i < targets.Length; i++) { if (i == length + 1) { continue; } targets[i] = rnd.Next(1, 255); } var values = new ReadOnlySpan<int>(targets); int idx = span.IndexOfAny(values); Assert.Equal(expectedIndex, idx); } } [Fact] public static void TestNoMatchIndexOfAny_ManyInteger() { var rnd = new Random(42); for (int length = 1; length < byte.MaxValue; length++) { var a = new int[length]; var targets = new int[length]; for (int i = 0; i < targets.Length; i++) { targets[i] = rnd.Next(1, 256); } var span = new ReadOnlySpan<int>(a); var values = new ReadOnlySpan<int>(targets); int idx = span.IndexOfAny(values); Assert.Equal(-1, idx); } } [Fact] public static void TestNoMatchValuesLargerIndexOfAny_ManyInteger() { var rnd = new Random(42); for (int length = 1; length < byte.MaxValue; length++) { var a = new int[length]; var targets = new int[length * 2]; for (int i = 0; i < targets.Length; i++) { targets[i] = rnd.Next(1, 256); } var span = new ReadOnlySpan<int>(a); var values = new ReadOnlySpan<int>(targets); int idx = span.IndexOfAny(values); Assert.Equal(-1, idx); } } [Fact] public static void TestMultipleMatchIndexOfAny_ManyInteger() { for (int length = 5; length < byte.MaxValue; length++) { var a = new int[length]; for (int i = 0; i < length; i++) { int val = i + 1; a[i] = val == 200 ? 201 : val; } a[length - 1] = 200; a[length - 2] = 200; a[length - 3] = 200; a[length - 4] = 200; a[length - 5] = 200; var span = new ReadOnlySpan<int>(a); var values = new ReadOnlySpan<int>(new int[] { 200, 200, 200, 200, 200, 200, 200, 200, 200 }); int idx = span.IndexOfAny(values); Assert.Equal(length - 5, idx); } } [Fact] public static void MakeSureNoChecksGoOutOfRangeIndexOfAny_ManyInteger() { for (int length = 1; length < byte.MaxValue; length++) { var a = new int[length + 2]; a[0] = 99; a[length + 1] = 98; var span = new ReadOnlySpan<int>(a, 1, length - 1); var values = new ReadOnlySpan<int>(new int[] { 99, 98, 99, 98, 99, 98 }); int index = span.IndexOfAny(values); Assert.Equal(-1, index); } for (int length = 1; length < byte.MaxValue; length++) { var a = new int[length + 2]; a[0] = 99; a[length + 1] = 99; var span = new ReadOnlySpan<int>(a, 1, length - 1); var values = new ReadOnlySpan<int>(new int[] { 99, 99, 99, 99, 99, 99 }); int index = span.IndexOfAny(values); Assert.Equal(-1, index); } } [Fact] public static void ZeroLengthIndexOfAny_TwoString() { var sp = new ReadOnlySpan<string>(Array.Empty<string>()); int idx = sp.IndexOfAny("0", "0"); Assert.Equal(-1, idx); } [Fact] public static void DefaultFilledIndexOfAny_TwoString() { var rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { var a = new string[length]; var tempSpan = new Span<string>(a); tempSpan.Fill(""); ReadOnlySpan<string> span = tempSpan; string[] targets = { "", "99" }; for (int i = 0; i < length; i++) { int index = rnd.Next(0, 2) == 0 ? 0 : 1; string target0 = targets[index]; string target1 = targets[(index + 1) % 2]; int idx = span.IndexOfAny(target0, target1); Assert.Equal(0, idx); } } } [Fact] public static void TestMatchIndexOfAny_TwoString() { var rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { var a = new string[length]; for (int i = 0; i < length; i++) { a[i] = (i + 1).ToString(); } var span = new ReadOnlySpan<string>(a); for (int targetIndex = 0; targetIndex < length; targetIndex++) { string target0 = a[targetIndex]; string target1 = "0"; int idx = span.IndexOfAny(target0, target1); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 1; targetIndex++) { int index = rnd.Next(0, 2) == 0 ? 0 : 1; string target0 = a[targetIndex + index]; string target1 = a[targetIndex + (index + 1) % 2]; int idx = span.IndexOfAny(target0, target1); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 1; targetIndex++) { string target0 = "0"; string target1 = a[targetIndex + 1]; int idx = span.IndexOfAny(target0, target1); Assert.Equal(targetIndex + 1, idx); } } } [Fact] public static void TestNoMatchIndexOfAny_TwoString() { var rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { var a = new string[length]; string target0 = rnd.Next(1, 256).ToString(); string target1 = rnd.Next(1, 256).ToString(); var span = new ReadOnlySpan<string>(a); int idx = span.IndexOfAny(target0, target1); Assert.Equal(-1, idx); } } [Fact] public static void TestMultipleMatchIndexOfAny_TwoString() { for (int length = 3; length < byte.MaxValue; length++) { var a = new string[length]; for (int i = 0; i < length; i++) { string val = (i + 1).ToString(); a[i] = val == "200" ? "201" : val; } a[length - 1] = "200"; a[length - 2] = "200"; a[length - 3] = "200"; var span = new ReadOnlySpan<string>(a); int idx = span.IndexOfAny("200", "200"); Assert.Equal(length - 3, idx); } } [Fact] public static void MakeSureNoChecksGoOutOfRangeIndexOfAny_TwoString() { for (int length = 1; length < byte.MaxValue; length++) { var a = new string[length + 2]; a[0] = "99"; a[length + 1] = "98"; var span = new ReadOnlySpan<string>(a, 1, length - 1); int index = span.IndexOfAny("99", "98"); Assert.Equal(-1, index); } for (int length = 1; length < byte.MaxValue; length++) { var a = new string[length + 2]; a[0] = "99"; a[length + 1] = "99"; var span = new ReadOnlySpan<string>(a, 1, length - 1); int index = span.IndexOfAny("99", "99"); Assert.Equal(-1, index); } } [Fact] public static void ZeroLengthIndexOf_ThreeString() { var sp = new ReadOnlySpan<string>(Array.Empty<string>()); int idx = sp.IndexOfAny("0", "0", "0"); Assert.Equal(-1, idx); } [Fact] public static void DefaultFilledIndexOfAny_ThreeString() { var rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { var a = new string[length]; var tempSpan = new Span<string>(a); tempSpan.Fill(""); ReadOnlySpan<string> span = tempSpan; string[] targets = { "", "99", "98" }; for (int i = 0; i < length; i++) { int index = rnd.Next(0, 3); string target0 = targets[index]; string target1 = targets[(index + 1) % 2]; string target2 = targets[(index + 1) % 3]; int idx = span.IndexOfAny(target0, target1, target2); Assert.Equal(0, idx); } } } [Fact] public static void TestMatchIndexOfAny_ThreeString() { Random rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { var a = new string[length]; for (int i = 0; i < length; i++) { a[i] = (i + 1).ToString(); } var span = new ReadOnlySpan<string>(a); for (int targetIndex = 0; targetIndex < length; targetIndex++) { string target0 = a[targetIndex]; string target1 = "0"; string target2 = "0"; int idx = span.IndexOfAny(target0, target1, target2); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 2; targetIndex++) { int index = rnd.Next(0, 3) == 0 ? 0 : 1; string target0 = a[targetIndex + index]; string target1 = a[targetIndex + (index + 1) % 2]; string target2 = a[targetIndex + (index + 1) % 3]; int idx = span.IndexOfAny(target0, target1, target2); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length; targetIndex++) { string target0 = "0"; string target1 = "0"; string target2 = a[targetIndex]; int idx = span.IndexOfAny(target0, target1, target2); Assert.Equal(targetIndex, idx); } } } [Fact] public static void TestNoMatchIndexOfAny_ThreeString() { var rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { var a = new string[length]; string target0 = rnd.Next(1, 256).ToString(); string target1 = rnd.Next(1, 256).ToString(); string target2 = rnd.Next(1, 256).ToString(); var span = new ReadOnlySpan<string>(a); int idx = span.IndexOfAny(target0, target1, target2); Assert.Equal(-1, idx); } } [Fact] public static void TestMultipleMatchIndexOfAny_ThreeString() { for (int length = 4; length < byte.MaxValue; length++) { var a = new string[length]; for (int i = 0; i < length; i++) { string val = (i + 1).ToString(); a[i] = val == "200" ? "201" : val; } a[length - 1] = "200"; a[length - 2] = "200"; a[length - 3] = "200"; a[length - 4] = "200"; var span = new ReadOnlySpan<string>(a); int idx = span.IndexOfAny("200", "200", "200"); Assert.Equal(length - 4, idx); } } [Fact] public static void MakeSureNoChecksGoOutOfRangeIndexOfAny_ThreeString() { for (int length = 1; length < byte.MaxValue; length++) { var a = new string[length + 2]; a[0] = "99"; a[length + 1] = "98"; var span = new ReadOnlySpan<string>(a, 1, length - 1); int index = span.IndexOfAny("99", "98", "99"); Assert.Equal(-1, index); } for (int length = 1; length < byte.MaxValue; length++) { var a = new string[length + 2]; a[0] = "99"; a[length + 1] = "99"; var span = new ReadOnlySpan<string>(a, 1, length - 1); int index = span.IndexOfAny("99", "99", "99"); Assert.Equal(-1, index); } } [Fact] public static void ZeroLengthIndexOfAny_ManyString() { var sp = new ReadOnlySpan<string>(Array.Empty<string>()); var values = new ReadOnlySpan<string>(new string[] { "0", "0", "0", "0" }); int idx = sp.IndexOfAny(values); Assert.Equal(-1, idx); values = new ReadOnlySpan<string>(new string[] { }); idx = sp.IndexOfAny(values); Assert.Equal(-1, idx); } [Fact] public static void DefaultFilledIndexOfAny_ManyString() { for (int length = 0; length < byte.MaxValue; length++) { var a = new string[length]; var tempSpan = new Span<string>(a); tempSpan.Fill(""); ReadOnlySpan<string> span = tempSpan; var values = new ReadOnlySpan<string>(new string[] { "", "99", "98", "0" }); for (int i = 0; i < length; i++) { int idx = span.IndexOfAny(values); Assert.Equal(0, idx); } } } [Fact] public static void TestMatchIndexOfAny_ManyString() { Random rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { var a = new string[length]; for (int i = 0; i < length; i++) { a[i] = (i + 1).ToString(); } var span = new ReadOnlySpan<string>(a); for (int targetIndex = 0; targetIndex < length; targetIndex++) { var values = new ReadOnlySpan<string>(new string[] { a[targetIndex], "0", "0", "0" }); int idx = span.IndexOfAny(values); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 3; targetIndex++) { int index = rnd.Next(0, 4) == 0 ? 0 : 1; var values = new ReadOnlySpan<string>(new string[] { a[targetIndex + index], a[targetIndex + (index + 1) % 2], a[targetIndex + (index + 1) % 3], a[targetIndex + (index + 1) % 4] }); int idx = span.IndexOfAny(values); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length; targetIndex++) { var values = new ReadOnlySpan<string>(new string[] { "0", "0", "0", a[targetIndex] }); int idx = span.IndexOfAny(values); Assert.Equal(targetIndex, idx); } } } [Fact] public static void TestMatchValuesLargerIndexOfAny_ManyString() { var rnd = new Random(42); for (int length = 2; length < byte.MaxValue; length++) { var a = new string[length]; int expectedIndex = length / 2; for (int i = 0; i < length; i++) { if (i == expectedIndex) { a[i] = "val"; continue; } a[i] = "255"; } var span = new ReadOnlySpan<string>(a); var targets = new string[length * 2]; for (int i = 0; i < targets.Length; i++) { if (i == length + 1) { targets[i] = "val"; continue; } targets[i] = rnd.Next(1, 255).ToString(); } var values = new ReadOnlySpan<string>(targets); int idx = span.IndexOfAny(values); Assert.Equal(expectedIndex, idx); } } [Fact] public static void TestNoMatchIndexOfAny_ManyString() { var rnd = new Random(42); for (int length = 1; length < byte.MaxValue; length++) { var a = new string[length]; var targets = new string[length]; for (int i = 0; i < targets.Length; i++) { targets[i] = rnd.Next(1, 256).ToString(); } var span = new ReadOnlySpan<string>(a); var values = new ReadOnlySpan<string>(targets); int idx = span.IndexOfAny(values); Assert.Equal(-1, idx); } } [Fact] public static void TestNoMatchValuesLargerIndexOfAny_ManyString() { var rnd = new Random(42); for (int length = 1; length < byte.MaxValue; length++) { var a = new string[length]; var targets = new string[length * 2]; for (int i = 0; i < targets.Length; i++) { targets[i] = rnd.Next(1, 256).ToString(); } var span = new ReadOnlySpan<string>(a); var values = new ReadOnlySpan<string>(targets); int idx = span.IndexOfAny(values); Assert.Equal(-1, idx); } } [Fact] public static void TestMultipleMatchIndexOfAny_ManyString() { for (int length = 5; length < byte.MaxValue; length++) { var a = new string[length]; for (int i = 0; i < length; i++) { string val = (i + 1).ToString(); a[i] = val == "200" ? "201" : val; } a[length - 1] = "200"; a[length - 2] = "200"; a[length - 3] = "200"; a[length - 4] = "200"; a[length - 5] = "200"; var span = new ReadOnlySpan<string>(a); var values = new ReadOnlySpan<string>(new string[] { "200", "200", "200", "200", "200", "200", "200", "200", "200" }); int idx = span.IndexOfAny(values); Assert.Equal(length - 5, idx); } } [Fact] public static void MakeSureNoChecksGoOutOfRangeIndexOfAny_ManyString() { for (int length = 1; length < byte.MaxValue; length++) { var a = new string[length + 2]; a[0] = "99"; a[length + 1] = "98"; var span = new ReadOnlySpan<string>(a, 1, length - 1); var values = new ReadOnlySpan<string>(new string[] { "99", "98", "99", "98", "99", "98" }); int index = span.IndexOfAny(values); Assert.Equal(-1, index); } for (int length = 1; length < byte.MaxValue; length++) { var a = new string[length + 2]; a[0] = "99"; a[length + 1] = "99"; var span = new ReadOnlySpan<string>(a, 1, length - 1); var values = new ReadOnlySpan<string>(new string[] { "99", "99", "99", "99", "99", "99" }); int index = span.IndexOfAny(values); Assert.Equal(-1, index); } } [Theory] [MemberData(nameof(TestHelpers.IndexOfAnyNullSequenceData), MemberType = typeof(TestHelpers))] public static void IndexOfAnyNullSequence_String(string[] spanInput, string[] searchInput, int expected) { ReadOnlySpan<string> theStrings = spanInput; Assert.Equal(expected, theStrings.IndexOfAny(searchInput)); Assert.Equal(expected, theStrings.IndexOfAny((ReadOnlySpan<string>)searchInput)); if (searchInput != null) { if (searchInput.Length >= 3) { Assert.Equal(expected, theStrings.IndexOfAny(searchInput[0], searchInput[1], searchInput[2])); } if (searchInput.Length >= 2) { Assert.Equal(expected, theStrings.IndexOfAny(searchInput[0], searchInput[1])); } } } } }
using System; using System.Collections; using OpenADK.Library; using OpenADK.Library.us.Common; using OpenADK.Library.us.Student; using OpenADK.Library.Tools.Cfg; using OpenADK.Library.Tools.Mapping; using NUnit.Framework; using Library.UnitTesting.Framework.Validation; namespace Library.Nunit.US.Library.Tools.Mapping { [TestFixture] public class SASIMappingsTests { private SifVersion fVersion = SifVersion.SIF15r1; private AgentConfig fCfg; [SetUp] public void setUp() { if( !Adk.Initialized ) { Adk.Initialize( ); } Adk.SifVersion = fVersion; fCfg = new AgentConfig(); fCfg.Read("..\\..\\Library\\Tools\\Mapping\\SASI2.0.cfg", false); } [Test] public void testStudentPersonalSIF15r1() { IDictionary values = new Hashtable(); values.Add( "PERMNUM", "9798" ); values.Add( "SOCSECNUM", "845457898" ); values.Add( "SCHOOLNUM", "999" ); values.Add( "SCHOOLNUM2", "999" ); values.Add( "GRADE", "09" ); values.Add( "HOMEROOM", "5" ); values.Add( "LASTNAME", "Doe" ); values.Add( "FIRSTNAME", "Jane" ); values.Add( "MIDDLENAME", null ); values.Add( "NICKNAME", null ); values.Add( "MAILADDR", "5845 Test Blvd" ); values.Add( "CITY", "slc" ); values.Add( "STATE", "Utah" ); values.Add( "COUNTRY", "" ); values.Add( "ZIPCODE", "84093" ); values.Add( "RESADDR", null ); values.Add( "RESCITY", null ); values.Add( "RESSTATE", null ); values.Add( "RESCOUNTRY", null ); values.Add( "RESZIPCODE", null ); values.Add( "BIRTHDATE", "20051209" ); values.Add( "GENDER", "F" ); values.Add( "ETHNICCODE", "W" ); values.Add( "ENGPROF", "" ); values.Add( "PRIMARYLNG", "" ); values.Add( "TELEPHONE", null ); StringMapAdaptor sma = new StringMapAdaptor( values ); StudentPersonal sp = new StudentPersonal(); Mappings m = fCfg.Mappings.GetMappings( "Default" ).Select( null, null, null ); m.MapOutbound( sma, sp, SifVersion.SIF15r1 ); Console.WriteLine( sp.ToXml() ); OtherIdList oil = sp.OtherIdList; bool gradeMappingFound = false; foreach ( OtherId oid in oil ) { if ( "ZZ".Equals( oid.Type ) && oid.Value.StartsWith( "GRADE" ) ) { Assertion.AssertEquals( "OtherId[@Type=ZZ]GRADE: mapping", "GRADE:09", oid.Value ); gradeMappingFound = true; } } Assertion.Assert( "GradeMapping found", gradeMappingFound ); } [Test] public void testStudentSnapshot15r1() { StringMapAdaptor sma = createStudentSnapshotFields(); StudentSnapshot ss = new StudentSnapshot(); ss.StudentPersonalRefId = Adk.MakeGuid(); ss.SnapDate = DateTime.Now; Mappings m = fCfg.Mappings.GetMappings( "Default" ).Select( null, null, null ); m .MapOutbound( sma, ss, new DefaultValueBuilder( sma ), SifVersion.SIF15r1 ); Console.WriteLine( ss.ToXml() ); int? onTimeGradYear = ss.OnTimeGraduationYear; Assertion.Assert( "onTimeGraduationYear is null", onTimeGradYear.HasValue ); Assertion.AssertEquals( "OnTimeGraduationYear", 2000, onTimeGradYear.Value ); SchemaValidator sv = USSchemaValidator.NewInstance( SifVersion.SIF15r1 ); // 3) Validate the file bool validated = sv.Validate( ss, SifVersion.SIF15r1 ); // 4) If validation failed, write the object out for tracing purposes if ( !validated ) { sv.PrintProblems( Console.Out ); Assertion.Fail( "Schema Validation Failed:" ); } } [Test] public void testStudentSnapshot15r1_Adk20r1() { Adk.SifVersion = SifVersion.SIF15r1; StringMapAdaptor sma = createStudentSnapshotFields(); StudentSnapshot ss = new StudentSnapshot(); Mappings m = fCfg.Mappings.GetMappings( "Default" ).Select( null, null, null ); m.MapOutbound( sma, ss, SifVersion.SIF20r1 ); Console.WriteLine( ss.ToXml() ); int? onTimeGradYear = ss.OnTimeGraduationYear; Assertion.Assert( "onTimeGraduationYear is null", onTimeGradYear.HasValue ); Assertion.AssertEquals( "OnTimeGraduationYear", 2000, onTimeGradYear.Value ); } [Test] public void testStudentSnapshot15r1_EmptyGradYear() { Adk.SifVersion = SifVersion.SIF15r1; StringMapAdaptor sma = createStudentSnapshotFields(); // SASI Expects that an empty string in a grad year // field will not produce an error, but rather an empty element sma.Dictionary[ "ORIGYRGRAD"] = "" ; StudentSnapshot ss = new StudentSnapshot(); Mappings m = fCfg.Mappings.GetMappings( "Default" ).Select( null, null, null ); m.MapOutbound( sma, ss, SifVersion.SIF15r1 ); Console.WriteLine( ss.ToXml() ); int? onTimeGradYear = ss.OnTimeGraduationYear; Assertion.Assert( "onTimeGraduationYear is not null", !onTimeGradYear.HasValue ); } [Test] public void testStudentSnapshot20_EmptyGradYear() { Adk.SifVersion = SifVersion.LATEST; StringMapAdaptor sma = createStudentSnapshotFields(); // SASI Expects that an empty string in a grad year // field will not produce an error, but rather an empty element sma.Dictionary[ "ORIGYRGRAD" ] = "" ; StudentSnapshot ss = new StudentSnapshot(); Mappings m = fCfg.Mappings.GetMappings( "Default" ).Select( null, null, null ); m.MapOutbound( sma, ss, SifVersion.LATEST ); Console.WriteLine( ss.ToXml() ); int? onTimeGradYear = ss.OnTimeGraduationYear; Assertion.Assert( "onTimeGraduationYear is not null", !onTimeGradYear.HasValue ); } [Test] public void testStudentSnapshot15r1_BlankGradYear() { Adk.SifVersion = SifVersion.SIF15r1; StringMapAdaptor sma = createStudentSnapshotFields(); // SASI Expects that a single space character in a grad year // field will not produce an error, but rather an empty element sma.Dictionary[ "ORIGYRGRAD" ] = " " ; StudentSnapshot ss = new StudentSnapshot(); Mappings m = fCfg.Mappings.GetMappings( "Default" ).Select( null, null, null ); m.MapOutbound( sma, ss, SifVersion.SIF15r1 ); Console.WriteLine( ss.ToXml() ); int? onTimeGradYear = ss.OnTimeGraduationYear; Assertion.Assert( "onTimeGraduationYear is not null", !onTimeGradYear.HasValue ); } [Test] public void testStudentSnapshot20_BlankGradYear() { Adk.SifVersion = SifVersion.LATEST; StringMapAdaptor sma = createStudentSnapshotFields(); // SASI Expects that a single space character in a grad year // field will not produce an error, but rather an empty element sma.Dictionary[ "ORIGYRGRAD"] = " "; StudentSnapshot ss = new StudentSnapshot(); Mappings m = fCfg.Mappings.GetMappings( "Default" ).Select( null, null, null ); m.MapOutbound( sma, ss, SifVersion.LATEST ); Console.WriteLine( ss.ToXml() ); int? onTimeGradYear = ss.OnTimeGraduationYear; Assertion.Assert( "onTimeGraduationYear is not null", !onTimeGradYear.HasValue ); } [Test] public void testStudentSnapshot15r1_NullLastName() { Adk.SifVersion = SifVersion.SIF15r1; StringMapAdaptor sma = createStudentSnapshotFields(); // SASI Expects that a null string will result in // the field not being mapped. Checking that here sma.Dictionary[ "LASTNAME" ] = null; StudentSnapshot ss = new StudentSnapshot(); Mappings m = fCfg.Mappings.GetMappings( "Default" ).Select( null, null, null ); m.MapOutbound( sma, ss, SifVersion.SIF15r1 ); String value = ss.ToXml(); Console.WriteLine( value ); Assertion.Assert( "Last Name should be null", value.IndexOf( "LastName" ) == -1 ); } [Test] public void testStudentSnapshot20_NullLastName() { Adk.SifVersion = SifVersion.LATEST; StringMapAdaptor sma = createStudentSnapshotFields(); // SASI Expects that a null string will result in // the field not being mapped. Checking that here sma.Dictionary["LASTNAME"] = null ; StudentSnapshot ss = new StudentSnapshot(); Mappings m = fCfg.Mappings.GetMappings( "Default" ).Select( null, null, null ); m.MapOutbound( sma, ss, SifVersion.LATEST ); String value = ss.ToXml(); Console.WriteLine( value ); Assertion.Assert( "Last Name should be null", value.IndexOf( "LastName" ) == -1 ); } [Test] public void testStudentSnapshot20r1() { StringMapAdaptor sma = createStudentSnapshotFields(); StudentSnapshot ss = new StudentSnapshot(); Mappings m = fCfg.Mappings.GetMappings( "Default" ).Select( null, null, null ); m.MapOutbound( sma, ss, SifVersion.SIF20r1 ); int? onTimeGradYear = ss.OnTimeGraduationYear; Assertion.Assert( "onTimeGraduationYear is null", onTimeGradYear.HasValue ); Assertion.AssertEquals( "OnTimeGraduationYear", 2000, onTimeGradYear.Value ); Console.WriteLine( ss.ToXml() ); } private StringMapAdaptor createStudentSnapshotFields() { IDictionary values = new Hashtable(); values.Add( "PERMNUM", "9798" ); values.Add( "SOCSECNUM", "845457898" ); values.Add( "SCHOOLNUM", "999" ); values.Add( "SCHOOLNUM2", "999" ); values.Add( "GRADE", "09" ); values.Add( "HOMEROOM", "5" ); values.Add( "LASTNAME", "Doe" ); values.Add( "FIRSTNAME", "Jane" ); values.Add( "MIDDLENAME", null ); values.Add( "NICKNAME", null ); values.Add( "MAILADDR", "5845 Test Blvd" ); values.Add( "CITY", "slc" ); values.Add( "STATE", "Utah" ); values.Add( "COUNTRY", "" ); values.Add( "ZIPCODE", "84093" ); values.Add( "RESADDR", null ); values.Add( "RESCITY", null ); values.Add( "RESSTATE", null ); values.Add( "RESCOUNTRY", null ); values.Add( "RESZIPCODE", null ); values.Add( "BIRTHDATE", "20051209" ); values.Add( "GENDER", "F" ); values.Add( "ETHNICCODE", "W" ); values.Add( "ENGPROF", "" ); values.Add( "PRIMARYLNG", "" ); values.Add( "TELEPHONE", null ); values.Add( "ORIGYRGRAD", "2000" ); StringMapAdaptor sma = new StringMapAdaptor( values ); return sma; } [Test] public void testStudentPersonalNullHomeroom() { IDictionary values = new Hashtable(); values.Add( "PERMNUM", "9798" ); values.Add( "SOCSECNUM", "845457898" ); values.Add( "SCHOOLNUM", "999" ); values.Add( "SCHOOLNUM2", "999" ); values.Add( "GRADE", "09" ); values.Add( "HOMEROOM", null ); values.Add( "LASTNAME", "Doe" ); values.Add( "FIRSTNAME", "Jane" ); values.Add( "MIDDLENAME", null ); values.Add( "NICKNAME", null ); values.Add( "MAILADDR", "5845 Test Blvd" ); values.Add( "CITY", "slc" ); values.Add( "STATE", "Utah" ); values.Add( "COUNTRY", "" ); values.Add( "ZIPCODE", "84093" ); values.Add( "RESADDR", null ); values.Add( "RESCITY", null ); values.Add( "RESSTATE", null ); values.Add( "RESCOUNTRY", null ); values.Add( "RESZIPCODE", null ); values.Add( "BIRTHDATE", "20051209" ); values.Add( "GENDER", "F" ); values.Add( "ETHNICCODE", "W" ); values.Add( "ENGPROF", "" ); values.Add( "PRIMARYLNG", "" ); values.Add( "TELEPHONE", null ); StringMapAdaptor sma = new StringMapAdaptor( values ); StudentPersonal sp = new StudentPersonal(); Mappings m = fCfg.Mappings.GetMappings( "Default" ).Select( null, null, null ); m.MapOutbound( sma, sp, SifVersion.SIF15r1 ); Console.WriteLine( sp.ToXml() ); Element e = sp .GetElementOrAttribute( "OtherId[@Type='ZZ' and starts-with(., 'HOMEROOM') ]" ); Assertion.AssertNull( "HOMEROOM should not have been mapped", e ); } [Test] public void testStudentPersonal2Addresses15r1() { IDictionary values = new Hashtable(); values.Add( "PERMNUM", "9798" ); values.Add( "LASTNAME", "Doe" ); values.Add( "FIRSTNAME", "Jane" ); values.Add( "MIDDLENAME", null ); values.Add( "MAILADDR", "PO Box 80077" ); values.Add( "CITY", "Salt Lake City" ); values.Add( "STATE", "Utah" ); values.Add( "COUNTRY", "US" ); values.Add( "ZIPCODE", "84093" ); values.Add( "RESADDR", "528 Big CottonWood Rd" ); values.Add( "RESCITY", "Sandy" ); values.Add( "RESSTATE", "UT" ); values.Add( "RESCOUNTRY", "US" ); values.Add( "RESZIPCODE", "84095" ); StringMapAdaptor sma = new StringMapAdaptor( values ); StudentPersonal sp = new StudentPersonal(); Mappings m = fCfg.Mappings.GetMappings( "Default" ).Select( null, null, null ); m.MapOutbound( sma, sp, SifVersion.SIF15r1 ); Console.WriteLine( sp.ToXml() ); Element e = sp .GetElementOrAttribute( "StudentAddress[@PickupOrDropoff='NA',@DayOfWeek='NA']/Address[@Type='M']/Street/Line1" ); Assertion.AssertNotNull( "Mailing Address was not mapped ", e ); Assertion.AssertEquals( "Mailing Address", "PO Box 80077", e.TextValue ); e = sp .GetElementOrAttribute( "StudentAddress[@PickupOrDropoff='NA',@DayOfWeek='NA']/Address[@Type='P']/Street/Line1" ); Assertion.AssertNotNull( "Residential Address was not mapped ", e ); Assertion.AssertEquals( "Mailing Address", "528 Big CottonWood Rd", e .TextValue ); StudentAddressList children = sp.AddressList; Assertion.AssertEquals( "Should have two StudentAddress elements", 2, children.Count ); } [Test] public void testStudentPersonal2Addresses20r1() { IDictionary values = new Hashtable(); values.Add( "PERMNUM", "9798" ); values.Add( "LASTNAME", "Doe" ); values.Add( "FIRSTNAME", "Jane" ); values.Add( "MIDDLENAME", null ); values.Add( "MAILADDR", "PO Box 80077" ); values.Add( "CITY", "Salt Lake City" ); values.Add( "STATE", "Utah" ); values.Add( "COUNTRY", "US" ); values.Add( "ZIPCODE", "84093" ); values.Add( "RESADDR", "528 Big CottonWood Rd" ); values.Add( "RESCITY", "Sandy" ); values.Add( "RESSTATE", "UT" ); values.Add( "RESCOUNTRY", "US" ); values.Add( "RESZIPCODE", "84095" ); StringMapAdaptor sma = new StringMapAdaptor( values ); StudentPersonal sp = new StudentPersonal(); Mappings m = fCfg.Mappings.GetMappings( "Default" ).Select( null, null, null ); m.MapOutbound( sma, sp, SifVersion.SIF20r1 ); Console.WriteLine( sp.ToXml() ); Element e = sp .GetElementOrAttribute( "AddressList/Address[@Type='0123']/Street/Line1" ); Assertion.AssertNotNull( "Mailing Address was not mapped ", e ); Assertion.AssertEquals( "Mailing Address", "PO Box 80077", e.TextValue ); e = sp .GetElementOrAttribute( "AddressList/Address[@Type='0765']/Street/Line1" ); Assertion.AssertNotNull( "Residential Address was not mapped ", e ); Assertion.AssertEquals( "Mailing Address", "528 Big CottonWood Rd", e .TextValue ); StudentAddressList[] list = sp.AddressLists; SifElementList children = sp.GetChildList( CommonDTD.ADDRESSLIST ); Assertion.AssertEquals( "Should have one StudentAddress elements", 1, children.Count ); Assertion.AssertEquals( "Should have two address elements", 2, children[0].ChildCount ); } [Test] public void testStaffPersonalATCH() { IDictionary values = new Hashtable(); values.Add( "ATCH.TCHNUM", "98" ); values.Add( "ATCH.SOCSECNUM", "455128888" ); values.Add( "ATCH.SCHOOLNUM", "999" ); values.Add( "ATCH.SCHOOLNUM2", "999" ); values.Add( "ATCH.HOMEROOM", "5" ); values.Add( "ATCH.LASTNAME", "Ngo" ); values.Add( "ATCH.FIRSTNAME", "Van" ); values.Add( "ATCH.MIDDLENAME", null ); values.Add( "ATCH.TELEPHONE", "8011234567" ); values.Add( "ATCH.TELEXTN", null ); values.Add( "ATCH.EMAILADDR", null ); values.Add( "ATCH.ETHNIC", "W" ); StringMapAdaptor sma = new StringMapAdaptor( values ); StaffPersonal s = new StaffPersonal(); Mappings m = fCfg.Mappings.GetMappings( "Default" ).Select( null, null, null ); m.MapOutbound( sma, s, SifVersion.SIF15r1 ); Console.WriteLine( s.ToXml() ); } [Test] public void testStaffPersonalATCHNullPhone() { IDictionary values = new Hashtable(); values.Add( "ATCH.TCHNUM", "98" ); values.Add( "ATCH.SOCSECNUM", "455128888" ); values.Add( "ATCH.SCHOOLNUM", "999" ); values.Add( "ATCH.SCHOOLNUM2", "999" ); values.Add( "ATCH.HOMEROOM", "5" ); values.Add( "ATCH.LASTNAME", "Ngo" ); values.Add( "ATCH.FIRSTNAME", "Van" ); values.Add( "ATCH.MIDDLENAME", null ); values.Add( "ATCH.TELEPHONE", null ); values.Add( "ATCH.TELEXTN", null ); values.Add( "ATCH.EMAILADDR", null ); values.Add( "ATCH.ETHNIC", "W" ); StringMapAdaptor sma = new StringMapAdaptor( values ); StaffPersonal s = new StaffPersonal(); Mappings m = fCfg.Mappings.GetMappings( "Default" ).Select( null, null, null ); m.MapOutbound( sma, s, SifVersion.SIF15r1 ); Console.WriteLine( s.ToXml() ); Element e = s .GetElementOrAttribute( "PhoneNumber[@Format='NA' and @Type='WP']" ); Assertion.AssertNull( "PhoneNumber should be null", e ); } [Test] public void testStaffPersonalASTF() { IDictionary values = new Hashtable(); values.Add( "ASTF.STAFFNUM", "9847" ); values.Add( "ASTF.SOCSECNUM", "123456789" ); values.Add( "ASTF.SCHOOLNUM", "999" ); values.Add( "ASTF.SCHOOLNUM2", "999" ); values.Add( "ASTF.HOMEROOM", "8" ); values.Add( "ASTF.EMAILADDR", null ); values.Add( "ASTF.LASTNAME", "Ngo" ); values.Add( "ASTF.FIRSTNAME", "Tom" ); values.Add( "ASTF.MIDDLENAME", "C" ); values.Add( "ASTF.ADDRESS", "1232 Bateman Point Drive" ); values.Add( "ASTF.CITY", "West Jordan" ); values.Add( "ASTF.STATE", "Utah" ); values.Add( "ASTF.COUNTRY", "" ); values.Add( "ASTF.ZIPCODE", "84084" ); values.Add( "ASTF.SCHOOLTEL", "1234567890" ); values.Add( "ASTF.TELEXTN", null ); values.Add( "ASTF.HOMETEL", null ); values.Add( "ASTF.ETHNICCODE", "W" ); StringMapAdaptor sma = new StringMapAdaptor( values ); StaffPersonal s = new StaffPersonal(); Mappings m = fCfg.Mappings.GetMappings( "Default" ).Select( null, null, null ); m.MapOutbound( sma, s, SifVersion.SIF15r1 ); Console.WriteLine( s.ToXml() ); Element e = s .GetElementOrAttribute( "PhoneNumber[@Format='NA' and @Type='HP']" ); Assertion.AssertNull( "Home PhoneNumber should not be mapped", e ); e = s.GetElementOrAttribute( "PhoneNumber[@Format='NA' and @Type='WP']" ); Assertion.AssertNotNull( "School PhoneNumber should be mapped", e ); Assertion.AssertEquals( "School phone", "1234567890", e.TextValue ); } [Test] public void testStudentContactSIF15r1() { StringMapAdaptor sma = createStudentContactFields(); StudentContact sc = new StudentContact(); Mappings m = fCfg.Mappings.GetMappings( "Default" ).Select( null, null, null ); m.MapOutbound( sma, sc, SifVersion.SIF15r1 ); String value = sc.ToXml(); Console.WriteLine( value ); // Verify that the phone number is properly escaped int loc = value.IndexOf( "<PhoneNumber Format=\"NA\" Type=\"EX\">M&amp;W</PhoneNumber>" ); Assertion.Assert( "Phone number should be escaped", loc > -1 ); Element e = sc .GetElementOrAttribute( "PhoneNumber[@Format='NA' and @Type='HP']" ); Assertion.AssertNotNull( "School PhoneNumber should be mapped", e ); Assertion.AssertEquals( "School phone", "8014504555", e.TextValue ); e = sc .GetElementOrAttribute( "PhoneNumber[@Format='NA' and @Type='AP']" ); Assertion.AssertNotNull( "School PhoneNumber should be mapped", e ); // Note the " " Space at the end of the value. This should be there, // according to the mapping Assertion.AssertEquals( "School phone", "8014505555 ", e.TextValue ); e = sc .GetElementOrAttribute( "PhoneNumber[@Format='NA' and @Type='WP']" ); Assertion.AssertNull( "School PhoneNumber should not be mapped", e ); AddressList al = sc.AddressList; if ( al != null ) { foreach ( Address addr in al ) { Assertion.AssertNull( "Country should be null", addr.Country ); if ( addr.Type.Equals( "O" ) ) { Assertion.AssertNull( "State should be null", addr.StateProvince ); } } } } [Test] public void testStudentSchoolEnrollmentGradeLevelMapping() { Adk.SifVersion = SifVersion.SIF15r1; IDictionary values = new Hashtable(); values.Add( "GRADE", "00" ); StringMapAdaptor sma = new StringMapAdaptor( values ); StudentSchoolEnrollment sse = new StudentSchoolEnrollment(); Mappings m = fCfg.Mappings.GetMappings( "Default" ).Select( null, null, null ); m.MapOutbound( sma, sse, SifVersion.SIF15r1 ); sse.SetHomeroom( "RoomInfo", Adk.MakeGuid() ); Console.WriteLine( sse.ToXml() ); // This specific case tests what should happen when the grade level is // using an undefined value. // The valueset entries don't have a value for "00", so "00" should be // returned as-is } [Test] public void testStudentContactSIF20() { Adk.SifVersion = SifVersion.SIF20r1; StringMapAdaptor sma = createStudentContactFields(); StudentContact sc = new StudentContact(); sc.Type = "E4"; Mappings m = fCfg.Mappings.GetMappings( "Default" ).Select( null, null, null ); m.MapOutbound( sma, sc, SifVersion.SIF20r1 ); String value = sc.ToXml(); Console.WriteLine( value ); // Verify that the phone number is properly escaped int loc = value.IndexOf( "<Number>M&amp;W</Number>" ); Assertion.Assert( "Phone number should be escaped", loc > -1 ); // Verify that the @Type attribute is not rendered in SIF 2.0 loc = value.IndexOf( "Type=\"E4\"" ); Assertion.AssertEquals( "Type Attribute should not be rendered", -1, loc ); sc.SifVersion = SifVersion.SIF20r1; Element e = sc .GetElementOrAttribute( "//PhoneNumber[@Type='0096']/Number" ); Assertion.AssertNotNull( "School PhoneNumber should be mapped", e ); Assertion.AssertEquals( "School phone", "8014504555", e.TextValue ); e = sc.GetElementOrAttribute( "//PhoneNumber[@Type='0350'][1]/Number" ); Assertion.AssertNotNull( "School PhoneNumber should be mapped", e ); // Note the " " Space at the end of the value. This should be there, // according to the mapping Assertion.AssertEquals( "School phone", "8014505555 ", e.TextValue ); e = sc.GetElementOrAttribute( "//PhoneNumber[@Type='0350'][2]/Number" ); Assertion.AssertNull( "School PhoneNumber should not be mapped", e ); AddressList al = sc.AddressList; if ( al != null ) { foreach ( Address addr in al ) { Assertion.AssertNull( "Country should be null", addr.Country ); if ( addr.Type.Equals( "1075" ) ) { Assertion.AssertNull( "State should be null", addr.StateProvince ); } } } } private StringMapAdaptor createStudentContactFields() { IDictionary values = new Hashtable(); values.Add( "APRN.SOCSECNUM", "123456789" ); values.Add( "APRN.SCHOOLNUM", "999" ); values.Add( "APRN.SCHOOLNUM2", "999" ); values.Add( "APRN.EMAILADDR", null ); values.Add( "APRN.LASTNAME", "DOE" ); values.Add( "APRN.FIRSTNAME", "JOHN" ); values.Add( "APRN.MIDDLENAME", null ); values.Add( "APRN.WRKADDR", null ); values.Add( "APRN.WRKCITY", null ); values.Add( "APRN.WRKSTATE", null ); values.Add( "APRN.WRKCOUNTRY", null ); values.Add( "APRN.WRKZIP", "54494" ); values.Add( "APRN.ADDRESS", null ); values.Add( "APRN.CITY", null ); values.Add( "APRN.STATE", null ); values.Add( "APRN.COUNTRY", null ); values.Add( "APRN.ZIPCODE", null ); values.Add( "APRN.TELEPHONE", "8014504555" ); values.Add( "APRN.ALTTEL", "8014505555" ); values.Add( "APRN.WRKTEL", null ); // Test escaping of text values in the phone number field values.Add( "APRN.WRKEXTN", "M&W" ); values.Add( "APRN.RELATION", "01" ); // values.Add( "APRN.WRKSTATE", "" ); // values.Add( "APRN.RELATION2", "01" ); StringMapAdaptor sma = new StringMapAdaptor( values ); return sma; } [Test] public void testSchoolCourseInfo() { IDictionary values = new Hashtable(); values.Add( "CREDVALUE", "0" ); values.Add( "MAXCREDITS", "1" ); StringMapAdaptor sma = new StringMapAdaptor( values ); SchoolCourseInfo sc = new SchoolCourseInfo(); sc.SchoolYear = 1999; Mappings m = fCfg.Mappings.GetMappings( "Default" ).Select( null, null, null ); m.MapOutbound( sma, sc, SifVersion.SIF15r1 ); Console.WriteLine( sc.ToXml() ); Element e = sc.GetElementOrAttribute( "CourseCredits[@Code='01']" ); Assertion.AssertNotNull( "credits", e ); Assertion.AssertEquals( "credits", "0", e.TextValue ); e = sc.GetElementOrAttribute( "CourseCredits[@Code='02']" ); Assertion.AssertNotNull( "maxcredits", e ); Assertion.AssertEquals( "maxcredits", "1", e.TextValue ); } } }
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.3 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculus.com/licenses/LICENSE-3.3 Unless required by applicable law or agreed to in writing, the Oculus VR SDK distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ************************************************************************************/ using System; using System.Runtime.InteropServices; // Internal C# wrapper for OVRPlugin. internal static class OVRPlugin { public static readonly System.Version wrapperVersion = OVRP_1_8_0.version; private static System.Version _version; public static System.Version version { get { if (_version == null) { try { string pluginVersion = OVRP_1_1_0.ovrp_GetVersion(); if (pluginVersion != null) { // Truncate unsupported trailing version info for System.Version. Original string is returned if not present. pluginVersion = pluginVersion.Split('-')[0]; _version = new System.Version(pluginVersion); } else { _version = new System.Version(0, 0, 0); } } catch { _version = new System.Version(0, 0, 0); } // Unity 5.1.1f3-p3 have OVRPlugin version "0.5.0", which isn't accurate. if (_version == OVRP_0_5_0.version) _version = OVRP_0_1_0.version; if (_version < OVRP_1_3_0.version) throw new PlatformNotSupportedException("Oculus Utilities version " + wrapperVersion + " is too new for OVRPlugin version " + _version.ToString () + ". Update to the latest version of Unity."); } return _version; } } private static System.Version _nativeSDKVersion; public static System.Version nativeSDKVersion { get { if (_nativeSDKVersion == null) { try { string sdkVersion = string.Empty; if (version >= OVRP_1_1_0.version) sdkVersion = OVRP_1_1_0.ovrp_GetNativeSDKVersion(); else sdkVersion = "0.0.0"; if (sdkVersion != null) { // Truncate unsupported trailing version info for System.Version. Original string is returned if not present. sdkVersion = sdkVersion.Split('-')[0]; _nativeSDKVersion = new System.Version(sdkVersion); } else { _nativeSDKVersion = new System.Version(0, 0, 0); } } catch { _nativeSDKVersion = new System.Version(0, 0, 0); } } return _nativeSDKVersion; } } [StructLayout(LayoutKind.Sequential)] private struct GUID { public int a; public short b; public short c; public byte d0; public byte d1; public byte d2; public byte d3; public byte d4; public byte d5; public byte d6; public byte d7; } public enum Bool { False = 0, True } public enum Eye { None = -1, Left = 0, Right = 1, Count = 2 } public enum Tracker { None = -1, Zero = 0, One = 1, Count, } public enum Node { None = -1, EyeLeft = 0, EyeRight = 1, EyeCenter = 2, HandLeft = 3, HandRight = 4, TrackerZero = 5, TrackerOne = 6, TrackerTwo = 7, TrackerThree = 8, Head = 9, Count, } public enum Controller { None = 0, LTouch = 0x00000001, RTouch = 0x00000002, Touch = LTouch | RTouch, Remote = 0x00000004, Gamepad = 0x00000008, Active = unchecked((int)0x80000000), All = ~None, } public enum TrackingOrigin { EyeLevel = 0, FloorLevel = 1, Count, } public enum RecenterFlags { Default = 0, IgnoreAll = unchecked((int)0x80000000), Count, } public enum BatteryStatus { Charging = 0, Discharging, Full, NotCharging, Unknown, } public enum PlatformUI { None = -1, GlobalMenu = 0, ConfirmQuit, GlobalMenuTutorial, } public enum SystemRegion { Unspecified = 0, Japan, China, } public enum OverlayShape { Quad = 0, Cylinder = 1, Cubemap = 2, } private const int OverlayShapeFlagShift = 4; private enum OverlayFlag { None = unchecked((int)0x00000000), OnTop = unchecked((int)0x00000001), HeadLocked = unchecked((int)0x00000002), // Using the 5-8 bits for shapes, total 16 potential shapes can be supported 0x000000[0]0 -> 0x000000[F]0 ShapeFlag_Quad = unchecked((int)OverlayShape.Quad << OverlayShapeFlagShift), ShapeFlag_Cylinder = unchecked((int)OverlayShape.Cylinder << OverlayShapeFlagShift), ShapeFlag_Cubemap = unchecked((int)OverlayShape.Cubemap << OverlayShapeFlagShift), ShapeFlagRangeMask = unchecked((int)0xF << OverlayShapeFlagShift), } [StructLayout(LayoutKind.Sequential)] public struct Vector2i { public int x; public int y; } [StructLayout(LayoutKind.Sequential)] public struct Vector2f { public float x; public float y; } [StructLayout(LayoutKind.Sequential)] public struct Vector3f { public float x; public float y; public float z; } [StructLayout(LayoutKind.Sequential)] public struct Quatf { public float x; public float y; public float z; public float w; } [StructLayout(LayoutKind.Sequential)] public struct Posef { public Quatf Orientation; public Vector3f Position; } [StructLayout(LayoutKind.Sequential)] internal struct InputState { public uint ConnectedControllers; public uint Buttons; public uint Touches; public uint NearTouches; public float LIndexTrigger; public float RIndexTrigger; public float LHandTrigger; public float RHandTrigger; public Vector2f LThumbstick; public Vector2f RThumbstick; } [StructLayout(LayoutKind.Sequential)] public struct ControllerState { public uint ConnectedControllers; public uint Buttons; public uint Touches; public uint NearTouches; public float LIndexTrigger; public float RIndexTrigger; public float LHandTrigger; public float RHandTrigger; public Vector2f LThumbstick; public Vector2f RThumbstick; // maintain backwards compat for OVRP_0_1_2.ovrp_GetInputState() internal ControllerState(InputState inputState) { ConnectedControllers = inputState.ConnectedControllers; Buttons = inputState.Buttons; Touches = inputState.Touches; NearTouches = inputState.NearTouches; LIndexTrigger = inputState.LIndexTrigger; RIndexTrigger = inputState.RIndexTrigger; LHandTrigger = inputState.LHandTrigger; RHandTrigger = inputState.RHandTrigger; LThumbstick = inputState.LThumbstick; RThumbstick = inputState.RThumbstick; } } [StructLayout(LayoutKind.Sequential)] public struct HapticsBuffer { public IntPtr Samples; public int SamplesCount; } [StructLayout(LayoutKind.Sequential)] public struct HapticsState { public int SamplesAvailable; public int SamplesQueued; } [StructLayout(LayoutKind.Sequential)] public struct HapticsDesc { public int SampleRateHz; public int SampleSizeInBytes; public int MinimumSafeSamplesQueued; public int MinimumBufferSamplesCount; public int OptimalBufferSamplesCount; public int MaximumBufferSamplesCount; } [StructLayout(LayoutKind.Sequential)] public struct Sizei { public int w; public int h; } [StructLayout(LayoutKind.Sequential)] public struct Frustumf { public float zNear; public float zFar; public float fovX; public float fovY; } public enum BoundaryType { OuterBoundary = 0x0001, PlayArea = 0x0100, } [StructLayout(LayoutKind.Sequential)] public struct BoundaryTestResult { public Bool IsTriggering; public float ClosestDistance; public Vector3f ClosestPoint; public Vector3f ClosestPointNormal; } [StructLayout(LayoutKind.Sequential)] public struct BoundaryLookAndFeel { public Colorf Color; } [StructLayout(LayoutKind.Sequential)] public struct BoundaryGeometry { public BoundaryType BoundaryType; [MarshalAs(UnmanagedType.ByValArray, SizeConst=256)] public Vector3f[] Points; public int PointsCount; } [StructLayout(LayoutKind.Sequential)] public struct Colorf { public float r; public float g; public float b; public float a; } public static bool initialized { get { return OVRP_1_1_0.ovrp_GetInitialized() == OVRPlugin.Bool.True; } } public static bool chromatic { get { if (version >= OVRP_1_7_0.version) return OVRP_1_7_0.ovrp_GetAppChromaticCorrection() == OVRPlugin.Bool.True; #if UNITY_ANDROID && !UNITY_EDITOR return false; #else return true; #endif } set { if (version >= OVRP_1_7_0.version) OVRP_1_7_0.ovrp_SetAppChromaticCorrection(ToBool(value)); } } public static bool monoscopic { get { return OVRP_1_1_0.ovrp_GetAppMonoscopic() == OVRPlugin.Bool.True; } set { OVRP_1_1_0.ovrp_SetAppMonoscopic(ToBool(value)); } } public static bool rotation { get { return OVRP_1_1_0.ovrp_GetTrackingOrientationEnabled() == Bool.True; } set { OVRP_1_1_0.ovrp_SetTrackingOrientationEnabled(ToBool(value)); } } public static bool position { get { return OVRP_1_1_0.ovrp_GetTrackingPositionEnabled() == Bool.True; } set { OVRP_1_1_0.ovrp_SetTrackingPositionEnabled(ToBool(value)); } } public static bool useIPDInPositionTracking { get { if (version >= OVRP_1_6_0.version) return OVRP_1_6_0.ovrp_GetTrackingIPDEnabled() == OVRPlugin.Bool.True; return true; } set { if (version >= OVRP_1_6_0.version) OVRP_1_6_0.ovrp_SetTrackingIPDEnabled(ToBool(value)); } } public static bool positionSupported { get { return OVRP_1_1_0.ovrp_GetTrackingPositionSupported() == Bool.True; } } public static bool positionTracked { get { return OVRP_1_1_0.ovrp_GetNodePositionTracked(Node.EyeCenter) == Bool.True; } } public static bool powerSaving { get { return OVRP_1_1_0.ovrp_GetSystemPowerSavingMode() == Bool.True; } } public static bool hmdPresent { get { return OVRP_1_1_0.ovrp_GetNodePresent(Node.EyeCenter) == Bool.True; } } public static bool userPresent { get { return OVRP_1_1_0.ovrp_GetUserPresent() == Bool.True; } } public static bool headphonesPresent { get { return OVRP_1_3_0.ovrp_GetSystemHeadphonesPresent() == OVRPlugin.Bool.True; } } public static int recommendedMSAALevel { get { if (version >= OVRP_1_6_0.version) return OVRP_1_6_0.ovrp_GetSystemRecommendedMSAALevel (); else return 2; } } public static SystemRegion systemRegion { get { if (version >= OVRP_1_5_0.version) return OVRP_1_5_0.ovrp_GetSystemRegion(); else return SystemRegion.Unspecified; } } private static Guid _cachedAudioOutGuid; private static string _cachedAudioOutString; public static string audioOutId { get { try { IntPtr ptr = OVRP_1_1_0.ovrp_GetAudioOutId(); if (ptr != IntPtr.Zero) { GUID nativeGuid = (GUID)Marshal.PtrToStructure(ptr, typeof(OVRPlugin.GUID)); Guid managedGuid = new Guid( nativeGuid.a, nativeGuid.b, nativeGuid.c, nativeGuid.d0, nativeGuid.d1, nativeGuid.d2, nativeGuid.d3, nativeGuid.d4, nativeGuid.d5, nativeGuid.d6, nativeGuid.d7); if (managedGuid != _cachedAudioOutGuid) { _cachedAudioOutGuid = managedGuid; _cachedAudioOutString = _cachedAudioOutGuid.ToString(); } return _cachedAudioOutString; } } catch {} return string.Empty; } } private static Guid _cachedAudioInGuid; private static string _cachedAudioInString; public static string audioInId { get { try { IntPtr ptr = OVRP_1_1_0.ovrp_GetAudioInId(); if (ptr != IntPtr.Zero) { GUID nativeGuid = (GUID)Marshal.PtrToStructure(ptr, typeof(OVRPlugin.GUID)); Guid managedGuid = new Guid( nativeGuid.a, nativeGuid.b, nativeGuid.c, nativeGuid.d0, nativeGuid.d1, nativeGuid.d2, nativeGuid.d3, nativeGuid.d4, nativeGuid.d5, nativeGuid.d6, nativeGuid.d7); if (managedGuid != _cachedAudioInGuid) { _cachedAudioInGuid = managedGuid; _cachedAudioInString = _cachedAudioInGuid.ToString(); } return _cachedAudioInString; } } catch {} return string.Empty; } } public static bool hasVrFocus { get { return OVRP_1_1_0.ovrp_GetAppHasVrFocus() == Bool.True; } } public static bool shouldQuit { get { return OVRP_1_1_0.ovrp_GetAppShouldQuit() == Bool.True; } } public static bool shouldRecenter { get { return OVRP_1_1_0.ovrp_GetAppShouldRecenter() == Bool.True; } } public static string productName { get { return OVRP_1_1_0.ovrp_GetSystemProductName(); } } public static string latency { get { return OVRP_1_1_0.ovrp_GetAppLatencyTimings(); } } public static float eyeDepth { get { return OVRP_1_1_0.ovrp_GetUserEyeDepth(); } set { OVRP_1_1_0.ovrp_SetUserEyeDepth(value); } } public static float eyeHeight { get { return OVRP_1_1_0.ovrp_GetUserEyeHeight(); } set { OVRP_1_1_0.ovrp_SetUserEyeHeight(value); } } public static float batteryLevel { get { return OVRP_1_1_0.ovrp_GetSystemBatteryLevel(); } } public static float batteryTemperature { get { return OVRP_1_1_0.ovrp_GetSystemBatteryTemperature(); } } public static int cpuLevel { get { return OVRP_1_1_0.ovrp_GetSystemCpuLevel(); } set { OVRP_1_1_0.ovrp_SetSystemCpuLevel(value); } } public static int gpuLevel { get { return OVRP_1_1_0.ovrp_GetSystemGpuLevel(); } set { OVRP_1_1_0.ovrp_SetSystemGpuLevel(value); } } public static int vsyncCount { get { return OVRP_1_1_0.ovrp_GetSystemVSyncCount(); } set { OVRP_1_2_0.ovrp_SetSystemVSyncCount(value); } } public static float systemVolume { get { return OVRP_1_1_0.ovrp_GetSystemVolume(); } } public static float ipd { get { return OVRP_1_1_0.ovrp_GetUserIPD(); } set { OVRP_1_1_0.ovrp_SetUserIPD(value); } } public static bool occlusionMesh { get { return OVRP_1_3_0.ovrp_GetEyeOcclusionMeshEnabled() == Bool.True; } set { OVRP_1_3_0.ovrp_SetEyeOcclusionMeshEnabled(ToBool(value)); } } public static BatteryStatus batteryStatus { get { return OVRP_1_1_0.ovrp_GetSystemBatteryStatus(); } } public static Posef GetEyeVelocity(Eye eyeId) { return GetNodeVelocity((Node)eyeId, false); } public static Posef GetEyeAcceleration(Eye eyeId) { return GetNodeAcceleration((Node)eyeId, false); } public static Frustumf GetEyeFrustum(Eye eyeId) { return OVRP_1_1_0.ovrp_GetNodeFrustum((Node)eyeId); } public static Sizei GetEyeTextureSize(Eye eyeId) { return OVRP_0_1_0.ovrp_GetEyeTextureSize(eyeId); } public static Posef GetTrackerPose(Tracker trackerId) { return GetNodePose((Node)((int)trackerId + (int)Node.TrackerZero), false); } public static Frustumf GetTrackerFrustum(Tracker trackerId) { return OVRP_1_1_0.ovrp_GetNodeFrustum((Node)((int)trackerId + (int)Node.TrackerZero)); } public static bool ShowUI(PlatformUI ui) { return OVRP_1_1_0.ovrp_ShowSystemUI(ui) == Bool.True; } public static bool SetOverlayQuad(bool onTop, bool headLocked, IntPtr leftTexture, IntPtr rightTexture, IntPtr device, Posef pose, Vector3f scale, int layerIndex=0, OverlayShape shape=OverlayShape.Quad) { if (version >= OVRP_1_6_0.version) { uint flags = (uint)OverlayFlag.None; if (onTop) flags |= (uint)OverlayFlag.OnTop; if (headLocked) flags |= (uint)OverlayFlag.HeadLocked; if (shape == OverlayShape.Cylinder || shape == OverlayShape.Cubemap) { #if UNITY_ANDROID if (version >= OVRP_1_7_0.version) flags |= (uint)(shape) << OverlayShapeFlagShift; else #endif return false; } return OVRP_1_6_0.ovrp_SetOverlayQuad3(flags, leftTexture, rightTexture, device, pose, scale, layerIndex) == Bool.True; } if (layerIndex != 0) return false; return OVRP_0_1_1.ovrp_SetOverlayQuad2(ToBool(onTop), ToBool(headLocked), leftTexture, device, pose, scale) == Bool.True; } public static bool UpdateNodePhysicsPoses(int frameIndex, double predictionSeconds) { if (version >= OVRP_1_8_0.version) return OVRP_1_8_0.ovrp_Update2(0, frameIndex, predictionSeconds) == Bool.True; return false; } public static Posef GetNodePose(Node nodeId, bool usePhysicsPose) { if (version >= OVRP_1_8_0.version && usePhysicsPose) return OVRP_1_8_0.ovrp_GetNodePose2(0, nodeId); return OVRP_0_1_2.ovrp_GetNodePose(nodeId); } public static Posef GetNodeVelocity(Node nodeId, bool usePhysicsPose) { if (version >= OVRP_1_8_0.version && usePhysicsPose) return OVRP_1_8_0.ovrp_GetNodeVelocity2(0, nodeId); return OVRP_0_1_3.ovrp_GetNodeVelocity(nodeId); } public static Posef GetNodeAcceleration(Node nodeId, bool usePhysicsPose) { if (version >= OVRP_1_8_0.version && usePhysicsPose) return OVRP_1_8_0.ovrp_GetNodeAcceleration2(0, nodeId); return OVRP_0_1_3.ovrp_GetNodeAcceleration(nodeId); } public static bool GetNodePresent(Node nodeId) { return OVRP_1_1_0.ovrp_GetNodePresent(nodeId) == Bool.True; } public static bool GetNodeOrientationTracked(Node nodeId) { return OVRP_1_1_0.ovrp_GetNodeOrientationTracked(nodeId) == Bool.True; } public static bool GetNodePositionTracked(Node nodeId) { return OVRP_1_1_0.ovrp_GetNodePositionTracked(nodeId) == Bool.True; } public static ControllerState GetControllerState(uint controllerMask) { return OVRP_1_1_0.ovrp_GetControllerState(controllerMask); } public static bool SetControllerVibration(uint controllerMask, float frequency, float amplitude) { return OVRP_0_1_2.ovrp_SetControllerVibration(controllerMask, frequency, amplitude) == Bool.True; } public static HapticsDesc GetControllerHapticsDesc(uint controllerMask) { if (version >= OVRP_1_6_0.version) { return OVRP_1_6_0.ovrp_GetControllerHapticsDesc(controllerMask); } else { return new HapticsDesc(); } } public static HapticsState GetControllerHapticsState(uint controllerMask) { if (version >= OVRP_1_6_0.version) { return OVRP_1_6_0.ovrp_GetControllerHapticsState(controllerMask); } else { return new HapticsState(); } } public static bool SetControllerHaptics(uint controllerMask, HapticsBuffer hapticsBuffer) { if (version >= OVRP_1_6_0.version) { return OVRP_1_6_0.ovrp_SetControllerHaptics(controllerMask, hapticsBuffer) == Bool.True; } else { return false; } } public static float GetEyeRecommendedResolutionScale() { if (version >= OVRP_1_6_0.version) { return OVRP_1_6_0.ovrp_GetEyeRecommendedResolutionScale(); } else { return 1.0f; } } public static float GetAppCpuStartToGpuEndTime() { if (version >= OVRP_1_6_0.version) { return OVRP_1_6_0.ovrp_GetAppCpuStartToGpuEndTime(); } else { return 0.0f; } } public static bool GetBoundaryConfigured() { if (version >= OVRP_1_8_0.version) { return OVRP_1_8_0.ovrp_GetBoundaryConfigured() == OVRPlugin.Bool.True; } else { return false; } } public static BoundaryTestResult TestBoundaryNode(Node nodeId, BoundaryType boundaryType) { if (version >= OVRP_1_8_0.version) { return OVRP_1_8_0.ovrp_TestBoundaryNode(nodeId, boundaryType); } else { return new BoundaryTestResult(); } } public static BoundaryTestResult TestBoundaryPoint(Vector3f point, BoundaryType boundaryType) { if (version >= OVRP_1_8_0.version) { return OVRP_1_8_0.ovrp_TestBoundaryPoint(point, boundaryType); } else { return new BoundaryTestResult(); } } public static bool SetBoundaryLookAndFeel(BoundaryLookAndFeel lookAndFeel) { if (version >= OVRP_1_8_0.version) { return OVRP_1_8_0.ovrp_SetBoundaryLookAndFeel(lookAndFeel) == OVRPlugin.Bool.True; } else { return false; } } public static bool ResetBoundaryLookAndFeel() { if (version >= OVRP_1_8_0.version) { return OVRP_1_8_0.ovrp_ResetBoundaryLookAndFeel() == OVRPlugin.Bool.True; } else { return false; } } public static BoundaryGeometry GetBoundaryGeometry(BoundaryType boundaryType) { if (version >= OVRP_1_8_0.version) { return OVRP_1_8_0.ovrp_GetBoundaryGeometry(boundaryType); } else { return new BoundaryGeometry(); } } public static Vector3f GetBoundaryDimensions(BoundaryType boundaryType) { if (version >= OVRP_1_8_0.version) { return OVRP_1_8_0.ovrp_GetBoundaryDimensions(boundaryType); } else { return new Vector3f(); } } public static bool GetBoundaryVisible() { if (version >= OVRP_1_8_0.version) { return OVRP_1_8_0.ovrp_GetBoundaryVisible() == OVRPlugin.Bool.True; } else { return false; } } public static bool SetBoundaryVisible(bool value) { if (version >= OVRP_1_8_0.version) { return OVRP_1_8_0.ovrp_SetBoundaryVisible(ToBool(value)) == OVRPlugin.Bool.True; } else { return false; } } private static Bool ToBool(bool b) { return (b) ? OVRPlugin.Bool.True : OVRPlugin.Bool.False; } public static TrackingOrigin GetTrackingOriginType() { return OVRP_1_0_0.ovrp_GetTrackingOriginType(); } public static bool SetTrackingOriginType(TrackingOrigin originType) { return OVRP_1_0_0.ovrp_SetTrackingOriginType(originType) == Bool.True; } public static Posef GetTrackingCalibratedOrigin() { return OVRP_1_0_0.ovrp_GetTrackingCalibratedOrigin(); } public static bool SetTrackingCalibratedOrigin() { return OVRP_1_2_0.ovrpi_SetTrackingCalibratedOrigin() == Bool.True; } public static bool RecenterTrackingOrigin(RecenterFlags flags) { return OVRP_1_0_0.ovrp_RecenterTrackingOrigin((uint)flags) == Bool.True; } //HACK: This makes Unity think it always has VR focus while OVRPlugin.cs reports the correct value. internal static bool ignoreVrFocus { set { OVRP_1_2_1.ovrp_SetAppIgnoreVrFocus(ToBool(value)); } } private const string pluginName = "OVRPlugin"; private static class OVRP_0_1_0 { public static readonly System.Version version = new System.Version(0, 1, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Sizei ovrp_GetEyeTextureSize(Eye eyeId); } private static class OVRP_0_1_1 { public static readonly System.Version version = new System.Version(0, 1, 1); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetOverlayQuad2(Bool onTop, Bool headLocked, IntPtr texture, IntPtr device, Posef pose, Vector3f scale); } private static class OVRP_0_1_2 { public static readonly System.Version version = new System.Version(0, 1, 2); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Posef ovrp_GetNodePose(Node nodeId); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetControllerVibration(uint controllerMask, float frequency, float amplitude); } private static class OVRP_0_1_3 { public static readonly System.Version version = new System.Version(0, 1, 3); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Posef ovrp_GetNodeVelocity(Node nodeId); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Posef ovrp_GetNodeAcceleration(Node nodeId); } private static class OVRP_0_5_0 { public static readonly System.Version version = new System.Version(0, 5, 0); } private static class OVRP_1_0_0 { public static readonly System.Version version = new System.Version(1, 0, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern TrackingOrigin ovrp_GetTrackingOriginType(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetTrackingOriginType(TrackingOrigin originType); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Posef ovrp_GetTrackingCalibratedOrigin(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_RecenterTrackingOrigin(uint flags); } private static class OVRP_1_1_0 { public static readonly System.Version version = new System.Version(1, 1, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetInitialized(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_GetVersion")] private static extern IntPtr _ovrp_GetVersion(); public static string ovrp_GetVersion() { return Marshal.PtrToStringAnsi(_ovrp_GetVersion()); } [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_GetNativeSDKVersion")] private static extern IntPtr _ovrp_GetNativeSDKVersion(); public static string ovrp_GetNativeSDKVersion() { return Marshal.PtrToStringAnsi(_ovrp_GetNativeSDKVersion()); } [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr ovrp_GetAudioOutId(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr ovrp_GetAudioInId(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetEyeTextureScale(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetEyeTextureScale(float value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetTrackingOrientationSupported(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetTrackingOrientationEnabled(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetTrackingOrientationEnabled(Bool value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetTrackingPositionSupported(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetTrackingPositionEnabled(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetTrackingPositionEnabled(Bool value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetNodePresent(Node nodeId); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetNodeOrientationTracked(Node nodeId); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetNodePositionTracked(Node nodeId); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Frustumf ovrp_GetNodeFrustum(Node nodeId); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern ControllerState ovrp_GetControllerState(uint controllerMask); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern int ovrp_GetSystemCpuLevel(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetSystemCpuLevel(int value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern int ovrp_GetSystemGpuLevel(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetSystemGpuLevel(int value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetSystemPowerSavingMode(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetSystemDisplayFrequency(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern int ovrp_GetSystemVSyncCount(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetSystemVolume(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern BatteryStatus ovrp_GetSystemBatteryStatus(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetSystemBatteryLevel(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetSystemBatteryTemperature(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_GetSystemProductName")] private static extern IntPtr _ovrp_GetSystemProductName(); public static string ovrp_GetSystemProductName() { return Marshal.PtrToStringAnsi(_ovrp_GetSystemProductName()); } [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_ShowSystemUI(PlatformUI ui); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetAppMonoscopic(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetAppMonoscopic(Bool value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetAppHasVrFocus(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetAppShouldQuit(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetAppShouldRecenter(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ovrp_GetAppLatencyTimings")] private static extern IntPtr _ovrp_GetAppLatencyTimings(); public static string ovrp_GetAppLatencyTimings() { return Marshal.PtrToStringAnsi(_ovrp_GetAppLatencyTimings()); } [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetUserPresent(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetUserIPD(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetUserIPD(float value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetUserEyeDepth(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetUserEyeDepth(float value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetUserEyeHeight(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetUserEyeHeight(float value); } private static class OVRP_1_2_0 { public static readonly System.Version version = new System.Version(1, 2, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetSystemVSyncCount(int vsyncCount); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrpi_SetTrackingCalibratedOrigin(); } private static class OVRP_1_2_1 { public static readonly System.Version version = new System.Version(1, 2, 1); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetAppIgnoreVrFocus(Bool value); } private static class OVRP_1_3_0 { public static readonly System.Version version = new System.Version(1, 3, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetEyeOcclusionMeshEnabled(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetEyeOcclusionMeshEnabled(Bool value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetSystemHeadphonesPresent(); } private static class OVRP_1_5_0 { public static readonly System.Version version = new System.Version(1, 5, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern SystemRegion ovrp_GetSystemRegion(); } private static class OVRP_1_6_0 { public static readonly System.Version version = new System.Version(1, 6, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetTrackingIPDEnabled(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetTrackingIPDEnabled(Bool value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern HapticsDesc ovrp_GetControllerHapticsDesc(uint controllerMask); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern HapticsState ovrp_GetControllerHapticsState(uint controllerMask); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetControllerHaptics(uint controllerMask, HapticsBuffer hapticsBuffer); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetOverlayQuad3(uint flags, IntPtr textureLeft, IntPtr textureRight, IntPtr device, Posef pose, Vector3f scale, int layerIndex); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetEyeRecommendedResolutionScale(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern float ovrp_GetAppCpuStartToGpuEndTime(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern int ovrp_GetSystemRecommendedMSAALevel(); } private static class OVRP_1_7_0 { public static readonly System.Version version = new System.Version(1, 7, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetAppChromaticCorrection(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetAppChromaticCorrection(Bool value); } private static class OVRP_1_8_0 { public static readonly System.Version version = new System.Version(1, 8, 0); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetBoundaryConfigured(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern BoundaryTestResult ovrp_TestBoundaryNode(Node nodeId, BoundaryType boundaryType); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern BoundaryTestResult ovrp_TestBoundaryPoint(Vector3f point, BoundaryType boundaryType); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetBoundaryLookAndFeel(BoundaryLookAndFeel lookAndFeel); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_ResetBoundaryLookAndFeel(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern BoundaryGeometry ovrp_GetBoundaryGeometry(BoundaryType boundaryType); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Vector3f ovrp_GetBoundaryDimensions(BoundaryType boundaryType); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_GetBoundaryVisible(); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_SetBoundaryVisible(Bool value); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Bool ovrp_Update2(int stateId, int frameIndex, double predictionSeconds); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Posef ovrp_GetNodePose2(int stateId, Node nodeId); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Posef ovrp_GetNodeVelocity2(int stateId, Node nodeId); [DllImport(pluginName, CallingConvention = CallingConvention.Cdecl)] public static extern Posef ovrp_GetNodeAcceleration2(int stateId, Node nodeId); } }
using System; using System.Linq; using System.Net.Http; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Microsoft.Bot.Connector { /// <summary> /// An Activity is the basic communication type for the Bot Framework 3.0 protocol /// </summary> /// <remarks> /// The Activity class contains all properties that individual, more specific activities /// could contain. It is a superset type. /// </remarks> public partial class Activity : IActivity, IConversationUpdateActivity, IContactRelationUpdateActivity, IInstallationUpdateActivity, IMessageActivity, ITypingActivity, IEndOfConversationActivity, IEventActivity, IInvokeActivity { /// <summary> /// Content-type for an Activity /// </summary> public const string ContentType = "application/vnd.microsoft.activity"; /// <summary> /// Take a message and create a reply message for it with the routing information /// set up to correctly route a reply to the source message /// </summary> /// <param name="text">text you want to reply with</param> /// <param name="locale">language of your reply</param> /// <returns>message set up to route back to the sender</returns> public Activity CreateReply(string text = null, string locale = null) { Activity reply = new Activity(); reply.Type = ActivityTypes.Message; reply.Timestamp = DateTime.UtcNow; reply.From = new ChannelAccount(id: this.Recipient.Id, name: this.Recipient.Name); reply.Recipient = new ChannelAccount(id: this.From.Id, name: this.From.Name); reply.ReplyToId = this.Id; reply.ServiceUrl = this.ServiceUrl; reply.ChannelId = this.ChannelId; reply.Conversation = new ConversationAccount(isGroup: this.Conversation.IsGroup, id: this.Conversation.Id, name: this.Conversation.Name); reply.Text = text ?? String.Empty; reply.Locale = locale ?? this.Locale; return reply; } /// <summary> /// Extension data for overflow of properties /// </summary> [JsonExtensionData(ReadData = true, WriteData = true)] public JObject Properties { get; set; } = new JObject(); /// <summary> /// Create an instance of the Activity class with IMessageActivity masking /// </summary> public static IMessageActivity CreateMessageActivity() { return new Activity(ActivityTypes.Message); } /// <summary> /// Create an instance of the Activity class with IContactRelationUpdateActivity masking /// </summary> public static IContactRelationUpdateActivity CreateContactRelationUpdateActivity() { return new Activity(ActivityTypes.ContactRelationUpdate); } /// <summary> /// Create an instance of the Activity class with IConversationUpdateActivity masking /// </summary> public static IConversationUpdateActivity CreateConversationUpdateActivity() { return new Activity(ActivityTypes.ConversationUpdate); } /// <summary> /// Create an instance of the Activity class with ITypingActivity masking /// </summary> public static ITypingActivity CreateTypingActivity() { return new Activity(ActivityTypes.Typing); } /// <summary> /// Create an instance of the Activity class with IActivity masking /// </summary> public static IActivity CreatePingActivity() { return new Activity(ActivityTypes.Ping); } /// <summary> /// Create an instance of the Activity class with IEndOfConversationActivity masking /// </summary> public static IEndOfConversationActivity CreateEndOfConversationActivity() { return new Activity(ActivityTypes.EndOfConversation); } /// <summary> /// Create an instance of the Activity class with an IEventActivity masking /// </summary> public static IEventActivity CreateEventActivity() { return new Activity(ActivityTypes.Event); } /// <summary> /// Create an instance of the Activity class with IInvokeActivity masking /// </summary> public static IInvokeActivity CreateInvokeActivity() { return new Activity(ActivityTypes.Invoke); } /// <summary> /// True if the Activity is of the specified activity type /// </summary> protected bool IsActivity(string activity) { return string.Compare(this.Type?.Split('/').First(), activity, true) == 0; } /// <summary> /// Return an IMessageActivity mask if this is a message activity /// </summary> public IMessageActivity AsMessageActivity() { return IsActivity(ActivityTypes.Message) ? this : null; } /// <summary> /// Return an IContactRelationUpdateActivity mask if this is a contact relation update activity /// </summary> public IContactRelationUpdateActivity AsContactRelationUpdateActivity() { return IsActivity(ActivityTypes.ContactRelationUpdate) ? this : null; } /// <summary> /// Return an IInstallationUpdateActivity mask if this is a installation update activity /// </summary> public IInstallationUpdateActivity AsInstallationUpdateActivity() { return IsActivity(ActivityTypes.InstallationUpdate) ? this : null; } /// <summary> /// Return an IConversationUpdateActivity mask if this is a conversation update activity /// </summary> public IConversationUpdateActivity AsConversationUpdateActivity() { return IsActivity(ActivityTypes.ConversationUpdate) ? this : null; } /// <summary> /// Return an ITypingActivity mask if this is a typing activity /// </summary> public ITypingActivity AsTypingActivity() { return IsActivity(ActivityTypes.Typing) ? this : null; } /// <summary> /// Return an IEndOfConversationActivity mask if this is an end of conversation activity /// </summary> public IEndOfConversationActivity AsEndOfConversationActivity() { return IsActivity(ActivityTypes.EndOfConversation) ? this : null; } /// <summary> /// Return an IEventActivity mask if this is an event activity /// </summary> public IEventActivity AsEventActivity() { return IsActivity(ActivityTypes.Event) ? this : null; } /// <summary> /// Return an IInvokeActivity mask if this is an invoke activity /// </summary> public IInvokeActivity AsInvokeActivity() { return IsActivity(ActivityTypes.Invoke) ? this : null; } /// <summary> /// Maps type to activity types /// </summary> /// <param name="type"> The type.</param> /// <returns> The activity type.</returns> public static string GetActivityType(string type) { if (String.Equals(type, ActivityTypes.Message, StringComparison.OrdinalIgnoreCase)) return ActivityTypes.Message; if (String.Equals(type, ActivityTypes.ContactRelationUpdate, StringComparison.OrdinalIgnoreCase)) return ActivityTypes.ContactRelationUpdate; if (String.Equals(type, ActivityTypes.ConversationUpdate, StringComparison.OrdinalIgnoreCase)) return ActivityTypes.ConversationUpdate; if (String.Equals(type, ActivityTypes.DeleteUserData, StringComparison.OrdinalIgnoreCase)) return ActivityTypes.DeleteUserData; if (String.Equals(type, ActivityTypes.Typing, StringComparison.OrdinalIgnoreCase)) return ActivityTypes.Typing; if (String.Equals(type, ActivityTypes.Ping, StringComparison.OrdinalIgnoreCase)) return ActivityTypes.Ping; return $"{Char.ToLower(type[0])}{type.Substring(1)}"; } /// <summary> /// Checks if this (message) activity has content. /// </summary> /// <returns>Returns true, if this message has any content to send. False otherwise.</returns> public bool HasContent() { if (!String.IsNullOrWhiteSpace(this.Text)) return true; if (!String.IsNullOrWhiteSpace(this.Summary)) return true; if (this.Attachments != null && this.Attachments.Any()) return true; if (this.ChannelData != null) return true; return false; } /// <summary> /// Resolves the mentions from the entities of this (message) activity. /// </summary> /// <returns>The array of mentions or an empty array, if none found.</returns> public Mention[] GetMentions() { return this.Entities?.Where(entity => String.Compare(entity.Type, "mention", ignoreCase: true) == 0) .Select(e => e.Properties.ToObject<Mention>()).ToArray() ?? new Mention[0]; } } public static class ActivityExtensions { /// <summary> /// Get StateClient appropriate for this activity /// </summary> /// <param name="credentials">credentials for bot to access state api</param> /// <param name="serviceUrl">alternate serviceurl to use for state service</param> /// <param name="handlers"></param> /// <param name="activity"></param> /// <returns></returns> public static StateClient GetStateClient(this IActivity activity, MicrosoftAppCredentials credentials, string serviceUrl = null, params DelegatingHandler[] handlers) { bool useServiceUrl = (activity.ChannelId == "emulator"); if (useServiceUrl) return new StateClient(new Uri(activity.ServiceUrl), credentials: credentials, handlers: handlers); if (serviceUrl != null) return new StateClient(new Uri(serviceUrl), credentials: credentials, handlers: handlers); return new StateClient(credentials, true, handlers); } /// <summary> /// Get StateClient appropriate for this activity /// </summary> /// <param name="microsoftAppId"></param> /// <param name="microsoftAppPassword"></param> /// <param name="serviceUrl">alternate serviceurl to use for state service</param> /// <param name="handlers"></param> /// <param name="activity"></param> /// <returns></returns> public static StateClient GetStateClient(this IActivity activity, string microsoftAppId = null, string microsoftAppPassword = null, string serviceUrl = null, params DelegatingHandler[] handlers) => GetStateClient(activity, new MicrosoftAppCredentials(microsoftAppId, microsoftAppPassword), serviceUrl, handlers); /// <summary> /// Return the "major" portion of the activity /// </summary> /// <param name="activity"></param> /// <returns>normalized major portion of the activity, aka message/... will return "message"</returns> public static string GetActivityType(this IActivity activity) { var type = activity.Type.Split('/').First(); return Activity.GetActivityType(type); } /// <summary> /// Get channeldata as typed structure /// </summary> /// <param name="activity"></param> /// <typeparam name="TypeT">type to use</typeparam> /// <returns>typed object or default(TypeT)</returns> public static TypeT GetChannelData<TypeT>(this IActivity activity) { if (activity.ChannelData == null) return default(TypeT); return ((JObject)activity.ChannelData).ToObject<TypeT>(); } /// <summary> /// Get channeldata as typed structure /// </summary> /// <param name="activity"></param> /// <typeparam name="TypeT">type to use</typeparam> /// <param name="instance">The resulting instance, if possible</param> /// <returns> /// <c>true</c> if value of <seealso cref="IActivity.ChannelData"/> was coerceable to <typeparamref name="TypeT"/>, <c>false</c> otherwise. /// </returns> public static bool TryGetChannelData<TypeT>(this IActivity activity, out TypeT instance) { instance = default(TypeT); try { if (activity.ChannelData == null) { return false; } instance = GetChannelData<TypeT>(activity); return true; } catch { return false; } } /// <summary> /// Is there a mention of Id in the Text Property /// </summary> /// <param name="id">ChannelAccount.Id</param> /// <param name="activity"></param> /// <returns>true if this id is mentioned in the text</returns> public static bool MentionsId(this IMessageActivity activity, string id) { return activity.GetMentions().Where(mention => mention.Mentioned.Id == id).Any(); } /// <summary> /// Is there a mention of Recipient.Id in the Text Property /// </summary> /// <param name="activity"></param> /// <returns>true if this id is mentioned in the text</returns> public static bool MentionsRecipient(this IMessageActivity activity) { return activity.GetMentions().Where(mention => mention.Mentioned.Id == activity.Recipient.Id).Any(); } /// <summary> /// Remove recipient mention text from Text property /// </summary> /// <param name="activity"></param> /// <returns>new .Text property value</returns> public static string RemoveRecipientMention(this IMessageActivity activity) { return activity.RemoveMentionText(activity.Recipient.Id); } /// <summary> /// Replace any mention text for given id from Text property /// </summary> /// <param name="id">id to match</param> /// <param name="activity"></param> /// <returns>new .Text property value</returns> public static string RemoveMentionText(this IMessageActivity activity, string id) { foreach (var mention in activity.GetMentions().Where(mention => mention.Mentioned.Id == id)) { activity.Text = Regex.Replace(activity.Text, mention.Text, "", RegexOptions.IgnoreCase); } return activity.Text; } } }
// // Copyright (c) Microsoft. All rights reserved. // // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media.Media3D; namespace CubeAnimationDemo { public class Trackball { private Vector3D _center; private bool _centered; // The state of the trackball private bool _enabled; private Point _point; // Initial point of drag private bool _rotating; private Quaternion _rotation; private Quaternion _rotationDelta; // Change to rotation because of this drag private double _scale; private double _scaleDelta; // Change to scale because of this drag // The state of the current drag private bool _scaling; private List<Viewport3D> _slaves; private Vector3D _translate; private Vector3D _translateDelta; public Trackball() { Reset(); } public List<Viewport3D> Slaves { get { return _slaves ?? (_slaves = new List<Viewport3D>()); } set { _slaves = value; } } public bool Enabled { get { return _enabled && (_slaves != null) && (_slaves.Count > 0); } set { _enabled = value; } } public void Attach(FrameworkElement element) { element.MouseMove += MouseMoveHandler; element.MouseRightButtonDown += MouseDownHandler; element.MouseRightButtonUp += MouseUpHandler; element.MouseWheel += OnMouseWheel; } public void Detach(FrameworkElement element) { element.MouseMove -= MouseMoveHandler; element.MouseRightButtonDown -= MouseDownHandler; element.MouseRightButtonUp -= MouseUpHandler; element.MouseWheel -= OnMouseWheel; } // Updates the matrices of the slaves using the rotation quaternion. private void UpdateSlaves(Quaternion q, double s, Vector3D t) { if (_slaves != null) { foreach (var i in _slaves) { var mv = i.Children[0] as ModelVisual3D; var t3Dg = mv.Transform as Transform3DGroup; var groupScaleTransform = t3Dg.Children[0] as ScaleTransform3D; var groupRotateTransform = t3Dg.Children[1] as RotateTransform3D; var groupTranslateTransform = t3Dg.Children[2] as TranslateTransform3D; groupScaleTransform.ScaleX = s; groupScaleTransform.ScaleY = s; groupScaleTransform.ScaleZ = s; groupRotateTransform.Rotation = new AxisAngleRotation3D(q.Axis, q.Angle); groupTranslateTransform.OffsetX = t.X; groupTranslateTransform.OffsetY = t.Y; groupTranslateTransform.OffsetZ = t.Z; } } } private void MouseMoveHandler(object sender, MouseEventArgs e) { if (!Enabled) return; e.Handled = true; var el = (UIElement) sender; if (el.IsMouseCaptured) { var delta = _point - e.MouseDevice.GetPosition(el); delta /= 2; var q = _rotation; if (_rotating) { // We can redefine this 2D mouse delta as a 3D mouse delta // where "into the screen" is Z var mouse = new Vector3D(delta.X, -delta.Y, 0); var axis = Vector3D.CrossProduct(mouse, new Vector3D(0, 0, 1)); var len = axis.Length; if (len < 0.00001 || _scaling) _rotationDelta = new Quaternion(new Vector3D(0, 0, 1), 0); else _rotationDelta = new Quaternion(axis, len); q = _rotationDelta*_rotation; } else { delta /= 20; _translateDelta.X = delta.X*-1; _translateDelta.Y = delta.Y; } var t = _translate + _translateDelta; UpdateSlaves(q, _scale*_scaleDelta, t); } } private void MouseDownHandler(object sender, MouseButtonEventArgs e) { if (!Enabled) return; e.Handled = true; if (Keyboard.IsKeyDown(Key.F1)) { Reset(); return; } var el = (UIElement) sender; _point = e.MouseDevice.GetPosition(el); // Initialize the center of rotation to the lookatpoint if (!_centered) { var camera = (ProjectionCamera) _slaves[0].Camera; _center = camera.LookDirection; _centered = true; } _scaling = (e.MiddleButton == MouseButtonState.Pressed); _rotating = Keyboard.IsKeyDown(Key.Space) == false; el.CaptureMouse(); } private void MouseUpHandler(object sender, MouseButtonEventArgs e) { if (!_enabled) return; e.Handled = true; // Stuff the current initial + delta into initial so when we next move we // start at the right place. if (_rotating) _rotation = _rotationDelta*_rotation; else { _translate += _translateDelta; _translateDelta.X = 0; _translateDelta.Y = 0; } //_scale = _scaleDelta*_scale; var el = (UIElement) sender; el.ReleaseMouseCapture(); } private void OnMouseWheel(object sender, MouseWheelEventArgs e) { e.Handled = true; _scaleDelta += e.Delta/(double) 1000; var q = _rotation; UpdateSlaves(q, _scale*_scaleDelta, _translate); } private void MouseDoubleClickHandler(object sender, MouseButtonEventArgs e) { Reset(); } private void Reset() { _rotation = new Quaternion(0, 0, 0, 1); _scale = 1; _translate.X = 0; _translate.Y = 0; _translate.Z = 0; _translateDelta.X = 0; _translateDelta.Y = 0; _translateDelta.Z = 0; // Clear delta too, because if reset is called because of a double click then the mouse // up handler will also be called and this way it won't do anything. _rotationDelta = Quaternion.Identity; _scaleDelta = 1; UpdateSlaves(_rotation, _scale, _translate); } } }
// 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. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by google-apis-code-generator 1.5.1 // C# generator version: 1.38.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * IAM Service Account Credentials API Version v1 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials'>IAM Service Account Credentials API</a> * <tr><th>API Version<td>v1 * <tr><th>API Rev<td>20190125 (1485) * <tr><th>API Docs * <td><a href='https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials'> * https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials</a> * <tr><th>Discovery Name<td>iamcredentials * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using IAM Service Account Credentials API can be found at * <a href='https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials'>https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials</a>. * * For more information about the Google APIs Client Library for .NET, see * <a href='https://developers.google.com/api-client-library/dotnet/get_started'> * https://developers.google.com/api-client-library/dotnet/get_started</a> */ namespace Google.Apis.IAMCredentials.v1 { /// <summary>The IAMCredentials Service.</summary> public class IAMCredentialsService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public IAMCredentialsService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public IAMCredentialsService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { projects = new ProjectsResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features { get { return new string[0]; } } /// <summary>Gets the service name.</summary> public override string Name { get { return "iamcredentials"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://iamcredentials.googleapis.com/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return ""; } } #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri { get { return "https://iamcredentials.googleapis.com/batch"; } } /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath { get { return "batch"; } } #endif /// <summary>Available OAuth 2.0 scopes for use with the IAM Service Account Credentials API.</summary> public class Scope { /// <summary>View and manage your data across Google Cloud Platform services</summary> public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; } /// <summary>Available OAuth 2.0 scope constants for use with the IAM Service Account Credentials API.</summary> public static class ScopeConstants { /// <summary>View and manage your data across Google Cloud Platform services</summary> public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; } private readonly ProjectsResource projects; /// <summary>Gets the Projects resource.</summary> public virtual ProjectsResource Projects { get { return projects; } } } ///<summary>A base abstract class for IAMCredentials requests.</summary> public abstract class IAMCredentialsBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new IAMCredentialsBaseServiceRequest instance.</summary> protected IAMCredentialsBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> /// [default: json] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto, } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string /// assigned to a user, but should not exceed 40 characters.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes IAMCredentials parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add( "callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "projects" collection of methods.</summary> public class ProjectsResource { private const string Resource = "projects"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public ProjectsResource(Google.Apis.Services.IClientService service) { this.service = service; serviceAccounts = new ServiceAccountsResource(service); } private readonly ServiceAccountsResource serviceAccounts; /// <summary>Gets the ServiceAccounts resource.</summary> public virtual ServiceAccountsResource ServiceAccounts { get { return serviceAccounts; } } /// <summary>The "serviceAccounts" collection of methods.</summary> public class ServiceAccountsResource { private const string Resource = "serviceAccounts"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public ServiceAccountsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Generates an OAuth 2.0 access token for a service account.</summary> /// <param name="body">The body of the request.</param> /// <param name="name">The resource name of the service account for which the credentials are requested, in the /// following format: `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`.</param> public virtual GenerateAccessTokenRequest GenerateAccessToken(Google.Apis.IAMCredentials.v1.Data.GenerateAccessTokenRequest body, string name) { return new GenerateAccessTokenRequest(service, body, name); } /// <summary>Generates an OAuth 2.0 access token for a service account.</summary> public class GenerateAccessTokenRequest : IAMCredentialsBaseServiceRequest<Google.Apis.IAMCredentials.v1.Data.GenerateAccessTokenResponse> { /// <summary>Constructs a new GenerateAccessToken request.</summary> public GenerateAccessTokenRequest(Google.Apis.Services.IClientService service, Google.Apis.IAMCredentials.v1.Data.GenerateAccessTokenRequest body, string name) : base(service) { Name = name; Body = body; InitParameters(); } /// <summary>The resource name of the service account for which the credentials are requested, in the /// following format: `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.IAMCredentials.v1.Data.GenerateAccessTokenRequest Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "generateAccessToken"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/{+name}:generateAccessToken"; } } /// <summary>Initializes GenerateAccessToken parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/serviceAccounts/[^/]+$", }); } } /// <summary>Generates an OpenID Connect ID token for a service account.</summary> /// <param name="body">The body of the request.</param> /// <param name="name">The resource name of the service account for which the credentials are requested, in the /// following format: `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`.</param> public virtual GenerateIdTokenRequest GenerateIdToken(Google.Apis.IAMCredentials.v1.Data.GenerateIdTokenRequest body, string name) { return new GenerateIdTokenRequest(service, body, name); } /// <summary>Generates an OpenID Connect ID token for a service account.</summary> public class GenerateIdTokenRequest : IAMCredentialsBaseServiceRequest<Google.Apis.IAMCredentials.v1.Data.GenerateIdTokenResponse> { /// <summary>Constructs a new GenerateIdToken request.</summary> public GenerateIdTokenRequest(Google.Apis.Services.IClientService service, Google.Apis.IAMCredentials.v1.Data.GenerateIdTokenRequest body, string name) : base(service) { Name = name; Body = body; InitParameters(); } /// <summary>The resource name of the service account for which the credentials are requested, in the /// following format: `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.IAMCredentials.v1.Data.GenerateIdTokenRequest Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "generateIdToken"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/{+name}:generateIdToken"; } } /// <summary>Initializes GenerateIdToken parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/serviceAccounts/[^/]+$", }); } } /// <param name="body">The body of the request.</param> /// <param name="name">The resource name of the service account for which the credentials are requested, in the /// following format: `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`.</param> public virtual GenerateIdentityBindingAccessTokenRequest GenerateIdentityBindingAccessToken(Google.Apis.IAMCredentials.v1.Data.GenerateIdentityBindingAccessTokenRequest body, string name) { return new GenerateIdentityBindingAccessTokenRequest(service, body, name); } public class GenerateIdentityBindingAccessTokenRequest : IAMCredentialsBaseServiceRequest<Google.Apis.IAMCredentials.v1.Data.GenerateIdentityBindingAccessTokenResponse> { /// <summary>Constructs a new GenerateIdentityBindingAccessToken request.</summary> public GenerateIdentityBindingAccessTokenRequest(Google.Apis.Services.IClientService service, Google.Apis.IAMCredentials.v1.Data.GenerateIdentityBindingAccessTokenRequest body, string name) : base(service) { Name = name; Body = body; InitParameters(); } /// <summary>The resource name of the service account for which the credentials are requested, in the /// following format: `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.IAMCredentials.v1.Data.GenerateIdentityBindingAccessTokenRequest Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "generateIdentityBindingAccessToken"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/{+name}:generateIdentityBindingAccessToken"; } } /// <summary>Initializes GenerateIdentityBindingAccessToken parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/serviceAccounts/[^/]+$", }); } } /// <summary>Signs a blob using a service account's system-managed private key.</summary> /// <param name="body">The body of the request.</param> /// <param name="name">The resource name of the service account for which the credentials are requested, in the /// following format: `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`.</param> public virtual SignBlobRequest SignBlob(Google.Apis.IAMCredentials.v1.Data.SignBlobRequest body, string name) { return new SignBlobRequest(service, body, name); } /// <summary>Signs a blob using a service account's system-managed private key.</summary> public class SignBlobRequest : IAMCredentialsBaseServiceRequest<Google.Apis.IAMCredentials.v1.Data.SignBlobResponse> { /// <summary>Constructs a new SignBlob request.</summary> public SignBlobRequest(Google.Apis.Services.IClientService service, Google.Apis.IAMCredentials.v1.Data.SignBlobRequest body, string name) : base(service) { Name = name; Body = body; InitParameters(); } /// <summary>The resource name of the service account for which the credentials are requested, in the /// following format: `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.IAMCredentials.v1.Data.SignBlobRequest Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "signBlob"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/{+name}:signBlob"; } } /// <summary>Initializes SignBlob parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/serviceAccounts/[^/]+$", }); } } /// <summary>Signs a JWT using a service account's system-managed private key.</summary> /// <param name="body">The body of the request.</param> /// <param name="name">The resource name of the service account for which the credentials are requested, in the /// following format: `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`.</param> public virtual SignJwtRequest SignJwt(Google.Apis.IAMCredentials.v1.Data.SignJwtRequest body, string name) { return new SignJwtRequest(service, body, name); } /// <summary>Signs a JWT using a service account's system-managed private key.</summary> public class SignJwtRequest : IAMCredentialsBaseServiceRequest<Google.Apis.IAMCredentials.v1.Data.SignJwtResponse> { /// <summary>Constructs a new SignJwt request.</summary> public SignJwtRequest(Google.Apis.Services.IClientService service, Google.Apis.IAMCredentials.v1.Data.SignJwtRequest body, string name) : base(service) { Name = name; Body = body; InitParameters(); } /// <summary>The resource name of the service account for which the credentials are requested, in the /// following format: `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.IAMCredentials.v1.Data.SignJwtRequest Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "signJwt"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/{+name}:signJwt"; } } /// <summary>Initializes SignJwt parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^projects/[^/]+/serviceAccounts/[^/]+$", }); } } } } } namespace Google.Apis.IAMCredentials.v1.Data { public class GenerateAccessTokenRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The sequence of service accounts in a delegation chain. Each service account must be granted the /// `roles/iam.serviceAccountTokenCreator` role on its next service account in the chain. The last service /// account in the chain must be granted the `roles/iam.serviceAccountTokenCreator` role on the service account /// that is specified in the `name` field of the request. /// /// The delegates must have the following format: /// `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`</summary> [Newtonsoft.Json.JsonPropertyAttribute("delegates")] public virtual System.Collections.Generic.IList<string> Delegates { get; set; } /// <summary>The desired lifetime duration of the access token in seconds. Must be set to a value less than or /// equal to 3600 (1 hour). If a value is not specified, the token's lifetime will be set to a default value of /// one hour.</summary> [Newtonsoft.Json.JsonPropertyAttribute("lifetime")] public virtual object Lifetime { get; set; } /// <summary>Code to identify the scopes to be included in the OAuth 2.0 access token. See /// https://developers.google.com/identity/protocols/googlescopes for more information. At least one value /// required.</summary> [Newtonsoft.Json.JsonPropertyAttribute("scope")] public virtual System.Collections.Generic.IList<string> Scope { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } public class GenerateAccessTokenResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The OAuth 2.0 access token.</summary> [Newtonsoft.Json.JsonPropertyAttribute("accessToken")] public virtual string AccessToken { get; set; } /// <summary>Token expiration time. The expiration time is always set.</summary> [Newtonsoft.Json.JsonPropertyAttribute("expireTime")] public virtual object ExpireTime { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } public class GenerateIdTokenRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The audience for the token, such as the API or account that this token grants access to.</summary> [Newtonsoft.Json.JsonPropertyAttribute("audience")] public virtual string Audience { get; set; } /// <summary>The sequence of service accounts in a delegation chain. Each service account must be granted the /// `roles/iam.serviceAccountTokenCreator` role on its next service account in the chain. The last service /// account in the chain must be granted the `roles/iam.serviceAccountTokenCreator` role on the service account /// that is specified in the `name` field of the request. /// /// The delegates must have the following format: /// `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`</summary> [Newtonsoft.Json.JsonPropertyAttribute("delegates")] public virtual System.Collections.Generic.IList<string> Delegates { get; set; } /// <summary>Include the service account email in the token. If set to `true`, the token will contain `email` /// and `email_verified` claims.</summary> [Newtonsoft.Json.JsonPropertyAttribute("includeEmail")] public virtual System.Nullable<bool> IncludeEmail { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } public class GenerateIdTokenResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The OpenId Connect ID token.</summary> [Newtonsoft.Json.JsonPropertyAttribute("token")] public virtual string Token { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } public class GenerateIdentityBindingAccessTokenRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Required. Input token. Must be in JWT format according to RFC7523 /// (https://tools.ietf.org/html/rfc7523) and must have 'kid' field in the header. Supported signing algorithms: /// RS256 (RS512, ES256, ES512 coming soon). Mandatory payload fields (along the lines of RFC 7523, section 3): /// - iss: issuer of the token. Must provide a discovery document at $iss/.well-known/openid-configuration . The /// document needs to be formatted according to section 4.2 of the OpenID Connect Discovery 1.0 specification. - /// iat: Issue time in seconds since epoch. Must be in the past. - exp: Expiration time in seconds since epoch. /// Must be less than 48 hours after iat. We recommend to create tokens that last shorter than 6 hours to /// improve security unless business reasons mandate longer expiration times. Shorter token lifetimes are /// generally more secure since tokens that have been exfiltrated by attackers can be used for a shorter time. /// you can configure the maximum lifetime of the incoming token in the configuration of the mapper. The /// resulting Google token will expire within an hour or at "exp", whichever is earlier. - sub: JWT subject, /// identity asserted in the JWT. - aud: Configured in the mapper policy. By default the service account email. /// /// Claims from the incoming token can be transferred into the output token accoding to the mapper /// configuration. The outgoing claim size is limited. Outgoing claims size must be less than 4kB serialized as /// JSON without whitespace. /// /// Example header: { "alg": "RS256", "kid": "92a4265e14ab04d4d228a48d10d4ca31610936f8" } Example payload: { /// "iss": "https://accounts.google.com", "iat": 1517963104, "exp": 1517966704, "aud": /// "https://iamcredentials.googleapis.com/google.iam.credentials.v1.CloudGaia", "sub": "113475438248934895348", /// "my_claims": { "additional_claim": "value" } }</summary> [Newtonsoft.Json.JsonPropertyAttribute("jwt")] public virtual string Jwt { get; set; } /// <summary>Code to identify the scopes to be included in the OAuth 2.0 access token. See /// https://developers.google.com/identity/protocols/googlescopes for more information. At least one value /// required.</summary> [Newtonsoft.Json.JsonPropertyAttribute("scope")] public virtual System.Collections.Generic.IList<string> Scope { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } public class GenerateIdentityBindingAccessTokenResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The OAuth 2.0 access token.</summary> [Newtonsoft.Json.JsonPropertyAttribute("accessToken")] public virtual string AccessToken { get; set; } /// <summary>Token expiration time. The expiration time is always set.</summary> [Newtonsoft.Json.JsonPropertyAttribute("expireTime")] public virtual object ExpireTime { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } public class SignBlobRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The sequence of service accounts in a delegation chain. Each service account must be granted the /// `roles/iam.serviceAccountTokenCreator` role on its next service account in the chain. The last service /// account in the chain must be granted the `roles/iam.serviceAccountTokenCreator` role on the service account /// that is specified in the `name` field of the request. /// /// The delegates must have the following format: /// `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`</summary> [Newtonsoft.Json.JsonPropertyAttribute("delegates")] public virtual System.Collections.Generic.IList<string> Delegates { get; set; } /// <summary>The bytes to sign.</summary> [Newtonsoft.Json.JsonPropertyAttribute("payload")] public virtual string Payload { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } public class SignBlobResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ID of the key used to sign the blob.</summary> [Newtonsoft.Json.JsonPropertyAttribute("keyId")] public virtual string KeyId { get; set; } /// <summary>The signed blob.</summary> [Newtonsoft.Json.JsonPropertyAttribute("signedBlob")] public virtual string SignedBlob { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } public class SignJwtRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The sequence of service accounts in a delegation chain. Each service account must be granted the /// `roles/iam.serviceAccountTokenCreator` role on its next service account in the chain. The last service /// account in the chain must be granted the `roles/iam.serviceAccountTokenCreator` role on the service account /// that is specified in the `name` field of the request. /// /// The delegates must have the following format: /// `projects/-/serviceAccounts/{ACCOUNT_EMAIL_OR_UNIQUEID}`</summary> [Newtonsoft.Json.JsonPropertyAttribute("delegates")] public virtual System.Collections.Generic.IList<string> Delegates { get; set; } /// <summary>The JWT payload to sign: a JSON object that contains a JWT Claims Set.</summary> [Newtonsoft.Json.JsonPropertyAttribute("payload")] public virtual string Payload { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } public class SignJwtResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ID of the key used to sign the JWT.</summary> [Newtonsoft.Json.JsonPropertyAttribute("keyId")] public virtual string KeyId { get; set; } /// <summary>The signed JWT.</summary> [Newtonsoft.Json.JsonPropertyAttribute("signedJwt")] public virtual string SignedJwt { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.IO; #if HAVE_BIG_INTEGER using System.Numerics; #endif using Newtonsoft.Json.Utilities; using System.Globalization; #if !HAVE_LINQ using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json { /// <summary> /// Represents a writer that provides a fast, non-cached, forward-only way of generating JSON data. /// </summary> public abstract partial class JsonWriter : IDisposable { internal enum State { Start = 0, Property = 1, ObjectStart = 2, Object = 3, ArrayStart = 4, Array = 5, ConstructorStart = 6, Constructor = 7, Closed = 8, Error = 9 } // array that gives a new state based on the current state an the token being written private static readonly State[][] StateArray; internal static readonly State[][] StateArrayTempate = new[] { // Start PropertyName ObjectStart Object ArrayStart Array ConstructorStart Constructor Closed Error // /* None */new[] { State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error }, /* StartObject */new[] { State.ObjectStart, State.ObjectStart, State.Error, State.Error, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.Error, State.Error }, /* StartArray */new[] { State.ArrayStart, State.ArrayStart, State.Error, State.Error, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.Error, State.Error }, /* StartConstructor */new[] { State.ConstructorStart, State.ConstructorStart, State.Error, State.Error, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.Error, State.Error }, /* Property */new[] { State.Property, State.Error, State.Property, State.Property, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error }, /* Comment */new[] { State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error }, /* Raw */new[] { State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error }, /* Value (this will be copied) */new[] { State.Start, State.Object, State.Error, State.Error, State.Array, State.Array, State.Constructor, State.Constructor, State.Error, State.Error } }; internal static State[][] BuildStateArray() { List<State[]> allStates = StateArrayTempate.ToList(); State[] errorStates = StateArrayTempate[0]; State[] valueStates = StateArrayTempate[7]; EnumInfo enumValuesAndNames = EnumUtils.GetEnumValuesAndNames(typeof(JsonToken)); foreach (ulong valueToken in enumValuesAndNames.Values) { if (allStates.Count <= (int)valueToken) { JsonToken token = (JsonToken)valueToken; switch (token) { case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Undefined: case JsonToken.Date: case JsonToken.Bytes: allStates.Add(valueStates); break; default: allStates.Add(errorStates); break; } } } return allStates.ToArray(); } static JsonWriter() { StateArray = BuildStateArray(); } private List<JsonPosition> _stack; private JsonPosition _currentPosition; private State _currentState; private Formatting _formatting; /// <summary> /// Gets or sets a value indicating whether the destination should be closed when this writer is closed. /// </summary> /// <value> /// <c>true</c> to close the destination when this writer is closed; otherwise <c>false</c>. The default is <c>true</c>. /// </value> public bool CloseOutput { get; set; } /// <summary> /// Gets or sets a value indicating whether the JSON should be auto-completed when this writer is closed. /// </summary> /// <value> /// <c>true</c> to auto-complete the JSON when this writer is closed; otherwise <c>false</c>. The default is <c>true</c>. /// </value> public bool AutoCompleteOnClose { get; set; } /// <summary> /// Gets the top. /// </summary> /// <value>The top.</value> protected internal int Top { get { int depth = _stack?.Count ?? 0; if (Peek() != JsonContainerType.None) { depth++; } return depth; } } /// <summary> /// Gets the state of the writer. /// </summary> public WriteState WriteState { get { switch (_currentState) { case State.Error: return WriteState.Error; case State.Closed: return WriteState.Closed; case State.Object: case State.ObjectStart: return WriteState.Object; case State.Array: case State.ArrayStart: return WriteState.Array; case State.Constructor: case State.ConstructorStart: return WriteState.Constructor; case State.Property: return WriteState.Property; case State.Start: return WriteState.Start; default: throw JsonWriterException.Create(this, "Invalid state: " + _currentState, null); } } } internal string ContainerPath { get { if (_currentPosition.Type == JsonContainerType.None || _stack == null) { return string.Empty; } return JsonPosition.BuildPath(_stack, null); } } /// <summary> /// Gets the path of the writer. /// </summary> public string Path { get { if (_currentPosition.Type == JsonContainerType.None) { return string.Empty; } bool insideContainer = (_currentState != State.ArrayStart && _currentState != State.ConstructorStart && _currentState != State.ObjectStart); JsonPosition? current = insideContainer ? (JsonPosition?)_currentPosition : null; return JsonPosition.BuildPath(_stack, current); } } private DateFormatHandling _dateFormatHandling; private DateTimeZoneHandling _dateTimeZoneHandling; private StringEscapeHandling _stringEscapeHandling; private FloatFormatHandling _floatFormatHandling; private string _dateFormatString; private CultureInfo _culture; /// <summary> /// Gets or sets a value indicating how JSON text output should be formatted. /// </summary> public Formatting Formatting { get => _formatting; set { if (value < Formatting.None || value > Formatting.Indented) { throw new ArgumentOutOfRangeException(nameof(value)); } _formatting = value; } } /// <summary> /// Gets or sets how dates are written to JSON text. /// </summary> public DateFormatHandling DateFormatHandling { get => _dateFormatHandling; set { if (value < DateFormatHandling.IsoDateFormat || value > DateFormatHandling.MicrosoftDateFormat) { throw new ArgumentOutOfRangeException(nameof(value)); } _dateFormatHandling = value; } } /// <summary> /// Gets or sets how <see cref="DateTime"/> time zones are handled when writing JSON text. /// </summary> public DateTimeZoneHandling DateTimeZoneHandling { get => _dateTimeZoneHandling; set { if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind) { throw new ArgumentOutOfRangeException(nameof(value)); } _dateTimeZoneHandling = value; } } /// <summary> /// Gets or sets how strings are escaped when writing JSON text. /// </summary> public StringEscapeHandling StringEscapeHandling { get => _stringEscapeHandling; set { if (value < StringEscapeHandling.Default || value > StringEscapeHandling.EscapeHtml) { throw new ArgumentOutOfRangeException(nameof(value)); } _stringEscapeHandling = value; OnStringEscapeHandlingChanged(); } } internal virtual void OnStringEscapeHandlingChanged() { // hacky but there is a calculated value that relies on StringEscapeHandling } /// <summary> /// Gets or sets how special floating point numbers, e.g. <see cref="Double.NaN"/>, /// <see cref="Double.PositiveInfinity"/> and <see cref="Double.NegativeInfinity"/>, /// are written to JSON text. /// </summary> public FloatFormatHandling FloatFormatHandling { get => _floatFormatHandling; set { if (value < FloatFormatHandling.String || value > FloatFormatHandling.DefaultValue) { throw new ArgumentOutOfRangeException(nameof(value)); } _floatFormatHandling = value; } } /// <summary> /// Gets or sets how <see cref="DateTime"/> and <see cref="DateTimeOffset"/> values are formatted when writing JSON text. /// </summary> public string DateFormatString { get => _dateFormatString; set => _dateFormatString = value; } /// <summary> /// Gets or sets the culture used when writing JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>. /// </summary> public CultureInfo Culture { get => _culture ?? CultureInfo.InvariantCulture; set => _culture = value; } /// <summary> /// Initializes a new instance of the <see cref="JsonWriter"/> class. /// </summary> protected JsonWriter() { _currentState = State.Start; _formatting = Formatting.None; _dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; CloseOutput = true; AutoCompleteOnClose = true; } internal void UpdateScopeWithFinishedValue() { if (_currentPosition.HasIndex) { _currentPosition.Position++; } } private void Push(JsonContainerType value) { if (_currentPosition.Type != JsonContainerType.None) { if (_stack == null) { _stack = new List<JsonPosition>(); } _stack.Add(_currentPosition); } _currentPosition = new JsonPosition(value); } private JsonContainerType Pop() { JsonPosition oldPosition = _currentPosition; if (_stack != null && _stack.Count > 0) { _currentPosition = _stack[_stack.Count - 1]; _stack.RemoveAt(_stack.Count - 1); } else { _currentPosition = new JsonPosition(); } return oldPosition.Type; } private JsonContainerType Peek() { return _currentPosition.Type; } /// <summary> /// Flushes whatever is in the buffer to the destination and also flushes the destination. /// </summary> public abstract void Flush(); /// <summary> /// Closes this writer. /// If <see cref="CloseOutput"/> is set to <c>true</c>, the destination is also closed. /// If <see cref="AutoCompleteOnClose"/> is set to <c>true</c>, the JSON is auto-completed. /// </summary> public virtual void Close() { if (AutoCompleteOnClose) { AutoCompleteAll(); } } /// <summary> /// Writes the beginning of a JSON object. /// </summary> public virtual void WriteStartObject() { InternalWriteStart(JsonToken.StartObject, JsonContainerType.Object); } /// <summary> /// Writes the end of a JSON object. /// </summary> public virtual void WriteEndObject() { InternalWriteEnd(JsonContainerType.Object); } /// <summary> /// Writes the beginning of a JSON array. /// </summary> public virtual void WriteStartArray() { InternalWriteStart(JsonToken.StartArray, JsonContainerType.Array); } /// <summary> /// Writes the end of an array. /// </summary> public virtual void WriteEndArray() { InternalWriteEnd(JsonContainerType.Array); } /// <summary> /// Writes the start of a constructor with the given name. /// </summary> /// <param name="name">The name of the constructor.</param> public virtual void WriteStartConstructor(string name) { InternalWriteStart(JsonToken.StartConstructor, JsonContainerType.Constructor); } /// <summary> /// Writes the end constructor. /// </summary> public virtual void WriteEndConstructor() { InternalWriteEnd(JsonContainerType.Constructor); } /// <summary> /// Writes the property name of a name/value pair of a JSON object. /// </summary> /// <param name="name">The name of the property.</param> public virtual void WritePropertyName(string name) { InternalWritePropertyName(name); } /// <summary> /// Writes the property name of a name/value pair of a JSON object. /// </summary> /// <param name="name">The name of the property.</param> /// <param name="escape">A flag to indicate whether the text should be escaped when it is written as a JSON property name.</param> public virtual void WritePropertyName(string name, bool escape) { WritePropertyName(name); } /// <summary> /// Writes the end of the current JSON object or array. /// </summary> public virtual void WriteEnd() { WriteEnd(Peek()); } /// <summary> /// Writes the current <see cref="JsonReader"/> token and its children. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> to read the token from.</param> public void WriteToken(JsonReader reader) { WriteToken(reader, true); } /// <summary> /// Writes the current <see cref="JsonReader"/> token. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> to read the token from.</param> /// <param name="writeChildren">A flag indicating whether the current token's children should be written.</param> public void WriteToken(JsonReader reader, bool writeChildren) { ValidationUtils.ArgumentNotNull(reader, nameof(reader)); WriteToken(reader, writeChildren, true, true); } /// <summary> /// Writes the <see cref="JsonToken"/> token and its value. /// </summary> /// <param name="token">The <see cref="JsonToken"/> to write.</param> /// <param name="value"> /// The value to write. /// A value is only required for tokens that have an associated value, e.g. the <see cref="String"/> property name for <see cref="JsonToken.PropertyName"/>. /// <c>null</c> can be passed to the method for tokens that don't have a value, e.g. <see cref="JsonToken.StartObject"/>. /// </param> public void WriteToken(JsonToken token, object value) { switch (token) { case JsonToken.None: // read to next break; case JsonToken.StartObject: WriteStartObject(); break; case JsonToken.StartArray: WriteStartArray(); break; case JsonToken.StartConstructor: ValidationUtils.ArgumentNotNull(value, nameof(value)); WriteStartConstructor(value.ToString()); break; case JsonToken.PropertyName: ValidationUtils.ArgumentNotNull(value, nameof(value)); WritePropertyName(value.ToString()); break; case JsonToken.Comment: WriteComment(value?.ToString()); break; case JsonToken.Integer: ValidationUtils.ArgumentNotNull(value, nameof(value)); #if HAVE_BIG_INTEGER if (value is BigInteger integer) { WriteValue(integer); } else #endif { WriteValue(Convert.ToInt64(value, CultureInfo.InvariantCulture)); } break; case JsonToken.Float: ValidationUtils.ArgumentNotNull(value, nameof(value)); if (value is decimal d) { WriteValue(d); } else if (value is double) { WriteValue((double)value); } else if (value is float) { WriteValue((float)value); } else { WriteValue(Convert.ToDouble(value, CultureInfo.InvariantCulture)); } break; case JsonToken.String: ValidationUtils.ArgumentNotNull(value, nameof(value)); WriteValue(value.ToString()); break; case JsonToken.Boolean: ValidationUtils.ArgumentNotNull(value, nameof(value)); WriteValue(Convert.ToBoolean(value, CultureInfo.InvariantCulture)); break; case JsonToken.Null: WriteNull(); break; case JsonToken.Undefined: WriteUndefined(); break; case JsonToken.EndObject: WriteEndObject(); break; case JsonToken.EndArray: WriteEndArray(); break; case JsonToken.EndConstructor: WriteEndConstructor(); break; case JsonToken.Date: ValidationUtils.ArgumentNotNull(value, nameof(value)); #if HAVE_DATE_TIME_OFFSET if (value is DateTimeOffset dt) { WriteValue(dt); } else #endif { WriteValue(Convert.ToDateTime(value, CultureInfo.InvariantCulture)); } break; case JsonToken.Raw: WriteRawValue(value?.ToString()); break; case JsonToken.Bytes: ValidationUtils.ArgumentNotNull(value, nameof(value)); if (value is Guid guid) { WriteValue(guid); } else { WriteValue((byte[])value); } break; default: throw MiscellaneousUtils.CreateArgumentOutOfRangeException(nameof(token), token, "Unexpected token type."); } } /// <summary> /// Writes the <see cref="JsonToken"/> token. /// </summary> /// <param name="token">The <see cref="JsonToken"/> to write.</param> public void WriteToken(JsonToken token) { WriteToken(token, null); } internal virtual void WriteToken(JsonReader reader, bool writeChildren, bool writeDateConstructorAsDate, bool writeComments) { int initialDepth = CalculateWriteTokenInitialDepth(reader); do { // write a JValue date when the constructor is for a date if (writeDateConstructorAsDate && reader.TokenType == JsonToken.StartConstructor && string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal)) { WriteConstructorDate(reader); } else { if (writeComments || reader.TokenType != JsonToken.Comment) { WriteToken(reader.TokenType, reader.Value); } } } while ( // stop if we have reached the end of the token being read initialDepth - 1 < reader.Depth - (JsonTokenUtils.IsEndToken(reader.TokenType) ? 1 : 0) && writeChildren && reader.Read()); if (initialDepth < CalculateWriteTokenFinalDepth(reader)) { throw JsonWriterException.Create(this, "Unexpected end when reading token.", null); } } private int CalculateWriteTokenInitialDepth(JsonReader reader) { JsonToken type = reader.TokenType; if (type == JsonToken.None) { return -1; } return JsonTokenUtils.IsStartToken(type) ? reader.Depth : reader.Depth + 1; } private int CalculateWriteTokenFinalDepth(JsonReader reader) { JsonToken type = reader.TokenType; if (type == JsonToken.None) { return -1; } return JsonTokenUtils.IsEndToken(type) ? reader.Depth - 1 : reader.Depth; } private void WriteConstructorDate(JsonReader reader) { if (!reader.Read()) { throw JsonWriterException.Create(this, "Unexpected end when reading date constructor.", null); } if (reader.TokenType != JsonToken.Integer) { throw JsonWriterException.Create(this, "Unexpected token when reading date constructor. Expected Integer, got " + reader.TokenType, null); } long ticks = (long)reader.Value; DateTime date = DateTimeUtils.ConvertJavaScriptTicksToDateTime(ticks); if (!reader.Read()) { throw JsonWriterException.Create(this, "Unexpected end when reading date constructor.", null); } if (reader.TokenType != JsonToken.EndConstructor) { throw JsonWriterException.Create(this, "Unexpected token when reading date constructor. Expected EndConstructor, got " + reader.TokenType, null); } WriteValue(date); } private void WriteEnd(JsonContainerType type) { switch (type) { case JsonContainerType.Object: WriteEndObject(); break; case JsonContainerType.Array: WriteEndArray(); break; case JsonContainerType.Constructor: WriteEndConstructor(); break; default: throw JsonWriterException.Create(this, "Unexpected type when writing end: " + type, null); } } private void AutoCompleteAll() { while (Top > 0) { WriteEnd(); } } private JsonToken GetCloseTokenForType(JsonContainerType type) { switch (type) { case JsonContainerType.Object: return JsonToken.EndObject; case JsonContainerType.Array: return JsonToken.EndArray; case JsonContainerType.Constructor: return JsonToken.EndConstructor; default: throw JsonWriterException.Create(this, "No close token for type: " + type, null); } } private void AutoCompleteClose(JsonContainerType type) { int levelsToComplete = CalculateLevelsToComplete(type); for (int i = 0; i < levelsToComplete; i++) { JsonToken token = GetCloseTokenForType(Pop()); if (_currentState == State.Property) { WriteNull(); } if (_formatting == Formatting.Indented) { if (_currentState != State.ObjectStart && _currentState != State.ArrayStart) { WriteIndent(); } } WriteEnd(token); UpdateCurrentState(); } } private int CalculateLevelsToComplete(JsonContainerType type) { int levelsToComplete = 0; if (_currentPosition.Type == type) { levelsToComplete = 1; } else { int top = Top - 2; for (int i = top; i >= 0; i--) { int currentLevel = top - i; if (_stack[currentLevel].Type == type) { levelsToComplete = i + 2; break; } } } if (levelsToComplete == 0) { throw JsonWriterException.Create(this, "No token to close.", null); } return levelsToComplete; } private void UpdateCurrentState() { JsonContainerType currentLevelType = Peek(); switch (currentLevelType) { case JsonContainerType.Object: _currentState = State.Object; break; case JsonContainerType.Array: _currentState = State.Array; break; case JsonContainerType.Constructor: _currentState = State.Array; break; case JsonContainerType.None: _currentState = State.Start; break; default: throw JsonWriterException.Create(this, "Unknown JsonType: " + currentLevelType, null); } } /// <summary> /// Writes the specified end token. /// </summary> /// <param name="token">The end token to write.</param> protected virtual void WriteEnd(JsonToken token) { } /// <summary> /// Writes indent characters. /// </summary> protected virtual void WriteIndent() { } /// <summary> /// Writes the JSON value delimiter. /// </summary> protected virtual void WriteValueDelimiter() { } /// <summary> /// Writes an indent space. /// </summary> protected virtual void WriteIndentSpace() { } internal void AutoComplete(JsonToken tokenBeingWritten) { // gets new state based on the current state and what is being written State newState = StateArray[(int)tokenBeingWritten][(int)_currentState]; if (newState == State.Error) { throw JsonWriterException.Create(this, "Token {0} in state {1} would result in an invalid JSON object.".FormatWith(CultureInfo.InvariantCulture, tokenBeingWritten.ToString(), _currentState.ToString()), null); } if ((_currentState == State.Object || _currentState == State.Array || _currentState == State.Constructor) && tokenBeingWritten != JsonToken.Comment) { WriteValueDelimiter(); } if (_formatting == Formatting.Indented) { if (_currentState == State.Property) { WriteIndentSpace(); } // don't indent a property when it is the first token to be written (i.e. at the start) if ((_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.Constructor || _currentState == State.ConstructorStart) || (tokenBeingWritten == JsonToken.PropertyName && _currentState != State.Start)) { WriteIndent(); } } _currentState = newState; } #region WriteValue methods /// <summary> /// Writes a null value. /// </summary> public virtual void WriteNull() { InternalWriteValue(JsonToken.Null); } /// <summary> /// Writes an undefined value. /// </summary> public virtual void WriteUndefined() { InternalWriteValue(JsonToken.Undefined); } /// <summary> /// Writes raw JSON without changing the writer's state. /// </summary> /// <param name="json">The raw JSON to write.</param> public virtual void WriteRaw(string json) { InternalWriteRaw(); } /// <summary> /// Writes raw JSON where a value is expected and updates the writer's state. /// </summary> /// <param name="json">The raw JSON to write.</param> public virtual void WriteRawValue(string json) { // hack. want writer to change state as if a value had been written UpdateScopeWithFinishedValue(); AutoComplete(JsonToken.Undefined); WriteRaw(json); } /// <summary> /// Writes a <see cref="String"/> value. /// </summary> /// <param name="value">The <see cref="String"/> value to write.</param> public virtual void WriteValue(string value) { InternalWriteValue(JsonToken.String); } /// <summary> /// Writes a <see cref="Int32"/> value. /// </summary> /// <param name="value">The <see cref="Int32"/> value to write.</param> public virtual void WriteValue(int value) { InternalWriteValue(JsonToken.Integer); } /// <summary> /// Writes a <see cref="UInt32"/> value. /// </summary> /// <param name="value">The <see cref="UInt32"/> value to write.</param> [CLSCompliant(false)] public virtual void WriteValue(uint value) { InternalWriteValue(JsonToken.Integer); } /// <summary> /// Writes a <see cref="Int64"/> value. /// </summary> /// <param name="value">The <see cref="Int64"/> value to write.</param> public virtual void WriteValue(long value) { InternalWriteValue(JsonToken.Integer); } /// <summary> /// Writes a <see cref="UInt64"/> value. /// </summary> /// <param name="value">The <see cref="UInt64"/> value to write.</param> [CLSCompliant(false)] public virtual void WriteValue(ulong value) { InternalWriteValue(JsonToken.Integer); } /// <summary> /// Writes a <see cref="Single"/> value. /// </summary> /// <param name="value">The <see cref="Single"/> value to write.</param> public virtual void WriteValue(float value) { InternalWriteValue(JsonToken.Float); } /// <summary> /// Writes a <see cref="Double"/> value. /// </summary> /// <param name="value">The <see cref="Double"/> value to write.</param> public virtual void WriteValue(double value) { InternalWriteValue(JsonToken.Float); } /// <summary> /// Writes a <see cref="Boolean"/> value. /// </summary> /// <param name="value">The <see cref="Boolean"/> value to write.</param> public virtual void WriteValue(bool value) { InternalWriteValue(JsonToken.Boolean); } /// <summary> /// Writes a <see cref="Int16"/> value. /// </summary> /// <param name="value">The <see cref="Int16"/> value to write.</param> public virtual void WriteValue(short value) { InternalWriteValue(JsonToken.Integer); } /// <summary> /// Writes a <see cref="UInt16"/> value. /// </summary> /// <param name="value">The <see cref="UInt16"/> value to write.</param> [CLSCompliant(false)] public virtual void WriteValue(ushort value) { InternalWriteValue(JsonToken.Integer); } /// <summary> /// Writes a <see cref="Char"/> value. /// </summary> /// <param name="value">The <see cref="Char"/> value to write.</param> public virtual void WriteValue(char value) { InternalWriteValue(JsonToken.String); } /// <summary> /// Writes a <see cref="Byte"/> value. /// </summary> /// <param name="value">The <see cref="Byte"/> value to write.</param> public virtual void WriteValue(byte value) { InternalWriteValue(JsonToken.Integer); } /// <summary> /// Writes a <see cref="SByte"/> value. /// </summary> /// <param name="value">The <see cref="SByte"/> value to write.</param> [CLSCompliant(false)] public virtual void WriteValue(sbyte value) { InternalWriteValue(JsonToken.Integer); } /// <summary> /// Writes a <see cref="Decimal"/> value. /// </summary> /// <param name="value">The <see cref="Decimal"/> value to write.</param> public virtual void WriteValue(decimal value) { InternalWriteValue(JsonToken.Float); } /// <summary> /// Writes a <see cref="DateTime"/> value. /// </summary> /// <param name="value">The <see cref="DateTime"/> value to write.</param> public virtual void WriteValue(DateTime value) { InternalWriteValue(JsonToken.Date); } #if HAVE_DATE_TIME_OFFSET /// <summary> /// Writes a <see cref="DateTimeOffset"/> value. /// </summary> /// <param name="value">The <see cref="DateTimeOffset"/> value to write.</param> public virtual void WriteValue(DateTimeOffset value) { InternalWriteValue(JsonToken.Date); } #endif /// <summary> /// Writes a <see cref="Guid"/> value. /// </summary> /// <param name="value">The <see cref="Guid"/> value to write.</param> public virtual void WriteValue(Guid value) { InternalWriteValue(JsonToken.String); } /// <summary> /// Writes a <see cref="TimeSpan"/> value. /// </summary> /// <param name="value">The <see cref="TimeSpan"/> value to write.</param> public virtual void WriteValue(TimeSpan value) { InternalWriteValue(JsonToken.String); } /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="Int32"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Int32"/> value to write.</param> public virtual void WriteValue(int? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="UInt32"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="UInt32"/> value to write.</param> [CLSCompliant(false)] public virtual void WriteValue(uint? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="Int64"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Int64"/> value to write.</param> public virtual void WriteValue(long? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="UInt64"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="UInt64"/> value to write.</param> [CLSCompliant(false)] public virtual void WriteValue(ulong? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="Single"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Single"/> value to write.</param> public virtual void WriteValue(float? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="Double"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Double"/> value to write.</param> public virtual void WriteValue(double? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="Boolean"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Boolean"/> value to write.</param> public virtual void WriteValue(bool? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="Int16"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Int16"/> value to write.</param> public virtual void WriteValue(short? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="UInt16"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="UInt16"/> value to write.</param> [CLSCompliant(false)] public virtual void WriteValue(ushort? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="Char"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Char"/> value to write.</param> public virtual void WriteValue(char? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="Byte"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Byte"/> value to write.</param> public virtual void WriteValue(byte? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="SByte"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="SByte"/> value to write.</param> [CLSCompliant(false)] public virtual void WriteValue(sbyte? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="Decimal"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Decimal"/> value to write.</param> public virtual void WriteValue(decimal? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="DateTime"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="DateTime"/> value to write.</param> public virtual void WriteValue(DateTime? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } #if HAVE_DATE_TIME_OFFSET /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/> value to write.</param> public virtual void WriteValue(DateTimeOffset? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } #endif /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="Guid"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Guid"/> value to write.</param> public virtual void WriteValue(Guid? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="TimeSpan"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="TimeSpan"/> value to write.</param> public virtual void WriteValue(TimeSpan? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } /// <summary> /// Writes a <see cref="Byte"/>[] value. /// </summary> /// <param name="value">The <see cref="Byte"/>[] value to write.</param> public virtual void WriteValue(byte[] value) { if (value == null) { WriteNull(); } else { InternalWriteValue(JsonToken.Bytes); } } /// <summary> /// Writes a <see cref="Uri"/> value. /// </summary> /// <param name="value">The <see cref="Uri"/> value to write.</param> public virtual void WriteValue(Uri value) { if (value == null) { WriteNull(); } else { InternalWriteValue(JsonToken.String); } } /// <summary> /// Writes a <see cref="Object"/> value. /// An error will raised if the value cannot be written as a single JSON token. /// </summary> /// <param name="value">The <see cref="Object"/> value to write.</param> public virtual void WriteValue(object value) { if (value == null) { WriteNull(); } else { #if HAVE_BIG_INTEGER // this is here because adding a WriteValue(BigInteger) to JsonWriter will // mean the user has to add a reference to System.Numerics.dll if (value is BigInteger) { throw CreateUnsupportedTypeException(this, value); } #endif WriteValue(this, ConvertUtils.GetTypeCode(value.GetType()), value); } } #endregion /// <summary> /// Writes a comment <c>/*...*/</c> containing the specified text. /// </summary> /// <param name="text">Text to place inside the comment.</param> public virtual void WriteComment(string text) { InternalWriteComment(); } /// <summary> /// Writes the given white space. /// </summary> /// <param name="ws">The string of white space characters.</param> public virtual void WriteWhitespace(string ws) { InternalWriteWhitespace(ws); } void IDisposable.Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (_currentState != State.Closed && disposing) { Close(); } } internal static void WriteValue(JsonWriter writer, PrimitiveTypeCode typeCode, object value) { while (true) { switch (typeCode) { case PrimitiveTypeCode.Char: writer.WriteValue((char)value); return; case PrimitiveTypeCode.CharNullable: writer.WriteValue((value == null) ? (char?)null : (char)value); return; case PrimitiveTypeCode.Boolean: writer.WriteValue((bool)value); return; case PrimitiveTypeCode.BooleanNullable: writer.WriteValue((value == null) ? (bool?)null : (bool)value); return; case PrimitiveTypeCode.SByte: writer.WriteValue((sbyte)value); return; case PrimitiveTypeCode.SByteNullable: writer.WriteValue((value == null) ? (sbyte?)null : (sbyte)value); return; case PrimitiveTypeCode.Int16: writer.WriteValue((short)value); return; case PrimitiveTypeCode.Int16Nullable: writer.WriteValue((value == null) ? (short?)null : (short)value); return; case PrimitiveTypeCode.UInt16: writer.WriteValue((ushort)value); return; case PrimitiveTypeCode.UInt16Nullable: writer.WriteValue((value == null) ? (ushort?)null : (ushort)value); return; case PrimitiveTypeCode.Int32: writer.WriteValue((int)value); return; case PrimitiveTypeCode.Int32Nullable: writer.WriteValue((value == null) ? (int?)null : (int)value); return; case PrimitiveTypeCode.Byte: writer.WriteValue((byte)value); return; case PrimitiveTypeCode.ByteNullable: writer.WriteValue((value == null) ? (byte?)null : (byte)value); return; case PrimitiveTypeCode.UInt32: writer.WriteValue((uint)value); return; case PrimitiveTypeCode.UInt32Nullable: writer.WriteValue((value == null) ? (uint?)null : (uint)value); return; case PrimitiveTypeCode.Int64: writer.WriteValue((long)value); return; case PrimitiveTypeCode.Int64Nullable: writer.WriteValue((value == null) ? (long?)null : (long)value); return; case PrimitiveTypeCode.UInt64: writer.WriteValue((ulong)value); return; case PrimitiveTypeCode.UInt64Nullable: writer.WriteValue((value == null) ? (ulong?)null : (ulong)value); return; case PrimitiveTypeCode.Single: writer.WriteValue((float)value); return; case PrimitiveTypeCode.SingleNullable: writer.WriteValue((value == null) ? (float?)null : (float)value); return; case PrimitiveTypeCode.Double: writer.WriteValue((double)value); return; case PrimitiveTypeCode.DoubleNullable: writer.WriteValue((value == null) ? (double?)null : (double)value); return; case PrimitiveTypeCode.DateTime: writer.WriteValue((DateTime)value); return; case PrimitiveTypeCode.DateTimeNullable: writer.WriteValue((value == null) ? (DateTime?)null : (DateTime)value); return; #if HAVE_DATE_TIME_OFFSET case PrimitiveTypeCode.DateTimeOffset: writer.WriteValue((DateTimeOffset)value); return; case PrimitiveTypeCode.DateTimeOffsetNullable: writer.WriteValue((value == null) ? (DateTimeOffset?)null : (DateTimeOffset)value); return; #endif case PrimitiveTypeCode.Decimal: writer.WriteValue((decimal)value); return; case PrimitiveTypeCode.DecimalNullable: writer.WriteValue((value == null) ? (decimal?)null : (decimal)value); return; case PrimitiveTypeCode.Guid: writer.WriteValue((Guid)value); return; case PrimitiveTypeCode.GuidNullable: writer.WriteValue((value == null) ? (Guid?)null : (Guid)value); return; case PrimitiveTypeCode.TimeSpan: writer.WriteValue((TimeSpan)value); return; case PrimitiveTypeCode.TimeSpanNullable: writer.WriteValue((value == null) ? (TimeSpan?)null : (TimeSpan)value); return; #if HAVE_BIG_INTEGER case PrimitiveTypeCode.BigInteger: // this will call to WriteValue(object) writer.WriteValue((BigInteger)value); return; case PrimitiveTypeCode.BigIntegerNullable: // this will call to WriteValue(object) writer.WriteValue((value == null) ? (BigInteger?)null : (BigInteger)value); return; #endif case PrimitiveTypeCode.Uri: writer.WriteValue((Uri)value); return; case PrimitiveTypeCode.String: writer.WriteValue((string)value); return; case PrimitiveTypeCode.Bytes: writer.WriteValue((byte[])value); return; #if HAVE_DB_NULL_TYPE_CODE case PrimitiveTypeCode.DBNull: writer.WriteNull(); return; #endif default: #if HAVE_ICONVERTIBLE if (value is IConvertible convertible) { ResolveConvertibleValue(convertible, out typeCode, out value); continue; } #endif // write an unknown null value, fix https://github.com/JamesNK/Newtonsoft.Json/issues/1460 if (value == null) { writer.WriteNull(); return; } throw CreateUnsupportedTypeException(writer, value); } } } #if HAVE_ICONVERTIBLE private static void ResolveConvertibleValue(IConvertible convertible, out PrimitiveTypeCode typeCode, out object value) { // the value is a non-standard IConvertible // convert to the underlying value and retry TypeInformation typeInformation = ConvertUtils.GetTypeInformation(convertible); // if convertible has an underlying typecode of Object then attempt to convert it to a string typeCode = typeInformation.TypeCode == PrimitiveTypeCode.Object ? PrimitiveTypeCode.String : typeInformation.TypeCode; Type resolvedType = typeInformation.TypeCode == PrimitiveTypeCode.Object ? typeof(string) : typeInformation.Type; value = convertible.ToType(resolvedType, CultureInfo.InvariantCulture); } #endif private static JsonWriterException CreateUnsupportedTypeException(JsonWriter writer, object value) { return JsonWriterException.Create(writer, "Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), null); } /// <summary> /// Sets the state of the <see cref="JsonWriter"/>. /// </summary> /// <param name="token">The <see cref="JsonToken"/> being written.</param> /// <param name="value">The value being written.</param> protected void SetWriteState(JsonToken token, object value) { switch (token) { case JsonToken.StartObject: InternalWriteStart(token, JsonContainerType.Object); break; case JsonToken.StartArray: InternalWriteStart(token, JsonContainerType.Array); break; case JsonToken.StartConstructor: InternalWriteStart(token, JsonContainerType.Constructor); break; case JsonToken.PropertyName: if (!(value is string)) { throw new ArgumentException("A name is required when setting property name state.", nameof(value)); } InternalWritePropertyName((string)value); break; case JsonToken.Comment: InternalWriteComment(); break; case JsonToken.Raw: InternalWriteRaw(); break; case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Date: case JsonToken.Bytes: case JsonToken.Null: case JsonToken.Undefined: InternalWriteValue(token); break; case JsonToken.EndObject: InternalWriteEnd(JsonContainerType.Object); break; case JsonToken.EndArray: InternalWriteEnd(JsonContainerType.Array); break; case JsonToken.EndConstructor: InternalWriteEnd(JsonContainerType.Constructor); break; default: throw new ArgumentOutOfRangeException(nameof(token)); } } internal void InternalWriteEnd(JsonContainerType container) { AutoCompleteClose(container); } internal void InternalWritePropertyName(string name) { _currentPosition.PropertyName = name; AutoComplete(JsonToken.PropertyName); } internal void InternalWriteRaw() { } internal void InternalWriteStart(JsonToken token, JsonContainerType container) { UpdateScopeWithFinishedValue(); AutoComplete(token); Push(container); } internal void InternalWriteValue(JsonToken token) { UpdateScopeWithFinishedValue(); AutoComplete(token); } internal void InternalWriteWhitespace(string ws) { if (ws != null) { if (!StringUtils.IsWhiteSpace(ws)) { throw JsonWriterException.Create(this, "Only white space characters should be used.", null); } } } internal void InternalWriteComment() { AutoComplete(JsonToken.Comment); } } }
#region License /* * HttpListenerRequest.cs * * This code is derived from HttpListenerRequest.cs (System.Net) of Mono * (http://www.mono-project.com). * * The MIT License * * Copyright (c) 2005 Novell, Inc. (http://www.novell.com) * Copyright (c) 2012-2021 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Authors /* * Authors: * - Gonzalo Paniagua Javier <gonzalo@novell.com> */ #endregion using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Globalization; using System.IO; using System.Security.Cryptography.X509Certificates; using System.Text; namespace WebSocketSharp.Net { /// <summary> /// Represents an incoming HTTP request to a <see cref="HttpListener"/> /// instance. /// </summary> /// <remarks> /// This class cannot be inherited. /// </remarks> public sealed class HttpListenerRequest { #region Private Fields private static readonly byte[] _100continue; private string[] _acceptTypes; private bool _chunked; private HttpConnection _connection; private Encoding _contentEncoding; private long _contentLength; private HttpListenerContext _context; private CookieCollection _cookies; private WebHeaderCollection _headers; private string _httpMethod; private Stream _inputStream; private Version _protocolVersion; private NameValueCollection _queryString; private string _rawUrl; private Guid _requestTraceIdentifier; private Uri _url; private Uri _urlReferrer; private bool _urlSet; private string _userHostName; private string[] _userLanguages; #endregion #region Static Constructor static HttpListenerRequest () { _100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n"); } #endregion #region Internal Constructors internal HttpListenerRequest (HttpListenerContext context) { _context = context; _connection = context.Connection; _contentLength = -1; _headers = new WebHeaderCollection (); _requestTraceIdentifier = Guid.NewGuid (); } #endregion #region Public Properties /// <summary> /// Gets the media types that are acceptable for the client. /// </summary> /// <value> /// <para> /// An array of <see cref="string"/> that contains the names of the media /// types specified in the value of the Accept header. /// </para> /// <para> /// <see langword="null"/> if the header is not present. /// </para> /// </value> public string[] AcceptTypes { get { var val = _headers["Accept"]; if (val == null) return null; if (_acceptTypes == null) { _acceptTypes = val .SplitHeaderValue (',') .TrimEach () .ToList () .ToArray (); } return _acceptTypes; } } /// <summary> /// Gets an error code that identifies a problem with the certificate /// provided by the client. /// </summary> /// <value> /// An <see cref="int"/> that represents an error code. /// </value> /// <exception cref="NotSupportedException"> /// This property is not supported. /// </exception> public int ClientCertificateError { get { throw new NotSupportedException (); } } /// <summary> /// Gets the encoding for the entity body data included in the request. /// </summary> /// <value> /// <para> /// A <see cref="Encoding"/> converted from the charset value of the /// Content-Type header. /// </para> /// <para> /// <see cref="Encoding.UTF8"/> if the charset value is not available. /// </para> /// </value> public Encoding ContentEncoding { get { if (_contentEncoding == null) _contentEncoding = getContentEncoding (); return _contentEncoding; } } /// <summary> /// Gets the length in bytes of the entity body data included in the /// request. /// </summary> /// <value> /// <para> /// A <see cref="long"/> converted from the value of the Content-Length /// header. /// </para> /// <para> /// -1 if the header is not present. /// </para> /// </value> public long ContentLength64 { get { return _contentLength; } } /// <summary> /// Gets the media type of the entity body data included in the request. /// </summary> /// <value> /// <para> /// A <see cref="string"/> that represents the value of the Content-Type /// header. /// </para> /// <para> /// <see langword="null"/> if the header is not present. /// </para> /// </value> public string ContentType { get { return _headers["Content-Type"]; } } /// <summary> /// Gets the cookies included in the request. /// </summary> /// <value> /// <para> /// A <see cref="CookieCollection"/> that contains the cookies. /// </para> /// <para> /// An empty collection if not included. /// </para> /// </value> public CookieCollection Cookies { get { if (_cookies == null) _cookies = _headers.GetCookies (false); return _cookies; } } /// <summary> /// Gets a value indicating whether the request has the entity body data. /// </summary> /// <value> /// <c>true</c> if the request has the entity body data; otherwise, /// <c>false</c>. /// </value> public bool HasEntityBody { get { return _contentLength > 0 || _chunked; } } /// <summary> /// Gets the headers included in the request. /// </summary> /// <value> /// A <see cref="NameValueCollection"/> that contains the headers. /// </value> public NameValueCollection Headers { get { return _headers; } } /// <summary> /// Gets the HTTP method specified by the client. /// </summary> /// <value> /// A <see cref="string"/> that represents the HTTP method specified in /// the request line. /// </value> public string HttpMethod { get { return _httpMethod; } } /// <summary> /// Gets a stream that contains the entity body data included in /// the request. /// </summary> /// <value> /// <para> /// A <see cref="Stream"/> that contains the entity body data. /// </para> /// <para> /// <see cref="Stream.Null"/> if the entity body data is not available. /// </para> /// </value> public Stream InputStream { get { if (_inputStream == null) { _inputStream = _contentLength > 0 || _chunked ? _connection .GetRequestStream (_contentLength, _chunked) : Stream.Null; } return _inputStream; } } /// <summary> /// Gets a value indicating whether the client is authenticated. /// </summary> /// <value> /// <c>true</c> if the client is authenticated; otherwise, <c>false</c>. /// </value> public bool IsAuthenticated { get { return _context.User != null; } } /// <summary> /// Gets a value indicating whether the request is sent from the local /// computer. /// </summary> /// <value> /// <c>true</c> if the request is sent from the same computer as the server; /// otherwise, <c>false</c>. /// </value> public bool IsLocal { get { return _connection.IsLocal; } } /// <summary> /// Gets a value indicating whether a secure connection is used to send /// the request. /// </summary> /// <value> /// <c>true</c> if the connection is secure; otherwise, <c>false</c>. /// </value> public bool IsSecureConnection { get { return _connection.IsSecure; } } /// <summary> /// Gets a value indicating whether the request is a WebSocket handshake /// request. /// </summary> /// <value> /// <c>true</c> if the request is a WebSocket handshake request; otherwise, /// <c>false</c>. /// </value> public bool IsWebSocketRequest { get { return _httpMethod == "GET" && _headers.Upgrades ("websocket"); } } /// <summary> /// Gets a value indicating whether a persistent connection is requested. /// </summary> /// <value> /// <c>true</c> if the request specifies that the connection is kept open; /// otherwise, <c>false</c>. /// </value> public bool KeepAlive { get { return _headers.KeepsAlive (_protocolVersion); } } /// <summary> /// Gets the endpoint to which the request is sent. /// </summary> /// <value> /// A <see cref="System.Net.IPEndPoint"/> that represents the server IP /// address and port number. /// </value> public System.Net.IPEndPoint LocalEndPoint { get { return _connection.LocalEndPoint; } } /// <summary> /// Gets the HTTP version specified by the client. /// </summary> /// <value> /// A <see cref="Version"/> that represents the HTTP version specified in /// the request line. /// </value> public Version ProtocolVersion { get { return _protocolVersion; } } /// <summary> /// Gets the query string included in the request. /// </summary> /// <value> /// <para> /// A <see cref="NameValueCollection"/> that contains the query /// parameters. /// </para> /// <para> /// An empty collection if not included. /// </para> /// </value> public NameValueCollection QueryString { get { if (_queryString == null) { var url = Url; _queryString = QueryStringCollection .Parse ( url != null ? url.Query : null, Encoding.UTF8 ); } return _queryString; } } /// <summary> /// Gets the raw URL specified by the client. /// </summary> /// <value> /// A <see cref="string"/> that represents the request target specified in /// the request line. /// </value> public string RawUrl { get { return _rawUrl; } } /// <summary> /// Gets the endpoint from which the request is sent. /// </summary> /// <value> /// A <see cref="System.Net.IPEndPoint"/> that represents the client IP /// address and port number. /// </value> public System.Net.IPEndPoint RemoteEndPoint { get { return _connection.RemoteEndPoint; } } /// <summary> /// Gets the trace identifier of the request. /// </summary> /// <value> /// A <see cref="Guid"/> that represents the trace identifier. /// </value> public Guid RequestTraceIdentifier { get { return _requestTraceIdentifier; } } /// <summary> /// Gets the URL requested by the client. /// </summary> /// <value> /// <para> /// A <see cref="Uri"/> that represents the URL parsed from the request. /// </para> /// <para> /// <see langword="null"/> if the URL cannot be parsed. /// </para> /// </value> public Uri Url { get { if (!_urlSet) { _url = HttpUtility .CreateRequestUrl ( _rawUrl, _userHostName ?? UserHostAddress, IsWebSocketRequest, IsSecureConnection ); _urlSet = true; } return _url; } } /// <summary> /// Gets the URI of the resource from which the requested URL was obtained. /// </summary> /// <value> /// <para> /// A <see cref="Uri"/> converted from the value of the Referer header. /// </para> /// <para> /// <see langword="null"/> if the header value is not available. /// </para> /// </value> public Uri UrlReferrer { get { var val = _headers["Referer"]; if (val == null) return null; if (_urlReferrer == null) _urlReferrer = val.ToUri (); return _urlReferrer; } } /// <summary> /// Gets the user agent from which the request is originated. /// </summary> /// <value> /// <para> /// A <see cref="string"/> that represents the value of the User-Agent /// header. /// </para> /// <para> /// <see langword="null"/> if the header is not present. /// </para> /// </value> public string UserAgent { get { return _headers["User-Agent"]; } } /// <summary> /// Gets the IP address and port number to which the request is sent. /// </summary> /// <value> /// A <see cref="string"/> that represents the server IP address and port /// number. /// </value> public string UserHostAddress { get { return _connection.LocalEndPoint.ToString (); } } /// <summary> /// Gets the server host name requested by the client. /// </summary> /// <value> /// <para> /// A <see cref="string"/> that represents the value of the Host header. /// </para> /// <para> /// It includes the port number if provided. /// </para> /// <para> /// <see langword="null"/> if the header is not present. /// </para> /// </value> public string UserHostName { get { return _userHostName; } } /// <summary> /// Gets the natural languages that are acceptable for the client. /// </summary> /// <value> /// <para> /// An array of <see cref="string"/> that contains the names of the /// natural languages specified in the value of the Accept-Language /// header. /// </para> /// <para> /// <see langword="null"/> if the header is not present. /// </para> /// </value> public string[] UserLanguages { get { var val = _headers["Accept-Language"]; if (val == null) return null; if (_userLanguages == null) _userLanguages = val.Split (',').TrimEach ().ToList ().ToArray (); return _userLanguages; } } #endregion #region Private Methods private Encoding getContentEncoding () { var val = _headers["Content-Type"]; if (val == null) return Encoding.UTF8; Encoding ret; return HttpUtility.TryGetEncoding (val, out ret) ? ret : Encoding.UTF8; } #endregion #region Internal Methods internal void AddHeader (string headerField) { var start = headerField[0]; if (start == ' ' || start == '\t') { _context.ErrorMessage = "Invalid header field"; return; } var colon = headerField.IndexOf (':'); if (colon < 1) { _context.ErrorMessage = "Invalid header field"; return; } var name = headerField.Substring (0, colon).Trim (); if (name.Length == 0 || !name.IsToken ()) { _context.ErrorMessage = "Invalid header name"; return; } var val = colon < headerField.Length - 1 ? headerField.Substring (colon + 1).Trim () : String.Empty; _headers.InternalSet (name, val, false); var lower = name.ToLower (CultureInfo.InvariantCulture); if (lower == "host") { if (_userHostName != null) { _context.ErrorMessage = "Invalid Host header"; return; } if (val.Length == 0) { _context.ErrorMessage = "Invalid Host header"; return; } _userHostName = val; return; } if (lower == "content-length") { if (_contentLength > -1) { _context.ErrorMessage = "Invalid Content-Length header"; return; } long len; if (!Int64.TryParse (val, out len)) { _context.ErrorMessage = "Invalid Content-Length header"; return; } if (len < 0) { _context.ErrorMessage = "Invalid Content-Length header"; return; } _contentLength = len; return; } } internal void FinishInitialization () { if (_userHostName == null) { _context.ErrorMessage = "Host header required"; return; } var transferEnc = _headers["Transfer-Encoding"]; if (transferEnc != null) { var comparison = StringComparison.OrdinalIgnoreCase; if (!transferEnc.Equals ("chunked", comparison)) { _context.ErrorMessage = "Invalid Transfer-Encoding header"; _context.ErrorStatusCode = 501; return; } _chunked = true; } if (_httpMethod == "POST" || _httpMethod == "PUT") { if (_contentLength <= 0 && !_chunked) { _context.ErrorMessage = String.Empty; _context.ErrorStatusCode = 411; return; } } var expect = _headers["Expect"]; if (expect != null) { var comparison = StringComparison.OrdinalIgnoreCase; if (!expect.Equals ("100-continue", comparison)) { _context.ErrorMessage = "Invalid Expect header"; return; } var output = _connection.GetResponseStream (); output.InternalWrite (_100continue, 0, _100continue.Length); } } internal bool FlushInput () { var input = InputStream; if (input == Stream.Null) return true; var len = 2048; if (_contentLength > 0 && _contentLength < len) len = (int) _contentLength; var buff = new byte[len]; while (true) { try { var ares = input.BeginRead (buff, 0, len, null, null); if (!ares.IsCompleted) { var timeout = 100; if (!ares.AsyncWaitHandle.WaitOne (timeout)) return false; } if (input.EndRead (ares) <= 0) return true; } catch { return false; } } } internal bool IsUpgradeRequest (string protocol) { return _headers.Upgrades (protocol); } internal void SetRequestLine (string requestLine) { var parts = requestLine.Split (new[] { ' ' }, 3); if (parts.Length < 3) { _context.ErrorMessage = "Invalid request line (parts)"; return; } var method = parts[0]; if (method.Length == 0) { _context.ErrorMessage = "Invalid request line (method)"; return; } var target = parts[1]; if (target.Length == 0) { _context.ErrorMessage = "Invalid request line (target)"; return; } var rawVer = parts[2]; if (rawVer.Length != 8) { _context.ErrorMessage = "Invalid request line (version)"; return; } if (!rawVer.StartsWith ("HTTP/", StringComparison.Ordinal)) { _context.ErrorMessage = "Invalid request line (version)"; return; } Version ver; if (!rawVer.Substring (5).TryCreateVersion (out ver)) { _context.ErrorMessage = "Invalid request line (version)"; return; } if (ver != HttpVersion.Version11) { _context.ErrorMessage = "Invalid request line (version)"; _context.ErrorStatusCode = 505; return; } if (!method.IsHttpMethod (ver)) { _context.ErrorMessage = "Invalid request line (method)"; _context.ErrorStatusCode = 501; return; } _httpMethod = method; _rawUrl = target; _protocolVersion = ver; } #endregion #region Public Methods /// <summary> /// Begins getting the certificate provided by the client asynchronously. /// </summary> /// <returns> /// An <see cref="IAsyncResult"/> instance that indicates the status of the /// operation. /// </returns> /// <param name="requestCallback"> /// An <see cref="AsyncCallback"/> delegate that invokes the method called /// when the operation is complete. /// </param> /// <param name="state"> /// An <see cref="object"/> that represents a user defined object to pass to /// the callback delegate. /// </param> /// <exception cref="NotSupportedException"> /// This method is not supported. /// </exception> public IAsyncResult BeginGetClientCertificate ( AsyncCallback requestCallback, object state ) { throw new NotSupportedException (); } /// <summary> /// Ends an asynchronous operation to get the certificate provided by the /// client. /// </summary> /// <returns> /// A <see cref="X509Certificate2"/> that represents an X.509 certificate /// provided by the client. /// </returns> /// <param name="asyncResult"> /// An <see cref="IAsyncResult"/> instance returned when the operation /// started. /// </param> /// <exception cref="NotSupportedException"> /// This method is not supported. /// </exception> public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult) { throw new NotSupportedException (); } /// <summary> /// Gets the certificate provided by the client. /// </summary> /// <returns> /// A <see cref="X509Certificate2"/> that represents an X.509 certificate /// provided by the client. /// </returns> /// <exception cref="NotSupportedException"> /// This method is not supported. /// </exception> public X509Certificate2 GetClientCertificate () { throw new NotSupportedException (); } /// <summary> /// Returns a string that represents the current instance. /// </summary> /// <returns> /// A <see cref="string"/> that contains the request line and headers /// included in the request. /// </returns> public override string ToString () { var buff = new StringBuilder (64); buff .AppendFormat ( "{0} {1} HTTP/{2}\r\n", _httpMethod, _rawUrl, _protocolVersion ) .Append (_headers.ToString ()); return buff.ToString (); } #endregion } }
using System; using System.ComponentModel; using System.Globalization; namespace Eto.Drawing { /// <summary> /// A struct representing X and Y co-ordinates as integer values /// </summary> /// <remarks> /// The point struct is used for drawing and positioning of elements and widgets /// </remarks> /// <copyright>(c) 2014 by Curtis Wensley</copyright> /// <license type="BSD-3">See LICENSE for full terms</license> [TypeConverter(typeof(PointConverter))] public struct Point : IEquatable<Point> { int x; int y; /// <summary> /// Gets an empty point with an X and Y value of zero /// </summary> public static readonly Point Empty = new Point (0, 0); /// <summary> /// Truncates the X and Y components of the specified <paramref name="point"/> to a <see cref="Point"/> /// </summary> /// <param name="point">Floating point value to truncate</param> /// <returns>A new instance of a Point with truncated X and Y values of the specified <paramref name="point"/></returns> public static Point Truncate (PointF point) { return new Point ((int)point.X, (int)point.Y); } /// <summary> /// Rounds the X and Y components of the specified <paramref name="point"/> to a <see cref="Point"/> /// </summary> /// <param name="point">Floating point value to round</param> /// <returns>A new instance of a Point with rounded X and Y values of the specified <paramref name="point"/></returns> public static Point Round (PointF point) { return new Point ((int)Math.Round (point.X), (int)Math.Round (point.Y)); } /// <summary> /// Returns the minimum X and Y components of two points /// </summary> /// <param name="point1">First point</param> /// <param name="point2">Second point</param> /// <returns>A new point with the minimum X and Y values of the two points</returns> public static Point Min (Point point1, Point point2) { return new Point (Math.Min (point1.X, point2.X), Math.Min (point1.Y, point2.Y)); } /// <summary> /// Returns the maximum X and Y components of two points /// </summary> /// <param name="point1">First point</param> /// <param name="point2">Second point</param> /// <returns>A new point with the maximum X and Y values of the two points</returns> public static Point Max (Point point1, Point point2) { return new Point (Math.Max (point1.X, point2.X), Math.Max (point1.Y, point2.Y)); } /// <summary> /// Returns the absolute X and Y components of the specified <paramref name="point"/> /// </summary> /// <param name="point">Point with positive or negative X and/or Y values</param> /// <returns>A new point with absolute (positive) X and Y values of the specified <paramref name="point"/></returns> public static Point Abs (Point point) { return new Point (Math.Abs (point.X), Math.Abs (point.Y)); } /// <summary> /// Initializes a new instance of a Point class with specified <paramref name="x"/> and <paramref name="y"/> values /// </summary> /// <param name="x">Initial X value for the point</param> /// <param name="y">Initial Y value for the point</param> public Point (int x, int y) { this.x = x; this.y = y; } /// <summary> /// Initializes a new instance of a Point class with <see cref="X"/> and <see cref="Y"/> values corresponding to the <see cref="Size.Width"/> and <see cref="Size.Height"/> values /// of the specified <paramref name="size"/>, respecitively /// </summary> /// <param name="size">Size to initialize the X and Y values of the new instance with</param> public Point (Size size) { this.x = size.Width; this.y = size.Height; } /// <summary> /// Initializes a new instance of a Point class with truncated values of the specified floating-point <paramref name="point"/> /// </summary> /// <param name="point">PointF to initialize the X and Y values of the new instance with</param> public Point (PointF point) { this.x = (int)point.X; this.y = (int)point.Y; } /// <summary> /// Gets or sets the X co-ordinate of this point /// </summary> public int X { get { return x; } set { x = value; } } /// <summary> /// Gets or sets the Y co-ordinate of this point /// </summary> public int Y { get { return y; } set { y = value; } } /// <summary> /// Gets the point as a normal vector (perpendicular) to the current point from the origin /// </summary> /// <value>The normal vector of this point</value> public Point Normal { get { return new Point (-Y, X); } } /// <summary> /// Creates a unit vector PointF (a point with a <see cref="Length"/> of 1.0 from origin 0,0) with the specified angle, in degrees /// </summary> /// <returns>A new instance of a PointF with the x,y co-ordinates set at a distance of 1.0 from the origin</returns> /// <param name="angle">Angle in degrees of the unit vector</param> public static PointF UnitVectorAtAngle (float angle) { angle = angle * Helper.DegreesToRadians; return new PointF ((float)Math.Cos(angle), (float)Math.Sin(angle)); } /// <summary> /// Gets the current point as a unit vector (a point with a <see cref="Length"/> of 1.0 from origin 0,0) /// </summary> /// <value>The unit vector equivalent of this point's X and Y coordinates</value> public PointF UnitVector { get { double length = Length; const float epsilon = 1e-6f; var x = X; var y = Y; // deal with very small points without blowing up. int iterations = 0; while (length < epsilon && iterations < 3) { if (Math.Abs (x) > epsilon) { y = y * x; x = 1; } else if (Math.Abs (y) > epsilon) { x = x * y; y = 1; } length = Math.Sqrt (x * x + y * y); iterations++; } if (iterations == 3) return new PointF (1, 0); // arbitrary return new PointF ((float)(X / length), (float)(Y / length)); } } /// <summary> /// Gets the length of the point as a vector from origin 0,0 /// </summary> /// <value>The length of this point as a vector</value> public float Length { get { return (float)Math.Sqrt (X * X + Y * Y); } } /// <summary> /// Gets the squared length of the point as a vector from origin 0,0. /// </summary> /// <value>The length of the squared.</value> public int LengthSquared { get { return X * X + Y * Y; } } /// <summary> /// Gets a value indicating that both the X and Y co-ordinates of this point are zero /// </summary> public bool IsZero { get { return x == 0 && y == 0; } } /// <summary> /// Gets the distance between this point and the specified <paramref name="point"/> /// </summary> /// <param name="point">Point to calculate the distance from</param> public float Distance (Point point) { var dx = Math.Abs (X - point.X); var dy = Math.Abs (Y - point.Y); return (float)Math.Sqrt (dx * dx + dy * dy); } /// <summary> /// Gets the distance between two points using pythagoras theorem /// </summary> /// <param name="point1">First point to calculate the distance from</param> /// <param name="point2">Second point to calculate the distance to</param> /// <returns>The distance between the two points</returns> public static float Distance (Point point1, Point point2) { return point1.Distance (point2); } /// <summary> /// Restricts the X and Y co-ordinates within the specified <paramref name="rectangle"/> /// </summary> /// <remarks> /// This will update the X and Y co-ordinates to be within the specified <paramref name="rectangle"/>'s bounds. /// The updated co-ordinates will be the closest to the original value as possible. /// E.g. if the X co-ordinate is greater than the <see cref="Rectangle.Right"/> of the rectangle, it will be set /// to be <see cref="Rectangle.Right"/> minus one, to be within the rectangle's bounds. /// </remarks> /// <param name="rectangle">Rectangle to restrict the X and Y co-ordinates in</param> public void Restrict (Rectangle rectangle) { if (x < rectangle.Left) x = rectangle.Left; if (x > rectangle.InnerRight) x = rectangle.InnerRight; if (y < rectangle.Top) y = rectangle.Top; if (y > rectangle.InnerBottom) y = rectangle.InnerBottom; } /// <summary> /// Restricts the X and Y co-ordinates of the specified <paramref name="point"/> within the <paramref name="rectangle"/> /// </summary> /// <param name="point">Point to restrict</param> /// <param name="rectangle">Rectangle to restrict the point within</param> /// <returns>A new point that falls within the <paramref name="rectangle"/></returns> public static Point Restrict (Point point, Rectangle rectangle) { point.Restrict (rectangle); return point; } /// <summary> /// Offsets the X and Y co-ordinates of this point by the specified <paramref name="x"/> and <paramref name="y"/> values /// </summary> /// <param name="x">Value to add to the X co-ordinate of this point</param> /// <param name="y">Value to add to the Y co-ordinate of this point</param> public void Offset (int x, int y) { this.x += x; this.y += y; } /// <summary> /// Offsets the X and Y co-ordinates of this point by the values from the specified <paramref name="point"/> /// </summary> /// <param name="point">Point with X and Y values to add to this point</param> public void Offset (Point point) { Offset(point.X, point.Y); } /// <summary> /// Offsets the X and Y co-ordinates of the <paramref name="point"/> by the specified <paramref name="x"/> and <paramref name="y"/> values /// </summary> /// <param name="point">Point to offset</param> /// <param name="x">Value to add to the X co-ordinate of this point</param> /// <param name="y">Value to add to the Y co-ordinate of this point</param> /// <returns>A new point with the offset X and Y values</returns> public static Point Offset (Point point, int x, int y) { point.Offset (x, y); return point; } /// <summary> /// Offsets the X and Y co-ordinates of the <paramref name="point"/> by the values from the specified <paramref name="offset"/> /// </summary> /// <param name="point">Point to offset</param> /// <param name="offset">Point with X and Y values to add to this point</param> /// <returns>A new point offset by the specified value</returns> public static Point Offset (Point point, Point offset) { point.Offset (offset); return point; } /// <summary> /// Gets the dot product of this instance and the specified <paramref name="point"/> /// </summary> /// <param name="point">Point to get the dot product for</param> /// <returns>The dot product (X * point.X + Y * point.Y) between this point and the specified point</returns> public int DotProduct (Point point) { return x * point.x + y * point.y; } /// <summary> /// Gets the dot product between two points /// </summary> /// <param name="point1">First point to get the dot product</param> /// <param name="point2">Second point to get the dot product</param> /// <returns>The dot product (point1.X * point2.X + poin1.Y * point2.Y) between the two points</returns> public static int DotProduct (Point point1, Point point2) { return point1.DotProduct (point2); } /// <summary> /// Returns a new Point with negative x and y values of the specified <paramref name="point"/> /// </summary> /// <param name="point">Point to negate</param> public static Point operator - (Point point) { return new Point (-point.x, -point.y); } /// <summary> /// Operator to return the difference between two points as a <see cref="Size"/> /// </summary> /// <param name="point1">Base point value</param> /// <param name="point2">Point to subtract</param> /// <returns>A new instance of a Size with the X and Y equal to the difference of the X and Y co-ordinates, respectively</returns> public static Point operator - (Point point1, Point point2) { return new Point (point1.x - point2.x, point1.y - point2.y); } /// <summary> /// Operator to return the addition of two points as a <see cref="Point"/> /// </summary> /// <param name="point1">Base point value</param> /// <param name="point2">Point to add</param> /// <returns>A new instance of a Point with the X and Y equal to the sum of the two point's X and Y co-ordinates, respectively</returns> public static Point operator + (Point point1, Point point2) { return new Point (point1.x + point2.x, point1.y + point2.y); } /// <summary> /// Operator to add a size to a point /// </summary> /// <param name="point">Base point value</param> /// <param name="size">Size to add to the point's X and Y co-ordinates</param> /// <returns>A new point with the sum of the specified <paramref name="point"/>'s X and Y components and the <paramref name="size"/></returns> public static Point operator + (Point point, Size size) { return new Point (point.x + size.Width, point.y + size.Height); } /// <summary> /// Operator to subtract a size from a point /// </summary> /// <param name="point">Base point value</param> /// <param name="size">Size to subtract to the point's X and Y co-ordinates</param> /// <returns>A new point with the sum of the specified <paramref name="point"/>'s X and Y components and the <paramref name="size"/></returns> public static Point operator - (Point point, Size size) { return new Point (point.x - size.Width, point.y - size.Height); } /// <summary> /// Operator to add a <paramref name="value"/> to both the X and Y co-ordinates of a point /// </summary> /// <param name="point">Base point value</param> /// <param name="value">Value to add to both the X and Y co-ordinates of the point</param> /// <returns>A new instance of a point with the sum of the <paramref name="point"/>'s X and Y co-ordinates and the specified <paramref name="value"/></returns> public static Point operator + (Point point, int value) { return new Point (point.x + value, point.y + value); } /// <summary> /// Operator to subtract a <paramref name="value"/> from both the X and Y co-ordinates of a point /// </summary> /// <param name="point">Base point value</param> /// <param name="value">Value to subtract to both the X and Y co-ordinates of the point</param> /// <returns>A new instance of a point with the value of the <paramref name="point"/>'s X and Y co-ordinates minus the specified <paramref name="value"/></returns> public static Point operator - (Point point, int value) { return new Point (point.x - value, point.y - value); } /// <summary> /// Determines equality between two points /// </summary> /// <remarks> /// Equality is when both the X and Y values of both points are equal /// </remarks> /// <param name="point1">First point to compare</param> /// <param name="point2">Second point to compare</param> /// <returns>True if both points are equal, false if not</returns> public static bool operator == (Point point1, Point point2) { return point1.x == point2.x && point1.y == point2.y; } /// <summary> /// Determines the inequality between two points /// </summary> /// <remarks> /// Inequality is when either the X and Y values of both points are different /// </remarks> /// <param name="point1">First point to compare</param> /// <param name="point2">Second point to compare</param> /// <returns>True if the two points are not equal, false if not</returns> public static bool operator != (Point point1, Point point2) { return point1.x != point2.x || point1.y != point2.y; } /// <summary> /// Multiplies the specified <paramref name="point"/> with a <paramref name="size"/> /// </summary> /// <param name="point">Base point value</param> /// <param name="size">Size to multiply the X and Y co-ordinates with the Width and Height of the <paramref name="size"/>, respectively</param> /// <returns>A new instance of a point with the product of the specified <paramref name="point"/> and <paramref name="size"/></returns> public static Point operator * (Point point, Size size) { return new Point (point.X * size.Width, point.Y * size.Height); } /// <summary>Multiplies the X and Y co-ordinates of the two specified point values</summary> /// <param name="point1">First point to multiply</param> /// <param name="point2">Secont point to multiply</param> public static Point operator * (Point point1, Point point2) { return new Point (point1.X * point2.X, point1.Y * point2.Y); } /// <summary> /// Divides the specified <paramref name="point"/> with a <paramref name="size"/> /// </summary> /// <param name="point">Base point value</param> /// <param name="size">Size to divide the X and Y co-ordinates with the Width and Height of the <paramref name="size"/>, respectively</param> /// <returns>A new instance of a point with the division of the specified <paramref name="point"/> and <paramref name="size"/></returns> public static Point operator / (Point point, Size size) { return new Point (point.X / size.Width, point.Y / size.Height); } /// <summary> /// Multiplies the X and Y co-ordinates of the specified <paramref name="point"/> with a given <paramref name="factor"/> /// </summary> /// <param name="point">Base point value</param> /// <param name="factor">Value to multiply the X and Y co-ordinates with</param> /// <returns>A new instance of a point with the product of the X and Y co-ordinates of the <paramref name="point"/> and specified <paramref name="factor"/></returns> public static Point operator * (Point point, int factor) { return new Point (point.X * factor, point.Y * factor); } /// <summary> /// Multiplies the X and Y co-ordinates of the specified <paramref name="point"/> with a given <paramref name="factor"/> /// </summary> /// <param name="point">Base point value</param> /// <param name="factor">Value to multiply the X and Y co-ordinates with</param> /// <returns>A new instance of a point with the product of the X and Y co-ordinates of the <paramref name="point"/> and specified <paramref name="factor"/></returns> public static Point operator * (int factor, Point point) { return new Point (point.X * factor, point.Y * factor); } /// <summary> /// Multiplies the <see cref="X"/> and <see cref="Y"/> of a <paramref name="point"/> by the specified floating point <paramref name="factor"/> /// </summary> /// <param name="point">Point to multiply</param> /// <param name="factor">Factor to multiply both the X and Y coordinates by</param> /// <returns>A new instance of a PointF struct with the product of the <paramref name="point"/> and <paramref name="factor"/></returns> public static PointF operator * (Point point, float factor) { return new PointF (point.X * factor, point.Y * factor); } /// <summary> /// Divides the X and Y co-ordinates of the specified <paramref name="point"/> with a given <paramref name="value"/> /// </summary> /// <param name="point">Base point value</param> /// <param name="value">Value to divide the X and Y co-ordinates with</param> /// <returns>A new instance of a point with the division of the X and Y co-ordinates of the <paramref name="point"/> and specified <paramref name="value"/></returns> public static Point operator / (Point point, int value) { return new Point (point.X / value, point.Y / value); } /// <summary> /// Explicit conversion from a <see cref="PointF"/> to a <see cref="Point"/> by truncating values /// </summary> /// <param name="point">Point to convert</param> /// <returns>A new instance of a Point with the value of the specified <paramref name="point"/></returns> public static explicit operator Point (PointF point) { return new Point ((int)point.X, (int)point.Y); } /// <summary> /// Explicit conversion from a <paramref name="size"/> to a Point with a X and Y of the Width and Height values of the size, respectively /// </summary> /// <param name="size">Size to convert</param> /// <returns>A new size with the width and height of the X and Y values of the point, respectively</returns> public static explicit operator Point (Size size) { return new Point (size); } /// <summary> /// Returns a value indicating that the specified <paramref name="obj"/> is equal to this point /// </summary> /// <param name="obj">Object to compare</param> /// <returns>True if the specified <paramref name="obj"/> is a Point and is equal to this instance, false otherwise</returns> public override bool Equals (object obj) { return obj is Point && (Point)obj == this; } /// <summary> /// Gets the hash code of this point /// </summary> /// <returns>Hash code for this point</returns> public override int GetHashCode () { return X ^ Y; } /// <summary> /// Converts this point to a string /// </summary> /// <returns>String representation of this point</returns> public override string ToString () { return String.Format (CultureInfo.InvariantCulture, "{0},{1}", x, y); } /// <summary> /// Returns a value indicating that the specified <paramref name="other"/> point is equal to this point /// </summary> /// <param name="other">Other point to compare</param> /// <returns>True if the other point is equal to this point, otherwise false</returns> public bool Equals (Point other) { return other == this; } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Globalization; using System.Xml; using System.Text; namespace System.Management.Automation { /// <summary> /// /// Class MamlCommandHelpInfo keeps track of help information to be returned by /// command help provider. /// /// </summary> internal class MamlCommandHelpInfo : BaseCommandHelpInfo { /// <summary> /// Constructor for custom HelpInfo object construction /// /// This is used by the CommandHelpProvider class to generate the /// default help UX when no help content is present. /// </summary> /// <param name="helpObject"></param> /// <param name="helpCategory"></param> internal MamlCommandHelpInfo(PSObject helpObject, HelpCategory helpCategory) : base(helpCategory) { _fullHelpObject = helpObject; this.ForwardHelpCategory = HelpCategory.Provider; this.AddCommonHelpProperties(); // set user defined data if (helpObject.Properties["Component"] != null) { _component = helpObject.Properties["Component"].Value as string; } if (helpObject.Properties["Role"] != null) { _role = helpObject.Properties["Role"].Value as string; } if (helpObject.Properties["Functionality"] != null) { _functionality = helpObject.Properties["Functionality"].Value as string; } } /// <summary> /// Constructor for MamlCommandHelpInfo. This constructor will call the corresponding /// constructor in CommandHelpInfo so that xmlNode will be converted a mamlNode. /// </summary> /// <remarks> /// This constructor is intentionally made private so that the only way to create /// MamlCommandHelpInfo is through static function /// Load(XmlNode node) /// where some sanity check is done. /// </remarks> private MamlCommandHelpInfo(XmlNode xmlNode, HelpCategory helpCategory) : base(helpCategory) { MamlNode mamlNode = new MamlNode(xmlNode); _fullHelpObject = mamlNode.PSObject; this.Errors = mamlNode.Errors; // The type name hierarchy for mshObject doesn't necessary // reflect the hierarchy in source code. From display's point of // view MamlCommandHelpInfo is derived from HelpInfo. _fullHelpObject.TypeNames.Clear(); if (helpCategory == HelpCategory.DscResource) { _fullHelpObject.TypeNames.Add("DscResourceHelpInfo"); } else { _fullHelpObject.TypeNames.Add("MamlCommandHelpInfo"); _fullHelpObject.TypeNames.Add("HelpInfo"); } this.ForwardHelpCategory = HelpCategory.Provider; } /// <summary> /// Override the FullHelp PSObject of this provider-specific HelpInfo with generic help. /// </summary> internal void OverrideProviderSpecificHelpWithGenericHelp(HelpInfo genericHelpInfo) { PSObject genericHelpMaml = genericHelpInfo.FullHelp; MamlUtil.OverrideName(_fullHelpObject, genericHelpMaml); MamlUtil.OverridePSTypeNames(_fullHelpObject, genericHelpMaml); MamlUtil.PrependSyntax(_fullHelpObject, genericHelpMaml); MamlUtil.PrependDetailedDescription(_fullHelpObject, genericHelpMaml); MamlUtil.OverrideParameters(_fullHelpObject, genericHelpMaml); MamlUtil.PrependNotes(_fullHelpObject, genericHelpMaml); MamlUtil.AddCommonProperties(_fullHelpObject, genericHelpMaml); } #region Basic Help Properties private PSObject _fullHelpObject; /// <summary> /// Full help object for this help item. /// </summary> /// <value>Full help object for this help item.</value> internal override PSObject FullHelp { get { return _fullHelpObject; } } /// <summary> /// Examples string of this cmdlet help info. /// </summary> private string Examples { get { return ExtractTextForHelpProperty(this.FullHelp, "Examples"); } } /// <summary> /// Parameters string of this cmdlet help info. /// </summary> private string Parameters { get { return ExtractTextForHelpProperty(this.FullHelp, "Parameters"); } } /// <summary> /// Notes string of this cmdlet help info. /// </summary> private string Notes { get { return ExtractTextForHelpProperty(this.FullHelp, "alertset"); } } #endregion #region Component, Role, Features // Component, Role, Functionality are required by exchange for filtering // help contents to be returned from help system. // // Following is how this is going to work, // 1. Each command will optionally include component, role and functionality // information. This information is discovered from help content // from xml tags <component>, <role>, <functionality> respectively // as part of command metadata. // 2. From command line, end user can request help for commands for // particular component, role and functionality using parameters like // -component, -role, -functionality. // 3. At runtime, help engine will match against component/role/functionality // criteria before returning help results. // private string _component = null; /// <summary> /// Component for this command. /// </summary> /// <value></value> internal override string Component { get { return _component; } } private string _role = null; /// <summary> /// Role for this command /// </summary> /// <value></value> internal override string Role { get { return _role; } } private string _functionality = null; /// <summary> /// Functionality for this command /// </summary> /// <value></value> internal override string Functionality { get { return _functionality; } } internal void SetAdditionalDataFromHelpComment(string component, string functionality, string role) { _component = component; _functionality = functionality; _role = role; // component,role,functionality is part of common help.. // Update these properties as we have new data now.. this.UpdateUserDefinedDataProperties(); } /// <summary> /// Add user-defined command help data to command help. /// </summary> /// <param name="userDefinedData">User defined data object</param> internal void AddUserDefinedData(UserDefinedHelpData userDefinedData) { if (userDefinedData == null) return; string propertyValue; if (userDefinedData.Properties.TryGetValue("component", out propertyValue)) { _component = propertyValue; } if (userDefinedData.Properties.TryGetValue("role", out propertyValue)) { _role = propertyValue; } if (userDefinedData.Properties.TryGetValue("functionality", out propertyValue)) { _functionality = propertyValue; } // component,role,functionality is part of common help.. // Update these properties as we have new data now.. this.UpdateUserDefinedDataProperties(); } #endregion #region Load /// <summary> /// Create a MamlCommandHelpInfo object from an XmlNode. /// </summary> /// <param name="xmlNode">xmlNode that contains help info</param> /// <param name="helpCategory">help category this maml object fits into</param> /// <returns>MamlCommandHelpInfo object created</returns> internal static MamlCommandHelpInfo Load(XmlNode xmlNode, HelpCategory helpCategory) { MamlCommandHelpInfo mamlCommandHelpInfo = new MamlCommandHelpInfo(xmlNode, helpCategory); if (String.IsNullOrEmpty(mamlCommandHelpInfo.Name)) return null; mamlCommandHelpInfo.AddCommonHelpProperties(); return mamlCommandHelpInfo; } #endregion #region Provider specific help #if V2 /// <summary> /// Merge the provider specific help with current command help. /// /// The cmdletHelp and dynamicParameterHelp is normally retrieved from ProviderHelpProvider. /// </summary> /// <remarks> /// A new MamlCommandHelpInfo is created to avoid polluting the provider help cache. /// </remarks> /// <param name="cmdletHelp">provider-specific cmdletHelp to merge into current MamlCommandHelpInfo object</param> /// <param name="dynamicParameterHelp">provider-specific dynamic parameter help to merge into current MamlCommandHelpInfo object</param> /// <returns>merged command help info object</returns> internal MamlCommandHelpInfo MergeProviderSpecificHelp(PSObject cmdletHelp, PSObject[] dynamicParameterHelp) { if (this._fullHelpObject == null) return null; MamlCommandHelpInfo result = (MamlCommandHelpInfo)this.MemberwiseClone(); // We will need to use a deep clone of _fullHelpObject // to avoid _fullHelpObject being get terminated. result._fullHelpObject = this._fullHelpObject.Copy(); if (cmdletHelp != null) result._fullHelpObject.Properties.Add(new PSNoteProperty("PS_Cmdlet", cmdletHelp)); if (dynamicParameterHelp != null) result._fullHelpObject.Properties.Add(new PSNoteProperty("PS_DynamicParameters", dynamicParameterHelp)); return result; } #endif #endregion #region Helper Methods and Overloads /// <summary> /// Extracts text for a given property from the full help object /// </summary> /// <param name="psObject">FullHelp object</param> /// <param name="propertyName"> /// Name of the property for which text needs to be extracted. /// </param> /// <returns></returns> private string ExtractTextForHelpProperty(PSObject psObject, string propertyName) { if (psObject == null) return string.Empty; if (psObject.Properties[propertyName] == null || psObject.Properties[propertyName].Value == null) { return string.Empty; } return ExtractText(PSObject.AsPSObject(psObject.Properties[propertyName].Value)); } /// <summary> /// Given a PSObject, this method will traverse through the objects properties, /// extracts content from properties that are of type System.String, appends them /// together and returns. /// </summary> /// <param name="psObject"></param> /// <returns></returns> private string ExtractText(PSObject psObject) { if (null == psObject) { return string.Empty; } // I think every cmdlet description should atleast have 400 characters... // so starting with this assumption..I did an average of all the cmdlet // help content available at the time of writing this code and came up // with this number. StringBuilder result = new StringBuilder(400); foreach (PSPropertyInfo propertyInfo in psObject.Properties) { string typeNameOfValue = propertyInfo.TypeNameOfValue; switch (typeNameOfValue.ToLowerInvariant()) { case "system.boolean": case "system.int32": case "system.object": case "system.object[]": continue; case "system.string": result.Append((string)LanguagePrimitives.ConvertTo(propertyInfo.Value, typeof(string), CultureInfo.InvariantCulture)); break; case "system.management.automation.psobject[]": PSObject[] items = (PSObject[])LanguagePrimitives.ConvertTo( propertyInfo.Value, typeof(PSObject[]), CultureInfo.InvariantCulture); foreach (PSObject item in items) { result.Append(ExtractText(item)); } break; case "system.management.automation.psobject": result.Append(ExtractText(PSObject.AsPSObject(propertyInfo.Value))); break; default: result.Append(ExtractText(PSObject.AsPSObject(propertyInfo.Value))); break; } } return result.ToString(); } /// <summary> /// Returns true if help content in help info matches the /// pattern contained in <paramref name="pattern"/>. /// The underlying code will usually run pattern.IsMatch() on /// content it wants to search. /// Cmdlet help info looks for pattern in Synopsis and /// DetailedDescription /// </summary> /// <param name="pattern"></param> /// <returns></returns> internal override bool MatchPatternInContent(WildcardPattern pattern) { System.Management.Automation.Diagnostics.Assert(null != pattern, "pattern cannot be null"); string synopsis = Synopsis; if ((!string.IsNullOrEmpty(synopsis)) && (pattern.IsMatch(synopsis))) { return true; } string detailedDescription = DetailedDescription; if ((!string.IsNullOrEmpty(detailedDescription)) && (pattern.IsMatch(detailedDescription))) { return true; } string examples = Examples; if ((!string.IsNullOrEmpty(examples)) && (pattern.IsMatch(examples))) { return true; } string notes = Notes; if ((!string.IsNullOrEmpty(notes)) && (pattern.IsMatch(notes))) { return true; } string parameters = Parameters; if ((!string.IsNullOrEmpty(parameters)) && (pattern.IsMatch(parameters))) { return true; } return false; } internal MamlCommandHelpInfo Copy() { MamlCommandHelpInfo result = new MamlCommandHelpInfo(_fullHelpObject.Copy(), this.HelpCategory); return result; } internal MamlCommandHelpInfo Copy(HelpCategory newCategoryToUse) { MamlCommandHelpInfo result = new MamlCommandHelpInfo(_fullHelpObject.Copy(), newCategoryToUse); result.FullHelp.Properties["Category"].Value = newCategoryToUse; return result; } #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. /*============================================================ ** ** ** ** ** Purpose: Provides a way to write primitives types in ** binary from a Stream, while also supporting writing Strings ** in a particular encoding. ** ** ===========================================================*/ using System; using System.Runtime; using System.Runtime.Serialization; using System.Text; using System.Diagnostics.Contracts; namespace System.IO { // This abstract base class represents a writer that can write // primitives to an arbitrary stream. A subclass can override methods to // give unique encodings. // [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public class BinaryWriter : IDisposable { public static readonly BinaryWriter Null = new BinaryWriter(); protected Stream OutStream; private byte[] _buffer; // temp space for writing primitives to. private Encoding _encoding; private Encoder _encoder; [OptionalField] // New in .NET FX 4.5. False is the right default value. private bool _leaveOpen; // This field should never have been serialized and has not been used since before v2.0. // However, this type is serializable, and we need to keep the field name around when deserializing. // Also, we'll make .NET FX 4.5 not break if it's missing. #pragma warning disable 169 [OptionalField] private char[] _tmpOneCharBuffer; #pragma warning restore 169 // Perf optimization stuff private byte[] _largeByteBuffer; // temp space for writing chars. private int _maxChars; // max # of chars we can put in _largeByteBuffer // Size should be around the max number of chars/string * Encoding's max bytes/char private const int LargeByteBufferSize = 256; // Protected default constructor that sets the output stream // to a null stream (a bit bucket). protected BinaryWriter() { OutStream = Stream.Null; _buffer = new byte[16]; _encoding = new UTF8Encoding(false, true); _encoder = _encoding.GetEncoder(); } public BinaryWriter(Stream output) : this(output, new UTF8Encoding(false, true), false) { } public BinaryWriter(Stream output, Encoding encoding) : this(output, encoding, false) { } public BinaryWriter(Stream output, Encoding encoding, bool leaveOpen) { if (output==null) throw new ArgumentNullException("output"); if (encoding==null) throw new ArgumentNullException("encoding"); if (!output.CanWrite) throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotWritable")); Contract.EndContractBlock(); OutStream = output; _buffer = new byte[16]; _encoding = encoding; _encoder = _encoding.GetEncoder(); _leaveOpen = leaveOpen; } // Closes this writer and releases any system resources associated with the // writer. Following a call to Close, any operations on the writer // may raise exceptions. public virtual void Close() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { if (_leaveOpen) OutStream.Flush(); else OutStream.Close(); } } public void Dispose() { Dispose(true); } /* * Returns the stream associate with the writer. It flushes all pending * writes before returning. All subclasses should override Flush to * ensure that all buffered data is sent to the stream. */ public virtual Stream BaseStream { get { Flush(); return OutStream; } } // Clears all buffers for this writer and causes any buffered data to be // written to the underlying device. public virtual void Flush() { OutStream.Flush(); } public virtual long Seek(int offset, SeekOrigin origin) { return OutStream.Seek(offset, origin); } // Writes a boolean to this stream. A single byte is written to the stream // with the value 0 representing false or the value 1 representing true. // public virtual void Write(bool value) { _buffer[0] = (byte) (value ? 1 : 0); OutStream.Write(_buffer, 0, 1); } // Writes a byte to this stream. The current position of the stream is // advanced by one. // public virtual void Write(byte value) { OutStream.WriteByte(value); } // Writes a signed byte to this stream. The current position of the stream // is advanced by one. // [CLSCompliant(false)] public virtual void Write(sbyte value) { OutStream.WriteByte((byte) value); } // Writes a byte array to this stream. // // This default implementation calls the Write(Object, int, int) // method to write the byte array. // public virtual void Write(byte[] buffer) { if (buffer == null) throw new ArgumentNullException("buffer"); Contract.EndContractBlock(); OutStream.Write(buffer, 0, buffer.Length); } // Writes a section of a byte array to this stream. // // This default implementation calls the Write(Object, int, int) // method to write the byte array. // public virtual void Write(byte[] buffer, int index, int count) { OutStream.Write(buffer, index, count); } // Writes a character to this stream. The current position of the stream is // advanced by two. // Note this method cannot handle surrogates properly in UTF-8. // [System.Security.SecuritySafeCritical] // auto-generated public unsafe virtual void Write(char ch) { if (Char.IsSurrogate(ch)) throw new ArgumentException(Environment.GetResourceString("Arg_SurrogatesNotAllowedAsSingleChar")); Contract.EndContractBlock(); Contract.Assert(_encoding.GetMaxByteCount(1) <= 16, "_encoding.GetMaxByteCount(1) <= 16)"); int numBytes = 0; fixed(byte * pBytes = _buffer) { numBytes = _encoder.GetBytes(&ch, 1, pBytes, 16, true); } OutStream.Write(_buffer, 0, numBytes); } // Writes a character array to this stream. // // This default implementation calls the Write(Object, int, int) // method to write the character array. // public virtual void Write(char[] chars) { if (chars == null) throw new ArgumentNullException("chars"); Contract.EndContractBlock(); byte[] bytes = _encoding.GetBytes(chars, 0, chars.Length); OutStream.Write(bytes, 0, bytes.Length); } // Writes a section of a character array to this stream. // // This default implementation calls the Write(Object, int, int) // method to write the character array. // public virtual void Write(char[] chars, int index, int count) { byte[] bytes = _encoding.GetBytes(chars, index, count); OutStream.Write(bytes, 0, bytes.Length); } // Writes a double to this stream. The current position of the stream is // advanced by eight. // [System.Security.SecuritySafeCritical] // auto-generated public unsafe virtual void Write(double value) { ulong TmpValue = *(ulong *)&value; _buffer[0] = (byte) TmpValue; _buffer[1] = (byte) (TmpValue >> 8); _buffer[2] = (byte) (TmpValue >> 16); _buffer[3] = (byte) (TmpValue >> 24); _buffer[4] = (byte) (TmpValue >> 32); _buffer[5] = (byte) (TmpValue >> 40); _buffer[6] = (byte) (TmpValue >> 48); _buffer[7] = (byte) (TmpValue >> 56); OutStream.Write(_buffer, 0, 8); } public virtual void Write(decimal value) { Decimal.GetBytes(value,_buffer); OutStream.Write(_buffer, 0, 16); } // Writes a two-byte signed integer to this stream. The current position of // the stream is advanced by two. // public virtual void Write(short value) { _buffer[0] = (byte) value; _buffer[1] = (byte) (value >> 8); OutStream.Write(_buffer, 0, 2); } // Writes a two-byte unsigned integer to this stream. The current position // of the stream is advanced by two. // [CLSCompliant(false)] public virtual void Write(ushort value) { _buffer[0] = (byte) value; _buffer[1] = (byte) (value >> 8); OutStream.Write(_buffer, 0, 2); } // Writes a four-byte signed integer to this stream. The current position // of the stream is advanced by four. // public virtual void Write(int value) { _buffer[0] = (byte) value; _buffer[1] = (byte) (value >> 8); _buffer[2] = (byte) (value >> 16); _buffer[3] = (byte) (value >> 24); OutStream.Write(_buffer, 0, 4); } // Writes a four-byte unsigned integer to this stream. The current position // of the stream is advanced by four. // [CLSCompliant(false)] public virtual void Write(uint value) { _buffer[0] = (byte) value; _buffer[1] = (byte) (value >> 8); _buffer[2] = (byte) (value >> 16); _buffer[3] = (byte) (value >> 24); OutStream.Write(_buffer, 0, 4); } // Writes an eight-byte signed integer to this stream. The current position // of the stream is advanced by eight. // public virtual void Write(long value) { _buffer[0] = (byte) value; _buffer[1] = (byte) (value >> 8); _buffer[2] = (byte) (value >> 16); _buffer[3] = (byte) (value >> 24); _buffer[4] = (byte) (value >> 32); _buffer[5] = (byte) (value >> 40); _buffer[6] = (byte) (value >> 48); _buffer[7] = (byte) (value >> 56); OutStream.Write(_buffer, 0, 8); } // Writes an eight-byte unsigned integer to this stream. The current // position of the stream is advanced by eight. // [CLSCompliant(false)] public virtual void Write(ulong value) { _buffer[0] = (byte) value; _buffer[1] = (byte) (value >> 8); _buffer[2] = (byte) (value >> 16); _buffer[3] = (byte) (value >> 24); _buffer[4] = (byte) (value >> 32); _buffer[5] = (byte) (value >> 40); _buffer[6] = (byte) (value >> 48); _buffer[7] = (byte) (value >> 56); OutStream.Write(_buffer, 0, 8); } // Writes a float to this stream. The current position of the stream is // advanced by four. // [System.Security.SecuritySafeCritical] // auto-generated public unsafe virtual void Write(float value) { uint TmpValue = *(uint *)&value; _buffer[0] = (byte) TmpValue; _buffer[1] = (byte) (TmpValue >> 8); _buffer[2] = (byte) (TmpValue >> 16); _buffer[3] = (byte) (TmpValue >> 24); OutStream.Write(_buffer, 0, 4); } // Writes a length-prefixed string to this stream in the BinaryWriter's // current Encoding. This method first writes the length of the string as // a four-byte unsigned integer, and then writes that many characters // to the stream. // [System.Security.SecuritySafeCritical] // auto-generated public unsafe virtual void Write(String value) { if (value==null) throw new ArgumentNullException("value"); Contract.EndContractBlock(); int len = _encoding.GetByteCount(value); Write7BitEncodedInt(len); if (_largeByteBuffer == null) { _largeByteBuffer = new byte[LargeByteBufferSize]; _maxChars = LargeByteBufferSize / _encoding.GetMaxByteCount(1); } if (len <= LargeByteBufferSize) { //Contract.Assert(len == _encoding.GetBytes(chars, 0, chars.Length, _largeByteBuffer, 0), "encoding's GetByteCount & GetBytes gave different answers! encoding type: "+_encoding.GetType().Name); _encoding.GetBytes(value, 0, value.Length, _largeByteBuffer, 0); OutStream.Write(_largeByteBuffer, 0, len); } else { // Aggressively try to not allocate memory in this loop for // runtime performance reasons. Use an Encoder to write out // the string correctly (handling surrogates crossing buffer // boundaries properly). int charStart = 0; int numLeft = value.Length; #if _DEBUG int totalBytes = 0; #endif while (numLeft > 0) { // Figure out how many chars to process this round. int charCount = (numLeft > _maxChars) ? _maxChars : numLeft; int byteLen; fixed(char* pChars = value) { fixed(byte* pBytes = _largeByteBuffer) { byteLen = _encoder.GetBytes(pChars + charStart, charCount, pBytes, LargeByteBufferSize, charCount == numLeft); } } #if _DEBUG totalBytes += byteLen; Contract.Assert (totalBytes <= len && byteLen <= LargeByteBufferSize, "BinaryWriter::Write(String) - More bytes encoded than expected!"); #endif OutStream.Write(_largeByteBuffer, 0, byteLen); charStart += charCount; numLeft -= charCount; } #if _DEBUG Contract.Assert(totalBytes == len, "BinaryWriter::Write(String) - Didn't write out all the bytes!"); #endif } } protected void Write7BitEncodedInt(int value) { // Write out an int 7 bits at a time. The high bit of the byte, // when on, tells reader to continue reading more bytes. uint v = (uint) value; // support negative numbers while (v >= 0x80) { Write((byte) (v | 0x80)); v >>= 7; } Write((byte)v); } } }
// // Copyright (c) Microsoft and contributors. 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. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Microsoft.WindowsAzure.Management; using Microsoft.WindowsAzure.Management.Models; namespace Microsoft.WindowsAzure.Management { /// <summary> /// You can use management certificates, which are also known as /// subscription certificates, to authenticate clients attempting to /// connect to resources associated with your Azure subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154124.aspx for /// more information) /// </summary> internal partial class ManagementCertificateOperations : IServiceOperations<ManagementClient>, Microsoft.WindowsAzure.Management.IManagementCertificateOperations { /// <summary> /// Initializes a new instance of the ManagementCertificateOperations /// class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ManagementCertificateOperations(ManagementClient client) { this._client = client; } private ManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.ManagementClient. /// </summary> public ManagementClient Client { get { return this._client; } } /// <summary> /// The Create Management Certificate operation adds a certificate to /// the list of management certificates. Management certificates, /// which are also known as subscription certificates, authenticate /// clients attempting to connect to resources associated with your /// Azure subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154123.aspx /// for more information) /// </summary> /// <param name='parameters'> /// Required. Parameters supplied to the Create Management Certificate /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async System.Threading.Tasks.Task<OperationResponse> CreateAsync(ManagementCertificateCreateParameters parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "CreateAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/certificates"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement subscriptionCertificateElement = new XElement(XName.Get("SubscriptionCertificate", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(subscriptionCertificateElement); if (parameters.PublicKey != null) { XElement subscriptionCertificatePublicKeyElement = new XElement(XName.Get("SubscriptionCertificatePublicKey", "http://schemas.microsoft.com/windowsazure")); subscriptionCertificatePublicKeyElement.Value = Convert.ToBase64String(parameters.PublicKey); subscriptionCertificateElement.Add(subscriptionCertificatePublicKeyElement); } if (parameters.Thumbprint != null) { XElement subscriptionCertificateThumbprintElement = new XElement(XName.Get("SubscriptionCertificateThumbprint", "http://schemas.microsoft.com/windowsazure")); subscriptionCertificateThumbprintElement.Value = parameters.Thumbprint; subscriptionCertificateElement.Add(subscriptionCertificateThumbprintElement); } if (parameters.Data != null) { XElement subscriptionCertificateDataElement = new XElement(XName.Get("SubscriptionCertificateData", "http://schemas.microsoft.com/windowsazure")); subscriptionCertificateDataElement.Value = Convert.ToBase64String(parameters.Data); subscriptionCertificateElement.Add(subscriptionCertificateDataElement); } requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperationResponse result = null; result = new OperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Delete Management Certificate operation deletes a certificate /// from the list of management certificates. Management certificates, /// which are also known as subscription certificates, authenticate /// clients attempting to connect to resources associated with your /// Azure subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154127.aspx /// for more information) /// </summary> /// <param name='thumbprint'> /// Required. The thumbprint value of the certificate to delete. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async System.Threading.Tasks.Task<OperationResponse> DeleteAsync(string thumbprint, CancellationToken cancellationToken) { // Validate if (thumbprint == null) { throw new ArgumentNullException("thumbprint"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("thumbprint", thumbprint); Tracing.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/certificates/" + thumbprint.Trim(); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NotFound) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result OperationResponse result = null; result = new OperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Get Management Certificate operation retrieves information /// about the management certificate with the specified thumbprint. /// Management certificates, which are also known as subscription /// certificates, authenticate clients attempting to connect to /// resources associated with your Azure subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154131.aspx /// for more information) /// </summary> /// <param name='thumbprint'> /// Required. The thumbprint value of the certificate to retrieve /// information about. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get Management Certificate operation response. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Models.ManagementCertificateGetResponse> GetAsync(string thumbprint, CancellationToken cancellationToken) { // Validate if (thumbprint == null) { throw new ArgumentNullException("thumbprint"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("thumbprint", thumbprint); Tracing.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/certificates/" + thumbprint.Trim(); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result ManagementCertificateGetResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ManagementCertificateGetResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement subscriptionCertificateElement = responseDoc.Element(XName.Get("SubscriptionCertificate", "http://schemas.microsoft.com/windowsazure")); if (subscriptionCertificateElement != null) { XElement subscriptionCertificatePublicKeyElement = subscriptionCertificateElement.Element(XName.Get("SubscriptionCertificatePublicKey", "http://schemas.microsoft.com/windowsazure")); if (subscriptionCertificatePublicKeyElement != null) { byte[] subscriptionCertificatePublicKeyInstance = Convert.FromBase64String(subscriptionCertificatePublicKeyElement.Value); result.PublicKey = subscriptionCertificatePublicKeyInstance; } XElement subscriptionCertificateThumbprintElement = subscriptionCertificateElement.Element(XName.Get("SubscriptionCertificateThumbprint", "http://schemas.microsoft.com/windowsazure")); if (subscriptionCertificateThumbprintElement != null) { string subscriptionCertificateThumbprintInstance = subscriptionCertificateThumbprintElement.Value; result.Thumbprint = subscriptionCertificateThumbprintInstance; } XElement subscriptionCertificateDataElement = subscriptionCertificateElement.Element(XName.Get("SubscriptionCertificateData", "http://schemas.microsoft.com/windowsazure")); if (subscriptionCertificateDataElement != null) { byte[] subscriptionCertificateDataInstance = Convert.FromBase64String(subscriptionCertificateDataElement.Value); result.Data = subscriptionCertificateDataInstance; } XElement createdElement = subscriptionCertificateElement.Element(XName.Get("Created", "http://schemas.microsoft.com/windowsazure")); if (createdElement != null) { DateTime createdInstance = DateTime.Parse(createdElement.Value, CultureInfo.InvariantCulture); result.Created = createdInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The List Management Certificates operation lists and returns basic /// information about all of the management certificates associated /// with the specified subscription. Management certificates, which /// are also known as subscription certificates, authenticate clients /// attempting to connect to resources associated with your Azure /// subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154105.aspx /// for more information) /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Management Certificates operation response. /// </returns> public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.Models.ManagementCertificateListResponse> ListAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); Tracing.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = "/" + (this.Client.Credentials.SubscriptionId != null ? this.Client.Credentials.SubscriptionId.Trim() : "") + "/certificates"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2014-10-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result ManagementCertificateListResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ManagementCertificateListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement subscriptionCertificatesSequenceElement = responseDoc.Element(XName.Get("SubscriptionCertificates", "http://schemas.microsoft.com/windowsazure")); if (subscriptionCertificatesSequenceElement != null) { foreach (XElement subscriptionCertificatesElement in subscriptionCertificatesSequenceElement.Elements(XName.Get("SubscriptionCertificate", "http://schemas.microsoft.com/windowsazure"))) { ManagementCertificateListResponse.SubscriptionCertificate subscriptionCertificateInstance = new ManagementCertificateListResponse.SubscriptionCertificate(); result.SubscriptionCertificates.Add(subscriptionCertificateInstance); XElement subscriptionCertificatePublicKeyElement = subscriptionCertificatesElement.Element(XName.Get("SubscriptionCertificatePublicKey", "http://schemas.microsoft.com/windowsazure")); if (subscriptionCertificatePublicKeyElement != null) { byte[] subscriptionCertificatePublicKeyInstance = Convert.FromBase64String(subscriptionCertificatePublicKeyElement.Value); subscriptionCertificateInstance.PublicKey = subscriptionCertificatePublicKeyInstance; } XElement subscriptionCertificateThumbprintElement = subscriptionCertificatesElement.Element(XName.Get("SubscriptionCertificateThumbprint", "http://schemas.microsoft.com/windowsazure")); if (subscriptionCertificateThumbprintElement != null) { string subscriptionCertificateThumbprintInstance = subscriptionCertificateThumbprintElement.Value; subscriptionCertificateInstance.Thumbprint = subscriptionCertificateThumbprintInstance; } XElement subscriptionCertificateDataElement = subscriptionCertificatesElement.Element(XName.Get("SubscriptionCertificateData", "http://schemas.microsoft.com/windowsazure")); if (subscriptionCertificateDataElement != null) { byte[] subscriptionCertificateDataInstance = Convert.FromBase64String(subscriptionCertificateDataElement.Value); subscriptionCertificateInstance.Data = subscriptionCertificateDataInstance; } XElement createdElement = subscriptionCertificatesElement.Element(XName.Get("Created", "http://schemas.microsoft.com/windowsazure")); if (createdElement != null) { DateTime createdInstance = DateTime.Parse(createdElement.Value, CultureInfo.InvariantCulture); subscriptionCertificateInstance.Created = createdInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Collections.Generic; using System.Security.Principal; namespace System.DirectoryServices.AccountManagement { [DirectoryRdnPrefix("CN")] public class UserPrincipal : AuthenticablePrincipal { // // Public constructors // public UserPrincipal(PrincipalContext context) : base(context) { if (context == null) throw new ArgumentException(SR.NullArguments); this.ContextRaw = context; this.unpersisted = true; } public UserPrincipal(PrincipalContext context, string samAccountName, string password, bool enabled) : this(context) { if (samAccountName == null || password == null) throw new ArgumentException(SR.NullArguments); if (Context.ContextType != ContextType.ApplicationDirectory) this.SamAccountName = samAccountName; this.Name = samAccountName; this.SetPassword(password); this.Enabled = enabled; } // // Public properties // // GivenName private string _givenName = null; // the actual property value private LoadState _givenNameChanged = LoadState.NotSet; // change-tracking public string GivenName { get { return HandleGet<string>(ref _givenName, PropertyNames.UserGivenName, ref _givenNameChanged); } set { if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.UserGivenName)) throw new InvalidOperationException(SR.InvalidPropertyForStore); HandleSet<string>(ref _givenName, value, ref _givenNameChanged, PropertyNames.UserGivenName); } } // MiddleName private string _middleName = null; // the actual property value private LoadState _middleNameChanged = LoadState.NotSet; // change-tracking public string MiddleName { get { return HandleGet<string>(ref _middleName, PropertyNames.UserMiddleName, ref _middleNameChanged); } set { if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.UserMiddleName)) throw new InvalidOperationException(SR.InvalidPropertyForStore); HandleSet<string>(ref _middleName, value, ref _middleNameChanged, PropertyNames.UserMiddleName); } } // Surname private string _surname = null; // the actual property value private LoadState _surnameChanged = LoadState.NotSet; // change-tracking public string Surname { get { return HandleGet<string>(ref _surname, PropertyNames.UserSurname, ref _surnameChanged); } set { if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.UserSurname)) throw new InvalidOperationException(SR.InvalidPropertyForStore); HandleSet<string>(ref _surname, value, ref _surnameChanged, PropertyNames.UserSurname); } } // EmailAddress private string _emailAddress = null; // the actual property value private LoadState _emailAddressChanged = LoadState.NotSet; // change-tracking public string EmailAddress { get { return HandleGet<string>(ref _emailAddress, PropertyNames.UserEmailAddress, ref _emailAddressChanged); } set { if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.UserEmailAddress)) throw new InvalidOperationException(SR.InvalidPropertyForStore); HandleSet<string>(ref _emailAddress, value, ref _emailAddressChanged, PropertyNames.UserEmailAddress); } } // VoiceTelephoneNumber private string _voiceTelephoneNumber = null; // the actual property value private LoadState _voiceTelephoneNumberChanged = LoadState.NotSet; // change-tracking public string VoiceTelephoneNumber { get { return HandleGet<string>(ref _voiceTelephoneNumber, PropertyNames.UserVoiceTelephoneNumber, ref _voiceTelephoneNumberChanged); } set { if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.UserVoiceTelephoneNumber)) throw new InvalidOperationException(SR.InvalidPropertyForStore); HandleSet<string>(ref _voiceTelephoneNumber, value, ref _voiceTelephoneNumberChanged, PropertyNames.UserVoiceTelephoneNumber); } } // EmployeeId private string _employeeID = null; // the actual property value private LoadState _employeeIDChanged = LoadState.NotSet; // change-tracking public string EmployeeId { get { return HandleGet<string>(ref _employeeID, PropertyNames.UserEmployeeID, ref _employeeIDChanged); } set { if (!GetStoreCtxToUse().IsValidProperty(this, PropertyNames.UserEmployeeID)) throw new InvalidOperationException(SR.InvalidPropertyForStore); HandleSet<string>(ref _employeeID, value, ref _employeeIDChanged, PropertyNames.UserEmployeeID); } } public override AdvancedFilters AdvancedSearchFilter { get { return rosf; } } public static UserPrincipal Current { get { PrincipalContext context; // Get the correct PrincipalContext to query against, depending on whether we're running // as a local or domain user if (Utils.IsSamUser()) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "Current: is local user"); #if PAPI_REGSAM context = new PrincipalContext(ContextType.Machine); #else // This implementation doesn't support Reg-SAM/MSAM (machine principals) throw new NotSupportedException(SR.UserLocalNotSupportedOnPlatform); #endif // PAPI_REGSAM } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "Current: is not local user"); #if PAPI_AD context = new PrincipalContext(ContextType.Domain); #else // This implementation doesn't support AD (domain principals) throw new NotSupportedException(SR.UserDomainNotSupportedOnPlatform); #endif // PAPI_AD } // Construct a query for the current user, using a SID IdentityClaim IntPtr pSid = IntPtr.Zero; UserPrincipal user = null; try { pSid = Utils.GetCurrentUserSid(); byte[] sid = Utils.ConvertNativeSidToByteArray(pSid); SecurityIdentifier sidObj = new SecurityIdentifier(sid, 0); GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "Current: using SID " + sidObj.ToString()); user = UserPrincipal.FindByIdentity(context, IdentityType.Sid, sidObj.ToString()); } finally { if (pSid != IntPtr.Zero) System.Runtime.InteropServices.Marshal.FreeHGlobal(pSid); } // We're running as the user, we know they must exist, but perhaps we don't have access // to their user object if (user == null) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "User", "Current: found no user"); throw new NoMatchingPrincipalException(SR.UserCouldNotFindCurrent); } return user; } } // // Public methods // public static new PrincipalSearchResult<UserPrincipal> FindByLockoutTime(PrincipalContext context, DateTime time, MatchType type) { return FindByLockoutTime<UserPrincipal>(context, time, type); } public static new PrincipalSearchResult<UserPrincipal> FindByLogonTime(PrincipalContext context, DateTime time, MatchType type) { return FindByLogonTime<UserPrincipal>(context, time, type); } public static new PrincipalSearchResult<UserPrincipal> FindByExpirationTime(PrincipalContext context, DateTime time, MatchType type) { return FindByExpirationTime<UserPrincipal>(context, time, type); } public static new PrincipalSearchResult<UserPrincipal> FindByBadPasswordAttempt(PrincipalContext context, DateTime time, MatchType type) { return FindByBadPasswordAttempt<UserPrincipal>(context, time, type); } public static new PrincipalSearchResult<UserPrincipal> FindByPasswordSetTime(PrincipalContext context, DateTime time, MatchType type) { return FindByPasswordSetTime<UserPrincipal>(context, time, type); } public static new UserPrincipal FindByIdentity(PrincipalContext context, string identityValue) { return (UserPrincipal)FindByIdentityWithType(context, typeof(UserPrincipal), identityValue); } public static new UserPrincipal FindByIdentity(PrincipalContext context, IdentityType identityType, string identityValue) { return (UserPrincipal)FindByIdentityWithType(context, typeof(UserPrincipal), identityType, identityValue); } public PrincipalSearchResult<Principal> GetAuthorizationGroups() { return new PrincipalSearchResult<Principal>(GetAuthorizationGroupsHelper()); } // // Internal "constructor": Used for constructing Users returned by a query // static internal UserPrincipal MakeUser(PrincipalContext ctx) { UserPrincipal u = new UserPrincipal(ctx); u.unpersisted = false; return u; } // // Private implementation // private ResultSet GetAuthorizationGroupsHelper() { // Make sure we're not disposed or deleted. CheckDisposedOrDeleted(); // Unpersisted principals are not members of any group if (this.unpersisted) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "GetAuthorizationGroupsHelper: unpersisted, using EmptySet"); return new EmptySet(); } StoreCtx storeCtx = GetStoreCtxToUse(); Debug.Assert(storeCtx != null); GlobalDebug.WriteLineIf( GlobalDebug.Info, "User", "GetAuthorizationGroupsHelper: retrieving AZ groups from StoreCtx of type=" + storeCtx.GetType().ToString() + ", base path=" + storeCtx.BasePath); ResultSet resultSet = storeCtx.GetGroupsMemberOfAZ(this); return resultSet; } // // Load/Store implementation // // // Loading with query results // internal override void LoadValueIntoProperty(string propertyName, object value) { if (value == null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "LoadValueIntoProperty: name=" + propertyName + " value= null"); } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "LoadValueIntoProperty: name=" + propertyName + " value=" + value.ToString()); } switch (propertyName) { case (PropertyNames.UserGivenName): _givenName = (string)value; _givenNameChanged = LoadState.Loaded; break; case (PropertyNames.UserMiddleName): _middleName = (string)value; _middleNameChanged = LoadState.Loaded; break; case (PropertyNames.UserSurname): _surname = (string)value; _surnameChanged = LoadState.Loaded; break; case (PropertyNames.UserEmailAddress): _emailAddress = (string)value; _emailAddressChanged = LoadState.Loaded; break; case (PropertyNames.UserVoiceTelephoneNumber): _voiceTelephoneNumber = (string)value; _voiceTelephoneNumberChanged = LoadState.Loaded; break; case (PropertyNames.UserEmployeeID): _employeeID = (string)value; _employeeIDChanged = LoadState.Loaded; break; default: base.LoadValueIntoProperty(propertyName, value); break; } } // // Getting changes to persist (or to build a query from a QBE filter) // // Given a property name, returns true if that property has changed since it was loaded, false otherwise. internal override bool GetChangeStatusForProperty(string propertyName) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "GetChangeStatusForProperty: name=" + propertyName); switch (propertyName) { case (PropertyNames.UserGivenName): return _givenNameChanged == LoadState.Changed; case (PropertyNames.UserMiddleName): return _middleNameChanged == LoadState.Changed; case (PropertyNames.UserSurname): return _surnameChanged == LoadState.Changed; case (PropertyNames.UserEmailAddress): return _emailAddressChanged == LoadState.Changed; case (PropertyNames.UserVoiceTelephoneNumber): return _voiceTelephoneNumberChanged == LoadState.Changed; case (PropertyNames.UserEmployeeID): return _employeeIDChanged == LoadState.Changed; default: return base.GetChangeStatusForProperty(propertyName); } } // Given a property name, returns the current value for the property. internal override object GetValueForProperty(string propertyName) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "GetValueForProperty: name=" + propertyName); switch (propertyName) { case (PropertyNames.UserGivenName): return _givenName; case (PropertyNames.UserMiddleName): return _middleName; case (PropertyNames.UserSurname): return _surname; case (PropertyNames.UserEmailAddress): return _emailAddress; case (PropertyNames.UserVoiceTelephoneNumber): return _voiceTelephoneNumber; case (PropertyNames.UserEmployeeID): return _employeeID; default: return base.GetValueForProperty(propertyName); } } // Reset all change-tracking status for all properties on the object to "unchanged". internal override void ResetAllChangeStatus() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "User", "ResetAllChangeStatus"); _givenNameChanged = (_givenNameChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; ; _middleNameChanged = (_middleNameChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; ; _surnameChanged = (_surnameChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; ; _emailAddressChanged = (_emailAddressChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; ; _voiceTelephoneNumberChanged = (_voiceTelephoneNumberChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; ; _employeeIDChanged = (_employeeIDChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; ; base.ResetAllChangeStatus(); } } }
#region References using System; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using Raspberry.IO.Interop; using Raspberry.Timers; #endregion namespace Raspberry.IO.GeneralPurpose { /// <summary> /// Represents a connection driver that uses memory. /// </summary> public class MemoryGpioConnectionDriver : IGpioConnectionDriver { #region Fields private readonly IntPtr gpioAddress; private readonly Dictionary<ProcessorPin, PinResistor> pinResistors = new Dictionary<ProcessorPin, PinResistor>(); /// <summary> /// The default timeout (5 seconds). /// </summary> public static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(5); private static readonly TimeSpan resistorSetDelay = TimeSpanUtility.FromMicroseconds(5); #endregion #region Instance Management /// <summary> /// Initializes a new instance of the <see cref="MemoryGpioConnectionDriver"/> class. /// </summary> public MemoryGpioConnectionDriver() { using (var memoryFile = UnixFile.Open("/dev/mem", UnixFileMode.ReadWrite | UnixFileMode.Synchronized)) { gpioAddress = MemoryMap.Create( IntPtr.Zero, Interop.BCM2835_BLOCK_SIZE, MemoryProtection.ReadWrite, MemoryFlags.Shared, memoryFile.Descriptor, GetProcessorBaseAddress(Board.Current.Processor)); } } /// <summary> /// Releases unmanaged resources and performs other cleanup operations before the /// <see cref="MemoryGpioConnectionDriver"/> is reclaimed by garbage collection. /// </summary> ~MemoryGpioConnectionDriver() { MemoryMap.Close(gpioAddress, Interop.BCM2835_BLOCK_SIZE); } #endregion #region Methods /// <summary> /// Gets driver capabilities. /// </summary> /// <returns>The capabilites.</returns> GpioConnectionDriverCapabilities IGpioConnectionDriver.GetCapabilities() { return GetCapabilities(); } /// <summary> /// Gets driver capabilities. /// </summary> /// <returns>The capabilites.</returns> public static GpioConnectionDriverCapabilities GetCapabilities() { return GpioConnectionDriverCapabilities.CanSetPinResistor | GpioConnectionDriverCapabilities.CanChangePinDirectionRapidly; } /// <summary> /// Allocates the specified pin. /// </summary> /// <param name="pin">The pin.</param> /// <param name="direction">The direction.</param> public void Allocate(ProcessorPin pin, PinDirection direction) { // Set the direction on the pin and update the exported list SetPinMode(pin, direction == PinDirection.Input ? Interop.BCM2835_GPIO_FSEL_INPT : Interop.BCM2835_GPIO_FSEL_OUTP); if (direction == PinDirection.Input) { PinResistor pinResistor; if (!pinResistors.TryGetValue(pin, out pinResistor) || pinResistor != PinResistor.None) SetPinResistor(pin, PinResistor.None); } } /// <summary> /// Sets the pin resistor. /// </summary> /// <param name="pin">The pin.</param> /// <param name="resistor">The resistor.</param> public void SetPinResistor(ProcessorPin pin, PinResistor resistor) { // Set the pullup/down resistor for a pin // // The GPIO Pull-up/down Clock Registers control the actuation of internal pull-downs on // the respective GPIO pins. These registers must be used in conjunction with the GPPUD // register to effect GPIO Pull-up/down changes. The following sequence of events is // required: // 1. Write to GPPUD to set the required control signal (i.e. Pull-up or Pull-Down or neither // to remove the current Pull-up/down) // 2. Wait 150 cycles ? this provides the required set-up time for the control signal // 3. Write to GPPUDCLK0/1 to clock the control signal into the GPIO pads you wish to // modify ? NOTE only the pads which receive a clock will be modified, all others will // retain their previous state. // 4. Wait 150 cycles ? this provides the required hold time for the control signal // 5. Write to GPPUD to remove the control signal // 6. Write to GPPUDCLK0/1 to remove the clock // // RPi has P1-03 and P1-05 with 1k8 pullup resistor uint pud; switch(resistor) { case PinResistor.None: pud = Interop.BCM2835_GPIO_PUD_OFF; break; case PinResistor.PullDown: pud = Interop.BCM2835_GPIO_PUD_DOWN; break; case PinResistor.PullUp: pud = Interop.BCM2835_GPIO_PUD_UP; break; default: throw new ArgumentOutOfRangeException("resistor", resistor, string.Format(CultureInfo.InvariantCulture, "{0} is not a valid value for pin resistor", resistor)); } WriteResistor(pud); HighResolutionTimer.Sleep(resistorSetDelay); SetPinResistorClock(pin, true); HighResolutionTimer.Sleep(resistorSetDelay); WriteResistor(Interop.BCM2835_GPIO_PUD_OFF); SetPinResistorClock(pin, false); pinResistors[pin] = PinResistor.None; } /// <summary> /// Sets the detected edges on an input pin. /// </summary> /// <param name="pin">The pin.</param> /// <param name="edges">The edges.</param> /// <remarks> /// By default, both edges may be detected on input pins. /// </remarks> public void SetPinDetectedEdges(ProcessorPin pin, PinDetectedEdges edges) { throw new NotSupportedException("Edge detection is not supported by memory GPIO connection driver"); } /// <summary> /// Waits for the specified pin to be in the specified state. /// </summary> /// <param name="pin">The pin.</param> /// <param name="waitForUp">if set to <c>true</c> waits for the pin to be up. Default value is <c>true</c>.</param> /// <param name="timeout">The timeout. Default value is <see cref="TimeSpan.Zero" />.</param> /// <remarks> /// If <c>timeout</c> is set to <see cref="TimeSpan.Zero" />, a default timeout of <see cref="DefaultTimeout"/> is used. /// </remarks> public void Wait(ProcessorPin pin, bool waitForUp = true, TimeSpan timeout = new TimeSpan()) { var startWait = DateTime.UtcNow; if (timeout == TimeSpan.Zero) timeout = DefaultTimeout; while (Read(pin) != waitForUp) { if (DateTime.UtcNow >= startWait + timeout) throw new TimeoutException("A timeout occurred while waiting for pin status to change"); } } /// <summary> /// Releases the specified pin. /// </summary> /// <param name="pin">The pin.</param> public void Release(ProcessorPin pin) { SetPinMode(pin, Interop.BCM2835_GPIO_FSEL_INPT); } /// <summary> /// Modified the status of a pin. /// </summary> /// <param name="pin">The pin.</param> /// <param name="value">The pin status.</param> public void Write(ProcessorPin pin, bool value) { int shift; var offset = Math.DivRem((int)pin, 32, out shift); var pinGroupAddress = gpioAddress + (int)((value ? Interop.BCM2835_GPSET0 : Interop.BCM2835_GPCLR0) + offset); SafeWriteUInt32(pinGroupAddress, (uint) 1 << shift); } /// <summary> /// Reads the status of the specified pin. /// </summary> /// <param name="pin">The pin.</param> /// <returns> /// The pin status. /// </returns> public bool Read(ProcessorPin pin) { int shift; var offset = Math.DivRem((int) pin, 32, out shift); var pinGroupAddress = gpioAddress + (int) (Interop.BCM2835_GPLEV0 + offset); var value = SafeReadUInt32(pinGroupAddress); return (value & (1 << shift)) != 0; } /// <summary> /// Reads the status of the specified pins. /// </summary> /// <param name="pins">The pins.</param> /// <returns> /// The pins status. /// </returns> public ProcessorPins Read(ProcessorPins pins) { var pinGroupAddress = gpioAddress + (int) (Interop.BCM2835_GPLEV0 + (uint) 0 * 4); var value = SafeReadUInt32(pinGroupAddress); return (ProcessorPins)((uint)pins & value); } #endregion #region Private Methods private static uint GetProcessorBaseAddress(Processor processor) { switch (processor) { case Processor.Bcm2708: return Interop.BCM2835_GPIO_BASE; case Processor.Bcm2709: case Processor.Bcm2835: return Interop.BCM2836_GPIO_BASE; default: throw new ArgumentOutOfRangeException("processor"); } } private void SetPinResistorClock(ProcessorPin pin, bool on) { int shift; var offset = Math.DivRem((int)pin, 32, out shift); var clockAddress = gpioAddress + (int)(Interop.BCM2835_GPPUDCLK0 + offset); SafeWriteUInt32(clockAddress, (uint) (on ? 1 : 0) << shift); } private void WriteResistor(uint resistor) { var resistorPin = gpioAddress + (int) Interop.BCM2835_GPPUD; SafeWriteUInt32(resistorPin, resistor); } private void SetPinMode(ProcessorPin pin, uint mode) { // Function selects are 10 pins per 32 bit word, 3 bits per pin var pinModeAddress = gpioAddress + (int) (Interop.BCM2835_GPFSEL0 + 4*((int)pin/10)); var shift = 3*((int) pin%10); var mask = Interop.BCM2835_GPIO_FSEL_MASK << shift; var value = mode << shift; WriteUInt32Mask(pinModeAddress, value, mask); } private static void WriteUInt32Mask(IntPtr address, uint value, uint mask) { var v = SafeReadUInt32(address); v = (v & ~mask) | (value & mask); SafeWriteUInt32(address, v); } private static uint SafeReadUInt32(IntPtr address) { // Make sure we dont return the _last_ read which might get lost // if subsequent code changes to a different peripheral var ret = ReadUInt32(address); ReadUInt32(address); return ret; } private static uint ReadUInt32(IntPtr address) { unchecked { return (uint) Marshal.ReadInt32(address); } } private static void SafeWriteUInt32(IntPtr address, uint value) { // Make sure we don't rely on the first write, which may get // lost if the previous access was to a different peripheral. WriteUInt32(address, value); WriteUInt32(address, value); } private static void WriteUInt32(IntPtr address, uint value) { unchecked { Marshal.WriteInt32(address, (int)value); } } #endregion } }
// // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using System.Text; using System.Threading; using Mono.Collections.Generic; namespace Mono.Cecil { public class MethodReference : MemberReference, IMethodSignature, IGenericParameterProvider, IGenericContext { internal ParameterDefinitionCollection parameters; MethodReturnType return_type; bool has_this; bool explicit_this; MethodCallingConvention calling_convention; internal Collection<GenericParameter> generic_parameters; public virtual bool HasThis { get { return has_this; } set { has_this = value; } } public virtual bool ExplicitThis { get { return explicit_this; } set { explicit_this = value; } } public virtual MethodCallingConvention CallingConvention { get { return calling_convention; } set { calling_convention = value; } } public virtual bool HasParameters { get { return !parameters.IsNullOrEmpty (); } } public virtual Collection<ParameterDefinition> Parameters { get { if (parameters == null) Interlocked.CompareExchange (ref parameters, new ParameterDefinitionCollection (this), null); return parameters; } } IGenericParameterProvider IGenericContext.Type { get { var declaring_type = this.DeclaringType; var instance = declaring_type as GenericInstanceType; if (instance != null) return instance.ElementType; return declaring_type; } } IGenericParameterProvider IGenericContext.Method { get { return this; } } GenericParameterType IGenericParameterProvider.GenericParameterType { get { return GenericParameterType.Method; } } public virtual bool HasGenericParameters { get { return !generic_parameters.IsNullOrEmpty (); } } public virtual Collection<GenericParameter> GenericParameters { get { if (generic_parameters == null) Interlocked.CompareExchange (ref generic_parameters, new GenericParameterCollection (this), null); return generic_parameters; } } public TypeReference ReturnType { get { var return_type = MethodReturnType; return return_type != null ? return_type.ReturnType : null; } set { var return_type = MethodReturnType; if (return_type != null) return_type.ReturnType = value; } } public virtual MethodReturnType MethodReturnType { get { return return_type; } set { return_type = value; } } public override string FullName { get { var builder = new StringBuilder (); builder.Append (ReturnType.FullName) .Append (" ") .Append (MemberFullName ()); this.MethodSignatureFullName (builder); return builder.ToString (); } } public virtual bool IsGenericInstance { get { return false; } } public override bool ContainsGenericParameter { get { if (this.ReturnType.ContainsGenericParameter || base.ContainsGenericParameter) return true; if (!HasParameters) return false; var parameters = this.Parameters; for (int i = 0; i < parameters.Count; i++) if (parameters [i].ParameterType.ContainsGenericParameter) return true; return false; } } internal MethodReference () { this.return_type = new MethodReturnType (this); this.token = new MetadataToken (TokenType.MemberRef); } public MethodReference (string name, TypeReference returnType) : base (name) { Mixin.CheckType (returnType, Mixin.Argument.returnType); this.return_type = new MethodReturnType (this); this.return_type.ReturnType = returnType; this.token = new MetadataToken (TokenType.MemberRef); } public MethodReference (string name, TypeReference returnType, TypeReference declaringType) : this (name, returnType) { Mixin.CheckType (declaringType, Mixin.Argument.declaringType); this.DeclaringType = declaringType; } public virtual MethodReference GetElementMethod () { return this; } protected override IMemberDefinition ResolveDefinition () { return this.Resolve (); } public new virtual MethodDefinition Resolve () { var module = this.Module; if (module == null) throw new NotSupportedException (); return module.Resolve (this); } } static partial class Mixin { public static bool IsVarArg (this IMethodSignature self) { return self.CallingConvention == MethodCallingConvention.VarArg; } public static int GetSentinelPosition (this IMethodSignature self) { if (!self.HasParameters) return -1; var parameters = self.Parameters; for (int i = 0; i < parameters.Count; i++) if (parameters [i].ParameterType.IsSentinel) return i; return -1; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace MusicStore.Api.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using UnityEngine; using UnityEditor; using System.Collections.Generic; using System.Reflection; using System.Linq; namespace Anima2D { public class ContextMenu { [MenuItem("Assets/Create/Anima2D/SpriteMesh", true)] static bool ValidateCreateSpriteMesh(MenuCommand menuCommand) { bool valid = false; Sprite sprite = Selection.activeObject as Sprite; if(sprite && !SpriteMeshPostprocessor.GetSpriteMeshFromSprite(sprite)) { valid = true; } List<Texture2D> selectedTextures = Selection.objects.ToList().Where( o => o is Texture2D).ToList().ConvertAll( o => o as Texture2D); valid = valid || selectedTextures.Count > 0; return valid; } [MenuItem("Assets/Create/Anima2D/SpriteMesh", false)] static void CreateSpriteMesh(MenuCommand menuCommand) { List<Texture2D> selectedTextures = Selection.objects.ToList().Where( o => o is Texture2D).ToList().ConvertAll( o => o as Texture2D); foreach(Texture2D texture in selectedTextures) { SpriteMeshUtils.CreateSpriteMesh(texture); } if(selectedTextures.Count == 0) { SpriteMeshUtils.CreateSpriteMesh(Selection.activeObject as Sprite); } } [MenuItem("GameObject/2D Object/SpriteMesh", false, 10)] static void ContextCreateSpriteMesh(MenuCommand menuCommand) { GameObject spriteRendererGO = Selection.activeGameObject; SpriteRenderer spriteRenderer = null; SpriteMesh spriteMesh = null; if(spriteRendererGO) { spriteRenderer = spriteRendererGO.GetComponent<SpriteRenderer>(); } if(spriteRenderer && spriteRenderer.sprite) { SpriteMesh overrideSpriteMesh = SpriteMeshPostprocessor.GetSpriteMeshFromSprite(spriteRenderer.sprite); if(overrideSpriteMesh) { spriteMesh = overrideSpriteMesh; }else{ spriteMesh = SpriteMeshUtils.CreateSpriteMesh(spriteRenderer.sprite); } } if(spriteMesh) { Undo.SetCurrentGroupName("create SpriteMeshInstance"); Undo.DestroyObjectImmediate(spriteRenderer); SpriteMeshUtils.CreateSpriteMeshInstance(spriteMesh,spriteRendererGO,true); Selection.activeGameObject = spriteRendererGO; }else{ Debug.Log("Select a SpriteRenderer with a Sprite to convert to SpriteMesh"); } } [MenuItem("GameObject/2D Object/Bone &#b", false, 10)] public static void CreateBone(MenuCommand menuCommand) { GameObject bone = new GameObject("New bone"); Bone2D boneComponent = bone.AddComponent<Bone2D>(); Undo.RegisterCreatedObjectUndo(bone, "Create bone"); bone.transform.position = GetDefaultInstantiatePosition(); GameObject selectedGO = Selection.activeGameObject; if(selectedGO) { bone.transform.parent = selectedGO.transform; Vector3 localPosition = bone.transform.localPosition; localPosition.z = 0f; bone.transform.localPosition = localPosition; bone.transform.localRotation = Quaternion.identity; bone.transform.localScale = Vector3.one; Bone2D selectedBone = selectedGO.GetComponent<Bone2D>(); if(selectedBone) { if(!selectedBone.child) { bone.transform.position = selectedBone.endPosition; selectedBone.child = boneComponent; } } } Selection.activeGameObject = bone; } [MenuItem("GameObject/2D Object/IK CCD &#k", false, 10)] static void CreateIkCCD(MenuCommand menuCommand) { GameObject ikCCD = new GameObject("New Ik CCD"); Undo.RegisterCreatedObjectUndo(ikCCD,"Crate Ik CCD"); IkCCD2D ikCCDComponent = ikCCD.AddComponent<IkCCD2D>(); ikCCD.transform.position = GetDefaultInstantiatePosition(); GameObject selectedGO = Selection.activeGameObject; if(selectedGO) { ikCCD.transform.parent = selectedGO.transform; ikCCD.transform.localPosition = Vector3.zero; Bone2D selectedBone = selectedGO.GetComponent<Bone2D>(); if(selectedBone) { ikCCD.transform.parent = selectedBone.root.transform.parent; ikCCD.transform.position = selectedBone.endPosition; if(selectedBone.child) { ikCCD.transform.rotation = selectedBone.child.transform.rotation; } ikCCDComponent.numBones = selectedBone.chainLength; ikCCDComponent.target = selectedBone; } } ikCCD.transform.localScale = Vector3.one; EditorUtility.SetDirty(ikCCDComponent); Selection.activeGameObject = ikCCD; } [MenuItem("GameObject/2D Object/IK Limb &#l", false, 10)] static void CreateIkLimb(MenuCommand menuCommand) { GameObject ikLimb = new GameObject("New Ik Limb"); Undo.RegisterCreatedObjectUndo(ikLimb,"Crate Ik Limb"); IkLimb2D ikLimbComponent = ikLimb.AddComponent<IkLimb2D>(); ikLimb.transform.position = GetDefaultInstantiatePosition(); GameObject selectedGO = Selection.activeGameObject; if(selectedGO) { ikLimb.transform.parent = selectedGO.transform; ikLimb.transform.localPosition = Vector3.zero; Bone2D selectedBone = selectedGO.GetComponent<Bone2D>(); if(selectedBone) { ikLimb.transform.parent = selectedBone.root.transform.parent; ikLimb.transform.position = selectedBone.endPosition; if(selectedBone.child) { ikLimb.transform.rotation = selectedBone.child.transform.rotation; } ikLimbComponent.numBones = selectedBone.chainLength; ikLimbComponent.target = selectedBone; } } ikLimb.transform.localScale = Vector3.one; EditorUtility.SetDirty(ikLimbComponent); Selection.activeGameObject = ikLimb; } [MenuItem("GameObject/2D Object/Control &#c", false, 10)] static void CreateControl(MenuCommand menuCommand) { GameObject control = new GameObject("New control"); Undo.RegisterCreatedObjectUndo(control,"Crate Control"); Control controlComponent = control.AddComponent<Control>(); control.transform.position = GetDefaultInstantiatePosition(); GameObject selectedGO = Selection.activeGameObject; if(selectedGO) { control.transform.parent = selectedGO.transform; control.transform.localPosition = Vector3.zero; control.transform.localRotation = Quaternion.identity; Bone2D selectedBone = selectedGO.GetComponent<Bone2D>(); if(selectedBone) { control.name = "Control " + selectedBone.name; controlComponent.bone = selectedBone; control.transform.parent = selectedBone.root.transform.parent; } } EditorUtility.SetDirty(controlComponent); Selection.activeGameObject = control; } [MenuItem("Assets/Create/Anima2D/Pose")] public static void CreatePose(MenuCommand menuCommand) { string path = AssetDatabase.GetAssetPath(Selection.activeObject); if(System.IO.File.Exists(path)) { path = System.IO.Path.GetDirectoryName(path); } path += "/"; if(System.IO.Directory.Exists(path)) { path += "New pose.asset"; ScriptableObjectUtility.CreateAsset<Pose>(path); } } static Vector3 GetDefaultInstantiatePosition() { Vector3 result = Vector3.zero; if (SceneView.lastActiveSceneView) { if (SceneView.lastActiveSceneView.in2DMode) { result = SceneView.lastActiveSceneView.camera.transform.position; result.z = 0f; } else { PropertyInfo prop = typeof(SceneView).GetProperty("cameraTargetPosition",BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); result = (Vector3) prop.GetValue(SceneView.lastActiveSceneView,null); } } 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 Microsoft.Build.Framework; using NuGet; using NuGet.Frameworks; using NuGet.Versioning; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.Versioning; namespace Microsoft.DotNet.Build.Tasks.Packaging { public static class Extensions { private static readonly NuGetFramework NullFramework = new NuGetFramework("Null,Version=v1.0"); public static string GetString(this ITaskItem taskItem, string metadataName) { var metadataValue = taskItem.GetMetadata(metadataName)?.Trim(); return String.IsNullOrEmpty(metadataValue) ? null : metadataValue; } public static bool GetBoolean(this ITaskItem taskItem, string metadataName, bool defaultValue = false) { bool result = false; var metadataValue = taskItem.GetMetadata(metadataName); if (!bool.TryParse(metadataValue, out result)) { result = defaultValue; } return result; } public static NuGetFramework GetTargetFramework(this ITaskItem taskItem) { NuGetFramework result = null; var metadataValue = taskItem.GetMetadata(Metadata.TargetFramework); if (!string.IsNullOrEmpty(metadataValue)) { result = NuGetFramework.Parse(metadataValue); } return result; } public static NuGetFramework GetTargetFrameworkMoniker(this ITaskItem taskItem) { NuGetFramework result = null; var metadataValue = taskItem.GetMetadata(Metadata.TargetFrameworkMoniker); if (!string.IsNullOrEmpty(metadataValue)) { result = new NuGetFramework(metadataValue); } return result; } public static PackageDirectory GetPackageDirectory(this ITaskItem taskItem) { var packageDirectoryName = taskItem.GetMetadata(Metadata.PackageDirectory); if (string.IsNullOrEmpty(packageDirectoryName)) { return PackageDirectory.Lib; } PackageDirectory result; Enum.TryParse(packageDirectoryName, true, out result); return result; } public static VersionRange GetVersion(this ITaskItem taskItem) { VersionRange result = null; var metadataValue = taskItem.GetMetadata(Metadata.Version); if (!string.IsNullOrEmpty(metadataValue)) { VersionRange.TryParse(metadataValue, out result); } return result; } public static IReadOnlyList<string> GetValueList(this ITaskItem taskItem, string metadataName) { var metadataValue = taskItem.GetMetadata(metadataName); if (!string.IsNullOrEmpty(metadataValue)) { return metadataValue.Split(';'); } return null; } public static IEnumerable<string> GetStrings(this ITaskItem taskItem, string metadataName) { var metadataValue = taskItem.GetMetadata(metadataName)?.Trim(); if (!string.IsNullOrEmpty(metadataValue)) { return metadataValue.Split(';').Where(v => !String.IsNullOrEmpty(v.Trim())).ToArray(); } return Enumerable.Empty<string>(); } public static IEnumerable<T> NullAsEmpty<T>(this IEnumerable<T> source) { if (source == null) { return Enumerable.Empty<T>(); } return source; } public static string TrimAndGetNullForEmpty(this string s) { if (s == null) { return null; } s = s.Trim(); return s.Length == 0 ? null : s; } public static IEnumerable<string> TrimAndExcludeNullOrEmpty(this string[] strings) { if (strings == null) { return Enumerable.Empty<string>(); } return strings .Select(s => TrimAndGetNullForEmpty(s)) .Where(s => s != null); } public static string ToStringSafe(this object value) { if (value == null) { return null; } return value.ToString(); } public static void UpdateMember<T1, T2>(this T1 target, Expression<Func<T1, T2>> memberLamda, T2 value) { if (value == null) { return; } var memberSelectorExpression = memberLamda.Body as MemberExpression; if (memberSelectorExpression == null) { throw new InvalidOperationException("Invalid member expression."); } var property = memberSelectorExpression.Member as PropertyInfo; if (property == null) { throw new InvalidOperationException("Invalid member expression."); } property.SetValue(target, value, null); } public static void AddRangeToMember<T, TItem>(this T target, Expression<Func<T, ICollection<TItem>>> memberLamda, IEnumerable<TItem> value) { if (value == null || value.Count() == 0) { return; } var memberSelectorExpression = memberLamda.Body as MemberExpression; if (memberSelectorExpression == null) { throw new InvalidOperationException("Invalid member expression."); } var property = memberSelectorExpression.Member as PropertyInfo; if (property == null) { throw new InvalidOperationException("Invalid member expression."); } var list = (List<TItem>)property.GetValue(target) ?? new List<TItem>(); list.AddRange(value); //property.SetValue(target, list, null); } } } namespace NuGet { internal static class NuGetFrameworkExtensions { // NuGet.Frameworks doesn't have the equivalent of the old VersionUtility.GetFrameworkString // which is relevant for building packages public static string GetFrameworkString(this NuGetFramework self) { var frameworkName = new FrameworkName(self.DotNetFrameworkName); string name = frameworkName.Identifier + frameworkName.Version; if (string.IsNullOrEmpty(frameworkName.Profile)) { return name; } return name + "-" + frameworkName.Profile; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics.Contracts; using System.IO; namespace System.Security.Claims { /// <summary> /// A Claim is a statement about an entity by an Issuer. /// A Claim consists of a Type, Value, a Subject and an Issuer. /// Additional properties, ValueType, Properties and OriginalIssuer help understand the claim when making decisions. /// </summary> public class Claim { private enum SerializationMask { None = 0, NameClaimType = 1, RoleClaimType = 2, StringType = 4, Issuer = 8, OriginalIssuerEqualsIssuer = 16, OriginalIssuer = 32, HasProperties = 64, UserData = 128, } private byte[] _userSerializationData; private string _issuer; private string _originalIssuer; private Dictionary<string, string> _properties = new Dictionary<string, string>(); private ClaimsIdentity _subject; private string _type; private string _value; private string _valueType; /// <summary> /// Initializes an instance of <see cref="Claim"/> using a <see cref="BinaryReader"/>. /// Normally the <see cref="BinaryReader"/> is constructed using the bytes from <see cref="WriteTo(BinaryWriter)"/> and initialized in the same way as the <see cref="BinaryWriter"/>. /// </summary> /// <param name="reader">a <see cref="BinaryReader"/> pointing to a <see cref="Claim"/>.</param> /// <exception cref="ArgumentNullException">if 'reader' is null.</exception> public Claim(BinaryReader reader) : this(reader, null) { } /// <summary> /// Initializes an instance of <see cref="Claim"/> using a <see cref="BinaryReader"/>. /// Normally the <see cref="BinaryReader"/> is constructed using the bytes from <see cref="WriteTo(BinaryWriter)"/> and initialized in the same way as the <see cref="BinaryWriter"/>. /// </summary> /// <param name="reader">a <see cref="BinaryReader"/> pointing to a <see cref="Claim"/>.</param> /// <param name="subject"> the value for <see cref="Claim.Subject"/>, which is the <see cref="ClaimsIdentity"/> that has these claims.</param> /// <exception cref="ArgumentNullException">if 'reader' is null.</exception> public Claim(BinaryReader reader, ClaimsIdentity subject) { if (reader == null) throw new ArgumentNullException(nameof(reader)); Initialize(reader, subject); } /// <summary> /// Creates a <see cref="Claim"/> with the specified type and value. /// </summary> /// <param name="type">The claim type.</param> /// <param name="value">The claim value.</param> /// <exception cref="ArgumentNullException"><paramref name="type"/> or <paramref name="value"/> is null.</exception> /// <remarks> /// <see cref="Claim.Issuer"/> is set to <see cref="ClaimsIdentity.DefaultIssuer"/>, /// <see cref="Claim.ValueType"/> is set to <see cref="ClaimValueTypes.String"/>, /// <see cref="Claim.OriginalIssuer"/> is set to <see cref="ClaimsIdentity.DefaultIssuer"/>, and /// <see cref="Claim.Subject"/> is set to null. /// </remarks> /// <seealso cref="ClaimsIdentity"/> /// <seealso cref="ClaimTypes"/> /// <seealso cref="ClaimValueTypes"/> public Claim(string type, string value) : this(type, value, ClaimValueTypes.String, ClaimsIdentity.DefaultIssuer, ClaimsIdentity.DefaultIssuer, (ClaimsIdentity)null) { } /// <summary> /// Creates a <see cref="Claim"/> with the specified type, value, and value type. /// </summary> /// <param name="type">The claim type.</param> /// <param name="value">The claim value.</param> /// <param name="valueType">The claim value type.</param> /// <exception cref="ArgumentNullException"><paramref name="type"/> or <paramref name="value"/> is null.</exception> /// <remarks> /// <see cref="Claim.Issuer"/> is set to <see cref="ClaimsIdentity.DefaultIssuer"/>, /// <see cref="Claim.OriginalIssuer"/> is set to <see cref="ClaimsIdentity.DefaultIssuer"/>, /// and <see cref="Claim.Subject"/> is set to null. /// </remarks> /// <seealso cref="ClaimsIdentity"/> /// <seealso cref="ClaimTypes"/> /// <seealso cref="ClaimValueTypes"/> public Claim(string type, string value, string valueType) : this(type, value, valueType, ClaimsIdentity.DefaultIssuer, ClaimsIdentity.DefaultIssuer, (ClaimsIdentity)null) { } /// <summary> /// Creates a <see cref="Claim"/> with the specified type, value, value type, and issuer. /// </summary> /// <param name="type">The claim type.</param> /// <param name="value">The claim value.</param> /// <param name="valueType">The claim value type. If this parameter is empty or null, then <see cref="ClaimValueTypes.String"/> is used.</param> /// <param name="issuer">The claim issuer. If this parameter is empty or null, then <see cref="ClaimsIdentity.DefaultIssuer"/> is used.</param> /// <exception cref="ArgumentNullException"><paramref name="type"/> or <paramref name="value"/> is null.</exception> /// <remarks> /// <see cref="Claim.OriginalIssuer"/> is set to value of the <paramref name="issuer"/> parameter, /// <see cref="Claim.Subject"/> is set to null. /// </remarks> /// <seealso cref="ClaimsIdentity"/> /// <seealso cref="ClaimTypes"/> /// <seealso cref="ClaimValueTypes"/> public Claim(string type, string value, string valueType, string issuer) : this(type, value, valueType, issuer, issuer, (ClaimsIdentity)null) { } /// <summary> /// Creates a <see cref="Claim"/> with the specified type, value, value type, issuer and original issuer. /// </summary> /// <param name="type">The claim type.</param> /// <param name="value">The claim value.</param> /// <param name="valueType">The claim value type. If this parameter is null, then <see cref="ClaimValueTypes.String"/> is used.</param> /// <param name="issuer">The claim issuer. If this parameter is empty or null, then <see cref="ClaimsIdentity.DefaultIssuer"/> is used.</param> /// <param name="originalIssuer">The original issuer of this claim. If this parameter is empty or null, then orignalIssuer == issuer.</param> /// <exception cref="ArgumentNullException"><paramref name="type"/> or <paramref name="value"/> is null.</exception> /// <remarks> /// <see cref="Claim.Subject"/> is set to null. /// </remarks> /// <seealso cref="ClaimsIdentity"/> /// <seealso cref="ClaimTypes"/> /// <seealso cref="ClaimValueTypes"/> public Claim(string type, string value, string valueType, string issuer, string originalIssuer) : this(type, value, valueType, issuer, originalIssuer, (ClaimsIdentity)null) { } /// <summary> /// Creates a <see cref="Claim"/> with the specified type, value, value type, issuer, original issuer and subject. /// </summary> /// <param name="type">The claim type.</param> /// <param name="value">The claim value.</param> /// <param name="valueType">The claim value type. If this parameter is null, then <see cref="ClaimValueTypes.String"/> is used.</param> /// <param name="issuer">The claim issuer. If this parameter is empty or null, then <see cref="ClaimsIdentity.DefaultIssuer"/> is used.</param> /// <param name="originalIssuer">The original issuer of this claim. If this parameter is empty or null, then orignalIssuer == issuer.</param> /// <param name="subject">The subject that this claim describes.</param> /// <exception cref="ArgumentNullException"><paramref name="type"/> or <paramref name="value"/> is null.</exception> /// <seealso cref="ClaimsIdentity"/> /// <seealso cref="ClaimTypes"/> /// <seealso cref="ClaimValueTypes"/> public Claim(string type, string value, string valueType, string issuer, string originalIssuer, ClaimsIdentity subject) : this(type, value, valueType, issuer, originalIssuer, subject, null, null) { } /// <summary> /// This internal constructor was added as a performance boost when adding claims that are found in the NTToken. /// We need to add a property value to distinguish DeviceClaims from UserClaims. /// </summary> /// <param name="propertyKey">This allows adding a property when adding a Claim.</param> /// <param name="propertyValue">The value associcated with the property.</param> internal Claim(string type, string value, string valueType, string issuer, string originalIssuer, ClaimsIdentity subject, string propertyKey, string propertyValue) { if (type == null) { throw new ArgumentNullException(nameof(type)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } Contract.EndContractBlock(); _type = type; _value = value; _valueType = string.IsNullOrEmpty(valueType) ? ClaimValueTypes.String : valueType; _issuer = string.IsNullOrEmpty(issuer) ? ClaimsIdentity.DefaultIssuer : issuer; _originalIssuer = string.IsNullOrEmpty(originalIssuer) ? _issuer : originalIssuer; _subject = subject; if (propertyKey != null) { _properties[propertyKey] = propertyValue; } } /// <summary> /// Copy constructor for <see cref="Claim"/> /// </summary> /// <param name="other">the <see cref="Claim"/> to copy.</param> /// <remarks><see cref="Claim.Subject"/>will be set to 'null'.</remarks> /// <exception cref="ArgumentNullException">if 'other' is null.</exception> protected Claim(Claim other) : this(other, (other == null ? (ClaimsIdentity)null : other._subject)) { } /// <summary> /// Copy constructor for <see cref="Claim"/> /// </summary> /// <param name="other">the <see cref="Claim"/> to copy.</param> /// <param name="subject">the <see cref="ClaimsIdentity"/> to assign to <see cref="Claim.Subject"/>.</param> /// <remarks><see cref="Claim.Subject"/>will be set to 'subject'.</remarks> /// <exception cref="ArgumentNullException">if 'other' is null.</exception> protected Claim(Claim other, ClaimsIdentity subject) { if (other == null) throw new ArgumentNullException(nameof(other)); _issuer = other._issuer; _originalIssuer = other._originalIssuer; _subject = subject; _type = other._type; _value = other._value; _valueType = other._valueType; foreach (var key in other._properties.Keys) { _properties.Add(key, other._properties[key]); } if (other._userSerializationData != null) { _userSerializationData = other._userSerializationData.Clone() as byte[]; } } /// <summary> /// Contains any additional data provided by a derived type, typically set when calling <see cref="WriteTo(BinaryWriter, byte[])"/>.</param> /// </summary> protected virtual byte[] CustomSerializationData { get { return _userSerializationData; } } /// <summary> /// Gets the issuer of the <see cref="Claim"/>. /// </summary> public string Issuer { get { return _issuer; } } /// <summary> /// Gets the original issuer of the <see cref="Claim"/>. /// </summary> /// <remarks> /// When the <see cref="OriginalIssuer"/> differs from the <see cref="Issuer"/>, it means /// that the claim was issued by the <see cref="OriginalIssuer"/> and was re-issued /// by the <see cref="Issuer"/>. /// </remarks> public string OriginalIssuer { get { return _originalIssuer; } } /// <summary> /// Gets the collection of Properties associated with the <see cref="Claim"/>. /// </summary> public IDictionary<string, string> Properties { get { return _properties; } } /// <summary> /// Gets the subject of the <see cref="Claim"/>. /// </summary> public ClaimsIdentity Subject { get { return _subject; } internal set { _subject = value; } } /// <summary> /// Gets the claim type of the <see cref="Claim"/>. /// <seealso cref="ClaimTypes"/>. /// </summary> public string Type { get { return _type; } } /// <summary> /// Gets the value of the <see cref="Claim"/>. /// </summary> public string Value { get { return _value; } } /// <summary> /// Gets the value type of the <see cref="Claim"/>. /// <seealso cref="ClaimValueTypes"/> /// </summary> public string ValueType { get { return _valueType; } } /// <summary> /// Creates a new instance <see cref="Claim"/> with values copied from this object. /// </summary> public virtual Claim Clone() { return Clone((ClaimsIdentity)null); } /// <summary> /// Creates a new instance <see cref="Claim"/> with values copied from this object. /// </summary> /// <param name="identity">the value for <see cref="Claim.Subject"/>, which is the <see cref="ClaimsIdentity"/> that has these claims. /// <remarks><see cref="Claim.Subject"/> will be set to 'identity'.</remarks> public virtual Claim Clone(ClaimsIdentity identity) { return new Claim(this, identity); } private void Initialize(BinaryReader reader, ClaimsIdentity subject) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } _subject = subject; SerializationMask mask = (SerializationMask)reader.ReadInt32(); int numPropertiesRead = 1; int numPropertiesToRead = reader.ReadInt32(); _value = reader.ReadString(); if ((mask & SerializationMask.NameClaimType) == SerializationMask.NameClaimType) { _type = ClaimsIdentity.DefaultNameClaimType; } else if ((mask & SerializationMask.RoleClaimType) == SerializationMask.RoleClaimType) { _type = ClaimsIdentity.DefaultRoleClaimType; } else { _type = reader.ReadString(); numPropertiesRead++; } if ((mask & SerializationMask.StringType) == SerializationMask.StringType) { _valueType = reader.ReadString(); numPropertiesRead++; } else { _valueType = ClaimValueTypes.String; } if ((mask & SerializationMask.Issuer) == SerializationMask.Issuer) { _issuer = reader.ReadString(); numPropertiesRead++; } else { _issuer = ClaimsIdentity.DefaultIssuer; } if ((mask & SerializationMask.OriginalIssuerEqualsIssuer) == SerializationMask.OriginalIssuerEqualsIssuer) { _originalIssuer = _issuer; } else if ((mask & SerializationMask.OriginalIssuer) == SerializationMask.OriginalIssuer) { _originalIssuer = reader.ReadString(); numPropertiesRead++; } else { _originalIssuer = ClaimsIdentity.DefaultIssuer; } if ((mask & SerializationMask.HasProperties) == SerializationMask.HasProperties) { // TODO - brentsch, maximum # of properties int numProperties = reader.ReadInt32(); for (int i = 0; i < numProperties; i++) { Properties.Add(reader.ReadString(), reader.ReadString()); } } if ((mask & SerializationMask.UserData) == SerializationMask.UserData) { // TODO - brentschmaltz - maximum size ?? int cb = reader.ReadInt32(); _userSerializationData = reader.ReadBytes(cb); numPropertiesRead++; } for (int i = numPropertiesRead; i < numPropertiesToRead; i++) { reader.ReadString(); } } /// <summary> /// Serializes using a <see cref="BinaryWriter"/> /// </summary> /// <param name="writer">the <see cref="BinaryWriter"/> to use for data storage.</param> /// <exception cref="ArgumentNullException">if 'writer' is null.</exception> public virtual void WriteTo(BinaryWriter writer) { WriteTo(writer, null); } /// <summary> /// Serializes using a <see cref="BinaryWriter"/> /// </summary> /// <param name="writer">the <see cref="BinaryWriter"/> to use for data storage.</param> /// <param name="userData">additional data provided by derived type.</param> /// <exception cref="ArgumentNullException">if 'writer' is null.</exception> protected virtual void WriteTo(BinaryWriter writer, byte[] userData) { if (writer == null) { throw new ArgumentNullException(nameof(writer)); } // TODO - brentsch, given that there may be a bunch of NameClaims and or RoleClaims, we should account for this. // This would require coordination between ClaimsIdentity and Claim since the ClaimsIdentity defines these 'types'. For now just use defaults. int numberOfPropertiesWritten = 1; SerializationMask mask = SerializationMask.None; if (string.Equals(_type, ClaimsIdentity.DefaultNameClaimType)) { mask |= SerializationMask.NameClaimType; } else if (string.Equals(_type, ClaimsIdentity.DefaultRoleClaimType)) { mask |= SerializationMask.RoleClaimType; } else { numberOfPropertiesWritten++; } if (!string.Equals(_valueType, ClaimValueTypes.String, StringComparison.Ordinal)) { numberOfPropertiesWritten++; mask |= SerializationMask.StringType; } if (!string.Equals(_issuer, ClaimsIdentity.DefaultIssuer, StringComparison.Ordinal)) { numberOfPropertiesWritten++; mask |= SerializationMask.Issuer; } if (string.Equals(_originalIssuer, _issuer, StringComparison.Ordinal)) { mask |= SerializationMask.OriginalIssuerEqualsIssuer; } else if (!string.Equals(_originalIssuer, ClaimsIdentity.DefaultIssuer, StringComparison.Ordinal)) { numberOfPropertiesWritten++; mask |= SerializationMask.OriginalIssuer; } if (Properties.Count > 0) { numberOfPropertiesWritten++; mask |= SerializationMask.HasProperties; } // TODO - brentschmaltz - maximum size ?? if (userData != null && userData.Length > 0) { numberOfPropertiesWritten++; mask |= SerializationMask.UserData; } writer.Write((Int32)mask); writer.Write((Int32)numberOfPropertiesWritten); writer.Write(_value); if (((mask & SerializationMask.NameClaimType) != SerializationMask.NameClaimType) && ((mask & SerializationMask.RoleClaimType) != SerializationMask.RoleClaimType)) { writer.Write(_type); } if ((mask & SerializationMask.StringType) == SerializationMask.StringType) { writer.Write(_valueType); } if ((mask & SerializationMask.Issuer) == SerializationMask.Issuer) { writer.Write(_issuer); } if ((mask & SerializationMask.OriginalIssuer) == SerializationMask.OriginalIssuer) { writer.Write(_originalIssuer); } if ((mask & SerializationMask.HasProperties) == SerializationMask.HasProperties) { writer.Write(Properties.Count); foreach (var key in Properties.Keys) { writer.Write(key); writer.Write(Properties[key]); } } if ((mask & SerializationMask.UserData) == SerializationMask.UserData) { writer.Write((Int32)userData.Length); writer.Write(userData); } writer.Flush(); } /// <summary> /// Returns a string representation of the <see cref="Claim"/> object. /// </summary> /// <remarks> /// The returned string contains the values of the <see cref="Type"/> and <see cref="Value"/> properties. /// </remarks> /// <returns>The string representation of the <see cref="Claim"/> object.</returns> public override string ToString() { return String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}: {1}", _type, _value); } } }
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using MS.Core; namespace System.Diagnostics.Tracing { public static class __EventSource { public static IObservable<System.Boolean> IsEnabled( this IObservable<System.Diagnostics.Tracing.EventSource> EventSourceValue) { return Observable.Select(EventSourceValue, (EventSourceValueLambda) => EventSourceValueLambda.IsEnabled()); } public static IObservable<System.Boolean> IsEnabled( this IObservable<System.Diagnostics.Tracing.EventSource> EventSourceValue, IObservable<System.Diagnostics.Tracing.EventLevel> level, IObservable<System.Diagnostics.Tracing.EventKeywords> keywords) { return Observable.Zip(EventSourceValue, level, keywords, (EventSourceValueLambda, levelLambda, keywordsLambda) => EventSourceValueLambda.IsEnabled(levelLambda, keywordsLambda)); } public static IObservable<System.Boolean> IsEnabled( this IObservable<System.Diagnostics.Tracing.EventSource> EventSourceValue, IObservable<System.Diagnostics.Tracing.EventLevel> level, IObservable<System.Diagnostics.Tracing.EventKeywords> keywords, IObservable<System.Diagnostics.Tracing.EventChannel> channel) { return Observable.Zip(EventSourceValue, level, keywords, channel, (EventSourceValueLambda, levelLambda, keywordsLambda, channelLambda) => EventSourceValueLambda.IsEnabled(levelLambda, keywordsLambda, channelLambda)); } public static IObservable<System.Guid> GetGuid(IObservable<System.Type> eventSourceType) { return Observable.Select(eventSourceType, (eventSourceTypeLambda) => System.Diagnostics.Tracing.EventSource.GetGuid(eventSourceTypeLambda)); } public static IObservable<System.String> GetName(IObservable<System.Type> eventSourceType) { return Observable.Select(eventSourceType, (eventSourceTypeLambda) => System.Diagnostics.Tracing.EventSource.GetName(eventSourceTypeLambda)); } public static IObservable<System.String> GenerateManifest(IObservable<System.Type> eventSourceType, IObservable<System.String> assemblyPathToIncludeInManifest) { return Observable.Zip(eventSourceType, assemblyPathToIncludeInManifest, (eventSourceTypeLambda, assemblyPathToIncludeInManifestLambda) => System.Diagnostics.Tracing.EventSource.GenerateManifest(eventSourceTypeLambda, assemblyPathToIncludeInManifestLambda)); } public static IObservable<System.String> GenerateManifest(IObservable<System.Type> eventSourceType, IObservable<System.String> assemblyPathToIncludeInManifest, IObservable<System.Diagnostics.Tracing.EventManifestOptions> flags) { return Observable.Zip(eventSourceType, assemblyPathToIncludeInManifest, flags, (eventSourceTypeLambda, assemblyPathToIncludeInManifestLambda, flagsLambda) => System.Diagnostics.Tracing.EventSource.GenerateManifest(eventSourceTypeLambda, assemblyPathToIncludeInManifestLambda, flagsLambda)); } public static IObservable<System.Collections.Generic.IEnumerable<System.Diagnostics.Tracing.EventSource>> GetSources() { return ObservableExt.Factory(() => System.Diagnostics.Tracing.EventSource.GetSources()); } public static IObservable<System.Reactive.Unit> SendCommand( IObservable<System.Diagnostics.Tracing.EventSource> eventSource, IObservable<System.Diagnostics.Tracing.EventCommand> command, IObservable<System.Collections.Generic.IDictionary<System.String, System.String>> commandArguments) { return ObservableExt.ZipExecute(eventSource, command, commandArguments, (eventSourceLambda, commandLambda, commandArgumentsLambda) => System.Diagnostics.Tracing.EventSource.SendCommand(eventSourceLambda, commandLambda, commandArgumentsLambda)); } public static IObservable<System.Reactive.Unit> SetCurrentThreadActivityId(IObservable<System.Guid> activityId) { return Observable.Do(activityId, (activityIdLambda) => System.Diagnostics.Tracing.EventSource.SetCurrentThreadActivityId(activityIdLambda)).ToUnit(); } public static IObservable<System.Guid> SetCurrentThreadActivityId_OutGuid(IObservable<System.Guid> activityId) { return Observable.Select(activityId, (activityIdLambda) => { System.Guid oldActivityThatWillContinueOutput = default(System.Guid); System.Diagnostics.Tracing.EventSource.SetCurrentThreadActivityId(activityIdLambda, out oldActivityThatWillContinueOutput); return oldActivityThatWillContinueOutput; }); } public static IObservable<System.String> GetTrait( this IObservable<System.Diagnostics.Tracing.EventSource> EventSourceValue, IObservable<System.String> key) { return Observable.Zip(EventSourceValue, key, (EventSourceValueLambda, keyLambda) => EventSourceValueLambda.GetTrait(keyLambda)); } public static IObservable<System.String> ToString( this IObservable<System.Diagnostics.Tracing.EventSource> EventSourceValue) { return Observable.Select(EventSourceValue, (EventSourceValueLambda) => EventSourceValueLambda.ToString()); } public static IObservable<System.Reactive.Unit> Dispose( this IObservable<System.Diagnostics.Tracing.EventSource> EventSourceValue) { return Observable.Do(EventSourceValue, (EventSourceValueLambda) => EventSourceValueLambda.Dispose()).ToUnit(); } public static IObservable<System.Reactive.Unit> Write( this IObservable<System.Diagnostics.Tracing.EventSource> EventSourceValue, IObservable<System.String> eventName) { return ObservableExt.ZipExecute(EventSourceValue, eventName, (EventSourceValueLambda, eventNameLambda) => EventSourceValueLambda.Write(eventNameLambda)); } public static IObservable<System.Reactive.Unit> Write( this IObservable<System.Diagnostics.Tracing.EventSource> EventSourceValue, IObservable<System.String> eventName, IObservable<System.Diagnostics.Tracing.EventSourceOptions> options) { return ObservableExt.ZipExecute(EventSourceValue, eventName, options, (EventSourceValueLambda, eventNameLambda, optionsLambda) => EventSourceValueLambda.Write(eventNameLambda, optionsLambda)); } public static IObservable<System.Reactive.Unit> Write<T>( this IObservable<System.Diagnostics.Tracing.EventSource> EventSourceValue, IObservable<System.String> eventName, IObservable<T> data) { return ObservableExt.ZipExecute(EventSourceValue, eventName, data, (EventSourceValueLambda, eventNameLambda, dataLambda) => EventSourceValueLambda.Write(eventNameLambda, dataLambda)); } public static IObservable<System.Reactive.Unit> Write<T>( this IObservable<System.Diagnostics.Tracing.EventSource> EventSourceValue, IObservable<System.String> eventName, IObservable<System.Diagnostics.Tracing.EventSourceOptions> options, IObservable<T> data) { return ObservableExt.ZipExecute(EventSourceValue, eventName, options, data, (EventSourceValueLambda, eventNameLambda, optionsLambda, dataLambda) => EventSourceValueLambda.Write(eventNameLambda, optionsLambda, dataLambda)); } public static IObservable<Tuple<System.Diagnostics.Tracing.EventSourceOptions, T>> Write_RefEventSourceOptionsRefT<T>( this IObservable<System.Diagnostics.Tracing.EventSource> EventSourceValue, IObservable<System.String> eventName, IObservable<System.Diagnostics.Tracing.EventSourceOptions> options, IObservable<T> data) { return Observable.Zip(EventSourceValue, eventName, options, data, (EventSourceValueLambda, eventNameLambda, optionsLambda, dataLambda) => { EventSourceValueLambda.Write(eventNameLambda, ref optionsLambda, ref dataLambda); return Tuple.Create(optionsLambda, dataLambda); }); } public static IObservable<Tuple<System.Diagnostics.Tracing.EventSourceOptions, System.Guid, System.Guid, T>> Write<T>(this IObservable<System.Diagnostics.Tracing.EventSource> EventSourceValue, IObservable<System.String> eventName, IObservable<System.Diagnostics.Tracing.EventSourceOptions> options, IObservable<System.Guid> activityId, IObservable<System.Guid> relatedActivityId, IObservable<T> data) { return Observable.Zip(EventSourceValue, eventName, options, activityId, relatedActivityId, data, (EventSourceValueLambda, eventNameLambda, optionsLambda, activityIdLambda, relatedActivityIdLambda, dataLambda) => { EventSourceValueLambda.Write(eventNameLambda, ref optionsLambda, ref activityIdLambda, ref relatedActivityIdLambda, ref dataLambda); return Tuple.Create(optionsLambda, activityIdLambda, relatedActivityIdLambda, dataLambda); }); } public static IObservable<System.String> get_Name( this IObservable<System.Diagnostics.Tracing.EventSource> EventSourceValue) { return Observable.Select(EventSourceValue, (EventSourceValueLambda) => EventSourceValueLambda.Name); } public static IObservable<System.Guid> get_Guid( this IObservable<System.Diagnostics.Tracing.EventSource> EventSourceValue) { return Observable.Select(EventSourceValue, (EventSourceValueLambda) => EventSourceValueLambda.Guid); } public static IObservable<System.Diagnostics.Tracing.EventSourceSettings> get_Settings( this IObservable<System.Diagnostics.Tracing.EventSource> EventSourceValue) { return Observable.Select(EventSourceValue, (EventSourceValueLambda) => EventSourceValueLambda.Settings); } public static IObservable<System.Guid> get_CurrentThreadActivityId() { return ObservableExt.Factory(() => System.Diagnostics.Tracing.EventSource.CurrentThreadActivityId); } public static IObservable<System.Exception> get_ConstructionException( this IObservable<System.Diagnostics.Tracing.EventSource> EventSourceValue) { return Observable.Select(EventSourceValue, (EventSourceValueLambda) => EventSourceValueLambda.ConstructionException); } } }
#region Apache License // // 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. // #endregion // MONO 1.0 Beta mcs does not like #if !A && !B && !C syntax // .NET Compact Framework 1.0 has no support for Win32 NetMessageBufferSend API #if !NETCF // MONO 1.0 has no support for Win32 NetMessageBufferSend API #if !MONO // SSCLI 1.0 has no support for Win32 NetMessageBufferSend API #if !SSCLI // We don't want framework or platform specific code in the CLI version of log4net #if !CLI_1_0 using System; using System.Globalization; using System.Runtime.InteropServices; using log4net.Util; using log4net.Layout; using log4net.Core; namespace log4net.Appender { /// <summary> /// Logs entries by sending network messages using the /// <see cref="NetMessageBufferSend" /> native function. /// </summary> /// <remarks> /// <para> /// You can send messages only to names that are active /// on the network. If you send the message to a user name, /// that user must be logged on and running the Messenger /// service to receive the message. /// </para> /// <para> /// The receiver will get a top most window displaying the /// messages one at a time, therefore this appender should /// not be used to deliver a high volume of messages. /// </para> /// <para> /// The following table lists some possible uses for this appender : /// </para> /// <para> /// <list type="table"> /// <listheader> /// <term>Action</term> /// <description>Property Value(s)</description> /// </listheader> /// <item> /// <term>Send a message to a user account on the local machine</term> /// <description> /// <para> /// <see cref="NetSendAppender.Server"/> = &lt;name of the local machine&gt; /// </para> /// <para> /// <see cref="NetSendAppender.Recipient"/> = &lt;user name&gt; /// </para> /// </description> /// </item> /// <item> /// <term>Send a message to a user account on a remote machine</term> /// <description> /// <para> /// <see cref="NetSendAppender.Server"/> = &lt;name of the remote machine&gt; /// </para> /// <para> /// <see cref="NetSendAppender.Recipient"/> = &lt;user name&gt; /// </para> /// </description> /// </item> /// <item> /// <term>Send a message to a domain user account</term> /// <description> /// <para> /// <see cref="NetSendAppender.Server"/> = &lt;name of a domain controller | uninitialized&gt; /// </para> /// <para> /// <see cref="NetSendAppender.Recipient"/> = &lt;user name&gt; /// </para> /// </description> /// </item> /// <item> /// <term>Send a message to all the names in a workgroup or domain</term> /// <description> /// <para> /// <see cref="NetSendAppender.Recipient"/> = &lt;workgroup name | domain name&gt;* /// </para> /// </description> /// </item> /// <item> /// <term>Send a message from the local machine to a remote machine</term> /// <description> /// <para> /// <see cref="NetSendAppender.Server"/> = &lt;name of the local machine | uninitialized&gt; /// </para> /// <para> /// <see cref="NetSendAppender.Recipient"/> = &lt;name of the remote machine&gt; /// </para> /// </description> /// </item> /// </list> /// </para> /// <para> /// <b>Note :</b> security restrictions apply for sending /// network messages, see <see cref="NetMessageBufferSend" /> /// for more information. /// </para> /// </remarks> /// <example> /// <para> /// An example configuration section to log information /// using this appender from the local machine, named /// LOCAL_PC, to machine OPERATOR_PC : /// </para> /// <code lang="XML" escaped="true"> /// <appender name="NetSendAppender_Operator" type="log4net.Appender.NetSendAppender"> /// <server value="LOCAL_PC" /> /// <recipient value="OPERATOR_PC" /> /// <layout type="log4net.Layout.PatternLayout" value="%-5p %c [%x] - %m%n" /> /// </appender> /// </code> /// </example> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public class NetSendAppender : AppenderSkeleton { #region Member Variables /// <summary> /// The DNS or NetBIOS name of the server on which the function is to execute. /// </summary> private string m_server; /// <summary> /// The sender of the network message. /// </summary> private string m_sender; /// <summary> /// The message alias to which the message should be sent. /// </summary> private string m_recipient; /// <summary> /// The security context to use for privileged calls /// </summary> private SecurityContext m_securityContext; #endregion #region Constructors /// <summary> /// Initializes the appender. /// </summary> /// <remarks> /// The default constructor initializes all fields to their default values. /// </remarks> public NetSendAppender() { } #endregion #region Properties /// <summary> /// Gets or sets the sender of the message. /// </summary> /// <value> /// The sender of the message. /// </value> /// <remarks> /// If this property is not specified, the message is sent from the local computer. /// </remarks> public string Sender { get { return m_sender; } set { m_sender = value; } } /// <summary> /// Gets or sets the message alias to which the message should be sent. /// </summary> /// <value> /// The recipient of the message. /// </value> /// <remarks> /// This property should always be specified in order to send a message. /// </remarks> public string Recipient { get { return m_recipient; } set { m_recipient = value; } } /// <summary> /// Gets or sets the DNS or NetBIOS name of the remote server on which the function is to execute. /// </summary> /// <value> /// DNS or NetBIOS name of the remote server on which the function is to execute. /// </value> /// <remarks> /// <para> /// For Windows NT 4.0 and earlier, the string should begin with \\. /// </para> /// <para> /// If this property is not specified, the local computer is used. /// </para> /// </remarks> public string Server { get { return m_server; } set { m_server = value; } } /// <summary> /// Gets or sets the <see cref="SecurityContext"/> used to call the NetSend method. /// </summary> /// <value> /// The <see cref="SecurityContext"/> used to call the NetSend method. /// </value> /// <remarks> /// <para> /// Unless a <see cref="SecurityContext"/> specified here for this appender /// the <see cref="SecurityContextProvider.DefaultProvider"/> is queried for the /// security context to use. The default behavior is to use the security context /// of the current thread. /// </para> /// </remarks> public SecurityContext SecurityContext { get { return m_securityContext; } set { m_securityContext = value; } } #endregion #region Implementation of IOptionHandler /// <summary> /// Initialize the appender based on the options set. /// </summary> /// <remarks> /// <para> /// This is part of the <see cref="IOptionHandler"/> delayed object /// activation scheme. The <see cref="ActivateOptions"/> method must /// be called on this object after the configuration properties have /// been set. Until <see cref="ActivateOptions"/> is called this /// object is in an undefined state and must not be used. /// </para> /// <para> /// If any of the configuration properties are modified then /// <see cref="ActivateOptions"/> must be called again. /// </para> /// <para> /// The appender will be ignored if no <see cref="Recipient" /> was specified. /// </para> /// </remarks> /// <exception cref="ArgumentNullException">The required property <see cref="Recipient" /> was not specified.</exception> public override void ActivateOptions() { base.ActivateOptions(); if (this.Recipient == null) { throw new ArgumentNullException("Recipient", "The required property 'Recipient' was not specified."); } if (m_securityContext == null) { m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); } } #endregion #region Override implementation of AppenderSkeleton /// <summary> /// This method is called by the <see cref="AppenderSkeleton.DoAppend(LoggingEvent)"/> method. /// </summary> /// <param name="loggingEvent">The event to log.</param> /// <remarks> /// <para> /// Sends the event using a network message. /// </para> /// </remarks> #if NET_4_0 [System.Security.SecuritySafeCritical] #endif [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)] protected override void Append(LoggingEvent loggingEvent) { NativeError nativeError = null; // Render the event in the callers security context string renderedLoggingEvent = RenderLoggingEvent(loggingEvent); using(m_securityContext.Impersonate(this)) { // Send the message int returnValue = NetMessageBufferSend(this.Server, this.Recipient, this.Sender, renderedLoggingEvent, renderedLoggingEvent.Length * Marshal.SystemDefaultCharSize); // Log the error if the message could not be sent if (returnValue != 0) { // Lookup the native error nativeError = NativeError.GetError(returnValue); } } if (nativeError != null) { // Handle the error over to the ErrorHandler ErrorHandler.Error(nativeError.ToString() + " (Params: Server=" + this.Server + ", Recipient=" + this.Recipient + ", Sender=" + this.Sender + ")"); } } /// <summary> /// This appender requires a <see cref="Layout"/> to be set. /// </summary> /// <value><c>true</c></value> /// <remarks> /// <para> /// This appender requires a <see cref="Layout"/> to be set. /// </para> /// </remarks> override protected bool RequiresLayout { get { return true; } } #endregion #region Stubs For Native Function Calls /// <summary> /// Sends a buffer of information to a registered message alias. /// </summary> /// <param name="serverName">The DNS or NetBIOS name of the server on which the function is to execute.</param> /// <param name="msgName">The message alias to which the message buffer should be sent</param> /// <param name="fromName">The originator of the message.</param> /// <param name="buffer">The message text.</param> /// <param name="bufferSize">The length, in bytes, of the message text.</param> /// <remarks> /// <para> /// The following restrictions apply for sending network messages: /// </para> /// <para> /// <list type="table"> /// <listheader> /// <term>Platform</term> /// <description>Requirements</description> /// </listheader> /// <item> /// <term>Windows NT</term> /// <description> /// <para> /// No special group membership is required to send a network message. /// </para> /// <para> /// Admin, Accounts, Print, or Server Operator group membership is required to /// successfully send a network message on a remote server. /// </para> /// </description> /// </item> /// <item> /// <term>Windows 2000 or later</term> /// <description> /// <para> /// If you send a message on a domain controller that is running Active Directory, /// access is allowed or denied based on the access control list (ACL) for the securable /// object. The default ACL permits only Domain Admins and Account Operators to send a network message. /// </para> /// <para> /// On a member server or workstation, only Administrators and Server Operators can send a network message. /// </para> /// </description> /// </item> /// </list> /// </para> /// <para> /// For more information see <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/netmgmt/netmgmt/security_requirements_for_the_network_management_functions.asp">Security Requirements for the Network Management Functions</a>. /// </para> /// </remarks> /// <returns> /// <para> /// If the function succeeds, the return value is zero. /// </para> /// </returns> [DllImport("netapi32.dll", SetLastError=true)] protected static extern int NetMessageBufferSend( [MarshalAs(UnmanagedType.LPWStr)] string serverName, [MarshalAs(UnmanagedType.LPWStr)] string msgName, [MarshalAs(UnmanagedType.LPWStr)] string fromName, [MarshalAs(UnmanagedType.LPWStr)] string buffer, int bufferSize); #endregion } } #endif // !CLI_1_0 #endif // !SSCLI #endif // !MONO #endif // !NETCF
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.Runtime; using System.ServiceModel; using System.ServiceModel.Security.Tokens; using Microsoft.Xml; using System.ServiceModel.Diagnostics; using System.Diagnostics; namespace System.ServiceModel.Security { public class WSSecurityTokenSerializer : SecurityTokenSerializer { private const int DefaultMaximumKeyDerivationOffset = 64; // bytes private const int DefaultMaximumKeyDerivationLabelLength = 128; // bytes private const int DefaultMaximumKeyDerivationNonceLength = 128; // bytes private static WSSecurityTokenSerializer s_instance; private readonly bool _emitBspRequiredAttributes; private readonly SecurityVersion _securityVersion; private readonly List<SerializerEntries> _serializerEntries; private WSSecureConversation _secureConversation; private readonly List<TokenEntry> _tokenEntries; private int _maximumKeyDerivationOffset; private int _maximumKeyDerivationLabelLength; private int _maximumKeyDerivationNonceLength; private KeyInfoSerializer _keyInfoSerializer; public WSSecurityTokenSerializer() : this(SecurityVersion.WSSecurity11) { } public WSSecurityTokenSerializer(bool emitBspRequiredAttributes) : this(SecurityVersion.WSSecurity11, emitBspRequiredAttributes) { } public WSSecurityTokenSerializer(SecurityVersion securityVersion) : this(securityVersion, false) { } public WSSecurityTokenSerializer(SecurityVersion securityVersion, bool emitBspRequiredAttributes) : this(securityVersion, emitBspRequiredAttributes, null) { } public WSSecurityTokenSerializer(SecurityVersion securityVersion, bool emitBspRequiredAttributes, SamlSerializer samlSerializer) : this(securityVersion, emitBspRequiredAttributes, samlSerializer, null, null) { } public WSSecurityTokenSerializer(SecurityVersion securityVersion, bool emitBspRequiredAttributes, SamlSerializer samlSerializer, SecurityStateEncoder securityStateEncoder, IEnumerable<Type> knownTypes) : this(securityVersion, emitBspRequiredAttributes, samlSerializer, securityStateEncoder, knownTypes, DefaultMaximumKeyDerivationOffset, DefaultMaximumKeyDerivationLabelLength, DefaultMaximumKeyDerivationNonceLength) { } public WSSecurityTokenSerializer(SecurityVersion securityVersion, TrustVersion trustVersion, SecureConversationVersion secureConversationVersion, bool emitBspRequiredAttributes, SamlSerializer samlSerializer, SecurityStateEncoder securityStateEncoder, IEnumerable<Type> knownTypes) : this(securityVersion, trustVersion, secureConversationVersion, emitBspRequiredAttributes, samlSerializer, securityStateEncoder, knownTypes, DefaultMaximumKeyDerivationOffset, DefaultMaximumKeyDerivationLabelLength, DefaultMaximumKeyDerivationNonceLength) { } public WSSecurityTokenSerializer(SecurityVersion securityVersion, bool emitBspRequiredAttributes, SamlSerializer samlSerializer, SecurityStateEncoder securityStateEncoder, IEnumerable<Type> knownTypes, int maximumKeyDerivationOffset, int maximumKeyDerivationLabelLength, int maximumKeyDerivationNonceLength) : this(securityVersion, TrustVersion.Default, SecureConversationVersion.Default, emitBspRequiredAttributes, samlSerializer, securityStateEncoder, knownTypes, maximumKeyDerivationOffset, maximumKeyDerivationLabelLength, maximumKeyDerivationNonceLength) { } public WSSecurityTokenSerializer(SecurityVersion securityVersion, TrustVersion trustVersion, SecureConversationVersion secureConversationVersion, bool emitBspRequiredAttributes, SamlSerializer samlSerializer, SecurityStateEncoder securityStateEncoder, IEnumerable<Type> knownTypes, int maximumKeyDerivationOffset, int maximumKeyDerivationLabelLength, int maximumKeyDerivationNonceLength) { if (securityVersion == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("securityVersion")); if (maximumKeyDerivationOffset < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("maximumKeyDerivationOffset", SRServiceModel.ValueMustBeNonNegative)); } if (maximumKeyDerivationLabelLength < 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("maximumKeyDerivationLabelLength", SRServiceModel.ValueMustBeNonNegative)); } if (maximumKeyDerivationNonceLength <= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("maximumKeyDerivationNonceLength", SRServiceModel.ValueMustBeGreaterThanZero)); } _securityVersion = securityVersion; _emitBspRequiredAttributes = emitBspRequiredAttributes; _maximumKeyDerivationOffset = maximumKeyDerivationOffset; _maximumKeyDerivationNonceLength = maximumKeyDerivationNonceLength; _maximumKeyDerivationLabelLength = maximumKeyDerivationLabelLength; _serializerEntries = new List<SerializerEntries>(); if (secureConversationVersion == SecureConversationVersion.WSSecureConversationFeb2005) { _secureConversation = new WSSecureConversationFeb2005(this, securityStateEncoder, knownTypes, maximumKeyDerivationOffset, maximumKeyDerivationLabelLength, maximumKeyDerivationNonceLength); } else if (secureConversationVersion == SecureConversationVersion.WSSecureConversation13) { _secureConversation = new WSSecureConversationDec2005(this, securityStateEncoder, knownTypes, maximumKeyDerivationOffset, maximumKeyDerivationLabelLength, maximumKeyDerivationNonceLength); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } if (securityVersion == SecurityVersion.WSSecurity10) { _serializerEntries.Add(new WSSecurityJan2004(this, samlSerializer)); } else if (securityVersion == SecurityVersion.WSSecurity11) { _serializerEntries.Add(new WSSecurityXXX2005(this, samlSerializer)); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("securityVersion", SRServiceModel.MessageSecurityVersionOutOfRange)); } _serializerEntries.Add(_secureConversation); IdentityModel.TrustDictionary trustDictionary; if (trustVersion == TrustVersion.WSTrustFeb2005) { _serializerEntries.Add(new WSTrustFeb2005(this)); trustDictionary = new IdentityModel.TrustFeb2005Dictionary(new CollectionDictionary(DXD.TrustDec2005Dictionary.Feb2005DictionaryStrings)); } else if (trustVersion == TrustVersion.WSTrust13) { _serializerEntries.Add(new WSTrustDec2005(this)); trustDictionary = new IdentityModel.TrustDec2005Dictionary(new CollectionDictionary(DXD.TrustDec2005Dictionary.Dec2005DictionaryString)); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } _tokenEntries = new List<TokenEntry>(); for (int i = 0; i < _serializerEntries.Count; ++i) { SerializerEntries serializerEntry = _serializerEntries[i]; serializerEntry.PopulateTokenEntries(_tokenEntries); } IdentityModel.DictionaryManager dictionaryManager = new IdentityModel.DictionaryManager(ServiceModelDictionary.CurrentVersion); dictionaryManager.SecureConversationDec2005Dictionary = new IdentityModel.SecureConversationDec2005Dictionary(new CollectionDictionary(DXD.SecureConversationDec2005Dictionary.SecureConversationDictionaryStrings)); dictionaryManager.SecurityAlgorithmDec2005Dictionary = new IdentityModel.SecurityAlgorithmDec2005Dictionary(new CollectionDictionary(DXD.SecurityAlgorithmDec2005Dictionary.SecurityAlgorithmDictionaryStrings)); _keyInfoSerializer = new WSKeyInfoSerializer(_emitBspRequiredAttributes, dictionaryManager, trustDictionary, this, securityVersion, secureConversationVersion); } public static WSSecurityTokenSerializer DefaultInstance { get { if (s_instance == null) s_instance = new WSSecurityTokenSerializer(); return s_instance; } } public bool EmitBspRequiredAttributes { get { return _emitBspRequiredAttributes; } } public SecurityVersion SecurityVersion { get { return _securityVersion; } } public int MaximumKeyDerivationOffset { get { return _maximumKeyDerivationOffset; } } public int MaximumKeyDerivationLabelLength { get { return _maximumKeyDerivationLabelLength; } } public int MaximumKeyDerivationNonceLength { get { return _maximumKeyDerivationNonceLength; } } internal WSSecureConversation SecureConversation { get { return _secureConversation; } } private bool ShouldWrapException(Exception e) { if (Fx.IsFatal(e)) { return false; } return ((e is ArgumentException) || (e is FormatException) || (e is InvalidOperationException)); } protected override bool CanReadTokenCore(XmlReader reader) { XmlDictionaryReader localReader = XmlDictionaryReader.CreateDictionaryReader(reader); for (int i = 0; i < _tokenEntries.Count; i++) { TokenEntry tokenEntry = _tokenEntries[i]; if (tokenEntry.CanReadTokenCore(localReader)) return true; } return false; } protected override SecurityToken ReadTokenCore(XmlReader reader, SecurityTokenResolver tokenResolver) { XmlDictionaryReader localReader = XmlDictionaryReader.CreateDictionaryReader(reader); for (int i = 0; i < _tokenEntries.Count; i++) { TokenEntry tokenEntry = _tokenEntries[i]; if (tokenEntry.CanReadTokenCore(localReader)) { try { return tokenEntry.ReadTokenCore(localReader, tokenResolver); } #pragma warning disable 56500 // covered by FxCOP catch (Exception e) { if (!ShouldWrapException(e)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SRServiceModel.ErrorDeserializingTokenXml, e)); } } } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(string.Format(SRServiceModel.CannotReadToken, reader.LocalName, reader.NamespaceURI, localReader.GetAttribute(XD.SecurityJan2004Dictionary.ValueType, null)))); } protected override bool CanWriteTokenCore(SecurityToken token) { for (int i = 0; i < _tokenEntries.Count; i++) { TokenEntry tokenEntry = _tokenEntries[i]; if (tokenEntry.SupportsCore(token.GetType())) return true; } return false; } protected override void WriteTokenCore(XmlWriter writer, SecurityToken token) { throw new NotImplementedException(); } protected override bool CanReadKeyIdentifierCore(XmlReader reader) { try { return _keyInfoSerializer.CanReadKeyIdentifier(reader); } catch (System.IdentityModel.SecurityMessageSerializationException ex) { throw FxTrace.Exception.AsError(new MessageSecurityException(ex.Message)); } } protected override SecurityKeyIdentifier ReadKeyIdentifierCore(XmlReader reader) { try { return _keyInfoSerializer.ReadKeyIdentifier(reader); } catch (System.IdentityModel.SecurityMessageSerializationException ex) { throw FxTrace.Exception.AsError(new MessageSecurityException(ex.Message)); } } protected override bool CanWriteKeyIdentifierCore(SecurityKeyIdentifier keyIdentifier) { try { return _keyInfoSerializer.CanWriteKeyIdentifier(keyIdentifier); } catch (System.IdentityModel.SecurityMessageSerializationException ex) { throw FxTrace.Exception.AsError(new MessageSecurityException(ex.Message)); } } protected override void WriteKeyIdentifierCore(XmlWriter writer, SecurityKeyIdentifier keyIdentifier) { try { _keyInfoSerializer.WriteKeyIdentifier(writer, keyIdentifier); } catch (System.IdentityModel.SecurityMessageSerializationException ex) { throw FxTrace.Exception.AsError(new MessageSecurityException(ex.Message)); } } protected override bool CanReadKeyIdentifierClauseCore(XmlReader reader) { try { return _keyInfoSerializer.CanReadKeyIdentifierClause(reader); } catch (System.IdentityModel.SecurityMessageSerializationException ex) { throw FxTrace.Exception.AsError(new MessageSecurityException(ex.Message)); } } protected override SecurityKeyIdentifierClause ReadKeyIdentifierClauseCore(XmlReader reader) { try { return _keyInfoSerializer.ReadKeyIdentifierClause(reader); } catch (System.IdentityModel.SecurityMessageSerializationException ex) { throw FxTrace.Exception.AsError(new MessageSecurityException(ex.Message)); } } protected override bool CanWriteKeyIdentifierClauseCore(SecurityKeyIdentifierClause keyIdentifierClause) { try { return _keyInfoSerializer.CanWriteKeyIdentifierClause(keyIdentifierClause); } catch (System.IdentityModel.SecurityMessageSerializationException ex) { throw FxTrace.Exception.AsError(new MessageSecurityException(ex.Message)); } } protected override void WriteKeyIdentifierClauseCore(XmlWriter writer, SecurityKeyIdentifierClause keyIdentifierClause) { try { _keyInfoSerializer.WriteKeyIdentifierClause(writer, keyIdentifierClause); } catch (System.IdentityModel.SecurityMessageSerializationException ex) { throw FxTrace.Exception.AsError(new MessageSecurityException(ex.Message)); } } internal Type[] GetTokenTypes(string tokenTypeUri) { if (tokenTypeUri != null) { for (int i = 0; i < _tokenEntries.Count; i++) { TokenEntry tokenEntry = _tokenEntries[i]; if (tokenEntry.SupportsTokenTypeUri(tokenTypeUri)) { return tokenEntry.GetTokenTypes(); } } } return null; } protected internal virtual string GetTokenTypeUri(Type tokenType) { if (tokenType != null) { for (int i = 0; i < _tokenEntries.Count; i++) { TokenEntry tokenEntry = _tokenEntries[i]; if (tokenEntry.SupportsCore(tokenType)) { return tokenEntry.TokenTypeUri; } } } return null; } public virtual bool TryCreateKeyIdentifierClauseFromTokenXml(XmlElement element, SecurityTokenReferenceStyle tokenReferenceStyle, out SecurityKeyIdentifierClause securityKeyIdentifierClause) { if (element == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("element"); securityKeyIdentifierClause = null; try { securityKeyIdentifierClause = CreateKeyIdentifierClauseFromTokenXml(element, tokenReferenceStyle); } catch (XmlException e) { return false; } return true; } public virtual SecurityKeyIdentifierClause CreateKeyIdentifierClauseFromTokenXml(XmlElement element, SecurityTokenReferenceStyle tokenReferenceStyle) { if (element == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("element"); for (int i = 0; i < _tokenEntries.Count; i++) { TokenEntry tokenEntry = _tokenEntries[i]; if (tokenEntry.CanReadTokenCore(element)) { try { return tokenEntry.CreateKeyIdentifierClauseFromTokenXmlCore(element, tokenReferenceStyle); } #pragma warning disable 56500 // covered by FxCOP catch (Exception e) { if (!ShouldWrapException(e)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(string.Format(SRServiceModel.ErrorDeserializingKeyIdentifierClauseFromTokenXml), e)); } } } // PreSharp Bug: Parameter 'element' to this public method must be validated: A null-dereference can occur here. #pragma warning disable 56506 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(string.Format(SRServiceModel.CannotReadToken, element.LocalName, element.NamespaceURI, element.GetAttribute(SecurityJan2004Strings.ValueType, null)))); } internal abstract new class TokenEntry { private Type[] _tokenTypes = null; public virtual IAsyncResult BeginReadTokenCore(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver, AsyncCallback callback, object state) { SecurityToken result = this.ReadTokenCore(reader, tokenResolver); return new CompletedAsyncResult<SecurityToken>(result, callback, state); } protected abstract XmlDictionaryString LocalName { get; } protected abstract XmlDictionaryString NamespaceUri { get; } public Type TokenType { get { return GetTokenTypes()[0]; } } public abstract string TokenTypeUri { get; } protected abstract string ValueTypeUri { get; } protected abstract Type[] GetTokenTypesCore(); public Type[] GetTokenTypes() { if (_tokenTypes == null) _tokenTypes = GetTokenTypesCore(); return _tokenTypes; } public bool SupportsCore(Type tokenType) { Type[] tokenTypes = GetTokenTypes(); for (int i = 0; i < tokenTypes.Length; ++i) { if (tokenTypes[i].IsAssignableFrom(tokenType)) return true; } return false; } public virtual bool SupportsTokenTypeUri(string tokenTypeUri) { return (this.TokenTypeUri == tokenTypeUri); } protected static SecurityKeyIdentifierClause CreateDirectReference(XmlElement issuedTokenXml, string idAttributeLocalName, string idAttributeNamespace, Type tokenType) { string id = issuedTokenXml.GetAttribute(idAttributeLocalName, idAttributeNamespace); if (id == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(string.Format(SRServiceModel.RequiredAttributeMissing, idAttributeLocalName, issuedTokenXml.LocalName))); } return new LocalIdKeyIdentifierClause(id, tokenType); } public virtual bool CanReadTokenCore(XmlElement element) { string valueTypeUri = null; if (element.HasAttribute(SecurityJan2004Strings.ValueType, null)) { valueTypeUri = element.GetAttribute(SecurityJan2004Strings.ValueType, null); } return element.LocalName == LocalName.Value && element.NamespaceURI == NamespaceUri.Value && valueTypeUri == this.ValueTypeUri; } public virtual bool CanReadTokenCore(XmlDictionaryReader reader) { return reader.IsStartElement(this.LocalName, this.NamespaceUri) && reader.GetAttribute(XD.SecurityJan2004Dictionary.ValueType, null) == this.ValueTypeUri; } public virtual SecurityToken EndReadTokenCore(IAsyncResult result) { return CompletedAsyncResult<SecurityToken>.End(result); } public abstract SecurityKeyIdentifierClause CreateKeyIdentifierClauseFromTokenXmlCore(XmlElement issuedTokenXml, SecurityTokenReferenceStyle tokenReferenceStyle); public abstract SecurityToken ReadTokenCore(XmlDictionaryReader reader, SecurityTokenResolver tokenResolver); public abstract void WriteTokenCore(XmlDictionaryWriter writer, SecurityToken token); } internal abstract new class SerializerEntries { public virtual void PopulateTokenEntries(IList<TokenEntry> tokenEntries) { } } internal class CollectionDictionary : IXmlDictionary { private List<XmlDictionaryString> _dictionaryStrings; public CollectionDictionary(List<XmlDictionaryString> dictionaryStrings) { if (dictionaryStrings == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("dictionaryStrings")); _dictionaryStrings = dictionaryStrings; } public bool TryLookup(string value, out XmlDictionaryString result) { if (value == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); for (int i = 0; i < _dictionaryStrings.Count; ++i) { if (_dictionaryStrings[i].Value.Equals(value)) { result = _dictionaryStrings[i]; return true; } } result = null; return false; } public bool TryLookup(int key, out XmlDictionaryString result) { for (int i = 0; i < _dictionaryStrings.Count; ++i) { if (_dictionaryStrings[i].Key == key) { result = _dictionaryStrings[i]; return true; } } result = null; return false; } public bool TryLookup(XmlDictionaryString value, out XmlDictionaryString result) { if (value == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); for (int i = 0; i < _dictionaryStrings.Count; ++i) { if ((_dictionaryStrings[i].Key == value.Key) && (_dictionaryStrings[i].Value.Equals(value.Value))) { result = _dictionaryStrings[i]; return true; } } result = null; return false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Data.Common; using System.Runtime.InteropServices; using System.Globalization; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; namespace System.Data.SqlTypes { /// <summary> /// Represents a floating-point number within the range of -1.79E /// +308 through 1.79E +308 to be stored in or retrieved from a database. /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] [XmlSchemaProvider("GetXsdType")] [System.Runtime.CompilerServices.TypeForwardedFrom("System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct SqlDouble : INullable, IComparable, IXmlSerializable { private bool m_fNotNull; // false if null. Do not rename (binary serialization) private double m_value; // Do not rename (binary serialization) // constructor // construct a Null private SqlDouble(bool fNull) { m_fNotNull = false; m_value = 0.0; } public SqlDouble(double value) { if (double.IsInfinity(value) || double.IsNaN(value)) throw new OverflowException(SQLResource.ArithOverflowMessage); else { m_value = value; m_fNotNull = true; } } // INullable public bool IsNull { get { return !m_fNotNull; } } // property: Value public double Value { get { if (m_fNotNull) return m_value; else throw new SqlNullValueException(); } } // Implicit conversion from double to SqlDouble public static implicit operator SqlDouble(double x) { return new SqlDouble(x); } // Explicit conversion from SqlDouble to double. Throw exception if x is Null. public static explicit operator double (SqlDouble x) { return x.Value; } public override string ToString() { return IsNull ? SQLResource.NullString : m_value.ToString((IFormatProvider)null); } public static SqlDouble Parse(string s) { if (s == SQLResource.NullString) return SqlDouble.Null; else return new SqlDouble(double.Parse(s, CultureInfo.InvariantCulture)); } // Unary operators public static SqlDouble operator -(SqlDouble x) { return x.IsNull ? Null : new SqlDouble(-x.m_value); } // Binary operators // Arithmetic operators public static SqlDouble operator +(SqlDouble x, SqlDouble y) { if (x.IsNull || y.IsNull) return Null; double value = x.m_value + y.m_value; if (double.IsInfinity(value)) throw new OverflowException(SQLResource.ArithOverflowMessage); return new SqlDouble(value); } public static SqlDouble operator -(SqlDouble x, SqlDouble y) { if (x.IsNull || y.IsNull) return Null; double value = x.m_value - y.m_value; if (double.IsInfinity(value)) throw new OverflowException(SQLResource.ArithOverflowMessage); return new SqlDouble(value); } public static SqlDouble operator *(SqlDouble x, SqlDouble y) { if (x.IsNull || y.IsNull) return Null; double value = x.m_value * y.m_value; if (double.IsInfinity(value)) throw new OverflowException(SQLResource.ArithOverflowMessage); return new SqlDouble(value); } public static SqlDouble operator /(SqlDouble x, SqlDouble y) { if (x.IsNull || y.IsNull) return Null; if (y.m_value == 0.0) throw new DivideByZeroException(SQLResource.DivideByZeroMessage); double value = x.m_value / y.m_value; if (double.IsInfinity(value)) throw new OverflowException(SQLResource.ArithOverflowMessage); return new SqlDouble(value); } // Implicit conversions // Implicit conversion from SqlBoolean to SqlDouble public static explicit operator SqlDouble(SqlBoolean x) { return x.IsNull ? Null : new SqlDouble(x.ByteValue); } // Implicit conversion from SqlByte to SqlDouble public static implicit operator SqlDouble(SqlByte x) { return x.IsNull ? Null : new SqlDouble(x.Value); } // Implicit conversion from SqlInt16 to SqlDouble public static implicit operator SqlDouble(SqlInt16 x) { return x.IsNull ? Null : new SqlDouble(x.Value); } // Implicit conversion from SqlInt32 to SqlDouble public static implicit operator SqlDouble(SqlInt32 x) { return x.IsNull ? Null : new SqlDouble(x.Value); } // Implicit conversion from SqlInt64 to SqlDouble public static implicit operator SqlDouble(SqlInt64 x) { return x.IsNull ? Null : new SqlDouble(x.Value); } // Implicit conversion from SqlSingle to SqlDouble public static implicit operator SqlDouble(SqlSingle x) { return x.IsNull ? Null : new SqlDouble(x.Value); } // Implicit conversion from SqlMoney to SqlDouble public static implicit operator SqlDouble(SqlMoney x) { return x.IsNull ? Null : new SqlDouble(x.ToDouble()); } // Implicit conversion from SqlDecimal to SqlDouble public static implicit operator SqlDouble(SqlDecimal x) { return x.IsNull ? Null : new SqlDouble(x.ToDouble()); } // Explicit conversions // Explicit conversion from SqlString to SqlDouble // Throws FormatException or OverflowException if necessary. public static explicit operator SqlDouble(SqlString x) { if (x.IsNull) return SqlDouble.Null; return Parse(x.Value); } // Overloading comparison operators public static SqlBoolean operator ==(SqlDouble x, SqlDouble y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x.m_value == y.m_value); } public static SqlBoolean operator !=(SqlDouble x, SqlDouble y) { return !(x == y); } public static SqlBoolean operator <(SqlDouble x, SqlDouble y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x.m_value < y.m_value); } public static SqlBoolean operator >(SqlDouble x, SqlDouble y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x.m_value > y.m_value); } public static SqlBoolean operator <=(SqlDouble x, SqlDouble y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x.m_value <= y.m_value); } public static SqlBoolean operator >=(SqlDouble x, SqlDouble y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x.m_value >= y.m_value); } //-------------------------------------------------- // Alternative methods for overloaded operators //-------------------------------------------------- // Alternative method for operator + public static SqlDouble Add(SqlDouble x, SqlDouble y) { return x + y; } // Alternative method for operator - public static SqlDouble Subtract(SqlDouble x, SqlDouble y) { return x - y; } // Alternative method for operator * public static SqlDouble Multiply(SqlDouble x, SqlDouble y) { return x * y; } // Alternative method for operator / public static SqlDouble Divide(SqlDouble x, SqlDouble y) { return x / y; } // Alternative method for operator == public static SqlBoolean Equals(SqlDouble x, SqlDouble y) { return (x == y); } // Alternative method for operator != public static SqlBoolean NotEquals(SqlDouble x, SqlDouble y) { return (x != y); } // Alternative method for operator < public static SqlBoolean LessThan(SqlDouble x, SqlDouble y) { return (x < y); } // Alternative method for operator > public static SqlBoolean GreaterThan(SqlDouble x, SqlDouble y) { return (x > y); } // Alternative method for operator <= public static SqlBoolean LessThanOrEqual(SqlDouble x, SqlDouble y) { return (x <= y); } // Alternative method for operator >= public static SqlBoolean GreaterThanOrEqual(SqlDouble x, SqlDouble y) { return (x >= y); } // Alternative method for conversions. public SqlBoolean ToSqlBoolean() { return (SqlBoolean)this; } public SqlByte ToSqlByte() { return (SqlByte)this; } public SqlInt16 ToSqlInt16() { return (SqlInt16)this; } public SqlInt32 ToSqlInt32() { return (SqlInt32)this; } public SqlInt64 ToSqlInt64() { return (SqlInt64)this; } public SqlMoney ToSqlMoney() { return (SqlMoney)this; } public SqlDecimal ToSqlDecimal() { return (SqlDecimal)this; } public SqlSingle ToSqlSingle() { return (SqlSingle)this; } public SqlString ToSqlString() { return (SqlString)this; } // IComparable // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this < object, zero if this = object, // or a value greater than zero if this > object. // null is considered to be less than any instance. // If object is not of same type, this method throws an ArgumentException. public int CompareTo(object value) { if (value is SqlDouble) { SqlDouble i = (SqlDouble)value; return CompareTo(i); } throw ADP.WrongType(value.GetType(), typeof(SqlDouble)); } public int CompareTo(SqlDouble value) { // If both Null, consider them equal. // Otherwise, Null is less than anything. if (IsNull) return value.IsNull ? 0 : -1; else if (value.IsNull) return 1; if (this < value) return -1; if (this > value) return 1; return 0; } // Compares this instance with a specified object public override bool Equals(object value) { if (!(value is SqlDouble)) { return false; } SqlDouble i = (SqlDouble)value; if (i.IsNull || IsNull) return (i.IsNull && IsNull); else return (this == i).Value; } // For hashing purpose public override int GetHashCode() { return IsNull ? 0 : Value.GetHashCode(); } XmlSchema IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader reader) { string isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { // Read the next value. reader.ReadElementString(); m_fNotNull = false; } else { m_value = XmlConvert.ToDouble(reader.ReadElementString()); m_fNotNull = true; } } void IXmlSerializable.WriteXml(XmlWriter writer) { if (IsNull) { writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true"); } else { writer.WriteString(XmlConvert.ToString(m_value)); } } public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet) { return new XmlQualifiedName("double", XmlSchema.Namespace); } public static readonly SqlDouble Null = new SqlDouble(true); public static readonly SqlDouble Zero = new SqlDouble(0.0); public static readonly SqlDouble MinValue = new SqlDouble(double.MinValue); public static readonly SqlDouble MaxValue = new SqlDouble(double.MaxValue); } // SqlDouble } // namespace System.Data.SqlTypes
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // A barrier allows multiple tasks to cooperatively work on some algorithm in parallel. // A group of tasks cooperate by moving through a series of phases, where each in the group signals it has arrived at // the barrier in a given phase and implicitly waits for all others to arrive. // The same barrier can be used for multiple phases. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Diagnostics; using System.Security; namespace System.Threading { /// <summary> /// The exception that is thrown when the post-phase action of a <see cref="Barrier"/> fails. /// </summary> public class BarrierPostPhaseException : Exception { /// <summary> /// Initializes a new instance of the <see cref="BarrierPostPhaseException"/> class. /// </summary> public BarrierPostPhaseException() : this((string)null) { } /// <summary> /// Initializes a new instance of the <see cref="BarrierPostPhaseException"/> class with the specified inner exception. /// </summary> /// <param name="innerException">The exception that is the cause of the current exception.</param> public BarrierPostPhaseException(Exception innerException) : this(null, innerException) { } /// <summary> /// Initializes a new instance of the <see cref="BarrierPostPhaseException"/> class with a specified error message. /// </summary> /// <param name="message">A string that describes the exception.</param> public BarrierPostPhaseException(string message) : this(message, null) { } /// <summary> /// Initializes a new instance of the <see cref="BarrierPostPhaseException"/> class with a specified error message and inner exception. /// </summary> /// <param name="message">A string that describes the exception.</param> /// <param name="innerException">The exception that is the cause of the current exception.</param> public BarrierPostPhaseException(string message, Exception innerException) : base(message == null ? SR.BarrierPostPhaseException : message, innerException) { } } /// <summary> /// Enables multiple tasks to cooperatively work on an algorithm in parallel through multiple phases. /// </summary> /// <remarks> /// <para> /// A group of tasks cooperate by moving through a series of phases, where each in the group signals it /// has arrived at the <see cref="Barrier"/> in a given phase and implicitly waits for all others to /// arrive. The same <see cref="Barrier"/> can be used for multiple phases. /// </para> /// <para> /// All public and protected members of <see cref="Barrier"/> are thread-safe and may be used /// concurrently from multiple threads, with the exception of Dispose, which /// must only be used when all other operations on the <see cref="Barrier"/> have /// completed. /// </para> /// </remarks> [DebuggerDisplay("Participant Count={ParticipantCount},Participants Remaining={ParticipantsRemaining}")] public class Barrier : IDisposable { //This variable holds the basic barrier variables: // 1- The current particiants count // 2- The total participants count // 3- The sense flag (true if the cuurrent phase is even, false otherwise) // The first 15 bits are for the total count which means the maximum participants for the barrier is about 32K // The 16th bit is dummy // The next 15th bit for the current // And the last highest bit is for the sense private volatile int _currentTotalCount; // Bitmask to extract the current count private const int CURRENT_MASK = 0x7FFF0000; // Bitmask to extract the total count private const int TOTAL_MASK = 0x00007FFF; // Bitmask to extratc the sense flag private const int SENSE_MASK = unchecked((int)0x80000000); // The maximum participants the barrier can operate = 32767 ( 2 power 15 - 1 ) private const int MAX_PARTICIPANTS = TOTAL_MASK; // The current barrier phase // We don't need to worry about overflow, the max value is 2^63-1; If it starts from 0 at a // rate of 4 billion increments per second, it will takes about 64 years to overflow. private long _currentPhase; // dispose flag private bool _disposed; // Odd phases event private ManualResetEventSlim _oddEvent; // Even phases event private ManualResetEventSlim _evenEvent; // The execution context of the creator thread private ExecutionContext _ownerThreadContext; // The EC callback that invokes the post phase action [SecurityCritical] private static ContextCallback s_invokePostPhaseAction; // Post phase action after each phase private Action<Barrier> _postPhaseAction; // In case the post phase action throws an exception, wraps it in BarrierPostPhaseException private Exception _exception; // This is the ManagedThreadID of the postPhaseAction caller thread, this is used to determine if the SignalAndWait, Dispose or Add/RemoveParticipant caller thread is // the same thread as the postPhaseAction thread which means this method was called from the postPhaseAction which is illegal. // This value is captured before calling the action and reset back to zero after it. private int _actionCallerID; #region Properties /// <summary> /// Gets the number of participants in the barrier that haven?t yet signaled /// in the current phase. /// </summary> /// <remarks> /// This could be 0 during a post-phase action delegate execution or if the /// ParticipantCount is 0. /// </remarks> public int ParticipantsRemaining { get { int currentTotal = _currentTotalCount; int total = (int)(currentTotal & TOTAL_MASK); int current = (int)((currentTotal & CURRENT_MASK) >> 16); return total - current; } } /// <summary> /// Gets the total number of participants in the barrier. /// </summary> public int ParticipantCount { get { return (int)(_currentTotalCount & TOTAL_MASK); } } /// <summary> /// Gets the number of the barrier's current phase. /// </summary> public long CurrentPhaseNumber { // use the new Volatile.Read/Write method because it is cheaper than Interlocked.Read on AMD64 architecture get { return Volatile.Read(ref _currentPhase); } internal set { Volatile.Write(ref _currentPhase, value); } } #endregion /// <summary> /// Initializes a new instance of the <see cref="Barrier"/> class. /// </summary> /// <param name="participantCount">The number of participating threads.</param> /// <exception cref="ArgumentOutOfRangeException"> <paramref name="participantCount"/> is less than 0 /// or greater than <see cref="T:System.Int16.MaxValue"/>.</exception> public Barrier(int participantCount) : this(participantCount, null) { } /// <summary> /// Initializes a new instance of the <see cref="Barrier"/> class. /// </summary> /// <param name="participantCount">The number of participating threads.</param> /// <param name="postPhaseAction">The <see cref="T:System.Action`1"/> to be executed after each /// phase.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"> <paramref name="participantCount"/> is less than 0 /// or greater than <see cref="T:System.Int32.MaxValue"/>.</exception> /// <remarks> /// The <paramref name="postPhaseAction"/> delegate will be executed after /// all participants have arrived at the barrier in one phase. The participants /// will not be released to the next phase until the postPhaseAction delegate /// has completed execution. /// </remarks> public Barrier(int participantCount, Action<Barrier> postPhaseAction) { // the count must be non negative value if (participantCount < 0 || participantCount > MAX_PARTICIPANTS) { throw new ArgumentOutOfRangeException(nameof(participantCount), participantCount, SR.Barrier_ctor_ArgumentOutOfRange); } _currentTotalCount = (int)participantCount; _postPhaseAction = postPhaseAction; //Lazily initialize the events _oddEvent = new ManualResetEventSlim(true); _evenEvent = new ManualResetEventSlim(false); // Capture the context if the post phase action is not null if (postPhaseAction != null) { _ownerThreadContext = ExecutionContext.Capture(); } _actionCallerID = 0; } /// <summary> /// Extract the three variables current, total and sense from a given big variable /// </summary> /// <param name="currentTotal">The integer variable that contains the other three variables</param> /// <param name="current">The current cparticipant count</param> /// <param name="total">The total participants count</param> /// <param name="sense">The sense flag</param> private void GetCurrentTotal(int currentTotal, out int current, out int total, out bool sense) { total = (int)(currentTotal & TOTAL_MASK); current = (int)((currentTotal & CURRENT_MASK) >> 16); sense = (currentTotal & SENSE_MASK) == 0 ? true : false; } /// <summary> /// Write the three variables current. total and the sense to the m_currentTotal /// </summary> /// <param name="currentTotal">The old current total to compare</param> /// <param name="current">The current cparticipant count</param> /// <param name="total">The total participants count</param> /// <param name="sense">The sense flag</param> /// <returns>True if the CAS succeeded, false otherwise</returns> private bool SetCurrentTotal(int currentTotal, int current, int total, bool sense) { int newCurrentTotal = (current << 16) | total; if (!sense) { newCurrentTotal |= SENSE_MASK; } #pragma warning disable 0420 return Interlocked.CompareExchange(ref _currentTotalCount, newCurrentTotal, currentTotal) == currentTotal; #pragma warning restore 0420 } /// <summary> /// Notifies the <see cref="Barrier"/> that there will be an additional participant. /// </summary> /// <returns>The phase number of the barrier in which the new participants will first /// participate.</returns> /// <exception cref="T:System.InvalidOperationException"> /// Adding a participant would cause the barrier's participant count to /// exceed <see cref="T:System.Int16.MaxValue"/>. /// </exception> /// <exception cref="T:System.InvalidOperationException"> /// The method was invoked from within a post-phase action. /// </exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public long AddParticipant() { try { return AddParticipants(1); } catch (ArgumentOutOfRangeException) { throw new InvalidOperationException(SR.Barrier_AddParticipants_Overflow_ArgumentOutOfRange); } } /// <summary> /// Notifies the <see cref="Barrier"/> that there will be additional participants. /// </summary> /// <param name="participantCount">The number of additional participants to add to the /// barrier.</param> /// <returns>The phase number of the barrier in which the new participants will first /// participate.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="participantCount"/> is less than /// 0.</exception> /// <exception cref="T:System.ArgumentOutOfRangeException">Adding <paramref name="participantCount"/> participants would cause the /// barrier's participant count to exceed <see cref="T:System.Int16.MaxValue"/>.</exception> /// <exception cref="T:System.InvalidOperationException"> /// The method was invoked from within a post-phase action. /// </exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public long AddParticipants(int participantCount) { // check dispose ThrowIfDisposed(); if (participantCount < 1) { throw new ArgumentOutOfRangeException(nameof(participantCount), participantCount, SR.Barrier_AddParticipants_NonPositive_ArgumentOutOfRange); } else if (participantCount > MAX_PARTICIPANTS) //overflow { throw new ArgumentOutOfRangeException(nameof(participantCount), SR.Barrier_AddParticipants_Overflow_ArgumentOutOfRange); } // in case of this is called from the PHA if (_actionCallerID != 0 && Environment.CurrentManagedThreadId == _actionCallerID) { throw new InvalidOperationException(SR.Barrier_InvalidOperation_CalledFromPHA); } SpinWait spinner = new SpinWait(); long newPhase = 0; while (true) { int currentTotal = _currentTotalCount; int total; int current; bool sense; GetCurrentTotal(currentTotal, out current, out total, out sense); if (participantCount + total > MAX_PARTICIPANTS) //overflow { throw new ArgumentOutOfRangeException(nameof(participantCount), SR.Barrier_AddParticipants_Overflow_ArgumentOutOfRange); } if (SetCurrentTotal(currentTotal, current, total + participantCount, sense)) { // Calculating the first phase for that participant, if the current phase already finished return the nextphase else return the current phase // To know that the current phase is the sense doesn't match the // phase odd even, so that means it didn't yet change the phase count, so currentPhase +1 is returned, otherwise currentPhase is returned long currPhase = CurrentPhaseNumber; newPhase = (sense != (currPhase % 2 == 0)) ? currPhase + 1 : currPhase; // If this participant is going to join the next phase, which means the postPhaseAction is being running, this participants must wait until this done // and its event is reset. // Without that, if the postPhaseAction takes long time, this means the event ehich the current participant is goint to wait on is still set // (FinishPPhase didn't reset it yet) so it should wait until it reset if (newPhase != currPhase) { // Wait on the opposite event if (sense) { _oddEvent.Wait(); } else { _evenEvent.Wait(); } } //This else to fix the racing where the current phase has been finished, m_currentPhase has been updated but the events have not been set/reset yet // otherwise when this participant calls SignalAndWait it will wait on a set event however all other participants have not arrived yet. else { if (sense && _evenEvent.IsSet) _evenEvent.Reset(); else if (!sense && _oddEvent.IsSet) _oddEvent.Reset(); } break; } spinner.SpinOnce(); } return newPhase; } /// <summary> /// Notifies the <see cref="Barrier"/> that there will be one less participant. /// </summary> /// <exception cref="T:System.InvalidOperationException">The barrier already has 0 /// participants.</exception> /// <exception cref="T:System.InvalidOperationException"> /// The method was invoked from within a post-phase action. /// </exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public void RemoveParticipant() { RemoveParticipants(1); } /// <summary> /// Notifies the <see cref="Barrier"/> that there will be fewer participants. /// </summary> /// <param name="participantCount">The number of additional participants to remove from the barrier.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="participantCount"/> is less than /// 0.</exception> /// <exception cref="T:System.InvalidOperationException">The barrier already has 0 participants.</exception> /// <exception cref="T:System.InvalidOperationException"> /// The method was invoked from within a post-phase action. /// </exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public void RemoveParticipants(int participantCount) { // check dispose ThrowIfDisposed(); // Validate input if (participantCount < 1) { throw new ArgumentOutOfRangeException(nameof(participantCount), participantCount, SR.Barrier_RemoveParticipants_NonPositive_ArgumentOutOfRange); } // in case of this is called from the PHA if (_actionCallerID != 0 && Environment.CurrentManagedThreadId == _actionCallerID) { throw new InvalidOperationException(SR.Barrier_InvalidOperation_CalledFromPHA); } SpinWait spinner = new SpinWait(); while (true) { int currentTotal = _currentTotalCount; int total; int current; bool sense; GetCurrentTotal(currentTotal, out current, out total, out sense); if (total < participantCount) { throw new ArgumentOutOfRangeException(nameof(participantCount), SR.Barrier_RemoveParticipants_ArgumentOutOfRange); } if (total - participantCount < current) { throw new InvalidOperationException(SR.Barrier_RemoveParticipants_InvalidOperation); } // If the remaining participats = current participants, then finish the current phase int remaingParticipants = total - participantCount; if (remaingParticipants > 0 && current == remaingParticipants) { if (SetCurrentTotal(currentTotal, 0, total - participantCount, !sense)) { FinishPhase(sense); break; } } else { if (SetCurrentTotal(currentTotal, current, total - participantCount, sense)) { break; } } spinner.SpinOnce(); } } /// <summary> /// Signals that a participant has reached the <see cref="Barrier"/> and waits for all other /// participants to reach the barrier as well. /// </summary> /// <exception cref="T:System.InvalidOperationException"> /// The method was invoked from within a post-phase action, the barrier currently has 0 participants, /// or the barrier is being used by more threads than are registered as participants. /// </exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public void SignalAndWait() { SignalAndWait(new CancellationToken()); } /// <summary> /// Signals that a participant has reached the <see cref="Barrier"/> and waits for all other /// participants to reach the barrier, while observing a <see /// cref="T:System.Threading.CancellationToken"/>. /// </summary> /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to /// observe.</param> /// <exception cref="T:System.InvalidOperationException"> /// The method was invoked from within a post-phase action, the barrier currently has 0 participants, /// or the barrier is being used by more threads than are registered as participants. /// </exception> /// <exception cref="T:System.OperationCanceledException"><paramref name="cancellationToken"/> has been /// canceled.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public void SignalAndWait(CancellationToken cancellationToken) { #if DEBUG bool result = #endif SignalAndWait(Timeout.Infinite, cancellationToken); #if DEBUG Debug.Assert(result); #endif } /// <summary> /// Signals that a participant has reached the <see cref="Barrier"/> and waits for all other /// participants to reach the barrier as well, using a /// <see cref="T:System.TimeSpan"/> to measure the time interval. /// </summary> /// <param name="timeout">A <see cref="T:System.TimeSpan"/> that represents the number of /// milliseconds to wait, or a <see cref="T:System.TimeSpan"/> that represents -1 milliseconds to /// wait indefinitely.</param> /// <returns>true if all other participants reached the barrier; otherwise, false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/>is a negative number /// other than -1 milliseconds, which represents an infinite time-out, or it is greater than /// <see cref="T:System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.InvalidOperationException"> /// The method was invoked from within a post-phase action, the barrier currently has 0 participants, /// or the barrier is being used by more threads than are registered as participants. /// </exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public Boolean SignalAndWait(TimeSpan timeout) { return SignalAndWait(timeout, new CancellationToken()); } /// <summary> /// Signals that a participant has reached the <see cref="Barrier"/> and waits for all other /// participants to reach the barrier as well, using a /// <see cref="T:System.TimeSpan"/> to measure the time interval, while observing a <see /// cref="T:System.Threading.CancellationToken"/>. /// </summary> /// <param name="timeout">A <see cref="T:System.TimeSpan"/> that represents the number of /// milliseconds to wait, or a <see cref="T:System.TimeSpan"/> that represents -1 milliseconds to /// wait indefinitely.</param> /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to /// observe.</param> /// <returns>true if all other participants reached the barrier; otherwise, false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/>is a negative number /// other than -1 milliseconds, which represents an infinite time-out.</exception> /// <exception cref="T:System.InvalidOperationException"> /// The method was invoked from within a post-phase action, the barrier currently has 0 participants, /// or the barrier is being used by more threads than are registered as participants. /// </exception> /// <exception cref="T:System.OperationCanceledException"><paramref name="cancellationToken"/> has been /// canceled.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public Boolean SignalAndWait(TimeSpan timeout, CancellationToken cancellationToken) { Int64 totalMilliseconds = (Int64)timeout.TotalMilliseconds; if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new System.ArgumentOutOfRangeException(nameof(timeout), timeout, SR.Barrier_SignalAndWait_ArgumentOutOfRange); } return SignalAndWait((int)timeout.TotalMilliseconds, cancellationToken); } /// <summary> /// Signals that a participant has reached the <see cref="Barrier"/> and waits for all other /// participants to reach the barrier as well, using a /// 32-bit signed integer to measure the time interval. /// </summary> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see /// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param> /// <returns>true if all other participants reached the barrier; otherwise, false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a /// negative number other than -1, which represents an infinite time-out.</exception> /// <exception cref="T:System.InvalidOperationException"> /// The method was invoked from within a post-phase action, the barrier currently has 0 participants, /// or the barrier is being used by more threads than are registered as participants. /// </exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public bool SignalAndWait(int millisecondsTimeout) { return SignalAndWait(millisecondsTimeout, new CancellationToken()); } /// <summary> /// Signals that a participant has reached the barrier and waits for all other participants to reach /// the barrier as well, using a /// 32-bit signed integer to measure the time interval, while observing a <see /// cref="T:System.Threading.CancellationToken"/>. /// </summary> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see /// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param> /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to /// observe.</param> /// <returns>true if all other participants reached the barrier; otherwise, false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a /// negative number other than -1, which represents an infinite time-out.</exception> /// <exception cref="T:System.InvalidOperationException"> /// The method was invoked from within a post-phase action, the barrier currently has 0 participants, /// or the barrier is being used by more threads than are registered as participants. /// </exception> /// <exception cref="T:System.OperationCanceledException"><paramref name="cancellationToken"/> has been /// canceled.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public bool SignalAndWait(int millisecondsTimeout, CancellationToken cancellationToken) { ThrowIfDisposed(); cancellationToken.ThrowIfCancellationRequested(); if (millisecondsTimeout < -1) { throw new System.ArgumentOutOfRangeException(nameof(millisecondsTimeout), millisecondsTimeout, SR.Barrier_SignalAndWait_ArgumentOutOfRange); } // in case of this is called from the PHA if (_actionCallerID != 0 && Environment.CurrentManagedThreadId == _actionCallerID) { throw new InvalidOperationException(SR.Barrier_InvalidOperation_CalledFromPHA); } // local variables to extract the basic barrier variable and update them // The are declared here instead of inside the loop body because the will be used outside the loop bool sense; // The sense of the barrier *before* the phase associated with this SignalAndWait call completes int total; int current; int currentTotal; long phase; SpinWait spinner = new SpinWait(); while (true) { currentTotal = _currentTotalCount; GetCurrentTotal(currentTotal, out current, out total, out sense); phase = CurrentPhaseNumber; // throw if zero participants if (total == 0) { throw new InvalidOperationException(SR.Barrier_SignalAndWait_InvalidOperation_ZeroTotal); } // Try to detect if the number of threads for this phase exceeded the total number of participants or not // This can be detected if the current is zero which means all participants for that phase has arrived and the phase number is not changed yet if (current == 0 && sense != (CurrentPhaseNumber % 2 == 0)) { throw new InvalidOperationException(SR.Barrier_SignalAndWait_InvalidOperation_ThreadsExceeded); } //This is the last thread, finish the phase if (current + 1 == total) { if (SetCurrentTotal(currentTotal, 0, total, !sense)) { if (CdsSyncEtwBCLProvider.Log.IsEnabled()) { CdsSyncEtwBCLProvider.Log.Barrier_PhaseFinished(sense, CurrentPhaseNumber); } FinishPhase(sense); return true; } } else if (SetCurrentTotal(currentTotal, current + 1, total, sense)) { break; } spinner.SpinOnce(); } // ** Perform the real wait ** // select the correct event to wait on, based on the current sense. ManualResetEventSlim eventToWaitOn = (sense) ? _evenEvent : _oddEvent; bool waitWasCanceled = false; bool waitResult = false; try { waitResult = DiscontinuousWait(eventToWaitOn, millisecondsTimeout, cancellationToken, phase); } catch (OperationCanceledException) { waitWasCanceled = true; } catch (ObjectDisposedException)// in case a race happen where one of the thread returned from SignalAndWait and the current thread calls Wait on a disposed event { // make sure the current phase for this thread is already finished, otherwise propagate the exception if (phase < CurrentPhaseNumber) waitResult = true; else throw; } if (!waitResult) { //reset the spinLock to prepare it for the next loop spinner.Reset(); //If the wait timeout expired and all other thread didn't reach the barrier yet, update the current count back while (true) { bool newSense; currentTotal = _currentTotalCount; GetCurrentTotal(currentTotal, out current, out total, out newSense); // If the timeout expired and the phase has just finished, return true and this is considered as succeeded SignalAndWait //otherwise the timeout expired and the current phase has not been finished yet, return false //The phase is finished if the phase member variable is changed (incremented) or the sense has been changed // we have to use the statements in the comparison below for two cases: // 1- The sense is changed but the last thread didn't update the phase yet // 2- The phase is already incremented but the sense flipped twice due to the termination of the next phase if (phase < CurrentPhaseNumber || sense != newSense) { // The current phase has been finished, but we shouldn't return before the events are set/reset otherwise this thread could start // next phase and the appropriate event has not reset yet which could make it return immediately from the next phase SignalAndWait // before waiting other threads WaitCurrentPhase(eventToWaitOn, phase); Debug.Assert(phase < CurrentPhaseNumber); break; } //The phase has not been finished yet, try to update the current count. if (SetCurrentTotal(currentTotal, current - 1, total, sense)) { //if here, then the attempt to backout was successful. //throw (a fresh) oce if cancellation woke the wait //or return false if it was the timeout that woke the wait. // if (waitWasCanceled) throw new OperationCanceledException(SR.Common_OperationCanceled, cancellationToken); else return false; } spinner.SpinOnce(); } } if (_exception != null) throw new BarrierPostPhaseException(_exception); return true; } /// <summary> /// Finish the phase by invoking the post phase action, and setting the event, this must be called by the /// last arrival thread /// </summary> /// <param name="observedSense">The current phase sense</param> [SecuritySafeCritical] private void FinishPhase(bool observedSense) { // Execute the PHA in try/finally block to reset the variables back in case of it threw an exception if (_postPhaseAction != null) { try { // Capture the caller thread ID to check if the Add/RemoveParticipant(s) is called from the PHA _actionCallerID = Environment.CurrentManagedThreadId; if (_ownerThreadContext != null) { var currentContext = _ownerThreadContext; ContextCallback handler = s_invokePostPhaseAction; if (handler == null) { s_invokePostPhaseAction = handler = InvokePostPhaseAction; } ExecutionContext.Run(_ownerThreadContext, handler, this); } else { _postPhaseAction(this); } _exception = null; // reset the exception if it was set previously } catch (Exception ex) { _exception = ex; } finally { _actionCallerID = 0; SetResetEvents(observedSense); if (_exception != null) throw new BarrierPostPhaseException(_exception); } } else { SetResetEvents(observedSense); } } /// <summary> /// Helper method to call the post phase action /// </summary> /// <param name="obj"></param> [SecurityCritical] private static void InvokePostPhaseAction(object obj) { var thisBarrier = (Barrier)obj; thisBarrier._postPhaseAction(thisBarrier); } /// <summary> /// Sets the current phase event and reset the next phase event /// </summary> /// <param name="observedSense">The current phase sense</param> private void SetResetEvents(bool observedSense) { // Increment the phase count using Volatile class because m_currentPhase is 64 bit long type, that could cause torn write on 32 bit machines CurrentPhaseNumber = CurrentPhaseNumber + 1; if (observedSense) { _oddEvent.Reset(); _evenEvent.Set(); } else { _evenEvent.Reset(); _oddEvent.Set(); } } /// <summary> /// Wait until the current phase finishes completely by spinning until either the event is set, /// or the phase count is incremented more than one time /// </summary> /// <param name="currentPhaseEvent">The current phase event</param> /// <param name="observedPhase">The current phase for that thread</param> private void WaitCurrentPhase(ManualResetEventSlim currentPhaseEvent, long observedPhase) { //spin until either of these two conditions succeeds //1- The event is set //2- the phase count is incremented more than one time, this means the next phase is finished as well, //but the event will be reset again, so we check the phase count instead SpinWait spinner = new SpinWait(); while (!currentPhaseEvent.IsSet && CurrentPhaseNumber - observedPhase <= 1) { spinner.SpinOnce(); } } /// <summary> /// The reason of discontinuous waiting instead of direct waiting on the event is to avoid the race where the sense is /// changed twice because the next phase is finished (due to either RemoveParticipant is called or another thread joined /// the next phase instead of the current thread) so the current thread will be stuck on the event because it is reset back /// The maxwait and the shift numbers are arbitrarily choosen, there were no references picking them /// </summary> /// <param name="currentPhaseEvent">The current phase event</param> /// <param name="totalTimeout">wait timeout in milliseconds</param> /// <param name="token">cancellation token passed to SignalAndWait</param> /// <param name="observedPhase">The current phase number for this thread</param> /// <returns>True if the event is set or the phasenumber changed, false if the timeout expired</returns> private bool DiscontinuousWait(ManualResetEventSlim currentPhaseEvent, int totalTimeout, CancellationToken token, long observedPhase) { int maxWait = 100; // 100 ms int waitTimeCeiling = 10000; // 10 seconds while (observedPhase == CurrentPhaseNumber) { // the next wait time, the min of the maxWait and the totalTimeout int waitTime = totalTimeout == Timeout.Infinite ? maxWait : Math.Min(maxWait, totalTimeout); if (currentPhaseEvent.Wait(waitTime, token)) return true; //update the total wait time if (totalTimeout != Timeout.Infinite) { totalTimeout -= waitTime; if (totalTimeout <= 0) return false; } //if the maxwait exceeded 10 seconds then we will stop increasing the maxWait time and keep it 10 seconds, otherwise keep doubling it maxWait = maxWait >= waitTimeCeiling ? waitTimeCeiling : Math.Min(maxWait << 1, waitTimeCeiling); } //if we exited the loop because the observed phase doesn't match the current phase, then we have to spin to mske sure //the event is set or the next phase is finished WaitCurrentPhase(currentPhaseEvent, observedPhase); return true; } /// <summary> /// Releases all resources used by the current instance of <see cref="Barrier"/>. /// </summary> /// <exception cref="T:System.InvalidOperationException"> /// The method was invoked from within a post-phase action. /// </exception> /// <remarks> /// Unlike most of the members of <see cref="Barrier"/>, Dispose is not thread-safe and may not be /// used concurrently with other members of this instance. /// </remarks> public void Dispose() { // in case of this is called from the PHA if (_actionCallerID != 0 && Environment.CurrentManagedThreadId == _actionCallerID) { throw new InvalidOperationException(SR.Barrier_InvalidOperation_CalledFromPHA); } Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// When overridden in a derived class, releases the unmanaged resources used by the /// <see cref="Barrier"/>, and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release /// only unmanaged resources.</param> /// <remarks> /// Unlike most of the members of <see cref="Barrier"/>, Dispose is not thread-safe and may not be /// used concurrently with other members of this instance. /// </remarks> protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { _oddEvent.Dispose(); _evenEvent.Dispose(); } _disposed = true; } } /// <summary> /// Throw ObjectDisposedException if the barrier is disposed /// </summary> private void ThrowIfDisposed() { if (_disposed) { throw new ObjectDisposedException("Barrier", SR.Barrier_Dispose); } } } }
using System; using System.Collections.Generic; using System.Composition.Hosting; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Microsoft.AspNet.Http; using Microsoft.CodeAnalysis; using Microsoft.Framework.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OmniSharp.Mef; using OmniSharp.Middleware.Endpoint.Exports; using OmniSharp.Models; using OmniSharp.Plugins; namespace OmniSharp.Middleware.Endpoint { class LanguageModel { public string Language { get; set; } public string FileName { get; set; } } abstract class EndpointHandler { public abstract Task<object> Handle(HttpContext context); public static EndpointHandler Create<TRequest, TResponse>(IPredicateHandler languagePredicateHandler, CompositionHost host, ILogger logger, EndpointDescriptor item, IEnumerable<Lazy<IRequestHandler, OmniSharpLanguage>> handlers, Lazy<EndpointHandler<UpdateBufferRequest, object>> updateBufferHandler, IEnumerable<Plugin> plugins) { return new EndpointHandler<TRequest, TResponse>(languagePredicateHandler, host, logger, item, handlers.Where(x => x.Metadata.EndpointName == item.EndpointName), updateBufferHandler, plugins); } public static EndpointHandler Factory(IPredicateHandler languagePredicateHandler, CompositionHost host, ILogger logger, EndpointDescriptor item, IEnumerable<Lazy<IRequestHandler, OmniSharpLanguage>> handlers, Lazy<EndpointHandler<UpdateBufferRequest, object>> updateBufferHandler, IEnumerable<Plugin> plugins) { var createMethod = typeof(EndpointHandler).GetTypeInfo().DeclaredMethods.First(x => x.Name == nameof(EndpointHandler.Create)); return (EndpointHandler)createMethod.MakeGenericMethod(item.RequestType, item.ResponseType).Invoke(null, new object[] { languagePredicateHandler, host, logger, item, handlers, updateBufferHandler, plugins }); } } class EndpointHandler<TRequest, TResponse> : EndpointHandler { private readonly CompositionHost _host; private readonly IPredicateHandler _languagePredicateHandler; private readonly Lazy<Task<Dictionary<string, ExportHandler<TRequest, TResponse>>>> _exports; private readonly OmnisharpWorkspace _workspace; private readonly bool _hasLanguageProperty; private readonly bool _hasFileNameProperty; private readonly bool _canBeAggregated; private readonly ILogger _logger; private readonly IEnumerable<Plugin> _plugins; private readonly Lazy<EndpointHandler<UpdateBufferRequest, object>> _updateBufferHandler; public EndpointHandler(IPredicateHandler languagePredicateHandler, CompositionHost host, ILogger logger, EndpointDescriptor item, IEnumerable<Lazy<IRequestHandler, OmniSharpLanguage>> handlers, Lazy<EndpointHandler<UpdateBufferRequest, object>> updateBufferHandler, IEnumerable<Plugin> plugins) { EndpointName = item.EndpointName; _host = host; _logger = logger; _languagePredicateHandler = languagePredicateHandler; _plugins = plugins; _workspace = host.GetExport<OmnisharpWorkspace>(); _hasLanguageProperty = item.RequestType.GetRuntimeProperty(nameof(LanguageModel.Language)) != null; _hasFileNameProperty = item.RequestType.GetRuntimeProperty(nameof(Request.FileName)) != null; _canBeAggregated = typeof(IAggregateResponse).IsAssignableFrom(item.ResponseType); _updateBufferHandler = updateBufferHandler; _exports = new Lazy<Task<Dictionary<string, ExportHandler<TRequest, TResponse>>>>(() => LoadExportHandlers(handlers)); } private Task<Dictionary<string, ExportHandler<TRequest, TResponse>>> LoadExportHandlers(IEnumerable<Lazy<IRequestHandler, OmniSharpLanguage>> handlers) { var interfaceHandlers = handlers .Select(export => new RequestHandlerExportHandler<TRequest, TResponse>(export.Metadata.Language, (RequestHandler<TRequest, TResponse>)export.Value)) .Cast<ExportHandler<TRequest, TResponse>>(); var plugins = _plugins.Where(x => x.Config.Endpoints.Contains(EndpointName)) .Select(plugin => new PluginExportHandler<TRequest, TResponse>(EndpointName, plugin)) .Cast<ExportHandler<TRequest, TResponse>>(); return Task.FromResult(interfaceHandlers .Concat(plugins) .ToDictionary(export => export.Language)); } public string EndpointName { get; } public override Task<object> Handle(HttpContext context) { var requestObject = DeserializeRequestObject(context.Request.Body); var model = GetLanguageModel(requestObject); return Process(context, model, requestObject); } public async Task<object> Process(HttpContext context, LanguageModel model, JToken requestObject) { var request = requestObject.ToObject<TRequest>(); if (request is Request && _updateBufferHandler.Value != null) { var realRequest = request as Request; if (!string.IsNullOrWhiteSpace(realRequest.FileName) && (realRequest.Buffer != null || realRequest.Changes != null)) { await _updateBufferHandler.Value.Process(context, model, requestObject); } } if (_hasLanguageProperty) { // Handle cases where a request isn't aggrgate and a language isn't specified. // This helps with editors calling a legacy end point, for example /metadata if (!_canBeAggregated && string.IsNullOrWhiteSpace(model.Language)) { model.Language = LanguageNames.CSharp; } return await HandleLanguageRequest(model.Language, request, context); } else if (_hasFileNameProperty) { var language = _languagePredicateHandler.GetLanguageForFilePath(model.FileName ?? string.Empty); return await HandleLanguageRequest(language, request, context); } else { var language = _languagePredicateHandler.GetLanguageForFilePath(string.Empty); if (!string.IsNullOrEmpty(language)) { return await HandleLanguageRequest(language, request, context); } } return await HandleAllRequest(request, context); } private Task<object> HandleLanguageRequest(string language, TRequest request, HttpContext context) { if (!string.IsNullOrEmpty(language)) { return HandleSingleRequest(language, request, context); } return HandleAllRequest(request, context); } private async Task<object> HandleSingleRequest(string language, TRequest request, HttpContext context) { var exports = await _exports.Value; ExportHandler<TRequest, TResponse> handler; if (exports.TryGetValue(language, out handler)) { return await handler.Handle(request); } throw new NotSupportedException($"{language} does not support {EndpointName}"); } private async Task<object> HandleAllRequest(TRequest request, HttpContext context) { if (!_canBeAggregated) { throw new NotSupportedException($"Must be able aggregate the response to spread them out across all plugins for {EndpointName}"); } var exports = await _exports.Value; IAggregateResponse aggregateResponse = null; var responses = new List<Task<TResponse>>(); foreach (var handler in exports.Values) { responses.Add(handler.Handle(request)); } foreach (IAggregateResponse exportResponse in await Task.WhenAll(responses)) { if (aggregateResponse != null) { aggregateResponse = aggregateResponse.Merge(exportResponse); } else { aggregateResponse = exportResponse; } } object response = aggregateResponse; if (response != null) { return response; } return null; } private LanguageModel GetLanguageModel(JToken jtoken) { var response = new LanguageModel(); var jobject = jtoken as JObject; if (jobject == null) { return response; } JToken token; if (jobject.TryGetValue(nameof(LanguageModel.Language), StringComparison.OrdinalIgnoreCase, out token)) { response.Language = token.ToString(); } if (jobject.TryGetValue(nameof(LanguageModel.FileName), StringComparison.OrdinalIgnoreCase, out token)) { response.FileName = token.ToString(); } return response; } private JToken DeserializeRequestObject(Stream readStream) { try { using (var streamReader = new StreamReader(readStream)) { using (var textReader = new JsonTextReader(streamReader)) { return JToken.Load(textReader); } } } catch { return new JObject(); } } } }
#region using Android.Content; using Android.Graphics; using Android.OS; using Android.Support.V4.View; using Android.Util; using Android.Views; using Java.Interop; using Java.Lang; #endregion namespace Xsseract.Droid.Views { public class CirclePageIndicator : View, IPageIndicator { #region Fields private int mActivePointerId = invalidPointer; private bool mCentered; private int mCurrentOffset; private int mCurrentPage; private bool mIsDragging; private float mLastMotionX = -1; private ViewPager.IOnPageChangeListener mListener; private int mOrientation; private int mPageSize; private readonly Paint mPaintFill; private readonly Paint mPaintPageFill; private readonly Paint mPaintStroke; private float mRadius; private int mScrollState; private bool mSnap; private int mSnapPage; private readonly int mTouchSlop; private ViewPager mViewPager; #endregion #region .ctors public CirclePageIndicator(Context context) : this(context, null) {} public CirclePageIndicator(Context context, IAttributeSet attrs) : this(context, attrs, Resource.Attribute.vpiCirclePageIndicatorStyle) {} public CirclePageIndicator(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle) { //Load defaults from resources var res = Resources; int defaultPageColor = res.GetColor(Resource.Color.default_circle_indicator_page_color); int defaultFillColor = res.GetColor(Resource.Color.default_circle_indicator_fill_color); int defaultOrientation = res.GetInteger(Resource.Integer.default_circle_indicator_orientation); int defaultStrokeColor = res.GetColor(Resource.Color.default_circle_indicator_stroke_color); float defaultStrokeWidth = res.GetDimension(Resource.Dimension.default_circle_indicator_stroke_width); float defaultRadius = res.GetDimension(Resource.Dimension.default_circle_indicator_radius); bool defaultCentered = res.GetBoolean(Resource.Boolean.default_circle_indicator_centered); bool defaultSnap = res.GetBoolean(Resource.Boolean.default_circle_indicator_snap); //Retrieve styles attributes var a = context.ObtainStyledAttributes(attrs, Resource.Styleable.CirclePageIndicator, defStyle, Resource.Style.Widget_CirclePageIndicator); mCentered = a.GetBoolean(Resource.Styleable.CirclePageIndicator_centered, defaultCentered); mOrientation = a.GetInt(Resource.Styleable.CirclePageIndicator_orientation, defaultOrientation); mPaintPageFill = new Paint(PaintFlags.AntiAlias); mPaintPageFill.SetStyle(Paint.Style.Fill); mPaintPageFill.Color = a.GetColor(Resource.Styleable.CirclePageIndicator_pageColor, defaultPageColor); mPaintStroke = new Paint(PaintFlags.AntiAlias); mPaintStroke.SetStyle(Paint.Style.Stroke); mPaintStroke.Color = a.GetColor(Resource.Styleable.CirclePageIndicator_strokeColor, defaultStrokeColor); mPaintStroke.StrokeWidth = a.GetDimension(Resource.Styleable.CirclePageIndicator_strokeWidth, defaultStrokeWidth); mPaintFill = new Paint(PaintFlags.AntiAlias); mPaintFill.SetStyle(Paint.Style.Fill); mPaintFill.Color = a.GetColor(Resource.Styleable.CirclePageIndicator_fillColor, defaultFillColor); mRadius = a.GetDimension(Resource.Styleable.CirclePageIndicator_radius, defaultRadius); mSnap = a.GetBoolean(Resource.Styleable.CirclePageIndicator_snap, defaultSnap); a.Recycle(); var configuration = ViewConfiguration.Get(context); mTouchSlop = ViewConfigurationCompat.GetScaledPagingTouchSlop(configuration); } #endregion public void SetCentered(bool centered) { mCentered = centered; Invalidate(); } public bool IsCentered() { return mCentered; } public void SetPageColor(Color pageColor) { mPaintPageFill.Color = pageColor; Invalidate(); } public int GetPageColor() { return mPaintPageFill.Color; } public void SetFillColor(Color fillColor) { mPaintFill.Color = fillColor; Invalidate(); } public int GetFillColor() { return mPaintFill.Color; } public void setOrientation(int orientation) { switch(orientation) { case horizontal: case vertical: mOrientation = orientation; UpdatePageSize(); RequestLayout(); break; default: throw new IllegalArgumentException("Orientation must be either HORIZONTAL or VERTICAL."); } } public int GetOrientation() { return mOrientation; } public void SetStrokeColor(Color strokeColor) { mPaintStroke.Color = strokeColor; Invalidate(); } public int GetStrokeColor() { return mPaintStroke.Color; } public void SetStrokeWidth(float strokeWidth) { mPaintStroke.StrokeWidth = strokeWidth; Invalidate(); } public float GetStrokeWidth() { return mPaintStroke.StrokeWidth; } public void SetRadius(float radius) { mRadius = radius; Invalidate(); } public float GetRadius() { return mRadius; } public void SetSnap(bool snap) { mSnap = snap; Invalidate(); } public bool IsSnap() { return mSnap; } public override bool OnTouchEvent(MotionEvent ev) { if (base.OnTouchEvent(ev)) { return true; } if ((mViewPager == null) || (mViewPager.Adapter.Count == 0)) { return false; } var action = ev.Action; switch((int)action & MotionEventCompat.ActionMask) { case (int)MotionEventActions.Down: mActivePointerId = MotionEventCompat.GetPointerId(ev, 0); mLastMotionX = ev.GetX(); break; case (int)MotionEventActions.Move: { int activePointerIndex = MotionEventCompat.FindPointerIndex(ev, mActivePointerId); float x = MotionEventCompat.GetX(ev, activePointerIndex); float deltaX = x - mLastMotionX; if (!mIsDragging) { if (Math.Abs(deltaX) > mTouchSlop) { mIsDragging = true; } } if (mIsDragging) { if (!mViewPager.IsFakeDragging) { mViewPager.BeginFakeDrag(); } mLastMotionX = x; mViewPager.FakeDragBy(deltaX); } break; } case (int)MotionEventActions.Cancel: case (int)MotionEventActions.Up: if (!mIsDragging) { int count = mViewPager.Adapter.Count; int width = Width; float halfWidth = width / 2f; float sixthWidth = width / 6f; if ((mCurrentPage > 0) && (ev.GetX() < halfWidth - sixthWidth)) { mViewPager.CurrentItem = mCurrentPage - 1; return true; } else if ((mCurrentPage < count - 1) && (ev.GetX() > halfWidth + sixthWidth)) { mViewPager.CurrentItem = mCurrentPage + 1; return true; } } mIsDragging = false; mActivePointerId = invalidPointer; if (mViewPager.IsFakeDragging) { mViewPager.EndFakeDrag(); } break; case MotionEventCompat.ActionPointerDown: { int index = MotionEventCompat.GetActionIndex(ev); float x = MotionEventCompat.GetX(ev, index); mLastMotionX = x; mActivePointerId = MotionEventCompat.GetPointerId(ev, index); break; } case MotionEventCompat.ActionPointerUp: int pointerIndex = MotionEventCompat.GetActionIndex(ev); int pointerId = MotionEventCompat.GetPointerId(ev, pointerIndex); if (pointerId == mActivePointerId) { int newPointerIndex = pointerIndex == 0 ? 1 : 0; mActivePointerId = MotionEventCompat.GetPointerId(ev, newPointerIndex); } mLastMotionX = MotionEventCompat.GetX(ev, MotionEventCompat.FindPointerIndex(ev, mActivePointerId)); break; } return true; } public void SetViewPager(ViewPager view) { if (view.Adapter == null) { throw new IllegalStateException("ViewPager does not have adapter instance."); } mViewPager = view; mViewPager.SetOnPageChangeListener(this); UpdatePageSize(); Invalidate(); } public void SetViewPager(ViewPager view, int initialPosition) { SetViewPager(view); SetCurrentItem(initialPosition); } public void SetCurrentItem(int item) { if (mViewPager == null) { throw new IllegalStateException("ViewPager has not been bound."); } mViewPager.CurrentItem = item; mCurrentPage = item; Invalidate(); } public void NotifyDataSetChanged() { Invalidate(); } public void OnPageScrollStateChanged(int state) { mScrollState = state; if (mListener != null) { mListener.OnPageScrollStateChanged(state); } } public void OnPageScrolled(int position, float positionOffset, int positionOffsetPixels) { mCurrentPage = position; mCurrentOffset = positionOffsetPixels; UpdatePageSize(); Invalidate(); if (mListener != null) { mListener.OnPageScrolled(position, positionOffset, positionOffsetPixels); } } public void OnPageSelected(int position) { if (mSnap || mScrollState == ViewPager.ScrollStateIdle) { mCurrentPage = position; mSnapPage = position; Invalidate(); } if (mListener != null) { mListener.OnPageSelected(position); } } public void SetOnPageChangeListener(ViewPager.IOnPageChangeListener listener) { mListener = listener; } protected override void OnDraw(Canvas canvas) { base.OnDraw(canvas); if (mViewPager == null) { return; } int count = mViewPager.Adapter.Count; if (count == 0) { return; } if (mCurrentPage >= count) { SetCurrentItem(count - 1); return; } int longSize; int longPaddingBefore; int longPaddingAfter; int shortPaddingBefore; if (mOrientation == horizontal) { longSize = Width; longPaddingBefore = PaddingLeft; longPaddingAfter = PaddingRight; shortPaddingBefore = PaddingTop; } else { longSize = Height; longPaddingBefore = PaddingTop; longPaddingAfter = PaddingBottom; shortPaddingBefore = PaddingLeft; } float threeRadius = mRadius * 3; float shortOffset = shortPaddingBefore + mRadius; float longOffset = longPaddingBefore + mRadius; if (mCentered) { longOffset += ((longSize - longPaddingBefore - longPaddingAfter) / 2.0f) - ((count * threeRadius) / 2.0f); } float dX; float dY; float pageFillRadius = mRadius; if (mPaintStroke.StrokeWidth > 0) { pageFillRadius -= mPaintStroke.StrokeWidth / 2.0f; } //Draw stroked circles for(int iLoop = 0; iLoop < count; iLoop++) { float drawLong = longOffset + (iLoop * threeRadius); if (mOrientation == horizontal) { dX = drawLong; dY = shortOffset; } else { dX = shortOffset; dY = drawLong; } // Only paint fill if not completely transparent if (mPaintPageFill.Alpha > 0) { canvas.DrawCircle(dX, dY, pageFillRadius, mPaintPageFill); } // Only paint stroke if a stroke width was non-zero if (pageFillRadius != mRadius) { canvas.DrawCircle(dX, dY, mRadius, mPaintStroke); } } //Draw the filled circle according to the current scroll float cx = (mSnap ? mSnapPage : mCurrentPage) * threeRadius; if (!mSnap && (mPageSize != 0)) { cx += (mCurrentOffset * 1.0f / mPageSize) * threeRadius; } if (mOrientation == horizontal) { dX = longOffset + cx; dY = shortOffset; } else { dX = shortOffset; dY = longOffset + cx; } canvas.DrawCircle(dX, dY, mRadius, mPaintFill); } protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (mOrientation == horizontal) { SetMeasuredDimension(MeasureLong(widthMeasureSpec), MeasureShort(heightMeasureSpec)); } else { SetMeasuredDimension(MeasureShort(widthMeasureSpec), MeasureLong(heightMeasureSpec)); } } protected override void OnRestoreInstanceState(IParcelable state) { try { SavedState savedState = (SavedState)state; base.OnRestoreInstanceState(savedState.SuperState); mCurrentPage = savedState.CurrentPage; mSnapPage = savedState.CurrentPage; } catch { base.OnRestoreInstanceState(state); // Ignore, this needs to support IParcelable... } RequestLayout(); } protected override IParcelable OnSaveInstanceState() { var superState = base.OnSaveInstanceState(); var savedState = new SavedState(superState); savedState.CurrentPage = mCurrentPage; return savedState; } #region Private Methods /** * Determines the width of this view * * @param measureSpec * A measureSpec packed into an int * @return The width of the view, honoring constraints from measureSpec */ private int MeasureLong(int measureSpec) { int result = 0; var specMode = MeasureSpec.GetMode(measureSpec); var specSize = MeasureSpec.GetSize(measureSpec); if ((specMode == MeasureSpecMode.Exactly) || (mViewPager == null)) { //We were told how big to be result = specSize; } else { //Calculate the width according the views count int count = mViewPager.Adapter.Count; result = (int)(PaddingLeft + PaddingRight + (count * 2 * mRadius) + (count - 1) * mRadius + 1); //Respect AT_MOST value if that was what is called for by measureSpec if (specMode == MeasureSpecMode.AtMost) { result = Math.Min(result, specSize); } } return result; } /** * Determines the height of this view * * @param measureSpec * A measureSpec packed into an int * @return The height of the view, honoring constraints from measureSpec */ private int MeasureShort(int measureSpec) { int result = 0; var specMode = MeasureSpec.GetMode(measureSpec); var specSize = MeasureSpec.GetSize(measureSpec); if (specMode == MeasureSpecMode.Exactly) { //We were told how big to be result = specSize; } else { //Measure the height result = (int)(2 * mRadius + PaddingTop + PaddingBottom + 1); //Respect AT_MOST value if that was what is called for by measureSpec if (specMode == MeasureSpecMode.AtMost) { result = Math.Min(result, specSize); } } return result; } private void UpdatePageSize() { if (mViewPager != null) { mPageSize = (mOrientation == horizontal) ? mViewPager.Width : mViewPager.Height; } } #endregion #region Inner Classes/Enums public class SavedState : BaseSavedState { public int CurrentPage { get; set; } #region .ctors public SavedState(IParcelable superState) : base(superState) {} private SavedState(Parcel parcel) : base(parcel) { CurrentPage = parcel.ReadInt(); } #endregion public override void WriteToParcel(Parcel dest, ParcelableWriteFlags flags) { base.WriteToParcel(dest, flags); dest.WriteInt(CurrentPage); } #region Private Methods [ExportField("CREATOR")] private static SavedStateCreator InitializeCreator() { return new SavedStateCreator(); } #endregion #region Inner Classes/Enums private class SavedStateCreator : Object, IParcelableCreator { public Object CreateFromParcel(Parcel source) { return new SavedState(source); } public Object[] NewArray(int size) { return new SavedState[size]; } } #endregion } #endregion private const int horizontal = 0; private const int vertical = 1; private const int invalidPointer = -1; } }
// 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: Capture synchronization semantics for asynchronous callbacks ** ** ===========================================================*/ namespace System.Threading { using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime; using System.Runtime.Versioning; using System.Runtime.ConstrainedExecution; using System.Reflection; using System.Security; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Diagnostics.CodeAnalysis; [Flags] internal enum SynchronizationContextProperties { None = 0, RequireWaitNotification = 0x1 }; #if FEATURE_COMINTEROP && FEATURE_APPX // // This is implemented in System.Runtime.WindowsRuntime, allowing us to ask that assembly for a WinRT-specific SyncCtx. // I'd like this to be an interface, or at least an abstract class - but neither seems to play nice with FriendAccessAllowed. // [FriendAccessAllowed] internal class WinRTSynchronizationContextFactoryBase { public virtual SynchronizationContext Create(object coreDispatcher) { return null; } } #endif //FEATURE_COMINTEROP public class SynchronizationContext { private SynchronizationContextProperties _props = SynchronizationContextProperties.None; public SynchronizationContext() { } // helper delegate to statically bind to Wait method private delegate int WaitDelegate(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout); private static Type s_cachedPreparedType1; private static Type s_cachedPreparedType2; private static Type s_cachedPreparedType3; private static Type s_cachedPreparedType4; private static Type s_cachedPreparedType5; // protected so that only the derived sync context class can enable these flags [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "We never dereference s_cachedPreparedType*, so ordering is unimportant")] protected void SetWaitNotificationRequired() { // // Prepare the method so that it can be called in a reliable fashion when a wait is needed. // This will obviously only make the Wait reliable if the Wait method is itself reliable. The only thing // preparing the method here does is to ensure there is no failure point before the method execution begins. // // Preparing the method in this way is quite expensive, but only needs to be done once per type, per AppDomain. // So we keep track of a few types we've already prepared in this AD. It is uncommon to have more than // a few SynchronizationContext implementations, so we only cache the first five we encounter; this lets // our cache be much faster than a more general cache might be. This is important, because this // is a *very* hot code path for many WPF and WinForms apps. // Type type = this.GetType(); if (s_cachedPreparedType1 != type && s_cachedPreparedType2 != type && s_cachedPreparedType3 != type && s_cachedPreparedType4 != type && s_cachedPreparedType5 != type) { RuntimeHelpers.PrepareDelegate(new WaitDelegate(this.Wait)); if (s_cachedPreparedType1 == null) s_cachedPreparedType1 = type; else if (s_cachedPreparedType2 == null) s_cachedPreparedType2 = type; else if (s_cachedPreparedType3 == null) s_cachedPreparedType3 = type; else if (s_cachedPreparedType4 == null) s_cachedPreparedType4 = type; else if (s_cachedPreparedType5 == null) s_cachedPreparedType5 = type; } _props |= SynchronizationContextProperties.RequireWaitNotification; } public bool IsWaitNotificationRequired() { return ((_props & SynchronizationContextProperties.RequireWaitNotification) != 0); } public virtual void Send(SendOrPostCallback d, Object state) { d(state); } public virtual void Post(SendOrPostCallback d, Object state) { ThreadPool.QueueUserWorkItem(new WaitCallback(d), state); } /// <summary> /// Optional override for subclasses, for responding to notification that operation is starting. /// </summary> public virtual void OperationStarted() { } /// <summary> /// Optional override for subclasses, for responding to notification that operation has completed. /// </summary> public virtual void OperationCompleted() { } // Method called when the CLR does a wait operation [CLSCompliant(false)] public virtual int Wait(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout) { return WaitHelper(waitHandles, waitAll, millisecondsTimeout); } // Method that can be called by Wait overrides [CLSCompliant(false)] protected static int WaitHelper(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout) { if (waitHandles == null) { throw new ArgumentNullException(nameof(waitHandles)); } Contract.EndContractBlock(); return WaitHelperNative(waitHandles, waitAll, millisecondsTimeout); } // Static helper to which the above method can delegate to in order to get the default // COM behavior. [CLSCompliant(false)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int WaitHelperNative(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout); public static void SetSynchronizationContext(SynchronizationContext syncContext) { Thread.CurrentThread.SynchronizationContext = syncContext; } public static SynchronizationContext Current { get { SynchronizationContext context = Thread.CurrentThread.SynchronizationContext; #if FEATURE_APPX if (context == null && AppDomain.IsAppXModel()) context = GetWinRTContext(); #endif return context; } } // Get the last SynchronizationContext that was set explicitly (not flowed via ExecutionContext.Capture/Run) internal static SynchronizationContext CurrentNoFlow { [FriendAccessAllowed] get { return Current; // SC never flows } } #if FEATURE_APPX private static SynchronizationContext GetWinRTContext() { Debug.Assert(Environment.IsWinRTSupported); Debug.Assert(AppDomain.IsAppXModel()); // // We call into the VM to get the dispatcher. This is because: // // a) We cannot call the WinRT APIs directly from mscorlib, because we don't have the fancy projections here. // b) We cannot call into System.Runtime.WindowsRuntime here, because we don't want to load that assembly // into processes that don't need it (for performance reasons). // // So, we check the VM to see if the current thread has a dispatcher; if it does, we pass that along to // System.Runtime.WindowsRuntime to get a corresponding SynchronizationContext. // object dispatcher = GetWinRTDispatcherForCurrentThread(); if (dispatcher != null) return GetWinRTSynchronizationContextFactory().Create(dispatcher); return null; } private static WinRTSynchronizationContextFactoryBase s_winRTContextFactory; private static WinRTSynchronizationContextFactoryBase GetWinRTSynchronizationContextFactory() { // // Since we can't directly reference System.Runtime.WindowsRuntime from mscorlib, we have to get the factory via reflection. // It would be better if we could just implement WinRTSynchronizationContextFactory in mscorlib, but we can't, because // we can do very little with WinRT stuff in mscorlib. // WinRTSynchronizationContextFactoryBase factory = s_winRTContextFactory; if (factory == null) { Type factoryType = Type.GetType("System.Threading.WinRTSynchronizationContextFactory, " + AssemblyRef.SystemRuntimeWindowsRuntime, true); s_winRTContextFactory = factory = (WinRTSynchronizationContextFactoryBase)Activator.CreateInstance(factoryType, true); } return factory; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Interface)] private static extern object GetWinRTDispatcherForCurrentThread(); #endif //FEATURE_APPX // helper to Clone this SynchronizationContext, public virtual SynchronizationContext CreateCopy() { // the CLR dummy has an empty clone function - no member data return new SynchronizationContext(); } private static int InvokeWaitMethodHelper(SynchronizationContext syncContext, IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout) { return syncContext.Wait(waitHandles, waitAll, millisecondsTimeout); } } }
/* ==================================================================== 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 NPOI.SS.Format { using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using static NPOI.SS.Format.CellNumberFormatter; /** * Internal helper class for CellNumberFormatter */ public class CellNumberPartHandler : CellFormatPart.IPartHandler { private char insertSignForExponent; private double scale = 1; private Special decimalPoint; private Special slash; private Special exponent; private Special numerator; private List<Special> specials = new List<Special>(); private bool improperFraction; public String HandlePart(Match m, String part, CellFormatType type, StringBuilder descBuf) { int pos = descBuf.Length; char firstCh = part[0]; switch (firstCh) { case 'e': case 'E': // See comment in WriteScientific -- exponent handling is complex. // (1) When parsing the format, remove the sign from After the 'e' and // Put it before the first digit of the exponent. if (exponent == null && specials.Count > 0) { exponent = new Special('.', pos); specials.Add(exponent); insertSignForExponent = part[1]; return part.Substring(0, 1); } break; case '0': case '?': case '#': if (insertSignForExponent != '\0') { specials.Add(new Special(insertSignForExponent, pos)); descBuf.Append(insertSignForExponent); insertSignForExponent = '\0'; pos++; } for (int i = 0; i < part.Length; i++) { char ch = part[i]; specials.Add(new Special(ch, pos + i)); } break; case '.': if (decimalPoint == null && specials.Count > 0) { decimalPoint = new Special('.', pos); specials.Add(decimalPoint); } break; case '/': //!! This assumes there is a numerator and a denominator, but these are actually optional if (slash == null && specials.Count > 0) { numerator = PreviousNumber(); // If the first number in the whole format is the numerator, the // entire number should be printed as an improper fraction improperFraction |= (numerator == FirstDigit(specials)); slash = new Special('.', pos); specials.Add(slash); } break; case '%': // don't need to remember because we don't need to do anything with these scale *= 100; break; default: return null; } return part; } public double Scale { get { return scale; } } public Special DecimalPoint { get { return decimalPoint; } } public Special Slash { get { return slash; } } public Special Exponent { get { return exponent; } } public Special Numerator { get { return numerator; } } public List<Special> Specials { get { return specials; } } public bool IsImproperFraction { get { return improperFraction; } } private Special PreviousNumber() { for (int i = specials.Count - 1; i >= 0; i--) { Special s = specials[i]; if (IsDigitFmt(s)) { //Special numStart = s; Special last = s; while (i >= 0) { s = specials[i]; if (last.pos - s.pos > 1 || !IsDigitFmt(s)) // it has to be continuous digits break; last = s; i--; } return last; } } return null; } private static bool IsDigitFmt(Special s) { return s.ch == '0' || s.ch == '?' || s.ch == '#'; } private static Special FirstDigit(List<Special> specials) { foreach (Special s in specials) { if (IsDigitFmt(s)) { return s; } } return null; } } }
using System; using System.Collections.Generic; using UnityEngine; namespace UnitySampleAssets.Water { [ExecuteInEditMode] [RequireComponent(typeof(WaterBase))] public class PlanarReflection : MonoBehaviour { public LayerMask reflectionMask; public bool reflectSkybox = false; public Color clearColor = Color.grey; public String reflectionSampler = "_ReflectionTex"; public float clipPlaneOffset = 0.07F; Vector3 m_Oldpos; Camera m_ReflectionCamera; Material m_SharedMaterial; Dictionary<Camera, bool> m_HelperCameras; public void Start() { m_SharedMaterial = ((WaterBase)gameObject.GetComponent(typeof(WaterBase))).sharedMaterial; } Camera CreateReflectionCameraFor(Camera cam) { String reflName = gameObject.name + "Reflection" + cam.name; GameObject go = GameObject.Find(reflName); if (!go) { go = new GameObject(reflName, typeof(Camera)); } if (!go.GetComponent(typeof(Camera))) { go.AddComponent(typeof(Camera)); } Camera reflectCamera = go.GetComponent<Camera>(); reflectCamera.backgroundColor = clearColor; reflectCamera.clearFlags = reflectSkybox ? CameraClearFlags.Skybox : CameraClearFlags.SolidColor; SetStandardCameraParameter(reflectCamera, reflectionMask); if (!reflectCamera.targetTexture) { reflectCamera.targetTexture = CreateTextureFor(cam); } return reflectCamera; } void SetStandardCameraParameter(Camera cam, LayerMask mask) { cam.cullingMask = mask & ~(1 << LayerMask.NameToLayer("Water")); cam.backgroundColor = Color.black; cam.enabled = false; } RenderTexture CreateTextureFor(Camera cam) { RenderTexture rt = new RenderTexture(Mathf.FloorToInt(cam.pixelWidth * 0.5F), Mathf.FloorToInt(cam.pixelHeight * 0.5F), 24); rt.hideFlags = HideFlags.DontSave; return rt; } public void RenderHelpCameras(Camera currentCam) { if (null == m_HelperCameras) { m_HelperCameras = new Dictionary<Camera, bool>(); } if (!m_HelperCameras.ContainsKey(currentCam)) { m_HelperCameras.Add(currentCam, false); } if (m_HelperCameras[currentCam]) { return; } if (!m_ReflectionCamera) { m_ReflectionCamera = CreateReflectionCameraFor(currentCam); } RenderReflectionFor(currentCam, m_ReflectionCamera); m_HelperCameras[currentCam] = true; } public void LateUpdate() { if (null != m_HelperCameras) { m_HelperCameras.Clear(); } } public void WaterTileBeingRendered(Transform tr, Camera currentCam) { RenderHelpCameras(currentCam); if (m_ReflectionCamera && m_SharedMaterial) { m_SharedMaterial.SetTexture(reflectionSampler, m_ReflectionCamera.targetTexture); } } public void OnEnable() { Shader.EnableKeyword("WATER_REFLECTIVE"); Shader.DisableKeyword("WATER_SIMPLE"); } public void OnDisable() { Shader.EnableKeyword("WATER_SIMPLE"); Shader.DisableKeyword("WATER_REFLECTIVE"); } void RenderReflectionFor(Camera cam, Camera reflectCamera) { if (!reflectCamera) { return; } if (m_SharedMaterial && !m_SharedMaterial.HasProperty(reflectionSampler)) { return; } reflectCamera.cullingMask = reflectionMask & ~(1 << LayerMask.NameToLayer("Water")); SaneCameraSettings(reflectCamera); reflectCamera.backgroundColor = clearColor; reflectCamera.clearFlags = reflectSkybox ? CameraClearFlags.Skybox : CameraClearFlags.SolidColor; if (reflectSkybox) { if (cam.gameObject.GetComponent(typeof(Skybox))) { Skybox sb = (Skybox)reflectCamera.gameObject.GetComponent(typeof(Skybox)); if (!sb) { sb = (Skybox)reflectCamera.gameObject.AddComponent(typeof(Skybox)); } sb.material = ((Skybox)cam.GetComponent(typeof(Skybox))).material; } } GL.invertCulling = true; Transform reflectiveSurface = transform; //waterHeight; Vector3 eulerA = cam.transform.eulerAngles; reflectCamera.transform.eulerAngles = new Vector3(-eulerA.x, eulerA.y, eulerA.z); reflectCamera.transform.position = cam.transform.position; Vector3 pos = reflectiveSurface.transform.position; pos.y = reflectiveSurface.position.y; Vector3 normal = reflectiveSurface.transform.up; float d = -Vector3.Dot(normal, pos) - clipPlaneOffset; Vector4 reflectionPlane = new Vector4(normal.x, normal.y, normal.z, d); Matrix4x4 reflection = Matrix4x4.zero; reflection = CalculateReflectionMatrix(reflection, reflectionPlane); m_Oldpos = cam.transform.position; Vector3 newpos = reflection.MultiplyPoint(m_Oldpos); reflectCamera.worldToCameraMatrix = cam.worldToCameraMatrix * reflection; Vector4 clipPlane = CameraSpacePlane(reflectCamera, pos, normal, 1.0f); Matrix4x4 projection = cam.projectionMatrix; projection = CalculateObliqueMatrix(projection, clipPlane); reflectCamera.projectionMatrix = projection; reflectCamera.transform.position = newpos; Vector3 euler = cam.transform.eulerAngles; reflectCamera.transform.eulerAngles = new Vector3(-euler.x, euler.y, euler.z); reflectCamera.Render(); GL.invertCulling = false; } void SaneCameraSettings(Camera helperCam) { helperCam.depthTextureMode = DepthTextureMode.None; helperCam.backgroundColor = Color.black; helperCam.clearFlags = CameraClearFlags.SolidColor; helperCam.renderingPath = RenderingPath.Forward; } static Matrix4x4 CalculateObliqueMatrix(Matrix4x4 projection, Vector4 clipPlane) { Vector4 q = projection.inverse * new Vector4( Sgn(clipPlane.x), Sgn(clipPlane.y), 1.0F, 1.0F ); Vector4 c = clipPlane * (2.0F / (Vector4.Dot(clipPlane, q))); // third row = clip plane - fourth row projection[2] = c.x - projection[3]; projection[6] = c.y - projection[7]; projection[10] = c.z - projection[11]; projection[14] = c.w - projection[15]; return projection; } static Matrix4x4 CalculateReflectionMatrix(Matrix4x4 reflectionMat, Vector4 plane) { reflectionMat.m00 = (1.0F - 2.0F * plane[0] * plane[0]); reflectionMat.m01 = (- 2.0F * plane[0] * plane[1]); reflectionMat.m02 = (- 2.0F * plane[0] * plane[2]); reflectionMat.m03 = (- 2.0F * plane[3] * plane[0]); reflectionMat.m10 = (- 2.0F * plane[1] * plane[0]); reflectionMat.m11 = (1.0F - 2.0F * plane[1] * plane[1]); reflectionMat.m12 = (- 2.0F * plane[1] * plane[2]); reflectionMat.m13 = (- 2.0F * plane[3] * plane[1]); reflectionMat.m20 = (- 2.0F * plane[2] * plane[0]); reflectionMat.m21 = (- 2.0F * plane[2] * plane[1]); reflectionMat.m22 = (1.0F - 2.0F * plane[2] * plane[2]); reflectionMat.m23 = (- 2.0F * plane[3] * plane[2]); reflectionMat.m30 = 0.0F; reflectionMat.m31 = 0.0F; reflectionMat.m32 = 0.0F; reflectionMat.m33 = 1.0F; return reflectionMat; } static float Sgn(float a) { if (a > 0.0F) { return 1.0F; } if (a < 0.0F) { return -1.0F; } return 0.0F; } Vector4 CameraSpacePlane(Camera cam, Vector3 pos, Vector3 normal, float sideSign) { Vector3 offsetPos = pos + normal * clipPlaneOffset; Matrix4x4 m = cam.worldToCameraMatrix; Vector3 cpos = m.MultiplyPoint(offsetPos); Vector3 cnormal = m.MultiplyVector(normal).normalized * sideSign; return new Vector4(cnormal.x, cnormal.y, cnormal.z, -Vector3.Dot(cpos, cnormal)); } } }
using System; using System.IO; using System.Linq; using System.Net.Sockets; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using MySqlConnector.Protocol; namespace MySqlConnector.Tests; internal sealed class FakeMySqlServerConnection { public FakeMySqlServerConnection(FakeMySqlServer server, int connectionId) { m_server = server ?? throw new ArgumentNullException(nameof(server)); m_connectionId = connectionId; CancelQueryEvent = new(); } public ManualResetEventSlim CancelQueryEvent { get; } public async Task RunAsync(TcpClient client, CancellationToken token) { try { using (token.Register(client.Dispose)) using (client) using (var stream = client.GetStream()) { if (m_server.BlockOnConnect) Thread.Sleep(TimeSpan.FromSeconds(10)); await SendAsync(stream, 0, WriteInitialHandshake); await ReadPayloadAsync(stream, token); // handshake response if (m_server.SendIncompletePostHandshakeResponse) { await stream.WriteAsync(new byte[] { 1, 0, 0, 2 }, 0, 4); return; } await SendAsync(stream, 2, WriteOk); var keepRunning = true; while (keepRunning) { byte[] bytes; try { bytes = await ReadPayloadAsync(stream, token); } catch (EndOfStreamException) { break; } switch ((CommandKind) bytes[0]) { case CommandKind.Quit: await SendAsync(stream, 1, WriteOk); keepRunning = false; break; case CommandKind.Ping: case CommandKind.ResetConnection: await SendAsync(stream, 1, WriteOk); break; case CommandKind.Query: var query = Encoding.UTF8.GetString(bytes, 1, bytes.Length - 1); Match match; if (query == "SET NAMES utf8mb4;") { await SendAsync(stream, 1, WriteOk); } else if ((match = Regex.Match(query, @"^SELECT ([0-9])(;|$)")).Success) { var number = match.Groups[1].Value; var data = new byte[number.Length + 1]; data[0] = (byte) number.Length; Encoding.UTF8.GetBytes(number, 0, number.Length, data, 1); await SendAsync(stream, 1, x => x.Write((byte) 1)); // one column await SendAsync(stream, 2, x => x.Write(new byte[] { 3, 0x64, 0x65, 0x66, 0, 0, 0, 1, 0x5F, 0, 0x0c, 0x3f, 0, 1, 0, 0, 0, 3, 0x81, 0, 0, 0, 0 })); // column definition await SendAsync(stream, 3, x => x.Write(new byte[] { 0xFE, 0, 0, 2, 0 })); // EOF await SendAsync(stream, 4, x => x.Write(data)); await SendAsync(stream, 5, x => x.Write(new byte[] { 0xFE, 0, 0, 2, 0 })); // EOF } else if ((match = Regex.Match(query, @"^SELECT ([0-9]+), ([0-9]+), ([0-9-]+), ([0-9]+)(;|$)")).Success) { // command is "SELECT {value}, {delay}, {pauseStep}, {flags}" var number = match.Groups[1].Value; var value = int.Parse(number); var delay = int.Parse(match.Groups[2].Value); var pauseStep = int.Parse(match.Groups[3].Value); var flags = int.Parse(match.Groups[4].Value); var ignoreCancellation = (flags & 1) == 1; var bufferOutput = (flags & 2) == 2; var data = new byte[number.Length + 1]; data[0] = (byte) number.Length; Encoding.UTF8.GetBytes(number, 0, number.Length, data, 1); var negativeOne = new byte[] { 2, 0x2D, 0x31 }; var packets = new[] { new byte[] { 0xFF, 0x25, 0x05, 0x23, 0x37, 0x30, 0x31, 0x30, 0x30 }.Concat(Encoding.ASCII.GetBytes("Query execution was interrupted")).ToArray(), // error new byte[] { 1 }, // one column new byte[] { 3, 0x64, 0x65, 0x66, 0, 0, 0, 1, 0x5F, 0, 0x0c, 0x3f, 0, 1, 0, 0, 0, 3, 0x81, 0, 0, 0, 0 }, // column definition new byte[] { 0xFE, 0, 0, 2, 0 }, // EOF data, negativeOne, negativeOne, new byte[] { 0xFE, 0, 0, 10, 0 }, // EOF, more results exist new byte[] { 1 }, // one column new byte[] { 3, 0x64, 0x65, 0x66, 0, 0, 0, 1, 0x5F, 0, 0x0c, 0x3f, 0, 1, 0, 0, 0, 3, 0x81, 0, 0, 0, 0 }, // column definition new byte[] { 0xFE, 0, 0, 2, 0 }, // EOF negativeOne, new byte[] { 0xFE, 0, 0, 2, 0 }, // EOF }; if (bufferOutput) { // if 'bufferOutput' is set, perform the delay immediately then send all the output afterwards, as though it were buffered on the server var queryInterrupted = false; if (ignoreCancellation) await Task.Delay(delay, token); else queryInterrupted = CancelQueryEvent.Wait(delay, token); for (var step = 1; step < pauseStep; step++) await SendAsync(stream, step, x => x.Write(packets[step])); await SendAsync(stream, pauseStep, x => x.Write(packets[queryInterrupted ? 0 : pauseStep])); } else { var queryInterrupted = false; for (var step = 1; step < packets.Length && !queryInterrupted; step++) { if (pauseStep == step || pauseStep == -1) { if (ignoreCancellation) await Task.Delay(delay, token); else queryInterrupted = CancelQueryEvent.Wait(delay, token); } await SendAsync(stream, step, x => x.Write(packets[queryInterrupted ? 0 : step])); } } } else if ((match = Regex.Match(query, @"^KILL QUERY ([0-9]+)(;|$)", RegexOptions.IgnoreCase)).Success) { var connectionId = int.Parse(match.Groups[1].Value); m_server.CancelQuery(connectionId); await SendAsync(stream, 1, WriteOk); } else if (query == "SELECT SLEEP(0) INTO @\uE001MySqlConnector\uE001Sleep;") { var wasSet = CancelQueryEvent.Wait(0, token); await SendAsync(stream, 1, WriteOk); } else { await SendAsync(stream, 1, x => WriteError(x, "Unhandled query: " + query)); } break; default: Console.WriteLine("** UNHANDLED ** {0}", (CommandKind) bytes[0]); await SendAsync(stream, 1, x => WriteError(x)); break; } } } } finally { m_server.ClientDisconnected(); } } private static async Task SendAsync(Stream stream, int sequenceNumber, Action<BinaryWriter> writePayload) { var packet = MakePayload(sequenceNumber, writePayload); await stream.WriteAsync(packet, 0, packet.Length); } private static byte[] MakePayload(int sequenceNumber, Action<BinaryWriter> writePayload) { using var memoryStream = new MemoryStream(); using (var writer = new BinaryWriter(memoryStream, Encoding.UTF8, leaveOpen: true)) { writer.Write(default(int)); writePayload(writer); memoryStream.Position = 0; writer.Write(((int) (memoryStream.Length - 4)) | ((sequenceNumber % 256) << 24)); } return memoryStream.ToArray(); } private static async Task<byte[]> ReadPayloadAsync(Stream stream, CancellationToken token) { var header = await ReadBytesAsync(stream, 4, token); var length = header[0] | (header[1] << 8) | (header[2] << 16); var sequenceNumber = header[3]; return await ReadBytesAsync(stream, length, token); } private static async Task<byte[]> ReadBytesAsync(Stream stream, int count, CancellationToken token) { var bytes = new byte[count]; for (var totalBytesRead = 0; totalBytesRead < count;) { var bytesRead = await stream.ReadAsync(bytes, totalBytesRead, count - totalBytesRead, token); if (bytesRead == 0) throw new EndOfStreamException(); totalBytesRead += bytesRead; } return bytes; } private void WriteInitialHandshake(BinaryWriter writer) { var random = new Random(1); var authData = new byte[20]; random.NextBytes(authData); var capabilities = ProtocolCapabilities.LongPassword | ProtocolCapabilities.FoundRows | ProtocolCapabilities.LongFlag | ProtocolCapabilities.IgnoreSpace | ProtocolCapabilities.Protocol41 | ProtocolCapabilities.Transactions | ProtocolCapabilities.SecureConnection | ProtocolCapabilities.MultiStatements | ProtocolCapabilities.MultiResults | ProtocolCapabilities.PluginAuth | ProtocolCapabilities.ConnectionAttributes | ProtocolCapabilities.PluginAuthLengthEncodedClientData; writer.Write((byte) 10); // protocol version writer.WriteNullTerminated(m_server.ServerVersion); // server version writer.Write(m_connectionId); // conection ID writer.Write(authData, 0, 8); // auth plugin data part 1 writer.Write((byte) 0); // filler writer.Write((ushort) capabilities); writer.Write((byte) CharacterSet.Utf8Binary); // character set writer.Write((ushort) 0); // status flags writer.Write((ushort) ((uint) capabilities >> 16)); writer.Write((byte) authData.Length); writer.Write(new byte[10]); // reserved writer.Write(authData, 8, authData.Length - 8); if (authData.Length - 8 < 13) writer.Write(new byte[13 - (authData.Length - 8)]); // have to write at least 13 bytes writer.Write(Encoding.UTF8.GetBytes("mysql_native_password")); if (!m_server.SuppressAuthPluginNameTerminatingNull) writer.Write((byte) 0); } private static void WriteOk(BinaryWriter writer) { writer.Write((byte) 0); // signature writer.Write((byte) 0); // 0 rows affected writer.Write((byte) 0); // last insert ID writer.Write((ushort) 0); // server status writer.Write((ushort) 0); // warning count } private static void WriteError(BinaryWriter writer, string message = "An unknown error occurred") { writer.Write((byte) 0xFF); // signature writer.Write((ushort) MySqlErrorCode.UnknownError); // error code writer.WriteRaw("#ERROR"); writer.WriteRaw(message); } readonly FakeMySqlServer m_server; readonly int m_connectionId; }
using System; using System.IO; using System.Collections.Specialized; using System.Net; using System.Text; using System.Web; using System.Security.Cryptography; using Newtonsoft.Json; using System.Security.Cryptography.X509Certificates; using System.Net.Security; namespace SteamBot { public class SteamWeb { public static string Fetch (string url, string method, NameValueCollection data = null, CookieContainer cookies = null, bool ajax = true) { HttpWebResponse response = Request (url, method, data, cookies, ajax); StreamReader reader = new StreamReader (response.GetResponseStream ()); return reader.ReadToEnd (); } public static HttpWebResponse Request (string url, string method, NameValueCollection data = null, CookieContainer cookies = null, bool ajax = true) { HttpWebRequest request = WebRequest.Create (url) as HttpWebRequest; request.Method = method; request.Accept = "text/javascript, text/html, application/xml, text/xml, */*"; request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; request.Host = "steamcommunity.com"; request.UserAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11"; request.Referer = "http://steamcommunity.com/trade/1"; if (ajax) { request.Headers.Add ("X-Requested-With", "XMLHttpRequest"); request.Headers.Add ("X-Prototype-Version", "1.7"); } // Cookies request.CookieContainer = cookies ?? new CookieContainer (); // Request data if (data != null) { string dataString = String.Join ("&", Array.ConvertAll (data.AllKeys, key => String.Format ("{0}={1}", HttpUtility.UrlEncode (key), HttpUtility.UrlEncode (data [key])) ) ); byte[] dataBytes = Encoding.ASCII.GetBytes (dataString); request.ContentLength = dataBytes.Length; Stream requestStream = request.GetRequestStream (); requestStream.Write (dataBytes, 0, dataBytes.Length); } // Get the response return request.GetResponse () as HttpWebResponse; } /// <summary> /// Executes the login by using the Steam Website. /// </summary> public static CookieCollection DoLogin (string username, string password) { var data = new NameValueCollection (); data.Add ("username", username); string response = Fetch ("https://steamcommunity.com/login/getrsakey", "POST", data, null, false); GetRsaKey rsaJSON = JsonConvert.DeserializeObject<GetRsaKey> (response); // Validate if (rsaJSON.success != true) { return null; } //RSA Encryption RSACryptoServiceProvider rsa = new RSACryptoServiceProvider (); RSAParameters rsaParameters = new RSAParameters (); rsaParameters.Exponent = HexToByte (rsaJSON.publickey_exp); rsaParameters.Modulus = HexToByte (rsaJSON.publickey_mod); rsa.ImportParameters (rsaParameters); byte[] bytePassword = Encoding.ASCII.GetBytes (password); byte[] encodedPassword = rsa.Encrypt (bytePassword, false); string encryptedBase64Password = Convert.ToBase64String (encodedPassword); SteamResult loginJson = null; CookieCollection cookies; string steamGuardText = ""; string steamGuardId = ""; do { Console.WriteLine ("SteamWeb: Logging In..."); bool captcha = loginJson != null && loginJson.captcha_needed == true; bool steamGuard = loginJson != null && loginJson.emailauth_needed == true; string time = Uri.EscapeDataString (rsaJSON.timestamp); string capGID = loginJson == null ? null : Uri.EscapeDataString (loginJson.captcha_gid); data = new NameValueCollection (); data.Add ("password", encryptedBase64Password); data.Add ("username", username); // Captcha string capText = ""; if (captcha) { Console.WriteLine ("SteamWeb: Captcha is needed."); System.Diagnostics.Process.Start ("https://steamcommunity.com/public/captcha.php?gid=" + loginJson.captcha_gid); Console.WriteLine ("SteamWeb: Type the captcha:"); capText = Uri.EscapeDataString (Console.ReadLine ()); } data.Add ("captcha_gid", captcha ? capGID : ""); data.Add ("captcha_text", captcha ? capText : ""); // Captcha end // SteamGuard if (steamGuard) { Console.WriteLine ("SteamWeb: SteamGuard is needed."); Console.WriteLine ("SteamWeb: Type the code:"); steamGuardText = Uri.EscapeDataString (Console.ReadLine ()); steamGuardId = loginJson.emailsteamid; } data.Add ("emailauth", steamGuardText); data.Add ("emailsteamid", steamGuardId); // SteamGuard end data.Add ("rsatimestamp", time); HttpWebResponse webResponse = Request ("https://steamcommunity.com/login/dologin/", "POST", data, null, false); StreamReader reader = new StreamReader (webResponse.GetResponseStream ()); string json = reader.ReadToEnd (); loginJson = JsonConvert.DeserializeObject<SteamResult> (json); cookies = webResponse.Cookies; } while (loginJson.captcha_needed == true || loginJson.emailauth_needed == true); if (loginJson.success == true) { CookieContainer c = new CookieContainer (); foreach (Cookie cookie in cookies) { c.Add (cookie); } SubmitCookies (c); return cookies; } else { Console.WriteLine ("SteamWeb Error: " + loginJson.message); return null; } } static void SubmitCookies (CookieContainer cookies) { HttpWebRequest w = WebRequest.Create ("https://steamcommunity.com/") as HttpWebRequest; w.Method = "POST"; w.ContentType = "application/x-www-form-urlencoded"; w.CookieContainer = cookies; w.GetResponse ().Close (); // Why would you need to do this? Reading the response isn't nessicary, since // you submitted the request already. //string result = new StreamReader (response.GetResponseStream ()).ReadToEnd (); //response.Close (); return; } static byte[] HexToByte (string hex) { if (hex.Length % 2 == 1) throw new Exception ("The binary key cannot have an odd number of digits"); byte[] arr = new byte[hex.Length >> 1]; int l = hex.Length; for (int i = 0; i < (l >> 1); ++i) { arr [i] = (byte)((GetHexVal (hex [i << 1]) << 4) + (GetHexVal (hex [(i << 1) + 1]))); } return arr; } static int GetHexVal (char hex) { int val = (int)hex; return val - (val < 58 ? 48 : 55); } public static bool ValidateRemoteCertificate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) { // allow all certificates return true; } } // JSON Classes public class GetRsaKey { public bool success { get; set; } public string publickey_mod { get; set; } public string publickey_exp { get; set; } public string timestamp { get; set; } } public class SteamResult { public bool success { get; set; } public string message { get; set; } public bool captcha_needed { get; set; } public string captcha_gid { get; set; } public bool emailauth_needed { get; set; } public string emailsteamid { get; set; } } }
// Inflater.cs // // Copyright (C) 2001 Mike Krueger // Copyright (C) 2004 John Reilly // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. // ************************************************************************* // // Name: Inflater.cs // // Created: 19-02-2008 SharedCache.com, rschuetz // Modified: 19-02-2008 SharedCache.com, rschuetz : Creation // ************************************************************************* using System; using MergeSystem.Indexus.WinServiceCommon.SharpZipLib.Checksum; using MergeSystem.Indexus.WinServiceCommon.SharpZipLib.Zip.Compression.Streams; namespace MergeSystem.Indexus.WinServiceCommon.SharpZipLib.Zip.Compression { /// <summary> /// Inflater is used to decompress data that has been compressed according /// to the "deflate" standard described in rfc1951. /// /// By default Zlib (rfc1950) headers and footers are expected in the input. /// You can use constructor <code> public Inflater(bool noHeader)</code> passing true /// if there is no Zlib header information /// /// The usage is as following. First you have to set some input with /// <code>SetInput()</code>, then Inflate() it. If inflate doesn't /// inflate any bytes there may be three reasons: /// <ul> /// <li>IsNeedingInput() returns true because the input buffer is empty. /// You have to provide more input with <code>SetInput()</code>. /// NOTE: IsNeedingInput() also returns true when, the stream is finished. /// </li> /// <li>IsNeedingDictionary() returns true, you have to provide a preset /// dictionary with <code>SetDictionary()</code>.</li> /// <li>IsFinished returns true, the inflater has finished.</li> /// </ul> /// Once the first output byte is produced, a dictionary will not be /// needed at a later stage. /// /// author of the original java version : John Leuner, Jochen Hoenicke /// </summary> public class Inflater { #region Constants/Readonly /// <summary> /// Copy lengths for literal codes 257..285 /// </summary> static readonly int[] CPLENS = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 }; /// <summary> /// Extra bits for literal codes 257..285 /// </summary> static readonly int[] CPLEXT = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 }; /// <summary> /// Copy offsets for distance codes 0..29 /// </summary> static readonly int[] CPDIST = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577 }; /// <summary> /// Extra bits for distance codes /// </summary> static readonly int[] CPDEXT = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }; /// <summary> /// These are the possible states for an inflater /// </summary> const int DECODE_HEADER = 0; const int DECODE_DICT = 1; const int DECODE_BLOCKS = 2; const int DECODE_STORED_LEN1 = 3; const int DECODE_STORED_LEN2 = 4; const int DECODE_STORED = 5; const int DECODE_DYN_HEADER = 6; const int DECODE_HUFFMAN = 7; const int DECODE_HUFFMAN_LENBITS = 8; const int DECODE_HUFFMAN_DIST = 9; const int DECODE_HUFFMAN_DISTBITS = 10; const int DECODE_CHKSUM = 11; const int FINISHED = 12; #endregion #region Instance Fields /// <summary> /// This variable contains the current state. /// </summary> int mode; /// <summary> /// The adler checksum of the dictionary or of the decompressed /// stream, as it is written in the header resp. footer of the /// compressed stream. /// Only valid if mode is DECODE_DICT or DECODE_CHKSUM. /// </summary> int readAdler; /// <summary> /// The number of bits needed to complete the current state. This /// is valid, if mode is DECODE_DICT, DECODE_CHKSUM, /// DECODE_HUFFMAN_LENBITS or DECODE_HUFFMAN_DISTBITS. /// </summary> int neededBits; int repLength; int repDist; int uncomprLen; /// <summary> /// True, if the last block flag was set in the last block of the /// inflated stream. This means that the stream ends after the /// current block. /// </summary> bool isLastBlock; /// <summary> /// The total number of inflated bytes. /// </summary> long totalOut; /// <summary> /// The total number of bytes set with setInput(). This is not the /// value returned by the TotalIn property, since this also includes the /// unprocessed input. /// </summary> long totalIn; /// <summary> /// This variable stores the noHeader flag that was given to the constructor. /// True means, that the inflated stream doesn't contain a Zlib header or /// footer. /// </summary> bool noHeader; StreamManipulator input; OutputWindow outputWindow; InflaterDynHeader dynHeader; InflaterHuffmanTree litlenTree, distTree; Adler32 adler; #endregion #region Constructors /// <summary> /// Creates a new inflater or RFC1951 decompressor /// RFC1950/Zlib headers and footers will be expected in the input data /// </summary> public Inflater() : this(false) { } /// <summary> /// Creates a new inflater. /// </summary> /// <param name="noHeader"> /// True if no RFC1950/Zlib header and footer fields are expected in the input data /// /// This is used for GZIPed/Zipped input. /// /// For compatibility with /// Sun JDK you should provide one byte of input more than needed in /// this case. /// </param> public Inflater(bool noHeader) { this.noHeader = noHeader; this.adler = new Adler32(); input = new StreamManipulator(); outputWindow = new OutputWindow(); mode = noHeader ? DECODE_BLOCKS : DECODE_HEADER; } #endregion /// <summary> /// Resets the inflater so that a new stream can be decompressed. All /// pending input and output will be discarded. /// </summary> public void Reset() { mode = noHeader ? DECODE_BLOCKS : DECODE_HEADER; totalIn = 0; totalOut = 0; input.Reset(); outputWindow.Reset(); dynHeader = null; litlenTree = null; distTree = null; isLastBlock = false; adler.Reset(); } /// <summary> /// Decodes a zlib/RFC1950 header. /// </summary> /// <returns> /// False if more input is needed. /// </returns> /// <exception cref="SharpZipBaseException"> /// The header is invalid. /// </exception> private bool DecodeHeader() { int header = input.PeekBits(16); if (header < 0) { return false; } input.DropBits(16); // The header is written in "wrong" byte order header = ((header << 8) | (header >> 8)) & 0xffff; if (header % 31 != 0) { throw new SharpZipBaseException("Header checksum illegal"); } if ((header & 0x0f00) != (Deflater.DEFLATED << 8)) { throw new SharpZipBaseException("Compression Method unknown"); } /* Maximum size of the backwards window in bits. * We currently ignore this, but we could use it to make the * inflater window more space efficient. On the other hand the * full window (15 bits) is needed most times, anyway. int max_wbits = ((header & 0x7000) >> 12) + 8; */ if ((header & 0x0020) == 0) { // Dictionary flag? mode = DECODE_BLOCKS; } else { mode = DECODE_DICT; neededBits = 32; } return true; } /// <summary> /// Decodes the dictionary checksum after the deflate header. /// </summary> /// <returns> /// False if more input is needed. /// </returns> private bool DecodeDict() { while (neededBits > 0) { int dictByte = input.PeekBits(8); if (dictByte < 0) { return false; } input.DropBits(8); readAdler = (readAdler << 8) | dictByte; neededBits -= 8; } return false; } /// <summary> /// Decodes the huffman encoded symbols in the input stream. /// </summary> /// <returns> /// false if more input is needed, true if output window is /// full or the current block ends. /// </returns> /// <exception cref="SharpZipBaseException"> /// if deflated stream is invalid. /// </exception> private bool DecodeHuffman() { int free = outputWindow.GetFreeSpace(); while (free >= 258) { int symbol; switch (mode) { case DECODE_HUFFMAN: // This is the inner loop so it is optimized a bit while (((symbol = litlenTree.GetSymbol(input)) & ~0xff) == 0) { outputWindow.Write(symbol); if (--free < 258) { return true; } } if (symbol < 257) { if (symbol < 0) { return false; } else { // symbol == 256: end of block distTree = null; litlenTree = null; mode = DECODE_BLOCKS; return true; } } try { repLength = CPLENS[symbol - 257]; neededBits = CPLEXT[symbol - 257]; } catch (Exception) { throw new SharpZipBaseException("Illegal rep length code"); } goto case DECODE_HUFFMAN_LENBITS; // fall through case DECODE_HUFFMAN_LENBITS: if (neededBits > 0) { mode = DECODE_HUFFMAN_LENBITS; int i = input.PeekBits(neededBits); if (i < 0) { return false; } input.DropBits(neededBits); repLength += i; } mode = DECODE_HUFFMAN_DIST; goto case DECODE_HUFFMAN_DIST; // fall through case DECODE_HUFFMAN_DIST: symbol = distTree.GetSymbol(input); if (symbol < 0) { return false; } try { repDist = CPDIST[symbol]; neededBits = CPDEXT[symbol]; } catch (Exception) { throw new SharpZipBaseException("Illegal rep dist code"); } goto case DECODE_HUFFMAN_DISTBITS; // fall through case DECODE_HUFFMAN_DISTBITS: if (neededBits > 0) { mode = DECODE_HUFFMAN_DISTBITS; int i = input.PeekBits(neededBits); if (i < 0) { return false; } input.DropBits(neededBits); repDist += i; } outputWindow.Repeat(repLength, repDist); free -= repLength; mode = DECODE_HUFFMAN; break; default: throw new SharpZipBaseException("Inflater unknown mode"); } } return true; } /// <summary> /// Decodes the adler checksum after the deflate stream. /// </summary> /// <returns> /// false if more input is needed. /// </returns> /// <exception cref="SharpZipBaseException"> /// If checksum doesn't match. /// </exception> private bool DecodeChksum() { while (neededBits > 0) { int chkByte = input.PeekBits(8); if (chkByte < 0) { return false; } input.DropBits(8); readAdler = (readAdler << 8) | chkByte; neededBits -= 8; } if ((int)adler.Value != readAdler) { throw new SharpZipBaseException("Adler chksum doesn't match: " + (int)adler.Value + " vs. " + readAdler); } mode = FINISHED; return false; } /// <summary> /// Decodes the deflated stream. /// </summary> /// <returns> /// false if more input is needed, or if finished. /// </returns> /// <exception cref="SharpZipBaseException"> /// if deflated stream is invalid. /// </exception> private bool Decode() { switch (mode) { case DECODE_HEADER: return DecodeHeader(); case DECODE_DICT: return DecodeDict(); case DECODE_CHKSUM: return DecodeChksum(); case DECODE_BLOCKS: if (isLastBlock) { if (noHeader) { mode = FINISHED; return false; } else { input.SkipToByteBoundary(); neededBits = 32; mode = DECODE_CHKSUM; return true; } } int type = input.PeekBits(3); if (type < 0) { return false; } input.DropBits(3); if ((type & 1) != 0) { isLastBlock = true; } switch (type >> 1) { case DeflaterConstants.STORED_BLOCK: input.SkipToByteBoundary(); mode = DECODE_STORED_LEN1; break; case DeflaterConstants.STATIC_TREES: litlenTree = InflaterHuffmanTree.defLitLenTree; distTree = InflaterHuffmanTree.defDistTree; mode = DECODE_HUFFMAN; break; case DeflaterConstants.DYN_TREES: dynHeader = new InflaterDynHeader(); mode = DECODE_DYN_HEADER; break; default: throw new SharpZipBaseException("Unknown block type " + type); } return true; case DECODE_STORED_LEN1: { if ((uncomprLen = input.PeekBits(16)) < 0) { return false; } input.DropBits(16); mode = DECODE_STORED_LEN2; } goto case DECODE_STORED_LEN2; // fall through case DECODE_STORED_LEN2: { int nlen = input.PeekBits(16); if (nlen < 0) { return false; } input.DropBits(16); if (nlen != (uncomprLen ^ 0xffff)) { throw new SharpZipBaseException("broken uncompressed block"); } mode = DECODE_STORED; } goto case DECODE_STORED; // fall through case DECODE_STORED: { int more = outputWindow.CopyStored(input, uncomprLen); uncomprLen -= more; if (uncomprLen == 0) { mode = DECODE_BLOCKS; return true; } return !input.IsNeedingInput; } case DECODE_DYN_HEADER: if (!dynHeader.Decode(input)) { return false; } litlenTree = dynHeader.BuildLitLenTree(); distTree = dynHeader.BuildDistTree(); mode = DECODE_HUFFMAN; goto case DECODE_HUFFMAN; // fall through case DECODE_HUFFMAN: case DECODE_HUFFMAN_LENBITS: case DECODE_HUFFMAN_DIST: case DECODE_HUFFMAN_DISTBITS: return DecodeHuffman(); case FINISHED: return false; default: throw new SharpZipBaseException("Inflater.Decode unknown mode"); } } /// <summary> /// Sets the preset dictionary. This should only be called, if /// needsDictionary() returns true and it should set the same /// dictionary, that was used for deflating. The getAdler() /// function returns the checksum of the dictionary needed. /// </summary> /// <param name="buffer"> /// The dictionary. /// </param> public void SetDictionary(byte[] buffer) { SetDictionary(buffer, 0, buffer.Length); } /// <summary> /// Sets the preset dictionary. This should only be called, if /// needsDictionary() returns true and it should set the same /// dictionary, that was used for deflating. The getAdler() /// function returns the checksum of the dictionary needed. /// </summary> /// <param name="buffer"> /// The dictionary. /// </param> /// <param name="index"> /// The index into buffer where the dictionary starts. /// </param> /// <param name="count"> /// The number of bytes in the dictionary. /// </param> /// <exception cref="System.InvalidOperationException"> /// No dictionary is needed. /// </exception> /// <exception cref="SharpZipBaseException"> /// The adler checksum for the buffer is invalid /// </exception> public void SetDictionary(byte[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (index < 0) { throw new ArgumentOutOfRangeException("index"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (!IsNeedingDictionary) { throw new InvalidOperationException("Dictionary is not needed"); } adler.Update(buffer, index, count); if ((int)adler.Value != readAdler) { throw new SharpZipBaseException("Wrong adler checksum"); } adler.Reset(); outputWindow.CopyDict(buffer, index, count); mode = DECODE_BLOCKS; } /// <summary> /// Sets the input. This should only be called, if needsInput() /// returns true. /// </summary> /// <param name="buffer"> /// the input. /// </param> public void SetInput(byte[] buffer) { SetInput(buffer, 0, buffer.Length); } /// <summary> /// Sets the input. This should only be called, if needsInput() /// returns true. /// </summary> /// <param name="buffer"> /// The source of input data /// </param> /// <param name="index"> /// The index into buffer where the input starts. /// </param> /// <param name="count"> /// The number of bytes of input to use. /// </param> /// <exception cref="System.InvalidOperationException"> /// No input is needed. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// The index and/or count are wrong. /// </exception> public void SetInput(byte[] buffer, int index, int count) { input.SetInput(buffer, index, count); totalIn += (long)count; } /// <summary> /// Inflates the compressed stream to the output buffer. If this /// returns 0, you should check, whether IsNeedingDictionary(), /// IsNeedingInput() or IsFinished() returns true, to determine why no /// further output is produced. /// </summary> /// <param name="buffer"> /// the output buffer. /// </param> /// <returns> /// The number of bytes written to the buffer, 0 if no further /// output can be produced. /// </returns> /// <exception cref="System.ArgumentOutOfRangeException"> /// if buffer has length 0. /// </exception> /// <exception cref="System.FormatException"> /// if deflated stream is invalid. /// </exception> public int Inflate(byte[] buffer) { if (buffer == null) { throw new ArgumentNullException("buffer"); } return Inflate(buffer, 0, buffer.Length); } /// <summary> /// Inflates the compressed stream to the output buffer. If this /// returns 0, you should check, whether needsDictionary(), /// needsInput() or finished() returns true, to determine why no /// further output is produced. /// </summary> /// <param name="buffer"> /// the output buffer. /// </param> /// <param name="offset"> /// the offset in buffer where storing starts. /// </param> /// <param name="count"> /// the maximum number of bytes to output. /// </param> /// <returns> /// the number of bytes written to the buffer, 0 if no further output can be produced. /// </returns> /// <exception cref="System.ArgumentOutOfRangeException"> /// if count is less than 0. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// if the index and / or count are wrong. /// </exception> /// <exception cref="System.FormatException"> /// if deflated stream is invalid. /// </exception> public int Inflate(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (count < 0) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("count"); #else throw new ArgumentOutOfRangeException("count", "count cannot be negative"); #endif } if (offset < 0) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("offset"); #else throw new ArgumentOutOfRangeException("offset", "offset cannot be negative"); #endif } if (offset + count > buffer.Length) { throw new ArgumentException("count exceeds buffer bounds"); } // Special case: count may be zero if (count == 0) { if (!IsFinished) { // -jr- 08-Nov-2003 INFLATE_BUG fix.. Decode(); } return 0; } int bytesCopied = 0; do { if (mode != DECODE_CHKSUM) { /* Don't give away any output, if we are waiting for the * checksum in the input stream. * * With this trick we have always: * IsNeedingInput() and not IsFinished() * implies more output can be produced. */ int more = outputWindow.CopyOutput(buffer, offset, count); if (more > 0) { adler.Update(buffer, offset, more); offset += more; bytesCopied += more; totalOut += (long)more; count -= more; if (count == 0) { return bytesCopied; } } } } while (Decode() || ((outputWindow.GetAvailable() > 0) && (mode != DECODE_CHKSUM))); return bytesCopied; } /// <summary> /// Returns true, if the input buffer is empty. /// You should then call setInput(). /// NOTE: This method also returns true when the stream is finished. /// </summary> public bool IsNeedingInput { get { return input.IsNeedingInput; } } /// <summary> /// Returns true, if a preset dictionary is needed to inflate the input. /// </summary> public bool IsNeedingDictionary { get { return mode == DECODE_DICT && neededBits == 0; } } /// <summary> /// Returns true, if the inflater has finished. This means, that no /// input is needed and no output can be produced. /// </summary> public bool IsFinished { get { return mode == FINISHED && outputWindow.GetAvailable() == 0; } } /// <summary> /// Gets the adler checksum. This is either the checksum of all /// uncompressed bytes returned by inflate(), or if needsDictionary() /// returns true (and thus no output was yet produced) this is the /// adler checksum of the expected dictionary. /// </summary> /// <returns> /// the adler checksum. /// </returns> public int Adler { get { return IsNeedingDictionary ? readAdler : (int)adler.Value; } } /// <summary> /// Gets the total number of output bytes returned by Inflate(). /// </summary> /// <returns> /// the total number of output bytes. /// </returns> public long TotalOut { get { return totalOut; } } /// <summary> /// Gets the total number of processed compressed input bytes. /// </summary> /// <returns> /// The total number of bytes of processed input bytes. /// </returns> public long TotalIn { get { return totalIn - (long)RemainingInput; } } /// <summary> /// Gets the number of unprocessed input bytes. Useful, if the end of the /// stream is reached and you want to further process the bytes after /// the deflate stream. /// </summary> /// <returns> /// The number of bytes of the input which have not been processed. /// </returns> public int RemainingInput { // TODO: This should be a long? get { return input.AvailableBytes; } } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Searchservice { using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for Indexers. /// </summary> public static partial class IndexersExtensions { /// <summary> /// Resets the change tracking state associated with an Azure Search indexer. /// <see href="https://msdn.microsoft.com/library/azure/dn946897.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexerName'> /// The name of the indexer to reset. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static void Reset(this IIndexers operations, string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { operations.ResetAsync(indexerName, searchRequestOptions).GetAwaiter().GetResult(); } /// <summary> /// Resets the change tracking state associated with an Azure Search indexer. /// <see href="https://msdn.microsoft.com/library/azure/dn946897.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexerName'> /// The name of the indexer to reset. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task ResetAsync(this IIndexers operations, string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.ResetWithHttpMessagesAsync(indexerName, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Runs an Azure Search indexer on-demand. /// <see href="https://msdn.microsoft.com/library/azure/dn946885.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexerName'> /// The name of the indexer to run. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static void Run(this IIndexers operations, string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { operations.RunAsync(indexerName, searchRequestOptions).GetAwaiter().GetResult(); } /// <summary> /// Runs an Azure Search indexer on-demand. /// <see href="https://msdn.microsoft.com/library/azure/dn946885.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexerName'> /// The name of the indexer to run. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task RunAsync(this IIndexers operations, string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.RunWithHttpMessagesAsync(indexerName, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Creates a new Azure Search indexer or updates an indexer if it already /// exists. /// <see href="https://msdn.microsoft.com/library/azure/dn946899.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexerName'> /// The name of the indexer to create or update. /// </param> /// <param name='indexer'> /// The definition of the indexer to create or update. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static Indexer CreateOrUpdate(this IIndexers operations, string indexerName, Indexer indexer, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { return operations.CreateOrUpdateAsync(indexerName, indexer, searchRequestOptions).GetAwaiter().GetResult(); } /// <summary> /// Creates a new Azure Search indexer or updates an indexer if it already /// exists. /// <see href="https://msdn.microsoft.com/library/azure/dn946899.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexerName'> /// The name of the indexer to create or update. /// </param> /// <param name='indexer'> /// The definition of the indexer to create or update. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Indexer> CreateOrUpdateAsync(this IIndexers operations, string indexerName, Indexer indexer, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(indexerName, indexer, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes an Azure Search indexer. /// <see href="https://msdn.microsoft.com/library/azure/dn946898.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexerName'> /// The name of the indexer to delete. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static void Delete(this IIndexers operations, string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { operations.DeleteAsync(indexerName, searchRequestOptions).GetAwaiter().GetResult(); } /// <summary> /// Deletes an Azure Search indexer. /// <see href="https://msdn.microsoft.com/library/azure/dn946898.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexerName'> /// The name of the indexer to delete. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IIndexers operations, string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(indexerName, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Retrieves an indexer definition from Azure Search. /// <see href="https://msdn.microsoft.com/library/azure/dn946874.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexerName'> /// The name of the indexer to retrieve. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static Indexer Get(this IIndexers operations, string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { return operations.GetAsync(indexerName, searchRequestOptions).GetAwaiter().GetResult(); } /// <summary> /// Retrieves an indexer definition from Azure Search. /// <see href="https://msdn.microsoft.com/library/azure/dn946874.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexerName'> /// The name of the indexer to retrieve. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Indexer> GetAsync(this IIndexers operations, string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(indexerName, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all indexers available for an Azure Search service. /// <see href="https://msdn.microsoft.com/library/azure/dn946883.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static IndexerListResult List(this IIndexers operations, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { return operations.ListAsync(searchRequestOptions).GetAwaiter().GetResult(); } /// <summary> /// Lists all indexers available for an Azure Search service. /// <see href="https://msdn.microsoft.com/library/azure/dn946883.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IndexerListResult> ListAsync(this IIndexers operations, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(searchRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates a new Azure Search indexer. /// <see href="https://msdn.microsoft.com/library/azure/dn946899.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexer'> /// The definition of the indexer to create. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static Indexer Create(this IIndexers operations, Indexer indexer, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { return operations.CreateAsync(indexer, searchRequestOptions).GetAwaiter().GetResult(); } /// <summary> /// Creates a new Azure Search indexer. /// <see href="https://msdn.microsoft.com/library/azure/dn946899.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexer'> /// The definition of the indexer to create. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Indexer> CreateAsync(this IIndexers operations, Indexer indexer, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(indexer, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Returns the current status and execution history of an indexer. /// <see href="https://msdn.microsoft.com/library/azure/dn946884.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexerName'> /// The name of the indexer for which to retrieve status. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static IndexerExecutionInfo GetStatus(this IIndexers operations, string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { return operations.GetStatusAsync(indexerName, searchRequestOptions).GetAwaiter().GetResult(); } /// <summary> /// Returns the current status and execution history of an indexer. /// <see href="https://msdn.microsoft.com/library/azure/dn946884.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexerName'> /// The name of the indexer for which to retrieve status. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IndexerExecutionInfo> GetStatusAsync(this IIndexers operations, string indexerName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetStatusWithHttpMessagesAsync(indexerName, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading; namespace System.Dynamic.Utils { internal static class ExpressionUtils { public static ReadOnlyCollection<T> ReturnReadOnly<T>(ref IList<T> collection) { IList<T> value = collection; // if it's already read-only just return it. ReadOnlyCollection<T> res = value as ReadOnlyCollection<T>; if (res != null) { return res; } // otherwise make sure only readonly collection every gets exposed Interlocked.CompareExchange<IList<T>>( ref collection, value.ToReadOnly(), value ); // and return it return (ReadOnlyCollection<T>)collection; } /// <summary> /// Helper used for ensuring we only return 1 instance of a ReadOnlyCollection of T. /// /// This is similar to the ReturnReadOnly of T. This version supports nodes which hold /// onto multiple Expressions where one is typed to object. That object field holds either /// an expression or a ReadOnlyCollection of Expressions. When it holds a ReadOnlyCollection /// the IList which backs it is a ListArgumentProvider which uses the Expression which /// implements IArgumentProvider to get 2nd and additional values. The ListArgumentProvider /// continues to hold onto the 1st expression. /// /// This enables users to get the ReadOnlyCollection w/o it consuming more memory than if /// it was just an array. Meanwhile The DLR internally avoids accessing which would force /// the readonly collection to be created resulting in a typical memory savings. /// </summary> public static ReadOnlyCollection<Expression> ReturnReadOnly(IArgumentProvider provider, ref object collection) { Expression tObj = collection as Expression; if (tObj != null) { // otherwise make sure only one readonly collection ever gets exposed Interlocked.CompareExchange( ref collection, new ReadOnlyCollection<Expression>(new ListArgumentProvider(provider, tObj)), tObj ); } // and return what is not guaranteed to be a readonly collection return (ReadOnlyCollection<Expression>)collection; } /// <summary> /// Helper which is used for specialized subtypes which use ReturnReadOnly(ref object, ...). /// This is the reverse version of ReturnReadOnly which takes an IArgumentProvider. /// /// This is used to return the 1st argument. The 1st argument is typed as object and either /// contains a ReadOnlyCollection or the Expression. We check for the Expression and if it's /// present we return that, otherwise we return the 1st element of the ReadOnlyCollection. /// </summary> public static T ReturnObject<T>(object collectionOrT) where T : class { T t = collectionOrT as T; if (t != null) { return t; } return ((ReadOnlyCollection<T>)collectionOrT)[0]; } public static void ValidateArgumentTypes(MethodBase method, ExpressionType nodeKind, ref ReadOnlyCollection<Expression> arguments) { Debug.Assert(nodeKind == ExpressionType.Invoke || nodeKind == ExpressionType.Call || nodeKind == ExpressionType.Dynamic || nodeKind == ExpressionType.New); ParameterInfo[] pis = GetParametersForValidation(method, nodeKind); ValidateArgumentCount(method, nodeKind, arguments.Count, pis); Expression[] newArgs = null; for (int i = 0, n = pis.Length; i < n; i++) { Expression arg = arguments[i]; ParameterInfo pi = pis[i]; arg = ValidateOneArgument(method, nodeKind, arg, pi); if (newArgs == null && arg != arguments[i]) { newArgs = new Expression[arguments.Count]; for (int j = 0; j < i; j++) { newArgs[j] = arguments[j]; } } if (newArgs != null) { newArgs[i] = arg; } } if (newArgs != null) { arguments = new TrueReadOnlyCollection<Expression>(newArgs); } } public static void ValidateArgumentCount(MethodBase method, ExpressionType nodeKind, int count, ParameterInfo[] pis) { if (pis.Length != count) { // Throw the right error for the node we were given switch (nodeKind) { case ExpressionType.New: throw Error.IncorrectNumberOfConstructorArguments(); case ExpressionType.Invoke: throw Error.IncorrectNumberOfLambdaArguments(); case ExpressionType.Dynamic: case ExpressionType.Call: throw Error.IncorrectNumberOfMethodCallArguments(method); default: throw ContractUtils.Unreachable; } } } public static Expression ValidateOneArgument(MethodBase method, ExpressionType nodeKind, Expression arguments, ParameterInfo pi) { RequiresCanRead(arguments, nameof(arguments)); Type pType = pi.ParameterType; if (pType.IsByRef) { pType = pType.GetElementType(); } TypeUtils.ValidateType(pType); if (!TypeUtils.AreReferenceAssignable(pType, arguments.Type)) { if (!TryQuote(pType, ref arguments)) { // Throw the right error for the node we were given switch (nodeKind) { case ExpressionType.New: throw Error.ExpressionTypeDoesNotMatchConstructorParameter(arguments.Type, pType); case ExpressionType.Invoke: throw Error.ExpressionTypeDoesNotMatchParameter(arguments.Type, pType); case ExpressionType.Dynamic: case ExpressionType.Call: throw Error.ExpressionTypeDoesNotMatchMethodParameter(arguments.Type, pType, method); default: throw ContractUtils.Unreachable; } } } return arguments; } public static void RequiresCanRead(Expression expression, string paramName) { if (expression == null) { throw new ArgumentNullException(paramName); } // validate that we can read the node switch (expression.NodeType) { case ExpressionType.Index: IndexExpression index = (IndexExpression)expression; if (index.Indexer != null && !index.Indexer.CanRead) { throw new ArgumentException(Strings.ExpressionMustBeReadable, paramName); } break; case ExpressionType.MemberAccess: MemberExpression member = (MemberExpression)expression; PropertyInfo prop = member.Member as PropertyInfo; if (prop != null) { if (!prop.CanRead) { throw new ArgumentException(Strings.ExpressionMustBeReadable, paramName); } } break; } } // Attempts to auto-quote the expression tree. Returns true if it succeeded, false otherwise. public static bool TryQuote(Type parameterType, ref Expression argument) { // We used to allow quoting of any expression, but the behavior of // quote (produce a new tree closed over parameter values), only // works consistently for lambdas Type quoteable = typeof(LambdaExpression); if (TypeUtils.IsSameOrSubclass(quoteable, parameterType) && parameterType.IsAssignableFrom(argument.GetType())) { argument = Expression.Quote(argument); return true; } return false; } internal static ParameterInfo[] GetParametersForValidation(MethodBase method, ExpressionType nodeKind) { ParameterInfo[] pis = method.GetParametersCached(); if (nodeKind == ExpressionType.Dynamic) { pis = pis.RemoveFirst(); // ignore CallSite argument } return pis; } } }
//----------------------------------------------------------------------------- // // <copyright file="CompressStream.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: // Emulates a fully functional stream that persists using the Deflate compression algorithm // // This class provides a fully functional Stream on a restricted functionality compression // stream (System.IO.Compression.DeflateStream). // // CompressStream operates in "transparent" mode (ReadThrough or WriteThrough) as long as possible for efficiency, // reverting to full emulation mode as required to satisfy Stream requests that would violate the capabilities // of the DeflateStream that actually does the reading or writing (decompress or compress). Emulation // mode is implemented by class CompressEmulationStream. // // Note that the reason we need these modes is that DeflateStream is entirely modal in nature once // constructed. If it is created in "compress" mode, it can only be used for compression. If it is // opened in "decompress" mode, it can only be used for decompression. This means that Reading is only // natively support in decompress mode, and writing is only natively supported in compress mode. // // Notes: // If baseStream is non-seekable and non-readable it is not possible to enter Emulation mode. In this case // we need to throw appropriate exception. // // History: // 08/02/2004: BruceMac: Initial implementation. //----------------------------------------------------------------------------- using System; using System.IO; using System.IO.Compression; // for DeflateStream using System.Diagnostics; using System.IO.Packaging; using MS.Internal.IO.Zip; using System.Windows; using MS.Internal.WindowsBase; namespace MS.Internal.IO.Packaging { //------------------------------------------------------ // // Internal Members // //------------------------------------------------------ /// <summary> /// Emulates a fully functional stream that persists using the Deflate compression algorithm /// </summary> /// <remarks>Attempts to provide ReadThrough or WriteThrough functionality as possible. If not possible, /// a CompressEmulationStream is created and work is delegated to that class.</remarks> internal class CompressStream : Stream { //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Stream Methods /// <summary> /// Return the bytes requested from the container /// </summary> /// <param name="buffer">destination buffer</param> /// <param name="offset">offset to write into that buffer</param> /// <param name="count">how many bytes requested</param> /// <returns>how many bytes were written into <paramref name="buffer" />.</returns> /// <remarks> /// The underlying stream, expected to be a DeflateStream or a CompressEmulationStream, /// is in charge of leaving the IO position unchanged in case of an exception. /// </remarks> public override int Read(byte[] buffer, int offset, int count) { CheckDisposed(); PackagingUtilities.VerifyStreamReadArgs(this, buffer, offset, count); // no-op if (count == 0) return 0; checked // catch any integer overflows { switch (_mode) { case Mode.Start: { // skip to the correct logical position if necessary (DeflateStream starts at position zero) if (_position == 0) { // enter ReadPassThrough mode if it is efficient ChangeMode(Mode.ReadPassThrough); } else ChangeMode(Mode.Emulation); break; } case Mode.ReadPassThrough: // continue in ReadPassThrough mode case Mode.Emulation: // continue to read from existing emulation stream { break; } case Mode.WritePassThrough: // enter Emulation mode { // optimization - if they are trying to jump back to the start to read, simply jump to ReadPassThrough mode if (_position == 0) ChangeMode(Mode.ReadPassThrough); else ChangeMode(Mode.Emulation); break; } default: Debug.Assert(false, "Illegal state for CompressStream - logic error"); break; } // we might be in Start mode now if we are beyond the end of stream - just return zero if (_current == null) return 0; int bytesRead = _current.Read(buffer, offset, count); // optimization for ReadPassThrough mode - we actually know the length because we ran out of bytes if (_mode == Mode.ReadPassThrough && bytesRead == 0) { // possible first chance to set and verify length from header against real data length UpdateUncompressedDataLength(_position); // since we've exhausted the deflateStream, discard it to reduce working set ChangeMode(Mode.Start); } // Stream contract - don't update position until we are certain that no exceptions have occurred _position += bytesRead; return bytesRead; } } /// <summary> /// Write /// </summary> /// <remarks>Note that zero length write to deflate stream actually results in a stream containing 2 bytes. This is /// required to maintain compatibility with the standard.</remarks> public override void Write(byte[] buffer, int offset, int count) { CheckDisposed(); PackagingUtilities.VerifyStreamWriteArgs(this, buffer, offset, count); // no-op if (count == 0) return; checked { switch (_mode) { case Mode.Start: // enter WritePassThrough mode if possible { // Special case: If stream has existing content, we need to go straight // to Emulation mode otherwise we'll potentially destroy existing data. // Don't bother entering WritePassThroughMode if position is non-zero because // we'll just enter emulation later. if (_position == 0 && IsDeflateStreamEmpty(_baseStream)) ChangeMode(Mode.WritePassThrough); else ChangeMode(Mode.Emulation); break; } case Mode.WritePassThrough: // continue in Write mode case Mode.Emulation: // continue to read from existing emulation stream { break; } case Mode.ReadPassThrough: // enter Emulation mode { ChangeMode(Mode.Emulation); break; } default: Debug.Assert(false, "Illegal state for CompressStream - logic error"); break; } _current.Write(buffer, offset, count); _position += count; } // keep track of the current length in case someone asks for it if (_mode == Mode.WritePassThrough) CachedLength = _position; _dirtyForFlushing= true; _dirtyForClosing= true; } /// <summary> /// Seek /// </summary> /// <param name="offset">offset</param> /// <param name="origin">origin</param> /// <returns>zero</returns> public override long Seek(long offset, SeekOrigin origin) { CheckDisposed(); if (!CanSeek) throw new NotSupportedException(SR.Get(SRID.SeekNotSupported)); checked { // Calculate newPos // If origin is Begin or Current newPos can be calculated without knowing // the stream length. If origin is End, switch to Emulation immediately. long newPos = -1; switch (origin) { case SeekOrigin.Begin: newPos = offset; break; case SeekOrigin.Current: newPos = _position + offset; break; case SeekOrigin.End: ChangeMode(Mode.Emulation); // has no effect if already in Emulation mode newPos = Length + offset; // Length is now legal to call break; } // we have a reliable newPos now - throw if its illegal if (newPos < 0) throw new ArgumentException(SR.Get(SRID.SeekNegative)); // is the new position any different than the current position? long delta = newPos - _position; if (delta == 0) return _position; // We optimize for very restricted case - short seek forward in read-only mode. // This prevents the expense of entering Emulation mode when a stream reader is // skipping a few bytes while parsing binary data structures (for example). if ((delta > 0) && (delta < _readPassThroughModeSeekThreshold) && (_mode == Mode.ReadPassThrough)) { // We're able to fake the seek by reading in this one corner case. // We cannot be in ReadPassThroughMode if currently beyond end of physical // data so it is safe to assume that the value returned from // this call represents real data. long bytesNotRead = ReadPassThroughModeSeek(delta); if (bytesNotRead > 0) { // Stream was exhausted - seek was beyond end of physical // stream so we need to update our cachedLength and // move to Start mode. UpdateUncompressedDataLength(newPos - bytesNotRead); ChangeMode(Mode.Start); } } else { // Enter Emulation for efficiency ChangeMode(Mode.Emulation); // No-op if already in Emulation _current.Position = newPos; // Update to new value } // update logical position _position = newPos; } return _position; } /// <summary> /// SetLength /// </summary> public override void SetLength(long newLength) { CheckDisposed(); if (!CanSeek) throw new NotSupportedException(SR.Get(SRID.SetLengthNotSupported)); _lengthVerified = true; // no longer need to verify our length against our constructor value switch (_mode) { case Mode.Start: case Mode.WritePassThrough: case Mode.ReadPassThrough: { // optimize for "clear the whole stream" - no need to enter emulation if (newLength == 0) { ChangeMode(Mode.Start); // discard any existing deflate stream _baseStream.SetLength(0); // clear the underlying stream UpdateUncompressedDataLength(newLength); } else ChangeMode(Mode.Emulation); break; } case Mode.Emulation: break; default: Debug.Assert(false, "Illegal state for CompressStream - logic error"); break; } if (_mode == Mode.Emulation) _current.SetLength(newLength); // position seek pointer appropriately if (newLength < _position) Seek(newLength, SeekOrigin.Begin); // still need to mark ourselves dirty so that our caller can get the correct result // when they query the IsDirty property _dirtyForFlushing= true; _dirtyForClosing= true; } /// <summary> /// Flush /// </summary> /// <remarks>Flushes to stream (if necessary)</remarks> public override void Flush() { CheckDisposed(); // Always pass through to subordinates because they may be caching things (ignore _dirty flag here). // Current must be non-null if changes have been made. if (_current != null) { _current.Flush(); _dirtyForFlushing = false; // extra flushes after this will not produce more data // avoid clearing flag when we are empty because it would prevent generation // of the 2-byte sequence on dispose if ((_mode == Mode.Emulation) && (Length != 0)) { _dirtyForClosing = false; // if it is ReadThrough or Start (it shouldn't be dirty in the first place) // if it is WriteThrough it is going to be dirty untill it is closed } } _baseStream.Flush(); } #endregion Stream Methods #region Stream Properties /// <summary> /// Current logical position within the stream /// </summary> public override long Position { get { CheckDisposed(); return _position; } set { CheckDisposed(); // convert to a Seek so we don't have to replicate the Seek logic here Seek(checked(value - _position), SeekOrigin.Current); } } /// <summary> /// Length /// </summary> public override long Length { get { CheckDisposed(); // if (!CanSeek) // throw new NotSupportedException(SR.Get(SRID.LengthNotSupported)); switch (_mode) { case Mode.Start: case Mode.WritePassThrough: case Mode.ReadPassThrough: { // use cached length if possible if (CachedLength >= 0) return CachedLength; else { // Special optimization for new/empty streams - avoid entering Emulation as long as possible. if (_position == 0 && IsDeflateStreamEmpty(_baseStream)) return 0; ChangeMode(Mode.Emulation); } break; } case Mode.Emulation: break; default: Debug.Assert(false, "Illegal state for CompressStream - logic error"); break; } // must be in Emulation mode to get here // possible first chance to verify length from header against real data length UpdateUncompressedDataLength(_current.Length); return _current.Length; } } /// <summary> /// Is stream readable? /// </summary> /// <remarks>returns false when called on disposed stream</remarks> public override bool CanRead { get { // cannot read from a close stream, but don't throw if asked return (_mode != Mode.Disposed) && _baseStream.CanRead; } } /// <summary> /// Is stream seekable - should be handled by our owner /// </summary> /// <remarks>returns false when called on disposed stream</remarks> public override bool CanSeek { get { // cannot seek on a close stream, but don't throw if asked return (_mode != Mode.Disposed) && _baseStream.CanSeek; } } /// <summary> /// Is stream writeable? /// </summary> /// <remarks>returns false when called on disposed stream</remarks> public override bool CanWrite { get { // cannot write to a close stream, but don't throw if asked return (_mode != Mode.Disposed) && _baseStream.CanWrite; } } #endregion #region Internal //------------------------------------------------------ // // Internal Constructors // //------------------------------------------------------ /// <summary> /// Constructor /// </summary> /// <param name="length">uncompressed length if known, or -1 if not known</param> /// <param name="baseStream">part stream</param> internal CompressStream(Stream baseStream, long length) : this (baseStream, length, false) { } /// <summary> /// Constructor /// </summary> /// <param name="baseStream">part stream</param> /// <param name="creating">new stream or not?</param> /// <param name="length">uncompressed length if known, or -1 if not known</param> internal CompressStream(Stream baseStream, long length, bool creating) { if (baseStream == null) throw new ArgumentNullException("baseStream"); if (length < -1) throw new ArgumentOutOfRangeException("length"); _baseStream = baseStream; _cachedLength = length; Debug.Assert(_baseStream.Position == 0, "Our logic assumes position zero and we don't seek because sometimes it's not supported"); // we need to be dirty if this is a new stream because an empty deflate // stream actually causes a write (this happens only on close ); therefore // we are dirty for close (in case of creation) and not dirty for flush _dirtyForFlushing= false; _dirtyForClosing= creating; } //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ /// <summary> /// IsDirty /// </summary> /// <value></value> internal bool IsDirty(bool closingFlag) { return closingFlag ? _dirtyForClosing : _dirtyForFlushing; } /// <summary> /// IsDisposed /// </summary> /// <value></value> internal bool IsDisposed { get { return (_mode == Mode.Disposed); } } #endregion #region Protected //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ /// <summary> /// Dispose(bool) /// </summary> /// <param name="disposing"></param> /// <remarks>We implement this because we want a consistent experience (essentially Flush our data) if the user chooses to /// call Dispose() instead of Close().</remarks> protected override void Dispose(bool disposing) { try { if (disposing) { if (_mode != Mode.Disposed) { Flush(); if (_current != null) { _current.Close(); // call Dispose() _current = null; } // Special handling for "empty" deflated streams - they actually persist // a 2 byte sequence. // Three separate cases (assuming the stream is dirty): // 1) Stream is seekable - check Length and write the 2-byte sequence // if the stream is empty. // 2) Stream is non-seekable and negative CachedLength - this means we were created // (not opened) and there have been no writes so we need the 2-byte sequence. // 3) Stream is non-seekable and zero CachedLength - this means we are // really zero-bytes long which indicates we need the 2-byte sequence. if (_dirtyForClosing && ((_baseStream.CanSeek && _baseStream.Length == 0) || (_cachedLength <= 0))) { _baseStream.Write(_emptyDeflateStreamConstant, 0, 2); _baseStream.Flush(); } // _baseStream.Close(); // never close a stream we do not own _baseStream = null; ChangeMode(Mode.Disposed); _dirtyForClosing = false; _dirtyForFlushing = false; } } } finally { base.Dispose(disposing); } } #endregion // Changed the mode from Emulation to Start internal void Reset() { CheckDisposed(); ChangeMode(Mode.Start); } #region Private //------------------------------------------------------ // // Private Properties // //------------------------------------------------------ //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ /// <summary> /// Verify Uncompressed length from data against what we were given in the constructor /// </summary> /// <param name="dataLength"></param> /// <remarks>verify length from header against real data length</remarks> private void UpdateUncompressedDataLength(long dataLength) { Debug.Assert(dataLength >= 0); // only compare if we have a value if (_cachedLength >= 0) { if (!_lengthVerified) { if (_cachedLength != dataLength) throw new FileFormatException(SR.Get(SRID.CompressLengthMismatch)); _lengthVerified = true; } } _cachedLength = dataLength; // always set } /// <summary> /// Helper method to reduce complexity in the public Seek method /// </summary> /// <param name="bytesToSeek"></param> /// <returns>bytes remaining - will be non-zero if stream was exhausted</returns> /// <remarks>Attempts to "seek" by reading an discarding bytes using the current /// Decompressing DeflateStream. /// _position is updated by our caller - this function does not change it</remarks> private long ReadPassThroughModeSeek(long bytesToSeek) { checked { Debug.Assert(bytesToSeek > 0, "Logic Error - bytesToSeek should be positive"); // allocate buffer just big enough for the seek, maximum of 4k byte[] buf = new byte[Math.Min(0x1000, bytesToSeek)]; // read to simulate Seek while (bytesToSeek > 0) { // don't exceed the buffer size long n = Math.Min(bytesToSeek, buf.Length); n = _current.Read(buf, 0, (int)n); // seek beyond end of stream is legal if (n == 0) { break; // just exit } bytesToSeek -= n; } // return bytes not read return bytesToSeek; } } /// <summary> /// Call this before accepting any public API call (except some Stream calls that /// are allowed to respond even when Closed /// </summary> private void CheckDisposed() { if (IsDisposed) throw new ObjectDisposedException(null, SR.Get(SRID.StreamObjectDisposed)); } /// <summary> /// ChangeMode /// </summary> /// <param name="newMode"></param> /// <remarks>Does not update Position of _current for change to ReadPassThroughMode.</remarks> private void ChangeMode(Mode newMode) { // ignore redundant calls (allowing these actually simplifies the logic in SetLength) if (newMode == _mode) return; // every state change requires this logic if (_current != null) { _current.Close(); _dirtyForClosing = false; _dirtyForFlushing = false; } // set the new mode - must be done before the call to Seek _mode = newMode; switch (newMode) { case Mode.Start: { _current = null; _baseStream.Position = 0; break; } case Mode.ReadPassThrough: case Mode.WritePassThrough: { Debug.Assert(_baseStream.Position == 0); // create the appropriate DeflateStream _current = new DeflateStream(_baseStream, newMode == Mode.WritePassThrough ? CompressionMode.Compress : CompressionMode.Decompress, true); break; } case Mode.Emulation: { // Create emulation stream. Use a MemoryStream for local caching. // Do not change this logic for RM cases because the data is "in the clear" and must // not be persisted in a vulnerable location. SparseMemoryStream memStream = new SparseMemoryStream(_lowWaterMark, _highWaterMark); _current = new CompressEmulationStream(_baseStream, memStream, _position, new DeflateEmulationTransform()); // verify and set length UpdateUncompressedDataLength(_current.Length); break; } case Mode.Disposed: break; default: Debug.Assert(false, "Illegal state for CompressStream - logic error"); break; } } /// <summary> /// Call this to determine if a deflate stream is empty - pass the actual compressed stream /// </summary> /// <param name="s"></param> /// <returns>true if empty</returns> private static bool IsDeflateStreamEmpty(Stream s) { bool empty = false; // Special case: If stream has existing content, we need to go straight // to Emulation mode otherwise we'll potentially destroy existing data. // This will not be possible if the base stream is write-only and non-seekable. // The minimal length of a persisted DeflateStream is 2 so if the length // is 2, we can safely overwrite. We explicitly call Deflate on a stream of length // 1 so that we can get a consistent exception because this will be an illegally // compressed stream. if (s.CanSeek && s.CanRead) { Debug.Assert(s.Position == 0); // read the two bytes and commpare to the known 2 bytes that represent // and empty deflate stream byte[] buf = new byte[2]; int bytesRead = s.Read(buf, 0, 2); empty = ((bytesRead == 0) || (buf[0] == _emptyDeflateStreamConstant[0] && buf[1] == _emptyDeflateStreamConstant[1])); s.Position = 0; // restore position } else empty = true; // if write-time-streaming we're going to destroy what's there anyway return empty; } private long CachedLength { get { // only maintained when NOT in Emulation mode Debug.Assert(_mode != Mode.Emulation, "Logic error: CachedLength not maintained in Emulation mode - illegal Get"); return _cachedLength; } set { // only maintained when NOT in Emulation mode Debug.Assert(_mode != Mode.Emulation, "Logic error: CachedLength not maintained in Emulation mode - illegal Set"); Debug.Assert(value >= 0, "Length cannot be negative - logic error?"); _cachedLength = value; } } //------------------------------------------------------ // // Private Variables // //------------------------------------------------------ // Add explicit values to these enum variables because we do some arithmetic with them and don't want to // rely on the default behavior. private enum Mode { Start = 0, // we have no outstanding memory in use - state on construction ReadPassThrough = 1, // we are able to read from the current position WritePassThrough = 2, // we are able to write to the current position Emulation = 3, // we have moved all data to a memory stream and all operations are supported Disposed = 4 // we are disposed }; private Mode _mode; // current stream mode private Int64 _position; // current logical position - only copy - shared with all helpers private Stream _baseStream; // stream we ultimately decompress from and to in the container private Stream _current; // current stream object private bool _dirtyForFlushing; // are we dirty, these 2 flags are going to differ in the case of the FLushed Write Through mode private bool _dirtyForClosing; // _dirtyForFlushing will be false (meaning that there is no data to be flushed) while // _dirtyForClosing will be true as there might be some data that need to be added for closing // Note: DirtyForFlushing can never be true when DirtyForClosing is false. private bool _lengthVerified; // true if we have successfully compared the length given in our constructor against that obtained from // actually decompressing the data private long _cachedLength; // cached value prevents us from entering Emulation to obtain length after ReadPassThrough reads all bytes // -1 means not set // this is what is persisted when a deflate stream is of length zero private static byte[] _emptyDeflateStreamConstant = new byte[] { 0x03, 0x00 }; private const long _lowWaterMark = 0x19000; // we definately would like to keep everythuing under 100 KB in memory private const long _highWaterMark = 0xA00000; // we would like to keep everything over 10 MB on disk private const long _readPassThroughModeSeekThreshold = 0x40; // amount we can seek in a reasonable amount of time while decompressing #endregion } }
/* * 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: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * 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; using System.Collections.Generic; namespace XenAPI { internal class Maps { internal static Dictionary<string, string> convert_from_proxy_string_string(Object o) { Hashtable table = (Hashtable)o; Dictionary<string, string> result = new Dictionary<string, string>(); if (table != null) { foreach (string key in table.Keys) { try { string k = key; string v = table[key] == null ? null : (string)table[key]; result[k] = v; } catch { continue; } } } return result; } internal static Hashtable convert_to_proxy_string_string(Dictionary<string, string> table) { CookComputing.XmlRpc.XmlRpcStruct result = new CookComputing.XmlRpc.XmlRpcStruct(); if (table != null) { foreach (string key in table.Keys) { try { string k = key ?? ""; string v = table[key] ?? ""; result[k] = v; } catch { continue; } } } return result; } internal static Dictionary<string, long> convert_from_proxy_string_long(Object o) { Hashtable table = (Hashtable)o; Dictionary<string, long> result = new Dictionary<string, long>(); if (table != null) { foreach (string key in table.Keys) { try { string k = key; long v = table[key] == null ? 0 : long.Parse((string)table[key]); result[k] = v; } catch { continue; } } } return result; } internal static Hashtable convert_to_proxy_string_long(Dictionary<string, long> table) { CookComputing.XmlRpc.XmlRpcStruct result = new CookComputing.XmlRpc.XmlRpcStruct(); if (table != null) { foreach (string key in table.Keys) { try { string k = key ?? ""; string v = table[key].ToString(); result[k] = v; } catch { continue; } } } return result; } internal static Dictionary<string, host_allowed_operations> convert_from_proxy_string_host_allowed_operations(Object o) { Hashtable table = (Hashtable)o; Dictionary<string, host_allowed_operations> result = new Dictionary<string, host_allowed_operations>(); if (table != null) { foreach (string key in table.Keys) { try { string k = key; host_allowed_operations v = table[key] == null ? (host_allowed_operations) 0 : (host_allowed_operations)Helper.EnumParseDefault(typeof(host_allowed_operations), (string)table[key]); result[k] = v; } catch { continue; } } } return result; } internal static Hashtable convert_to_proxy_string_host_allowed_operations(Dictionary<string, host_allowed_operations> table) { CookComputing.XmlRpc.XmlRpcStruct result = new CookComputing.XmlRpc.XmlRpcStruct(); if (table != null) { foreach (string key in table.Keys) { try { string k = key ?? ""; string v = host_allowed_operations_helper.ToString(table[key]); result[k] = v; } catch { continue; } } } return result; } internal static Dictionary<string, network_operations> convert_from_proxy_string_network_operations(Object o) { Hashtable table = (Hashtable)o; Dictionary<string, network_operations> result = new Dictionary<string, network_operations>(); if (table != null) { foreach (string key in table.Keys) { try { string k = key; network_operations v = table[key] == null ? (network_operations) 0 : (network_operations)Helper.EnumParseDefault(typeof(network_operations), (string)table[key]); result[k] = v; } catch { continue; } } } return result; } internal static Hashtable convert_to_proxy_string_network_operations(Dictionary<string, network_operations> table) { CookComputing.XmlRpc.XmlRpcStruct result = new CookComputing.XmlRpc.XmlRpcStruct(); if (table != null) { foreach (string key in table.Keys) { try { string k = key ?? ""; string v = network_operations_helper.ToString(table[key]); result[k] = v; } catch { continue; } } } return result; } internal static Dictionary<string, pool_allowed_operations> convert_from_proxy_string_pool_allowed_operations(Object o) { Hashtable table = (Hashtable)o; Dictionary<string, pool_allowed_operations> result = new Dictionary<string, pool_allowed_operations>(); if (table != null) { foreach (string key in table.Keys) { try { string k = key; pool_allowed_operations v = table[key] == null ? (pool_allowed_operations) 0 : (pool_allowed_operations)Helper.EnumParseDefault(typeof(pool_allowed_operations), (string)table[key]); result[k] = v; } catch { continue; } } } return result; } internal static Hashtable convert_to_proxy_string_pool_allowed_operations(Dictionary<string, pool_allowed_operations> table) { CookComputing.XmlRpc.XmlRpcStruct result = new CookComputing.XmlRpc.XmlRpcStruct(); if (table != null) { foreach (string key in table.Keys) { try { string k = key ?? ""; string v = pool_allowed_operations_helper.ToString(table[key]); result[k] = v; } catch { continue; } } } return result; } internal static Dictionary<string, storage_operations> convert_from_proxy_string_storage_operations(Object o) { Hashtable table = (Hashtable)o; Dictionary<string, storage_operations> result = new Dictionary<string, storage_operations>(); if (table != null) { foreach (string key in table.Keys) { try { string k = key; storage_operations v = table[key] == null ? (storage_operations) 0 : (storage_operations)Helper.EnumParseDefault(typeof(storage_operations), (string)table[key]); result[k] = v; } catch { continue; } } } return result; } internal static Hashtable convert_to_proxy_string_storage_operations(Dictionary<string, storage_operations> table) { CookComputing.XmlRpc.XmlRpcStruct result = new CookComputing.XmlRpc.XmlRpcStruct(); if (table != null) { foreach (string key in table.Keys) { try { string k = key ?? ""; string v = storage_operations_helper.ToString(table[key]); result[k] = v; } catch { continue; } } } return result; } internal static Dictionary<string, task_allowed_operations> convert_from_proxy_string_task_allowed_operations(Object o) { Hashtable table = (Hashtable)o; Dictionary<string, task_allowed_operations> result = new Dictionary<string, task_allowed_operations>(); if (table != null) { foreach (string key in table.Keys) { try { string k = key; task_allowed_operations v = table[key] == null ? (task_allowed_operations) 0 : (task_allowed_operations)Helper.EnumParseDefault(typeof(task_allowed_operations), (string)table[key]); result[k] = v; } catch { continue; } } } return result; } internal static Hashtable convert_to_proxy_string_task_allowed_operations(Dictionary<string, task_allowed_operations> table) { CookComputing.XmlRpc.XmlRpcStruct result = new CookComputing.XmlRpc.XmlRpcStruct(); if (table != null) { foreach (string key in table.Keys) { try { string k = key ?? ""; string v = task_allowed_operations_helper.ToString(table[key]); result[k] = v; } catch { continue; } } } return result; } internal static Dictionary<string, vbd_operations> convert_from_proxy_string_vbd_operations(Object o) { Hashtable table = (Hashtable)o; Dictionary<string, vbd_operations> result = new Dictionary<string, vbd_operations>(); if (table != null) { foreach (string key in table.Keys) { try { string k = key; vbd_operations v = table[key] == null ? (vbd_operations) 0 : (vbd_operations)Helper.EnumParseDefault(typeof(vbd_operations), (string)table[key]); result[k] = v; } catch { continue; } } } return result; } internal static Hashtable convert_to_proxy_string_vbd_operations(Dictionary<string, vbd_operations> table) { CookComputing.XmlRpc.XmlRpcStruct result = new CookComputing.XmlRpc.XmlRpcStruct(); if (table != null) { foreach (string key in table.Keys) { try { string k = key ?? ""; string v = vbd_operations_helper.ToString(table[key]); result[k] = v; } catch { continue; } } } return result; } internal static Dictionary<string, vdi_operations> convert_from_proxy_string_vdi_operations(Object o) { Hashtable table = (Hashtable)o; Dictionary<string, vdi_operations> result = new Dictionary<string, vdi_operations>(); if (table != null) { foreach (string key in table.Keys) { try { string k = key; vdi_operations v = table[key] == null ? (vdi_operations) 0 : (vdi_operations)Helper.EnumParseDefault(typeof(vdi_operations), (string)table[key]); result[k] = v; } catch { continue; } } } return result; } internal static Hashtable convert_to_proxy_string_vdi_operations(Dictionary<string, vdi_operations> table) { CookComputing.XmlRpc.XmlRpcStruct result = new CookComputing.XmlRpc.XmlRpcStruct(); if (table != null) { foreach (string key in table.Keys) { try { string k = key ?? ""; string v = vdi_operations_helper.ToString(table[key]); result[k] = v; } catch { continue; } } } return result; } internal static Dictionary<string, vif_operations> convert_from_proxy_string_vif_operations(Object o) { Hashtable table = (Hashtable)o; Dictionary<string, vif_operations> result = new Dictionary<string, vif_operations>(); if (table != null) { foreach (string key in table.Keys) { try { string k = key; vif_operations v = table[key] == null ? (vif_operations) 0 : (vif_operations)Helper.EnumParseDefault(typeof(vif_operations), (string)table[key]); result[k] = v; } catch { continue; } } } return result; } internal static Hashtable convert_to_proxy_string_vif_operations(Dictionary<string, vif_operations> table) { CookComputing.XmlRpc.XmlRpcStruct result = new CookComputing.XmlRpc.XmlRpcStruct(); if (table != null) { foreach (string key in table.Keys) { try { string k = key ?? ""; string v = vif_operations_helper.ToString(table[key]); result[k] = v; } catch { continue; } } } return result; } internal static Dictionary<string, vm_appliance_operation> convert_from_proxy_string_vm_appliance_operation(Object o) { Hashtable table = (Hashtable)o; Dictionary<string, vm_appliance_operation> result = new Dictionary<string, vm_appliance_operation>(); if (table != null) { foreach (string key in table.Keys) { try { string k = key; vm_appliance_operation v = table[key] == null ? (vm_appliance_operation) 0 : (vm_appliance_operation)Helper.EnumParseDefault(typeof(vm_appliance_operation), (string)table[key]); result[k] = v; } catch { continue; } } } return result; } internal static Hashtable convert_to_proxy_string_vm_appliance_operation(Dictionary<string, vm_appliance_operation> table) { CookComputing.XmlRpc.XmlRpcStruct result = new CookComputing.XmlRpc.XmlRpcStruct(); if (table != null) { foreach (string key in table.Keys) { try { string k = key ?? ""; string v = vm_appliance_operation_helper.ToString(table[key]); result[k] = v; } catch { continue; } } } return result; } internal static Dictionary<string, vm_operations> convert_from_proxy_string_vm_operations(Object o) { Hashtable table = (Hashtable)o; Dictionary<string, vm_operations> result = new Dictionary<string, vm_operations>(); if (table != null) { foreach (string key in table.Keys) { try { string k = key; vm_operations v = table[key] == null ? (vm_operations) 0 : (vm_operations)Helper.EnumParseDefault(typeof(vm_operations), (string)table[key]); result[k] = v; } catch { continue; } } } return result; } internal static Hashtable convert_to_proxy_string_vm_operations(Dictionary<string, vm_operations> table) { CookComputing.XmlRpc.XmlRpcStruct result = new CookComputing.XmlRpc.XmlRpcStruct(); if (table != null) { foreach (string key in table.Keys) { try { string k = key ?? ""; string v = vm_operations_helper.ToString(table[key]); result[k] = v; } catch { continue; } } } return result; } internal static Dictionary<string, vusb_operations> convert_from_proxy_string_vusb_operations(Object o) { Hashtable table = (Hashtable)o; Dictionary<string, vusb_operations> result = new Dictionary<string, vusb_operations>(); if (table != null) { foreach (string key in table.Keys) { try { string k = key; vusb_operations v = table[key] == null ? (vusb_operations) 0 : (vusb_operations)Helper.EnumParseDefault(typeof(vusb_operations), (string)table[key]); result[k] = v; } catch { continue; } } } return result; } internal static Hashtable convert_to_proxy_string_vusb_operations(Dictionary<string, vusb_operations> table) { CookComputing.XmlRpc.XmlRpcStruct result = new CookComputing.XmlRpc.XmlRpcStruct(); if (table != null) { foreach (string key in table.Keys) { try { string k = key ?? ""; string v = vusb_operations_helper.ToString(table[key]); result[k] = v; } catch { continue; } } } return result; } internal static Dictionary<string, XenRef<Blob>> convert_from_proxy_string_XenRefBlob(Object o) { Hashtable table = (Hashtable)o; Dictionary<string, XenRef<Blob>> result = new Dictionary<string, XenRef<Blob>>(); if (table != null) { foreach (string key in table.Keys) { try { string k = key; XenRef<Blob> v = table[key] == null ? null : XenRef<Blob>.Create(table[key]); result[k] = v; } catch { continue; } } } return result; } internal static Hashtable convert_to_proxy_string_XenRefBlob(Dictionary<string, XenRef<Blob>> table) { CookComputing.XmlRpc.XmlRpcStruct result = new CookComputing.XmlRpc.XmlRpcStruct(); if (table != null) { foreach (string key in table.Keys) { try { string k = key ?? ""; string v = table[key] ?? ""; result[k] = v; } catch { continue; } } } return result; } internal static Dictionary<long, long> convert_from_proxy_long_long(Object o) { Hashtable table = (Hashtable)o; Dictionary<long, long> result = new Dictionary<long, long>(); if (table != null) { foreach (string key in table.Keys) { try { long k = long.Parse(key); long v = table[key] == null ? 0 : long.Parse((string)table[key]); result[k] = v; } catch { continue; } } } return result; } internal static Hashtable convert_to_proxy_long_long(Dictionary<long, long> table) { CookComputing.XmlRpc.XmlRpcStruct result = new CookComputing.XmlRpc.XmlRpcStruct(); if (table != null) { foreach (long key in table.Keys) { try { string k = key.ToString(); string v = table[key].ToString(); result[k] = v; } catch { continue; } } } return result; } internal static Dictionary<long, double> convert_from_proxy_long_double(Object o) { Hashtable table = (Hashtable)o; Dictionary<long, double> result = new Dictionary<long, double>(); if (table != null) { foreach (string key in table.Keys) { try { long k = long.Parse(key); double v = Convert.ToDouble(table[key]); result[k] = v; } catch { continue; } } } return result; } internal static Hashtable convert_to_proxy_long_double(Dictionary<long, double> table) { CookComputing.XmlRpc.XmlRpcStruct result = new CookComputing.XmlRpc.XmlRpcStruct(); if (table != null) { foreach (long key in table.Keys) { try { string k = key.ToString(); double v = table[key]; result[k] = v; } catch { continue; } } } return result; } internal static Dictionary<long, string[]> convert_from_proxy_long_string_array(Object o) { Hashtable table = (Hashtable)o; Dictionary<long, string[]> result = new Dictionary<long, string[]>(); if (table != null) { foreach (string key in table.Keys) { try { long k = long.Parse(key); string[] v = table[key] == null ? new string[] {} : Array.ConvertAll<object, string>((object[])table[key], Convert.ToString); result[k] = v; } catch { continue; } } } return result; } internal static Hashtable convert_to_proxy_long_string_array(Dictionary<long, string[]> table) { CookComputing.XmlRpc.XmlRpcStruct result = new CookComputing.XmlRpc.XmlRpcStruct(); if (table != null) { foreach (long key in table.Keys) { try { string k = key.ToString(); string [] v = table[key]; result[k] = v; } catch { continue; } } } return result; } internal static Dictionary<vm_operations, string> convert_from_proxy_vm_operations_string(Object o) { Hashtable table = (Hashtable)o; Dictionary<vm_operations, string> result = new Dictionary<vm_operations, string>(); if (table != null) { foreach (string key in table.Keys) { try { vm_operations k = (vm_operations)Helper.EnumParseDefault(typeof(vm_operations), (string)key); string v = table[key] == null ? null : (string)table[key]; result[k] = v; } catch { continue; } } } return result; } internal static Hashtable convert_to_proxy_vm_operations_string(Dictionary<vm_operations, string> table) { CookComputing.XmlRpc.XmlRpcStruct result = new CookComputing.XmlRpc.XmlRpcStruct(); if (table != null) { foreach (vm_operations key in table.Keys) { try { string k = vm_operations_helper.ToString(key); string v = table[key] ?? ""; result[k] = v; } catch { continue; } } } return result; } internal static Dictionary<XenRef<VDI>, XenRef<SR>> convert_from_proxy_XenRefVDI_XenRefSR(Object o) { Hashtable table = (Hashtable)o; Dictionary<XenRef<VDI>, XenRef<SR>> result = new Dictionary<XenRef<VDI>, XenRef<SR>>(); if (table != null) { foreach (string key in table.Keys) { try { XenRef<VDI> k = XenRef<VDI>.Create(key); XenRef<SR> v = table[key] == null ? null : XenRef<SR>.Create(table[key]); result[k] = v; } catch { continue; } } } return result; } internal static Hashtable convert_to_proxy_XenRefVDI_XenRefSR(Dictionary<XenRef<VDI>, XenRef<SR>> table) { CookComputing.XmlRpc.XmlRpcStruct result = new CookComputing.XmlRpc.XmlRpcStruct(); if (table != null) { foreach (XenRef<VDI> key in table.Keys) { try { string k = key ?? ""; string v = table[key] ?? ""; result[k] = v; } catch { continue; } } } return result; } internal static Dictionary<XenRef<VGPU_type>, long> convert_from_proxy_XenRefVGPU_type_long(Object o) { Hashtable table = (Hashtable)o; Dictionary<XenRef<VGPU_type>, long> result = new Dictionary<XenRef<VGPU_type>, long>(); if (table != null) { foreach (string key in table.Keys) { try { XenRef<VGPU_type> k = XenRef<VGPU_type>.Create(key); long v = table[key] == null ? 0 : long.Parse((string)table[key]); result[k] = v; } catch { continue; } } } return result; } internal static Hashtable convert_to_proxy_XenRefVGPU_type_long(Dictionary<XenRef<VGPU_type>, long> table) { CookComputing.XmlRpc.XmlRpcStruct result = new CookComputing.XmlRpc.XmlRpcStruct(); if (table != null) { foreach (XenRef<VGPU_type> key in table.Keys) { try { string k = key ?? ""; string v = table[key].ToString(); result[k] = v; } catch { continue; } } } return result; } internal static Dictionary<XenRef<VIF>, string> convert_from_proxy_XenRefVIF_string(Object o) { Hashtable table = (Hashtable)o; Dictionary<XenRef<VIF>, string> result = new Dictionary<XenRef<VIF>, string>(); if (table != null) { foreach (string key in table.Keys) { try { XenRef<VIF> k = XenRef<VIF>.Create(key); string v = table[key] == null ? null : (string)table[key]; result[k] = v; } catch { continue; } } } return result; } internal static Hashtable convert_to_proxy_XenRefVIF_string(Dictionary<XenRef<VIF>, string> table) { CookComputing.XmlRpc.XmlRpcStruct result = new CookComputing.XmlRpc.XmlRpcStruct(); if (table != null) { foreach (XenRef<VIF> key in table.Keys) { try { string k = key ?? ""; string v = table[key] ?? ""; result[k] = v; } catch { continue; } } } return result; } internal static Dictionary<XenRef<VIF>, XenRef<Network>> convert_from_proxy_XenRefVIF_XenRefNetwork(Object o) { Hashtable table = (Hashtable)o; Dictionary<XenRef<VIF>, XenRef<Network>> result = new Dictionary<XenRef<VIF>, XenRef<Network>>(); if (table != null) { foreach (string key in table.Keys) { try { XenRef<VIF> k = XenRef<VIF>.Create(key); XenRef<Network> v = table[key] == null ? null : XenRef<Network>.Create(table[key]); result[k] = v; } catch { continue; } } } return result; } internal static Hashtable convert_to_proxy_XenRefVIF_XenRefNetwork(Dictionary<XenRef<VIF>, XenRef<Network>> table) { CookComputing.XmlRpc.XmlRpcStruct result = new CookComputing.XmlRpc.XmlRpcStruct(); if (table != null) { foreach (XenRef<VIF> key in table.Keys) { try { string k = key ?? ""; string v = table[key] ?? ""; result[k] = v; } catch { continue; } } } return result; } internal static Dictionary<XenRef<VM>, string> convert_from_proxy_XenRefVM_string(Object o) { Hashtable table = (Hashtable)o; Dictionary<XenRef<VM>, string> result = new Dictionary<XenRef<VM>, string>(); if (table != null) { foreach (string key in table.Keys) { try { XenRef<VM> k = XenRef<VM>.Create(key); string v = table[key] == null ? null : (string)table[key]; result[k] = v; } catch { continue; } } } return result; } internal static Hashtable convert_to_proxy_XenRefVM_string(Dictionary<XenRef<VM>, string> table) { CookComputing.XmlRpc.XmlRpcStruct result = new CookComputing.XmlRpc.XmlRpcStruct(); if (table != null) { foreach (XenRef<VM> key in table.Keys) { try { string k = key ?? ""; string v = table[key] ?? ""; result[k] = v; } catch { continue; } } } return result; } internal static Dictionary<XenRef<VM>, string[]> convert_from_proxy_XenRefVM_string_array(Object o) { Hashtable table = (Hashtable)o; Dictionary<XenRef<VM>, string[]> result = new Dictionary<XenRef<VM>, string[]>(); if (table != null) { foreach (string key in table.Keys) { try { XenRef<VM> k = XenRef<VM>.Create(key); string[] v = table[key] == null ? new string[] {} : Array.ConvertAll<object, string>((object[])table[key], Convert.ToString); result[k] = v; } catch { continue; } } } return result; } internal static Hashtable convert_to_proxy_XenRefVM_string_array(Dictionary<XenRef<VM>, string[]> table) { CookComputing.XmlRpc.XmlRpcStruct result = new CookComputing.XmlRpc.XmlRpcStruct(); if (table != null) { foreach (XenRef<VM> key in table.Keys) { try { string k = key ?? ""; string [] v = table[key]; result[k] = v; } catch { continue; } } } return result; } internal static Dictionary<XenRef<VM>, Dictionary<string, string>> convert_from_proxy_XenRefVM_Dictionary_string_string(Object o) { Hashtable table = (Hashtable)o; Dictionary<XenRef<VM>, Dictionary<string, string>> result = new Dictionary<XenRef<VM>, Dictionary<string, string>>(); if (table != null) { foreach (string key in table.Keys) { try { XenRef<VM> k = XenRef<VM>.Create(key); Dictionary<string, string> v = table[key] == null ? null : Maps.convert_from_proxy_string_string(table[key]); result[k] = v; } catch { continue; } } } return result; } internal static Hashtable convert_to_proxy_XenRefVM_Dictionary_string_string(Dictionary<XenRef<VM>, Dictionary<string, string>> table) { CookComputing.XmlRpc.XmlRpcStruct result = new CookComputing.XmlRpc.XmlRpcStruct(); if (table != null) { foreach (XenRef<VM> key in table.Keys) { try { string k = key ?? ""; Object v = Maps.convert_to_proxy_string_string(table[key]); result[k] = v; } catch { continue; } } } return result; } internal static Dictionary<XenRef<Host>, string[]> convert_from_proxy_XenRefHost_string_array(Object o) { Hashtable table = (Hashtable)o; Dictionary<XenRef<Host>, string[]> result = new Dictionary<XenRef<Host>, string[]>(); if (table != null) { foreach (string key in table.Keys) { try { XenRef<Host> k = XenRef<Host>.Create(key); string[] v = table[key] == null ? new string[] {} : Array.ConvertAll<object, string>((object[])table[key], Convert.ToString); result[k] = v; } catch { continue; } } } return result; } internal static Hashtable convert_to_proxy_XenRefHost_string_array(Dictionary<XenRef<Host>, string[]> table) { CookComputing.XmlRpc.XmlRpcStruct result = new CookComputing.XmlRpc.XmlRpcStruct(); if (table != null) { foreach (XenRef<Host> key in table.Keys) { try { string k = key ?? ""; string [] v = table[key]; result[k] = v; } catch { continue; } } } return result; } } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Security; namespace Archimedes.Web.Models { #region Services // The FormsAuthentication type is sealed and contains static members, so it is difficult to // unit test code that calls its members. The interface and helper class below demonstrate // how to create an abstract wrapper around such a type in order to make the AccountController // code unit testable. public interface IMembershipService { int MinPasswordLength { get; } bool ValidateUser(string userName, string password); MembershipCreateStatus CreateUser(string userName, string password, string email); bool ChangePassword(string userName, string oldPassword, string newPassword); } public class AccountMembershipService : IMembershipService { private readonly MembershipProvider _provider; public AccountMembershipService() : this(null) { } public AccountMembershipService(MembershipProvider provider) { _provider = provider ?? Membership.Provider; } public int MinPasswordLength { get { return _provider.MinRequiredPasswordLength; } } public bool ValidateUser(string userName, string password) { ValidationUtil.ValidateRequiredStringValue(userName, "userName"); ValidationUtil.ValidateRequiredStringValue(password, "password"); return _provider.ValidateUser(userName, password); } public MembershipCreateStatus CreateUser(string userName, string password, string email) { ValidationUtil.ValidateRequiredStringValue(userName, "userName"); ValidationUtil.ValidateRequiredStringValue(password, "password"); ValidationUtil.ValidateRequiredStringValue(email, "email"); MembershipCreateStatus status; _provider.CreateUser(userName, password, email, null, null, true, null, out status); return status; } public bool ChangePassword(string userName, string oldPassword, string newPassword) { ValidationUtil.ValidateRequiredStringValue(userName, "userName"); ValidationUtil.ValidateRequiredStringValue(oldPassword, "oldPassword"); ValidationUtil.ValidateRequiredStringValue(newPassword, "newPassword"); // The underlying ChangePassword() will throw an exception rather // than return false in certain failure scenarios. try { MembershipUser currentUser = _provider.GetUser(userName, true /* userIsOnline */); return currentUser.ChangePassword(oldPassword, newPassword); } catch (ArgumentException) { return false; } catch (MembershipPasswordException) { return false; } } } public interface IFormsAuthenticationService { void SignIn(string userName, bool createPersistentCookie); void SignOut(); } public class FormsAuthenticationService : IFormsAuthenticationService { public void SignIn(string userName, bool createPersistentCookie) { ValidationUtil.ValidateRequiredStringValue(userName, "userName"); FormsAuthentication.SetAuthCookie(userName, createPersistentCookie); } public void SignOut() { FormsAuthentication.SignOut(); } } internal static class ValidationUtil { private const string _stringRequiredErrorMessage = "Value cannot be null or empty."; public static void ValidateRequiredStringValue(string value, string parameterName) { if (String.IsNullOrEmpty(value)) { throw new ArgumentException(_stringRequiredErrorMessage, parameterName); } } } #endregion #region Models [PropertiesMustMatch("NewPassword", "ConfirmPassword", ErrorMessage = "The new password and confirmation password do not match.")] public class ChangePasswordModel { [Required] [DataType(DataType.Password)] [DisplayName("Current password")] public string OldPassword { get; set; } [Required] [ValidatePasswordLength] [DataType(DataType.Password)] [DisplayName("New password")] public string NewPassword { get; set; } [Required] [DataType(DataType.Password)] [DisplayName("Confirm new password")] public string ConfirmPassword { get; set; } } public class LogOnModel { [Required] [DisplayName("User name")] public string UserName { get; set; } [Required] [DataType(DataType.Password)] [DisplayName("Password")] public string Password { get; set; } [DisplayName("Remember me?")] public bool RememberMe { get; set; } } [PropertiesMustMatch("Password", "ConfirmPassword", ErrorMessage = "The password and confirmation password do not match.")] public class RegisterModel { [Required] [DisplayName("User name")] public string UserName { get; set; } [Required] [DataType(DataType.EmailAddress)] [DisplayName("Email address")] public string Email { get; set; } [Required] [ValidatePasswordLength] [DataType(DataType.Password)] [DisplayName("Password")] public string Password { get; set; } [Required] [DataType(DataType.Password)] [DisplayName("Confirm password")] public string ConfirmPassword { get; set; } } #endregion #region Validation [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)] public sealed class PropertiesMustMatchAttribute : ValidationAttribute { private const string _defaultErrorMessage = "'{0}' and '{1}' do not match."; private readonly object _typeId = new object(); public PropertiesMustMatchAttribute(string originalProperty, string confirmProperty) : base(_defaultErrorMessage) { OriginalProperty = originalProperty; ConfirmProperty = confirmProperty; } public string ConfirmProperty { get; private set; } public string OriginalProperty { get; private set; } public override object TypeId { get { return _typeId; } } public override string FormatErrorMessage(string name) { return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, OriginalProperty, ConfirmProperty); } public override bool IsValid(object value) { PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value); object originalValue = properties.Find(OriginalProperty, true /* ignoreCase */).GetValue(value); object confirmValue = properties.Find(ConfirmProperty, true /* ignoreCase */).GetValue(value); return Object.Equals(originalValue, confirmValue); } } [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class ValidatePasswordLengthAttribute : ValidationAttribute { private const string _defaultErrorMessage = "'{0}' must be at least {1} characters long."; private readonly int _minCharacters = Membership.Provider.MinRequiredPasswordLength; public ValidatePasswordLengthAttribute() : base(_defaultErrorMessage) { } public override string FormatErrorMessage(string name) { return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString, name, _minCharacters); } public override bool IsValid(object value) { string valueAsString = value as string; return (valueAsString != null && valueAsString.Length >= _minCharacters); } } #endregion }
namespace AngleSharp.Dom { using AngleSharp.Dom.Events; using AngleSharp.Text; using System; using System.IO; /// <summary> /// Represents a generic node attribute. /// </summary> public sealed class Attr : IAttr { #region Fields private readonly String _localName; private readonly String? _prefix; private readonly String? _namespace; private String _value; #endregion #region ctor /// <summary> /// Creates a new attribute with the given local name. /// </summary> /// <param name="localName">The local name of the attribute.</param> public Attr(String localName) : this(localName, String.Empty) { } /// <summary> /// Creates a new attribute with the given local name and value. /// </summary> /// <param name="localName">The local name of the attribute.</param> /// <param name="value">The value of the attribute.</param> public Attr(String localName, String value) { _localName = localName; _value = value; } /// <summary> /// Creates a new attribute with the given properties. /// </summary> /// <param name="prefix">The prefix of the attribute.</param> /// <param name="localName">The local name of the attribute.</param> /// <param name="value">The value of the attribute.</param> /// <param name="namespaceUri">The namespace of the attribute.</param> public Attr(String? prefix, String localName, String value, String? namespaceUri) { _prefix = prefix; _localName = localName; _value = value; _namespace = namespaceUri; } #endregion #region Internal Properties internal NamedNodeMap? Container { get; set; } #endregion #region Properties /// <summary> /// Gets always true. /// </summary> public Boolean IsSpecified => true; /// <summary> /// Gets the owner of the attribute, if any. /// </summary> public IElement? OwnerElement => Container?.Owner; /// <summary> /// Gets the attribute's prefix. /// </summary> public String? Prefix => _prefix; /// <summary> /// Gets if the attribute is an id attribute. /// </summary> public Boolean IsId => _prefix is null && _localName.Isi(AttributeNames.Id); /// <summary> /// Gets if the value is given or not. /// </summary> public Boolean Specified => !String.IsNullOrEmpty(_value); /// <summary> /// Gets the attribute's fully qualified name. /// </summary> public String Name => _prefix is null ? _localName : String.Concat(_prefix, ":", _localName); /// <summary> /// Gets the attribute's value. /// </summary> public String Value { get => _value; set { var oldValue = _value; _value = value; Container?.RaiseChangedEvent(this, value, oldValue); } } /// <summary> /// Gets the attribute's local name. /// </summary> public String LocalName => _localName; /// <summary> /// Gets the attribute's namespace. /// </summary> public String? NamespaceUri => _namespace; string INode.BaseUri => OwnerElement!.BaseUri; Url? INode.BaseUrl => OwnerElement?.BaseUrl; string INode.NodeName => Name; INodeList INode.ChildNodes => NodeList.Empty; IDocument? INode.Owner => OwnerElement?.Owner; IElement? INode.ParentElement => null; INode? INode.Parent => null; INode? INode.FirstChild => null; INode? INode.LastChild => null; INode? INode.NextSibling => null; INode? INode.PreviousSibling => null; NodeType INode.NodeType => NodeType.Attribute; string INode.NodeValue { get => Value; set => Value = value; } string INode.TextContent { get => Value; set => Value = value; } bool INode.HasChildNodes => false; NodeFlags INode.Flags => throw new NotImplementedException(); #endregion #region Methods /// <summary> /// Checks if the attribute equals another attribute. /// </summary> /// <param name="other">The other attribute.</param> /// <returns>True if both are equivalent, otherwise false.</returns> public Boolean Equals(IAttr? other) => Prefix.Is(other?.Prefix) && NamespaceUri.Is(other?.NamespaceUri) && Value.Is(other?.Value); /// <summary> /// Computes the hash code of the attribute. /// </summary> /// <returns>The computed hash code.</returns> public override Int32 GetHashCode() { const int prime = 31; var result = 1; result = result * prime + _localName.GetHashCode(); result = result * prime + (_value ?? String.Empty).GetHashCode(); result = result * prime + (_namespace ?? String.Empty).GetHashCode(); result = result * prime + (_prefix ?? String.Empty).GetHashCode(); return result; } #endregion #region INode Implementation INode INode.Clone(Boolean deep) => new Attr(_prefix, _localName, _value, _namespace); Boolean INode.Equals(INode otherNode) => otherNode is IAttr attr && Equals(attr); DocumentPositions INode.CompareDocumentPosition(INode otherNode) => OwnerElement?.CompareDocumentPosition(otherNode) ?? DocumentPositions.Disconnected; void INode.Normalize() {} Boolean INode.Contains(INode otherNode) => false; Boolean INode.IsDefaultNamespace(String namespaceUri) => OwnerElement?.IsDefaultNamespace(namespaceUri) ?? false; String? INode.LookupNamespaceUri(String prefix) => OwnerElement?.LookupNamespaceUri(prefix); String? INode.LookupPrefix(String? namespaceUri) => OwnerElement?.LookupPrefix(namespaceUri); INode INode.AppendChild(INode child) => throw new DomException(DomError.NotSupported); INode INode.InsertBefore(INode newElement, INode? referenceElement) => throw new DomException(DomError.NotSupported); INode INode.RemoveChild(INode child) => throw new DomException(DomError.NotSupported); INode INode.ReplaceChild(INode newChild, INode oldChild) => throw new DomException(DomError.NotSupported); void IEventTarget.AddEventListener(String type, DomEventHandler? callback, Boolean capture) => throw new DomException(DomError.NotSupported); void IEventTarget.RemoveEventListener(string type, DomEventHandler? callback, bool capture) => throw new DomException(DomError.NotSupported); void IEventTarget.InvokeEventListener(Event ev) => throw new DomException(DomError.NotSupported); Boolean IEventTarget.Dispatch(Event ev) => throw new DomException(DomError.NotSupported); void IMarkupFormattable.ToHtml(TextWriter writer, IMarkupFormatter formatter) {} #endregion } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //=========================================================================== // File: TcpClientChannel.cs // // Summary: Implements a channel that transmits method calls over TCP. // //========================================================================== using System; using System.Collections; using System.IO; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Messaging; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Text; using System.Globalization; #if !FEATURE_PAL using System.Security.Authentication; #endif using System.Security.Principal; using System.Security.Permissions; namespace System.Runtime.Remoting.Channels.Tcp { public class TcpClientChannel : IChannelSender, ISecurableChannel { private int _channelPriority = 1; // channel priority private String _channelName = "tcp"; // channel name private bool _secure = false; private IDictionary _prop = null; private IClientChannelSinkProvider _sinkProvider = null; // sink chain provider public TcpClientChannel() { SetupChannel(); } // TcpClientChannel public TcpClientChannel(String name, IClientChannelSinkProvider sinkProvider) { _channelName = name; _sinkProvider = sinkProvider; SetupChannel(); } // constructor used by config file public TcpClientChannel(IDictionary properties, IClientChannelSinkProvider sinkProvider) { if (properties != null) { _prop = properties; foreach (DictionaryEntry entry in properties) { switch ((String)entry.Key) { case "name": _channelName = (String)entry.Value; break; case "priority": _channelPriority = Convert.ToInt32(entry.Value, CultureInfo.InvariantCulture); break; case "secure": _secure = Convert.ToBoolean(entry.Value, CultureInfo.InvariantCulture); break; default: break; } } } _sinkProvider = sinkProvider; SetupChannel(); } // TcpClientChannel private void SetupChannel() { if (_sinkProvider != null) { CoreChannel.AppendProviderToClientProviderChain( _sinkProvider, new TcpClientTransportSinkProvider(_prop)); } else _sinkProvider = CreateDefaultClientProviderChain(); } // SetupChannel // // ISecurableChannel implementation // public bool IsSecured { [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure, Infrastructure=true)] get { return _secure; } [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure, Infrastructure=true)] set { _secure = value; } } // // IChannel implementation // public int ChannelPriority { [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure, Infrastructure=true)] get { return _channelPriority; } } public String ChannelName { [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure, Infrastructure=true)] get { return _channelName; } } // returns channelURI and places object uri into out parameter [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public String Parse(String url, out String objectURI) { return TcpChannelHelper.ParseURL(url, out objectURI); } // Parse // // end of IChannel implementation // // // IChannelSender implementation // [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure, Infrastructure=true)] public virtual IMessageSink CreateMessageSink(String url, Object remoteChannelData, out String objectURI) { // Set the out parameters objectURI = null; String channelURI = null; if (url != null) // Is this a well known object? { // Parse returns null if this is not one of our url's channelURI = Parse(url, out objectURI); } else // determine if we want to connect based on the channel data { if (remoteChannelData != null) { if (remoteChannelData is IChannelDataStore) { IChannelDataStore cds = (IChannelDataStore)remoteChannelData; // see if this is an tcp uri String simpleChannelUri = Parse(cds.ChannelUris[0], out objectURI); if (simpleChannelUri != null) channelURI = cds.ChannelUris[0]; } } } if (null != channelURI) { if (url == null) url = channelURI; IClientChannelSink sink = _sinkProvider.CreateSink(this, url, remoteChannelData); // return sink after making sure that it implements IMessageSink IMessageSink msgSink = sink as IMessageSink; if ((sink != null) && (msgSink == null)) { throw new RemotingException( CoreChannel.GetResourceString( "Remoting_Channels_ChannelSinkNotMsgSink")); } return msgSink; } return null; } // CreateMessageSink // // end of IChannelSender implementation // private IClientChannelSinkProvider CreateDefaultClientProviderChain() { IClientChannelSinkProvider chain = new BinaryClientFormatterSinkProvider(); IClientChannelSinkProvider sink = chain; sink.Next = new TcpClientTransportSinkProvider(_prop); return chain; } // CreateDefaultClientProviderChain } // class TcpClientChannel internal class TcpClientTransportSinkProvider : IClientChannelSinkProvider { IDictionary _prop = null; internal TcpClientTransportSinkProvider(IDictionary properties) { _prop = properties; } public IClientChannelSink CreateSink(IChannelSender channel, String url, Object remoteChannelData) { // url is set to the channel uri in CreateMessageSink TcpClientTransportSink sink = new TcpClientTransportSink(url, (TcpClientChannel) channel); if (_prop != null) { // Tansfer all properties from the channel to the sink foreach(Object key in _prop.Keys) { sink[key] = _prop[key]; } } return sink; } public IClientChannelSinkProvider Next { get { return null; } set { throw new NotSupportedException(); } } } // class TcpClientTransportSinkProvider internal class TcpClientTransportSink : BaseChannelSinkWithProperties, IClientChannelSink { // socket cache internal SocketCache ClientSocketCache; private bool authSet = false; private SocketHandler CreateSocketHandler( Socket socket, SocketCache socketCache, String machinePortAndSid) { Stream netStream = new SocketStream(socket); // Check if authentication is requested if(_channel.IsSecured) { #if !FEATURE_PAL netStream = CreateAuthenticatedStream(netStream, machinePortAndSid); #else throw new NotSupportedException(); #endif } return new TcpClientSocketHandler(socket, machinePortAndSid, netStream, this); } // CreateSocketHandler #if !FEATURE_PAL private Stream CreateAuthenticatedStream(Stream netStream, String machinePortAndSid) { //Check for explicitly set userName, and authenticate using it NetworkCredential credentials = null; NegotiateStream negoClient = null; if (_securityUserName != null) { credentials = new NetworkCredential(_securityUserName, _securityPassword, _securityDomain); } //else use default Credentials else { credentials = (NetworkCredential)CredentialCache.DefaultCredentials; } try { negoClient = new NegotiateStream(netStream); negoClient.AuthenticateAsClient(credentials, _spn, _protectionLevel, _tokenImpersonationLevel); } catch(IOException e){ throw new RemotingException( String.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Tcp_AuthenticationFailed")), e); } return negoClient; } #endif // !FEATURE_PAL // returns the connectiongroupname else the Sid for current credentials private String GetSid() { if (_connectionGroupName != null) { return _connectionGroupName; } #if !FEATURE_PAL return CoreChannel.GetCurrentSidString(); #else return null; #endif } // transport sink state private String m_machineName; private int m_port; private TcpClientChannel _channel = null; private String _machineAndPort; private const String UserNameKey = "username"; private const String PasswordKey = "password"; private const String DomainKey = "domain"; private const String ProtectionLevelKey = "protectionlevel"; private const String ConnectionGroupNameKey = "connectiongroupname"; #if !FEATURE_PAL private const String TokenImpersonationLevelKey = "tokenimpersonationlevel"; #endif // !FEATURE_PAL private const String SocketCacheTimeoutKey = "socketcachetimeout"; private const String ReceiveTimeoutKey = "timeout"; private const String SocketCachePolicyKey = "socketcachepolicy"; private const String SPNKey = "serviceprincipalname"; private const String RetryCountKey = "retrycount"; // property values private String _securityUserName = null; private String _securityPassword = null; private String _securityDomain = null; private String _connectionGroupName = null; private TimeSpan _socketCacheTimeout = TimeSpan.FromSeconds(10); // default timeout is 5 seconds private int _receiveTimeout = 0; // default timeout is infinite private SocketCachePolicy _socketCachePolicy = SocketCachePolicy.Default; // default is v1.0 behaviour private String _spn = string.Empty; private int _retryCount = 1; // defualt retry is 1 to keep it equivalent with v1.1 #if !FEATURE_PAL private TokenImpersonationLevel _tokenImpersonationLevel = TokenImpersonationLevel.Identification; // default is no authentication #endif // !FEATURE_PAL private ProtectionLevel _protectionLevel = ProtectionLevel.EncryptAndSign; private static ICollection s_keySet = null; internal TcpClientTransportSink(String channelURI, TcpClientChannel channel) { String objectURI; _channel = channel; String simpleChannelUri = TcpChannelHelper.ParseURL(channelURI, out objectURI); ClientSocketCache = new SocketCache(new SocketHandlerFactory(this.CreateSocketHandler), _socketCachePolicy, _socketCacheTimeout); // extract machine name and port Uri uri = new Uri(simpleChannelUri); if (uri.IsDefaultPort) { // If there is no colon, then there is no port number. throw new RemotingException( String.Format( CultureInfo.CurrentCulture, CoreChannel.GetResourceString( "Remoting_Tcp_UrlMustHavePort"), channelURI)); } m_machineName = uri.Host; IPAddress ipAddr = null; IPAddress.TryParse(m_machineName, out ipAddr); if ((ipAddr != null) && (ipAddr.IsIPv6LinkLocal || ipAddr.IsIPv6SiteLocal)) { m_machineName = "[" + uri.DnsSafeHost + "]"; } m_port = uri.Port; _machineAndPort = m_machineName + ":" + m_port; } // TcpClientTransportSink public void ProcessMessage(IMessage msg, ITransportHeaders requestHeaders, Stream requestStream, out ITransportHeaders responseHeaders, out Stream responseStream) { InternalRemotingServices.RemotingTrace("TcpClientTransportSink::ProcessMessage"); // the call to SendRequest can block a func eval, so we want to notify the debugger that we're // about to call a blocking operation. System.Diagnostics.Debugger.NotifyOfCrossThreadDependency(); TcpClientSocketHandler clientSocket = SendRequestWithRetry(msg, requestHeaders, requestStream); // receive response responseHeaders = clientSocket.ReadHeaders(); responseStream = clientSocket.GetResponseStream(); // The client socket will be returned to the cache // when the response stream is closed. } // ProcessMessage public void AsyncProcessRequest(IClientChannelSinkStack sinkStack, IMessage msg, ITransportHeaders headers, Stream stream) { InternalRemotingServices.RemotingTrace("TcpClientTransportSink::AsyncProcessRequest"); TcpClientSocketHandler clientSocket = SendRequestWithRetry(msg, headers, stream); if (clientSocket.OneWayRequest) { clientSocket.ReturnToCache(); } else { // do an async read on the reply clientSocket.DataArrivedCallback = new WaitCallback(this.ReceiveCallback); clientSocket.DataArrivedCallbackState = sinkStack; clientSocket.BeginReadMessage(); } } // AsyncProcessRequest public void AsyncProcessResponse(IClientResponseChannelSinkStack sinkStack, Object state, ITransportHeaders headers, Stream stream) { // We don't have to implement this since we are always last in the chain. throw new NotSupportedException(); } // AsyncProcessRequest public Stream GetRequestStream(IMessage msg, ITransportHeaders headers) { // Currently, we require a memory stream be handed to us since we need // the length before sending. return null; } // GetRequestStream public IClientChannelSink NextChannelSink { get { return null; } } // Next private TcpClientSocketHandler SendRequestWithRetry(IMessage msg, ITransportHeaders requestHeaders, Stream requestStream) { // If the stream is seekable, we can retry once on a failure to write. long initialPosition = 0; bool sendException = true; bool bCanSeek = requestStream.CanSeek; if (bCanSeek) initialPosition = requestStream.Position; TcpClientSocketHandler clientSocket = null; // Add the sid string only if the channel is secure. String machinePortAndSid = _machineAndPort + (_channel.IsSecured ? "/" + GetSid() : null); // The authentication config entries are only valid if secure is true if (authSet && !_channel.IsSecured) throw new RemotingException(CoreChannel.GetResourceString( "Remoting_Tcp_AuthenticationConfigClient")); // If explicitUserName is set but connectionGroupName isnt we will need to authenticate on each call bool openNewAlways = (_channel.IsSecured) && (_securityUserName != null) && (_connectionGroupName == null); try { clientSocket = (TcpClientSocketHandler)ClientSocketCache.GetSocket(machinePortAndSid, openNewAlways); clientSocket.SendRequest(msg, requestHeaders, requestStream); } catch (SocketException) { // Retry sending if socketexception occured, stream is seekable, retrycount times for(int count = 0; (count < _retryCount) && (bCanSeek && sendException); count++) { // retry sending if possible try { // reset position... requestStream.Position = initialPosition; // ...and try again. clientSocket = (TcpClientSocketHandler) ClientSocketCache.GetSocket(machinePortAndSid, openNewAlways); clientSocket.SendRequest(msg, requestHeaders, requestStream); sendException = false; } catch(SocketException) { } } if (sendException){ throw; } } requestStream.Close(); return clientSocket; } // SendRequestWithRetry private void ReceiveCallback(Object state) { TcpClientSocketHandler clientSocket = null; IClientChannelSinkStack sinkStack = null; try { clientSocket = (TcpClientSocketHandler)state; sinkStack = (IClientChannelSinkStack)clientSocket.DataArrivedCallbackState; ITransportHeaders responseHeaders = clientSocket.ReadHeaders(); Stream responseStream = clientSocket.GetResponseStream(); // call down the sink chain sinkStack.AsyncProcessResponse(responseHeaders, responseStream); } catch (Exception e) { try { if (sinkStack != null) sinkStack.DispatchException(e); } catch { // Fatal Error.. ignore } } // The client socket will be returned to the cache // when the response stream is closed. } // ReceiveCallback // // Properties // public override Object this[Object key] { get { String keyStr = key as String; if (keyStr == null) return null; switch (keyStr.ToLower(CultureInfo.InvariantCulture)) { case UserNameKey: return _securityUserName; case PasswordKey: return null; // Intentionally refuse to return password. case DomainKey: return _securityDomain; case SocketCacheTimeoutKey: return _socketCacheTimeout; case ReceiveTimeoutKey: return _receiveTimeout; case SocketCachePolicyKey: return _socketCachePolicy.ToString(); case RetryCountKey: return _retryCount; case ConnectionGroupNameKey: return _connectionGroupName; #if !FEATURE_PAL case TokenImpersonationLevelKey: if (authSet) return _tokenImpersonationLevel.ToString(); break; #endif // !FEATURE_PAL case ProtectionLevelKey: if (authSet) return _protectionLevel.ToString(); break; } // switch (keyStr.ToLower(CultureInfo.InvariantCulture)) return null; } set { String keyStr = key as String; if (keyStr == null) return; switch (keyStr.ToLower(CultureInfo.InvariantCulture)) { case UserNameKey: _securityUserName = (String)value; break; case PasswordKey: _securityPassword = (String)value; break; case DomainKey: _securityDomain = (String)value; break; case SocketCacheTimeoutKey: int timeout = Convert.ToInt32(value, CultureInfo.InvariantCulture); if (timeout < 0) throw new RemotingException( CoreChannel.GetResourceString( "Remoting_Tcp_SocketTimeoutNegative")); _socketCacheTimeout = TimeSpan.FromSeconds(timeout); ClientSocketCache.SocketTimeout = _socketCacheTimeout; break; case ReceiveTimeoutKey: _receiveTimeout = Convert.ToInt32(value, CultureInfo.InvariantCulture); ClientSocketCache.ReceiveTimeout = _receiveTimeout; break; case SocketCachePolicyKey: _socketCachePolicy = (SocketCachePolicy)(value is SocketCachePolicy ? value : Enum.Parse(typeof(SocketCachePolicy), (String)value, true)); ClientSocketCache.CachePolicy = _socketCachePolicy; break; case RetryCountKey: _retryCount = Convert.ToInt32(value, CultureInfo.InvariantCulture); break; case ConnectionGroupNameKey: _connectionGroupName = (String)value; break; #if !FEATURE_PAL case TokenImpersonationLevelKey: _tokenImpersonationLevel = (TokenImpersonationLevel)(value is TokenImpersonationLevel ? value : Enum.Parse(typeof(TokenImpersonationLevel), (String)value, true)); authSet = true; break; #endif // !FEATURE_PAL case ProtectionLevelKey: _protectionLevel = (ProtectionLevel)(value is ProtectionLevel ? value : Enum.Parse(typeof(ProtectionLevel), (String)value, true)); authSet = true; break; case SPNKey: _spn = (String)value; authSet = true; break; } // switch (keyStr.ToLower(CultureInfo.InvariantCulturey)) } } // this[] public override ICollection Keys { get { if (s_keySet == null) { // Don't need to synchronize. Doesn't matter if the list gets // generated twice. ArrayList keys = new ArrayList(6); keys.Add(UserNameKey); keys.Add(PasswordKey); keys.Add(DomainKey); keys.Add(SocketCacheTimeoutKey); keys.Add(SocketCachePolicyKey); keys.Add(RetryCountKey); #if !FEATURE_PAL keys.Add(TokenImpersonationLevelKey); #endif // !FEATURE_PAL keys.Add(ProtectionLevelKey); keys.Add(ConnectionGroupNameKey); keys.Add(ReceiveTimeoutKey); s_keySet = keys; } return s_keySet; } } // Keys // // end of Properties // } // class TcpClientTransportSink } // namespace namespace System.Runtime.Remoting.Channels.Tcp
// dnlib: See LICENSE.txt for more info using System; using System.Collections.Generic; using dnlib.PE; namespace dnlib.DotNet.MD { /// <summary> /// Reads .NET metadata /// </summary> public abstract class Metadata : IDisposable { /// <summary> /// <c>true</c> if the compressed (normal) metadata is used, <c>false</c> if the non-compressed /// (Edit N' Continue) metadata is used. This can be <c>false</c> even if the table stream /// is <c>#~</c> but that's very uncommon. /// </summary> public abstract bool IsCompressed { get; } /// <summary> /// <c>true</c> if this is standalone Portable PDB metadata /// </summary> public abstract bool IsStandalonePortablePdb { get; } /// <summary> /// Gets the .NET header /// </summary> public abstract ImageCor20Header ImageCor20Header { get; } /// <summary> /// Gets the version found in the metadata header. The major version number is in the high 16 bits /// and the lower version number is in the low 16 bits. /// </summary> public abstract uint Version { get; } /// <summary> /// Gets the version string found in the metadata header /// </summary> public abstract string VersionString { get; } /// <summary> /// Gets the <see cref="IPEImage"/> /// </summary> public abstract IPEImage PEImage { get; } /// <summary> /// Gets the metadata header /// </summary> public abstract MetadataHeader MetadataHeader { get; } /// <summary> /// Returns the #Strings stream or a default empty one if it's not present /// </summary> public abstract StringsStream StringsStream { get; } /// <summary> /// Returns the #US stream or a default empty one if it's not present /// </summary> public abstract USStream USStream { get; } /// <summary> /// Returns the #Blob stream or a default empty one if it's not present /// </summary> public abstract BlobStream BlobStream { get; } /// <summary> /// Returns the #GUID stream or a default empty one if it's not present /// </summary> public abstract GuidStream GuidStream { get; } /// <summary> /// Returns the #~ or #- tables stream /// </summary> public abstract TablesStream TablesStream { get; } /// <summary> /// Returns the #Pdb stream or null if it's not a standalone portable PDB file /// </summary> public abstract PdbStream PdbStream { get; } /// <summary> /// Gets all streams /// </summary> public abstract IList<DotNetStream> AllStreams { get; } /// <summary> /// Gets a list of all the valid <c>TypeDef</c> rids. It's usually every rid in the /// <c>TypeDef</c> table, but could be less if a type has been deleted. /// </summary> public abstract RidList GetTypeDefRidList(); /// <summary> /// Gets a list of all the valid <c>ExportedType</c> rids. It's usually every rid in the /// <c>ExportedType</c> table, but could be less if a type has been deleted. /// </summary> public abstract RidList GetExportedTypeRidList(); /// <summary> /// Gets the <c>Field</c> rid list /// </summary> /// <param name="typeDefRid"><c>TypeDef</c> rid</param> /// <returns>A new <see cref="RidList"/> instance</returns> public abstract RidList GetFieldRidList(uint typeDefRid); /// <summary> /// Gets the <c>Method</c> rid list /// </summary> /// <param name="typeDefRid"><c>TypeDef</c> rid</param> /// <returns>A new <see cref="RidList"/> instance</returns> public abstract RidList GetMethodRidList(uint typeDefRid); /// <summary> /// Gets the <c>Param</c> rid list /// </summary> /// <param name="methodRid"><c>Method</c> rid</param> /// <returns>A new <see cref="RidList"/> instance</returns> public abstract RidList GetParamRidList(uint methodRid); /// <summary> /// Gets the <c>Event</c> rid list /// </summary> /// <param name="eventMapRid"><c>EventMap</c> rid</param> /// <returns>A new <see cref="RidList"/> instance</returns> public abstract RidList GetEventRidList(uint eventMapRid); /// <summary> /// Gets the <c>Property</c> rid list /// </summary> /// <param name="propertyMapRid"><c>PropertyMap</c> rid</param> /// <returns>A new <see cref="RidList"/> instance</returns> public abstract RidList GetPropertyRidList(uint propertyMapRid); /// <summary> /// Finds all <c>InterfaceImpl</c> rids owned by <paramref name="typeDefRid"/> /// </summary> /// <param name="typeDefRid">Owner <c>TypeDef</c> rid</param> /// <returns>A <see cref="RidList"/> instance containing the valid <c>InterfaceImpl</c> rids</returns> public abstract RidList GetInterfaceImplRidList(uint typeDefRid); /// <summary> /// Finds all <c>GenericParam</c> rids owned by <paramref name="rid"/> in table <paramref name="table"/> /// </summary> /// <param name="table">A <c>TypeOrMethodDef</c> table</param> /// <param name="rid">Owner rid</param> /// <returns>A <see cref="RidList"/> instance containing the valid <c>GenericParam</c> rids</returns> public abstract RidList GetGenericParamRidList(Table table, uint rid); /// <summary> /// Finds all <c>GenericParamConstraint</c> rids owned by <paramref name="genericParamRid"/> /// </summary> /// <param name="genericParamRid">Owner <c>GenericParam</c> rid</param> /// <returns>A <see cref="RidList"/> instance containing the valid <c>GenericParamConstraint</c> rids</returns> public abstract RidList GetGenericParamConstraintRidList(uint genericParamRid); /// <summary> /// Finds all <c>CustomAttribute</c> rids owned by <paramref name="rid"/> in table <paramref name="table"/> /// </summary> /// <param name="table">A <c>HasCustomAttribute</c> table</param> /// <param name="rid">Owner rid</param> /// <returns>A <see cref="RidList"/> instance containing the valid <c>CustomAttribute</c> rids</returns> public abstract RidList GetCustomAttributeRidList(Table table, uint rid); /// <summary> /// Finds all <c>DeclSecurity</c> rids owned by <paramref name="rid"/> in table <paramref name="table"/> /// </summary> /// <param name="table">A <c>HasDeclSecurity</c> table</param> /// <param name="rid">Owner rid</param> /// <returns>A <see cref="RidList"/> instance containing the valid <c>DeclSecurity</c> rids</returns> public abstract RidList GetDeclSecurityRidList(Table table, uint rid); /// <summary> /// Finds all <c>MethodSemantics</c> rids owned by <paramref name="rid"/> in table <paramref name="table"/> /// </summary> /// <param name="table">A <c>HasSemantic</c> table</param> /// <param name="rid">Owner rid</param> /// <returns>A <see cref="RidList"/> instance containing the valid <c>MethodSemantics</c> rids</returns> public abstract RidList GetMethodSemanticsRidList(Table table, uint rid); /// <summary> /// Finds all <c>MethodImpl</c> rids owned by <paramref name="typeDefRid"/> /// </summary> /// <param name="typeDefRid">Owner <c>TypeDef</c> rid</param> /// <returns>A <see cref="RidList"/> instance containing the valid <c>MethodImpl</c> rids</returns> public abstract RidList GetMethodImplRidList(uint typeDefRid); /// <summary> /// Finds a <c>ClassLayout</c> rid /// </summary> /// <param name="typeDefRid">Owner <c>TypeDef</c> rid</param> /// <returns>The <c>ClassLayout</c> rid or 0 if <paramref name="typeDefRid"/> is invalid /// or if it has no row in the <c>ClassLayout</c> table.</returns> public abstract uint GetClassLayoutRid(uint typeDefRid); /// <summary> /// Finds a <c>FieldLayout</c> rid /// </summary> /// <param name="fieldRid">Owner <c>Field</c> rid</param> /// <returns>The <c>FieldLayout</c> rid or 0 if <paramref name="fieldRid"/> is invalid /// or if it has no row in the <c>FieldLayout</c> table.</returns> public abstract uint GetFieldLayoutRid(uint fieldRid); /// <summary> /// Finds a <c>FieldMarshal</c> rid /// </summary> /// <param name="table">A <c>HasFieldMarshal</c> table</param> /// <param name="rid">Owner rid</param> /// <returns>The <c>FieldMarshal</c> rid or 0 if <paramref name="rid"/> is invalid /// or if it has no row in the <c>FieldMarshal</c> table.</returns> public abstract uint GetFieldMarshalRid(Table table, uint rid); /// <summary> /// Finds a <c>FieldRVA</c> rid /// </summary> /// <param name="fieldRid">Owner <c>Field</c> rid</param> /// <returns>The <c>FieldRVA</c> rid or 0 if <paramref name="fieldRid"/> is invalid /// or if it has no row in the <c>FieldRVA</c> table.</returns> public abstract uint GetFieldRVARid(uint fieldRid); /// <summary> /// Finds an <c>ImplMap</c> rid /// </summary> /// <param name="table">A <c>MemberForwarded</c> table</param> /// <param name="rid">Owner rid</param> /// <returns>The <c>ImplMap</c> rid or 0 if <paramref name="rid"/> is invalid /// or if it has no row in the <c>ImplMap</c> table.</returns> public abstract uint GetImplMapRid(Table table, uint rid); /// <summary> /// Finds a <c>NestedClass</c> rid /// </summary> /// <param name="typeDefRid">Owner <c>TypeDef</c> rid</param> /// <returns>The <c>NestedClass</c> rid or 0 if <paramref name="typeDefRid"/> is invalid /// or if it has no row in the <c>NestedClass</c> table.</returns> public abstract uint GetNestedClassRid(uint typeDefRid); /// <summary> /// Finds an <c>EventMap</c> rid /// </summary> /// <param name="typeDefRid">Owner <c>TypeDef</c> rid</param> /// <returns>The <c>EventMap</c> rid or 0 if <paramref name="typeDefRid"/> is invalid /// or if it has no row in the <c>EventMap</c> table.</returns> public abstract uint GetEventMapRid(uint typeDefRid); /// <summary> /// Finds a <c>PropertyMap</c> rid /// </summary> /// <param name="typeDefRid">Owner <c>TypeDef</c> rid</param> /// <returns>The <c>PropertyMap</c> rid or 0 if <paramref name="typeDefRid"/> is invalid /// or if it has no row in the <c>PropertyMap</c> table.</returns> public abstract uint GetPropertyMapRid(uint typeDefRid); /// <summary> /// Finds a <c>Constant</c> rid /// </summary> /// <param name="table">A <c>HasConstant</c> table</param> /// <param name="rid">Owner rid</param> /// <returns>The <c>Constant</c> rid or 0 if <paramref name="rid"/> is invalid /// or if it has no row in the <c>Constant</c> table.</returns> public abstract uint GetConstantRid(Table table, uint rid); /// <summary> /// Returns the owner <c>TypeDef</c> rid /// </summary> /// <param name="fieldRid">A <c>Field</c> rid</param> /// <returns>The owner <c>TypeDef</c> rid or 0 if <paramref name="fieldRid"/> is invalid /// or if it has no owner.</returns> public abstract uint GetOwnerTypeOfField(uint fieldRid); /// <summary> /// Returns the owner <c>TypeDef</c> rid /// </summary> /// <param name="methodRid">A <c>Method</c> rid</param> /// <returns>The owner <c>TypeDef</c> rid or 0 if <paramref name="methodRid"/> is invalid /// or if it has no owner.</returns> public abstract uint GetOwnerTypeOfMethod(uint methodRid); /// <summary> /// Returns the owner <c>TypeDef</c> rid /// </summary> /// <param name="eventRid">A <c>Event</c> rid</param> /// <returns>The owner <c>TypeDef</c> rid or 0 if <paramref name="eventRid"/> is invalid /// or if it has no owner.</returns> public abstract uint GetOwnerTypeOfEvent(uint eventRid); /// <summary> /// Returns the owner <c>TypeDef</c> rid /// </summary> /// <param name="propertyRid">A <c>Property</c> rid</param> /// <returns>The owner <c>TypeDef</c> rid or 0 if <paramref name="propertyRid"/> is invalid /// or if it has no owner.</returns> public abstract uint GetOwnerTypeOfProperty(uint propertyRid); /// <summary> /// Returns the owner <c>TypeOrMethodDef</c> rid /// </summary> /// <param name="gpRid">A <c>GenericParam</c> rid</param> /// <returns>The owner <c>TypeOrMethodDef</c> rid or 0 if <paramref name="gpRid"/> is /// invalid or if it has no owner.</returns> public abstract uint GetOwnerOfGenericParam(uint gpRid); /// <summary> /// Returns the owner <c>GenericParam</c> rid /// </summary> /// <param name="gpcRid">A <c>GenericParamConstraint</c> rid</param> /// <returns>The owner <c>GenericParam</c> rid or 0 if <paramref name="gpcRid"/> is /// invalid or if it has no owner.</returns> public abstract uint GetOwnerOfGenericParamConstraint(uint gpcRid); /// <summary> /// Returns the owner <c>Method</c> rid /// </summary> /// <param name="paramRid">A <c>Param</c> rid</param> /// <returns>The owner <c>Method</c> rid or 0 if <paramref name="paramRid"/> is invalid /// or if it has no owner.</returns> public abstract uint GetOwnerOfParam(uint paramRid); /// <summary> /// Gets a list of all nested classes owned by <paramref name="typeDefRid"/> /// </summary> /// <param name="typeDefRid">A <c>TypeDef</c> rid</param> /// <returns>A new <see cref="RidList"/> instance</returns> public abstract RidList GetNestedClassRidList(uint typeDefRid); /// <summary> /// Gets a list of all non-nested classes. A type is a non-nested type if /// <see cref="GetNestedClassRidList(uint)"/> returns an empty list. /// </summary> /// <returns>A new <see cref="RidList"/> instance</returns> public abstract RidList GetNonNestedClassRidList(); /// <summary> /// Finds all <c>LocalScope</c> rids owned by <paramref name="methodRid"/> /// </summary> /// <param name="methodRid">Owner <c>Method</c> rid</param> /// <returns>A <see cref="RidList"/> instance containing the valid <c>LocalScope</c> rids</returns> public abstract RidList GetLocalScopeRidList(uint methodRid); /// <summary> /// Finds all <c>LocalVariable</c> rids owned by <paramref name="localScopeRid"/> /// </summary> /// <param name="localScopeRid">Owner <c>LocalScope</c> rid</param> /// <returns>A <see cref="RidList"/> instance containing the valid <c>LocalVariable</c> rids</returns> public abstract RidList GetLocalVariableRidList(uint localScopeRid); /// <summary> /// Finds all <c>LocalConstant</c> rids owned by <paramref name="localScopeRid"/> /// </summary> /// <param name="localScopeRid">Owner <c>LocalScope</c> rid</param> /// <returns>A <see cref="RidList"/> instance containing the valid <c>LocalConstant</c> rids</returns> public abstract RidList GetLocalConstantRidList(uint localScopeRid); /// <summary> /// Gets the <c>StateMachineMethod</c> rid or 0 if it's not a state machine method /// </summary> /// <param name="methodRid">Owner <c>Method</c> rid</param> /// <returns></returns> public abstract uint GetStateMachineMethodRid(uint methodRid); /// <summary> /// Finds all <c>CustomDebugInformation</c> rids owned by <paramref name="rid"/> in table <paramref name="table"/> /// </summary> /// <param name="table">A <c>HasCustomDebugInformation</c> table</param> /// <param name="rid">Owner rid</param> /// <returns>A <see cref="RidList"/> instance containing the valid <c>CustomDebugInformation</c> rids</returns> public abstract RidList GetCustomDebugInformationRidList(Table table, uint rid); /// <summary> /// Disposes of this instance /// </summary> public abstract void Dispose(); } }
/* * $Id: IrcUser.cs 198 2005-06-08 16:50:11Z meebey $ * $URL: svn+ssh://svn.qnetp.net/svn/smartirc/SmartIrc4net/trunk/src/IrcClient/IrcUser.cs $ * $Rev: 198 $ * $Author: meebey $ * $Date: 2005-06-08 18:50:11 +0200 (Wed, 08 Jun 2005) $ * * SmartIrc4net - the IRC library for .NET/C# <http://smartirc4net.sf.net> * * Copyright (c) 2008 Mirco Bauer <meebey@meebey.net> <http://www.meebey.net> * * Full LGPL License: <http://www.gnu.org/licenses/lgpl.txt> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; namespace Meebey.SmartIrc4net { public class WhoInfo { private string f_Channel; private string f_Ident; private string f_Host; private string f_Server; private string f_Nick; private int f_HopCount; private string f_Realname; private bool f_IsAway; private bool f_IsOwner; private bool f_IsChannelAdmin; private bool f_IsOp; private bool f_IsHalfop; private bool f_IsVoice; private bool f_IsIrcOp; private bool f_IsRegistered; public string Channel { get { return f_Channel; } } public string Ident { get { return f_Ident; } } public string Host { get { return f_Host; } } public string Server { get { return f_Server; } } public string Nick { get { return f_Nick; } } public int HopCount { get { return f_HopCount; } } public string Realname { get { return f_Realname; } } public bool IsAway { get { return f_IsAway; } } public bool IsOwner { get { return f_IsOwner; } } public bool IsChannelAdmin { get { return f_IsChannelAdmin; } } public bool IsOp { get { return f_IsOp; } } public bool IsHalfop { get { return f_IsHalfop; } } public bool IsVoice { get { return f_IsVoice; } } public bool IsIrcOp { get { return f_IsIrcOp; } } public bool IsRegistered { get { return f_IsRegistered; } } private WhoInfo() { } public static WhoInfo Parse(IrcMessageData data) { WhoInfo whoInfo = new WhoInfo(); // :fu-berlin.de 352 meebey_ * ~meebey e176002059.adsl.alicedsl.de fu-berlin.de meebey_ H :0 Mirco Bauer.. whoInfo.f_Channel = data.RawMessageArray[3]; whoInfo.f_Ident = data.RawMessageArray[4]; whoInfo.f_Host = data.RawMessageArray[5]; whoInfo.f_Server = data.RawMessageArray[6]; whoInfo.f_Nick = data.RawMessageArray[7]; // HACK: realname field can be empty on bugged IRCds like InspIRCd-2.0 // :topiary.voxanon.net 352 Mirco #anonplusradio CpGc igot.avhost Voxanon CpGc H if (data.MessageArray == null || data.MessageArray.Length < 2) { whoInfo.f_Realname = String.Empty; } else { int hopcount = 0; var hopcountStr = data.MessageArray[0]; if (Int32.TryParse(hopcountStr, out hopcount)) { whoInfo.f_HopCount = hopcount; } else { #if LOG4NET Logger.MessageParser.Warn("Parse(): couldn't parse hopcount (as int): '" + hopcountStr + "'"); #endif } // skip hop count whoInfo.f_Realname = String.Join(" ", data.MessageArray, 1, data.MessageArray.Length - 1); } string usermode = data.RawMessageArray[8]; bool owner = false; bool chanadmin = false; bool op = false; bool halfop = false; bool voice = false; bool ircop = false; bool away = false; bool registered = false; int usermodelength = usermode.Length; for (int i = 0; i < usermodelength; i++) { switch (usermode[i]) { case 'H': away = false; break; case 'G': away = true; break; case '~': owner = true; break; case '&': chanadmin = true; break; case '@': op = true; break; case '%': halfop = true; break; case '+': voice = true; break; case '*': ircop = true; break; case 'r': registered = true; break; } } whoInfo.f_IsAway = away; whoInfo.f_IsOwner = owner; whoInfo.f_IsChannelAdmin = chanadmin; whoInfo.f_IsOp = op; whoInfo.f_IsHalfop = halfop; whoInfo.f_IsVoice = voice; whoInfo.f_IsIrcOp = ircop; whoInfo.f_IsRegistered = registered; return whoInfo; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Reflection; using Xunit; namespace System.Linq.Expressions.Tests { public class OpAssign { [Theory] [PerCompilationType(nameof(AssignAndEquivalentMethods))] public void AssignmentEquivalents(MethodInfo nonAssign, MethodInfo assign, Type type, bool useInterpreter) { Func<Expression, Expression, Expression> withoutAssignment = (Func<Expression, Expression, Expression>)nonAssign.CreateDelegate(typeof(Func<Expression, Expression, Expression>)); Func<Expression, Expression, Expression> withAssignment = (Func<Expression, Expression, Expression>)assign.CreateDelegate(typeof(Func<Expression, Expression, Expression>)); foreach (object x in new[] { 0, -1, 1, 10 }.Select(i => Convert.ChangeType(i, type))) foreach (object y in new[] { -1, 1, 10 }.Select(i => Convert.ChangeType(i, type))) { ConstantExpression xExp = Expression.Constant(x); ConstantExpression yExp = Expression.Constant(y); Expression woAssign = withoutAssignment(xExp, yExp); ParameterExpression variable = Expression.Variable(type); Expression initAssign = Expression.Assign(variable, xExp); Expression assignment = withAssignment(variable, yExp); Expression wAssign = Expression.Block( new ParameterExpression[] { variable }, initAssign, assignment ); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(woAssign, wAssign)).Compile(useInterpreter)()); LabelTarget target = Expression.Label(type); Expression wAssignReturningVariable = Expression.Block( new ParameterExpression[] { variable }, initAssign, assignment, Expression.Return(target, variable), Expression.Label(target, Expression.Default(type)) ); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(woAssign, wAssignReturningVariable)).Compile(useInterpreter)()); } } private class Box<T> { public static T StaticValue { get; set; } public T Value { get; set; } public T this[int index] { get { return Value; } set { Value = value; } } public Box(T value) { Value = value; } } [Theory] [PerCompilationType(nameof(AssignAndEquivalentMethods))] public void AssignmentEquivalentsWithMemberAccess(MethodInfo nonAssign, MethodInfo assign, Type type, bool useInterpreter) { Func<Expression, Expression, Expression> withoutAssignment = (Func<Expression, Expression, Expression>)nonAssign.CreateDelegate(typeof(Func<Expression, Expression, Expression>)); Func<Expression, Expression, Expression> withAssignment = (Func<Expression, Expression, Expression>)assign.CreateDelegate(typeof(Func<Expression, Expression, Expression>)); foreach (object x in new[] { 0, -1, 1, 10 }.Select(i => Convert.ChangeType(i, type))) foreach (object y in new[] { -1, 1, 10 }.Select(i => Convert.ChangeType(i, type))) { ConstantExpression xExp = Expression.Constant(x); ConstantExpression yExp = Expression.Constant(y); Expression woAssign = withoutAssignment(xExp, yExp); Type boxType = typeof(Box<>).MakeGenericType(type); object box = boxType.GetConstructor(new[] { type }).Invoke(new object[] { x }); Expression boxExp = Expression.Constant(box); Expression property = Expression.Property(boxExp, boxType.GetProperty("Value")); Expression assignment = withAssignment(property, yExp); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(woAssign, assignment)).Compile(useInterpreter)()); LabelTarget target = Expression.Label(type); box = boxType.GetConstructor(new[] { type }).Invoke(new object[] { x }); boxExp = Expression.Constant(box); property = Expression.Property(boxExp, boxType.GetProperty("Value")); assignment = withAssignment(property, yExp); Expression wAssignReturningVariable = Expression.Block( assignment, Expression.Return(target, property), Expression.Label(target, Expression.Default(type)) ); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(woAssign, wAssignReturningVariable)).Compile(useInterpreter)()); } } [Theory, PerCompilationType(nameof(AssignAndEquivalentMethods))] public void AssignmentEquivalentsWithStaticMemberAccess(MethodInfo nonAssign, MethodInfo assign, Type type, bool useInterpreter) { Func<Expression, Expression, Expression> withoutAssignment = (Func<Expression, Expression, Expression>)nonAssign.CreateDelegate(typeof(Func<Expression, Expression, Expression>)); Func<Expression, Expression, Expression> withAssignment = (Func<Expression, Expression, Expression>)assign.CreateDelegate(typeof(Func<Expression, Expression, Expression>)); foreach (object x in new[] { 0, -1, 1, 10 }.Select(i => Convert.ChangeType(i, type))) foreach (object y in new[] { -1, 1, 10 }.Select(i => Convert.ChangeType(i, type))) { ConstantExpression xExp = Expression.Constant(x); ConstantExpression yExp = Expression.Constant(y); Expression woAssign = withoutAssignment(xExp, yExp); Type boxType = typeof(Box<>).MakeGenericType(type); PropertyInfo prop = boxType.GetProperty("StaticValue"); prop.SetValue(null, x); Expression property = Expression.Property(null, prop); Expression assignment = withAssignment(property, yExp); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(woAssign, assignment)).Compile(useInterpreter)()); prop.SetValue(null, x); Expression wAssignReturningVariable = Expression.Block( assignment, property ); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(woAssign, wAssignReturningVariable)).Compile(useInterpreter)()); } } [Theory] [PerCompilationType(nameof(AssignAndEquivalentMethods))] public void AssignmentEquivalentsWithIndexAccess(MethodInfo nonAssign, MethodInfo assign, Type type, bool useInterpreter) { Func<Expression, Expression, Expression> withoutAssignment = (Func<Expression, Expression, Expression>)nonAssign.CreateDelegate(typeof(Func<Expression, Expression, Expression>)); Func<Expression, Expression, Expression> withAssignment = (Func<Expression, Expression, Expression>)assign.CreateDelegate(typeof(Func<Expression, Expression, Expression>)); foreach (object x in new[] { 0, -1, 1, 10 }.Select(i => Convert.ChangeType(i, type))) foreach (object y in new[] { -1, 1, 10 }.Select(i => Convert.ChangeType(i, type))) { ConstantExpression xExp = Expression.Constant(x); ConstantExpression yExp = Expression.Constant(y); Expression woAssign = withoutAssignment(xExp, yExp); Type boxType = typeof(Box<>).MakeGenericType(type); object box = boxType.GetConstructor(new[] { type }).Invoke(new object[] { x }); Expression boxExp = Expression.Constant(box); Expression property = Expression.Property(boxExp, boxType.GetProperty("Item"), Expression.Constant(0)); Expression assignment = withAssignment(property, yExp); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(woAssign, assignment)).Compile(useInterpreter)()); LabelTarget target = Expression.Label(type); box = boxType.GetConstructor(new[] { type }).Invoke(new object[] { x }); boxExp = Expression.Constant(box); property = Expression.Property(boxExp, boxType.GetProperty("Item"), Expression.Constant(0)); assignment = withAssignment(property, yExp); Expression wAssignReturningVariable = Expression.Block( assignment, Expression.Return(target, property), Expression.Label(target, Expression.Default(type)) ); Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(woAssign, wAssignReturningVariable)).Compile(useInterpreter)()); } } [Theory] [MemberData(nameof(AssignmentMethods))] public void AssignmentReducable(MethodInfo assign, Type type) { Func<Expression, Expression, Expression> withAssignment = (Func<Expression, Expression, Expression>)assign.CreateDelegate(typeof(Func<Expression, Expression, Expression>)); ParameterExpression variable = Expression.Variable(type); Expression assignment = withAssignment(variable, Expression.Default(type)); Assert.True(assignment.CanReduce); Assert.NotSame(assignment, assignment.ReduceAndCheck()); } [Theory] [MemberData(nameof(AssignmentMethods))] public void CannotAssignToNonWritable(MethodInfo assign, Type type) { Func<Expression, Expression, Expression> withAssignment = (Func<Expression, Expression, Expression>)assign.CreateDelegate(typeof(Func<Expression, Expression, Expression>)); AssertExtensions.Throws<ArgumentException>("left", () => withAssignment(Expression.Default(type), Expression.Default(type))); } [Theory] [MemberData(nameof(AssignmentMethods))] public void AssignmentWithMemberAccessReducable(MethodInfo assign, Type type) { Func<Expression, Expression, Expression> withAssignment = (Func<Expression, Expression, Expression>)assign.CreateDelegate(typeof(Func<Expression, Expression, Expression>)); Type boxType = typeof(Box<>).MakeGenericType(type); object box = boxType.GetConstructor(new[] { type }).Invoke(new object[] { Convert.ChangeType(0, type) }); Expression boxExp = Expression.Constant(box); Expression property = Expression.Property(boxExp, boxType.GetProperty("Value")); Expression assignment = withAssignment(property, Expression.Default(type)); Assert.True(assignment.CanReduce); Assert.NotSame(assignment, assignment.ReduceAndCheck()); } [Theory] [MemberData(nameof(AssignmentMethods))] public void AssignmentWithIndexAccessReducable(MethodInfo assign, Type type) { Func<Expression, Expression, Expression> withAssignment = (Func<Expression, Expression, Expression>)assign.CreateDelegate(typeof(Func<Expression, Expression, Expression>)); Type boxType = typeof(Box<>).MakeGenericType(type); object box = boxType.GetConstructor(new[] { type }).Invoke(new object[] { Convert.ChangeType(0, type) }); Expression boxExp = Expression.Constant(box); Expression property = Expression.Property(boxExp, boxType.GetProperty("Item"), Expression.Constant(0)); Expression assignment = withAssignment(property, Expression.Default(type)); Assert.True(assignment.CanReduce); Assert.NotSame(assignment, assignment.ReduceAndCheck()); } private static class Unreadable<T> { public static T WriteOnly { set { } } } [Theory] [MemberData(nameof(AssignmentMethods))] public static void ThrowsOnLeftUnreadable(MethodInfo assign, Type type) { Func<Expression, Expression, Expression> withAssignment = (Func<Expression, Expression, Expression>)assign.CreateDelegate(typeof(Func<Expression, Expression, Expression>)); Type unreadableType = typeof(Unreadable<>).MakeGenericType(type); Expression property = Expression.Property(null, unreadableType.GetProperty("WriteOnly")); AssertExtensions.Throws<ArgumentException>("left", () => withAssignment(property, Expression.Default(type))); } [Theory] [MemberData(nameof(AssignmentMethods))] public static void ThrowsOnRightUnreadable(MethodInfo assign, Type type) { Func<Expression, Expression, Expression> withAssignment = (Func<Expression, Expression, Expression>)assign.CreateDelegate(typeof(Func<Expression, Expression, Expression>)); Type unreadableType = typeof(Unreadable<>).MakeGenericType(type); Expression property = Expression.Property(null, unreadableType.GetProperty("WriteOnly")); Expression variable = Expression.Variable(type); AssertExtensions.Throws<ArgumentException>("right", () => withAssignment(variable, property)); } [Theory] [MemberData(nameof(AssignmentMethodsWithoutTypes))] public void ThrowIfNoSuchBinaryOperation(MethodInfo assign) { Func<Expression, Expression, Expression> withAssignment = (Func<Expression, Expression, Expression>)assign.CreateDelegate(typeof(Func<Expression, Expression, Expression>)); ParameterExpression variable = Expression.Variable(typeof(string)); Expression value = Expression.Default(typeof(string)); Assert.Throws<InvalidOperationException>(() => withAssignment(variable, value)); } private static IEnumerable<object[]> AssignmentMethods() { MethodInfo[] expressionMethods = typeof(Expression).GetMethods().Where(mi => mi.GetParameters().Length == 2).ToArray(); foreach (Tuple<string, string> names in AssignAndEquivalentMethodNames(true)) yield return new object[] { expressionMethods.First(mi => mi.Name == names.Item2), typeof(int) }; foreach (Tuple<string, string> names in AssignAndEquivalentMethodNames(false)) yield return new object[] { expressionMethods.First(mi => mi.Name == names.Item2), typeof(double) }; } private static IEnumerable<object[]> AssignmentMethodsWithoutTypes() { MethodInfo[] expressionMethods = typeof(Expression).GetMethods().Where(mi => mi.GetParameters().Length == 2).ToArray(); return AssignAndEquivalentMethodNames(true).Concat(AssignAndEquivalentMethodNames(false)) .Select(i => i.Item2) .Distinct() .Select(i => new object[] { expressionMethods.First(mi => mi.Name == i) }); } private static IEnumerable<object[]> AssignAndEquivalentMethods() { MethodInfo[] expressionMethods = typeof(Expression).GetMethods().Where(mi => mi.GetParameters().Length == 2).ToArray(); foreach (Tuple<string, string> names in AssignAndEquivalentMethodNames(true)) yield return new object[] { expressionMethods.First(mi => mi.Name == names.Item1), expressionMethods.First(mi => mi.Name == names.Item2), typeof(int) }; foreach (Tuple<string, string> names in AssignAndEquivalentMethodNames(false)) yield return new object[] { expressionMethods.First(mi => mi.Name == names.Item1), expressionMethods.First(mi => mi.Name == names.Item2), typeof(double) }; } private static IEnumerable<Tuple<string, string>> AssignAndEquivalentMethodNames(bool integral) { yield return Tuple.Create("Add", "AddAssign"); yield return Tuple.Create("AddChecked", "AddAssignChecked"); yield return Tuple.Create("Divide", "DivideAssign"); yield return Tuple.Create("Modulo", "ModuloAssign"); yield return Tuple.Create("Multiply", "MultiplyAssign"); yield return Tuple.Create("MultiplyChecked", "MultiplyAssignChecked"); yield return Tuple.Create("Subtract", "SubtractAssign"); yield return Tuple.Create("SubtractChecked", "SubtractAssignChecked"); if (integral) { yield return Tuple.Create("And", "AndAssign"); yield return Tuple.Create("ExclusiveOr", "ExclusiveOrAssign"); yield return Tuple.Create("LeftShift", "LeftShiftAssign"); yield return Tuple.Create("Or", "OrAssign"); yield return Tuple.Create("RightShift", "RightShiftAssign"); } else yield return Tuple.Create("Power", "PowerAssign"); } [Theory] [MemberData(nameof(ToStringData))] public static void ToStringTest(ExpressionType kind, string symbol, Type type) { BinaryExpression e = Expression.MakeBinary(kind, Expression.Parameter(type, "a"), Expression.Parameter(type, "b")); Assert.Equal($"(a {symbol} b)", e.ToString()); } private static IEnumerable<object[]> ToStringData() { return ToStringDataImpl().Select(t => new object[] { t.Item1, t.Item2, t.Item3 }); } private static IEnumerable<Tuple<ExpressionType, string, Type>> ToStringDataImpl() { yield return Tuple.Create(ExpressionType.AddAssign, "+=", typeof(int)); yield return Tuple.Create(ExpressionType.AddAssignChecked, "+=", typeof(int)); yield return Tuple.Create(ExpressionType.SubtractAssign, "-=", typeof(int)); yield return Tuple.Create(ExpressionType.SubtractAssignChecked, "-=", typeof(int)); yield return Tuple.Create(ExpressionType.MultiplyAssign, "*=", typeof(int)); yield return Tuple.Create(ExpressionType.MultiplyAssignChecked, "*=", typeof(int)); yield return Tuple.Create(ExpressionType.DivideAssign, "/=", typeof(int)); yield return Tuple.Create(ExpressionType.ModuloAssign, "%=", typeof(int)); yield return Tuple.Create(ExpressionType.PowerAssign, "**=", typeof(double)); yield return Tuple.Create(ExpressionType.LeftShiftAssign, "<<=", typeof(int)); yield return Tuple.Create(ExpressionType.RightShiftAssign, ">>=", typeof(int)); yield return Tuple.Create(ExpressionType.AndAssign, "&=", typeof(int)); yield return Tuple.Create(ExpressionType.AndAssign, "&&=", typeof(bool)); yield return Tuple.Create(ExpressionType.OrAssign, "|=", typeof(int)); yield return Tuple.Create(ExpressionType.OrAssign, "||=", typeof(bool)); yield return Tuple.Create(ExpressionType.ExclusiveOrAssign, "^=", typeof(int)); yield return Tuple.Create(ExpressionType.ExclusiveOrAssign, "^=", typeof(bool)); } private static IEnumerable<ExpressionType> AssignExpressionTypes { get { yield return ExpressionType.AddAssign; yield return ExpressionType.SubtractAssign; yield return ExpressionType.MultiplyAssign; yield return ExpressionType.AddAssignChecked; yield return ExpressionType.SubtractAssignChecked; yield return ExpressionType.MultiplyAssignChecked; yield return ExpressionType.DivideAssign; yield return ExpressionType.ModuloAssign; yield return ExpressionType.PowerAssign; yield return ExpressionType.AndAssign; yield return ExpressionType.OrAssign; yield return ExpressionType.RightShiftAssign; yield return ExpressionType.LeftShiftAssign; yield return ExpressionType.ExclusiveOrAssign; } } private static IEnumerable<Func<Expression, Expression, MethodInfo, BinaryExpression>> AssignExpressionMethodInfoUsingFactories { get { yield return Expression.AddAssign; yield return Expression.SubtractAssign; yield return Expression.MultiplyAssign; yield return Expression.AddAssignChecked; yield return Expression.SubtractAssignChecked; yield return Expression.MultiplyAssignChecked; yield return Expression.DivideAssign; yield return Expression.ModuloAssign; yield return Expression.PowerAssign; yield return Expression.AndAssign; yield return Expression.OrAssign; yield return Expression.RightShiftAssign; yield return Expression.LeftShiftAssign; yield return Expression.ExclusiveOrAssign; } } public static IEnumerable<object[]> AssignExpressionTypesArguments => AssignExpressionTypes.Select(t => new object[] {t}); public static IEnumerable<object[]> AssignExpressionMethodInfoUsingFactoriesArguments = AssignExpressionMethodInfoUsingFactories.Select(f => new object[] {f}); private static IEnumerable<LambdaExpression> NonUnaryLambdas { get { yield return Expression.Lambda<Action>(Expression.Empty()); Expression<Func<int, int, int>> exp = (x, y) => x + y; yield return exp; } } public static IEnumerable<object[]> AssignExpressionTypesAndNonUnaryLambdas => AssignExpressionTypes.SelectMany(t => NonUnaryLambdas, (t, l) => new object[] {t, l}); private static IEnumerable<LambdaExpression> NonIntegerReturnUnaryIntegerLambdas { get { ParameterExpression param = Expression.Parameter(typeof(int)); yield return Expression.Lambda<Action<int>>(Expression.Empty(), param); Expression<Func<int, long>> convL = x => x; yield return convL; Expression<Func<int, string>> toString = x => x.ToString(); yield return toString; } } public static IEnumerable<object[]> AssignExpressionTypesAndNonIntegerReturnUnaryIntegerLambdas => AssignExpressionTypes.SelectMany(t => NonIntegerReturnUnaryIntegerLambdas, (t, l) => new object[] {t, l}); private static IEnumerable<LambdaExpression> NonIntegerTakingUnaryIntegerReturningLambda { get { Expression<Func<long, int>> fromL = x => (int)x; yield return fromL; Expression<Func<string, int>> fromS = x => x.Length; yield return fromS; } } public static IEnumerable<object[]> AssignExpressionTypesAndNonIntegerTakingUnaryIntegerReturningLambda => AssignExpressionTypes.SelectMany( t => NonIntegerTakingUnaryIntegerReturningLambda, (t, l) => new object[] {t, l}); [Theory, MemberData(nameof(AssignExpressionTypesArguments))] public void CannotHaveConversionOnAssignWithoutMethod(ExpressionType type) { var lhs = Expression.Variable(typeof(int)); var rhs = Expression.Constant(0); Expression<Func<int, int>> identity = x => x; Assert.Throws<InvalidOperationException>(() => Expression.MakeBinary(type, lhs, rhs, false, null, identity)); Assert.Throws<InvalidOperationException>(() => Expression.MakeBinary(type, lhs, rhs, true, null, identity)); } public static int FiftyNinthBear(int x, int y) { // Ensure numbers add up to 40. Then ignore that and return 59. if (x + y != 40) throw new ArgumentException(); return 59; } [Theory, PerCompilationType(nameof(AssignExpressionTypesArguments))] public void ConvertAssignment(ExpressionType type, bool useInterpreter) { var lhs = Expression.Parameter(typeof(int)); var rhs = Expression.Constant(25); Expression<Func<int, int>> doubleIt = x => 2 * x; var lambda = Expression.Lambda<Func<int, int>>( Expression.MakeBinary(type, lhs, rhs, false, GetType().GetMethod(nameof(FiftyNinthBear)), doubleIt), lhs ); var func = lambda.Compile(useInterpreter); Assert.Equal(118, func(15)); } [Theory, MemberData(nameof(AssignExpressionTypesAndNonUnaryLambdas))] public void ConversionMustBeUnary(ExpressionType type, LambdaExpression conversion) { var lhs = Expression.Parameter(typeof(int)); var rhs = Expression.Constant(25); MethodInfo meth = GetType().GetMethod(nameof(FiftyNinthBear)); AssertExtensions.Throws<ArgumentException>( "conversion", () => Expression.MakeBinary(type, lhs, rhs, false, meth, conversion)); } [Theory, MemberData(nameof(AssignExpressionTypesAndNonIntegerReturnUnaryIntegerLambdas))] public void ConversionMustConvertToLHSType(ExpressionType type, LambdaExpression conversion) { var lhs = Expression.Parameter(typeof(int)); var rhs = Expression.Constant(25); MethodInfo meth = GetType().GetMethod(nameof(FiftyNinthBear)); Assert.Throws<InvalidOperationException>(() => Expression.MakeBinary(type, lhs, rhs, false, meth, conversion)); } [Theory, MemberData(nameof(AssignExpressionTypesAndNonIntegerTakingUnaryIntegerReturningLambda))] public void ConversionMustConvertFromRHSType(ExpressionType type, LambdaExpression conversion) { var lhs = Expression.Parameter(typeof(int)); var rhs = Expression.Constant(25); MethodInfo meth = GetType().GetMethod(nameof(FiftyNinthBear)); Assert.Throws<InvalidOperationException>(() => Expression.MakeBinary(type, lhs, rhs, false, meth, conversion)); } private class AddsToSomethingElse : IEquatable<AddsToSomethingElse> { public int Value { get; } public AddsToSomethingElse(int value) { Value = value; } public static int operator +(AddsToSomethingElse x, AddsToSomethingElse y) => x.Value + y.Value; public bool Equals(AddsToSomethingElse other) => Value == other?.Value; public override bool Equals(object obj) => Equals(obj as AddsToSomethingElse); public override int GetHashCode() => Value; } private static string StringAddition(int x, int y) => (x + y).ToString(); [Fact] public void CannotAssignOpIfOpReturnNotAssignable() { var lhs = Expression.Parameter(typeof(AddsToSomethingElse)); var rhs = Expression.Constant(new AddsToSomethingElse(3)); AssertExtensions.Throws<ArgumentException>(null, () => Expression.AddAssign(lhs, rhs)); } [Theory, ClassData(typeof(CompilationTypes))] public void CanAssignOpIfOpReturnNotAssignableButConversionFixes(bool useInterpreter) { var lhs = Expression.Parameter(typeof(AddsToSomethingElse)); var rhs = Expression.Constant(new AddsToSomethingElse(3)); Expression<Func<int, AddsToSomethingElse>> conversion = x => new AddsToSomethingElse(x); var exp = Expression.Lambda<Func<AddsToSomethingElse, AddsToSomethingElse>>( Expression.AddAssign(lhs, rhs, null, conversion), lhs ); var func = exp.Compile(useInterpreter); Assert.Equal(new AddsToSomethingElse(10), func(new AddsToSomethingElse(7))); } [Theory, PerCompilationType(nameof(AssignExpressionTypesArguments))] public void ConvertOpAssignToMember(ExpressionType type, bool useInterpreter) { Box<int> box = new Box<int>(25); Expression<Func<int, int>> doubleIt = x => x * 2; var exp = Expression.Lambda<Func<int>>( Expression.MakeBinary( type, Expression.Property(Expression.Constant(box), "Value"), Expression.Constant(15), false, GetType().GetMethod(nameof(FiftyNinthBear)), doubleIt ) ); var act = exp.Compile(useInterpreter); Assert.Equal(118, act()); Assert.Equal(118, box.Value); } [Theory, PerCompilationType(nameof(AssignExpressionTypesArguments))] public void ConvertOpAssignToArrayIndex(ExpressionType type, bool useInterpreter) { int[] array = {0, 0, 25, 0}; Expression<Func<int, int>> doubleIt = x => x * 2; var exp = Expression.Lambda<Func<int>>( Expression.MakeBinary( type, Expression.ArrayAccess(Expression.Constant(array), Expression.Constant(2)), Expression.Constant(15), false, GetType().GetMethod(nameof(FiftyNinthBear)), doubleIt ) ); var act = exp.Compile(useInterpreter); Assert.Equal(118, act()); Assert.Equal(118, array[2]); } private delegate int ByRefInts(ref int x, int y); private delegate int BothByRefInts(ref int x, ref int y); [Theory, PerCompilationType(nameof(AssignExpressionMethodInfoUsingFactoriesArguments))] public void MethodNoConvertOpWriteByRefParameter(Func<Expression, Expression, MethodInfo, BinaryExpression> factory, bool useInterpreter) { var pX = Expression.Parameter(typeof(int).MakeByRefType()); var pY = Expression.Parameter(typeof(int)); var exp = Expression.Lambda<ByRefInts>(factory(pX, pY, GetType().GetMethod(nameof(FiftyNinthBear))), pX, pY); var del = exp.Compile(useInterpreter); int arg = 5; Assert.Equal(59, del(ref arg, 35)); Assert.Equal(59, arg); } private delegate AddsToSomethingElse ByRefSomeElse(ref AddsToSomethingElse x, AddsToSomethingElse y); [Theory, ClassData(typeof(CompilationTypes))] public void ConvertOpWriteByRefParameterOverloadedOperator(bool useInterpreter) { var pX = Expression.Parameter(typeof(AddsToSomethingElse).MakeByRefType()); var pY = Expression.Parameter(typeof(AddsToSomethingElse)); Expression<Func<int, AddsToSomethingElse>> conv = x => new AddsToSomethingElse(x); var exp = Expression.Lambda<ByRefSomeElse>(Expression.AddAssign(pX, pY, null, conv), pX, pY); var del = exp.Compile(useInterpreter); AddsToSomethingElse arg = new AddsToSomethingElse(5); AddsToSomethingElse result = del(ref arg, new AddsToSomethingElse(35)); Assert.Equal(result, arg); } } }
/* * 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: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * 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; using System.Collections.Generic; using CookComputing.XmlRpc; namespace XenAPI { /// <summary> /// a proxy connects a VM/VIF with a PVS site /// </summary> public partial class PVS_proxy : XenObject<PVS_proxy> { public PVS_proxy() { } public PVS_proxy(string uuid, XenRef<PVS_site> site, XenRef<VIF> VIF, bool currently_attached, pvs_proxy_status status) { this.uuid = uuid; this.site = site; this.VIF = VIF; this.currently_attached = currently_attached; this.status = status; } /// <summary> /// Creates a new PVS_proxy from a Proxy_PVS_proxy. /// </summary> /// <param name="proxy"></param> public PVS_proxy(Proxy_PVS_proxy proxy) { this.UpdateFromProxy(proxy); } public override void UpdateFrom(PVS_proxy update) { uuid = update.uuid; site = update.site; VIF = update.VIF; currently_attached = update.currently_attached; status = update.status; } internal void UpdateFromProxy(Proxy_PVS_proxy proxy) { uuid = proxy.uuid == null ? null : (string)proxy.uuid; site = proxy.site == null ? null : XenRef<PVS_site>.Create(proxy.site); VIF = proxy.VIF == null ? null : XenRef<VIF>.Create(proxy.VIF); currently_attached = (bool)proxy.currently_attached; status = proxy.status == null ? (pvs_proxy_status) 0 : (pvs_proxy_status)Helper.EnumParseDefault(typeof(pvs_proxy_status), (string)proxy.status); } public Proxy_PVS_proxy ToProxy() { Proxy_PVS_proxy result_ = new Proxy_PVS_proxy(); result_.uuid = (uuid != null) ? uuid : ""; result_.site = (site != null) ? site : ""; result_.VIF = (VIF != null) ? VIF : ""; result_.currently_attached = currently_attached; result_.status = pvs_proxy_status_helper.ToString(status); return result_; } /// <summary> /// Creates a new PVS_proxy from a Hashtable. /// </summary> /// <param name="table"></param> public PVS_proxy(Hashtable table) { uuid = Marshalling.ParseString(table, "uuid"); site = Marshalling.ParseRef<PVS_site>(table, "site"); VIF = Marshalling.ParseRef<VIF>(table, "VIF"); currently_attached = Marshalling.ParseBool(table, "currently_attached"); status = (pvs_proxy_status)Helper.EnumParseDefault(typeof(pvs_proxy_status), Marshalling.ParseString(table, "status")); } public bool DeepEquals(PVS_proxy other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._site, other._site) && Helper.AreEqual2(this._VIF, other._VIF) && Helper.AreEqual2(this._currently_attached, other._currently_attached) && Helper.AreEqual2(this._status, other._status); } public override string SaveChanges(Session session, string opaqueRef, PVS_proxy server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { throw new InvalidOperationException("This type has no read/write properties"); } } /// <summary> /// Get a record containing the current state of the given PVS_proxy. /// Experimental. First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param> public static PVS_proxy get_record(Session session, string _pvs_proxy) { return new PVS_proxy((Proxy_PVS_proxy)session.proxy.pvs_proxy_get_record(session.uuid, (_pvs_proxy != null) ? _pvs_proxy : "").parse()); } /// <summary> /// Get a reference to the PVS_proxy instance with the specified UUID. /// Experimental. First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<PVS_proxy> get_by_uuid(Session session, string _uuid) { return XenRef<PVS_proxy>.Create(session.proxy.pvs_proxy_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse()); } /// <summary> /// Get the uuid field of the given PVS_proxy. /// Experimental. First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param> public static string get_uuid(Session session, string _pvs_proxy) { return (string)session.proxy.pvs_proxy_get_uuid(session.uuid, (_pvs_proxy != null) ? _pvs_proxy : "").parse(); } /// <summary> /// Get the site field of the given PVS_proxy. /// Experimental. First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param> public static XenRef<PVS_site> get_site(Session session, string _pvs_proxy) { return XenRef<PVS_site>.Create(session.proxy.pvs_proxy_get_site(session.uuid, (_pvs_proxy != null) ? _pvs_proxy : "").parse()); } /// <summary> /// Get the VIF field of the given PVS_proxy. /// Experimental. First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param> public static XenRef<VIF> get_VIF(Session session, string _pvs_proxy) { return XenRef<VIF>.Create(session.proxy.pvs_proxy_get_vif(session.uuid, (_pvs_proxy != null) ? _pvs_proxy : "").parse()); } /// <summary> /// Get the currently_attached field of the given PVS_proxy. /// Experimental. First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param> public static bool get_currently_attached(Session session, string _pvs_proxy) { return (bool)session.proxy.pvs_proxy_get_currently_attached(session.uuid, (_pvs_proxy != null) ? _pvs_proxy : "").parse(); } /// <summary> /// Get the status field of the given PVS_proxy. /// Experimental. First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param> public static pvs_proxy_status get_status(Session session, string _pvs_proxy) { return (pvs_proxy_status)Helper.EnumParseDefault(typeof(pvs_proxy_status), (string)session.proxy.pvs_proxy_get_status(session.uuid, (_pvs_proxy != null) ? _pvs_proxy : "").parse()); } /// <summary> /// Configure a VM/VIF to use a PVS proxy /// Experimental. First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_site">PVS site that we proxy for</param> /// <param name="_vif">VIF for the VM that needs to be proxied</param> public static XenRef<PVS_proxy> create(Session session, string _site, string _vif) { return XenRef<PVS_proxy>.Create(session.proxy.pvs_proxy_create(session.uuid, (_site != null) ? _site : "", (_vif != null) ? _vif : "").parse()); } /// <summary> /// Configure a VM/VIF to use a PVS proxy /// Experimental. First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_site">PVS site that we proxy for</param> /// <param name="_vif">VIF for the VM that needs to be proxied</param> public static XenRef<Task> async_create(Session session, string _site, string _vif) { return XenRef<Task>.Create(session.proxy.async_pvs_proxy_create(session.uuid, (_site != null) ? _site : "", (_vif != null) ? _vif : "").parse()); } /// <summary> /// remove (or switch off) a PVS proxy for this VM /// Experimental. First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param> public static void destroy(Session session, string _pvs_proxy) { session.proxy.pvs_proxy_destroy(session.uuid, (_pvs_proxy != null) ? _pvs_proxy : "").parse(); } /// <summary> /// remove (or switch off) a PVS proxy for this VM /// Experimental. First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_pvs_proxy">The opaque_ref of the given pvs_proxy</param> public static XenRef<Task> async_destroy(Session session, string _pvs_proxy) { return XenRef<Task>.Create(session.proxy.async_pvs_proxy_destroy(session.uuid, (_pvs_proxy != null) ? _pvs_proxy : "").parse()); } /// <summary> /// Return a list of all the PVS_proxys known to the system. /// Experimental. First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> public static List<XenRef<PVS_proxy>> get_all(Session session) { return XenRef<PVS_proxy>.Create(session.proxy.pvs_proxy_get_all(session.uuid).parse()); } /// <summary> /// Get all the PVS_proxy Records at once, in a single XML RPC call /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<PVS_proxy>, PVS_proxy> get_all_records(Session session) { return XenRef<PVS_proxy>.Create<Proxy_PVS_proxy>(session.proxy.pvs_proxy_get_all_records(session.uuid).parse()); } /// <summary> /// Unique identifier/object reference /// Experimental. First published in XenServer 7.1. /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid; /// <summary> /// PVS site this proxy is part of /// Experimental. First published in XenServer 7.1. /// </summary> public virtual XenRef<PVS_site> site { get { return _site; } set { if (!Helper.AreEqual(value, _site)) { _site = value; Changed = true; NotifyPropertyChanged("site"); } } } private XenRef<PVS_site> _site; /// <summary> /// VIF of the VM using the proxy /// Experimental. First published in XenServer 7.1. /// </summary> public virtual XenRef<VIF> VIF { get { return _VIF; } set { if (!Helper.AreEqual(value, _VIF)) { _VIF = value; Changed = true; NotifyPropertyChanged("VIF"); } } } private XenRef<VIF> _VIF; /// <summary> /// true = VM is currently proxied /// Experimental. First published in XenServer 7.1. /// </summary> public virtual bool currently_attached { get { return _currently_attached; } set { if (!Helper.AreEqual(value, _currently_attached)) { _currently_attached = value; Changed = true; NotifyPropertyChanged("currently_attached"); } } } private bool _currently_attached; /// <summary> /// The run-time status of the proxy /// Experimental. First published in XenServer 7.1. /// </summary> public virtual pvs_proxy_status status { get { return _status; } set { if (!Helper.AreEqual(value, _status)) { _status = value; Changed = true; NotifyPropertyChanged("status"); } } } private pvs_proxy_status _status; } }
using System; using Anotar.NLog; public class ClassWithException { public async void AsyncMethod() { try { System.Diagnostics.Trace.WriteLine("Foo"); } catch { } } public void Trace() { try { LogTo.Trace(); } catch { } } public void TraceString() { try { LogTo.Trace("TheMessage"); } catch { } } public void TraceStringParams() { try { LogTo.Trace("TheMessage {0}", 1); } catch { } } public void TraceStringException() { try { LogTo.TraceException("TheMessage", new Exception()); } catch { } } public void Debug() { try { LogTo.Debug(); } catch { } } public void DebugString() { try { LogTo.Debug("TheMessage"); } catch { } } public void DebugStringParams() { try { LogTo.Debug("TheMessage {0}", 1); } catch { } } public void DebugStringException() { try { LogTo.DebugException("TheMessage", new Exception()); } catch { } } public void Info() { try { LogTo.Info(); } catch { } } public void InfoString() { try { LogTo.Info("TheMessage"); } catch { } } public void InfoStringParams() { try { LogTo.Info("TheMessage {0}", 1); } catch { } } public void InfoStringException() { try { LogTo.InfoException("TheMessage", new Exception()); } catch { } } public void Warn() { try { LogTo.Warn(); } catch { } } public void WarnString() { try { LogTo.Warn("TheMessage"); } catch { } } public void WarnStringParams() { try { LogTo.Warn("TheMessage {0}", 1); } catch { } } public void WarnStringException() { try { LogTo.WarnException("TheMessage", new Exception()); } catch { } } public void Error() { try { LogTo.Error(); } catch { } } public void ErrorString() { try { LogTo.Error("TheMessage"); } catch { } } public void ErrorStringParams() { try { LogTo.Error("TheMessage {0}", 1); } catch { } } public void ErrorStringException() { try { LogTo.ErrorException("TheMessage", new Exception()); } catch { } } public void Fatal() { try { LogTo.Fatal(); } catch { } } public void FatalString() { try { LogTo.Fatal("TheMessage"); } catch { } } public void FatalStringParams() { try { LogTo.Fatal("TheMessage {0}", 1); } catch { } } public void FatalStringException() { try { LogTo.FatalException("TheMessage", new Exception()); } catch { } } }
#region --- License --- /* Copyright (c) 2006, 2007 Stefanos Apostolopoulos * Contributions from Erik Ylvisaker * See license.txt for license info */ #endregion using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.Security; #pragma warning disable 1591 namespace OpenTK.Platform.X11 { #region Enums enum GLXAttribute : int { TRANSPARENT_BLUE_VALUE_EXT = 0x27, GRAY_SCALE = 0x8006, RGBA_TYPE = 0x8014, TRANSPARENT_RGB_EXT = 0x8008, ACCUM_BLUE_SIZE = 16, SHARE_CONTEXT_EXT = 0x800A, STEREO = 6, ALPHA_SIZE = 11, FLOAT_COMPONENTS_NV = 0x20B0, NONE = 0x8000, DEPTH_SIZE = 12, TRANSPARENT_INDEX_VALUE_EXT = 0x24, MAX_PBUFFER_WIDTH_SGIX = 0x8016, GREEN_SIZE = 9, X_RENDERABLE_SGIX = 0x8012, LARGEST_PBUFFER = 0x801C, DONT_CARE = unchecked((int)0xFFFFFFFF), TRANSPARENT_ALPHA_VALUE_EXT = 0x28, PSEUDO_COLOR_EXT = 0x8004, USE_GL = 1, SAMPLE_BUFFERS_SGIS = 100000, TRANSPARENT_GREEN_VALUE_EXT = 0x26, HYPERPIPE_ID_SGIX = 0x8030, COLOR_INDEX_TYPE_SGIX = 0x8015, SLOW_CONFIG = 0x8001, PRESERVED_CONTENTS = 0x801B, ACCUM_RED_SIZE = 14, EVENT_MASK = 0x801F, VISUAL_ID_EXT = 0x800B, EVENT_MASK_SGIX = 0x801F, SLOW_VISUAL_EXT = 0x8001, TRANSPARENT_GREEN_VALUE = 0x26, MAX_PBUFFER_WIDTH = 0x8016, DIRECT_COLOR_EXT = 0x8003, VISUAL_ID = 0x800B, ACCUM_GREEN_SIZE = 15, DRAWABLE_TYPE_SGIX = 0x8010, SCREEN_EXT = 0x800C, SAMPLES = 100001, HEIGHT = 0x801E, TRANSPARENT_INDEX_VALUE = 0x24, SAMPLE_BUFFERS_ARB = 100000, PBUFFER = 0x8023, RGBA_TYPE_SGIX = 0x8014, MAX_PBUFFER_HEIGHT = 0x8017, FBCONFIG_ID_SGIX = 0x8013, DRAWABLE_TYPE = 0x8010, SCREEN = 0x800C, RED_SIZE = 8, VISUAL_SELECT_GROUP_SGIX = 0x8028, VISUAL_CAVEAT_EXT = 0x20, PSEUDO_COLOR = 0x8004, PBUFFER_HEIGHT = 0x8040, STATIC_GRAY = 0x8007, PRESERVED_CONTENTS_SGIX = 0x801B, RGBA_FLOAT_TYPE_ARB = 0x20B9, TRANSPARENT_RED_VALUE = 0x25, TRANSPARENT_ALPHA_VALUE = 0x28, WINDOW = 0x8022, X_RENDERABLE = 0x8012, STENCIL_SIZE = 13, TRANSPARENT_RGB = 0x8008, LARGEST_PBUFFER_SGIX = 0x801C, STATIC_GRAY_EXT = 0x8007, TRANSPARENT_BLUE_VALUE = 0x27, DIGITAL_MEDIA_PBUFFER_SGIX = 0x8024, BLENDED_RGBA_SGIS = 0x8025, NON_CONFORMANT_VISUAL_EXT = 0x800D, COLOR_INDEX_TYPE = 0x8015, TRANSPARENT_RED_VALUE_EXT = 0x25, GRAY_SCALE_EXT = 0x8006, WINDOW_SGIX = 0x8022, X_VISUAL_TYPE = 0x22, MAX_PBUFFER_HEIGHT_SGIX = 0x8017, DOUBLEBUFFER = 5, OPTIMAL_PBUFFER_WIDTH_SGIX = 0x8019, X_VISUAL_TYPE_EXT = 0x22, WIDTH_SGIX = 0x801D, STATIC_COLOR_EXT = 0x8005, BUFFER_SIZE = 2, DIRECT_COLOR = 0x8003, MAX_PBUFFER_PIXELS = 0x8018, NONE_EXT = 0x8000, HEIGHT_SGIX = 0x801E, RENDER_TYPE = 0x8011, FBCONFIG_ID = 0x8013, TRANSPARENT_INDEX_EXT = 0x8009, TRANSPARENT_INDEX = 0x8009, TRANSPARENT_TYPE_EXT = 0x23, ACCUM_ALPHA_SIZE = 17, PBUFFER_SGIX = 0x8023, MAX_PBUFFER_PIXELS_SGIX = 0x8018, OPTIMAL_PBUFFER_HEIGHT_SGIX = 0x801A, DAMAGED = 0x8020, SAVED_SGIX = 0x8021, TRANSPARENT_TYPE = 0x23, MULTISAMPLE_SUB_RECT_WIDTH_SGIS = 0x8026, NON_CONFORMANT_CONFIG = 0x800D, BLUE_SIZE = 10, TRUE_COLOR_EXT = 0x8002, SAMPLES_SGIS = 100001, SAMPLES_ARB = 100001, TRUE_COLOR = 0x8002, RGBA = 4, AUX_BUFFERS = 7, SAMPLE_BUFFERS = 100000, SAVED = 0x8021, MULTISAMPLE_SUB_RECT_HEIGHT_SGIS = 0x8027, DAMAGED_SGIX = 0x8020, STATIC_COLOR = 0x8005, PBUFFER_WIDTH = 0x8041, WIDTH = 0x801D, LEVEL = 3, CONFIG_CAVEAT = 0x20, RENDER_TYPE_SGIX = 0x8011, } enum GLXHyperpipeAttrib : int { PIPE_RECT_LIMITS_SGIX = 0x00000002, PIPE_RECT_SGIX = 0x00000001, HYPERPIPE_STEREO_SGIX = 0x00000003, HYPERPIPE_PIXEL_AVERAGE_SGIX = 0x00000004, } enum GLXStringName : int { EXTENSIONS = 0x3, VERSION = 0x2, VENDOR = 0x1, } enum GLXEventMask : int { PBUFFER_CLOBBER_MASK = 0x08000000, BUFFER_CLOBBER_MASK_SGIX = 0x08000000, } enum GLXRenderTypeMask : int { COLOR_INDEX_BIT_SGIX = 0x00000002, RGBA_BIT = 0x00000001, RGBA_FLOAT_BIT_ARB = 0x00000004, RGBA_BIT_SGIX = 0x00000001, COLOR_INDEX_BIT = 0x00000002, } enum GLXHyperpipeTypeMask : int { HYPERPIPE_RENDER_PIPE_SGIX = 0x00000002, HYPERPIPE_DISPLAY_PIPE_SGIX = 0x00000001, } enum GLXPbufferClobberMask : int { ACCUM_BUFFER_BIT_SGIX = 0x00000080, FRONT_LEFT_BUFFER_BIT = 0x00000001, BACK_RIGHT_BUFFER_BIT = 0x00000008, FRONT_RIGHT_BUFFER_BIT_SGIX = 0x00000002, STENCIL_BUFFER_BIT_SGIX = 0x00000040, SAMPLE_BUFFERS_BIT_SGIX = 0x00000100, STENCIL_BUFFER_BIT = 0x00000040, BACK_RIGHT_BUFFER_BIT_SGIX = 0x00000008, BACK_LEFT_BUFFER_BIT_SGIX = 0x00000004, AUX_BUFFERS_BIT = 0x00000010, DEPTH_BUFFER_BIT_SGIX = 0x00000020, ACCUM_BUFFER_BIT = 0x00000080, AUX_BUFFERS_BIT_SGIX = 0x00000010, DEPTH_BUFFER_BIT = 0x00000020, FRONT_LEFT_BUFFER_BIT_SGIX = 0x00000001, BACK_LEFT_BUFFER_BIT = 0x00000004, FRONT_RIGHT_BUFFER_BIT = 0x00000002, } enum GLXHyperpipeMisc : int { HYPERPIPE_PIPE_NAME_LENGTH_SGIX = 80, } enum GLXErrorCode : int { BAD_CONTEXT = 5, NO_EXTENSION = 3, BAD_HYPERPIPE_SGIX = 92, BAD_ENUM = 7, BAD_SCREEN = 1, BAD_VALUE = 6, BAD_ATTRIBUTE = 2, BAD_VISUAL = 4, BAD_HYPERPIPE_CONFIG_SGIX = 91, } enum GLXSyncType : int { SYNC_SWAP_SGIX = 0x00000001, SYNC_FRAME_SGIX = 0x00000000, } enum GLXDrawableTypeMask : int { WINDOW_BIT = 0x00000001, PIXMAP_BIT = 0x00000002, PBUFFER_BIT_SGIX = 0x00000004, PBUFFER_BIT = 0x00000004, WINDOW_BIT_SGIX = 0x00000001, PIXMAP_BIT_SGIX = 0x00000002, } enum ArbCreateContext : int { DebugBit = 0x0001, ForwardCompatibleBit = 0x0002, MajorVersion = 0x2091, MinorVersion = 0x2092, LayerPlane = 0x2093, Flags = 0x2094, ErrorInvalidVersion = 0x2095, } enum ErrorCode : int { NO_ERROR = 0, BAD_SCREEN = 1, /* screen # is bad */ BAD_ATTRIBUTE = 2, /* attribute to get is bad */ NO_EXTENSION = 3, /* no glx extension on server */ BAD_VISUAL = 4, /* visual # not known by GLX */ BAD_CONTEXT = 5, /* returned only by import_context EXT? */ BAD_VALUE = 6, /* returned only by glXSwapIntervalSGI? */ BAD_ENUM = 7, /* unused? */ } #endregion /// \internal /// <summary> /// Provides access to GLX functions. /// </summary> partial class Glx { #region GLX functions [DllImport(Library, EntryPoint = "glXIsDirect")] public static extern bool IsDirect(IntPtr dpy, IntPtr context); [DllImport(Library, EntryPoint = "glXQueryExtension")] public static extern bool QueryExtension(IntPtr dpy, ref int errorBase, ref int eventBase); [DllImport(Library, EntryPoint = "glXQueryExtensionsString")] static extern IntPtr QueryExtensionsStringInternal(IntPtr dpy, int screen); public static string QueryExtensionsString(IntPtr dpy, int screen) { return Marshal.PtrToStringAnsi(QueryExtensionsStringInternal(dpy, screen)); } [DllImport(Library, EntryPoint = "glXCreateContext")] public static extern IntPtr CreateContext(IntPtr dpy, IntPtr vis, IntPtr shareList, bool direct); [DllImport(Library, EntryPoint = "glXCreateContext")] public static extern IntPtr CreateContext(IntPtr dpy, ref XVisualInfo vis, IntPtr shareList, bool direct); [DllImport(Library, EntryPoint = "glXDestroyContext")] public static extern void DestroyContext(IntPtr dpy, IntPtr context); public static void DestroyContext(IntPtr dpy, ContextHandle context) { DestroyContext(dpy, context.Handle); } [DllImport(Library, EntryPoint = "glXGetCurrentContext")] public static extern IntPtr GetCurrentContext(); [DllImport(Library, EntryPoint = "glXMakeCurrent")] public static extern bool MakeCurrent(IntPtr display, IntPtr drawable, IntPtr context); public static bool MakeCurrent(IntPtr display, IntPtr drawable, ContextHandle context) { return MakeCurrent(display, drawable, context.Handle); } [DllImport(Library, EntryPoint = "glXSwapBuffers")] public static extern void SwapBuffers(IntPtr display, IntPtr drawable); [DllImport(Library, EntryPoint = "glXGetProcAddress")] public static extern IntPtr GetProcAddress([MarshalAs(UnmanagedType.LPTStr)] string procName); [DllImport(Library, EntryPoint = "glXGetConfig")] public static extern int GetConfig(IntPtr dpy, ref XVisualInfo vis, GLXAttribute attrib, out int value); #region glXChooseVisual [DllImport(Library, EntryPoint = "glXChooseVisual")] public extern static IntPtr ChooseVisual(IntPtr dpy, int screen, IntPtr attriblist); [DllImport(Library, EntryPoint = "glXChooseVisual")] public extern static IntPtr ChooseVisual(IntPtr dpy, int screen, ref int attriblist); public static IntPtr ChooseVisual(IntPtr dpy, int screen, int[] attriblist) { unsafe { fixed (int* attriblist_ptr = attriblist) { return ChooseVisual(dpy, screen, (IntPtr)attriblist_ptr); } } } // Returns an array of GLXFBConfig structures. [DllImport(Library, EntryPoint = "glXChooseFBConfig")] unsafe public extern static IntPtr* ChooseFBConfig(IntPtr dpy, int screen, int[] attriblist, out int fbount); // Returns a pointer to an XVisualInfo structure. [DllImport(Library, EntryPoint = "glXGetVisualFromFBConfig")] public unsafe extern static IntPtr GetVisualFromFBConfig(IntPtr dpy, IntPtr fbconfig); #endregion #region Extensions public partial class Sgi { public static ErrorCode SwapInterval(int interval) { return (ErrorCode)Delegates.glXSwapIntervalSGI(interval); } } public partial class Arb { #region CreateContextAttribs unsafe public static IntPtr CreateContextAttribs(IntPtr display, IntPtr fbconfig, IntPtr share_context, bool direct, int* attribs) { return Delegates.glXCreateContextAttribsARB(display, fbconfig, share_context, direct, attribs); } public static IntPtr CreateContextAttribs(IntPtr display, IntPtr fbconfig, IntPtr share_context, bool direct, int[] attribs) { unsafe { fixed (int* attribs_ptr = attribs) { return Delegates.glXCreateContextAttribsARB(display, fbconfig, share_context, direct, attribs_ptr); } } } #endregion } internal static partial class Delegates { [SuppressUnmanagedCodeSecurity] public delegate int SwapIntervalSGI(int interval); public static SwapIntervalSGI glXSwapIntervalSGI = null; [SuppressUnmanagedCodeSecurity] unsafe public delegate IntPtr CreateContextAttribsARB(IntPtr display, IntPtr fbconfig, IntPtr share_context, bool direct, int* attribs); unsafe public static CreateContextAttribsARB glXCreateContextAttribsARB = null; } #endregion #endregion } } #pragma warning restore 1591
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Linq.Parallel.Tests { public partial class ParallelQueryCombinationTests { [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Aggregate(LabeledOperation source, LabeledOperation operation) { Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize), operation.Item(DefaultStart, DefaultSize, source.Item).Aggregate((x, y) => x + y)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Aggregate_Seed(LabeledOperation source, LabeledOperation operation) { Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize), operation.Item(DefaultStart, DefaultSize, source.Item).Aggregate(0, (x, y) => x + y)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Aggregate_Result(LabeledOperation source, LabeledOperation operation) { Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize), operation.Item(DefaultStart, DefaultSize, source.Item).Aggregate(0, (x, y) => x + y, r => r)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Aggregate_Accumulator(LabeledOperation source, LabeledOperation operation) { Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize), operation.Item(DefaultStart, DefaultSize, source.Item).Aggregate(0, (a, x) => a + x, (l, r) => l + r, r => r)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Aggregate_SeedFactory(LabeledOperation source, LabeledOperation operation) { Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize), operation.Item(DefaultStart, DefaultSize, source.Item).Aggregate(() => 0, (a, x) => a + x, (l, r) => l + r, r => r)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void All_False(LabeledOperation source, LabeledOperation operation) { Assert.False(operation.Item(DefaultStart, DefaultSize, source.Item).All(x => false)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void All_True(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); Assert.True(operation.Item(DefaultStart, DefaultSize, source.Item).All(x => seen.Add(x))); seen.AssertComplete(); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Any_False(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); Assert.False(operation.Item(DefaultStart, DefaultSize, source.Item).Any(x => !seen.Add(x))); seen.AssertComplete(); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Any_True(LabeledOperation source, LabeledOperation operation) { Assert.True(operation.Item(DefaultStart, DefaultSize, source.Item).Any(x => true)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Average(LabeledOperation source, LabeledOperation operation) { Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize) / (double)DefaultSize, operation.Item(DefaultStart, DefaultSize, source.Item).Average()); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Average_Nullable(LabeledOperation source, LabeledOperation operation) { Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize) / (double?)DefaultSize, operation.Item(DefaultStart, DefaultSize, source.Item).Average(x => (int?)x)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Cast(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; foreach (int? i in operation.Item(DefaultStart, DefaultSize, source.Item).Cast<int?>()) { Assert.True(i.HasValue); Assert.Equal(seen++, i.Value); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Cast_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Cast<int?>().ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Concat(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize / 2, source.Item) .Concat(operation.Item(DefaultStart + DefaultSize / 2, DefaultSize / 2, source.Item))) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Concat_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; Assert.All( operation.Item(DefaultStart, DefaultSize / 2, source.Item) .Concat(operation.Item(DefaultStart + DefaultSize / 2, DefaultSize / 2, source.Item)).ToList(), x => Assert.Equal(seen++, x) ); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Contains_True(LabeledOperation source, LabeledOperation operation) { Assert.True(operation.Item(DefaultStart, DefaultSize, source.Item).Contains(DefaultStart + DefaultSize / 2)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Contains_False(LabeledOperation source, LabeledOperation operation) { Assert.False(operation.Item(DefaultStart, DefaultSize, source.Item).Contains(DefaultStart + DefaultSize)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Count_Elements(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultSize, operation.Item(DefaultStart, DefaultSize, source.Item).Count()); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Count_Predicate_Some(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultSize / 2, operation.Item(DefaultStart, DefaultSize, source.Item).Count(x => x < DefaultStart + DefaultSize / 2)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Count_Predicate_None(LabeledOperation source, LabeledOperation operation) { Assert.Equal(0, operation.Item(DefaultStart, DefaultSize, source.Item).Count(x => x < DefaultStart)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void DefaultIfEmpty(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).DefaultIfEmpty()) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void DefaultIfEmpty_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).DefaultIfEmpty().ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Distinct(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; ParallelQuery<int> query = operation.Item(DefaultStart * 2, DefaultSize * 2, source.Item).Select(x => x / 2).Distinct(); foreach (int i in query) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Distinct_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; ParallelQuery<int> query = operation.Item(DefaultStart * 2, DefaultSize * 2, source.Item).Select(x => x / 2).Distinct(); Assert.All(query.ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void ElementAt(LabeledOperation source, LabeledOperation operation) { ParallelQuery<int> query = operation.Item(DefaultStart, DefaultSize, source.Item); int seen = DefaultStart; for (int i = 0; i < DefaultSize; i++) { Assert.Equal(seen++, query.ElementAt(i)); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void ElementAtOrDefault(LabeledOperation source, LabeledOperation operation) { ParallelQuery<int> query = operation.Item(DefaultStart, DefaultSize, source.Item); int seen = DefaultStart; for (int i = 0; i < DefaultSize; i++) { Assert.Equal(seen++, query.ElementAtOrDefault(i)); } Assert.Equal(DefaultStart + DefaultSize, seen); Assert.Equal(default(int), query.ElementAtOrDefault(-1)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Except(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; ParallelQuery<int> query = operation.Item(DefaultStart, DefaultSize + DefaultSize / 2, source.Item) .Except(operation.Item(DefaultStart + DefaultSize, DefaultSize, source.Item)); foreach (int i in query) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Except_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; ParallelQuery<int> query = operation.Item(DefaultStart, DefaultSize + DefaultSize / 2, source.Item) .Except(operation.Item(DefaultStart + DefaultSize, DefaultSize, source.Item)); Assert.All(query.ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void First(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultStart, operation.Item(DefaultStart, DefaultSize, source.Item).First()); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void First_Predicate(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultStart + DefaultSize / 2, operation.Item(DefaultStart, DefaultSize, source.Item).First(x => x >= DefaultStart + DefaultSize / 2)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void FirstOrDefault(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultStart, operation.Item(DefaultStart, DefaultSize, source.Item).FirstOrDefault()); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void FirstOrDefault_Predicate(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultStart + DefaultSize / 2, operation.Item(DefaultStart, DefaultSize, source.Item).FirstOrDefault(x => x >= DefaultStart + DefaultSize / 2)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void FirstOrDefault_Predicate_None(LabeledOperation source, LabeledOperation operation) { Assert.Equal(default(int), operation.Item(DefaultStart, DefaultSize, source.Item).FirstOrDefault(x => false)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void ForAll(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); operation.Item(DefaultStart, DefaultSize, source.Item).ForAll(x => seen.Add(x)); seen.AssertComplete(); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void GetEnumerator(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; IEnumerator<int> enumerator = operation.Item(DefaultStart, DefaultSize, source.Item).GetEnumerator(); while (enumerator.MoveNext()) { int current = enumerator.Current; Assert.Equal(seen++, current); Assert.Equal(current, enumerator.Current); } Assert.Equal(DefaultStart + DefaultSize, seen); Assert.Throws<NotSupportedException>(() => enumerator.Reset()); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void GroupBy(LabeledOperation source, LabeledOperation operation) { int seenKey = DefaultStart / GroupFactor; foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, source.Item).GroupBy(x => x / GroupFactor)) { Assert.Equal(seenKey++, group.Key); int seenElement = group.Key * GroupFactor; Assert.All(group, x => Assert.Equal(seenElement++, x)); Assert.Equal(Math.Min((group.Key + 1) * GroupFactor, DefaultStart + DefaultSize), seenElement); } Assert.Equal((DefaultSize + (GroupFactor - 1)) / GroupFactor + 1, seenKey); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void GroupBy_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seenKey = DefaultStart / GroupFactor; foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, source.Item).GroupBy(x => x / GroupFactor).ToList()) { Assert.Equal(seenKey++, group.Key); int seenElement = group.Key * GroupFactor; Assert.All(group, x => Assert.Equal(seenElement++, x)); Assert.Equal(Math.Min((group.Key + 1) * GroupFactor, DefaultStart + DefaultSize), seenElement); } Assert.Equal((DefaultSize + (GroupFactor - 1)) / GroupFactor + 1, seenKey); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void GroupBy_ElementSelector(LabeledOperation source, LabeledOperation operation) { int seenKey = DefaultStart / GroupFactor; foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, source.Item).GroupBy(x => x / GroupFactor, y => -y)) { Assert.Equal(seenKey++, group.Key); int seenElement = -group.Key * GroupFactor; Assert.All(group, x => Assert.Equal(seenElement--, x)); Assert.Equal(-Math.Min((group.Key + 1) * GroupFactor, DefaultStart + DefaultSize), seenElement); } Assert.Equal((DefaultSize + (GroupFactor - 1)) / GroupFactor + 1, seenKey); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void GroupBy_ElementSelector_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seenKey = DefaultStart / GroupFactor; foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, source.Item).GroupBy(x => x / GroupFactor, y => -y).ToList()) { Assert.Equal(seenKey++, group.Key); int seenElement = -group.Key * GroupFactor; Assert.All(group, x => Assert.Equal(seenElement--, x)); Assert.Equal(-Math.Min((group.Key + 1) * GroupFactor, DefaultStart + DefaultSize), seenElement); } Assert.Equal((DefaultSize + (GroupFactor - 1)) / GroupFactor + 1, seenKey); } [Theory] [ActiveIssue(1155)] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void GroupJoin(LabeledOperation source, LabeledOperation operation) { int seenKey = DefaultStart / GroupFactor; foreach (KeyValuePair<int, IEnumerable<int>> group in operation.Item(DefaultStart / GroupFactor, DefaultSize / GroupFactor, source.Item) .GroupJoin(operation.Item(DefaultStart, DefaultSize, source.Item), x => x, y => y / GroupFactor, (k, g) => new KeyValuePair<int, IEnumerable<int>>(k, g))) { Assert.Equal(seenKey++, group.Key); int seenElement = group.Key * GroupFactor; Assert.All(group.Value, x => Assert.Equal(seenElement++, x)); Assert.Equal((group.Key + 1) * GroupFactor, seenElement); } Assert.Equal((DefaultStart + DefaultSize) / GroupFactor, seenKey); } [Theory] [ActiveIssue(1155)] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void GroupJoin_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seenKey = DefaultStart / GroupFactor; foreach (KeyValuePair<int, IEnumerable<int>> group in operation.Item(DefaultStart / GroupFactor, DefaultSize / GroupFactor, source.Item) .GroupJoin(operation.Item(DefaultStart, DefaultSize, source.Item), x => x, y => y / GroupFactor, (k, g) => new KeyValuePair<int, IEnumerable<int>>(k, g)).ToList()) { Assert.Equal(seenKey++, group.Key); int seenElement = group.Key * GroupFactor; Assert.All(group.Value, x => Assert.Equal(seenElement++, x)); Assert.Equal((group.Key + 1) * GroupFactor, seenElement); } Assert.Equal((DefaultStart + DefaultSize) / GroupFactor, seenKey); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Intersect(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; ParallelQuery<int> query = operation.Item(DefaultStart - DefaultSize / 2, DefaultSize + DefaultSize / 2, source.Item) .Intersect(operation.Item(DefaultStart, DefaultSize + DefaultSize / 2, source.Item)); foreach (int i in query) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Intersect_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; ParallelQuery<int> query = operation.Item(DefaultStart - DefaultSize / 2, DefaultSize + DefaultSize / 2, source.Item) .Intersect(operation.Item(DefaultStart, DefaultSize + DefaultSize / 2, source.Item)); Assert.All(query.ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [ActiveIssue(1155)] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Join(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; ParallelQuery<KeyValuePair<int, int>> query = operation.Item(DefaultStart / GroupFactor, DefaultSize / GroupFactor, source.Item) .Join(operation.Item(DefaultStart, DefaultSize, source.Item), x => x, y => y / GroupFactor, (x, y) => new KeyValuePair<int, int>(x, y)); foreach (KeyValuePair<int, int> p in query) { Assert.Equal(seen++, p.Value); Assert.Equal(p.Key, p.Value / GroupFactor); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [ActiveIssue(1155)] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Join_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; ParallelQuery<KeyValuePair<int, int>> query = operation.Item(DefaultStart / GroupFactor, DefaultSize / GroupFactor, source.Item) .Join(operation.Item(DefaultStart, DefaultSize, source.Item), x => x, y => y / GroupFactor, (x, y) => new KeyValuePair<int, int>(x, y)); foreach (KeyValuePair<int, int> p in query.ToList()) { Assert.Equal(seen++, p.Value); Assert.Equal(p.Key, p.Value / GroupFactor); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Last(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultStart + DefaultSize - 1, operation.Item(DefaultStart, DefaultSize, source.Item).Last()); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Last_Predicate(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultStart + DefaultSize / 2 - 1, operation.Item(DefaultStart, DefaultSize, source.Item).Last(x => x < DefaultStart + DefaultSize / 2)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void LastOrDefault(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultStart + DefaultSize - 1, operation.Item(DefaultStart, DefaultSize, source.Item).LastOrDefault()); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void LastOrDefault_Predicate(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultStart + DefaultSize / 2 - 1, operation.Item(DefaultStart, DefaultSize, source.Item).LastOrDefault(x => x < DefaultStart + DefaultSize / 2)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void LastOrDefault_Predicate_None(LabeledOperation source, LabeledOperation operation) { Assert.Equal(default(int), operation.Item(DefaultStart, DefaultSize, source.Item).LastOrDefault(x => false)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void LongCount_Elements(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultSize, operation.Item(DefaultStart, DefaultSize, source.Item).LongCount()); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void LongCount_Predicate_Some(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultSize / 2, operation.Item(DefaultStart, DefaultSize, source.Item).LongCount(x => x < DefaultStart + DefaultSize / 2)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void LongCount_Predicate_None(LabeledOperation source, LabeledOperation operation) { Assert.Equal(0, operation.Item(DefaultStart, DefaultSize, source.Item).LongCount(x => x < DefaultStart)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Max(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultStart + DefaultSize - 1, operation.Item(DefaultStart, DefaultSize, source.Item).Max()); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Max_Nullable(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultStart + DefaultSize - 1, operation.Item(DefaultStart, DefaultSize, source.Item).Max(x => (int?)x)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Min(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultStart, operation.Item(DefaultStart, DefaultSize, source.Item).Min()); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Min_Nullable(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultStart, operation.Item(DefaultStart, DefaultSize, source.Item).Min(x => (int?)x)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void OfType(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OfType<int>()) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void OfType_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OfType<int>().ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void OfType_Other(LabeledOperation source, LabeledOperation operation) { Assert.Empty(operation.Item(DefaultStart, DefaultSize, source.Item).OfType<long>()); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void OfType_Other_NotPipelined(LabeledOperation source, LabeledOperation operation) { Assert.Empty(operation.Item(DefaultStart, DefaultSize, source.Item).OfType<long>().ToList()); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void OrderBy_Initial(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => x)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void OrderBy_Initial_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => x).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void OrderBy_OtherDirection(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => -x)) { Assert.Equal(--seen, i); } Assert.Equal(DefaultStart, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void OrderBy_OtherDirection_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => -x).ToList(), x => Assert.Equal(--seen, x)); Assert.Equal(DefaultStart, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void OrderByDescending_Initial(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderByDescending(x => -x)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void OrderByDescending_Initial_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderByDescending(x => -x).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void OrderByDescending_OtherDirection(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderByDescending(x => x)) { Assert.Equal(--seen, i); } Assert.Equal(DefaultStart, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void OrderByDescending_OtherDirection_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderByDescending(x => x).ToList(), x => Assert.Equal(--seen, x)); Assert.Equal(DefaultStart, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Reverse(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Reverse()) { Assert.Equal(--seen, i); } Assert.Equal(DefaultStart, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Reverse_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Reverse().ToList()) { Assert.Equal(--seen, i); } Assert.Equal(DefaultStart, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Select(LabeledOperation source, LabeledOperation operation) { int seen = -DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Select(x => -x)) { Assert.Equal(seen--, i); } Assert.Equal(-DefaultStart - DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Select_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = -DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Select(x => -x).ToList(), x => Assert.Equal(seen--, x)); Assert.Equal(-DefaultStart - DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Select_Indexed(LabeledOperation source, LabeledOperation operation) { int seen = -DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Select((x, index) => { Assert.Equal(DefaultStart + index, x); return -x; })) { Assert.Equal(seen--, i); } Assert.Equal(-DefaultStart - DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Select_Indexed_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = -DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Select((x, index) => { Assert.Equal(DefaultStart + index, x); return -x; }).ToList(), x => Assert.Equal(seen--, x)); Assert.Equal(-DefaultStart - DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void SelectMany(LabeledOperation source, LabeledOperation operation) { int seen = -DefaultStart; foreach (int i in operation.Item(0, DefaultSize, source.Item).SelectMany(x => new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x))) { Assert.Equal(seen--, i); } Assert.Equal(-DefaultStart - DefaultSize * 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void SelectMany_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = -DefaultStart; Assert.All(operation.Item(0, DefaultSize, source.Item).SelectMany(x => new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x)).ToList(), x => Assert.Equal(seen--, x)); Assert.Equal(-DefaultStart - DefaultSize * 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void SelectMany_Indexed(LabeledOperation source, LabeledOperation operation) { int seen = -DefaultStart; foreach (int i in operation.Item(0, DefaultSize, source.Item).SelectMany((x, index) => { Assert.Equal(index, x); return new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x); })) { Assert.Equal(seen--, i); } Assert.Equal(-DefaultStart - DefaultSize * 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void SelectMany_Indexed_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = -DefaultStart; Assert.All(operation.Item(0, DefaultSize, source.Item).SelectMany((x, index) => { Assert.Equal(index, x); return new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x); }).ToList(), x => Assert.Equal(seen--, x)); Assert.Equal(-DefaultStart - DefaultSize * 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void SelectMany_ResultSelector(LabeledOperation source, LabeledOperation operation) { int seen = -DefaultStart; foreach (int i in operation.Item(0, DefaultSize, source.Item).SelectMany(x => new[] { 0, -1 }, (x, y) => y + -DefaultStart - 2 * x)) { Assert.Equal(seen--, i); } Assert.Equal(-DefaultStart - DefaultSize * 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void SelectMany_ResultSelector_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = -DefaultStart; Assert.All(operation.Item(0, DefaultSize, source.Item).SelectMany(x => new[] { 0, -1 }, (x, y) => y + -DefaultStart - 2 * x).ToList(), x => Assert.Equal(seen--, x)); Assert.Equal(-DefaultStart - DefaultSize * 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void SelectMany_Indexed_ResultSelector(LabeledOperation source, LabeledOperation operation) { int seen = -DefaultStart; foreach (int i in operation.Item(0, DefaultSize, source.Item).SelectMany((x, index) => { Assert.Equal(index, x); return new[] { 0, -1 }; }, (x, y) => y + -DefaultStart - 2 * x)) { Assert.Equal(seen--, i); } Assert.Equal(-DefaultStart - DefaultSize * 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void SelectMany_Indexed_ResultSelector_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = -DefaultStart; Assert.All(operation.Item(0, DefaultSize, source.Item).SelectMany((x, index) => { Assert.Equal(index, x); return new[] { 0, -1 }; }, (x, y) => y + -DefaultStart - 2 * x).ToList(), x => Assert.Equal(seen--, x)); Assert.Equal(-DefaultStart - DefaultSize * 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void SequenceEqual(LabeledOperation source, LabeledOperation operation) { Assert.True(operation.Item(DefaultStart, DefaultSize, source.Item).SequenceEqual(ParallelEnumerable.Range(DefaultStart, DefaultSize).AsOrdered())); Assert.True(ParallelEnumerable.Range(DefaultStart, DefaultSize).AsOrdered().SequenceEqual(operation.Item(DefaultStart, DefaultSize, source.Item))); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void SequenceEqual_Self(LabeledOperation source, LabeledOperation operation) { Assert.True(operation.Item(DefaultStart, DefaultSize, source.Item).SequenceEqual(operation.Item(DefaultStart, DefaultSize, source.Item))); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void Single(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultStart, operation.Item(DefaultStart, 1, source.Item).Single()); Assert.Equal(DefaultStart + DefaultSize / 2, operation.Item(DefaultStart, DefaultSize, source.Item).Single(x => x == DefaultStart + DefaultSize / 2)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void SingleOrDefault(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultStart, operation.Item(DefaultStart, 1, source.Item).SingleOrDefault()); Assert.Equal(DefaultStart + DefaultSize / 2, operation.Item(DefaultStart, DefaultSize, source.Item).SingleOrDefault(x => x == DefaultStart + DefaultSize / 2)); if (!operation.ToString().StartsWith("DefaultIfEmpty")) { Assert.Equal(default(int), operation.Item(DefaultStart, 0, source.Item).SingleOrDefault()); Assert.Equal(default(int), operation.Item(DefaultStart, 0, source.Item).SingleOrDefault(x => x == DefaultStart + DefaultSize / 2)); } } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Skip(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize / 2; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Skip(DefaultSize / 2)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Skip_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize / 2; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Skip(DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void SkipWhile(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize / 2; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).SkipWhile(x => x < DefaultStart + DefaultSize / 2)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void SkipWhile_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize / 2; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).SkipWhile(x => x < DefaultStart + DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void SkipWhile_Indexed(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize / 2; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).SkipWhile((x, index) => index < DefaultSize / 2)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void SkipWhile_Indexed_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize / 2; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).SkipWhile((x, index) => index < DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void Sum(LabeledOperation source, LabeledOperation operation) { Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize), operation.Item(DefaultStart, DefaultSize, source.Item).Sum()); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void Sum_Nullable(LabeledOperation source, LabeledOperation operation) { Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize), operation.Item(DefaultStart, DefaultSize, source.Item).Sum(x => (int?)x)); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Take(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Take(DefaultSize / 2)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize / 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Take_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Take(DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize / 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void TakeWhile(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).TakeWhile(x => x < DefaultStart + DefaultSize / 2)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize / 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void TakeWhile_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).TakeWhile(x => x < DefaultStart + DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize / 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void TakeWhile_Indexed(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).TakeWhile((x, index) => index < DefaultSize / 2)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize / 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void TakeWhile_Indexed_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).TakeWhile((x, index) => index < DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize / 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void ThenBy_Initial(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenBy(x => x)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void ThenBy_Initial_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenBy(x => x).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void ThenBy_OtherDirection(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenBy(x => -x)) { Assert.Equal(--seen, i); } Assert.Equal(DefaultStart, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void ThenBy_OtherDirection_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenBy(x => -x).ToList(), x => Assert.Equal(--seen, x)); Assert.Equal(DefaultStart, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void ThenByDescending_Initial(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenByDescending(x => -x)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void ThenByDescending_Initial_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenByDescending(x => -x).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void ThenByDescending_OtherDirection(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenByDescending(x => x)) { Assert.Equal(--seen, i); } Assert.Equal(DefaultStart, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void ThenByDescending_OtherDirection_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenByDescending(x => x).ToList(), x => Assert.Equal(--seen, x)); Assert.Equal(DefaultStart, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void ToArray(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).ToArray(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void ToDictionary(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).ToDictionary(x => x * 2), p => { seen.Add(p.Key / 2); Assert.Equal(p.Key, p.Value * 2); }); seen.AssertComplete(); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void ToDictionary_ElementSelector(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).ToDictionary(x => x, y => y * 2), p => { seen.Add(p.Key); Assert.Equal(p.Key * 2, p.Value); }); seen.AssertComplete(); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void ToList(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void ToLookup(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seenOuter = new IntegerRangeSet(0, 2); ILookup<int, int> lookup = operation.Item(DefaultStart, DefaultSize, source.Item).ToLookup(x => x % 2); Assert.All(lookup, group => { seenOuter.Add(group.Key); IntegerRangeSet seenInner = new IntegerRangeSet(DefaultStart / 2, (DefaultSize + ((1 + group.Key) % 2)) / 2); Assert.All(group, y => { Assert.Equal(group.Key, y % 2); seenInner.Add(y / 2); }); seenInner.AssertComplete(); }); seenOuter.AssertComplete(); Assert.Empty(lookup[-1]); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] [MemberData(nameof(UnaryUnorderedOperators))] [MemberData(nameof(BinaryUnorderedOperators))] public static void ToLookup_ElementSelector(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seenOuter = new IntegerRangeSet(0, 2); ILookup<int, int> lookup = operation.Item(DefaultStart, DefaultSize, source.Item).ToLookup(x => x % 2, y => -y); Assert.All(lookup, group => { seenOuter.Add(group.Key); IntegerRangeSet seenInner = new IntegerRangeSet(DefaultStart / 2, (DefaultSize + ((1 + group.Key) % 2)) / 2); Assert.All(group, y => { Assert.Equal(group.Key, -y % 2); seenInner.Add(-y / 2); }); seenInner.AssertComplete(); }); seenOuter.AssertComplete(); Assert.Empty(lookup[-1]); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Where(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Where(x => x < DefaultStart + DefaultSize / 2)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize / 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Where_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Where(x => x < DefaultStart + DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize / 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Where_Indexed(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Where((x, index) => index < DefaultSize / 2)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize / 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Where_Indexed_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Where((x, index) => index < DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize / 2, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Zip(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; ParallelQuery<int> query = operation.Item(DefaultStart * 2, DefaultSize, source.Item) .Zip(operation.Item(0, DefaultSize, source.Item), (x, y) => (x + y) / 2); foreach (int i in query) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData(nameof(UnaryOperators))] [MemberData(nameof(BinaryOperators))] public static void Zip_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; ParallelQuery<int> query = operation.Item(0, DefaultSize, source.Item) .Zip(operation.Item(DefaultStart * 2, DefaultSize, source.Item), (x, y) => (x + y) / 2); Assert.All(query.ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Data.Entity.Core; using System.Data.Entity.Core.Metadata.Edm; using System.Data.Entity.Core.Objects.DataClasses; using System.Data.Entity.Spatial; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; namespace MockDbSet { internal static class TypeExtensions { private static readonly Dictionary<Type, PrimitiveType> _primitiveTypesMap = new Dictionary<Type, PrimitiveType>(); [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")] static TypeExtensions() { foreach (var primitiveType in PrimitiveType.GetEdmPrimitiveTypes()) { if (!_primitiveTypesMap.ContainsKey(primitiveType.ClrEquivalentType)) { _primitiveTypesMap.Add(primitiveType.ClrEquivalentType, primitiveType); } } } public static bool IsCollection(this Type type) { return type.IsCollection(out type); } public static bool IsCollection(this Type type, out Type elementType) { Debug.Assert(!type.IsGenericTypeDefinition()); elementType = TryGetElementType(type, typeof(ICollection<>)); if (elementType == null || type.IsArray) { elementType = type; return false; } return true; } public static IEnumerable<PropertyInfo> GetNonIndexerProperties(this Type type) { return type.GetRuntimeProperties().Where( p => PropertyInfoExtensions.IsPublic(p) && !p.GetIndexParameters().Any()); } // <summary> // Determine if the given type type implements the given generic interface or derives from the given generic type, // and if so return the element type of the collection. If the type implements the generic interface several times // <c>null</c> will be returned. // </summary> // <param name="type"> The type to examine. </param> // <param name="interfaceOrBaseType"> The generic type to be queried for. </param> // <returns> // <c>null</c> if <paramref name="interfaceOrBaseType"/> isn't implemented or implemented multiple times, // otherwise the generic argument. // </returns> public static Type TryGetElementType(this Type type, Type interfaceOrBaseType) { Debug.Assert(interfaceOrBaseType.GetGenericArguments().Count() == 1); if (!type.IsGenericTypeDefinition()) { var types = GetGenericTypeImplementations(type, interfaceOrBaseType).ToList(); return types.Count == 1 ? types[0].GetGenericArguments().FirstOrDefault() : null; } return null; } // <summary> // Determine if the given type type implements the given generic interface or derives from the given generic type, // and if so return the concrete types implemented. // </summary> // <param name="type"> The type to examine. </param> // <param name="interfaceOrBaseType"> The generic type to be queried for. </param> // <returns> // The generic types constructed from <paramref name="interfaceOrBaseType"/> and implemented by <paramref name="type"/>. // </returns> public static IEnumerable<Type> GetGenericTypeImplementations(this Type type, Type interfaceOrBaseType) { if (!type.IsGenericTypeDefinition()) { return (interfaceOrBaseType.IsInterface() ? type.GetInterfaces() : type.GetBaseTypes()) .Union(new[] { type }) .Where( t => IsGenericType(t) && t.GetGenericTypeDefinition() == interfaceOrBaseType); } return Enumerable.Empty<Type>(); } public static IEnumerable<Type> GetBaseTypes(this Type type) { type = type.BaseType(); while (type != null) { yield return type; type = type.BaseType(); } } public static Type GetTargetType(this Type type) { Type elementType; if (!type.IsCollection(out elementType)) { elementType = type; } return elementType; } public static bool TryUnwrapNullableType(this Type type, out Type underlyingType) { Debug.Assert(!type.IsGenericTypeDefinition()); underlyingType = Nullable.GetUnderlyingType(type) ?? type; return underlyingType != type; } // <summary> // Returns true if a variable of this type can be assigned a null value // </summary> // <returns> True if a reference type or a nullable value type, false otherwise </returns> public static bool IsNullable(this Type type) { return !type.IsValueType() || Nullable.GetUnderlyingType(type) != null; } public static bool IsValidStructuralType(this Type type) { return !(type.IsGenericType() || type.IsValueType() || type.IsPrimitive() || type.IsInterface() || type.IsArray || type == typeof(string) || type == typeof(DbGeography) || type == typeof(DbGeometry)) && type.IsValidStructuralPropertyType(); } public static bool IsValidStructuralPropertyType(this Type type) { return !(type.IsGenericTypeDefinition() || type.IsPointer || type == typeof(object) || typeof(ComplexObject).IsAssignableFrom(type) || typeof(EntityObject).IsAssignableFrom(type) || typeof(StructuralObject).IsAssignableFrom(type) || typeof(EntityKey).IsAssignableFrom(type) || typeof(EntityReference).IsAssignableFrom(type)); } public static bool IsPrimitiveType(this Type type, out PrimitiveType primitiveType) { return _primitiveTypesMap.TryGetValue(type, out primitiveType); } #if !SQLSERVER && !EF_FUNCTIONALS //public static T CreateInstance<T>( // this Type type, // Func<string, string, string> typeMessageFactory, // Func<string, Exception> exceptionFactory = null) //{ // exceptionFactory = exceptionFactory ?? (s => new InvalidOperationException(s)); // if (!typeof(T).IsAssignableFrom(type)) // { // throw exceptionFactory(typeMessageFactory(type.ToString(), typeof(T).ToString())); // } // return CreateInstance<T>(type, exceptionFactory); //} //public static T CreateInstance<T>(this Type type, Func<string, Exception> exceptionFactory = null) //{ // Debug.Assert(typeof(T).IsAssignableFrom(type)); // exceptionFactory = exceptionFactory ?? (s => new InvalidOperationException(s)); // if (type.GetDeclaredConstructor() == null) // { // throw exceptionFactory(Strings.CreateInstance_NoParameterlessConstructor(type)); // } // if (type.IsAbstract()) // { // throw exceptionFactory(Strings.CreateInstance_AbstractType(type)); // } // if (type.IsGenericType()) // { // throw exceptionFactory(Strings.CreateInstance_GenericType(type)); // } // return (T)Activator.CreateInstance(type, nonPublic: true); //} #endif public static bool IsValidEdmScalarType(this Type type) { type.TryUnwrapNullableType(out type); PrimitiveType _; return type.IsPrimitiveType(out _) || type.IsEnum(); } public static string NestingNamespace(this Type type) { if (!type.IsNested) { return type.Namespace; } var fullName = type.FullName; return fullName.Substring(0, fullName.Length - type.Name.Length - 1).Replace('+', '.'); } public static string FullNameWithNesting(this Type type) { if (!type.IsNested) { return type.FullName; } return type.FullName.Replace('+', '.'); } public static bool OverridesEqualsOrGetHashCode(this Type type) { while (type != typeof(object)) { if (type.GetDeclaredMethods() .Any(m => (m.Name == "Equals" || m.Name == "GetHashCode") && m.DeclaringType != typeof(object) && m.GetBaseDefinition().DeclaringType == typeof(object))) { return true; } type = type.BaseType(); } return false; } public static bool IsPublic(this Type type) { #if NET40 return type.IsPublic || (type.IsNestedPublic && type.DeclaringType.IsPublic()); #else var typeInfo = type.GetTypeInfo(); return typeInfo.IsPublic || (typeInfo.IsNestedPublic && type.DeclaringType.IsPublic()); #endif } public static bool IsNotPublic(this Type type) { return !type.IsPublic(); } public static MethodInfo GetOnlyDeclaredMethod(this Type type, string name) { return type.GetDeclaredMethods(name).SingleOrDefault(); } public static MethodInfo GetDeclaredMethod(this Type type, string name, params Type[] parameterTypes) { return type.GetDeclaredMethods(name) .SingleOrDefault(m => m.GetParameters().Select(p => p.ParameterType).SequenceEqual(parameterTypes)); } public static MethodInfo GetPublicInstanceMethod(this Type type, string name, params Type[] parameterTypes) { return type.GetRuntimeMethod(name, m => m.IsPublic && !m.IsStatic, parameterTypes); } public static MethodInfo GetRuntimeMethod( this Type type, string name, Func<MethodInfo, bool> predicate, params Type[][] parameterTypes) { return parameterTypes .Select(t => type.GetRuntimeMethod(name, predicate, t)) .FirstOrDefault(m => m != null); } private static MethodInfo GetRuntimeMethod( this Type type, string name, Func<MethodInfo, bool> predicate, Type[] parameterTypes) { var methods = type.GetRuntimeMethods().Where( m => name == m.Name && predicate(m) && m.GetParameters().Select(p => p.ParameterType).SequenceEqual(parameterTypes)).ToArray(); if (methods.Length == 1) { return methods[0]; } return methods.SingleOrDefault( m => !methods.Any(m2 => m2.DeclaringType.IsSubclassOf(m.DeclaringType))); } #if NET40 public static IEnumerable<MethodInfo> GetRuntimeMethods(this Type type) { DebugCheck.NotNull(type); const BindingFlags bindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; return type.GetMethods(bindingFlags); } #endif public static IEnumerable<MethodInfo> GetDeclaredMethods(this Type type) { #if NET40 const BindingFlags bindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; return type.GetMethods(bindingFlags); #else return type.GetTypeInfo().DeclaredMethods; #endif } public static IEnumerable<MethodInfo> GetDeclaredMethods(this Type type, string name) { #if NET40 const BindingFlags bindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; return type.GetMember(name, MemberTypes.Method, bindingFlags).OfType<MethodInfo>(); #else return type.GetTypeInfo().GetDeclaredMethods(name); #endif } public static PropertyInfo GetDeclaredProperty(this Type type, string name) { #if NET40 const BindingFlags bindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; return type.GetProperty(name, bindingFlags); #else return type.GetTypeInfo().GetDeclaredProperty(name); #endif } public static IEnumerable<PropertyInfo> GetDeclaredProperties(this Type type) { #if NET40 const BindingFlags bindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; return type.GetProperties(bindingFlags); #else return type.GetTypeInfo().DeclaredProperties; #endif } public static IEnumerable<PropertyInfo> GetInstanceProperties(this Type type) { return type.GetRuntimeProperties().Where(p => !p.IsStatic()); } #if NET40 public static IEnumerable<PropertyInfo> GetRuntimeProperties(this Type type) { DebugCheck.NotNull(type); const BindingFlags bindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; return type.GetProperties(bindingFlags); } #endif #if NET40 public static PropertyInfo GetRuntimeProperty(this Type type, string name) { DebugCheck.NotNull(type); DebugCheck.NotEmpty(name); return type.GetProperty(name); } #endif public static PropertyInfo GetAnyProperty(this Type type, string name) { var props = type.GetRuntimeProperties().Where(p => p.Name == name).ToList(); if (props.Count() > 1) { throw new AmbiguousMatchException(); } return props.SingleOrDefault(); } public static PropertyInfo GetInstanceProperty(this Type type, string name) { var props = type.GetRuntimeProperties().Where(p => p.Name == name && !p.IsStatic()).ToList(); if (props.Count() > 1) { throw new AmbiguousMatchException(); } return props.SingleOrDefault(); } public static PropertyInfo GetStaticProperty(this Type type, string name) { var properties = type.GetRuntimeProperties().Where(p => p.Name == name && p.IsStatic()).ToList(); if (properties.Count() > 1) { throw new AmbiguousMatchException(); } return properties.SingleOrDefault(); } public static PropertyInfo GetTopProperty(this Type type, string name) { do { #if NET40 const BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; var propertyInfo = type.GetProperty(name, bindingFlags); if (propertyInfo != null) { return propertyInfo; } type = type.BaseType; #else var typeInfo = type.GetTypeInfo(); var propertyInfo = typeInfo.GetDeclaredProperty(name); if (propertyInfo != null && !(propertyInfo.GetMethod ?? propertyInfo.SetMethod).IsStatic) { return propertyInfo; } type = typeInfo.BaseType; #endif } while (type != null); return null; } public static Assembly Assembly(this Type type) { #if NET40 return type.Assembly; #else return type.GetTypeInfo().Assembly; #endif } public static Type BaseType(this Type type) { #if NET40 return type.BaseType; #else return type.GetTypeInfo().BaseType; #endif } #if NET40 public static IEnumerable<FieldInfo> GetRuntimeFields(this Type type) { DebugCheck.NotNull(type); const BindingFlags bindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; return type.GetFields(bindingFlags); } #endif public static bool IsGenericType(this Type type) { #if NET40 return type.IsGenericType; #else return type.GetTypeInfo().IsGenericType; #endif } public static bool IsGenericTypeDefinition(this Type type) { #if NET40 return type.IsGenericTypeDefinition; #else return type.GetTypeInfo().IsGenericTypeDefinition; #endif } public static TypeAttributes Attributes(this Type type) { #if NET40 return type.Attributes; #else return type.GetTypeInfo().Attributes; #endif } public static bool IsClass(this Type type) { #if NET40 return type.IsClass; #else return type.GetTypeInfo().IsClass; #endif } public static bool IsInterface(this Type type) { #if NET40 return type.IsInterface; #else return type.GetTypeInfo().IsInterface; #endif } public static bool IsValueType(this Type type) { #if NET40 return type.IsValueType; #else return type.GetTypeInfo().IsValueType; #endif } public static bool IsAbstract(this Type type) { #if NET40 return type.IsAbstract; #else return type.GetTypeInfo().IsAbstract; #endif } public static bool IsSealed(this Type type) { #if NET40 return type.IsSealed; #else return type.GetTypeInfo().IsSealed; #endif } public static bool IsEnum(this Type type) { #if NET40 return type.IsEnum; #else return type.GetTypeInfo().IsEnum; #endif } public static bool IsSerializable(this Type type) { #if NET40 return type.IsSerializable; #else return type.GetTypeInfo().IsSerializable; #endif } public static bool IsGenericParameter(this Type type) { #if NET40 return type.IsGenericParameter; #else return type.GetTypeInfo().IsGenericParameter; #endif } public static bool ContainsGenericParameters(this Type type) { #if NET40 return type.ContainsGenericParameters; #else return type.GetTypeInfo().ContainsGenericParameters; #endif } public static bool IsPrimitive(this Type type) { #if NET40 return type.IsPrimitive; #else return type.GetTypeInfo().IsPrimitive; #endif } public static IEnumerable<ConstructorInfo> GetDeclaredConstructors(this Type type) { #if NET40 const BindingFlags bindingFlags = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; return type.GetConstructors(bindingFlags); #else return type.GetTypeInfo().DeclaredConstructors; #endif } public static ConstructorInfo GetDeclaredConstructor(this Type type, params Type[] parameterTypes) { return type.GetDeclaredConstructors().SingleOrDefault( c => !c.IsStatic && c.GetParameters().Select(p => p.ParameterType).SequenceEqual(parameterTypes)); } public static ConstructorInfo GetPublicConstructor(this Type type, params Type[] parameterTypes) { var constructor = type.GetDeclaredConstructor(parameterTypes); return constructor != null && constructor.IsPublic ? constructor : null; } public static ConstructorInfo GetDeclaredConstructor( this Type type, Func<ConstructorInfo, bool> predicate, params Type[][] parameterTypes) { return parameterTypes .Select(p => type.GetDeclaredConstructor(p)) .FirstOrDefault(c => c != null && predicate(c)); } #if !NET40 // This extension method will only be used when compiling for a platform on which Type // does not expose this method directly. public static bool IsSubclassOf(this Type type, Type otherType) { return type.GetTypeInfo().IsSubclassOf(otherType); } #endif } }
// // Copyright (c) 2004-2021 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.Internal { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using NLog.Common; using NLog.Config; /// <summary> /// Scans (breadth-first) the object graph following all the edges whose are /// instances have <see cref="NLogConfigurationItemAttribute"/> attached and returns /// all objects implementing a specified interfaces. /// </summary> internal static class ObjectGraphScanner { /// <summary> /// Finds the objects which have attached <see cref="NLogConfigurationItemAttribute"/> which are reachable /// from any of the given root objects when traversing the object graph over public properties. /// </summary> /// <typeparam name="T">Type of the objects to return.</typeparam> /// <param name="aggressiveSearch">Also search the properties of the wanted objects.</param> /// <param name="rootObjects">The root objects.</param> /// <returns>Ordered list of objects implementing T.</returns> public static List<T> FindReachableObjects<T>(bool aggressiveSearch, params object[] rootObjects) where T : class { if (InternalLogger.IsTraceEnabled) { InternalLogger.Trace("FindReachableObject<{0}>:", typeof(T)); } var result = new List<T>(); var visitedObjects = new HashSet<object>(SingleItemOptimizedHashSet<object>.ReferenceEqualityComparer.Default); foreach (var rootObject in rootObjects) { if (IncludeConfigurationItem(rootObject)) { ScanProperties(aggressiveSearch, result, rootObject, 0, visitedObjects); } } return result; } /// <remarks>ISet is not there in .net35, so using HashSet</remarks> private static void ScanProperties<T>(bool aggressiveSearch, List<T> result, object o, int level, HashSet<object> visitedObjects) where T : class { if (o is null) { return; } if (visitedObjects.Contains(o)) { return; } var type = o.GetType(); if (InternalLogger.IsTraceEnabled) { InternalLogger.Trace("{0}Scanning {1} '{2}'", new string(' ', level), type.Name, o); } if (o is T t) { result.Add(t); if (!aggressiveSearch) { return; } } foreach (var configProp in PropertyHelper.GetAllConfigItemProperties(type)) { if (string.IsNullOrEmpty(configProp.Key)) continue; // Ignore default values var propInfo = configProp.Value; if (PropertyHelper.IsSimplePropertyType(propInfo.PropertyType)) continue; var propValue = propInfo.GetValue(o, null); if (propValue is null) continue; visitedObjects.Add(o); ScanPropertyForObject(propInfo, propValue, aggressiveSearch, result, level, visitedObjects); } } private static void ScanPropertyForObject<T>(PropertyInfo prop, object propValue, bool aggressiveSearch, List<T> result, int level, HashSet<object> visitedObjects) where T : class { if (InternalLogger.IsTraceEnabled) { InternalLogger.Trace("{0}Scanning Property {1} '{2}' {3}", new string(' ', level + 1), prop.Name, propValue.ToString(), prop.PropertyType.Namespace); } if (propValue is IEnumerable enumerable) { var list = ConvertEnumerableToList(enumerable); if (list.Count > 0 && !visitedObjects.Contains(list)) { visitedObjects.Add(list); ScanPropertiesList(list, aggressiveSearch, result, level + 1, visitedObjects); } } else { // .NET native doesn't always allow reflection of System-types (Ex. Encoding) if (IncludeConfigurationItem(propValue, prop.PropertyType)) { ScanProperties(aggressiveSearch, result, propValue, level + 1, visitedObjects); } } } private static void ScanPropertiesList<T>(IList list, bool aggressiveSearch, List<T> result, int level, HashSet<object> visitedObjects) where T : class { for (int i = 0; i < list.Count; i++) { var element = list[i]; if (IncludeConfigurationItem(element)) { ScanProperties(aggressiveSearch, result, element, level, visitedObjects); } } } private static IList ConvertEnumerableToList(IEnumerable enumerable) { if (enumerable is ICollection collection && collection.Count == 0) { return ArrayHelper.Empty<object>(); } if (enumerable is IList list) { if (!list.IsReadOnly && !(list is Array)) { // Protect against collection was modified List<object> elements = new List<object>(list.Count); lock (list.SyncRoot) { for (int i = 0; i < list.Count; i++) { elements.Add(list[i]); } } return elements; } return list; } //new list to prevent: Collection was modified after the enumerator was instantiated. //note .Cast is tread-unsafe! But at least it isn't a ICollection / IList return enumerable.Cast<object>().ToList(); } private static bool IncludeConfigurationItem(object item, Type propertyType = null) { propertyType = propertyType ?? item?.GetType(); if (propertyType is null) return false; if (PropertyHelper.IsConfigurationItemType(propertyType)) return true; var itemType = item?.GetType(); if (itemType != null && itemType != propertyType && PropertyHelper.IsConfigurationItemType(itemType)) return true; return false; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Xml; using System.IO; using System.Web.Hosting; using System.Diagnostics; using System.Text; using System.Text.RegularExpressions; using System.Globalization; using DotNetNuke; using DotNetNuke.Security; using DotNetNuke.Entities.Portals; using DotNetNuke.Services.Scheduling; using DotNetNuke.Entities.Modules; using System.Reflection; using System.Security; using System.Security.Permissions; using Brafton; using Brafton.Modules.Globals; using System.Net; using Brafton.Modules.VideoImporter; namespace BraftonView.Brafton_Importer_Clean { [SecurityCritical] public partial class DesktopModules_Brafton_View2 : DotNetNuke.Entities.Modules.PortalModuleBase { //Connection properties public SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer"].ToString()); public SqlConnection connection2; public SqlCommand cmd = new SqlCommand(); public SqlCommand cmd2 = new SqlCommand(); //Application path variable public string appPath; public Boolean isEditable; //DNN Variables int intPortalID; int PageTabId; string checkDomain; //Local Variables public int checkBlogModule; public int checkFriendURLS; public int checkAuthor; public int checkBlogCreated; public int checkNewsAPI; public int checkBaseUrl; public int checkLimit; public int checkBlogID; public int checkVidID; public Dictionary<string, int> checkAll = new Dictionary<string, int>(); //Global Variables public int IncludeUpdatedFeedContent; public string strip(string alias) { // invalid chars, make into spaces alias = Regex.Replace(alias, @"[^a-zA-Z0-9\s-]", ""); // convert multiple spaces/hyphens into one space alias = Regex.Replace(alias, @"[\s-]+", " ").Trim(); // hyphens alias = Regex.Replace(alias, @"\s", "-"); return alias; } public Dictionary<string, int> checks() { /* cmd.CommandText = "IF OBJECT_ID('Blog_Settings') IS NOT NULL select 1 else select 0"; checkFriendURLS = 1; checkAll.Add("Friendly Urls", checkFriendURLS); */ cmd.CommandText = "IF OBJECT_ID('Blog_Blogs') IS NOT NULL SELECT 1 Else Select 0"; checkBlogCreated = (int)cmd.ExecuteScalar(); checkAll.Add("Blog", checkBlogCreated); cmd.CommandText = "IF (SELECT BaseUrl FROM Brafton WHERE content='1') IS NOT NULL SELECT 1 ELSE SELECT 0"; checkBaseUrl = (int)cmd.ExecuteScalar(); checkAll.Add("Base Url", checkBaseUrl); cmd.CommandText = "IF (SELECT Api FROM Brafton WHERE content='1') IS NOT NULL SELECT 1 ELSE SELECT 0"; checkNewsAPI = (int)cmd.ExecuteScalar(); checkAll.Add("News API", checkNewsAPI); cmd.CommandText = "IF (SELECT Limit FROM Brafton WHERE content='1') IS NOT NULL SELECT 1 ELSE SELECT 0"; checkLimit = (int)cmd.ExecuteScalar(); checkAll.Add("Limit", checkLimit); cmd.CommandText = "IF (SELECT count(*) as total_record FROM DesktopModules WHERE FriendlyName = 'blog') > 0 Select 1 else select 0"; checkBlogModule = ((int)cmd.ExecuteScalar()); checkAll.Add("Blog Module", checkBlogModule); cmd.CommandText = "If (SELECT count(*) as total_record FROM Brafton WHERE BlogId >= 1) > 0 Select 1 else select 0"; checkBlogID = ((int)cmd.ExecuteScalar()); checkAll.Add("Blog ID", checkBlogID); cmd.CommandText = "IF (SELECT VideoPublicKey FROM Brafton WHERE content='1') IS NOT NULL SELECT 1 ELSE SELECT 0"; checkVidID = ((int)cmd.ExecuteScalar()); checkAll.Add("Vid ID", checkVidID); cmd.CommandText = "IF (SELECT AuthorId FROM Brafton WHERE content='1') IS NOT NULL SELECT 1 ELSE SELECT 0"; checkAuthor = ((int)cmd.ExecuteScalar()); checkAll.Add("Author", checkAuthor); return checkAll; } public Boolean braftonViewable() { isEditable = HttpContext.Current.User.Identity.IsAuthenticated; if (isEditable) { return true; } return false; } protected void Page_Load(object sender, EventArgs e) { ModuleConfiguration.ModuleTitle = ""; //runBraftonImporter(); HtmlMeta meta = new HtmlMeta(); meta.Name = "brafton"; meta.Content = "my brafton"; this.Page.Header.Controls.Add(meta); //connection.Open(); //cmd.Connection = connection; //cmd2.Connection = connection; //cmd2.CommandText = "Select Title From Blog_Entries where EntryID = 2"; //string apiTest = cmd2.ExecuteScalar().ToString(); // apiURLLabel.Text = apiTest; //connection.Close(); //******************************************************************** //TODO check for Brafton Table //cmd2.CommandText = "CREATE TABLE [dbo].Brafton(Id int IDENTITY(1,1) NOT NULL,Content nvarchar(MAX) NULL,Api nvarchar(MAX) NULL,BaseUrl nvarchar(MAX) NULL, BlogId int NULL,PortalId int NULL,TabId int NULL,DomainName nvarchar(MAX) NULL, Limit int NULL)"; //cmd2.ExecuteNonQuery(); //******************************************************************** try { //Get current directory for style sheets and images appPath = HttpRuntime.AppDomainAppVirtualPath == "/" ? appPath = "" : appPath = HttpRuntime.AppDomainAppVirtualPath; isEditable = HttpContext.Current.User.Identity.IsAuthenticated; connection.Open(); cmd.Connection = connection; //Showing your current portal ID intPortalID = PortalSettings.PortalId; currentPortalID.Text = intPortalID.ToString(); //Showing your current TabID PageTabId = PortalSettings.ActiveTab.TabID; currentTabID.Text = PortalSettings.ActiveTab.TabID.ToString(); //Get your current domain to insert into database for error checking checkDomain = HttpContext.Current.Request.Url.Host; //MyGlobals.MyGlobalError = MyGlobals.MyGlobalError + "Check Domain:" + checkDomain; Dictionary<string, int> checkAll = checks(); //Sets the current PortalID in the Brafton Table cmd.CommandText = "IF Exists (SELECT * FROM Brafton WHERE content='1') UPDATE Brafton SET PortalId = " + intPortalID + " WHERE Content = '1' else INSERT INTO Brafton (Content, PortalId) VALUES (1, '" + intPortalID + "')"; cmd.ExecuteNonQuery(); //Sets the current TabID in the Brafton Table cmd.CommandText = "IF Exists (SELECT * FROM Brafton WHERE content='1') UPDATE Brafton SET TabId = " + PageTabId + " WHERE Content = '1' else INSERT INTO Brafton (Content, TabId) VALUES (1, '" + PageTabId + "')"; cmd.ExecuteNonQuery(); //Sets the current domain in the Brafton Table cmd.CommandText = "IF Exists (SELECT * FROM Brafton WHERE content='1') UPDATE Brafton SET DomainName = 'http://" + checkDomain + "' WHERE Content = '1' else INSERT INTO Brafton (Content, DomainName) VALUES (1, 'http://" + checkDomain + "')"; cmd.ExecuteNonQuery(); //HERE WE SET THE GLOBAL VARIABLES //This fills all the relevant fields with values from the database if they exist //All the prior queries have been left intact for the time being but can eventually be phased out MyGlobals.PopGlobals(); checkedStatusLabel.Text = MyGlobals.MyGlobalError; //For debugging it is a global text field you pass errors into /* if (checkAll["Friendly Urls"] == 1) { boolFriendURL.Text = "True"; boolFriendURL.CssClass = "boolTrue"; } else { boolFriendURL.Text = "False"; boolFriendURL.CssClass = "boolFalse"; } */ if (checkAll["Blog Module"] == 1) { boolBlogModule.Text = "True"; boolBlogModule.CssClass = "boolTrue"; cmd.CommandText = "IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='Blog_Posts' AND column_name='BraftonID') BEGIN ALTER TABLE Blog_Posts ADD BraftonID nvarchar(255) END"; cmd.ExecuteNonQuery(); } else { boolBlogModule.Text = "False"; boolBlogModule.CssClass = "boolFalse"; } if (checkAll["Blog"] == 1) { boolBlogCreated.Text = "True"; boolBlogCreated.CssClass = "boolTrue"; cmd.CommandText = "Select Title From Blog_Blogs"; SqlDataReader blogOptions = cmd.ExecuteReader(); if (!IsPostBack && blogOptions.HasRows) { while (blogOptions.Read()) { blogIdDrpDwn.Items.Add(new ListItem(blogOptions.GetString(0))); } } blogOptions.Close(); setAPIPH.Visible = true; } else { boolBlogCreated.Text = "False"; boolBlogCreated.CssClass = "boolFalse"; } if (!IsPostBack && checkAll["Author"] == 1) { boolAuthorSet.Text = "True"; boolAuthorSet.CssClass = "boolTrue"; cmd.CommandText = "Select Username, UserID From Users"; SqlDataReader blogAuthors = cmd.ExecuteReader(); if (blogAuthors.HasRows) { while (blogAuthors.Read()) { //string auth = blogAuthors.GetValue(1).ToString(); //MyGlobals.MyGlobalError = MyGlobals.MyGlobalError + "The Id is : " + blogAuthors.GetValue(1).ToString() + "<br/>"; blogUsersDrpDwn.Items.Add(new ListItem(blogAuthors.GetString(0), blogAuthors.GetValue(1).ToString() )); // blogUsersDrpDwn.Items.Add(new ListItem(blogAuthors.GetString(0))); } } blogAuthors.Close(); cmd.CommandText = "Select AuthorId From Brafton Where Content = '1'"; SqlDataReader thisAuthor = cmd.ExecuteReader(); if (thisAuthor.HasRows) { while (thisAuthor.Read()) { MyGlobals.MyGlobalError = MyGlobals.MyGlobalError + "The author is " + thisAuthor.GetValue(0) + "<br/>"; int auth = (int)thisAuthor.GetValue(0); blogUsersDrpDwn.SelectedValue = (string)auth.ToString(); } } thisAuthor.Close(); } else { if (checkAll["Author"] == 1) { boolAuthorSet.Text = "True"; boolAuthorSet.CssClass = "boolTrue"; } else { boolAuthorSet.Text = "False"; boolAuthorSet.CssClass = "boolFalse"; } } if (checkAll["News API"] == 0) { boolCheckAPI.Text = "False"; boolCheckAPI.CssClass = "boolFalse"; nextStep.Visible = false; } else { cmd.CommandText = "SELECT Api FROM Brafton WHERE content='1'"; string newsAPI = (string)cmd.ExecuteScalar(); boolCheckAPI.Text = "<span class='boolTrue'>True</span>"; //apiURLLabel.Text = newsAPI; if (Page.IsPostBack == false) { apiURL.Text = newsAPI; } if (checkAll["Base Url"] == 1) { nextStep.Visible = true; } } if (checkAll["Base Url"] == 0) { boolCheckUrl.Text = "False"; boolCheckUrl.CssClass = "boolFalse"; } else { cmd.CommandText = "SELECT BaseUrl FROM Brafton WHERE content='1'"; string newsAPI = (string)cmd.ExecuteScalar(); boolCheckUrl.Text = "<span class='boolTrue'>True</span>"; //baseURLLabel.Text = newsAPI; if (Page.IsPostBack == false) { baseURL.Text = newsAPI; } } //if (checkAll["Limit"] == 1) //{ // cmd.CommandText = "SELECT Limit FROM Brafton WHERE content='1'"; // limitLabel.Text = cmd.ExecuteScalar().ToString(); //} if (checkAll["Blog ID"] == 0) { boolCheckBlogID.Text = "<span class='boolFalse'>False</span>"; } else { boolCheckBlogID.Text = "<span class='boolTrue'>True</span>"; cmd.CommandText = "Select Title From Blog_Blogs Where BlogID = " + getBlogID(); string blogTitle = (string)cmd.ExecuteScalar(); currentBlogID.Text = blogTitle; } //check for video settings if there fill fields and make visible if (checkAll["Vid ID"] == 1 || checkAll["Vid ID"] == 0) { if (Page.IsPostBack == false) { VideoSettings.Visible = true; //InclVideo.Checked = true; updateVidSettings.Visible = true; MyGlobals.IncludeVideo = 1; setVidSettings.Visible = false; CurrentVidSetting1.Visible = true; CurrentVidSetting2.Visible = false; //CurrentVidSetting3.Visible = true; //VideoBaseURL.Text = MyGlobals.VideoBaseURL; VideoBaseURL.Text = "http://livevideo.api.brafton.com"; VideoPhotoURL.Text = MyGlobals.VideoPhotoURL; VideoPublicKey.Text = MyGlobals.VideoPublicKey; VideoSecretKey.Text = MyGlobals.VideoSecretKey; VideoFeedNumber.Text = MyGlobals.VideoFeedNumber.ToString(); RadioButtonList1.SelectedValue = "video"; VideoSettings.Visible = true; VideoPlaceHolder.Visible = true; Import.Visible = true; } } if (checkAll["Vid ID"] == 1 && checkAll["Base Url"] == 1) { Import.Visible = true; if (Page.IsPostBack == false) { RadioButtonList1.SelectedValue = "both"; ArticlePlaceHolder.Visible = true; VideoSettings.Visible = true; ArticlePlaceHolder.Visible = true; VideoPlaceHolder.Visible = true; } } if (checkAll.Values.Sum() == 6) { Import.Visible = true; if (Page.IsPostBack == false) { ArticlePlaceHolder.Visible = true; RadioButtonList1.SelectedValue = "articles"; MyGlobals.MyGlobalError = "Should be show Articles"; } } else { int sumnum = checkAll.Values.Sum(); MyGlobals.MyGlobalError = "Here is the problem" + sumnum; } //Check what the value of IncUpdatedFeedContentValue is in the db 1 is checked 0 is not checked Brafton.DotNetNuke.BraftonSchedule B1 = new Brafton.DotNetNuke.BraftonSchedule(); int checkForUpdatedCheck = B1.getUpdatedContent(); //int checkForUpdatedCheck = 0; if (Page.IsPostBack == false) { if (checkForUpdatedCheck == 1) { InclUpdatedFeedContent.Checked = true; MyGlobals.IncludeUpdatedFeedContent = 1; cmd.CommandText = "IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='Blog_Posts' AND column_name='LastUpdatedOn') BEGIN ALTER TABLE Blog_Posts ADD LastUpdatedOn DATETIME NULL END"; cmd.ExecuteNonQuery(); //checkedStatusLabel.Text = "The value in the db =" + checkForUpdatedCheck + " and the value in globals is " + MyGlobals.IncludeUpdatedFeedContent +"Means it should be checked"; } else { InclUpdatedFeedContent.Checked = false; MyGlobals.IncludeUpdatedFeedContent = 0; //checkedStatusLabel.Text = "The value in the db =" + checkForUpdatedCheck + " and the value in globals is " + MyGlobals.IncludeUpdatedFeedContent+" Means it should not be checked"; } } connection.Close(); cmd.Dispose(); } catch (Exception ex) { labelError.Text = "Generic exception: " + ex.ToString(); connection.Close(); cmd.Dispose(); } } #region GetAndSetBlock #region showSections protected void showSections(object sender, EventArgs e) { if (RadioButtonList1.Text == "articles") { if (Page.IsPostBack == true) { ArticlePlaceHolder.Visible = true; VideoPlaceHolder.Visible = false; MyGlobals.ArtOrBlog = "articles"; VideoSettings.Visible = false; } } if (RadioButtonList1.Text == "video") { if (Page.IsPostBack == true) { ArticlePlaceHolder.Visible = false; VideoPlaceHolder.Visible = true; MyGlobals.ArtOrBlog = "videos"; VideoSettings.Visible = true; } } if (RadioButtonList1.Text == "both") { if (Page.IsPostBack == true) { ArticlePlaceHolder.Visible = true; VideoPlaceHolder.Visible = true; VideoSettings.Visible = true; MyGlobals.ArtOrBlog = "both"; } } } #endregion #region check settings protected string checkSettings() { if (MyGlobals.ArtOrBlog == "articles" && MyGlobals.VideoSecretKey != "xxxxxx") { return "break"; } if (MyGlobals.ArtOrBlog == "videos" && MyGlobals.api != "xxxxxx") { return "break"; } if (MyGlobals.ArtOrBlog == "both" && MyGlobals.api != "xxxxxx" && MyGlobals.VideoSecretKey != "xxxxxx") { return "break"; } return "GTG"; } #endregion #region BLOG ID ///////////////////GET AND SET BLOG ID////////////////////////// protected void setBlogID_Click(object sender, EventArgs e) { connection.Open(); int findBlogID; string test = blogIdDrpDwn.Text; cmd.CommandText = "IF OBJECT_ID('Blog_Blogs') IS NOT NULL(Select BlogID FROM Blog_Blogs Where title = '" + blogIdDrpDwn.Text + "') Else select 0"; findBlogID = (int)cmd.ExecuteScalar(); if (findBlogID != 0) { cmd.CommandText = "UPDATE Brafton SET BlogId = " + findBlogID + " WHERE Content = '1'"; cmd.ExecuteNonQuery(); cmd.CommandText = "Select Title From Blog_Blogs Where BlogID = " + getBlogID(); string blogTitle = (string)cmd.ExecuteScalar(); currentBlogID.Text = blogTitle; //Set Check Blog ID Label = "TRUE" boolCheckBlogID.Text = "<span class='boolTrue'>True</span>"; //Make import button visible Import.Visible = true; } connection.Close(); } protected void setAuthorID_Click(object sender, EventArgs e) { connection.Open(); int userId; string author = blogUsersDrpDwn.Text; cmd.Connection = connection; cmd.CommandText = "SELECT UserID FROM Users WHERE Username = '" + author + "'"; userId = (int)cmd.ExecuteScalar(); cmd.CommandText = "UPDATE Brafton SET AuthorId = " + userId + " WHERE Content = '1'"; cmd.ExecuteNonQuery(); boolAuthorSet.Text = "<span class='boolTrue'>True</span>"; Import.Visible = true; connection.Close(); } protected void showVideoSettings(object sender, EventArgs e) { //if (InclVideo.Checked == true) //{ // VideoSettings.Visible = true; //} //else //{ // VideoSettings.Visible = false; //} } int getBlogID() { cmd.CommandText = "Select BlogId from Brafton Where Content = '1'"; int blogID = (int)cmd.ExecuteScalar(); return blogID; } #endregion BLOG ID #region Import Limits ///////////////////GET AND SET Limit////////////////////////// protected void setLimit_Click(object sender, EventArgs e) { string localVariable = "setLimit_Click"; } #endregion Import Limits #region API Key ///////////////////GET AND SET API KEY////////////////////////// protected void setAPI_Click(object sender, EventArgs e) { string newsURL = apiURL.Text; connection.Open(); cmd.Connection = connection; try { cmd.CommandText = "IF OBJECT_ID('Brafton') IS NOT NULL(SELECT count(*) as total_record FROM Brafton WHERE content='1') ELSE SELECT 0"; int apiAvail = (int)cmd.ExecuteScalar(); if (apiAvail == 1 && apiURL.Text != "") { cmd.CommandText = "UPDATE Brafton SET Api = '" + newsURL + "' WHERE Content = '1'"; cmd.ExecuteNonQuery(); //apiURLLabel.Text = newsURL; apiURL.Text = newsURL; boolCheckAPI.Text = "<span class='boolTrue'>True</span>"; } else if (apiAvail == 0 && apiURL.Text != "") { cmd.CommandText = "INSERT INTO Brafton (Content, Api) VALUES (1, '" + newsURL + "' )"; cmd.ExecuteNonQuery(); //apiURLLabel.Text = newsURL; apiURL.Text = newsURL; boolCheckAPI.Text = "<span class='boolTrue'>True</span>"; } if (checkAll.Values.Sum() == 6) { Import.Visible = true; } } catch (Exception ex) { labelError.Text = "Generic exception: " + ex.ToString(); } connection.Close(); } #endregion API Key #region Base URL ///////////////////GET AND SET Base URL////////////////////////// protected void setBaseURL_Click(object sender, EventArgs e) { string newBaseURL = baseURL.Text; connection.Open(); cmd.Connection = connection; try { cmd.CommandText = "IF OBJECT_ID('Brafton') IS NOT NULL(SELECT count(*) as total_record FROM Brafton WHERE content='1') ELSE SELECT 0"; int apiAvail = (int)cmd.ExecuteScalar(); if (apiAvail == 1 && baseURL.Text != "") { cmd.CommandText = "UPDATE Brafton SET BaseUrl = '" + newBaseURL + "' WHERE Content = '1'"; cmd.ExecuteNonQuery(); //baseURLLabel.Text = newBaseURL; baseURL.Text = newBaseURL; boolCheckUrl.Text = "<span class='boolTrue'>True</span>"; } else if (apiAvail == 0 && baseURL.Text != "") { cmd.CommandText = "INSERT INTO Brafton (Content, BaseUrl) VALUES (1, '" + newBaseURL + "' )"; cmd.ExecuteNonQuery(); // baseURLLabel.Text = newBaseURL; baseURL.Text = newBaseURL; boolCheckUrl.Text = "<span class='boolTrue'>True</span>"; } if (checkAll.Values.Sum() == 6) { Import.Visible = true; } } catch (Exception ex) { labelError.Text = "Generic exception: " + ex.ToString(); } connection.Close(); } // public string getBaseURL() //{ // cmd.CommandText = "SELECT BaseUrl FROM Brafton WHERE content='1'"; // string baseURL = cmd.ExecuteScalar().ToString(); // return baseURL; //} #endregion Base URL #region Updated Feed Content ///////////////////GET AND SET Checkbox for Updated Content////////////////////////// protected void setUpdateContent_Click() { connection2 = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer"].ToString()); connection2.Open(); cmd.Connection = connection2; cmd.CommandText = "IF OBJECT_ID('Brafton') IS NOT NULL(SELECT count(*) as total_record FROM Brafton WHERE content='1') ELSE SELECT 0"; int updateContent = (int)cmd.ExecuteScalar(); Brafton.DotNetNuke.BraftonSchedule B1 = new Brafton.DotNetNuke.BraftonSchedule(); int checkForUpdatedCheck = B1.getUpdatedContent(); //Check what is set in the db Brafton.DotNetNuke.BraftonSchedule B2 = new Brafton.DotNetNuke.BraftonSchedule(); int checkForUpdatedCheckDB = B2.getUpdatedContent(); if (InclUpdatedFeedContent.Checked == true) { MyGlobals.IncludeUpdatedFeedContent = 1; cmd.CommandText = "UPDATE Brafton SET IncUpdatedFeedContentValue = 1 WHERE Content = '1'"; cmd.ExecuteNonQuery(); //checkedStatusLabel.Text = "The after click value in the db =" + checkForUpdatedCheckDB + " and the value in globals is " + MyGlobals.IncludeUpdatedFeedContent+"And should be checked"; //checkedStatusLabel.Text = "CLICKED"; } else if (InclUpdatedFeedContent.Checked == false) { MyGlobals.IncludeUpdatedFeedContent = 0; cmd.CommandText = "UPDATE Brafton SET IncUpdatedFeedContentValue = 0 WHERE Content = '1'"; cmd.ExecuteNonQuery(); //checkedStatusLabel.Text = "The afet click value in the db =" + checkForUpdatedCheckDB + " and the value in globals is " + MyGlobals.IncludeUpdatedFeedContent+"And should not be checked"; //checkedStatusLabel.Text = "NOT CLICKED"; } else { checkedStatusLabel.Text = "SOMETHING ELSE HAPPENED"; } //connection2.Close(); try { } catch (Exception ex) { labelError.Text = "Generic exception: " + ex.ToString(); } } #endregion Updated Feed Content #region Check For Video public void checkForVideo(object sender, EventArgs e) { if (VideoBaseURL.Text != "") { MyGlobals.VideoBaseURL = VideoBaseURL.Text; BraftonVideoClass.AddUpdateVideoBaseURL(VideoBaseURL.Text); } if (VideoPhotoURL.Text != "") { MyGlobals.VideoPhotoURL = VideoPhotoURL.Text; BraftonVideoClass.AddUpdateVideoPhotoURL(VideoPhotoURL.Text); } if (VideoPublicKey.Text != "") { MyGlobals.VideoPublicKey = VideoPublicKey.Text; BraftonVideoClass.AddUpdatePublicKey(VideoPublicKey.Text); MyGlobals.IncludeVideo = 1; // currentVideoPublicKey.Text = VideoPublicKey.Text; //CurrentVidSetting1.Visible = true; //cmd.CommandText = "UPDATE Brafton SET IncUpdatedFeedContentValue = 1 WHERE Content = '1'"; //cmd.ExecuteNonQuery(); //checkedStatusLabel.Text = "The after click value in the db =" + checkForUpdatedCheckDB + " and the value in globals is " + MyGlobals.IncludeUpdatedFeedContent+"And should be checked"; //checkedStatusLabel.Text = "CLICKED"; } if (VideoSecretKey.Text != "") { MyGlobals.VideoSecretKey = VideoSecretKey.Text; BraftonVideoClass.AddUpdateSecretKey(VideoSecretKey.Text); // currentVideoSecretKey.Text = VideoSecretKey.Text; //CurrentVidSetting2.Visible = true; //cmd.CommandText = "UPDATE Brafton SET IncUpdatedFeedContentValue = 1 WHERE Content = '1'"; //cmd.ExecuteNonQuery(); //checkedStatusLabel.Text = "The after click value in the db =" + checkForUpdatedCheckDB + " and the value in globals is " + MyGlobals.IncludeUpdatedFeedContent+"And should be checked"; //checkedStatusLabel.Text = "CLICKED"; } if (VideoFeedNumber.Text != "") { int VidFeedNum = Convert.ToInt32(VideoFeedNumber.Text); MyGlobals.VideoFeedNumber = VidFeedNum; MyGlobals.VideoFeedText = VideoFeedNumber.Text; BraftonVideoClass.AddUpdateFeedNum(VidFeedNum); // currentVideoFeedNumber.Text = VideoFeedNumber.Text; //CurrentVidSetting3.Visible = true; //cmd.CommandText = "UPDATE Brafton SET IncUpdatedFeedContentValue = 1 WHERE Content = '1'"; //cmd.ExecuteNonQuery(); //checkedStatusLabel.Text = "The after click value in the db =" + checkForUpdatedCheckDB + " and the value in globals is " + MyGlobals.IncludeUpdatedFeedContent+"And should be checked"; //checkedStatusLabel.Text = MyGlobals.VideoFeedNumber; } updateVidSettings.Visible = true; setVidSettings.Visible = false; CurrentVidSetting1.Visible = true; CurrentVidSetting2.Visible = false; } #endregion Video Settings #region POSSIBLE DELETE public string getNewsURL() { cmd.CommandText = "SELECT Api FROM Brafton WHERE content='1'"; string feedURL = cmd.ExecuteScalar().ToString(); return feedURL; } #endregion POSSIBLE DELETE #endregion protected void Import_Click(object sender, EventArgs e) { //Double Check settings and confirm possible errors string cs = checkSettings(); setUpdateContent_Click(); Brafton.DotNetNuke.BraftonSchedule newSched = new Brafton.DotNetNuke.BraftonSchedule(); MyGlobals.MyGlobalError = MyGlobals.MyGlobalError + " Module id from view is:" + ModuleId + "<br/>" ; MyGlobals.BraftonViewModuleId = ModuleId; newSched.DoWork(); //Response.Redirect(Request.RawUrl); // Brafton.DotNetNuke.BraftonSchedule testSched = new Brafton.DotNetNuke.BraftonSchedule(); //errorCheckingLabel.Text = testSched.DoWork(); //testSched.DoWork(); globalErrorMessage.Text = MyGlobals.MyGlobalError; } protected void show_globals(object sender, EventArgs e) { globalErrorMessage.Text = MyGlobals.MyGlobalError + " imageInfo:" + MyGlobals.imageInfo; } protected void saveSettings(object sender, EventArgs e) { Response.Redirect(Request.RawUrl); } protected void setAuthor_click(object sender, EventArgs e) { connection.Open(); if (true) { int userId; string author = blogUsersDrpDwn.Text; /* MyGlobals.MyGlobalError = MyGlobals.MyGlobalError + " Author is supposed to be " + author + "<br/>"; cmd.Connection = connection; cmd.CommandText = "SELECT UserID FROM Users WHERE Username = '" + author + "'"; */ userId = Int32.Parse(author); if (userId != null) { cmd.CommandText = "UPDATE Brafton SET AuthorId = " + userId + " WHERE Content = '1'"; cmd.ExecuteNonQuery(); boolAuthorSet.Text = "<span class='boolTrue'>True</span>"; Import.Visible = true; } } connection.Close(); } public void runBraftonImporter(object sender, EventArgs e) { DateTime nx = new DateTime(1970, 1, 1); TimeSpan ts = DateTime.UtcNow - nx; string timestamp = ((int)ts.TotalSeconds).ToString(); MyGlobals.MyGlobalError = MyGlobals.MyGlobalError + " The TimeStamp is" + timestamp + " <br/>"; int LastImport = Settings.Contains("LastImport") ? Int32.Parse(Settings["LastImport"].ToString()) : 0; int diff = Int32.Parse(timestamp) - LastImport; MyGlobals.MyGlobalError = MyGlobals.MyGlobalError + " The difference is" + diff + " <br/>"; if (diff > 10800) { Brafton.DotNetNuke.BraftonSchedule newSched = new Brafton.DotNetNuke.BraftonSchedule(); MyGlobals.BraftonViewModuleId = ModuleId; var modules = new ModuleController(); modules.UpdateModuleSetting(ModuleId, "LastImport", timestamp); newSched.DoWork(); } } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// A movie. /// </summary> public class Movie_Core : TypeCore, ICreativeWork { public Movie_Core() { this._TypeId = 169; this._Id = "Movie"; this._Schema_Org_Url = "http://schema.org/Movie"; string label = ""; GetLabel(out label, "Movie", typeof(Movie_Core)); this._Label = label; this._Ancestors = new int[]{266,78}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{78}; this._Properties = new int[]{67,108,143,229,0,2,10,12,18,20,24,26,21,50,51,54,57,58,59,61,62,64,70,72,81,97,100,110,115,116,126,138,151,178,179,180,199,211,219,230,231,3,68,71,141,174,176,224}; } /// <summary> /// The subject matter of the content. /// </summary> private About_Core about; public About_Core About { get { return about; } set { about = value; SetPropertyInstance(about); } } /// <summary> /// Specifies the Person that is legally accountable for the CreativeWork. /// </summary> private AccountablePerson_Core accountablePerson; public AccountablePerson_Core AccountablePerson { get { return accountablePerson; } set { accountablePerson = value; SetPropertyInstance(accountablePerson); } } /// <summary> /// A cast member of the movie, TV series, season, or episode, or video. /// </summary> private Actors_Core actors; public Actors_Core Actors { get { return actors; } set { actors = value; SetPropertyInstance(actors); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// A secondary title of the CreativeWork. /// </summary> private AlternativeHeadline_Core alternativeHeadline; public AlternativeHeadline_Core AlternativeHeadline { get { return alternativeHeadline; } set { alternativeHeadline = value; SetPropertyInstance(alternativeHeadline); } } /// <summary> /// The media objects that encode this creative work. This property is a synonym for encodings. /// </summary> private AssociatedMedia_Core associatedMedia; public AssociatedMedia_Core AssociatedMedia { get { return associatedMedia; } set { associatedMedia = value; SetPropertyInstance(associatedMedia); } } /// <summary> /// An embedded audio object. /// </summary> private Audio_Core audio; public Audio_Core Audio { get { return audio; } set { audio = value; SetPropertyInstance(audio); } } /// <summary> /// The author of this content. Please note that author is special in that HTML 5 provides a special mechanism for indicating authorship via the rel tag. That is equivalent to this and may be used interchangabely. /// </summary> private Author_Core author; public Author_Core Author { get { return author; } set { author = value; SetPropertyInstance(author); } } /// <summary> /// Awards won by this person or for this creative work. /// </summary> private Awards_Core awards; public Awards_Core Awards { get { return awards; } set { awards = value; SetPropertyInstance(awards); } } /// <summary> /// Comments, typically from users, on this CreativeWork. /// </summary> private Comment_Core comment; public Comment_Core Comment { get { return comment; } set { comment = value; SetPropertyInstance(comment); } } /// <summary> /// The location of the content. /// </summary> private ContentLocation_Core contentLocation; public ContentLocation_Core ContentLocation { get { return contentLocation; } set { contentLocation = value; SetPropertyInstance(contentLocation); } } /// <summary> /// Official rating of a piece of content\u2014for example,'MPAA PG-13'. /// </summary> private ContentRating_Core contentRating; public ContentRating_Core ContentRating { get { return contentRating; } set { contentRating = value; SetPropertyInstance(contentRating); } } /// <summary> /// A secondary contributor to the CreativeWork. /// </summary> private Contributor_Core contributor; public Contributor_Core Contributor { get { return contributor; } set { contributor = value; SetPropertyInstance(contributor); } } /// <summary> /// The party holding the legal copyright to the CreativeWork. /// </summary> private CopyrightHolder_Core copyrightHolder; public CopyrightHolder_Core CopyrightHolder { get { return copyrightHolder; } set { copyrightHolder = value; SetPropertyInstance(copyrightHolder); } } /// <summary> /// The year during which the claimed copyright for the CreativeWork was first asserted. /// </summary> private CopyrightYear_Core copyrightYear; public CopyrightYear_Core CopyrightYear { get { return copyrightYear; } set { copyrightYear = value; SetPropertyInstance(copyrightYear); } } /// <summary> /// The creator/author of this CreativeWork or UserComments. This is the same as the Author property for CreativeWork. /// </summary> private Creator_Core creator; public Creator_Core Creator { get { return creator; } set { creator = value; SetPropertyInstance(creator); } } /// <summary> /// The date on which the CreativeWork was created. /// </summary> private DateCreated_Core dateCreated; public DateCreated_Core DateCreated { get { return dateCreated; } set { dateCreated = value; SetPropertyInstance(dateCreated); } } /// <summary> /// The date on which the CreativeWork was most recently modified. /// </summary> private DateModified_Core dateModified; public DateModified_Core DateModified { get { return dateModified; } set { dateModified = value; SetPropertyInstance(dateModified); } } /// <summary> /// Date of first broadcast/publication. /// </summary> private DatePublished_Core datePublished; public DatePublished_Core DatePublished { get { return datePublished; } set { datePublished = value; SetPropertyInstance(datePublished); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// The director of the movie, TV episode, or series. /// </summary> private Director_Core director; public Director_Core Director { get { return director; } set { director = value; SetPropertyInstance(director); } } /// <summary> /// A link to the page containing the comments of the CreativeWork. /// </summary> private DiscussionURL_Core discussionURL; public DiscussionURL_Core DiscussionURL { get { return discussionURL; } set { discussionURL = value; SetPropertyInstance(discussionURL); } } /// <summary> /// The duration of the item (movie, audio recording, event, etc.) in <a href=\http://en.wikipedia.org/wiki/ISO_8601\ target=\new\>ISO 8601 date format</a>. /// </summary> private Properties.Duration_Core duration; public Properties.Duration_Core Duration { get { return duration; } set { duration = value; SetPropertyInstance(duration); } } /// <summary> /// Specifies the Person who edited the CreativeWork. /// </summary> private Editor_Core editor; public Editor_Core Editor { get { return editor; } set { editor = value; SetPropertyInstance(editor); } } /// <summary> /// The media objects that encode this creative work /// </summary> private Encodings_Core encodings; public Encodings_Core Encodings { get { return encodings; } set { encodings = value; SetPropertyInstance(encodings); } } /// <summary> /// Genre of the creative work /// </summary> private Genre_Core genre; public Genre_Core Genre { get { return genre; } set { genre = value; SetPropertyInstance(genre); } } /// <summary> /// Headline of the article /// </summary> private Headline_Core headline; public Headline_Core Headline { get { return headline; } set { headline = value; SetPropertyInstance(headline); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// The language of the content. please use one of the language codes from the <a href=\http://tools.ietf.org/html/bcp47\>IETF BCP 47 standard.</a> /// </summary> private InLanguage_Core inLanguage; public InLanguage_Core InLanguage { get { return inLanguage; } set { inLanguage = value; SetPropertyInstance(inLanguage); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// Indicates whether this content is family friendly. /// </summary> private IsFamilyFriendly_Core isFamilyFriendly; public IsFamilyFriendly_Core IsFamilyFriendly { get { return isFamilyFriendly; } set { isFamilyFriendly = value; SetPropertyInstance(isFamilyFriendly); } } /// <summary> /// The keywords/tags used to describe this content. /// </summary> private Keywords_Core keywords; public Keywords_Core Keywords { get { return keywords; } set { keywords = value; SetPropertyInstance(keywords); } } /// <summary> /// Indicates that the CreativeWork contains a reference to, but is not necessarily about a concept. /// </summary> private Mentions_Core mentions; public Mentions_Core Mentions { get { return mentions; } set { mentions = value; SetPropertyInstance(mentions); } } /// <summary> /// The composer of the movie or TV soundtrack. /// </summary> private MusicBy_Core musicBy; public MusicBy_Core MusicBy { get { return musicBy; } set { musicBy = value; SetPropertyInstance(musicBy); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// An offer to sell this item\u2014for example, an offer to sell a product, the DVD of a movie, or tickets to an event. /// </summary> private Offers_Core offers; public Offers_Core Offers { get { return offers; } set { offers = value; SetPropertyInstance(offers); } } /// <summary> /// The producer of the movie, TV series, season, or episode, or video. /// </summary> private Producer_Core producer; public Producer_Core Producer { get { return producer; } set { producer = value; SetPropertyInstance(producer); } } /// <summary> /// The production company or studio that made the movie, TV series, season, or episode, or video. /// </summary> private ProductionCompany_Core productionCompany; public ProductionCompany_Core ProductionCompany { get { return productionCompany; } set { productionCompany = value; SetPropertyInstance(productionCompany); } } /// <summary> /// Specifies the Person or Organization that distributed the CreativeWork. /// </summary> private Provider_Core provider; public Provider_Core Provider { get { return provider; } set { provider = value; SetPropertyInstance(provider); } } /// <summary> /// The publisher of the creative work. /// </summary> private Publisher_Core publisher; public Publisher_Core Publisher { get { return publisher; } set { publisher = value; SetPropertyInstance(publisher); } } /// <summary> /// Link to page describing the editorial principles of the organization primarily responsible for the creation of the CreativeWork. /// </summary> private PublishingPrinciples_Core publishingPrinciples; public PublishingPrinciples_Core PublishingPrinciples { get { return publishingPrinciples; } set { publishingPrinciples = value; SetPropertyInstance(publishingPrinciples); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The Organization on whose behalf the creator was working. /// </summary> private SourceOrganization_Core sourceOrganization; public SourceOrganization_Core SourceOrganization { get { return sourceOrganization; } set { sourceOrganization = value; SetPropertyInstance(sourceOrganization); } } /// <summary> /// A thumbnail image relevant to the Thing. /// </summary> private ThumbnailURL_Core thumbnailURL; public ThumbnailURL_Core ThumbnailURL { get { return thumbnailURL; } set { thumbnailURL = value; SetPropertyInstance(thumbnailURL); } } /// <summary> /// The trailer of the movie or TV series, season, or episode. /// </summary> private Trailer_Core trailer; public Trailer_Core Trailer { get { return trailer; } set { trailer = value; SetPropertyInstance(trailer); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } /// <summary> /// The version of the CreativeWork embodied by a specified resource. /// </summary> private Version_Core version; public Version_Core Version { get { return version; } set { version = value; SetPropertyInstance(version); } } /// <summary> /// An embedded video object. /// </summary> private Video_Core video; public Video_Core Video { get { return video; } set { video = value; SetPropertyInstance(video); } } } }
/* * 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 OpenSim.Data; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Framework.Communications.Services; using OpenSim.Framework.Communications.Cache; using OpenSim.Framework.Communications.Osp; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Communications.Hypergrid; using OpenSim.Region.Communications.Local; using OpenSim.Region.Communications.OGS1; namespace OpenSim.ApplicationPlugins.CreateCommsManager { public class CreateCommsManagerPlugin : IApplicationPlugin { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); #region IApplicationPlugin Members // TODO: required by IPlugin, but likely not at all right private string m_name = "CreateCommsManagerPlugin"; private string m_version = "0.0"; public string Version { get { return m_version; } } public string Name { get { return m_name; } } protected OpenSimBase m_openSim; protected BaseHttpServer m_httpServer; protected CommunicationsManager m_commsManager; protected GridInfoService m_gridInfoService; protected IRegionCreator m_regionCreator; public void Initialise() { m_log.Info("[LOADREGIONS]: " + Name + " cannot be default-initialized!"); throw new PluginNotInitialisedException(Name); } public void Initialise(OpenSimBase openSim) { m_openSim = openSim; m_httpServer = openSim.HttpServer; MainServer.Instance = m_httpServer; InitialiseCommsManager(openSim); if (m_commsManager != null) { m_openSim.ApplicationRegistry.RegisterInterface<IUserService>(m_commsManager.UserService); } } public void PostInitialise() { if (m_openSim.ApplicationRegistry.TryGet<IRegionCreator>(out m_regionCreator)) { m_regionCreator.OnNewRegionCreated += RegionCreated; } } public void Dispose() { } #endregion private void RegionCreated(IScene scene) { if (m_commsManager != null) { scene.RegisterModuleInterface<IUserService>(m_commsManager.UserService); } } protected void InitialiseCommsManager(OpenSimBase openSim) { LibraryRootFolder libraryRootFolder = new LibraryRootFolder(m_openSim.ConfigurationSettings.LibrariesXMLFile); bool hgrid = m_openSim.ConfigSource.Source.Configs["Startup"].GetBoolean("hypergrid", false); if (hgrid) { InitialiseHGServices(openSim, libraryRootFolder); } else { InitialiseStandardServices(libraryRootFolder); } openSim.CommunicationsManager = m_commsManager; } protected void InitialiseHGServices(OpenSimBase openSim, LibraryRootFolder libraryRootFolder) { // Standalone mode is determined by !startupConfig.GetBoolean("gridmode", false) if (m_openSim.ConfigurationSettings.Standalone) { InitialiseHGStandaloneServices(libraryRootFolder); } else { // We are in grid mode InitialiseHGGridServices(libraryRootFolder); } } protected void InitialiseStandardServices(LibraryRootFolder libraryRootFolder) { // Standalone mode is determined by !startupConfig.GetBoolean("gridmode", false) if (m_openSim.ConfigurationSettings.Standalone) { InitialiseStandaloneServices(libraryRootFolder); } else { // We are in grid mode InitialiseGridServices(libraryRootFolder); } } /// <summary> /// Initialises the backend services for standalone mode, and registers some http handlers /// </summary> /// <param name="libraryRootFolder"></param> protected virtual void InitialiseStandaloneServices(LibraryRootFolder libraryRootFolder) { m_commsManager = new CommunicationsLocal( m_openSim.ConfigurationSettings, m_openSim.NetServersInfo, libraryRootFolder); CreateGridInfoService(); } protected virtual void InitialiseGridServices(LibraryRootFolder libraryRootFolder) { m_commsManager = new CommunicationsOGS1(m_openSim.NetServersInfo, libraryRootFolder); m_httpServer.AddStreamHandler(new OpenSim.SimStatusHandler()); m_httpServer.AddStreamHandler(new OpenSim.XSimStatusHandler(m_openSim)); if (m_openSim.userStatsURI != String.Empty) m_httpServer.AddStreamHandler(new OpenSim.UXSimStatusHandler(m_openSim)); } protected virtual void InitialiseHGStandaloneServices(LibraryRootFolder libraryRootFolder) { m_commsManager = new HGCommunicationsStandalone( m_openSim.ConfigurationSettings, m_openSim.NetServersInfo, m_httpServer, libraryRootFolder, false); CreateGridInfoService(); } protected virtual void InitialiseHGGridServices(LibraryRootFolder libraryRootFolder) { m_commsManager = new HGCommunicationsGridMode( m_openSim.NetServersInfo, m_openSim.SceneManager, libraryRootFolder); m_httpServer.AddStreamHandler(new OpenSim.SimStatusHandler()); m_httpServer.AddStreamHandler(new OpenSim.XSimStatusHandler(m_openSim)); if (m_openSim.userStatsURI != String.Empty) m_httpServer.AddStreamHandler(new OpenSim.UXSimStatusHandler(m_openSim)); } private void CreateGridInfoService() { // provide grid info m_gridInfoService = new GridInfoService(m_openSim.ConfigSource.Source); m_httpServer.AddXmlRPCHandler("get_grid_info", m_gridInfoService.XmlRpcGridInfoMethod); m_httpServer.AddStreamHandler( new RestStreamHandler("GET", "/get_grid_info", m_gridInfoService.RestGetGridInfoMethod)); } } }
#if OS_WINDOWS using Microsoft.VisualStudio.Services.Agent.Util; using Microsoft.Win32; using System; using System.Collections; using System.ComponentModel; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security; using System.Security.AccessControl; using System.Security.Principal; using System.ServiceProcess; using System.Threading; namespace Microsoft.VisualStudio.Services.Agent.Listener.Configuration { [ServiceLocator(Default = typeof(NativeWindowsServiceHelper))] public interface INativeWindowsServiceHelper : IAgentService { string GetUniqueBuildGroupName(); bool LocalGroupExists(string groupName); void CreateLocalGroup(string groupName); void DeleteLocalGroup(string groupName); void AddMemberToLocalGroup(string accountName, string groupName); void GrantFullControlToGroup(string path, string groupName); void RemoveGroupFromFolderSecuritySetting(string folderPath, string groupName); bool IsUserHasLogonAsServicePrivilege(string domain, string userName); bool GrantUserLogonAsServicePrivilage(string domain, string userName); bool IsValidCredential(string domain, string userName, string logonPassword); NTAccount GetDefaultServiceAccount(); NTAccount GetDefaultAdminServiceAccount(); bool IsServiceExists(string serviceName); void InstallService(string serviceName, string serviceDisplayName, string logonAccount, string logonPassword); void UninstallService(string serviceName); void StartService(string serviceName); void StopService(string serviceName); void CreateVstsAgentRegistryKey(); void DeleteVstsAgentRegistryKey(); string GetSecurityId(string domainName, string userName); void SetAutoLogonPassword(string password); void ResetAutoLogonPassword(); bool IsRunningInElevatedMode(); void LoadUserProfile(string domain, string userName, string logonPassword, out IntPtr tokenHandle, out PROFILEINFO userProfile); void UnloadUserProfile(IntPtr tokenHandle, PROFILEINFO userProfile); bool IsValidAutoLogonCredential(string domain, string userName, string logonPassword); } public class NativeWindowsServiceHelper : AgentService, INativeWindowsServiceHelper { private const string AgentServiceLocalGroupPrefix = "VSTS_AgentService_G"; private ITerminal _term; public override void Initialize(IHostContext hostContext) { base.Initialize(hostContext); _term = hostContext.GetService<ITerminal>(); } public string GetUniqueBuildGroupName() { return AgentServiceLocalGroupPrefix + IOUtil.GetPathHash(HostContext.GetDirectory(WellKnownDirectory.Bin)).Substring(0, 5); } // TODO: Make sure to remove Old agent's group and registry changes made during auto upgrade to vsts-agent. public bool LocalGroupExists(string groupName) { Trace.Entering(); bool exists = false; IntPtr bufptr; int returnCode = NetLocalGroupGetInfo(null, // computer name groupName, 1, // group info with comment out bufptr); // Win32GroupAPI.LocalGroupInfo try { switch (returnCode) { case ReturnCode.S_OK: Trace.Info($"Local group '{groupName}' exist."); exists = true; break; case ReturnCode.NERR_GroupNotFound: case ReturnCode.ERROR_NO_SUCH_ALIAS: exists = false; break; case ReturnCode.ERROR_ACCESS_DENIED: // NOTE: None of the exception thrown here are userName facing. The caller logs this exception and prints a more understandable error throw new UnauthorizedAccessException(StringUtil.Loc("AccessDenied")); default: throw new Exception(StringUtil.Loc("OperationFailed", nameof(NetLocalGroupGetInfo), returnCode)); } } finally { // we don't need to actually read the info to determine whether it exists int bufferFreeError = NetApiBufferFree(bufptr); if (bufferFreeError != 0) { Trace.Error(StringUtil.Format("Buffer free error, could not free buffer allocated, error code: {0}", bufferFreeError)); } } return exists; } public void CreateLocalGroup(string groupName) { Trace.Entering(); LocalGroupInfo groupInfo = new LocalGroupInfo(); groupInfo.Name = groupName; groupInfo.Comment = StringUtil.Format("Built-in group used by Team Foundation Server."); int returnCode = NetLocalGroupAdd(null, // computer name 1, // 1 means include comment ref groupInfo, 0); // param error number // return on success if (returnCode == ReturnCode.S_OK) { Trace.Info($"Local Group '{groupName}' created"); return; } // Error Cases switch (returnCode) { case ReturnCode.NERR_GroupExists: case ReturnCode.ERROR_ALIAS_EXISTS: Trace.Info(StringUtil.Format("Group {0} already exists", groupName)); break; case ReturnCode.ERROR_ACCESS_DENIED: throw new UnauthorizedAccessException(StringUtil.Loc("AccessDenied")); case ReturnCode.ERROR_INVALID_PARAMETER: throw new ArgumentException(StringUtil.Loc("InvalidGroupName", groupName)); default: throw new Exception(StringUtil.Loc("OperationFailed", nameof(NetLocalGroupAdd), returnCode)); } } public void DeleteLocalGroup(string groupName) { Trace.Entering(); int returnCode = NetLocalGroupDel(null, // computer name groupName); // return on success if (returnCode == ReturnCode.S_OK) { Trace.Info($"Local Group '{groupName}' deleted"); return; } // Error Cases switch (returnCode) { case ReturnCode.NERR_GroupNotFound: case ReturnCode.ERROR_NO_SUCH_ALIAS: Trace.Info(StringUtil.Format("Group {0} not exists.", groupName)); break; case ReturnCode.ERROR_ACCESS_DENIED: throw new UnauthorizedAccessException(StringUtil.Loc("AccessDenied")); default: throw new Exception(StringUtil.Loc("OperationFailed", nameof(NetLocalGroupDel), returnCode)); } } public void AddMemberToLocalGroup(string accountName, string groupName) { Trace.Entering(); LocalGroupMemberInfo memberInfo = new LocalGroupMemberInfo(); memberInfo.FullName = accountName; int returnCode = NetLocalGroupAddMembers(null, // computer name groupName, 3, // group info with fullname (vs sid) ref memberInfo, 1); //total entries // return on success if (returnCode == ReturnCode.S_OK) { Trace.Info($"Account '{accountName}' is added to local group '{groupName}'."); return; } // Error Cases switch (returnCode) { case ReturnCode.ERROR_MEMBER_IN_ALIAS: Trace.Info(StringUtil.Format("Account {0} is already member of group {1}", accountName, groupName)); break; case ReturnCode.NERR_GroupNotFound: case ReturnCode.ERROR_NO_SUCH_ALIAS: throw new ArgumentException(StringUtil.Loc("GroupDoesNotExists", groupName)); case ReturnCode.ERROR_NO_SUCH_MEMBER: throw new ArgumentException(StringUtil.Loc("MemberDoesNotExists", accountName)); case ReturnCode.ERROR_INVALID_MEMBER: throw new ArgumentException(StringUtil.Loc("InvalidMember")); case ReturnCode.ERROR_ACCESS_DENIED: throw new UnauthorizedAccessException(StringUtil.Loc("AccessDenied")); default: throw new Exception(StringUtil.Loc("OperationFailed", nameof(NetLocalGroupAddMembers), returnCode)); } } public void GrantFullControlToGroup(string path, string groupName) { Trace.Entering(); if (IsGroupHasFullControl(path, groupName)) { Trace.Info($"Local group '{groupName}' already has full control to path '{path}'."); return; } DirectoryInfo dInfo = new DirectoryInfo(path); DirectorySecurity dSecurity = dInfo.GetAccessControl(); if (!dSecurity.AreAccessRulesCanonical) { Trace.Warning("Acls are not canonical, this may cause failure"); } dSecurity.AddAccessRule( new FileSystemAccessRule( groupName, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow)); dInfo.SetAccessControl(dSecurity); } private bool IsGroupHasFullControl(string path, string groupName) { DirectoryInfo dInfo = new DirectoryInfo(path); DirectorySecurity dSecurity = dInfo.GetAccessControl(); var allAccessRuls = dSecurity.GetAccessRules(true, true, typeof(SecurityIdentifier)).Cast<FileSystemAccessRule>(); SecurityIdentifier sid = (SecurityIdentifier)new NTAccount(groupName).Translate(typeof(SecurityIdentifier)); if (allAccessRuls.Any(x => x.IdentityReference.Value == sid.ToString() && x.AccessControlType == AccessControlType.Allow && x.FileSystemRights.HasFlag(FileSystemRights.FullControl) && x.InheritanceFlags == (InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit) && x.PropagationFlags == PropagationFlags.None)) { return true; } else { return false; } } public bool IsUserHasLogonAsServicePrivilege(string domain, string userName) { Trace.Entering(); ArgUtil.NotNullOrEmpty(userName, nameof(userName)); bool userHasPermission = false; using (LsaPolicy lsaPolicy = new LsaPolicy()) { IntPtr rightsPtr; uint count; uint result = LsaEnumerateAccountRights(lsaPolicy.Handle, GetSidBinaryFromWindows(domain, userName), out rightsPtr, out count); try { if (result == 0) { IntPtr incrementPtr = rightsPtr; for (int i = 0; i < count; i++) { LSA_UNICODE_STRING nativeRightString = Marshal.PtrToStructure<LSA_UNICODE_STRING>(incrementPtr); string rightString = Marshal.PtrToStringUni(nativeRightString.Buffer); Trace.Verbose($"Account {userName} has '{rightString}' right."); if (string.Equals(rightString, s_logonAsServiceName, StringComparison.OrdinalIgnoreCase)) { userHasPermission = true; } incrementPtr += Marshal.SizeOf(nativeRightString); } } else { Trace.Error($"Can't enumerate account rights, return code {result}."); } } finally { result = LsaFreeMemory(rightsPtr); if (result != 0) { Trace.Error(StringUtil.Format("Failed to free memory from LsaEnumerateAccountRights. Return code : {0} ", result)); } } } return userHasPermission; } public bool GrantUserLogonAsServicePrivilage(string domain, string userName) { Trace.Entering(); ArgUtil.NotNullOrEmpty(userName, nameof(userName)); using (LsaPolicy lsaPolicy = new LsaPolicy()) { // STATUS_SUCCESS == 0 uint result = LsaAddAccountRights(lsaPolicy.Handle, GetSidBinaryFromWindows(domain, userName), LogonAsServiceRights, 1); if (result == 0) { Trace.Info($"Successfully grant logon as service privilage to account '{userName}'"); return true; } else { Trace.Info($"Fail to grant logon as service privilage to account '{userName}', error code {result}."); return false; } } } public static bool IsWellKnownIdentity(String accountName) { NTAccount ntaccount = new NTAccount(accountName); SecurityIdentifier sid = (SecurityIdentifier)ntaccount.Translate(typeof(SecurityIdentifier)); SecurityIdentifier networkServiceSid = new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null); SecurityIdentifier localServiceSid = new SecurityIdentifier(WellKnownSidType.LocalServiceSid, null); SecurityIdentifier localSystemSid = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null); return sid.Equals(networkServiceSid) || sid.Equals(localServiceSid) || sid.Equals(localSystemSid); } public bool IsValidCredential(string domain, string userName, string logonPassword) { return IsValidCredentialInternal(domain, userName, logonPassword, LOGON32_LOGON_NETWORK); } public bool IsValidAutoLogonCredential(string domain, string userName, string logonPassword) { return IsValidCredentialInternal(domain, userName, logonPassword, LOGON32_LOGON_INTERACTIVE); } public NTAccount GetDefaultServiceAccount() { SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, domainSid: null); NTAccount account = sid.Translate(typeof(NTAccount)) as NTAccount; if (account == null) { throw new InvalidOperationException(StringUtil.Loc("NetworkServiceNotFound")); } return account; } public NTAccount GetDefaultAdminServiceAccount() { SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, domainSid: null); NTAccount account = sid.Translate(typeof(NTAccount)) as NTAccount; if (account == null) { throw new InvalidOperationException(StringUtil.Loc("LocalSystemAccountNotFound")); } return account; } public void RemoveGroupFromFolderSecuritySetting(string folderPath, string groupName) { DirectoryInfo dInfo = new DirectoryInfo(folderPath); if (dInfo.Exists) { DirectorySecurity dSecurity = dInfo.GetAccessControl(); var allAccessRuls = dSecurity.GetAccessRules(true, true, typeof(SecurityIdentifier)).Cast<FileSystemAccessRule>(); SecurityIdentifier sid = (SecurityIdentifier)new NTAccount(groupName).Translate(typeof(SecurityIdentifier)); foreach (FileSystemAccessRule ace in allAccessRuls) { if (String.Equals(sid.ToString(), ace.IdentityReference.Value, StringComparison.OrdinalIgnoreCase)) { dSecurity.RemoveAccessRuleSpecific(ace); } } dInfo.SetAccessControl(dSecurity); } } public bool IsServiceExists(string serviceName) { Trace.Entering(); ServiceController service = ServiceController.GetServices().FirstOrDefault(x => x.ServiceName.Equals(serviceName, StringComparison.OrdinalIgnoreCase)); return service != null; } public void InstallService(string serviceName, string serviceDisplayName, string logonAccount, string logonPassword) { Trace.Entering(); string agentServiceExecutable = "\"" + Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Bin), WindowsServiceControlManager.WindowsServiceControllerName) + "\""; IntPtr scmHndl = IntPtr.Zero; IntPtr svcHndl = IntPtr.Zero; IntPtr tmpBuf = IntPtr.Zero; IntPtr svcLock = IntPtr.Zero; try { //invoke the service with special argument, that tells it to register an event log trace source (need to run as an admin) using (var processInvoker = HostContext.CreateService<IProcessInvoker>()) { processInvoker.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message) { _term.WriteLine(message.Data); }; processInvoker.ErrorDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message) { _term.WriteLine(message.Data); }; processInvoker.ExecuteAsync(workingDirectory: string.Empty, fileName: agentServiceExecutable, arguments: "init", environment: null, requireExitCodeZero: true, cancellationToken: CancellationToken.None).GetAwaiter().GetResult(); } Trace.Verbose(StringUtil.Format("Trying to open SCManager.")); scmHndl = OpenSCManager(null, null, ServiceManagerRights.AllAccess); if (scmHndl.ToInt64() <= 0) { throw new Exception(StringUtil.Loc("FailedToOpenSCM")); } Trace.Verbose(StringUtil.Format("Opened SCManager. Trying to create service {0}", serviceName)); svcHndl = CreateService(scmHndl, serviceName, serviceDisplayName, ServiceRights.AllAccess, SERVICE_WIN32_OWN_PROCESS, ServiceBootFlag.AutoStart, ServiceError.Normal, agentServiceExecutable, null, IntPtr.Zero, null, logonAccount, logonPassword); if (svcHndl.ToInt64() <= 0) { throw new InvalidOperationException(StringUtil.Loc("OperationFailed", nameof(CreateService), GetLastError())); } _term.WriteLine(StringUtil.Loc("ServiceInstalled", serviceName)); //set recovery option to restart on failure. ArrayList failureActions = new ArrayList(); //first failure, we will restart the service right away. failureActions.Add(new FailureAction(RecoverAction.Restart, 0)); //second failure, we will restart the service after 1 min. failureActions.Add(new FailureAction(RecoverAction.Restart, 60000)); //subsequent failures, we will restart the service after 1 min failureActions.Add(new FailureAction(RecoverAction.Restart, 60000)); // Lock the Service Database svcLock = LockServiceDatabase(scmHndl); if (svcLock.ToInt64() <= 0) { throw new Exception(StringUtil.Loc("FailedToLockServiceDB")); } int[] actions = new int[failureActions.Count * 2]; int currInd = 0; foreach (FailureAction fa in failureActions) { actions[currInd] = (int)fa.Type; actions[++currInd] = fa.Delay; currInd++; } // Need to pack 8 bytes per struct tmpBuf = Marshal.AllocHGlobal(failureActions.Count * 8); // Move array into marshallable pointer Marshal.Copy(actions, 0, tmpBuf, failureActions.Count * 2); // Change service error actions // Set the SERVICE_FAILURE_ACTIONS struct SERVICE_FAILURE_ACTIONS sfa = new SERVICE_FAILURE_ACTIONS(); sfa.cActions = failureActions.Count; sfa.dwResetPeriod = SERVICE_NO_CHANGE; sfa.lpCommand = String.Empty; sfa.lpRebootMsg = String.Empty; sfa.lpsaActions = tmpBuf.ToInt64(); // Call the ChangeServiceFailureActions() abstraction of ChangeServiceConfig2() bool falureActionsResult = ChangeServiceFailureActions(svcHndl, SERVICE_CONFIG_FAILURE_ACTIONS, ref sfa); //Check the return if (!falureActionsResult) { int lastErrorCode = (int)GetLastError(); Exception win32exception = new Win32Exception(lastErrorCode); if (lastErrorCode == ReturnCode.ERROR_ACCESS_DENIED) { throw new SecurityException(StringUtil.Loc("AccessDeniedSettingRecoveryOption"), win32exception); } else { throw win32exception; } } else { _term.WriteLine(StringUtil.Loc("ServiceRecoveryOptionSet", serviceName)); } // Change service to delayed auto start SERVICE_DELAYED_AUTO_START_INFO sdasi = new SERVICE_DELAYED_AUTO_START_INFO(); sdasi.fDelayedAutostart = true; // Call the ChangeServiceDelayedAutoStart() abstraction of ChangeServiceConfig2() bool delayedStartResult = ChangeServiceDelayedAutoStart(svcHndl, SERVICE_CONFIG_DELAYED_AUTO_START_INFO, ref sdasi); //Check the return if (!delayedStartResult) { int lastErrorCode = (int)GetLastError(); Exception win32exception = new Win32Exception(lastErrorCode); if (lastErrorCode == ReturnCode.ERROR_ACCESS_DENIED) { throw new SecurityException(StringUtil.Loc("AccessDeniedSettingDelayedStartOption"), win32exception); } else { throw win32exception; } } else { _term.WriteLine(StringUtil.Loc("ServiceDelayedStartOptionSet", serviceName)); } _term.WriteLine(StringUtil.Loc("ServiceConfigured", serviceName)); } finally { if (scmHndl != IntPtr.Zero) { // Unlock the service database if (svcLock != IntPtr.Zero) { UnlockServiceDatabase(svcLock); svcLock = IntPtr.Zero; } // Close the service control manager handle CloseServiceHandle(scmHndl); scmHndl = IntPtr.Zero; } // Close the service handle if (svcHndl != IntPtr.Zero) { CloseServiceHandle(svcHndl); svcHndl = IntPtr.Zero; } // Free the memory if (tmpBuf != IntPtr.Zero) { Marshal.FreeHGlobal(tmpBuf); tmpBuf = IntPtr.Zero; } } } public void UninstallService(string serviceName) { Trace.Entering(); Trace.Verbose(StringUtil.Format("Trying to open SCManager.")); IntPtr scmHndl = OpenSCManager(null, null, ServiceManagerRights.Connect); if (scmHndl.ToInt64() <= 0) { throw new Exception(StringUtil.Loc("FailedToOpenSCManager")); } try { Trace.Verbose(StringUtil.Format("Opened SCManager. query installed service {0}", serviceName)); IntPtr serviceHndl = OpenService(scmHndl, serviceName, ServiceRights.StandardRightsRequired | ServiceRights.Stop | ServiceRights.QueryStatus); if (serviceHndl == IntPtr.Zero) { int lastError = Marshal.GetLastWin32Error(); throw new Win32Exception(lastError); } try { Trace.Info(StringUtil.Format("Trying to delete service {0}", serviceName)); int result = DeleteService(serviceHndl); if (result == 0) { result = Marshal.GetLastWin32Error(); throw new Win32Exception(result, StringUtil.Loc("CouldNotRemoveService", serviceName)); } Trace.Info("successfully removed the service"); } finally { CloseServiceHandle(serviceHndl); } } finally { CloseServiceHandle(scmHndl); } } public void StartService(string serviceName) { Trace.Entering(); try { ServiceController service = ServiceController.GetServices().FirstOrDefault(x => x.ServiceName.Equals(serviceName, StringComparison.OrdinalIgnoreCase)); if (service != null) { service.Start(); _term.WriteLine(StringUtil.Loc("ServiceStartedSuccessfully", serviceName)); } else { throw new InvalidOperationException(StringUtil.Loc("CanNotFindService", serviceName)); } } catch (Exception exception) { Trace.Error(exception); _term.WriteError(StringUtil.Loc("CanNotStartService")); // This is the last step in the configuration. Even if the start failed the status of the configuration should be error // If its configured through scripts its mandatory we indicate the failure where configuration failed to start the service throw; } } public void StopService(string serviceName) { Trace.Entering(); try { ServiceController service = ServiceController.GetServices().FirstOrDefault(x => x.ServiceName.Equals(serviceName, StringComparison.OrdinalIgnoreCase)); if (service != null) { if (service.Status == ServiceControllerStatus.Running) { Trace.Info("Trying to stop the service"); service.Stop(); try { _term.WriteLine(StringUtil.Loc("WaitForServiceToStop")); service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(35)); } catch (System.ServiceProcess.TimeoutException) { throw new InvalidOperationException(StringUtil.Loc("CanNotStopService", serviceName)); } } Trace.Info("Successfully stopped the service"); } else { Trace.Info(StringUtil.Loc("CanNotFindService", serviceName)); } } catch (Exception exception) { Trace.Error(exception); _term.WriteError(StringUtil.Loc("CanNotStopService", serviceName)); // Log the exception but do not report it as error. We can try uninstalling the service and then report it as error if something goes wrong. } } public void CreateVstsAgentRegistryKey() { RegistryKey tfsKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\TeamFoundationServer\15.0", true); if (tfsKey == null) { //We could be on a machine that doesn't have TFS installed on it, create the key tfsKey = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\TeamFoundationServer\15.0"); } if (tfsKey == null) { throw new ArgumentNullException("Unable to create regiestry key: 'HKLM\\SOFTWARE\\Microsoft\\TeamFoundationServer\\15.0'"); } try { using (RegistryKey vstsAgentsKey = tfsKey.CreateSubKey("VstsAgents")) { String hash = IOUtil.GetPathHash(HostContext.GetDirectory(WellKnownDirectory.Bin)); using (RegistryKey agentKey = vstsAgentsKey.CreateSubKey(hash)) { agentKey.SetValue("InstallPath", Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Bin), "Agent.Listener.exe")); } } } finally { tfsKey.Dispose(); } } public void DeleteVstsAgentRegistryKey() { RegistryKey tfsKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\TeamFoundationServer\15.0", true); if (tfsKey != null) { try { RegistryKey vstsAgentsKey = tfsKey.OpenSubKey("VstsAgents", true); if (vstsAgentsKey != null) { try { String hash = IOUtil.GetPathHash(HostContext.GetDirectory(WellKnownDirectory.Bin)); vstsAgentsKey.DeleteSubKeyTree(hash); } finally { vstsAgentsKey.Dispose(); } } } finally { tfsKey.Dispose(); } } } public string GetSecurityId(string domainName, string userName) { var account = new NTAccount(domainName, userName); var sid = account.Translate(typeof(SecurityIdentifier)); return sid != null ? sid.ToString() : null; } public void SetAutoLogonPassword(string password) { using (LsaPolicy lsaPolicy = new LsaPolicy(LSA_AccessPolicy.POLICY_CREATE_SECRET)) { lsaPolicy.SetSecretData(LsaPolicy.DefaultPassword, password); } } public void ResetAutoLogonPassword() { using (LsaPolicy lsaPolicy = new LsaPolicy(LSA_AccessPolicy.POLICY_CREATE_SECRET)) { lsaPolicy.SetSecretData(LsaPolicy.DefaultPassword, null); } } public bool IsRunningInElevatedMode() { return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator); } public void LoadUserProfile(string domain, string userName, string logonPassword, out IntPtr tokenHandle, out PROFILEINFO userProfile) { Trace.Entering(); tokenHandle = IntPtr.Zero; ArgUtil.NotNullOrEmpty(userName, nameof(userName)); if (LogonUser(userName, domain, logonPassword, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out tokenHandle) == 0) { throw new Win32Exception(Marshal.GetLastWin32Error()); } userProfile = new PROFILEINFO(); userProfile.dwSize = Marshal.SizeOf(typeof(PROFILEINFO)); userProfile.lpUserName = userName; if (!LoadUserProfile(tokenHandle, ref userProfile)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } Trace.Info($"Successfully loaded the profile for {domain}\\{userName}."); } public void UnloadUserProfile(IntPtr tokenHandle, PROFILEINFO userProfile) { Trace.Entering(); if (tokenHandle == IntPtr.Zero) { Trace.Verbose("The handle to unload user profile is not set. Returning."); } if (!UnloadUserProfile(tokenHandle, userProfile.hProfile)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } Trace.Info($"Successfully unloaded the profile for {userProfile.lpUserName}."); } private bool IsValidCredentialInternal(string domain, string userName, string logonPassword, UInt32 logonType) { Trace.Entering(); IntPtr tokenHandle = IntPtr.Zero; ArgUtil.NotNullOrEmpty(userName, nameof(userName)); Trace.Info($"Verify credential for account {userName}."); int result = LogonUser(userName, domain, logonPassword, logonType, LOGON32_PROVIDER_DEFAULT, out tokenHandle); if (tokenHandle.ToInt32() != 0) { if (!CloseHandle(tokenHandle)) { Trace.Error("Failed during CloseHandle on token from LogonUser"); } } if (result != 0) { Trace.Info($"Credential for account '{userName}' is valid."); return true; } else { Trace.Info($"Credential for account '{userName}' is invalid."); return false; } } private byte[] GetSidBinaryFromWindows(string domain, string user) { try { SecurityIdentifier sid = (SecurityIdentifier)new NTAccount(StringUtil.Format("{0}\\{1}", domain, user).TrimStart('\\')).Translate(typeof(SecurityIdentifier)); byte[] binaryForm = new byte[sid.BinaryLength]; sid.GetBinaryForm(binaryForm, 0); return binaryForm; } catch (Exception exception) { Trace.Error(exception); return null; } } // Helper class not to repeat whenever we deal with LSA* api internal class LsaPolicy : IDisposable { public IntPtr Handle { get; set; } public LsaPolicy() : this(LSA_AccessPolicy.POLICY_ALL_ACCESS) { } public LsaPolicy(LSA_AccessPolicy access) { LSA_UNICODE_STRING system = new LSA_UNICODE_STRING(); LSA_OBJECT_ATTRIBUTES attrib = new LSA_OBJECT_ATTRIBUTES() { Length = 0, RootDirectory = IntPtr.Zero, Attributes = 0, SecurityDescriptor = IntPtr.Zero, SecurityQualityOfService = IntPtr.Zero, }; IntPtr handle = IntPtr.Zero; uint hr = LsaOpenPolicy(ref system, ref attrib, (uint)access, out handle); if (hr != 0 || handle == IntPtr.Zero) { throw new Exception(StringUtil.Loc("OperationFailed", nameof(LsaOpenPolicy), hr)); } Handle = handle; } public void SetSecretData(string key, string value) { LSA_UNICODE_STRING secretData = new LSA_UNICODE_STRING(); LSA_UNICODE_STRING secretName = new LSA_UNICODE_STRING(); secretName.Buffer = Marshal.StringToHGlobalUni(key); var charSize = sizeof(char); secretName.Length = (UInt16)(key.Length * charSize); secretName.MaximumLength = (UInt16)((key.Length + 1) * charSize); if (value != null && value.Length > 0) { // Create data and key secretData.Buffer = Marshal.StringToHGlobalUni(value); secretData.Length = (UInt16)(value.Length * charSize); secretData.MaximumLength = (UInt16)((value.Length + 1) * charSize); } else { // Delete data and key secretData.Buffer = IntPtr.Zero; secretData.Length = 0; secretData.MaximumLength = 0; } uint result = LsaStorePrivateData(Handle, ref secretName, ref secretData); uint winErrorCode = LsaNtStatusToWinError(result); if (winErrorCode != 0) { throw new Exception(StringUtil.Loc("OperationFailed", nameof(LsaNtStatusToWinError), winErrorCode)); } } void IDisposable.Dispose() { // We will ignore LsaClose error LsaClose(Handle); GC.SuppressFinalize(this); } internal static string DefaultPassword = "DefaultPassword"; } internal enum LSA_AccessPolicy : long { POLICY_VIEW_LOCAL_INFORMATION = 0x00000001L, POLICY_VIEW_AUDIT_INFORMATION = 0x00000002L, POLICY_GET_PRIVATE_INFORMATION = 0x00000004L, POLICY_TRUST_ADMIN = 0x00000008L, POLICY_CREATE_ACCOUNT = 0x00000010L, POLICY_CREATE_SECRET = 0x00000020L, POLICY_CREATE_PRIVILEGE = 0x00000040L, POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080L, POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100L, POLICY_AUDIT_LOG_ADMIN = 0x00000200L, POLICY_SERVER_ADMIN = 0x00000400L, POLICY_LOOKUP_NAMES = 0x00000800L, POLICY_NOTIFICATION = 0x00001000L, POLICY_ALL_ACCESS = 0x00001FFFL } [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] public static extern uint LsaStorePrivateData( IntPtr policyHandle, ref LSA_UNICODE_STRING KeyName, ref LSA_UNICODE_STRING PrivateData ); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] public static extern uint LsaNtStatusToWinError( uint status ); private static UInt32 LOGON32_LOGON_INTERACTIVE = 2; private const UInt32 LOGON32_LOGON_NETWORK = 3; // Declaration of external pinvoke functions private static readonly string s_logonAsServiceName = "SeServiceLogonRight"; private const UInt32 LOGON32_PROVIDER_DEFAULT = 0; private const int SERVICE_WIN32_OWN_PROCESS = 0x00000010; private const int SERVICE_NO_CHANGE = -1; private const int SERVICE_CONFIG_FAILURE_ACTIONS = 0x2; private const int SERVICE_CONFIG_DELAYED_AUTO_START_INFO = 0x3; // TODO Fix this. This is not yet available in coreclr (newer version?) private const int UnicodeCharSize = 2; private static LSA_UNICODE_STRING[] LogonAsServiceRights { get { return new[] { new LSA_UNICODE_STRING() { Buffer = Marshal.StringToHGlobalUni(s_logonAsServiceName), Length = (UInt16)(s_logonAsServiceName.Length * UnicodeCharSize), MaximumLength = (UInt16) ((s_logonAsServiceName.Length + 1) * UnicodeCharSize) } }; } } public struct ReturnCode { public const int S_OK = 0; public const int ERROR_ACCESS_DENIED = 5; public const int ERROR_INVALID_PARAMETER = 87; public const int ERROR_MEMBER_NOT_IN_ALIAS = 1377; // member not in a group public const int ERROR_MEMBER_IN_ALIAS = 1378; // member already exists public const int ERROR_ALIAS_EXISTS = 1379; // group already exists public const int ERROR_NO_SUCH_ALIAS = 1376; public const int ERROR_NO_SUCH_MEMBER = 1387; public const int ERROR_INVALID_MEMBER = 1388; public const int NERR_GroupNotFound = 2220; public const int NERR_GroupExists = 2223; public const int NERR_UserInGroup = 2236; public const uint STATUS_ACCESS_DENIED = 0XC0000022; //NTSTATUS error code: Access Denied } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct LocalGroupInfo { [MarshalAs(UnmanagedType.LPWStr)] public string Name; [MarshalAs(UnmanagedType.LPWStr)] public string Comment; } [StructLayout(LayoutKind.Sequential)] public struct LSA_UNICODE_STRING { public UInt16 Length; public UInt16 MaximumLength; // We need to use an IntPtr because if we wrap the Buffer with a SafeHandle-derived class, we get a failure during LsaAddAccountRights public IntPtr Buffer; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct LocalGroupMemberInfo { [MarshalAs(UnmanagedType.LPWStr)] public string FullName; } [StructLayout(LayoutKind.Sequential)] public struct LSA_OBJECT_ATTRIBUTES { public UInt32 Length; public IntPtr RootDirectory; public LSA_UNICODE_STRING ObjectName; public UInt32 Attributes; public IntPtr SecurityDescriptor; public IntPtr SecurityQualityOfService; } [StructLayout(LayoutKind.Sequential)] public struct SERVICE_FAILURE_ACTIONS { public int dwResetPeriod; public string lpRebootMsg; public string lpCommand; public int cActions; public long lpsaActions; } [StructLayout(LayoutKind.Sequential)] public struct SERVICE_DELAYED_AUTO_START_INFO { public bool fDelayedAutostart; } // Class to represent a failure action which consists of a recovery // action type and an action delay private class FailureAction { // Property to set recover action type public RecoverAction Type { get; set; } // Property to set recover action delay public int Delay { get; set; } // Constructor public FailureAction(RecoverAction actionType, int actionDelay) { Type = actionType; Delay = actionDelay; } } [Flags] public enum ServiceManagerRights { Connect = 0x0001, CreateService = 0x0002, EnumerateService = 0x0004, Lock = 0x0008, QueryLockStatus = 0x0010, ModifyBootConfig = 0x0020, StandardRightsRequired = 0xF0000, AllAccess = (StandardRightsRequired | Connect | CreateService | EnumerateService | Lock | QueryLockStatus | ModifyBootConfig) } [Flags] public enum ServiceRights { QueryConfig = 0x1, ChangeConfig = 0x2, QueryStatus = 0x4, EnumerateDependants = 0x8, Start = 0x10, Stop = 0x20, PauseContinue = 0x40, Interrogate = 0x80, UserDefinedControl = 0x100, Delete = 0x00010000, StandardRightsRequired = 0xF0000, AllAccess = (StandardRightsRequired | QueryConfig | ChangeConfig | QueryStatus | EnumerateDependants | Start | Stop | PauseContinue | Interrogate | UserDefinedControl) } public enum ServiceError { Ignore = 0x00000000, Normal = 0x00000001, Severe = 0x00000002, Critical = 0x00000003 } public enum ServiceBootFlag { Start = 0x00000000, SystemStart = 0x00000001, AutoStart = 0x00000002, DemandStart = 0x00000003, Disabled = 0x00000004 } // Enum for recovery actions (correspond to the Win32 equivalents ) private enum RecoverAction { None = 0, Restart = 1, Reboot = 2, RunCommand = 3 } [DllImport("Netapi32.dll")] private extern static int NetLocalGroupGetInfo(string servername, string groupname, int level, out IntPtr bufptr); [DllImport("Netapi32.dll")] private extern static int NetApiBufferFree(IntPtr Buffer); [DllImport("Netapi32.dll")] private extern static int NetLocalGroupAdd([MarshalAs(UnmanagedType.LPWStr)] string servername, int level, ref LocalGroupInfo buf, int parm_err); [DllImport("Netapi32.dll")] private extern static int NetLocalGroupAddMembers([MarshalAs(UnmanagedType.LPWStr)] string serverName, [MarshalAs(UnmanagedType.LPWStr)] string groupName, int level, ref LocalGroupMemberInfo buf, int totalEntries); [DllImport("Netapi32.dll")] public extern static int NetLocalGroupDel([MarshalAs(UnmanagedType.LPWStr)] string servername, [MarshalAs(UnmanagedType.LPWStr)] string groupname); [DllImport("advapi32.dll")] private static extern Int32 LsaClose(IntPtr ObjectHandle); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] private static extern uint LsaOpenPolicy( ref LSA_UNICODE_STRING SystemName, ref LSA_OBJECT_ATTRIBUTES ObjectAttributes, uint DesiredAccess, out IntPtr PolicyHandle); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] private static extern uint LsaAddAccountRights( IntPtr PolicyHandle, byte[] AccountSid, LSA_UNICODE_STRING[] UserRights, uint CountOfRights); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] public static extern uint LsaEnumerateAccountRights( IntPtr PolicyHandle, byte[] AccountSid, out IntPtr UserRights, out uint CountOfRights); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] public static extern uint LsaFreeMemory(IntPtr pBuffer); [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern int LogonUser(string userName, string domain, string password, uint logonType, uint logonProvider, out IntPtr tokenHandle); [DllImport("userenv.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern Boolean LoadUserProfile(IntPtr hToken, ref PROFILEINFO lpProfileInfo); [DllImport("userenv.dll", SetLastError = true, CharSet = CharSet.Unicode)] public static extern Boolean UnloadUserProfile(IntPtr hToken, IntPtr hProfile); [DllImport("kernel32", SetLastError = true)] public static extern bool CloseHandle(IntPtr handle); [DllImport("advapi32.dll", EntryPoint = "CreateServiceA")] private static extern IntPtr CreateService( IntPtr hSCManager, string lpServiceName, string lpDisplayName, ServiceRights dwDesiredAccess, int dwServiceType, ServiceBootFlag dwStartType, ServiceError dwErrorControl, string lpBinaryPathName, string lpLoadOrderGroup, IntPtr lpdwTagId, string lpDependencies, string lp, string lpPassword); [DllImport("advapi32.dll")] public static extern IntPtr OpenSCManager(string lpMachineName, string lpDatabaseName, ServiceManagerRights dwDesiredAccess); [DllImport("advapi32.dll", SetLastError = true)] public static extern IntPtr OpenService(IntPtr hSCManager, string lpServiceName, ServiceRights dwDesiredAccess); [DllImport("advapi32.dll", SetLastError = true)] public static extern int DeleteService(IntPtr hService); [DllImport("advapi32.dll")] public static extern int CloseServiceHandle(IntPtr hSCObject); [DllImport("advapi32.dll")] public static extern IntPtr LockServiceDatabase(IntPtr hSCManager); [DllImport("advapi32.dll")] public static extern bool UnlockServiceDatabase(IntPtr hSCManager); [DllImport("advapi32.dll", EntryPoint = "ChangeServiceConfig2")] public static extern bool ChangeServiceFailureActions(IntPtr hService, int dwInfoLevel, ref SERVICE_FAILURE_ACTIONS lpInfo); [DllImport("advapi32.dll", EntryPoint = "ChangeServiceConfig2")] public static extern bool ChangeServiceDelayedAutoStart(IntPtr hService, int dwInfoLevel, ref SERVICE_DELAYED_AUTO_START_INFO lpInfo); [DllImport("kernel32.dll")] static extern uint GetLastError(); } [StructLayout(LayoutKind.Sequential)] public struct PROFILEINFO { public int dwSize; public int dwFlags; [MarshalAs(UnmanagedType.LPTStr)] public String lpUserName; [MarshalAs(UnmanagedType.LPTStr)] public String lpProfilePath; [MarshalAs(UnmanagedType.LPTStr)] public String lpDefaultPath; [MarshalAs(UnmanagedType.LPTStr)] public String lpServerName; [MarshalAs(UnmanagedType.LPTStr)] public String lpPolicyPath; public IntPtr hProfile; } } #endif
/* * RegionNameTable.cs - Implementation of the * "I18N.Common.RegionNameTable" class. * * Copyright (C) 2002 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace I18N.Common { using System; using System.Globalization; internal sealed class RegionNameTable { // Array of all registered region names. private static RegionName[] regions; private static int numRegions; // Useful constants. private const int DefaultTableSize = 64; private const int TableExtendSize = 16; // Add an item to the region name table. public static void Add(RegionName name) { if(numRegions < regions.Length) { regions[numRegions++] = name; } else { RegionName[] newRegions; newRegions = new RegionName [numRegions + TableExtendSize]; Array.Copy(regions, newRegions, regions.Length); regions = newRegions; regions[numRegions++] = name; } } // Populate the region name table. Note: just because // a region exists in this table doesn't mean that it is // actually supported by the rest of the system. public static void PopulateNameTable() { Add(new RegionName (0x0401, "SA", "SAU", "SAU", true, "\u0631.\u0633.\u200F", "SAR", 2)); Add(new RegionName (0x0402, "BG", "BGR", "BGR", true, "\u043B\u0432", "BGL", 2)); Add(new RegionName (0x0403, "ES", "ESP", "ESP", true, "\u20AC", "EUR", 2)); Add(new RegionName (0x0404, "TW", "TWN", "TWN", true, "NT$", "TWD", 2)); Add(new RegionName (0x0405, "CZ", "CZE", "CZE", true, "K\u010D", "CZK", 2)); Add(new RegionName (0x0406, "DK", "DNK", "DNK", true, "kr", "DKK", 2)); Add(new RegionName (0x0407, "DE", "DEU", "DEU", true, "\u20AC", "EUR", 2)); Add(new RegionName (0x0408, "GR", "GRC", "GRC", true, "\u20AC", "EUR", 2)); Add(new RegionName (0x0409, "US", "USA", "USA", false, "$", "USD", 2)); Add(new RegionName (0x040A, "ES", "ESP", "ESP", true, "\u20AC", "EUR", 2)); Add(new RegionName (0x040B, "FI", "FIN", "FIN", true, "\u20AC", "EUR", 2)); Add(new RegionName (0x040C, "FR", "FRA", "FRA", true, "\u20AC", "EUR", 2)); Add(new RegionName (0x040D, "IL", "ISR", "ISR", true, "\u20AA", "ILS", 2)); Add(new RegionName (0x040E, "HU", "HUN", "HUN", true, "Ft", "HUF", 2)); Add(new RegionName (0x040F, "IS", "ISL", "ISL", true, "kr.", "ISK", 2)); Add(new RegionName (0x0410, "IT", "ITA", "ITA", true, "\u20AC", "EUR", 2)); Add(new RegionName (0x0411, "JP", "JPN", "JPN", true, "\u00A5", "JPY", 0)); Add(new RegionName (0x0412, "KR", "KOR", "KOR", true, "\u20A9", "KRW", 0)); Add(new RegionName (0x0413, "NL", "NLD", "NLD", true, "\u20AC", "EUR", 2)); Add(new RegionName (0x0414, "NO", "NOR", "NOR", true, "kr", "NOK", 2)); Add(new RegionName (0x0415, "PL", "POL", "POL", true, "z\u0142", "PLN", 2)); Add(new RegionName (0x0416, "BR", "BRA", "BRA", true, "R$ ", "BRL", 2)); Add(new RegionName (0x0418, "RO", "ROM", "ROM", true, "lei", "ROL", 2)); Add(new RegionName (0x0419, "RU", "RUS", "RUS", true, "\u0440.", "RUR", 2)); Add(new RegionName (0x041A, "HR", "HRV", "HRV", true, "kn", "HRK", 2)); Add(new RegionName (0x041B, "SK", "SVK", "SVK", true, "Sk", "SKK", 2)); Add(new RegionName (0x041C, "AL", "ALB", "ALB", true, "Lek", "ALL", 2)); Add(new RegionName (0x041D, "SE", "SWE", "SWE", true, "kr", "SEK", 2)); Add(new RegionName (0x041E, "TH", "THA", "THA", true, "\u0E3F", "THB", 2)); Add(new RegionName (0x041F, "TR", "TUR", "TUR", true, "TL", "TRL", 0)); Add(new RegionName (0x0420, "PK", "PAK", "PAK", true, "Rs", "PKR", 2)); Add(new RegionName (0x0421, "ID", "IDN", "IDN", true, "Rp", "IDR", 2)); Add(new RegionName (0x0422, "UA", "UKR", "UKR", true, "\u0433\u0440\u043D.", "UAH", 2)); Add(new RegionName (0x0423, "BY", "BLR", "BLR", true, "\u0440.", "BYB", 2)); Add(new RegionName (0x0424, "SI", "SVN", "SVN", true, "SIT", "SIT", 2)); Add(new RegionName (0x0425, "EE", "EST", "EST", true, "kr", "EEK", 2)); Add(new RegionName (0x0426, "LV", "LVA", "LVA", true, "Ls", "LVL", 2)); Add(new RegionName (0x0427, "LT", "LTU", "LTU", true, "Lt", "LTL", 2)); Add(new RegionName (0x0429, "IR", "IRN", "IRN", true, "\u0631\u064A\u0627\u0644", "IRR", 2)); Add(new RegionName (0x042A, "VN", "VNM", "VNM", true, "\u20AB", "VND", 2)); Add(new RegionName (0x042B, "AM", "ARM", "ARM", true, "\u0564\u0580.", "AMD", 2)); Add(new RegionName (0x042C, "AZ", "AZE", "AZE", true, "man.", "AZM", 2)); Add(new RegionName (0x042D, "ES", "ESP", "ESP", true, "\u20AC", "EUR", 2)); Add(new RegionName (0x042F, "MK", "MKD", "MKD", true, "\u0434\u0435\u043D.", "MKD", 2)); Add(new RegionName (0x0436, "ZA", "ZAF", "ZAF", true, "R", "ZAR", 2)); Add(new RegionName (0x0437, "GE", "GEO", "GEO", true, "Lari", "GEL", 2)); Add(new RegionName (0x0438, "FO", "FRO", "FRO", true, "kr", "DKK", 2)); Add(new RegionName (0x0439, "IN", "IND", "IND", true, "\u0930\u0941", "INR", 2)); Add(new RegionName (0x043E, "MY", "MYS", "MYS", true, "R", "MYR", 2)); Add(new RegionName (0x043F, "KZ", "KAZ", "KAZ", true, "\u0422", "KZT", 2)); Add(new RegionName (0x0440, "KG", "KGZ", "KGZ", true, "\u0441\u043E\u043C", "KGS", 2)); Add(new RegionName (0x0441, "KE", "KEN", "KEN", false, "S", "KES", 2)); Add(new RegionName (0x0443, "UZ", "UZB", "UZB", true, "su'm", "UZS", 2)); Add(new RegionName (0x0444, "TA", "TAT", "TAT", true, "\u0440.", "RUR", 2)); Add(new RegionName (0x0446, "IN", "IND", "IND", true, "\u0930\u0941", "INR", 2)); Add(new RegionName (0x0447, "IN", "IND", "IND", true, "\u0930\u0941", "INR", 2)); Add(new RegionName (0x0449, "IN", "IND", "IND", true, "\u0930\u0941", "INR", 2)); Add(new RegionName (0x044A, "IN", "IND", "IND", true, "\u0930\u0941", "INR", 2)); Add(new RegionName (0x044B, "IN", "IND", "IND", true, "\u0930\u0941", "INR", 2)); Add(new RegionName (0x044E, "IN", "IND", "IND", true, "\u0930\u0941", "INR", 2)); Add(new RegionName (0x044F, "IN", "IND", "IND", true, "\u0930\u0941", "INR", 2)); Add(new RegionName (0x0450, "MN", "MNG", "MNG", true, "\u20AE", "MNT", 2)); Add(new RegionName (0x0456, "ES", "ESP", "ESP", true, "\u20AC", "EUR", 2)); Add(new RegionName (0x0457, "IN", "IND", "IND", true, "\u0930\u0941", "INR", 2)); Add(new RegionName (0x045A, "SY", "SYR", "SYR", true, "\u0644.\u0633.\u200F", "SYP", 2)); Add(new RegionName (0x0465, "MV", "MDV", "MDV", true, "\u0783.", "MVR", 2)); Add(new RegionName (0x0801, "IQ", "IRQ", "IRQ", true, "\u062F.\u0639.\u200F", "IQD", 3)); Add(new RegionName (0x0804, "CN", "CHN", "CHN", true, "\uFFE5", "CNY", 2)); Add(new RegionName (0x0807, "CH", "CHE", "CHE", true, "SFr.", "CHF", 2)); Add(new RegionName (0x0809, "GB", "GBR", "GBR", true, "\u00A3", "GBP", 2)); Add(new RegionName (0x080A, "MX", "MEX", "MEX", true, "$", "MXN", 2)); Add(new RegionName (0x080C, "BE", "BEL", "BEL", true, "\u20AC", "EUR", 2)); Add(new RegionName (0x0810, "CH", "CHE", "CHE", true, "SFr.", "CHF", 2)); Add(new RegionName (0x0813, "BE", "BEL", "BEL", true, "\u20AC", "EUR", 2)); Add(new RegionName (0x0814, "NO", "NOR", "NOR", true, "kr", "NOK", 2)); Add(new RegionName (0x0816, "PT", "PRT", "PRT", true, "\u20AC", "EUR", 2)); Add(new RegionName (0x081A, "SP", "SPB", "SPB", true, "Din.", "YUN", 2)); Add(new RegionName (0x081D, "FI", "FIN", "FIN", true, "\u20AC", "EUR", 2)); Add(new RegionName (0x082C, "AZ", "AZE", "AZE", true, "man.", "AZM", 2)); Add(new RegionName (0x083E, "BN", "BRN", "BRN", true, "$", "BND", 2)); Add(new RegionName (0x0843, "UZ", "UZB", "UZB", true, "su'm", "UZS", 2)); Add(new RegionName (0x0C01, "EG", "EGY", "EGY", true, "\u062C.\u0645.\u200F", "EGP", 2)); Add(new RegionName (0x0C04, "HK", "HKG", "HKG", true, "HK$", "HKD", 2)); Add(new RegionName (0x0C07, "AT", "AUT", "AUT", true, "\u20AC", "EUR", 2)); Add(new RegionName (0x0C09, "AU", "AUS", "AUS", true, "$", "AUD", 2)); Add(new RegionName (0x0C0A, "ES", "ESP", "ESP", true, "\u20AC", "EUR", 2)); Add(new RegionName (0x0C0C, "CA", "CAN", "CAN", true, "$", "CAD", 2)); Add(new RegionName (0x0C1A, "SP", "SPB", "SPB", true, "Din.", "YUN", 2)); Add(new RegionName (0x1001, "LY", "LBY", "LBY", true, "\u062F.\u0644.\u200F", "LYD", 3)); Add(new RegionName (0x1004, "SG", "SGP", "SGP", false, "$", "SGD", 2)); Add(new RegionName (0x1007, "LU", "LUX", "LUX", true, "\u20AC", "EUR", 2)); Add(new RegionName (0x1009, "CA", "CAN", "CAN", true, "$", "CAD", 2)); Add(new RegionName (0x100A, "GT", "GTM", "GTM", true, "Q", "GTQ", 2)); Add(new RegionName (0x100C, "CH", "CHE", "CHE", true, "SFr.", "CHF", 2)); Add(new RegionName (0x1401, "DZ", "DZA", "DZA", true, "\u062F.\u062C.\u200F", "DZD", 2)); Add(new RegionName (0x1404, "MO", "MAC", "MCO", true, "P", "MOP", 2)); Add(new RegionName (0x1407, "LI", "LIE", "LIE", true, "CHF", "CHF", 2)); Add(new RegionName (0x1409, "NZ", "NZL", "NZL", true, "$", "NZD", 2)); Add(new RegionName (0x140A, "CR", "CRI", "CRI", true, "\u20A1", "CRC", 2)); Add(new RegionName (0x140C, "LU", "LUX", "LUX", true, "\u20AC", "EUR", 2)); Add(new RegionName (0x1801, "MA", "MAR", "MAR", true, "\u062F.\u0645.\u200F", "MAD", 2)); Add(new RegionName (0x1809, "IE", "IRL", "IRL", true, "\u20AC", "EUR", 2)); Add(new RegionName (0x180A, "PA", "PAN", "PAN", true, "B/.", "PAB", 2)); Add(new RegionName (0x180C, "MC", "MCO", "MCO", true, "\u20AC", "EUR", 2)); Add(new RegionName (0x1C01, "TN", "TUN", "TUN", true, "\u062F.\u062A.\u200F", "TND", 3)); Add(new RegionName (0x1C09, "ZA", "ZAF", "ZAF", true, "R", "ZAR", 2)); Add(new RegionName (0x1C0A, "DO", "DOM", "DOM", true, "RD$", "DOP", 2)); Add(new RegionName (0x2001, "OM", "OMN", "OMN", true, "\u0631.\u0639.\u200F", "OMR", 3)); Add(new RegionName (0x2009, "JM", "JAM", "JAM", false, "J$", "JMD", 2)); Add(new RegionName (0x200A, "VE", "VEN", "VEN", true, "Bs", "VEB", 2)); Add(new RegionName (0x2401, "YE", "YEM", "YEM", true, "\u0631.\u064A.\u200F", "YER", 2)); Add(new RegionName (0x2409, "CB", "CAR", "CAR", false, "$", "USD", 2)); Add(new RegionName (0x240A, "CO", "COL", "COL", true, "$", "COP", 2)); Add(new RegionName (0x2801, "SY", "SYR", "SYR", true, "\u0644.\u0633.\u200F", "SYP", 2)); Add(new RegionName (0x2809, "BZ", "BLZ", "BLZ", true, "BZ$", "BZD", 2)); Add(new RegionName (0x280A, "PE", "PER", "PER", true, "S/.", "PEN", 2)); Add(new RegionName (0x2C01, "JO", "JOR", "JOR", true, "\u062F.\u0627.\u200F", "JOD", 3)); Add(new RegionName (0x2C09, "TT", "TTO", "TTO", true, "TT$", "TTD", 0)); Add(new RegionName (0x2C0A, "AR", "ARG", "ARG", true, "$", "ARS", 2)); Add(new RegionName (0x3001, "LB", "LBN", "LBN", true, "\u0644.\u0644.\u200F", "LBP", 2)); Add(new RegionName (0x3009, "ZW", "ZWE", "ZWE", false, "Z$", "ZWD", 2)); Add(new RegionName (0x300A, "EC", "ECU", "ECU", true, "$", "USD", 2)); Add(new RegionName (0x3401, "KW", "KWT", "KWT", true, "\u062F.\u0643.\u200F", "KWD", 3)); Add(new RegionName (0x3409, "PH", "PHL", "PHL", false, "Php", "PHP", 2)); Add(new RegionName (0x340A, "CL", "CHL", "CHL", true, "$", "CLP", 0)); Add(new RegionName (0x3801, "AE", "ARE", "ARE", true, "\u062F.\u0625.\u200F", "AED", 2)); Add(new RegionName (0x380A, "UY", "URY", "URY", true, "$U", "UYU", 2)); Add(new RegionName (0x3C01, "BH", "BHR", "BHR", true, "\u062F.\u0628.\u200F", "BHD", 3)); Add(new RegionName (0x3C0A, "PY", "PRY", "PRY", true, "Gs", "PYG", 0)); Add(new RegionName (0x4001, "QA", "QAT", "QAT", true, "\u0631.\u0642.\u200F", "QAR", 2)); Add(new RegionName (0x400A, "BO", "BOL", "BOL", true, "$b", "BOB", 2)); Add(new RegionName (0x440A, "SV", "SLV", "SLV", true, "$", "USD", 2)); Add(new RegionName (0x480A, "HN", "HND", "HND", true, "L.", "HNL", 2)); Add(new RegionName (0x4C0A, "NI", "NIC", "NIC", true, "C$", "NIO", 2)); Add(new RegionName (0x500A, "PR", "PRI", "PRI", true, "$", "USD", 2)); } // Create the region name table. public static void CreateNameTable() { lock(typeof(RegionNameTable)) { // Return immediately if the name table already exists. if(regions != null) { return; } // Create a new region name table. regions = new RegionName [DefaultTableSize]; numRegions = 0; // Populate the region name table. PopulateNameTable(); } } // Get the name information for a specific region, by name. public static RegionName GetNameInfoByName(String name) { // Create the region name table. CreateNameTable(); // Search for the name in the table. int posn = numRegions - 1; while(posn >= 0) { if(regions[posn].twoLetterISOName == name) { return regions[posn]; } --posn; } // Could not find the region. return null; } // Get the name information for a specific region, by identifier. public static RegionName GetNameInfoByID(int regionID) { // Create the region name table. CreateNameTable(); // Search for the name in the table. int posn = numRegions - 1; while(posn >= 0) { if(regions[posn].regionID == regionID) { return regions[posn]; } --posn; } // Could not find the region. return null; } // Add currency information to a NumberFormatInfo object. public static void AddCurrencyInfo (NumberFormatInfo nfi, RootCulture culture) { String country = culture.Country; if(country != null) { RegionName region = GetNameInfoByName(country); if(region != null) { nfi.CurrencySymbol = region.currencySymbol; nfi.CurrencyDecimalDigits = region.currencyDigits; } } } }; // class RegionNameTable }; // namespace I18N.Common
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.ComponentModel.Composition.Hosting; using System.IO; using System.Linq; using System.Text; using System.Threading; using EnvDTE; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Storage; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Extensions; using Microsoft.VisualStudio.LanguageServices.Utilities; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; using Roslyn.VisualStudio.ProjectSystem; using VSLangProj; using VSLangProj140; using OLEServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; using OleInterop = Microsoft.VisualStudio.OLE.Interop; using Microsoft.CodeAnalysis.Esent; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { /// <summary> /// The Workspace for running inside Visual Studio. /// </summary> internal abstract partial class VisualStudioWorkspaceImpl : VisualStudioWorkspace { private static readonly IntPtr s_docDataExisting_Unknown = new IntPtr(-1); private const string AppCodeFolderName = "App_Code"; // document worker coordinator private ISolutionCrawlerRegistrationService _registrationService; /// <summary> /// A <see cref="ForegroundThreadAffinitizedObject"/> to make assertions that stuff is on the right thread. /// This is Lazy because it might be created on a background thread when nothing is initialized yet. /// </summary> private readonly Lazy<ForegroundThreadAffinitizedObject> _foregroundObject = new Lazy<ForegroundThreadAffinitizedObject>(() => new ForegroundThreadAffinitizedObject()); /// <summary> /// The <see cref="DeferredInitializationState"/> that consists of the <see cref="VisualStudioProjectTracker" /> /// and other UI-initialized types. It will be created as long as a single project has been created. /// </summary> internal DeferredInitializationState DeferredState { get; private set; } public VisualStudioWorkspaceImpl(ExportProvider exportProvider) : base( MefV1HostServices.Create(exportProvider), backgroundWork: WorkspaceBackgroundWork.ParseAndCompile) { PrimaryWorkspace.Register(this); } /// <summary> /// Ensures the workspace is fully hooked up to the host by subscribing to all sorts of VS /// UI thread affinitized events. /// </summary> internal VisualStudioProjectTracker GetProjectTrackerAndInitializeIfNecessary(IServiceProvider serviceProvider) { if (DeferredState == null) { _foregroundObject.Value.AssertIsForeground(); DeferredState = new DeferredInitializationState(this, serviceProvider); } return DeferredState.ProjectTracker; } /// <summary> /// A compatibility shim to ensure that F# and TypeScript continue to work after the deferred work goes in. This will be /// removed once they move to calling <see cref="GetProjectTrackerAndInitializeIfNecessary"/>. /// </summary> internal VisualStudioProjectTracker ProjectTracker { get { return GetProjectTrackerAndInitializeIfNecessary(ServiceProvider.GlobalProvider); } } internal void ClearReferenceCache() { DeferredState?.ProjectTracker.MetadataReferenceProvider.ClearCache(); } internal IVisualStudioHostDocument GetHostDocument(DocumentId documentId) { var project = GetHostProject(documentId.ProjectId); if (project != null) { return project.GetDocumentOrAdditionalDocument(documentId); } return null; } internal IVisualStudioHostProject GetHostProject(ProjectId projectId) { return DeferredState?.ProjectTracker.GetProject(projectId); } private bool TryGetHostProject(ProjectId projectId, out IVisualStudioHostProject project) { project = GetHostProject(projectId); return project != null; } internal override bool TryApplyChanges( Microsoft.CodeAnalysis.Solution newSolution, IProgressTracker progressTracker) { if (_foregroundObject.IsValueCreated && !_foregroundObject.Value.IsForeground()) { throw new InvalidOperationException(ServicesVSResources.VisualStudioWorkspace_TryApplyChanges_cannot_be_called_from_a_background_thread); } var projectChanges = newSolution.GetChanges(this.CurrentSolution).GetProjectChanges().ToList(); var projectsToLoad = new HashSet<Guid>(); foreach (var pc in projectChanges) { if (pc.GetAddedAdditionalDocuments().Any() || pc.GetAddedAnalyzerReferences().Any() || pc.GetAddedDocuments().Any() || pc.GetAddedMetadataReferences().Any() || pc.GetAddedProjectReferences().Any() || pc.GetRemovedAdditionalDocuments().Any() || pc.GetRemovedAnalyzerReferences().Any() || pc.GetRemovedDocuments().Any() || pc.GetRemovedMetadataReferences().Any() || pc.GetRemovedProjectReferences().Any()) { projectsToLoad.Add(GetHostProject(pc.ProjectId).Guid); } } if (projectsToLoad.Any()) { var vsSolution4 = (IVsSolution4)DeferredState.ServiceProvider.GetService(typeof(SVsSolution)); vsSolution4.EnsureProjectsAreLoaded( (uint)projectsToLoad.Count, projectsToLoad.ToArray(), (uint)__VSBSLFLAGS.VSBSLFLAGS_None); } // first make sure we can edit the document we will be updating (check them out from source control, etc) var changedDocs = projectChanges.SelectMany(pd => pd.GetChangedDocuments()).ToList(); if (changedDocs.Count > 0) { this.EnsureEditableDocuments(changedDocs); } return base.TryApplyChanges(newSolution, progressTracker); } public override bool CanOpenDocuments { get { return true; } } internal override bool CanChangeActiveContextDocument { get { return true; } } internal override bool CanRenameFilesDuringCodeActions(CodeAnalysis.Project project) => !IsCPSProject(project); internal bool IsCPSProject(CodeAnalysis.Project project) { _foregroundObject.Value.AssertIsForeground(); if (this.TryGetHierarchy(project.Id, out var hierarchy)) { // Currently renaming files in CPS projects (i.e. .Net Core) doesn't work proprey. // This is because the remove/add of the documents in CPS is not synchronous // (despite the DTE interfaces being synchronous). So Roslyn calls the methods // expecting the changes to happen immediately. Because they are deferred in CPS // this causes problems. return hierarchy.IsCapabilityMatch("CPS"); } return false; } protected override bool CanApplyParseOptionChange(ParseOptions oldOptions, ParseOptions newOptions, CodeAnalysis.Project project) { var parseOptionsService = project.LanguageServices.GetService<IParseOptionsService>(); if (parseOptionsService == null) { return false; } // Currently, only changes to the LanguageVersion of parse options are supported. var newLanguageVersion = parseOptionsService.GetLanguageVersion(newOptions); var updated = parseOptionsService.WithLanguageVersion(oldOptions, newLanguageVersion); return newOptions == updated; } public override bool CanApplyChange(ApplyChangesKind feature) { switch (feature) { case ApplyChangesKind.AddDocument: case ApplyChangesKind.RemoveDocument: case ApplyChangesKind.ChangeDocument: case ApplyChangesKind.AddMetadataReference: case ApplyChangesKind.RemoveMetadataReference: case ApplyChangesKind.AddProjectReference: case ApplyChangesKind.RemoveProjectReference: case ApplyChangesKind.AddAnalyzerReference: case ApplyChangesKind.RemoveAnalyzerReference: case ApplyChangesKind.AddAdditionalDocument: case ApplyChangesKind.RemoveAdditionalDocument: case ApplyChangesKind.ChangeAdditionalDocument: case ApplyChangesKind.ChangeParseOptions: return true; default: return false; } } private bool TryGetProjectData(ProjectId projectId, out IVisualStudioHostProject hostProject, out IVsHierarchy hierarchy, out EnvDTE.Project project) { hierarchy = null; project = null; return this.TryGetHostProject(projectId, out hostProject) && this.TryGetHierarchy(projectId, out hierarchy) && hierarchy.TryGetProject(out project); } internal void GetProjectData(ProjectId projectId, out IVisualStudioHostProject hostProject, out IVsHierarchy hierarchy, out EnvDTE.Project project) { if (!TryGetProjectData(projectId, out hostProject, out hierarchy, out project)) { throw new ArgumentException(string.Format(ServicesVSResources.Could_not_find_project_0, projectId)); } } internal EnvDTE.Project TryGetDTEProject(ProjectId projectId) { return TryGetProjectData(projectId, out var hostProject, out var hierarchy, out var project) ? project : null; } internal bool TryAddReferenceToProject(ProjectId projectId, string assemblyName) { EnvDTE.Project project; try { GetProjectData(projectId, out var hostProject, out var hierarchy, out project); } catch (ArgumentException) { return false; } var vsProject = (VSProject)project.Object; try { vsProject.References.Add(assemblyName); } catch (Exception) { return false; } return true; } private string GetAnalyzerPath(AnalyzerReference analyzerReference) { return analyzerReference.FullPath; } protected override void ApplyParseOptionsChanged(ProjectId projectId, ParseOptions options) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } var parseOptionsService = CurrentSolution.GetProject(projectId).LanguageServices.GetService<IParseOptionsService>(); Contract.ThrowIfNull(parseOptionsService, nameof(parseOptionsService)); string newVersion = parseOptionsService.GetLanguageVersion(options); GetProjectData(projectId, out var hostProject, out var hierarchy, out var project); foreach (string configurationName in (object[])project.ConfigurationManager.ConfigurationRowNames) { switch (hostProject.Language) { case LanguageNames.CSharp: var csharpProperties = (VSLangProj80.CSharpProjectConfigurationProperties3)project.ConfigurationManager .ConfigurationRow(configurationName).Item(1).Object; if (newVersion != csharpProperties.LanguageVersion) { csharpProperties.LanguageVersion = newVersion; } break; case LanguageNames.VisualBasic: throw new InvalidOperationException(ServicesVSResources.This_workspace_does_not_support_updating_Visual_Basic_parse_options); } } } protected override void ApplyAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (analyzerReference == null) { throw new ArgumentNullException(nameof(analyzerReference)); } GetProjectData(projectId, out var hostProject, out var hierarchy, out var project); string filePath = GetAnalyzerPath(analyzerReference); if (filePath != null) { VSProject3 vsProject = (VSProject3)project.Object; vsProject.AnalyzerReferences.Add(filePath); } } protected override void ApplyAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (analyzerReference == null) { throw new ArgumentNullException(nameof(analyzerReference)); } GetProjectData(projectId, out var hostProject, out var hierarchy, out var project); string filePath = GetAnalyzerPath(analyzerReference); if (filePath != null) { VSProject3 vsProject = (VSProject3)project.Object; vsProject.AnalyzerReferences.Remove(filePath); } } private string GetMetadataPath(MetadataReference metadataReference) { var fileMetadata = metadataReference as PortableExecutableReference; if (fileMetadata != null) { return fileMetadata.FilePath; } return null; } protected override void ApplyMetadataReferenceAdded( ProjectId projectId, MetadataReference metadataReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (metadataReference == null) { throw new ArgumentNullException(nameof(metadataReference)); } GetProjectData(projectId, out var hostProject, out var hierarchy, out var project); string filePath = GetMetadataPath(metadataReference); if (filePath != null) { VSProject vsProject = (VSProject)project.Object; vsProject.References.Add(filePath); var undoManager = TryGetUndoManager(); undoManager?.Add(new RemoveMetadataReferenceUndoUnit(this, projectId, filePath)); } } protected override void ApplyMetadataReferenceRemoved( ProjectId projectId, MetadataReference metadataReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (metadataReference == null) { throw new ArgumentNullException(nameof(metadataReference)); } GetProjectData(projectId, out var hostProject, out var hierarchy, out var project); string filePath = GetMetadataPath(metadataReference); if (filePath != null) { VSProject vsProject = (VSProject)project.Object; foreach (Reference reference in vsProject.References) { if (StringComparer.OrdinalIgnoreCase.Equals(reference.Path, filePath)) { reference.Remove(); var undoManager = TryGetUndoManager(); undoManager?.Add(new AddMetadataReferenceUndoUnit(this, projectId, filePath)); break; } } } } protected override void ApplyProjectReferenceAdded( ProjectId projectId, ProjectReference projectReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (projectReference == null) { throw new ArgumentNullException(nameof(projectReference)); } GetProjectData(projectId, out var hostProject, out var hierarchy, out var project); GetProjectData(projectReference.ProjectId, out var refHostProject, out var refHierarchy, out var refProject); var vsProject = (VSProject)project.Object; vsProject.References.AddProject(refProject); var undoManager = TryGetUndoManager(); undoManager?.Add(new RemoveProjectReferenceUndoUnit( this, projectId, projectReference.ProjectId)); } private OleInterop.IOleUndoManager TryGetUndoManager() { var documentTrackingService = this.Services.GetService<IDocumentTrackingService>(); if (documentTrackingService != null) { var documentId = documentTrackingService.GetActiveDocument() ?? documentTrackingService.GetVisibleDocuments().FirstOrDefault(); if (documentId != null) { var composition = (IComponentModel)this.DeferredState.ServiceProvider.GetService(typeof(SComponentModel)); var exportProvider = composition.DefaultExportProvider; var editorAdaptersService = exportProvider.GetExportedValue<IVsEditorAdaptersFactoryService>(); return editorAdaptersService.TryGetUndoManager(this, documentId, CancellationToken.None); } } return null; } protected override void ApplyProjectReferenceRemoved( ProjectId projectId, ProjectReference projectReference) { if (projectId == null) { throw new ArgumentNullException(nameof(projectId)); } if (projectReference == null) { throw new ArgumentNullException(nameof(projectReference)); } GetProjectData(projectId, out var hostProject, out var hierarchy, out var project); GetProjectData(projectReference.ProjectId, out var refHostProject, out var refHierarchy, out var refProject); var vsProject = (VSProject)project.Object; foreach (Reference reference in vsProject.References) { if (reference.SourceProject == refProject) { reference.Remove(); var undoManager = TryGetUndoManager(); undoManager?.Add(new AddProjectReferenceUndoUnit(this, projectId, projectReference.ProjectId)); } } } protected override void ApplyDocumentAdded(DocumentInfo info, SourceText text) { AddDocumentCore(info, text, isAdditionalDocument: false); } protected override void ApplyAdditionalDocumentAdded(DocumentInfo info, SourceText text) { AddDocumentCore(info, text, isAdditionalDocument: true); } private void AddDocumentCore(DocumentInfo info, SourceText initialText, bool isAdditionalDocument) { GetProjectData(info.Id.ProjectId, out var hostProject, out var hierarchy, out var project); // If the first namespace name matches the name of the project, then we don't want to // generate a folder for that. The project is implicitly a folder with that name. var folders = info.Folders.AsEnumerable(); if (folders.FirstOrDefault() == project.Name) { folders = folders.Skip(1); } folders = FilterFolderForProjectType(project, folders); if (IsWebsite(project)) { AddDocumentToFolder(hostProject, project, info.Id, SpecializedCollections.SingletonEnumerable(AppCodeFolderName), info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument); } else if (folders.Any()) { AddDocumentToFolder(hostProject, project, info.Id, folders, info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument); } else { AddDocumentToProject(hostProject, project, info.Id, info.Name, info.SourceCodeKind, initialText, isAdditionalDocument: isAdditionalDocument); } var undoManager = TryGetUndoManager(); if (isAdditionalDocument) { undoManager?.Add(new RemoveAdditionalDocumentUndoUnit(this, info.Id)); } else { undoManager?.Add(new RemoveDocumentUndoUnit(this, info.Id)); } } private bool IsWebsite(EnvDTE.Project project) { return project.Kind == VsWebSite.PrjKind.prjKindVenusProject; } private IEnumerable<string> FilterFolderForProjectType(EnvDTE.Project project, IEnumerable<string> folders) { foreach (var folder in folders) { var items = GetAllItems(project.ProjectItems); var folderItem = items.FirstOrDefault(p => StringComparer.OrdinalIgnoreCase.Compare(p.Name, folder) == 0); if (folderItem == null || folderItem.Kind != EnvDTE.Constants.vsProjectItemKindPhysicalFile) { yield return folder; } } } private IEnumerable<ProjectItem> GetAllItems(ProjectItems projectItems) { if (projectItems == null) { return SpecializedCollections.EmptyEnumerable<ProjectItem>(); } var items = projectItems.OfType<ProjectItem>(); return items.Concat(items.SelectMany(i => GetAllItems(i.ProjectItems))); } #if false protected override void AddExistingDocument(DocumentId documentId, string filePath, IEnumerable<string> folders) { IVsHierarchy hierarchy; EnvDTE.Project project; IVisualStudioHostProject hostProject; GetProjectData(documentId.ProjectId, out hostProject, out hierarchy, out project); // If the first namespace name matches the name of the project, then we don't want to // generate a folder for that. The project is implicitly a folder with that name. if (folders.FirstOrDefault() == project.Name) { folders = folders.Skip(1); } var name = Path.GetFileName(filePath); if (folders.Any()) { AddDocumentToFolder(hostProject, project, documentId, folders, name, SourceCodeKind.Regular, initialText: null, filePath: filePath); } else { AddDocumentToProject(hostProject, project, documentId, name, SourceCodeKind.Regular, initialText: null, filePath: filePath); } } #endif private ProjectItem AddDocumentToProject( IVisualStudioHostProject hostProject, EnvDTE.Project project, DocumentId documentId, string documentName, SourceCodeKind sourceCodeKind, SourceText initialText = null, string filePath = null, bool isAdditionalDocument = false) { if (!project.TryGetFullPath(out var folderPath)) { // TODO(cyrusn): Throw an appropriate exception here. throw new Exception(ServicesVSResources.Could_not_find_location_of_folder_on_disk); } return AddDocumentToProjectItems(hostProject, project.ProjectItems, documentId, folderPath, documentName, sourceCodeKind, initialText, filePath, isAdditionalDocument); } private ProjectItem AddDocumentToFolder( IVisualStudioHostProject hostProject, EnvDTE.Project project, DocumentId documentId, IEnumerable<string> folders, string documentName, SourceCodeKind sourceCodeKind, SourceText initialText = null, string filePath = null, bool isAdditionalDocument = false) { var folder = project.FindOrCreateFolder(folders); if (!folder.TryGetFullPath(out var folderPath)) { // TODO(cyrusn): Throw an appropriate exception here. throw new Exception(ServicesVSResources.Could_not_find_location_of_folder_on_disk); } return AddDocumentToProjectItems(hostProject, folder.ProjectItems, documentId, folderPath, documentName, sourceCodeKind, initialText, filePath, isAdditionalDocument); } private ProjectItem AddDocumentToProjectItems( IVisualStudioHostProject hostProject, ProjectItems projectItems, DocumentId documentId, string folderPath, string documentName, SourceCodeKind sourceCodeKind, SourceText initialText, string filePath, bool isAdditionalDocument) { if (filePath == null) { var baseName = Path.GetFileNameWithoutExtension(documentName); var extension = isAdditionalDocument ? Path.GetExtension(documentName) : GetPreferredExtension(hostProject, sourceCodeKind); var uniqueName = projectItems.GetUniqueName(baseName, extension); filePath = Path.Combine(folderPath, uniqueName); } if (initialText != null) { using (var writer = new StreamWriter(filePath, append: false, encoding: initialText.Encoding ?? Encoding.UTF8)) { initialText.Write(writer); } } using (var documentIdHint = DeferredState.ProjectTracker.DocumentProvider.ProvideDocumentIdHint(filePath, documentId)) { return projectItems.AddFromFile(filePath); } } protected void RemoveDocumentCore( DocumentId documentId, bool isAdditionalDocument) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } var hostDocument = this.GetHostDocument(documentId); if (hostDocument != null) { var document = this.CurrentSolution.GetDocument(documentId); var text = this.GetTextForced(document); var project = hostDocument.Project.Hierarchy as IVsProject3; var itemId = hostDocument.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // it is no longer part of the solution return; } project.RemoveItem(0, itemId, out var result); var undoManager = TryGetUndoManager(); var docInfo = CreateDocumentInfoWithoutText(document); if (isAdditionalDocument) { undoManager?.Add(new AddAdditionalDocumentUndoUnit(this, docInfo, text)); } else { undoManager?.Add(new AddDocumentUndoUnit(this, docInfo, text)); } } } protected override void ApplyDocumentRemoved(DocumentId documentId) { RemoveDocumentCore(documentId, isAdditionalDocument: false); } protected override void ApplyAdditionalDocumentRemoved(DocumentId documentId) { RemoveDocumentCore(documentId, isAdditionalDocument: true); } public override void OpenDocument(DocumentId documentId, bool activate = true) { OpenDocumentCore(documentId, activate); } public override void OpenAdditionalDocument(DocumentId documentId, bool activate = true) { OpenDocumentCore(documentId, activate); } public override void CloseDocument(DocumentId documentId) { CloseDocumentCore(documentId); } public override void CloseAdditionalDocument(DocumentId documentId) { CloseDocumentCore(documentId); } public void OpenDocumentCore(DocumentId documentId, bool activate = true) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } if (!_foregroundObject.Value.IsForeground()) { throw new InvalidOperationException(ServicesVSResources.This_workspace_only_supports_opening_documents_on_the_UI_thread); } var document = this.GetHostDocument(documentId); if (document != null && document.Project != null) { if (TryGetFrame(document, out var frame)) { if (activate) { frame.Show(); } else { frame.ShowNoActivate(); } } } } private bool TryGetFrame(IVisualStudioHostDocument document, out IVsWindowFrame frame) { frame = null; var itemId = document.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // If the ItemId is Nil, then IVsProject would not be able to open the // document using its ItemId. Thus, we must use OpenDocumentViaProject, which only // depends on the file path. return ErrorHandler.Succeeded(DeferredState.ShellOpenDocumentService.OpenDocumentViaProject( document.FilePath, VSConstants.LOGVIEWID.TextView_guid, out var oleServiceProvider, out var uiHierarchy, out var itemid, out frame)); } else { // If the ItemId is not Nil, then we should not call IVsUIShellDocument // .OpenDocumentViaProject here because that simply takes a file path and opens the // file within the context of the first project it finds. That would cause problems // if the document we're trying to open is actually a linked file in another // project. So, we get the project's hierarchy and open the document using its item // ID. // It's conceivable that IVsHierarchy might not implement IVsProject. However, // OpenDocumentViaProject itself relies upon this QI working, so it should be OK to // use here. var vsProject = document.Project.Hierarchy as IVsProject; return vsProject != null && ErrorHandler.Succeeded(vsProject.OpenItem(itemId, VSConstants.LOGVIEWID.TextView_guid, s_docDataExisting_Unknown, out frame)); } } public void CloseDocumentCore(DocumentId documentId) { if (documentId == null) { throw new ArgumentNullException(nameof(documentId)); } if (this.IsDocumentOpen(documentId)) { var document = this.GetHostDocument(documentId); if (document != null) { if (ErrorHandler.Succeeded(DeferredState.ShellOpenDocumentService.IsDocumentOpen(null, 0, document.FilePath, Guid.Empty, 0, out var uiHierarchy, null, out var frame, out var isOpen))) { // TODO: do we need save argument for CloseDocument? frame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave); } } } } protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText newText) { EnsureEditableDocuments(documentId); var hostDocument = GetHostDocument(documentId); hostDocument.UpdateText(newText); } protected override void ApplyAdditionalDocumentTextChanged(DocumentId documentId, SourceText newText) { EnsureEditableDocuments(documentId); var hostDocument = GetHostDocument(documentId); hostDocument.UpdateText(newText); } private static string GetPreferredExtension(IVisualStudioHostProject hostProject, SourceCodeKind sourceCodeKind) { // No extension was provided. Pick a good one based on the type of host project. switch (hostProject.Language) { case LanguageNames.CSharp: // TODO: uncomment when fixing https://github.com/dotnet/roslyn/issues/5325 //return sourceCodeKind == SourceCodeKind.Regular ? ".cs" : ".csx"; return ".cs"; case LanguageNames.VisualBasic: // TODO: uncomment when fixing https://github.com/dotnet/roslyn/issues/5325 //return sourceCodeKind == SourceCodeKind.Regular ? ".vb" : ".vbx"; return ".vb"; default: throw new InvalidOperationException(); } } public override IVsHierarchy GetHierarchy(ProjectId projectId) { var project = this.GetHostProject(projectId); if (project == null) { return null; } return project.Hierarchy; } internal override void SetDocumentContext(DocumentId documentId) { var hostDocument = GetHostDocument(documentId); if (hostDocument == null) { // the document or project is not being tracked return; } var itemId = hostDocument.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // the document has been removed from the solution return; } var hierarchy = hostDocument.Project.Hierarchy; var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hierarchy, itemId); if (sharedHierarchy != null) { if (sharedHierarchy.SetProperty( (uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID8.VSHPROPID_ActiveIntellisenseProjectContext, DeferredState.ProjectTracker.GetProject(documentId.ProjectId).ProjectSystemName) == VSConstants.S_OK) { // The ASP.NET 5 intellisense project is now updated. return; } else { // Universal Project shared files // Change the SharedItemContextHierarchy of the project's parent hierarchy, then // hierarchy events will trigger the workspace to update. var hr = sharedHierarchy.SetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID7.VSHPROPID_SharedItemContextHierarchy, hierarchy); } } else { // Regular linked files // Transfer the item (open buffer) to the new hierarchy, and then hierarchy events // will trigger the workspace to update. var vsproj = hierarchy as IVsProject3; var hr = vsproj.TransferItem(hostDocument.FilePath, hostDocument.FilePath, punkWindowFrame: null); } } internal void UpdateDocumentContextIfContainsDocument(IVsHierarchy sharedHierarchy, DocumentId documentId) { // TODO: This is a very roundabout way to update the context // The sharedHierarchy passed in has a new context, but we don't know what it is. // The documentId passed in is associated with this sharedHierarchy, and this method // will be called once for each such documentId. During this process, one of these // documentIds will actually belong to the new SharedItemContextHierarchy. Once we // find that one, we can map back to the open buffer and set its active context to // the appropriate project. // Note that if there is a single head project and it's in the process of being unloaded // there might not be a host project. var hostProject = LinkedFileUtilities.GetContextHostProject(sharedHierarchy, DeferredState.ProjectTracker); if (hostProject?.Hierarchy == sharedHierarchy) { return; } if (hostProject.Id != documentId.ProjectId) { // While this documentId is associated with one of the head projects for this // sharedHierarchy, it is not associated with the new context hierarchy. Another // documentId will be passed to this method and update the context. return; } // This documentId belongs to the new SharedItemContextHierarchy. Update the associated // buffer. OnDocumentContextUpdated(documentId); } /// <summary> /// Finds the <see cref="DocumentId"/> related to the given <see cref="DocumentId"/> that /// is in the current context. For regular files (non-shared and non-linked) and closed /// linked files, this is always the provided <see cref="DocumentId"/>. For open linked /// files and open shared files, the active context is already tracked by the /// <see cref="Workspace"/> and can be looked up directly. For closed shared files, the /// document in the shared project's <see cref="__VSHPROPID7.VSHPROPID_SharedItemContextHierarchy"/> /// is preferred. /// </summary> internal override DocumentId GetDocumentIdInCurrentContext(DocumentId documentId) { // If the document is open, then the Workspace knows the current context for both // linked and shared files if (IsDocumentOpen(documentId)) { return base.GetDocumentIdInCurrentContext(documentId); } var hostDocument = GetHostDocument(documentId); var itemId = hostDocument.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // An itemid is required to determine whether the file belongs to a Shared Project return base.GetDocumentIdInCurrentContext(documentId); } // If this is a regular document or a closed linked (non-shared) document, then use the // default logic for determining current context. var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hostDocument.Project.Hierarchy, itemId); if (sharedHierarchy == null) { return base.GetDocumentIdInCurrentContext(documentId); } // This is a closed shared document, so we must determine the correct context. var hostProject = LinkedFileUtilities.GetContextHostProject(sharedHierarchy, DeferredState.ProjectTracker); var matchingProject = CurrentSolution.GetProject(hostProject.Id); if (matchingProject == null || hostProject.Hierarchy == sharedHierarchy) { return base.GetDocumentIdInCurrentContext(documentId); } if (matchingProject.ContainsDocument(documentId)) { // The provided documentId is in the current context project return documentId; } // The current context document is from another project. var linkedDocumentIds = CurrentSolution.GetDocument(documentId).GetLinkedDocumentIds(); var matchingDocumentId = linkedDocumentIds.FirstOrDefault(id => id.ProjectId == matchingProject.Id); return matchingDocumentId ?? base.GetDocumentIdInCurrentContext(documentId); } internal bool TryGetHierarchy(ProjectId projectId, out IVsHierarchy hierarchy) { hierarchy = this.GetHierarchy(projectId); return hierarchy != null; } public override string GetFilePath(DocumentId documentId) { var document = this.GetHostDocument(documentId); if (document == null) { return null; } else { return document.FilePath; } } internal void StartSolutionCrawler() { if (_registrationService == null) { lock (this) { if (_registrationService == null) { _registrationService = this.Services.GetService<ISolutionCrawlerRegistrationService>(); _registrationService.Register(this); } } } } internal void StopSolutionCrawler() { if (_registrationService != null) { lock (this) { if (_registrationService != null) { _registrationService.Unregister(this, blockingShutdown: true); _registrationService = null; } } } } protected override void Dispose(bool finalize) { // workspace is going away. unregister this workspace from work coordinator StopSolutionCrawler(); // We should consider calling this here. It is commented out because Solution event tracking was // moved from VisualStudioProjectTracker, which is never Dispose()'d. Rather than risk the // UnadviseSolutionEvents causing another issue (calling into dead COM objects, etc), we'll just // continue to skip it for now. // UnadviseSolutionEvents(); base.Dispose(finalize); } public void EnsureEditableDocuments(IEnumerable<DocumentId> documents) { var queryEdit = (IVsQueryEditQuerySave2)DeferredState.ServiceProvider.GetService(typeof(SVsQueryEditQuerySave)); var fileNames = documents.Select(GetFilePath).ToArray(); // TODO: meditate about the flags we can pass to this and decide what is most appropriate for Roslyn int result = queryEdit.QueryEditFiles( rgfQueryEdit: 0, cFiles: fileNames.Length, rgpszMkDocuments: fileNames, rgrgf: new uint[fileNames.Length], rgFileInfo: new VSQEQS_FILE_ATTRIBUTE_DATA[fileNames.Length], pfEditVerdict: out var editVerdict, prgfMoreInfo: out var editResultFlags); if (ErrorHandler.Failed(result) || editVerdict != (uint)tagVSQueryEditResult.QER_EditOK) { throw new Exception("Unable to check out the files from source control."); } if ((editResultFlags & (uint)(tagVSQueryEditResultFlags2.QER_Changed | tagVSQueryEditResultFlags2.QER_Reloaded)) != 0) { throw new Exception("A file was reloaded during the source control checkout."); } } public void EnsureEditableDocuments(params DocumentId[] documents) { this.EnsureEditableDocuments((IEnumerable<DocumentId>)documents); } internal void OnDocumentTextUpdatedOnDisk(DocumentId documentId) { var vsDoc = this.GetHostDocument(documentId); this.OnDocumentTextLoaderChanged(documentId, vsDoc.Loader); } internal void OnAdditionalDocumentTextUpdatedOnDisk(DocumentId documentId) { var vsDoc = this.GetHostDocument(documentId); this.OnAdditionalDocumentTextLoaderChanged(documentId, vsDoc.Loader); } internal override bool CanAddProjectReference(ProjectId referencingProject, ProjectId referencedProject) { _foregroundObject.Value.AssertIsForeground(); if (!TryGetHierarchy(referencingProject, out var referencingHierarchy) || !TryGetHierarchy(referencedProject, out var referencedHierarchy)) { // Couldn't even get a hierarchy for this project. So we have to assume // that adding a reference is disallowed. return false; } // First we have to see if either project disallows the reference being added. const int ContextFlags = (int)__VSQUERYFLAVORREFERENCESCONTEXT.VSQUERYFLAVORREFERENCESCONTEXT_RefreshReference; uint canAddProjectReference = (uint)__VSREFERENCEQUERYRESULT.REFERENCE_UNKNOWN; uint canBeReferenced = (uint)__VSREFERENCEQUERYRESULT.REFERENCE_UNKNOWN; var referencingProjectFlavor3 = referencingHierarchy as IVsProjectFlavorReferences3; if (referencingProjectFlavor3 != null) { if (ErrorHandler.Failed(referencingProjectFlavor3.QueryAddProjectReferenceEx(referencedHierarchy, ContextFlags, out canAddProjectReference, out var unused))) { // Something went wrong even trying to see if the reference would be allowed. // Assume it won't be allowed. return false; } if (canAddProjectReference == (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY) { // Adding this project reference is not allowed. return false; } } var referencedProjectFlavor3 = referencedHierarchy as IVsProjectFlavorReferences3; if (referencedProjectFlavor3 != null) { if (ErrorHandler.Failed(referencedProjectFlavor3.QueryCanBeReferencedEx(referencingHierarchy, ContextFlags, out canBeReferenced, out var unused))) { // Something went wrong even trying to see if the reference would be allowed. // Assume it won't be allowed. return false; } if (canBeReferenced == (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY) { // Adding this project reference is not allowed. return false; } } // Neither project denied the reference being added. At this point, if either project // allows the reference to be added, and the other doesn't block it, then we can add // the reference. if (canAddProjectReference == (int)__VSREFERENCEQUERYRESULT.REFERENCE_ALLOW || canBeReferenced == (int)__VSREFERENCEQUERYRESULT.REFERENCE_ALLOW) { return true; } // In both directions things are still unknown. Fallback to the reference manager // to make the determination here. var referenceManager = (IVsReferenceManager)DeferredState.ServiceProvider.GetService(typeof(SVsReferenceManager)); if (referenceManager == null) { // Couldn't get the reference manager. Have to assume it's not allowed. return false; } // As long as the reference manager does not deny things, then we allow the // reference to be added. var result = referenceManager.QueryCanReferenceProject(referencingHierarchy, referencedHierarchy); return result != (uint)__VSREFERENCEQUERYRESULT.REFERENCE_DENY; } /// <summary> /// A trivial implementation of <see cref="IVisualStudioWorkspaceHost" /> that just /// forwards the calls down to the underlying Workspace. /// </summary> protected sealed class VisualStudioWorkspaceHost : IVisualStudioWorkspaceHost, IVisualStudioWorkspaceHost2, IVisualStudioWorkingFolder { private readonly VisualStudioWorkspaceImpl _workspace; private readonly Dictionary<DocumentId, uint> _documentIdToHierarchyEventsCookieMap = new Dictionary<DocumentId, uint>(); public VisualStudioWorkspaceHost(VisualStudioWorkspaceImpl workspace) { _workspace = workspace; } void IVisualStudioWorkspaceHost.OnOptionsChanged(ProjectId projectId, CompilationOptions compilationOptions, ParseOptions parseOptions) { _workspace.OnCompilationOptionsChanged(projectId, compilationOptions); _workspace.OnParseOptionsChanged(projectId, parseOptions); } void IVisualStudioWorkspaceHost.OnDocumentAdded(DocumentInfo documentInfo) { _workspace.OnDocumentAdded(documentInfo); } void IVisualStudioWorkspaceHost.OnDocumentClosed(DocumentId documentId, ITextBuffer textBuffer, TextLoader loader, bool updateActiveContext) { // TODO: Move this out to DocumentProvider. As is, this depends on being able to // access the host document which will already be deleted in some cases, causing // a crash. Until this is fixed, we will leak a HierarchyEventsSink every time a // Mercury shared document is closed. // UnsubscribeFromSharedHierarchyEvents(documentId); using (_workspace.Services.GetService<IGlobalOperationNotificationService>().Start("Document Closed")) { _workspace.OnDocumentClosed(documentId, loader, updateActiveContext); } } void IVisualStudioWorkspaceHost.OnDocumentOpened(DocumentId documentId, ITextBuffer textBuffer, bool currentContext) { SubscribeToSharedHierarchyEvents(documentId); _workspace.OnDocumentOpened(documentId, textBuffer.AsTextContainer(), currentContext); } private void SubscribeToSharedHierarchyEvents(DocumentId documentId) { // Todo: maybe avoid double alerts. var hostDocument = _workspace.GetHostDocument(documentId); if (hostDocument == null) { return; } var hierarchy = hostDocument.Project.Hierarchy; var itemId = hostDocument.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // the document has been removed from the solution return; } var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hierarchy, itemId); if (sharedHierarchy != null) { var eventSink = new HierarchyEventsSink(_workspace, sharedHierarchy, documentId); var hr = sharedHierarchy.AdviseHierarchyEvents(eventSink, out var cookie); if (hr == VSConstants.S_OK && !_documentIdToHierarchyEventsCookieMap.ContainsKey(documentId)) { _documentIdToHierarchyEventsCookieMap.Add(documentId, cookie); } } } private void UnsubscribeFromSharedHierarchyEvents(DocumentId documentId) { var hostDocument = _workspace.GetHostDocument(documentId); var itemId = hostDocument.GetItemId(); if (itemId == (uint)VSConstants.VSITEMID.Nil) { // the document has been removed from the solution return; } var sharedHierarchy = LinkedFileUtilities.GetSharedHierarchyForItem(hostDocument.Project.Hierarchy, itemId); if (sharedHierarchy != null) { if (_documentIdToHierarchyEventsCookieMap.TryGetValue(documentId, out var cookie)) { var hr = sharedHierarchy.UnadviseHierarchyEvents(cookie); _documentIdToHierarchyEventsCookieMap.Remove(documentId); } } } private void RegisterPrimarySolutionForPersistentStorage( SolutionId solutionId) { var service = _workspace.Services.GetService<IPersistentStorageService>() as AbstractPersistentStorageService; if (service == null) { return; } service.RegisterPrimarySolution(solutionId); } private void UnregisterPrimarySolutionForPersistentStorage( SolutionId solutionId, bool synchronousShutdown) { var service = _workspace.Services.GetService<IPersistentStorageService>() as AbstractPersistentStorageService; if (service == null) { return; } service.UnregisterPrimarySolution(solutionId, synchronousShutdown); } void IVisualStudioWorkspaceHost.OnDocumentRemoved(DocumentId documentId) { _workspace.OnDocumentRemoved(documentId); } void IVisualStudioWorkspaceHost.OnMetadataReferenceAdded(ProjectId projectId, PortableExecutableReference metadataReference) { _workspace.OnMetadataReferenceAdded(projectId, metadataReference); } void IVisualStudioWorkspaceHost.OnMetadataReferenceRemoved(ProjectId projectId, PortableExecutableReference metadataReference) { _workspace.OnMetadataReferenceRemoved(projectId, metadataReference); } void IVisualStudioWorkspaceHost.OnProjectAdded(ProjectInfo projectInfo) { using (_workspace.Services.GetService<IGlobalOperationNotificationService>()?.Start("Add Project")) { _workspace.OnProjectAdded(projectInfo); } } void IVisualStudioWorkspaceHost.OnProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference) { _workspace.OnProjectReferenceAdded(projectId, projectReference); } void IVisualStudioWorkspaceHost.OnProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference) { _workspace.OnProjectReferenceRemoved(projectId, projectReference); } void IVisualStudioWorkspaceHost.OnProjectRemoved(ProjectId projectId) { using (_workspace.Services.GetService<IGlobalOperationNotificationService>()?.Start("Remove Project")) { _workspace.OnProjectRemoved(projectId); } } void IVisualStudioWorkspaceHost.OnSolutionAdded(SolutionInfo solutionInfo) { RegisterPrimarySolutionForPersistentStorage(solutionInfo.Id); _workspace.OnSolutionAdded(solutionInfo); } void IVisualStudioWorkspaceHost.OnSolutionRemoved() { var solutionId = _workspace.CurrentSolution.Id; _workspace.OnSolutionRemoved(); _workspace.ClearReferenceCache(); UnregisterPrimarySolutionForPersistentStorage(solutionId, synchronousShutdown: false); } void IVisualStudioWorkspaceHost.ClearSolution() { _workspace.ClearSolution(); _workspace.ClearReferenceCache(); } void IVisualStudioWorkspaceHost.OnDocumentTextUpdatedOnDisk(DocumentId id) { _workspace.OnDocumentTextUpdatedOnDisk(id); } void IVisualStudioWorkspaceHost.OnAssemblyNameChanged(ProjectId id, string assemblyName) { _workspace.OnAssemblyNameChanged(id, assemblyName); } void IVisualStudioWorkspaceHost.OnOutputFilePathChanged(ProjectId id, string outputFilePath) { _workspace.OnOutputFilePathChanged(id, outputFilePath); } void IVisualStudioWorkspaceHost.OnProjectNameChanged(ProjectId projectId, string name, string filePath) { _workspace.OnProjectNameChanged(projectId, name, filePath); } void IVisualStudioWorkspaceHost.OnAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference) { _workspace.OnAnalyzerReferenceAdded(projectId, analyzerReference); } void IVisualStudioWorkspaceHost.OnAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference) { _workspace.OnAnalyzerReferenceRemoved(projectId, analyzerReference); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentAdded(DocumentInfo documentInfo) { _workspace.OnAdditionalDocumentAdded(documentInfo); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentRemoved(DocumentId documentInfo) { _workspace.OnAdditionalDocumentRemoved(documentInfo); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentOpened(DocumentId documentId, ITextBuffer textBuffer, bool isCurrentContext) { _workspace.OnAdditionalDocumentOpened(documentId, textBuffer.AsTextContainer(), isCurrentContext); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentClosed(DocumentId documentId, ITextBuffer textBuffer, TextLoader loader) { _workspace.OnAdditionalDocumentClosed(documentId, loader); } void IVisualStudioWorkspaceHost.OnAdditionalDocumentTextUpdatedOnDisk(DocumentId id) { _workspace.OnAdditionalDocumentTextUpdatedOnDisk(id); } void IVisualStudioWorkspaceHost2.OnHasAllInformation(ProjectId projectId, bool hasAllInformation) { _workspace.OnHasAllInformationChanged(projectId, hasAllInformation); } void IVisualStudioWorkingFolder.OnBeforeWorkingFolderChange() { UnregisterPrimarySolutionForPersistentStorage(_workspace.CurrentSolution.Id, synchronousShutdown: true); } void IVisualStudioWorkingFolder.OnAfterWorkingFolderChange() { var solutionId = _workspace.CurrentSolution.Id; _workspace.DeferredState.ProjectTracker.UpdateSolutionProperties(solutionId); RegisterPrimarySolutionForPersistentStorage(solutionId); } } } }
/* * 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.Data; using System.Reflection; using System.Collections.Generic; using log4net; using Mono.Data.SqliteClient; using OpenMetaverse; using OpenSim.Framework; namespace OpenSim.Data.SQLiteLegacy { /// <summary> /// An asset storage interface for the SQLite database system /// </summary> public class SQLiteAssetData : AssetDataBase { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private const string SelectAssetSQL = "select * from assets where UUID=:UUID"; private const string SelectAssetMetadataSQL = "select Name, Description, Type, Temporary, UUID from assets limit :start, :count"; private const string DeleteAssetSQL = "delete from assets where UUID=:UUID"; private const string InsertAssetSQL = "insert into assets(UUID, Name, Description, Type, Local, Temporary, Data) values(:UUID, :Name, :Description, :Type, :Local, :Temporary, :Data)"; private const string UpdateAssetSQL = "update assets set Name=:Name, Description=:Description, Type=:Type, Local=:Local, Temporary=:Temporary, Data=:Data where UUID=:UUID"; private const string assetSelect = "select * from assets"; private SqliteConnection m_conn; override public void Dispose() { if (m_conn != null) { m_conn.Close(); m_conn = null; } } /// <summary> /// <list type="bullet"> /// <item>Initialises AssetData interface</item> /// <item>Loads and initialises a new SQLite connection and maintains it.</item> /// <item>use default URI if connect string is empty.</item> /// </list> /// </summary> /// <param name="dbconnect">connect string</param> override public void Initialise(string dbconnect) { if (dbconnect == string.Empty) { dbconnect = "URI=file:Asset.db,version=3"; } m_conn = new SqliteConnection(dbconnect); m_conn.Open(); Assembly assem = GetType().Assembly; Migration m = new Migration(m_conn, assem, "AssetStore"); m.Update(); return; } /// <summary> /// Fetch Asset /// </summary> /// <param name="uuid">UUID of ... ?</param> /// <returns>Asset base</returns> override public AssetBase GetAsset(UUID uuid) { lock (this) { using (SqliteCommand cmd = new SqliteCommand(SelectAssetSQL, m_conn)) { cmd.Parameters.Add(new SqliteParameter(":UUID", uuid.ToString())); using (IDataReader reader = cmd.ExecuteReader()) { if (reader.Read()) { AssetBase asset = buildAsset(reader); reader.Close(); return asset; } else { reader.Close(); return null; } } } } } /// <summary> /// Create an asset /// </summary> /// <param name="asset">Asset Base</param> override public void StoreAsset(AssetBase asset) { //m_log.Info("[ASSET DB]: Creating Asset " + asset.FullID.ToString()); if (ExistsAsset(asset.FullID)) { //LogAssetLoad(asset); lock (this) { using (SqliteCommand cmd = new SqliteCommand(UpdateAssetSQL, m_conn)) { cmd.Parameters.Add(new SqliteParameter(":UUID", asset.FullID.ToString())); cmd.Parameters.Add(new SqliteParameter(":Name", asset.Name)); cmd.Parameters.Add(new SqliteParameter(":Description", asset.Description)); cmd.Parameters.Add(new SqliteParameter(":Type", asset.Type)); cmd.Parameters.Add(new SqliteParameter(":Local", asset.Local)); cmd.Parameters.Add(new SqliteParameter(":Temporary", asset.Temporary)); cmd.Parameters.Add(new SqliteParameter(":Data", asset.Data)); cmd.ExecuteNonQuery(); } } } else { lock (this) { using (SqliteCommand cmd = new SqliteCommand(InsertAssetSQL, m_conn)) { cmd.Parameters.Add(new SqliteParameter(":UUID", asset.FullID.ToString())); cmd.Parameters.Add(new SqliteParameter(":Name", asset.Name)); cmd.Parameters.Add(new SqliteParameter(":Description", asset.Description)); cmd.Parameters.Add(new SqliteParameter(":Type", asset.Type)); cmd.Parameters.Add(new SqliteParameter(":Local", asset.Local)); cmd.Parameters.Add(new SqliteParameter(":Temporary", asset.Temporary)); cmd.Parameters.Add(new SqliteParameter(":Data", asset.Data)); cmd.ExecuteNonQuery(); } } } } // /// <summary> // /// Some... logging functionnality // /// </summary> // /// <param name="asset"></param> // private static void LogAssetLoad(AssetBase asset) // { // string temporary = asset.Temporary ? "Temporary" : "Stored"; // string local = asset.Local ? "Local" : "Remote"; // // int assetLength = (asset.Data != null) ? asset.Data.Length : 0; // // m_log.Debug("[ASSET DB]: " + // string.Format("Loaded {5} {4} Asset: [{0}][{3}] \"{1}\":{2} ({6} bytes)", // asset.FullID, asset.Name, asset.Description, asset.Type, // temporary, local, assetLength)); // } /// <summary> /// Check if an asset exist in database /// </summary> /// <param name="uuid">The asset UUID</param> /// <returns>True if exist, or false.</returns> override public bool ExistsAsset(UUID uuid) { lock (this) { using (SqliteCommand cmd = new SqliteCommand(SelectAssetSQL, m_conn)) { cmd.Parameters.Add(new SqliteParameter(":UUID", uuid.ToString())); using (IDataReader reader = cmd.ExecuteReader()) { if (reader.Read()) { reader.Close(); return true; } else { reader.Close(); return false; } } } } } /// <summary> /// Delete an asset from database /// </summary> /// <param name="uuid"></param> public void DeleteAsset(UUID uuid) { using (SqliteCommand cmd = new SqliteCommand(DeleteAssetSQL, m_conn)) { cmd.Parameters.Add(new SqliteParameter(":UUID", uuid.ToString())); cmd.ExecuteNonQuery(); } } /// <summary> /// /// </summary> /// <param name="row"></param> /// <returns></returns> private static AssetBase buildAsset(IDataReader row) { // TODO: this doesn't work yet because something more // interesting has to be done to actually get these values // back out. Not enough time to figure it out yet. AssetBase asset = new AssetBase( new UUID((String)row["UUID"]), (String)row["Name"], Convert.ToSByte(row["Type"]) ); asset.Description = (String) row["Description"]; asset.Local = Convert.ToBoolean(row["Local"]); asset.Temporary = Convert.ToBoolean(row["Temporary"]); asset.Data = (byte[]) row["Data"]; return asset; } private static AssetMetadata buildAssetMetadata(IDataReader row) { AssetMetadata metadata = new AssetMetadata(); metadata.FullID = new UUID((string) row["UUID"]); metadata.Name = (string) row["Name"]; metadata.Description = (string) row["Description"]; metadata.Type = Convert.ToSByte(row["Type"]); metadata.Temporary = Convert.ToBoolean(row["Temporary"]); // Not sure if this is correct. // Current SHA1s are not stored/computed. metadata.SHA1 = new byte[] {}; return metadata; } /// <summary> /// Returns a list of AssetMetadata objects. The list is a subset of /// the entire data set offset by <paramref name="start" /> containing /// <paramref name="count" /> elements. /// </summary> /// <param name="start">The number of results to discard from the total data set.</param> /// <param name="count">The number of rows the returned list should contain.</param> /// <returns>A list of AssetMetadata objects.</returns> public override List<AssetMetadata> FetchAssetMetadataSet(int start, int count) { List<AssetMetadata> retList = new List<AssetMetadata>(count); lock (this) { using (SqliteCommand cmd = new SqliteCommand(SelectAssetMetadataSQL, m_conn)) { cmd.Parameters.Add(new SqliteParameter(":start", start)); cmd.Parameters.Add(new SqliteParameter(":count", count)); using (IDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { AssetMetadata metadata = buildAssetMetadata(reader); retList.Add(metadata); } } } } return retList; } /*********************************************************************** * * Database Binding functions * * These will be db specific due to typing, and minor differences * in databases. * **********************************************************************/ #region IPlugin interface /// <summary> /// /// </summary> override public string Version { get { Module module = GetType().Module; // string dllName = module.Assembly.ManifestModule.Name; Version dllVersion = module.Assembly.GetName().Version; return string.Format("{0}.{1}.{2}.{3}", dllVersion.Major, dllVersion.Minor, dllVersion.Build, dllVersion.Revision); } } /// <summary> /// Initialise the AssetData interface using default URI /// </summary> override public void Initialise() { Initialise("URI=file:Asset.db,version=3"); } /// <summary> /// Name of this DB provider /// </summary> override public string Name { get { return "SQLite Asset storage engine"; } } #endregion } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Dialogflow.V2.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedFulfillmentsClientTest { [xunit::FactAttribute] public void GetFulfillmentRequestObject() { moq::Mock<Fulfillments.FulfillmentsClient> mockGrpcClient = new moq::Mock<Fulfillments.FulfillmentsClient>(moq::MockBehavior.Strict); GetFulfillmentRequest request = new GetFulfillmentRequest { FulfillmentName = FulfillmentName.FromProject("[PROJECT]"), }; Fulfillment expectedResponse = new Fulfillment { FulfillmentName = FulfillmentName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", GenericWebService = new Fulfillment.Types.GenericWebService(), Enabled = true, Features = { new Fulfillment.Types.Feature(), }, }; mockGrpcClient.Setup(x => x.GetFulfillment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FulfillmentsClient client = new FulfillmentsClientImpl(mockGrpcClient.Object, null); Fulfillment response = client.GetFulfillment(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetFulfillmentRequestObjectAsync() { moq::Mock<Fulfillments.FulfillmentsClient> mockGrpcClient = new moq::Mock<Fulfillments.FulfillmentsClient>(moq::MockBehavior.Strict); GetFulfillmentRequest request = new GetFulfillmentRequest { FulfillmentName = FulfillmentName.FromProject("[PROJECT]"), }; Fulfillment expectedResponse = new Fulfillment { FulfillmentName = FulfillmentName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", GenericWebService = new Fulfillment.Types.GenericWebService(), Enabled = true, Features = { new Fulfillment.Types.Feature(), }, }; mockGrpcClient.Setup(x => x.GetFulfillmentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Fulfillment>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FulfillmentsClient client = new FulfillmentsClientImpl(mockGrpcClient.Object, null); Fulfillment responseCallSettings = await client.GetFulfillmentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Fulfillment responseCancellationToken = await client.GetFulfillmentAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetFulfillment() { moq::Mock<Fulfillments.FulfillmentsClient> mockGrpcClient = new moq::Mock<Fulfillments.FulfillmentsClient>(moq::MockBehavior.Strict); GetFulfillmentRequest request = new GetFulfillmentRequest { FulfillmentName = FulfillmentName.FromProject("[PROJECT]"), }; Fulfillment expectedResponse = new Fulfillment { FulfillmentName = FulfillmentName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", GenericWebService = new Fulfillment.Types.GenericWebService(), Enabled = true, Features = { new Fulfillment.Types.Feature(), }, }; mockGrpcClient.Setup(x => x.GetFulfillment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FulfillmentsClient client = new FulfillmentsClientImpl(mockGrpcClient.Object, null); Fulfillment response = client.GetFulfillment(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetFulfillmentAsync() { moq::Mock<Fulfillments.FulfillmentsClient> mockGrpcClient = new moq::Mock<Fulfillments.FulfillmentsClient>(moq::MockBehavior.Strict); GetFulfillmentRequest request = new GetFulfillmentRequest { FulfillmentName = FulfillmentName.FromProject("[PROJECT]"), }; Fulfillment expectedResponse = new Fulfillment { FulfillmentName = FulfillmentName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", GenericWebService = new Fulfillment.Types.GenericWebService(), Enabled = true, Features = { new Fulfillment.Types.Feature(), }, }; mockGrpcClient.Setup(x => x.GetFulfillmentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Fulfillment>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FulfillmentsClient client = new FulfillmentsClientImpl(mockGrpcClient.Object, null); Fulfillment responseCallSettings = await client.GetFulfillmentAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Fulfillment responseCancellationToken = await client.GetFulfillmentAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetFulfillmentResourceNames() { moq::Mock<Fulfillments.FulfillmentsClient> mockGrpcClient = new moq::Mock<Fulfillments.FulfillmentsClient>(moq::MockBehavior.Strict); GetFulfillmentRequest request = new GetFulfillmentRequest { FulfillmentName = FulfillmentName.FromProject("[PROJECT]"), }; Fulfillment expectedResponse = new Fulfillment { FulfillmentName = FulfillmentName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", GenericWebService = new Fulfillment.Types.GenericWebService(), Enabled = true, Features = { new Fulfillment.Types.Feature(), }, }; mockGrpcClient.Setup(x => x.GetFulfillment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FulfillmentsClient client = new FulfillmentsClientImpl(mockGrpcClient.Object, null); Fulfillment response = client.GetFulfillment(request.FulfillmentName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetFulfillmentResourceNamesAsync() { moq::Mock<Fulfillments.FulfillmentsClient> mockGrpcClient = new moq::Mock<Fulfillments.FulfillmentsClient>(moq::MockBehavior.Strict); GetFulfillmentRequest request = new GetFulfillmentRequest { FulfillmentName = FulfillmentName.FromProject("[PROJECT]"), }; Fulfillment expectedResponse = new Fulfillment { FulfillmentName = FulfillmentName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", GenericWebService = new Fulfillment.Types.GenericWebService(), Enabled = true, Features = { new Fulfillment.Types.Feature(), }, }; mockGrpcClient.Setup(x => x.GetFulfillmentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Fulfillment>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FulfillmentsClient client = new FulfillmentsClientImpl(mockGrpcClient.Object, null); Fulfillment responseCallSettings = await client.GetFulfillmentAsync(request.FulfillmentName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Fulfillment responseCancellationToken = await client.GetFulfillmentAsync(request.FulfillmentName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateFulfillmentRequestObject() { moq::Mock<Fulfillments.FulfillmentsClient> mockGrpcClient = new moq::Mock<Fulfillments.FulfillmentsClient>(moq::MockBehavior.Strict); UpdateFulfillmentRequest request = new UpdateFulfillmentRequest { Fulfillment = new Fulfillment(), UpdateMask = new wkt::FieldMask(), }; Fulfillment expectedResponse = new Fulfillment { FulfillmentName = FulfillmentName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", GenericWebService = new Fulfillment.Types.GenericWebService(), Enabled = true, Features = { new Fulfillment.Types.Feature(), }, }; mockGrpcClient.Setup(x => x.UpdateFulfillment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FulfillmentsClient client = new FulfillmentsClientImpl(mockGrpcClient.Object, null); Fulfillment response = client.UpdateFulfillment(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateFulfillmentRequestObjectAsync() { moq::Mock<Fulfillments.FulfillmentsClient> mockGrpcClient = new moq::Mock<Fulfillments.FulfillmentsClient>(moq::MockBehavior.Strict); UpdateFulfillmentRequest request = new UpdateFulfillmentRequest { Fulfillment = new Fulfillment(), UpdateMask = new wkt::FieldMask(), }; Fulfillment expectedResponse = new Fulfillment { FulfillmentName = FulfillmentName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", GenericWebService = new Fulfillment.Types.GenericWebService(), Enabled = true, Features = { new Fulfillment.Types.Feature(), }, }; mockGrpcClient.Setup(x => x.UpdateFulfillmentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Fulfillment>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FulfillmentsClient client = new FulfillmentsClientImpl(mockGrpcClient.Object, null); Fulfillment responseCallSettings = await client.UpdateFulfillmentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Fulfillment responseCancellationToken = await client.UpdateFulfillmentAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateFulfillment() { moq::Mock<Fulfillments.FulfillmentsClient> mockGrpcClient = new moq::Mock<Fulfillments.FulfillmentsClient>(moq::MockBehavior.Strict); UpdateFulfillmentRequest request = new UpdateFulfillmentRequest { Fulfillment = new Fulfillment(), UpdateMask = new wkt::FieldMask(), }; Fulfillment expectedResponse = new Fulfillment { FulfillmentName = FulfillmentName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", GenericWebService = new Fulfillment.Types.GenericWebService(), Enabled = true, Features = { new Fulfillment.Types.Feature(), }, }; mockGrpcClient.Setup(x => x.UpdateFulfillment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FulfillmentsClient client = new FulfillmentsClientImpl(mockGrpcClient.Object, null); Fulfillment response = client.UpdateFulfillment(request.Fulfillment, request.UpdateMask); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateFulfillmentAsync() { moq::Mock<Fulfillments.FulfillmentsClient> mockGrpcClient = new moq::Mock<Fulfillments.FulfillmentsClient>(moq::MockBehavior.Strict); UpdateFulfillmentRequest request = new UpdateFulfillmentRequest { Fulfillment = new Fulfillment(), UpdateMask = new wkt::FieldMask(), }; Fulfillment expectedResponse = new Fulfillment { FulfillmentName = FulfillmentName.FromProject("[PROJECT]"), DisplayName = "display_name137f65c2", GenericWebService = new Fulfillment.Types.GenericWebService(), Enabled = true, Features = { new Fulfillment.Types.Feature(), }, }; mockGrpcClient.Setup(x => x.UpdateFulfillmentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Fulfillment>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FulfillmentsClient client = new FulfillmentsClientImpl(mockGrpcClient.Object, null); Fulfillment responseCallSettings = await client.UpdateFulfillmentAsync(request.Fulfillment, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Fulfillment responseCancellationToken = await client.UpdateFulfillmentAsync(request.Fulfillment, request.UpdateMask, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Linq; using Xunit; using Moq; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.ProjectModel; using Microsoft.DotNet.Tools.Test.Utilities; using Microsoft.Extensions.PlatformAbstractions; using System.Threading; using FluentAssertions; using NuGet.Frameworks; using NuGet.Versioning; using NuGet.ProjectModel; using Microsoft.DotNet.ProjectModel.Graph; using Microsoft.DotNet.ProjectModel.Compilation; using NuGet.ProjectModel; using LockFile = Microsoft.DotNet.ProjectModel.Graph.LockFile; namespace Microsoft.DotNet.Cli.Utils.Tests { public class GivenAProjectToolsCommandResolver { private static readonly NuGetFramework s_toolPackageFramework = FrameworkConstants.CommonFrameworks.NetStandardApp15; private static readonly string s_liveProjectDirectory = Path.Combine(AppContext.BaseDirectory, "TestAssets/TestProjects/AppWithToolDependency"); [Fact] public void It_returns_null_when_CommandName_is_null() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var commandResolverArguments = new CommandResolverArguments() { CommandName = null, CommandArguments = new string[] {""}, ProjectDirectory = "/some/directory" }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().BeNull(); } [Fact] public void It_returns_null_when_ProjectDirectory_is_null() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "command", CommandArguments = new string[] {""}, ProjectDirectory = null }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().BeNull(); } [Fact] public void It_returns_null_when_CommandName_does_not_exist_in_ProjectTools() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "nonexistent-command", CommandArguments = null, ProjectDirectory = s_liveProjectDirectory }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().BeNull(); } [Fact] public void It_returns_a_CommandSpec_with_DOTNET_as_FileName_and_CommandName_in_Args_when_CommandName_exists_in_ProjectTools() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-portable", CommandArguments = null, ProjectDirectory = s_liveProjectDirectory }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); var commandFile = Path.GetFileNameWithoutExtension(result.Path); commandFile.Should().Be("dotnet"); result.Args.Should().Contain(commandResolverArguments.CommandName); } [Fact] public void It_escapes_CommandArguments_when_returning_a_CommandSpec() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-portable", CommandArguments = new [] { "arg with space"}, ProjectDirectory = s_liveProjectDirectory }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); result.Args.Should().Contain("\"arg with space\""); } [Fact] public void It_returns_a_CommandSpec_with_Args_containing_CommandPath_when_returning_a_CommandSpec_and_CommandArguments_are_null() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-portable", CommandArguments = null, ProjectDirectory = s_liveProjectDirectory }; var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); var commandPath = result.Args.Trim('"'); commandPath.Should().Contain("dotnet-portable.dll"); } [Fact] public void It_writes_a_deps_json_file_next_to_the_lockfile() { var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); var commandResolverArguments = new CommandResolverArguments() { CommandName = "dotnet-portable", CommandArguments = null, ProjectDirectory = s_liveProjectDirectory }; var context = ProjectContext.Create(Path.Combine(s_liveProjectDirectory, "project.json"), s_toolPackageFramework); var nugetPackagesRoot = context.PackagesDirectory; var toolPathCalculator = new ToolPathCalculator(nugetPackagesRoot); var lockFilePath = toolPathCalculator.GetLockFilePath( "dotnet-portable", new NuGetVersion("1.0.0"), s_toolPackageFramework); var directory = Path.GetDirectoryName(lockFilePath); var depsJsonFile = Directory .EnumerateFiles(directory) .FirstOrDefault(p => Path.GetFileName(p).EndsWith(FileNameSuffixes.DepsJson)); if (depsJsonFile != null) { File.Delete(depsJsonFile); } var result = projectToolsCommandResolver.Resolve(commandResolverArguments); result.Should().NotBeNull(); depsJsonFile = Directory .EnumerateFiles(directory) .FirstOrDefault(p => Path.GetFileName(p).EndsWith(FileNameSuffixes.DepsJson)); depsJsonFile.Should().NotBeNull(); } [Fact] public void Generate_deps_json_method_doesnt_overwrite_when_deps_file_already_exists() { var context = ProjectContext.Create(Path.Combine(s_liveProjectDirectory, "project.json"), s_toolPackageFramework); var nugetPackagesRoot = context.PackagesDirectory; var toolPathCalculator = new ToolPathCalculator(nugetPackagesRoot); var lockFilePath = toolPathCalculator.GetLockFilePath( "dotnet-portable", new NuGetVersion("1.0.0"), s_toolPackageFramework); var lockFile = LockFileReader.Read(lockFilePath, designTime: false); var depsJsonFile = Path.Combine( Path.GetDirectoryName(lockFilePath), "dotnet-portable.deps.json"); if (File.Exists(depsJsonFile)) { File.Delete(depsJsonFile); } File.WriteAllText(depsJsonFile, "temp"); var projectToolsCommandResolver = SetupProjectToolsCommandResolver(); projectToolsCommandResolver.GenerateDepsJsonFile(lockFile, depsJsonFile); File.ReadAllText(depsJsonFile).Should().Be("temp"); File.Delete(depsJsonFile); } private ProjectToolsCommandResolver SetupProjectToolsCommandResolver( IPackagedCommandSpecFactory packagedCommandSpecFactory = null) { packagedCommandSpecFactory = packagedCommandSpecFactory ?? new PackagedCommandSpecFactory(); var projectToolsCommandResolver = new ProjectToolsCommandResolver(packagedCommandSpecFactory); return projectToolsCommandResolver; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Input; using osu.Framework.Utils; using osu.Framework.Timing; using osu.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Configuration; using osu.Game.Rulesets; using osu.Game.Rulesets.Difficulty; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Objects.Legacy; using osu.Game.Rulesets.Objects.Types; using osu.Game.Rulesets.Osu; using osu.Game.Rulesets.UI; using osu.Game.Rulesets.UI.Scrolling; using osuTK; using osuTK.Graphics; namespace osu.Game.Tests.Visual.Gameplay { public class TestSceneDrawableScrollingRuleset : OsuTestScene { /// <summary> /// The amount of time visible by the "view window" of the playfield. /// All hitobjects added through <see cref="createBeatmap"/> are spaced apart by this value, such that for a beat length of 1000, /// there will be at most 2 hitobjects visible in the "view window". /// </summary> private const double time_range = 1000; private readonly ManualClock testClock = new ManualClock(); private TestDrawableScrollingRuleset drawableRuleset; [SetUp] public void Setup() => Schedule(() => testClock.CurrentTime = 0); [Test] public void TestRelativeBeatLengthScaleSingleTimingPoint() { var beatmap = createBeatmap(); beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range / 2 }); createTest(beatmap, d => d.RelativeScaleBeatLengthsOverride = true); assertPosition(0, 0f); // The single timing point is 1x speed relative to itself, such that the hitobject occurring time_range milliseconds later should appear // at the bottom of the view window regardless of the timing point's beat length assertPosition(1, 1f); } [Test] public void TestRelativeBeatLengthScaleTimingPointBeyondEndDoesNotBecomeDominant() { var beatmap = createBeatmap(); beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range / 2 }); beatmap.ControlPointInfo.Add(12000, new TimingControlPoint { BeatLength = time_range }); beatmap.ControlPointInfo.Add(100000, new TimingControlPoint { BeatLength = time_range }); createTest(beatmap, d => d.RelativeScaleBeatLengthsOverride = true); assertPosition(0, 0f); assertPosition(1, 1f); } [Test] public void TestRelativeBeatLengthScaleFromSecondTimingPoint() { var beatmap = createBeatmap(); beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range }); beatmap.ControlPointInfo.Add(3 * time_range, new TimingControlPoint { BeatLength = time_range / 2 }); createTest(beatmap, d => d.RelativeScaleBeatLengthsOverride = true); // The first timing point should have a relative velocity of 2 assertPosition(0, 0f); assertPosition(1, 0.5f); assertPosition(2, 1f); // Move to the second timing point setTime(3 * time_range); assertPosition(3, 0f); // As above, this is the timing point that is 1x speed relative to itself, so the hitobject occurring time_range milliseconds later should be at the bottom of the view window assertPosition(4, 1f); } [Test] public void TestNonRelativeScale() { var beatmap = createBeatmap(); beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range }); beatmap.ControlPointInfo.Add(3 * time_range, new TimingControlPoint { BeatLength = time_range / 2 }); createTest(beatmap); assertPosition(0, 0f); assertPosition(1, 1); // Move to the second timing point setTime(3 * time_range); assertPosition(3, 0f); // For a beat length of 500, the view window of this timing point is elongated 2x (1000 / 500), such that the second hitobject is two TimeRanges away (offscreen) // To bring it on-screen, half TimeRange is added to the current time, bringing the second half of the view window into view, and the hitobject should appear at the bottom setTime(3 * time_range + time_range / 2); assertPosition(4, 1f); } [Test] public void TestSliderMultiplierDoesNotAffectRelativeBeatLength() { var beatmap = createBeatmap(); beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range }); beatmap.BeatmapInfo.BaseDifficulty.SliderMultiplier = 2; createTest(beatmap, d => d.RelativeScaleBeatLengthsOverride = true); AddStep("adjust time range", () => drawableRuleset.TimeRange.Value = 5000); for (int i = 0; i < 5; i++) assertPosition(i, i / 5f); } [Test] public void TestSliderMultiplierAffectsNonRelativeBeatLength() { var beatmap = createBeatmap(); beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range }); beatmap.BeatmapInfo.BaseDifficulty.SliderMultiplier = 2; createTest(beatmap); AddStep("adjust time range", () => drawableRuleset.TimeRange.Value = 2000); assertPosition(0, 0); assertPosition(1, 1); } private void assertPosition(int index, float relativeY) => AddAssert($"hitobject {index} at {relativeY}", () => Precision.AlmostEquals(drawableRuleset.Playfield.AllHitObjects.ElementAt(index).DrawPosition.Y, drawableRuleset.Playfield.HitObjectContainer.DrawHeight * relativeY)); private void setTime(double time) { AddStep($"set time = {time}", () => testClock.CurrentTime = time); } /// <summary> /// Creates an <see cref="IBeatmap"/>, containing 10 hitobjects and user-provided timing points. /// The hitobjects are spaced <see cref="time_range"/> milliseconds apart. /// </summary> /// <returns>The <see cref="IBeatmap"/>.</returns> private IBeatmap createBeatmap() { var beatmap = new Beatmap<HitObject> { BeatmapInfo = { Ruleset = new OsuRuleset().RulesetInfo } }; for (int i = 0; i < 10; i++) beatmap.HitObjects.Add(new HitObject { StartTime = i * time_range }); return beatmap; } private void createTest(IBeatmap beatmap, Action<TestDrawableScrollingRuleset> overrideAction = null) => AddStep("create test", () => { var ruleset = new TestScrollingRuleset(); drawableRuleset = (TestDrawableScrollingRuleset)ruleset.CreateDrawableRulesetWith(CreateWorkingBeatmap(beatmap).GetPlayableBeatmap(ruleset.RulesetInfo)); drawableRuleset.FrameStablePlayback = false; overrideAction?.Invoke(drawableRuleset); Child = new Container { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.Y, Height = 0.75f, Width = 400, Masking = true, Clock = new FramedClock(testClock), Child = drawableRuleset }; }); #region Ruleset private class TestScrollingRuleset : Ruleset { public override IEnumerable<Mod> GetModsFor(ModType type) => throw new NotImplementedException(); public override DrawableRuleset CreateDrawableRulesetWith(IBeatmap beatmap, IReadOnlyList<Mod> mods = null) => new TestDrawableScrollingRuleset(this, beatmap, mods); public override IBeatmapConverter CreateBeatmapConverter(IBeatmap beatmap) => new TestBeatmapConverter(beatmap, null); public override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => throw new NotImplementedException(); public override string Description { get; } = string.Empty; public override string ShortName { get; } = string.Empty; } private class TestDrawableScrollingRuleset : DrawableScrollingRuleset<TestHitObject> { public bool RelativeScaleBeatLengthsOverride { get; set; } protected override bool RelativeScaleBeatLengths => RelativeScaleBeatLengthsOverride; protected override ScrollVisualisationMethod VisualisationMethod => ScrollVisualisationMethod.Overlapping; public new Bindable<double> TimeRange => base.TimeRange; public TestDrawableScrollingRuleset(Ruleset ruleset, IBeatmap beatmap, IReadOnlyList<Mod> mods = null) : base(ruleset, beatmap, mods) { TimeRange.Value = time_range; } public override DrawableHitObject<TestHitObject> CreateDrawableRepresentation(TestHitObject h) => new DrawableTestHitObject(h); protected override PassThroughInputManager CreateInputManager() => new PassThroughInputManager(); protected override Playfield CreatePlayfield() => new TestPlayfield(); } private class TestPlayfield : ScrollingPlayfield { public TestPlayfield() { AddInternal(new Container { RelativeSizeAxes = Axes.Both, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Alpha = 0.2f, }, new Container { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Top = 150 }, Children = new Drawable[] { new Box { Anchor = Anchor.TopCentre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.X, Height = 2, Colour = Color4.Green }, HitObjectContainer } } } }); } } private class TestBeatmapConverter : BeatmapConverter<TestHitObject> { public TestBeatmapConverter(IBeatmap beatmap, Ruleset ruleset) : base(beatmap, ruleset) { } public override bool CanConvert() => true; protected override IEnumerable<TestHitObject> ConvertHitObject(HitObject original, IBeatmap beatmap) { yield return new TestHitObject { StartTime = original.StartTime, EndTime = (original as IHasEndTime)?.EndTime ?? (original.StartTime + 100) }; } } #endregion #region HitObject private class TestHitObject : ConvertHitObject, IHasEndTime { public double EndTime { get; set; } public double Duration => EndTime - StartTime; } private class DrawableTestHitObject : DrawableHitObject<TestHitObject> { public DrawableTestHitObject(TestHitObject hitObject) : base(hitObject) { Anchor = Anchor.TopCentre; Origin = Anchor.TopCentre; Size = new Vector2(100, 25); AddRangeInternal(new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.LightPink }, new Box { Origin = Anchor.CentreLeft, RelativeSizeAxes = Axes.X, Height = 2, Colour = Color4.Red } }); } } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using JustRunnerChat.Areas.HelpPage.Models; namespace JustRunnerChat.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Globalization; ///<summary> ///System.Globalization.CharUnicodeInfo.GetUnicodeCategory(System.String,System.Int32) ///</summary> public class CharUnicodeInfoGetUnicodeCategory { public String str = "Aa\u1fa8\u02b0\u404e\u0300\u0903\u0488\u0030\u16ee\u00b2\u0020\u2028\u2029\0\u00ad\ud800\ue000\u005f\u002d()\u00ab\u00bb!+$^\u00a6\u0242"; public static int Main() { CharUnicodeInfoGetUnicodeCategory testObj = new CharUnicodeInfoGetUnicodeCategory(); TestLibrary.TestFramework.BeginTestCase("for method of System.Globalization.CharUnicodeInfo.GetUnicodeCategory"); if (testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; retVal = PosTest7() && retVal; retVal = PosTest8() && retVal; retVal = PosTest9() && retVal; retVal = PosTest10() && retVal; retVal = PosTest11() && retVal; retVal = PosTest12() && retVal; retVal = PosTest13() && retVal; retVal = PosTest14() && retVal; retVal = PosTest15() && retVal; retVal = PosTest16() && retVal; retVal = PosTest17() && retVal; retVal = PosTest18() && retVal; retVal = PosTest19() && retVal; retVal = PosTest20() && retVal; retVal = PosTest21() && retVal; retVal = PosTest22() && retVal; retVal = PosTest23() && retVal; retVal = PosTest24() && retVal; retVal = PosTest25() && retVal; retVal = PosTest26() && retVal; retVal = PosTest27() && retVal; retVal = PosTest28() && retVal; retVal = PosTest29() && retVal; retVal = PosTest30() && retVal; retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; return retVal; } #region Positive Test Logic public bool PosTest1() { bool retVal = true; Char ch = 'A'; int expectedValue = (int)UnicodeCategory.UppercaseLetter; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest1:Test the method with upper letter"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(str,0)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("001", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ") when char is '" + ch + "'"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; Char ch = 'a'; int expectedValue = (int)UnicodeCategory.LowercaseLetter; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest2:Test the method with low case char"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(str,1)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("003", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; Char ch = '\0'; int expectedValue = (int)UnicodeCategory.TitlecaseLetter; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest3:Test the method with '\\0'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(str,2)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("005", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; Char ch = '\u02b0'; int expectedValue = (int)UnicodeCategory.ModifierLetter; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest4:Test the method with '\\u02b0'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(str,3)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("007", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; Char ch = '\u404e'; int expectedValue = (int)UnicodeCategory.OtherLetter; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest5:Test the method with '\\u404e'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(str,4)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("009", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; Char ch = '\u0300'; int expectedValue = (int)UnicodeCategory.NonSpacingMark; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest6:Test the method with '\\u0300'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(str,5)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("011", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest7() { bool retVal = true; Char ch = '\u0903'; int expectedValue = (int)UnicodeCategory.SpacingCombiningMark; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest7:Test the method with '\\u0903'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(str,6)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("013", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("014", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest8() { bool retVal = true; Char ch = '\u0488'; int expectedValue = (int)UnicodeCategory.EnclosingMark; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest8:Test the method with '\\u0488'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(str,7)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("017", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("018", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest9() { bool retVal = true; Char ch = '0'; int expectedValue = (int)UnicodeCategory.DecimalDigitNumber; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest9:Test the method with '0'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(str,8)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("017", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("018", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest10() { bool retVal = true; Char ch = '\u16ee'; int expectedValue = (int)UnicodeCategory.LetterNumber; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest10:Test the method with '\\u16ee'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(str,9)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("019", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("020", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest11() { bool retVal = true; Char ch = '\u00b2'; int expectedValue = (int)UnicodeCategory.OtherNumber; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest11:Test the method with '\\u00b2'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(str,10)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("021", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("022", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest12() { bool retVal = true; Char ch = '\u0020'; int expectedValue = (int)UnicodeCategory.SpaceSeparator; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest12:Test the method with '\\u0020'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(str,11)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("023", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("024", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest13() { bool retVal = true; Char ch = '\u2028'; int expectedValue = (int)UnicodeCategory.LineSeparator; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest13:Test the method with '\\u2028'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(str,12)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("025", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("026", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest14() { bool retVal = true; Char ch = '\u2029'; int expectedValue = (int)UnicodeCategory.ParagraphSeparator; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest14:Test the method with '\\u2029'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(str,13)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("027", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("028", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest15() { bool retVal = true; Char ch = '\0'; int expectedValue = (int)UnicodeCategory.Control; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest15:Test the method with '\\0'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(str,14)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("029", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("030", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest16() { bool retVal = true; Char ch = '\u00ad'; int expectedValue = (int)UnicodeCategory.Format; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest16:Test the method with '\\u00ad'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(str,15)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("031", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("032", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest17() { bool retVal = true; Char ch = '\ud800'; int expectedValue = (int)UnicodeCategory.Surrogate; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest17:Test the method with '\\ud800'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(str,16)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("033", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("034", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest18() { bool retVal = true; Char ch = '\ue000'; int expectedValue = (int)UnicodeCategory.PrivateUse; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest18:Test the method with '\\ue000'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(str,17)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("035", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("036", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest19() { bool retVal = true; Char ch = '\u005f'; int expectedValue = (int)UnicodeCategory.ConnectorPunctuation; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest19:Test the method with '\\u005f'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(str,18)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("037", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("038", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest20() { bool retVal = true; Char ch = '-'; int expectedValue = (int)UnicodeCategory.DashPunctuation; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest20:Test the method with '-'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(str,19)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("039", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("040", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest21() { bool retVal = true; Char ch = '('; int expectedValue = (int)UnicodeCategory.OpenPunctuation; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest21:Test the method with '('"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(str,20)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("041", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("042", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest22() { bool retVal = true; Char ch = ')'; int expectedValue = (int)UnicodeCategory.ClosePunctuation; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest22:Test the method with ')'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(str,21)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("043", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("044", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest23() { bool retVal = true; Char ch = '\u00ab'; int expectedValue = (int)UnicodeCategory.InitialQuotePunctuation; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest23:Test the method with '\\u00ab'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(str,22)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("045", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("046", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest24() { bool retVal = true; Char ch = '\u00bb'; int expectedValue = (int)UnicodeCategory.FinalQuotePunctuation; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest24:Test the method with '\\u00bb'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(str,23)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("047", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("048", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest25() { bool retVal = true; Char ch = '!'; int expectedValue = (int)UnicodeCategory.OtherPunctuation; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest25:Test the method with '!'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(str,24)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("049", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("050", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest26() { bool retVal = true; Char ch = '+'; int expectedValue = (int)UnicodeCategory.MathSymbol; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest26:Test the method with '+'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(str,25)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("051", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("052", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest27() { bool retVal = true; Char ch = '$'; int expectedValue = (int)UnicodeCategory.CurrencySymbol; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest27:Test the method with '$'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(str,26)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("053", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("054", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest28() { bool retVal = true; Char ch = '^'; int expectedValue = (int)UnicodeCategory.ModifierSymbol; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest28:Test the method with '^'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(str,27)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("055", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("056", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest29() { bool retVal = true; Char ch = '\u00a6'; int expectedValue = (int)UnicodeCategory.OtherSymbol; int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest29:Test the method with '\\u00a6'"); try { actualValue = (int)(CharUnicodeInfo.GetUnicodeCategory(str,28)); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("057", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("058", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest30() { bool retVal = true; Char ch = '\u0242'; // The values 0242 thru 024F on the Mac PPC (which is unicode 4.0) are OtherNotAssigned // On Whidbey (QFE branch), Telesto and Intel Mac this 0242 has the value of LowercaseLetter int expectedValue = (int)UnicodeCategory.LowercaseLetter; if ((!TestLibrary.Utilities.IsWindows) && (TestLibrary.Utilities.IsBigEndian)) { expectedValue = (int)UnicodeCategory.OtherNotAssigned; } int actualValue; TestLibrary.TestFramework.BeginScenario("PosTest30:Test the method with '\\u0242'"); try { actualValue = (int) CharUnicodeInfo.GetUnicodeCategory(str,29); if (expectedValue != actualValue) { TestLibrary.TestFramework.LogError("059", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("060", "when char is '" + ch + "',Unexpected exception:" + e); retVal = false; } return retVal; } #endregion #region Negative Test Logic public bool NegTest1() { bool retVal = true; String testStr = null; int actualValue; TestLibrary.TestFramework.BeginScenario("NegTest1:Invoke the method with null string"); try { actualValue = (int)CharUnicodeInfo.GetUnicodeCategory(testStr, 0); TestLibrary.TestFramework.LogError("061", "No ArgumentNullExcepthion thrown out expected."); retVal = false; } catch (ArgumentNullException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("062", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; int actualValue; String testStr = TestLibrary.Generator.GetString(-55, false,1,5); TestLibrary.TestFramework.BeginScenario("NegTest2:Invoke the method with index out of left range."); try { actualValue = (int)CharUnicodeInfo.GetUnicodeCategory(testStr, -1); TestLibrary.TestFramework.LogError("063", "No ArgumentNullExcepthion thrown out expected."); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("064", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; int actualValue; String testStr = TestLibrary.Generator.GetString(-55, false,1,5); TestLibrary.TestFramework.BeginScenario("NegTest3:Invoke the method with index out of right range"); try { actualValue = (int)CharUnicodeInfo.GetUnicodeCategory(testStr, 6); TestLibrary.TestFramework.LogError("065", "No ArgumentNullExcepthion thrown out expected."); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("066", "Unexpected exception:" + e); retVal = false; } return retVal; } #endregion }
using System; using LanguageExt; using System.Linq; using System.Collections.Generic; using System.Runtime.ExceptionServices; using System.Threading.Tasks; using LanguageExt.TypeClasses; using static LanguageExt.Prelude; namespace LanguageExt { public static partial class TaskT { // // Collections // public static async Task<Arr<B>> Traverse<A, B>(this Arr<Task<A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Map(async a => f(await a))); return new Arr<B>(rb); } public static async Task<HashSet<B>> Traverse<A, B>(this HashSet<Task<A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Map(async a => f(await a))); return new HashSet<B>(rb); } [Obsolete("use TraverseSerial or TraverseParallel instead")] public static Task<IEnumerable<B>> Traverse<A, B>(this IEnumerable<Task<A>> ma, Func<A, B> f) => TraverseParallel(ma, f); public static async Task<IEnumerable<B>> TraverseSerial<A, B>(this IEnumerable<Task<A>> ma, Func<A, B> f) { var rb = new List<B>(); foreach (var a in ma) { rb.Add(f(await a)); } return rb; } public static Task<IEnumerable<B>> TraverseParallel<A, B>(this IEnumerable<Task<A>> ma, int windowSize, Func<A, B> f) => ma.WindowMap(windowSize, f).Map(xs => (IEnumerable<B>)xs); public static Task<IEnumerable<B>> TraverseParallel<A, B>(this IEnumerable<Task<A>> ma, Func<A, B> f) => ma.WindowMap(f).Map(xs => (IEnumerable<B>)xs); [Obsolete("use TraverseSerial or TraverseParallel instead")] public static Task<IEnumerable<A>> Sequence<A>(this IEnumerable<Task<A>> ma) => TraverseParallel(ma, Prelude.identity); public static Task<IEnumerable<A>> SequenceSerial<A>(this IEnumerable<Task<A>> ma) => TraverseSerial(ma, Prelude.identity); public static Task<IEnumerable<A>> SequenceParallel<A>(this IEnumerable<Task<A>> ma) => TraverseParallel(ma, Prelude.identity); public static Task<IEnumerable<A>> SequenceParallel<A>(this IEnumerable<Task<A>> ma, int windowSize) => TraverseParallel(ma, windowSize, Prelude.identity); public static async Task<Lst<B>> Traverse<A, B>(this Lst<Task<A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Map(async a => f(await a))); return new Lst<B>(rb); } public static async Task<Que<B>> Traverse<A, B>(this Que<Task<A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Map(async a => f(await a))); return new Que<B>(rb); } [Obsolete("use TraverseSerial or TraverseParallel instead")] public static Task<Seq<B>> Traverse<A, B>(this Seq<Task<A>> ma, Func<A, B> f) => TraverseParallel(ma, f); public static async Task<Seq<B>> TraverseSerial<A, B>(this Seq<Task<A>> ma, Func<A, B> f) { var rb = new List<B>(); foreach (var a in ma) { rb.Add(f(await a)); } return Seq.FromArray<B>(rb.ToArray()); } public static Task<Seq<B>> TraverseParallel<A, B>(this Seq<Task<A>> ma, int windowSize, Func<A, B> f) => ma.WindowMap(windowSize, f).Map(xs => Seq(xs)); public static Task<Seq<B>> TraverseParallel<A, B>(this Seq<Task<A>> ma, Func<A, B> f) => ma.WindowMap(f).Map(xs => Seq(xs)); [Obsolete("use TraverseSerial or TraverseParallel instead")] public static Task<Seq<A>> Sequence<A>(this Seq<Task<A>> ma) => TraverseParallel(ma, Prelude.identity); public static Task<Seq<A>> SequenceSerial<A>(this Seq<Task<A>> ma) => TraverseSerial(ma, Prelude.identity); public static Task<Seq<A>> SequenceParallel<A>(this Seq<Task<A>> ma) => TraverseParallel(ma, Prelude.identity); public static Task<Seq<A>> SequenceParallel<A>(this Seq<Task<A>> ma, int windowSize) => TraverseParallel(ma, windowSize, Prelude.identity); public static async Task<Set<B>> Traverse<A, B>(this Set<Task<A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Map(async a => f(await a))); return new Set<B>(rb); } public static async Task<Stck<B>> Traverse<A, B>(this Stck<Task<A>> ma, Func<A, B> f) { var rb = await Task.WhenAll(ma.Reverse().Map(async a => f(await a))); return new Stck<B>(rb); } // // Async types // public static async Task<EitherAsync<L, B>> Traverse<L, A, B>(this EitherAsync<L, Task<A>> ma, Func<A, B> f) { var da = await ma.Data; if (da.State == EitherStatus.IsBottom) throw new BottomException(); if (da.State == EitherStatus.IsLeft) return EitherAsync<L, B>.Left(da.Left); var a = await da.Right; if(da.Right.IsFaulted) ExceptionDispatchInfo.Capture(da.Right.Exception.InnerException).Throw(); return EitherAsync<L, B>.Right(f(a)); } public static async Task<OptionAsync<B>> Traverse<A, B>(this OptionAsync<Task<A>> ma, Func<A, B> f) { var (s, v) = await ma.Data; if (!s) return OptionAsync<B>.None; var a = await v; if (v.IsFaulted) ExceptionDispatchInfo.Capture(v.Exception.InnerException).Throw(); return OptionAsync<B>.Some(f(a)); } public static async Task<TryAsync<B>> Traverse<A, B>(this TryAsync<Task<A>> ma, Func<A, B> f) { var da = await ma.Try(); if (da.IsBottom) throw new BottomException(); if (da.IsFaulted) return TryAsyncFail<B>(da.Exception); var a = await da.Value; if(da.Value.IsFaulted) ExceptionDispatchInfo.Capture(da.Value.Exception.InnerException).Throw(); return TryAsyncSucc(f(a)); } public static async Task<TryOptionAsync<B>> Traverse<A, B>(this TryOptionAsync<Task<A>> ma, Func<A, B> f) { var da = await ma.Try(); if (da.IsBottom) throw new BottomException(); if (da.IsNone) return TryOptionalAsync<B>(None); if (da.IsFaulted) return TryOptionAsyncFail<B>(da.Exception); var a = await da.Value.Value; if(da.Value.Value.IsFaulted) ExceptionDispatchInfo.Capture(da.Value.Value.Exception.InnerException).Throw(); return TryOptionAsyncSucc(f(a)); } public static async Task<Task<B>> Traverse<A, B>(this Task<Task<A>> ma, Func<A, B> f) { var da = await ma; if (ma.IsFaulted) return TaskFail<B>(da.Exception); var a = await da; if (da.IsFaulted) ExceptionDispatchInfo.Capture(da.Exception.InnerException).Throw(); return TaskSucc(f(a)); } // // Sync types // public static async Task<Either<L, B>> Traverse<L, A, B>(this Either<L, Task<A>> ma, Func<A, B> f) { if (ma.IsBottom) return Either<L, B>.Bottom; else if (ma.IsLeft) return Either<L, B>.Left(ma.LeftValue); return Either<L, B>.Right(f(await ma.RightValue)); } public static async Task<EitherUnsafe<L, B>> Traverse<L, A, B>(this EitherUnsafe<L, Task<A>> ma, Func<A, B> f) { if (ma.IsBottom) return EitherUnsafe<L, B>.Bottom; else if (ma.IsLeft) return EitherUnsafe<L, B>.Left(ma.LeftValue); return EitherUnsafe<L, B>.Right(f(await ma.RightValue)); } public static async Task<Identity<B>> Traverse<A, B>(this Identity<Task<A>> ma, Func<A, B> f) => new Identity<B>(f(await ma.Value)); public static async Task<Option<B>> Traverse<A, B>(this Option<Task<A>> ma, Func<A, B> f) { if (ma.IsNone) return Option<B>.None; return Option<B>.Some(f(await ma.Value)); } public static async Task<OptionUnsafe<B>> Traverse<A, B>(this OptionUnsafe<Task<A>> ma, Func<A, B> f) { if (ma.IsNone) return OptionUnsafe<B>.None; return OptionUnsafe<B>.Some(f(await ma.Value)); } public static async Task<Try<B>> Traverse<A, B>(this Try<Task<A>> ma, Func<A, B> f) { var mr = ma.Try(); if (mr.IsBottom) return Try<B>(BottomException.Default); else if (mr.IsFaulted) return Try<B>(mr.Exception); return Try<B>(f(await mr.Value)); } public static async Task<TryOption<B>> Traverse<A, B>(this TryOption<Task<A>> ma, Func<A, B> f) { var mr = ma.Try(); if (mr.IsBottom) return TryOptionFail<B>(BottomException.Default); else if (mr.IsNone) return TryOption<B>(None); else if (mr.IsFaulted) return TryOption<B>(mr.Exception); return TryOption<B>(f(await mr.Value.Value)); } public static async Task<Validation<Fail, B>> Traverse<Fail, A, B>(this Validation<Fail, Task<A>> ma, Func<A, B> f) { if (ma.IsFail) return Validation<Fail, B>.Fail(ma.FailValue); return Validation<Fail, B>.Success(f(await ma.SuccessValue)); } public static async Task<Validation<MonoidFail, Fail, B>> Traverse<MonoidFail, Fail, A, B>(this Validation<MonoidFail, Fail, Task<A>> ma, Func<A, B> f) where MonoidFail : struct, Monoid<Fail>, Eq<Fail> { if (ma.IsFail) return Validation<MonoidFail, Fail, B>.Fail(ma.FailValue); return Validation<MonoidFail, Fail, B>.Success(f(await ma.SuccessValue)); } } }
// Class name is always file base name with "Class" appended: // /// <summary> /// VTK test class /// </summary> public class vtkObjectTestClass { // Static void method with same signature as "Main" is always // file base name: // /// <summary> /// VTK test Main method /// </summary> public static void vtkObjectTest(string[] args) { // Reference a method in the Kitware.VTK assembly: // (forces the Kitware.VTK assembly to load...) // string version = Kitware.VTK.vtkVersion.GetVTKSourceVersion(); string assemblyname = "Kitware.VTK"; bool listAllAssemblies = false; bool listAllClasses = false; bool collectingClassNames = false; System.Collections.Hashtable classnames = new System.Collections.Hashtable(); System.Collections.Hashtable classtypes = new System.Collections.Hashtable(); for (int i = 0; i < args.Length; ++i) { string s = args[i]; if (s == "--assemblyname") { collectingClassNames = false; if (i < args.Length - 1) { assemblyname = args[i + 1]; } else { throw new System.Exception("--assemblyname used, but no name given"); } } else if (s == "--classname") { collectingClassNames = false; if (i < args.Length - 1) { classnames.Add(args[i + 1], args[i + 1]); } else { throw new System.Exception("--classname used, but no name given"); } } else if (s == "--classnames") { collectingClassNames = true; } else if (s == "--classnames-file") { if (i < args.Length - 1) { ReadClassNamesFromFile(classnames, args[i + 1]); } else { throw new System.Exception("--classnames-file used, but no filename given"); } } else if (s == "--list-all-classes") { collectingClassNames = false; listAllClasses = true; } else if (s == "--list-all-assemblies") { collectingClassNames = false; listAllAssemblies = true; } else if (collectingClassNames) { classnames.Add(s, s); } } if (0 == classnames.Count) { classnames.Add("vtkObject", "vtkObject"); } // Find the assembly containing the class to instantiate: // System.Reflection.Assembly[] assemblies = System.AppDomain.CurrentDomain.GetAssemblies(); System.Reflection.Assembly assembly = null; foreach (System.Reflection.Assembly a in assemblies) { System.Reflection.AssemblyName aname = a.GetName(); if (aname.FullName == assemblyname || aname.Name == assemblyname) { assembly = a; } if (listAllAssemblies) { //System.Console.Error.WriteLine(aname.Name); System.Console.Error.WriteLine(aname.FullName); } } if (listAllAssemblies) { return; } // Find the type of the class to instantiate: // if (assembly != null) { foreach (System.Type et in assembly.GetExportedTypes()) { if (listAllClasses) { System.Console.Error.WriteLine(et.Name); System.Console.Error.WriteLine(et.AssemblyQualifiedName); } if (classnames.ContainsKey(et.Name)) { classtypes.Add(et.Name, et); } if (classnames.ContainsKey(et.AssemblyQualifiedName)) { classtypes.Add(et.AssemblyQualifiedName, et); } } if (listAllClasses) { return; } } if (0 == classtypes.Count) { throw new System.ArgumentException(System.String.Format( "error: did not find any Type objects... Typo in command line args?")); } // Instantiate and print each type: // string classname = ""; System.Type classtype = null; System.Console.Error.WriteLine(""); System.Console.Error.WriteLine("CTEST_FULL_OUTPUT (Avoid ctest truncation of output)"); System.Console.Error.WriteLine(""); System.Console.Error.WriteLine(System.String.Format("classtypes.Count: {0}", classtypes.Count)); System.Console.Error.WriteLine(""); System.Console.Error.WriteLine(System.String.Format("GetVTKSourceVersion(): '{0}'", version)); System.Console.Error.WriteLine(""); foreach (System.Collections.DictionaryEntry entry in classtypes) { classname = (string) entry.Key; classtype = (System.Type) entry.Value; // Instantiate via "New" method: // System.Console.Error.WriteLine(""); System.Console.Error.WriteLine( "=============================================================================="); System.Console.Error.WriteLine(System.String.Format( "Instantiating and printing class '{0}'", classname)); System.Console.Error.WriteLine(""); // Look for a New method that takes no parameters: // System.Reflection.MethodInfo mi = classtype.GetMethod("New", System.Type.EmptyTypes); if (null == mi) { if (classtype.IsAbstract) { System.Console.Error.WriteLine(System.String.Format( "No 'New' method in abstract class '{0}'. Test passes without instantiating or printing an object.", classname)); } else { System.Console.Error.WriteLine(System.String.Format( "No 'New' method in concrete class '{0}'. Test passes without instantiating or printing an object.", classname)); //throw new System.ArgumentException(System.String.Format( // "error: could not find 'New' method for concrete class '{0}'", // classname)); } } if (null != mi) { // Assumption: any object we create via a 'New' method will implement // the 'IDisposable' interface... // // 'using' forces an 'o.Dispose' call at the closing curly brace: // using (System.IDisposable o = (System.IDisposable) mi.Invoke(null, null)) { System.Console.Error.WriteLine(o.ToString()); } } System.Console.Error.WriteLine(""); // Instantiate via public default constructor: // //System.Type [] ca = new System.Type[0]; //System.Reflection.ConstructorInfo ci = classtype.GetConstructor(ca); //if (null == ci) // { // throw new System.ArgumentException(System.String.Format( // "error: could not find public default constructor for '{0}'", // classname)); // } // //o = ci.Invoke(null); //System.Console.Error.WriteLine(o.ToString()); } } /// <summary> /// Helper method to read in class names from a file. /// </summary> public static void ReadClassNamesFromFile(System.Collections.Hashtable classnames, string filename) { System.IO.StreamReader file = new System.IO.StreamReader(filename); string line; while ((line = file.ReadLine()) != null) { classnames.Add(line, line); } file.Close(); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using Apache.Ignite.Core; using Apache.Ignite.Core.Binary; namespace Apache.Ignite.Examples.Datagrid { using Apache.Ignite.ExamplesDll.Binary; /// <summary> /// This example demonstrates several put-get operations on Ignite cache /// with binary values. Note that binary object can be retrieved in /// fully-deserialized form or in binary object format using special /// cache projection. /// <para /> /// 1) Build the project Apache.Ignite.ExamplesDll (select it -> right-click -> Build). /// Apache.Ignite.ExamplesDll.dll must appear in %IGNITE_HOME%/platforms/dotnet/examples/Apache.Ignite.ExamplesDll/bin/${Platform]/${Configuration} folder. /// 2) Set this class as startup object (Apache.Ignite.Examples project -> right-click -> Properties -> /// Application -> Startup object); /// 3) Start example (F5 or Ctrl+F5). /// <para /> /// This example can be run with standalone Apache Ignite.NET node: /// 1) Run %IGNITE_HOME%/platforms/dotnet/bin/Apache.Ignite.exe: /// Apache.Ignite.exe -IgniteHome="%IGNITE_HOME%" -springConfigUrl=platforms\dotnet\examples\config\example-cache.xml -assembly=[path_to_Apache.Ignite.ExamplesDll.dll] /// 2) Start example. /// </summary> public class PutGetExample { /// <summary>Cache name.</summary> private const string CacheName = "cache_put_get"; /// <summary> /// Runs the example. /// </summary> [STAThread] public static void Main() { var cfg = new IgniteConfiguration { SpringConfigUrl = @"platforms\dotnet\examples\config\example-cache.xml", JvmOptions = new List<string> { "-Xms512m", "-Xmx1024m" } }; using (var ignite = Ignition.Start(cfg)) { Console.WriteLine(); Console.WriteLine(">>> Cache put-get example started."); // Clean up caches on all nodes before run. ignite.GetOrCreateCache<object, object>(CacheName).Clear(); PutGet(ignite); PutGetBinary(ignite); PutAllGetAll(ignite); PutAllGetAllBinary(ignite); Console.WriteLine(); } Console.WriteLine(); Console.WriteLine(">>> Example finished, press any key to exit ..."); Console.ReadKey(); } /// <summary> /// Execute individual Put and Get. /// </summary> /// <param name="ignite">Ignite instance.</param> private static void PutGet(IIgnite ignite) { var cache = ignite.GetCache<int, Organization>(CacheName); // Create new Organization to store in cache. Organization org = new Organization( "Microsoft", new Address("1096 Eddy Street, San Francisco, CA", 94109), OrganizationType.Private, DateTime.Now ); // Put created data entry to cache. cache.Put(1, org); // Get recently created employee as a strongly-typed fully de-serialized instance. Organization orgFromCache = cache.Get(1); Console.WriteLine(); Console.WriteLine(">>> Retrieved organization instance from cache: " + orgFromCache); } /// <summary> /// Execute individual Put and Get, getting value in binary format, without de-serializing it. /// </summary> /// <param name="ignite">Ignite instance.</param> private static void PutGetBinary(IIgnite ignite) { var cache = ignite.GetCache<int, Organization>(CacheName); // Create new Organization to store in cache. Organization org = new Organization( "Microsoft", new Address("1096 Eddy Street, San Francisco, CA", 94109), OrganizationType.Private, DateTime.Now ); // Put created data entry to cache. cache.Put(1, org); // Create projection that will get values as binary objects. var binaryCache = cache.WithKeepBinary<int, IBinaryObject>(); // Get recently created organization as a binary object. var binaryOrg = binaryCache.Get(1); // Get organization's name from binary object (note that object doesn't need to be fully deserialized). string name = binaryOrg.GetField<string>("name"); Console.WriteLine(); Console.WriteLine(">>> Retrieved organization name from binary object: " + name); } /// <summary> /// Execute bulk Put and Get operations. /// </summary> /// <param name="ignite">Ignite instance.</param> private static void PutAllGetAll(IIgnite ignite) { var cache = ignite.GetCache<int, Organization>(CacheName); // Create new Organizations to store in cache. Organization org1 = new Organization( "Microsoft", new Address("1096 Eddy Street, San Francisco, CA", 94109), OrganizationType.Private, DateTime.Now ); Organization org2 = new Organization( "Red Cross", new Address("184 Fidler Drive, San Antonio, TX", 78205), OrganizationType.NonProfit, DateTime.Now ); var map = new Dictionary<int, Organization> { { 1, org1 }, { 2, org2 } }; // Put created data entries to cache. cache.PutAll(map); // Get recently created organizations as a strongly-typed fully de-serialized instances. IDictionary<int, Organization> mapFromCache = cache.GetAll(new List<int> { 1, 2 }); Console.WriteLine(); Console.WriteLine(">>> Retrieved organization instances from cache:"); foreach (Organization org in mapFromCache.Values) Console.WriteLine(">>> " + org); } /// <summary> /// Execute bulk Put and Get operations getting values in binary format, without de-serializing it. /// </summary> /// <param name="ignite">Ignite instance.</param> private static void PutAllGetAllBinary(IIgnite ignite) { var cache = ignite.GetCache<int, Organization>(CacheName); // Create new Organizations to store in cache. Organization org1 = new Organization( "Microsoft", new Address("1096 Eddy Street, San Francisco, CA", 94109), OrganizationType.Private, DateTime.Now ); Organization org2 = new Organization( "Red Cross", new Address("184 Fidler Drive, San Antonio, TX", 78205), OrganizationType.NonProfit, DateTime.Now ); var map = new Dictionary<int, Organization> { { 1, org1 }, { 2, org2 } }; // Put created data entries to cache. cache.PutAll(map); // Create projection that will get values as binary objects. var binaryCache = cache.WithKeepBinary<int, IBinaryObject>(); // Get recently created organizations as binary objects. IDictionary<int, IBinaryObject> binaryMap = binaryCache.GetAll(new List<int> { 1, 2 }); Console.WriteLine(); Console.WriteLine(">>> Retrieved organization names from binary objects:"); foreach (IBinaryObject poratbleOrg in binaryMap.Values) Console.WriteLine(">>> " + poratbleOrg.GetField<string>("name")); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using QuantConnect.Benchmarks; using QuantConnect.Data; using QuantConnect.Data.UniverseSelection; using QuantConnect.Interfaces; using QuantConnect.Lean.Engine.DataFeeds.Enumerators.Factories; using QuantConnect.Logging; using QuantConnect.Securities; using QuantConnect.Util; using QuantConnect.Data.Fundamental; namespace QuantConnect.Lean.Engine.DataFeeds { /// <summary> /// Provides methods for apply the results of universe selection to an algorithm /// </summary> public class UniverseSelection { private IDataFeedSubscriptionManager _dataManager; private readonly IAlgorithm _algorithm; private readonly ISecurityService _securityService; private readonly Dictionary<DateTime, Dictionary<Symbol, Security>> _pendingSecurityAdditions = new Dictionary<DateTime, Dictionary<Symbol, Security>>(); private readonly PendingRemovalsManager _pendingRemovalsManager; private readonly CurrencySubscriptionDataConfigManager _currencySubscriptionDataConfigManager; private readonly InternalSubscriptionManager _internalSubscriptionManager; private bool _initializedSecurityBenchmark; private readonly IDataProvider _dataProvider; private bool _anyDoesNotHaveFundamentalDataWarningLogged; private readonly SecurityChangesConstructor _securityChangesConstructor; /// <summary> /// Initializes a new instance of the <see cref="UniverseSelection"/> class /// </summary> /// <param name="algorithm">The algorithm to add securities to</param> /// <param name="securityService">The security service</param> /// <param name="dataPermissionManager">The data permissions manager</param> /// <param name="dataProvider">The data provider to use</param> /// <param name="internalConfigResolution">The resolution to use for internal configuration</param> public UniverseSelection( IAlgorithm algorithm, ISecurityService securityService, IDataPermissionManager dataPermissionManager, IDataProvider dataProvider, Resolution internalConfigResolution = Resolution.Minute) { _dataProvider = dataProvider; _algorithm = algorithm; _securityService = securityService; _pendingRemovalsManager = new PendingRemovalsManager(algorithm.Transactions); _currencySubscriptionDataConfigManager = new CurrencySubscriptionDataConfigManager(algorithm.Portfolio.CashBook, algorithm.Securities, algorithm.SubscriptionManager, _securityService, Resolution.Minute); // TODO: next step is to merge currency internal subscriptions under the same 'internal manager' instance and we could move this directly into the DataManager class _internalSubscriptionManager = new InternalSubscriptionManager(_algorithm, internalConfigResolution); _securityChangesConstructor = new SecurityChangesConstructor(); } /// <summary> /// Sets the data manager /// </summary> public void SetDataManager(IDataFeedSubscriptionManager dataManager) { if (_dataManager != null) { throw new Exception("UniverseSelection.SetDataManager(): can only be set once"); } _dataManager = dataManager; _internalSubscriptionManager.Added += (sender, request) => { _dataManager.AddSubscription(request); }; _internalSubscriptionManager.Removed += (sender, request) => { _dataManager.RemoveSubscription(request.Configuration); }; } /// <summary> /// Applies universe selection the the data feed and algorithm /// </summary> /// <param name="universe">The universe to perform selection on</param> /// <param name="dateTimeUtc">The current date time in utc</param> /// <param name="universeData">The data provided to perform selection with</param> public SecurityChanges ApplyUniverseSelection(Universe universe, DateTime dateTimeUtc, BaseDataCollection universeData) { var algorithmEndDateUtc = _algorithm.EndDate.ConvertToUtc(_algorithm.TimeZone); if (dateTimeUtc > algorithmEndDateUtc) { return SecurityChanges.None; } IEnumerable<Symbol> selectSymbolsResult; // check if this universe must be filtered with fine fundamental data var fineFiltered = universe as FineFundamentalFilteredUniverse; if (fineFiltered != null // if the universe has been disposed we don't perform selection. This us handled bellow by 'Universe.PerformSelection' // but in this case we directly call 'SelectSymbols' because we want to perform fine selection even if coarse returns the same // symbols, see 'Universe.PerformSelection', which detects this and returns 'Universe.Unchanged' && !universe.DisposeRequested) { // perform initial filtering and limit the result selectSymbolsResult = universe.SelectSymbols(dateTimeUtc, universeData); if (!ReferenceEquals(selectSymbolsResult, Universe.Unchanged)) { // prepare a BaseDataCollection of FineFundamental instances var fineCollection = new BaseDataCollection(); // Create a dictionary of CoarseFundamental keyed by Symbol that also has FineFundamental // Coarse raw data has SID collision on: CRHCY R735QTJ8XC9X var allCoarse = universeData.Data.OfType<CoarseFundamental>(); var coarseData = allCoarse.Where(c => c.HasFundamentalData) .DistinctBy(c => c.Symbol) .ToDictionary(c => c.Symbol); // Remove selected symbols that does not have fine fundamental data var anyDoesNotHaveFundamentalData = false; // only pre filter selected symbols if there actually is any coarse data. This way we can support custom universe filtered by fine fundamental data // which do not use coarse data as underlying, in which case it could happen that we try to load fine fundamental data that is missing, but no problem, // 'FineFundamentalSubscriptionEnumeratorFactory' won't emit it if (allCoarse.Any()) { selectSymbolsResult = selectSymbolsResult .Where( symbol => { var result = coarseData.ContainsKey(symbol); anyDoesNotHaveFundamentalData |= !result; return result; } ); } if (!_anyDoesNotHaveFundamentalDataWarningLogged && anyDoesNotHaveFundamentalData) { _algorithm.Debug("Note: Your coarse selection filter was updated to exclude symbols without fine fundamental data. Make sure your coarse filter excludes symbols where HasFundamental is false."); _anyDoesNotHaveFundamentalDataWarningLogged = true; } // use all available threads, the entire system is waiting for this to complete var options = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }; Parallel.ForEach(selectSymbolsResult, options, symbol => { var config = FineFundamentalUniverse.CreateConfiguration(symbol); var security = _securityService.CreateSecurity(symbol, config, addToSymbolCache: false); var localStartTime = dateTimeUtc.ConvertFromUtc(config.ExchangeTimeZone).AddDays(-1); var factory = new FineFundamentalSubscriptionEnumeratorFactory(_algorithm.LiveMode, x => new[] { localStartTime }); var request = new SubscriptionRequest(true, universe, security, new SubscriptionDataConfig(config), localStartTime, localStartTime); using (var enumerator = factory.CreateEnumerator(request, _dataProvider)) { if (enumerator.MoveNext()) { lock (fineCollection.Data) { fineCollection.Add(enumerator.Current); } } } }); // WARNING -- HACK ATTACK -- WARNING // Fine universes are considered special due to their chaining behavior. // As such, we need a means of piping the fine data read in here back to the data feed // so that it can be properly emitted via a TimeSlice.Create call. There isn't a mechanism // in place for this function to return such data. The following lines are tightly coupled // to the universeData dictionaries in SubscriptionSynchronizer and LiveTradingDataFeed and // rely on reference semantics to work. universeData.Data = new List<BaseData>(); foreach (var fine in fineCollection.Data.OfType<FineFundamental>()) { var fundamentals = new Fundamentals { Symbol = fine.Symbol, Time = fine.Time, EndTime = fine.EndTime, DataType = fine.DataType, AssetClassification = fine.AssetClassification, CompanyProfile = fine.CompanyProfile, CompanyReference = fine.CompanyReference, EarningReports = fine.EarningReports, EarningRatios = fine.EarningRatios, FinancialStatements = fine.FinancialStatements, OperationRatios = fine.OperationRatios, SecurityReference = fine.SecurityReference, ValuationRatios = fine.ValuationRatios, Market = fine.Symbol.ID.Market }; CoarseFundamental coarse; if (coarseData.TryGetValue(fine.Symbol, out coarse)) { // the only time the coarse data won't exist is if the selection function // doesn't use the data provided, and instead returns a constant list of // symbols -- coupled with a potential hole in the data fundamentals.Value = coarse.Value; fundamentals.Volume = coarse.Volume; fundamentals.DollarVolume = coarse.DollarVolume; fundamentals.HasFundamentalData = coarse.HasFundamentalData; // set the fine fundamental price property to yesterday's closing price fine.Value = coarse.Value; } universeData.Add(fundamentals); } // END -- HACK ATTACK -- END // perform the fine fundamental universe selection selectSymbolsResult = fineFiltered.FineFundamentalUniverse.PerformSelection(dateTimeUtc, fineCollection); } } else { // perform initial filtering and limit the result selectSymbolsResult = universe.PerformSelection(dateTimeUtc, universeData); } // materialize the enumerable into a set for processing var selections = selectSymbolsResult.ToHashSet(); // first check for no pending removals, even if the universe selection // didn't change we might need to remove a security because a position was closed RemoveSecurityFromUniverse( _pendingRemovalsManager.CheckPendingRemovals(selections, universe), dateTimeUtc, algorithmEndDateUtc); // check for no changes second if (ReferenceEquals(selectSymbolsResult, Universe.Unchanged)) { return SecurityChanges.None; } // determine which data subscriptions need to be removed from this universe foreach (var member in universe.Securities.Values.OrderBy(member => member.Security.Symbol.SecurityType)) { var security = member.Security; // if we've selected this subscription again, keep it if (selections.Contains(security.Symbol)) continue; // don't remove if the universe wants to keep him in if (!universe.CanRemoveMember(dateTimeUtc, security)) continue; _securityChangesConstructor.Remove(member.Security, member.IsInternal); RemoveSecurityFromUniverse(_pendingRemovalsManager.TryRemoveMember(security, universe), dateTimeUtc, algorithmEndDateUtc); } Dictionary<Symbol, Security> pendingAdditions; if (!_pendingSecurityAdditions.TryGetValue(dateTimeUtc, out pendingAdditions)) { // if the frontier moved forward then we've added these securities to the algorithm _pendingSecurityAdditions.Clear(); // keep track of created securities so we don't create the same security twice, leads to bad things :) pendingAdditions = new Dictionary<Symbol, Security>(); _pendingSecurityAdditions[dateTimeUtc] = pendingAdditions; } // find new selections and add them to the algorithm foreach (var symbol in selections) { if (universe.Securities.ContainsKey(symbol)) { // if its already part of the universe no need to re add it continue; } Security underlying = null; if (symbol.HasUnderlying) { underlying = GetOrCreateSecurity(pendingAdditions, symbol.Underlying, universe.UniverseSettings); } // create the new security, the algorithm thread will add this at the appropriate time var security = GetOrCreateSecurity(pendingAdditions, symbol, universe.UniverseSettings, underlying); var addedSubscription = false; var dataFeedAdded = false; var internalFeed = true; foreach (var request in universe.GetSubscriptionRequests(security, dateTimeUtc, algorithmEndDateUtc, _algorithm.SubscriptionManager.SubscriptionDataConfigService)) { if (security.Symbol == request.Configuration.Symbol // Just in case check its the same symbol, else AddData will throw. && !security.Subscriptions.Contains(request.Configuration)) { // For now this is required for retro compatibility with usages of security.Subscriptions security.AddData(request.Configuration); } var toRemove = _currencySubscriptionDataConfigManager.GetSubscriptionDataConfigToRemove(request.Configuration.Symbol); if (toRemove != null) { Log.Trace($"UniverseSelection.ApplyUniverseSelection(): Removing internal currency data feed {toRemove}"); _dataManager.RemoveSubscription(toRemove); } // 'dataFeedAdded' will help us notify the user for security changes only once per non internal subscription // for example two universes adding the sample configuration, we don't want two notifications dataFeedAdded = _dataManager.AddSubscription(request); // only update our security changes if we actually added data if (!request.IsUniverseSubscription) { addedSubscription = true; // if any config isn't internal then it's not internal internalFeed &= request.Configuration.IsInternalFeed; _internalSubscriptionManager.AddedSubscriptionRequest(request); } } if (addedSubscription) { var addedMember = universe.AddMember(dateTimeUtc, security, internalFeed); if (addedMember && dataFeedAdded) { _securityChangesConstructor.Add(security, internalFeed); } } } var securityChanges = _securityChangesConstructor.Flush(); // Add currency data feeds that weren't explicitly added in Initialize if (securityChanges.AddedSecurities.Count > 0) { EnsureCurrencyDataFeeds(securityChanges); } if (securityChanges != SecurityChanges.None && Log.DebuggingEnabled) { // for performance lets not create the message string if debugging is not enabled // this can be executed many times and its in the algorithm thread Log.Debug("UniverseSelection.ApplyUniverseSelection(): " + dateTimeUtc + ": " + securityChanges); } return securityChanges; } /// <summary> /// Will add any pending internal currency subscriptions /// </summary> /// <param name="utcStart">The current date time in utc</param> /// <returns>Will return true if any subscription was added</returns> public bool AddPendingInternalDataFeeds(DateTime utcStart) { var added = false; if (!_initializedSecurityBenchmark) { _initializedSecurityBenchmark = true; var securityBenchmark = _algorithm.Benchmark as SecurityBenchmark; if (securityBenchmark != null) { var resolution = _algorithm.LiveMode ? Resolution.Minute : Resolution.Hour; // Check that the tradebar subscription we are using can support this resolution GH #5893 var subscriptionType = _algorithm.SubscriptionManager.SubscriptionDataConfigService.LookupSubscriptionConfigDataTypes(securityBenchmark.Security.Type, resolution, securityBenchmark.Security.Symbol.IsCanonical()).First(); var baseInstance = subscriptionType.Item1.GetBaseDataInstance(); baseInstance.Symbol = securityBenchmark.Security.Symbol; var supportedResolutions = baseInstance.SupportedResolutions(); if (!supportedResolutions.Contains(resolution)) { resolution = supportedResolutions.OrderByDescending(x => x).First(); } var subscriptionList = new List<Tuple<Type, TickType>>() {subscriptionType}; var dataConfig = _algorithm.SubscriptionManager.SubscriptionDataConfigService.Add( securityBenchmark.Security.Symbol, resolution, isInternalFeed: true, fillForward: false, subscriptionDataTypes: subscriptionList ).First(); // we want to start from the previous tradable bar so the benchmark security // never has 0 price var previousTradableBar = Time.GetStartTimeForTradeBars( securityBenchmark.Security.Exchange.Hours, utcStart.ConvertFromUtc(securityBenchmark.Security.Exchange.TimeZone), _algorithm.LiveMode ? Time.OneMinute : Time.OneDay, 1, false, dataConfig.DataTimeZone).ConvertToUtc(securityBenchmark.Security.Exchange.TimeZone); if (dataConfig != null) { added |= _dataManager.AddSubscription(new SubscriptionRequest( false, null, securityBenchmark.Security, dataConfig, previousTradableBar, _algorithm.EndDate.ConvertToUtc(_algorithm.TimeZone))); Log.Trace($"UniverseSelection.AddPendingInternalDataFeeds(): Adding internal benchmark data feed {dataConfig}"); } } } if (_currencySubscriptionDataConfigManager.UpdatePendingSubscriptionDataConfigs(_algorithm.BrokerageModel)) { foreach (var subscriptionDataConfig in _currencySubscriptionDataConfigManager .GetPendingSubscriptionDataConfigs()) { var security = _algorithm.Securities[subscriptionDataConfig.Symbol]; added |= _dataManager.AddSubscription(new SubscriptionRequest( false, null, security, subscriptionDataConfig, utcStart, _algorithm.EndDate.ConvertToUtc(_algorithm.TimeZone))); } } return added; } /// <summary> /// Checks the current subscriptions and adds necessary currency pair feeds to provide real time conversion data /// </summary> public void EnsureCurrencyDataFeeds(SecurityChanges securityChanges) { _currencySubscriptionDataConfigManager.EnsureCurrencySubscriptionDataConfigs(securityChanges, _algorithm.BrokerageModel); } private void RemoveSecurityFromUniverse( List<PendingRemovalsManager.RemovedMember> removedMembers, DateTime dateTimeUtc, DateTime algorithmEndDateUtc) { if (removedMembers == null) { return; } foreach (var removedMember in removedMembers) { var universe = removedMember.Universe; var member = removedMember.Security; // safe to remove the member from the universe universe.RemoveMember(dateTimeUtc, member); // we need to mark this security as untradeable while it has no data subscription // it is expected that this function is called while in sync with the algo thread, // so we can make direct edits to the security here member.Cache.Reset(); foreach (var subscription in universe.GetSubscriptionRequests(member, dateTimeUtc, algorithmEndDateUtc, _algorithm.SubscriptionManager.SubscriptionDataConfigService)) { if (_dataManager.RemoveSubscription(subscription.Configuration, universe)) { _internalSubscriptionManager.RemovedSubscriptionRequest(subscription); member.IsTradable = false; } } } } private Security GetOrCreateSecurity(Dictionary<Symbol, Security> pendingAdditions, Symbol symbol, UniverseSettings universeSettings, Security underlying = null) { // create the new security, the algorithm thread will add this at the appropriate time Security security; if (!pendingAdditions.TryGetValue(symbol, out security) && !_algorithm.Securities.TryGetValue(symbol, out security)) { security = _securityService.CreateSecurity(symbol, new List<SubscriptionDataConfig>(), universeSettings.Leverage, symbol.ID.SecurityType.IsOption(), underlying); pendingAdditions.Add(symbol, security); } return security; } } }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.ComponentModel; namespace WeifenLuo.WinFormsUI.Docking { internal class VS2012LightDockPaneStrip : DockPaneStripBase { private class TabVS2012Light : Tab { public TabVS2012Light(IDockContent content) : base(content) { } private int m_tabX; public int TabX { get { return m_tabX; } set { m_tabX = value; } } private int m_tabWidth; public int TabWidth { get { return m_tabWidth; } set { m_tabWidth = value; } } private int m_maxWidth; public int MaxWidth { get { return m_maxWidth; } set { m_maxWidth = value; } } private bool m_flag; protected internal bool Flag { get { return m_flag; } set { m_flag = value; } } } protected internal override Tab CreateTab(IDockContent content) { return new TabVS2012Light(content); } private sealed class InertButton : InertButtonBase { private Bitmap m_image0, m_image1; public InertButton(Bitmap image0, Bitmap image1) : base() { m_image0 = image0; m_image1 = image1; } private int m_imageCategory = 0; public int ImageCategory { get { return m_imageCategory; } set { if (m_imageCategory == value) return; m_imageCategory = value; Invalidate(); } } public override Bitmap Image { get { return ImageCategory == 0 ? m_image0 : m_image1; } } } #region Constants private const int _ToolWindowStripGapTop = 0; private const int _ToolWindowStripGapBottom = 1; private const int _ToolWindowStripGapLeft = 0; private const int _ToolWindowStripGapRight = 0; private const int _ToolWindowImageHeight = 16; private const int _ToolWindowImageWidth = 0;//16; private const int _ToolWindowImageGapTop = 3; private const int _ToolWindowImageGapBottom = 1; private const int _ToolWindowImageGapLeft = 2; private const int _ToolWindowImageGapRight = 0; private const int _ToolWindowTextGapRight = 3; private const int _ToolWindowTabSeperatorGapTop = 3; private const int _ToolWindowTabSeperatorGapBottom = 3; private const int _DocumentStripGapTop = 0; private const int _DocumentStripGapBottom = 0; private const int _DocumentTabMaxWidth = 200; private const int _DocumentButtonGapTop = 3; private const int _DocumentButtonGapBottom = 3; private const int _DocumentButtonGapBetween = 0; private const int _DocumentButtonGapRight = 3; private const int _DocumentTabGapTop = 0;//3; private const int _DocumentTabGapLeft = 0;//3; private const int _DocumentTabGapRight = 0;//3; private const int _DocumentIconGapBottom = 2;//2; private const int _DocumentIconGapLeft = 8; private const int _DocumentIconGapRight = 0; private const int _DocumentIconHeight = 16; private const int _DocumentIconWidth = 16; private const int _DocumentTextGapRight = 6; #endregion #region Members private ContextMenuStrip m_selectMenu; private static Bitmap m_imageButtonClose; private InertButton m_buttonClose; private static Bitmap m_imageButtonWindowList; private static Bitmap m_imageButtonWindowListOverflow; private InertButton m_buttonWindowList; private IContainer m_components; private ToolTip m_toolTip; private Font m_font; private Font m_boldFont; private int m_startDisplayingTab = 0; private int m_endDisplayingTab = 0; private int m_firstDisplayingTab = 0; private bool m_documentTabsOverflow = false; private static string m_toolTipSelect; private static string m_toolTipClose; private bool m_closeButtonVisible = false; private Rectangle _activeClose; private int _selectMenuMargin = 5; #endregion #region Properties private Rectangle TabStripRectangle { get { if (Appearance == DockPane.AppearanceStyle.Document) return TabStripRectangle_Document; else return TabStripRectangle_ToolWindow; } } private Rectangle TabStripRectangle_ToolWindow { get { Rectangle rect = ClientRectangle; return new Rectangle(rect.X, rect.Top + ToolWindowStripGapTop, rect.Width, rect.Height - ToolWindowStripGapTop - ToolWindowStripGapBottom); } } private Rectangle TabStripRectangle_Document { get { Rectangle rect = ClientRectangle; return new Rectangle(rect.X, rect.Top + DocumentStripGapTop, rect.Width, rect.Height + DocumentStripGapTop - ToolWindowStripGapBottom); } } private Rectangle TabsRectangle { get { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return TabStripRectangle; Rectangle rectWindow = TabStripRectangle; int x = rectWindow.X; int y = rectWindow.Y; int width = rectWindow.Width; int height = rectWindow.Height; x += DocumentTabGapLeft; width -= DocumentTabGapLeft + DocumentTabGapRight + DocumentButtonGapRight + ButtonClose.Width + ButtonWindowList.Width + 2 * DocumentButtonGapBetween; return new Rectangle(x, y, width, height); } } private ContextMenuStrip SelectMenu { get { return m_selectMenu; } } public int SelectMenuMargin { get { return _selectMenuMargin; } set { _selectMenuMargin = value; } } private static Bitmap ImageButtonClose { get { if (m_imageButtonClose == null) m_imageButtonClose = Resources.DockPane_Close; return m_imageButtonClose; } } private InertButton ButtonClose { get { if (m_buttonClose == null) { m_buttonClose = new InertButton(ImageButtonClose, ImageButtonClose); m_toolTip.SetToolTip(m_buttonClose, ToolTipClose); m_buttonClose.Click += new EventHandler(Close_Click); Controls.Add(m_buttonClose); } return m_buttonClose; } } private static Bitmap ImageButtonWindowList { get { if (m_imageButtonWindowList == null) m_imageButtonWindowList = Resources.DockPane_Option; return m_imageButtonWindowList; } } private static Bitmap ImageButtonWindowListOverflow { get { if (m_imageButtonWindowListOverflow == null) m_imageButtonWindowListOverflow = Resources.DockPane_OptionOverflow; return m_imageButtonWindowListOverflow; } } private InertButton ButtonWindowList { get { if (m_buttonWindowList == null) { m_buttonWindowList = new InertButton(ImageButtonWindowList, ImageButtonWindowListOverflow); m_toolTip.SetToolTip(m_buttonWindowList, ToolTipSelect); m_buttonWindowList.Click += new EventHandler(WindowList_Click); Controls.Add(m_buttonWindowList); } return m_buttonWindowList; } } private static GraphicsPath GraphicsPath { get { return VS2005AutoHideStrip.GraphicsPath; } } private IContainer Components { get { return m_components; } } public Font TextFont { get { return DockPane.DockPanel.Skin.DockPaneStripSkin.TextFont; } } private Font BoldFont { get { if (IsDisposed) return null; if (m_boldFont == null) { m_font = TextFont; m_boldFont = new Font(TextFont, FontStyle.Bold); } else if (m_font != TextFont) { m_boldFont.Dispose(); m_font = TextFont; m_boldFont = new Font(TextFont, FontStyle.Bold); } return m_boldFont; } } private int StartDisplayingTab { get { return m_startDisplayingTab; } set { m_startDisplayingTab = value; Invalidate(); } } private int EndDisplayingTab { get { return m_endDisplayingTab; } set { m_endDisplayingTab = value; } } private int FirstDisplayingTab { get { return m_firstDisplayingTab; } set { m_firstDisplayingTab = value; } } private bool DocumentTabsOverflow { set { if (m_documentTabsOverflow == value) return; m_documentTabsOverflow = value; if (value) ButtonWindowList.ImageCategory = 1; else ButtonWindowList.ImageCategory = 0; } } #region Customizable Properties private static int ToolWindowStripGapTop { get { return _ToolWindowStripGapTop; } } private static int ToolWindowStripGapBottom { get { return _ToolWindowStripGapBottom; } } private static int ToolWindowStripGapLeft { get { return _ToolWindowStripGapLeft; } } private static int ToolWindowStripGapRight { get { return _ToolWindowStripGapRight; } } private static int ToolWindowImageHeight { get { return _ToolWindowImageHeight; } } private static int ToolWindowImageWidth { get { return _ToolWindowImageWidth; } } private static int ToolWindowImageGapTop { get { return _ToolWindowImageGapTop; } } private static int ToolWindowImageGapBottom { get { return _ToolWindowImageGapBottom; } } private static int ToolWindowImageGapLeft { get { return _ToolWindowImageGapLeft; } } private static int ToolWindowImageGapRight { get { return _ToolWindowImageGapRight; } } private static int ToolWindowTextGapRight { get { return _ToolWindowTextGapRight; } } private static int ToolWindowTabSeperatorGapTop { get { return _ToolWindowTabSeperatorGapTop; } } private static int ToolWindowTabSeperatorGapBottom { get { return _ToolWindowTabSeperatorGapBottom; } } private static string ToolTipClose { get { if (m_toolTipClose == null) m_toolTipClose = Strings.DockPaneStrip_ToolTipClose; return m_toolTipClose; } } private static string ToolTipSelect { get { if (m_toolTipSelect == null) m_toolTipSelect = Strings.DockPaneStrip_ToolTipWindowList; return m_toolTipSelect; } } private TextFormatFlags ToolWindowTextFormat { get { TextFormatFlags textFormat = TextFormatFlags.EndEllipsis | TextFormatFlags.HorizontalCenter | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter; if (RightToLeft == RightToLeft.Yes) return textFormat | TextFormatFlags.RightToLeft | TextFormatFlags.Right; else return textFormat; } } private static int DocumentStripGapTop { get { return _DocumentStripGapTop; } } private static int DocumentStripGapBottom { get { return _DocumentStripGapBottom; } } private TextFormatFlags DocumentTextFormat { get { TextFormatFlags textFormat = TextFormatFlags.EndEllipsis | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.HorizontalCenter; if (RightToLeft == RightToLeft.Yes) return textFormat | TextFormatFlags.RightToLeft; else return textFormat; } } private static int DocumentTabMaxWidth { get { return _DocumentTabMaxWidth; } } private static int DocumentButtonGapTop { get { return _DocumentButtonGapTop; } } private static int DocumentButtonGapBottom { get { return _DocumentButtonGapBottom; } } private static int DocumentButtonGapBetween { get { return _DocumentButtonGapBetween; } } private static int DocumentButtonGapRight { get { return _DocumentButtonGapRight; } } private static int DocumentTabGapTop { get { return _DocumentTabGapTop; } } private static int DocumentTabGapLeft { get { return _DocumentTabGapLeft; } } private static int DocumentTabGapRight { get { return _DocumentTabGapRight; } } private static int DocumentIconGapBottom { get { return _DocumentIconGapBottom; } } private static int DocumentIconGapLeft { get { return _DocumentIconGapLeft; } } private static int DocumentIconGapRight { get { return _DocumentIconGapRight; } } private static int DocumentIconWidth { get { return _DocumentIconWidth; } } private static int DocumentIconHeight { get { return _DocumentIconHeight; } } private static int DocumentTextGapRight { get { return _DocumentTextGapRight; } } private static Pen PenToolWindowTabBorder { get { return SystemPens.ControlDark; } } private static Pen PenDocumentTabActiveBorder { get { return SystemPens.ControlDarkDark; } } private static Pen PenDocumentTabInactiveBorder { get { return SystemPens.GrayText; } } #endregion #endregion public VS2012LightDockPaneStrip(DockPane pane) : base(pane) { SetStyle(ControlStyles.ResizeRedraw | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true); SuspendLayout(); m_components = new Container(); m_toolTip = new ToolTip(Components); m_selectMenu = new ContextMenuStrip(Components); ResumeLayout(); } protected override void Dispose(bool disposing) { if (disposing) { Components.Dispose(); if (m_boldFont != null) { m_boldFont.Dispose(); m_boldFont = null; } } base.Dispose(disposing); } protected internal override int MeasureHeight() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return MeasureHeight_ToolWindow(); else return MeasureHeight_Document(); } private int MeasureHeight_ToolWindow() { if (DockPane.IsAutoHide || Tabs.Count <= 1) return 0; int height = Math.Max(TextFont.Height, ToolWindowImageHeight + ToolWindowImageGapTop + ToolWindowImageGapBottom) + ToolWindowStripGapTop + ToolWindowStripGapBottom; return height; } private int MeasureHeight_Document() { int height = Math.Max(TextFont.Height + DocumentTabGapTop, ButtonClose.Height + DocumentButtonGapTop + DocumentButtonGapBottom) + DocumentStripGapBottom + DocumentStripGapTop; return height; } protected override void OnPaint(PaintEventArgs e) { Rectangle rect = TabsRectangle; if (Appearance == DockPane.AppearanceStyle.Document) { rect.X -= DocumentTabGapLeft; // Add these values back in so that the DockStrip color is drawn // beneath the close button and window list button. rect.Width += DocumentTabGapLeft + DocumentTabGapRight + DocumentButtonGapRight + ButtonClose.Width + ButtonWindowList.Width; // It is possible depending on the DockPanel DocumentStyle to have // a Document without a DockStrip. if (rect.Width > 0 && rect.Height > 0) { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.LinearGradientMode; using (LinearGradientBrush brush = new LinearGradientBrush(rect, startColor, endColor, gradientMode)) { e.Graphics.FillRectangle(brush, rect); } } } else { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.LinearGradientMode; using (LinearGradientBrush brush = new LinearGradientBrush(rect, startColor, endColor, gradientMode)) { e.Graphics.FillRectangle(brush, rect); } } base.OnPaint(e); CalculateTabs(); if (Appearance == DockPane.AppearanceStyle.Document && DockPane.ActiveContent != null) { if (EnsureDocumentTabVisible(DockPane.ActiveContent, false)) CalculateTabs(); } DrawTabStrip(e.Graphics); } protected override void OnRefreshChanges() { SetInertButtons(); Invalidate(); } protected internal override GraphicsPath GetOutline(int index) { if (Appearance == DockPane.AppearanceStyle.Document) return GetOutline_Document(index); else return GetOutline_ToolWindow(index); } private GraphicsPath GetOutline_Document(int index) { Rectangle rectTab = GetTabRectangle(index); rectTab.X -= rectTab.Height / 2; rectTab.Intersect(TabsRectangle); rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab)); Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle); GraphicsPath path = new GraphicsPath(); GraphicsPath pathTab = GetTabOutline_Document(Tabs[index], true, true, true); path.AddPath(pathTab, true); if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { path.AddLine(rectTab.Right, rectTab.Top, rectPaneClient.Right, rectTab.Top); path.AddLine(rectPaneClient.Right, rectTab.Top, rectPaneClient.Right, rectPaneClient.Top); path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Left, rectPaneClient.Top); path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Left, rectTab.Top); path.AddLine(rectPaneClient.Left, rectTab.Top, rectTab.Right, rectTab.Top); } else { path.AddLine(rectTab.Right, rectTab.Bottom, rectPaneClient.Right, rectTab.Bottom); path.AddLine(rectPaneClient.Right, rectTab.Bottom, rectPaneClient.Right, rectPaneClient.Bottom); path.AddLine(rectPaneClient.Right, rectPaneClient.Bottom, rectPaneClient.Left, rectPaneClient.Bottom); path.AddLine(rectPaneClient.Left, rectPaneClient.Bottom, rectPaneClient.Left, rectTab.Bottom); path.AddLine(rectPaneClient.Left, rectTab.Bottom, rectTab.Right, rectTab.Bottom); } return path; } private GraphicsPath GetOutline_ToolWindow(int index) { Rectangle rectTab = GetTabRectangle(index); rectTab.Intersect(TabsRectangle); rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab)); Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle); GraphicsPath path = new GraphicsPath(); GraphicsPath pathTab = GetTabOutline(Tabs[index], true, true); path.AddPath(pathTab, true); path.AddLine(rectTab.Left, rectTab.Top, rectPaneClient.Left, rectTab.Top); path.AddLine(rectPaneClient.Left, rectTab.Top, rectPaneClient.Left, rectPaneClient.Top); path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Right, rectPaneClient.Top); path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Right, rectTab.Top); path.AddLine(rectPaneClient.Right, rectTab.Top, rectTab.Right, rectTab.Top); return path; } private void CalculateTabs() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) CalculateTabs_ToolWindow(); else CalculateTabs_Document(); } private void CalculateTabs_ToolWindow() { if (Tabs.Count <= 1 || DockPane.IsAutoHide) return; Rectangle rectTabStrip = TabStripRectangle; // Calculate tab widths int countTabs = Tabs.Count; foreach (TabVS2012Light tab in Tabs) { tab.MaxWidth = GetMaxTabWidth(Tabs.IndexOf(tab)); tab.Flag = false; } // Set tab whose max width less than average width bool anyWidthWithinAverage = true; int totalWidth = rectTabStrip.Width - ToolWindowStripGapLeft - ToolWindowStripGapRight; int totalAllocatedWidth = 0; int averageWidth = totalWidth / countTabs; int remainedTabs = countTabs; for (anyWidthWithinAverage = true; anyWidthWithinAverage && remainedTabs > 0; ) { anyWidthWithinAverage = false; foreach (TabVS2012Light tab in Tabs) { if (tab.Flag) continue; if (tab.MaxWidth <= averageWidth) { tab.Flag = true; tab.TabWidth = tab.MaxWidth; totalAllocatedWidth += tab.TabWidth; anyWidthWithinAverage = true; remainedTabs--; } } if (remainedTabs != 0) averageWidth = (totalWidth - totalAllocatedWidth) / remainedTabs; } // If any tab width not set yet, set it to the average width if (remainedTabs > 0) { int roundUpWidth = (totalWidth - totalAllocatedWidth) - (averageWidth * remainedTabs); foreach (TabVS2012Light tab in Tabs) { if (tab.Flag) continue; tab.Flag = true; if (roundUpWidth > 0) { tab.TabWidth = averageWidth + 1; roundUpWidth--; } else tab.TabWidth = averageWidth; } } // Set the X position of the tabs int x = rectTabStrip.X + ToolWindowStripGapLeft; foreach (TabVS2012Light tab in Tabs) { tab.TabX = x; x += tab.TabWidth; } } private bool CalculateDocumentTab(Rectangle rectTabStrip, ref int x, int index) { bool overflow = false; var tab = Tabs[index] as TabVS2012Light; tab.MaxWidth = GetMaxTabWidth(index); int width = Math.Min(tab.MaxWidth, DocumentTabMaxWidth); if (x + width < rectTabStrip.Right || index == StartDisplayingTab) { tab.TabX = x; tab.TabWidth = width; EndDisplayingTab = index; } else { tab.TabX = 0; tab.TabWidth = 0; overflow = true; } x += width; return overflow; } /// <summary> /// Calculate which tabs are displayed and in what order. /// </summary> private void CalculateTabs_Document() { if (m_startDisplayingTab >= Tabs.Count) m_startDisplayingTab = 0; Rectangle rectTabStrip = TabsRectangle; int x = rectTabStrip.X; //+ rectTabStrip.Height / 2; bool overflow = false; // Originally all new documents that were considered overflow // (not enough pane strip space to show all tabs) were added to // the far left (assuming not right to left) and the tabs on the // right were dropped from view. If StartDisplayingTab is not 0 // then we are dealing with making sure a specific tab is kept in focus. if (m_startDisplayingTab > 0) { int tempX = x; var tab = Tabs[m_startDisplayingTab] as TabVS2012Light; tab.MaxWidth = GetMaxTabWidth(m_startDisplayingTab); // Add the active tab and tabs to the left for (int i = StartDisplayingTab; i >= 0; i--) CalculateDocumentTab(rectTabStrip, ref tempX, i); // Store which tab is the first one displayed so that it // will be drawn correctly (without part of the tab cut off) FirstDisplayingTab = EndDisplayingTab; tempX = x; // Reset X location because we are starting over // Start with the first tab displayed - name is a little misleading. // Loop through each tab and set its location. If there is not enough // room for all of them overflow will be returned. for (int i = EndDisplayingTab; i < Tabs.Count; i++) overflow = CalculateDocumentTab(rectTabStrip, ref tempX, i); // If not all tabs are shown then we have an overflow. if (FirstDisplayingTab != 0) overflow = true; } else { for (int i = StartDisplayingTab; i < Tabs.Count; i++) overflow = CalculateDocumentTab(rectTabStrip, ref x, i); for (int i = 0; i < StartDisplayingTab; i++) overflow = CalculateDocumentTab(rectTabStrip, ref x, i); FirstDisplayingTab = StartDisplayingTab; } if (!overflow) { m_startDisplayingTab = 0; FirstDisplayingTab = 0; x = rectTabStrip.X;// +rectTabStrip.Height / 2; foreach (TabVS2012Light tab in Tabs) { tab.TabX = x; x += tab.TabWidth; } } DocumentTabsOverflow = overflow; } protected internal override void EnsureTabVisible(IDockContent content) { if (Appearance != DockPane.AppearanceStyle.Document || !Tabs.Contains(content)) return; CalculateTabs(); EnsureDocumentTabVisible(content, true); } private bool EnsureDocumentTabVisible(IDockContent content, bool repaint) { int index = Tabs.IndexOf(content); var tab = Tabs[index] as TabVS2012Light; if (tab.TabWidth != 0) return false; StartDisplayingTab = index; if (repaint) Invalidate(); return true; } private int GetMaxTabWidth(int index) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetMaxTabWidth_ToolWindow(index); else return GetMaxTabWidth_Document(index); } private int GetMaxTabWidth_ToolWindow(int index) { IDockContent content = Tabs[index].Content; Size sizeString = TextRenderer.MeasureText(content.DockHandler.TabText, TextFont); return ToolWindowImageWidth + sizeString.Width + ToolWindowImageGapLeft + ToolWindowImageGapRight + ToolWindowTextGapRight; } private const int TAB_CLOSE_BUTTON_WIDTH = 30; private int GetMaxTabWidth_Document(int index) { IDockContent content = Tabs[index].Content; int height = GetTabRectangle_Document(index).Height; Size sizeText = TextRenderer.MeasureText(content.DockHandler.TabText, BoldFont, new Size(DocumentTabMaxWidth, height), DocumentTextFormat); int width; if (DockPane.DockPanel.ShowDocumentIcon) width = sizeText.Width + DocumentIconWidth + DocumentIconGapLeft + DocumentIconGapRight + DocumentTextGapRight; else width = sizeText.Width + DocumentIconGapLeft + DocumentTextGapRight; width += TAB_CLOSE_BUTTON_WIDTH; return width; } private void DrawTabStrip(Graphics g) { if (Appearance == DockPane.AppearanceStyle.Document) DrawTabStrip_Document(g); else DrawTabStrip_ToolWindow(g); } private void DrawTabStrip_Document(Graphics g) { int count = Tabs.Count; if (count == 0) return; Rectangle rectTabStrip = TabStripRectangle; rectTabStrip.Height += 1; // Draw the tabs Rectangle rectTabOnly = TabsRectangle; Rectangle rectTab = Rectangle.Empty; TabVS2012Light tabActive = null; g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly)); for (int i = 0; i < count; i++) { rectTab = GetTabRectangle(i); if (Tabs[i].Content == DockPane.ActiveContent) { tabActive = Tabs[i] as TabVS2012Light; continue; } if (rectTab.IntersectsWith(rectTabOnly)) DrawTab(g, Tabs[i] as TabVS2012Light, rectTab); } g.SetClip(rectTabStrip); if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) g.DrawLine(PenDocumentTabActiveBorder, rectTabStrip.Left, rectTabStrip.Top + 1, rectTabStrip.Right, rectTabStrip.Top + 1); else { Color tabUnderLineColor; if (tabActive != null && DockPane.IsActiveDocumentPane) tabUnderLineColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor; else tabUnderLineColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor; g.DrawLine(new Pen(tabUnderLineColor, 4), rectTabStrip.Left, rectTabStrip.Bottom, rectTabStrip.Right, rectTabStrip.Bottom); } g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly)); if (tabActive != null) { rectTab = GetTabRectangle(Tabs.IndexOf(tabActive)); if (rectTab.IntersectsWith(rectTabOnly)) { rectTab.Intersect(rectTabOnly); DrawTab(g, tabActive, rectTab); } } } private void DrawTabStrip_ToolWindow(Graphics g) { Rectangle rectTabStrip = TabStripRectangle; g.DrawLine(PenToolWindowTabBorder, rectTabStrip.Left, rectTabStrip.Top, rectTabStrip.Right, rectTabStrip.Top); for (int i = 0; i < Tabs.Count; i++) DrawTab(g, Tabs[i] as TabVS2012Light, GetTabRectangle(i)); } private Rectangle GetTabRectangle(int index) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetTabRectangle_ToolWindow(index); else return GetTabRectangle_Document(index); } private Rectangle GetTabRectangle_ToolWindow(int index) { Rectangle rectTabStrip = TabStripRectangle; TabVS2012Light tab = (TabVS2012Light)(Tabs[index]); return new Rectangle(tab.TabX, rectTabStrip.Y, tab.TabWidth, rectTabStrip.Height); } private Rectangle GetTabRectangle_Document(int index) { Rectangle rectTabStrip = TabStripRectangle; var tab = (TabVS2012Light)Tabs[index]; Rectangle rect = new Rectangle(); rect.X = tab.TabX; rect.Width = tab.TabWidth; rect.Height = rectTabStrip.Height - DocumentTabGapTop; if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) rect.Y = rectTabStrip.Y + DocumentStripGapBottom; else rect.Y = rectTabStrip.Y + DocumentTabGapTop; return rect; } private void DrawTab(Graphics g, TabVS2012Light tab, Rectangle rect) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) DrawTab_ToolWindow(g, tab, rect); else DrawTab_Document(g, tab, rect); } private GraphicsPath GetTabOutline(Tab tab, bool rtlTransform, bool toScreen) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetTabOutline_ToolWindow(tab, rtlTransform, toScreen); else return GetTabOutline_Document(tab, rtlTransform, toScreen, false); } private GraphicsPath GetTabOutline_ToolWindow(Tab tab, bool rtlTransform, bool toScreen) { Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab)); if (rtlTransform) rect = DrawHelper.RtlTransform(this, rect); if (toScreen) rect = RectangleToScreen(rect); DrawHelper.GetRoundedCornerTab(GraphicsPath, rect, false); return GraphicsPath; } private GraphicsPath GetTabOutline_Document(Tab tab, bool rtlTransform, bool toScreen, bool full) { GraphicsPath.Reset(); Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab)); // Shorten TabOutline so it doesn't get overdrawn by icons next to it rect.Intersect(TabsRectangle); rect.Width--; if (rtlTransform) rect = DrawHelper.RtlTransform(this, rect); if (toScreen) rect = RectangleToScreen(rect); GraphicsPath.AddRectangle(rect); return GraphicsPath; } private void DrawTab_ToolWindow(Graphics g, TabVS2012Light tab, Rectangle rect) { rect.Y += 1; Rectangle rectIcon = new Rectangle( rect.X + ToolWindowImageGapLeft, rect.Y - 1 + rect.Height - ToolWindowImageGapBottom - ToolWindowImageHeight, ToolWindowImageWidth, ToolWindowImageHeight); Rectangle rectText = rectIcon; rectText.X += rectIcon.Width + ToolWindowImageGapRight; rectText.Width = rect.Width - rectIcon.Width - ToolWindowImageGapLeft - ToolWindowImageGapRight - ToolWindowTextGapRight; Rectangle rectTab = DrawHelper.RtlTransform(this, rect); rectText = DrawHelper.RtlTransform(this, rectText); rectIcon = DrawHelper.RtlTransform(this, rectIcon); if (DockPane.ActiveContent == tab.Content && ((DockContent)tab.Content).IsActivated) { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.LinearGradientMode; g.FillRectangle(new LinearGradientBrush(rectTab, startColor, endColor, gradientMode), rect); Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor; TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat); } else { Color textColor; if (tab.Content == DockPane.MouseOverTab) textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor; else textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.TextColor; TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat); } g.DrawLine(PenToolWindowTabBorder, rect.X + rect.Width - 1, rect.Y, rect.X + rect.Width - 1, rect.Height); if (rectTab.Contains(rectIcon)) g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon); } private void DrawTab_Document(Graphics g, TabVS2012Light tab, Rectangle rect) { if (tab.TabWidth == 0) return; var rectCloseButton = GetCloseButtonRect(rect); Rectangle rectIcon = new Rectangle( rect.X + DocumentIconGapLeft, rect.Y + rect.Height - DocumentIconGapBottom - DocumentIconHeight, DocumentIconWidth, DocumentIconHeight); Rectangle rectText = rectIcon; if (DockPane.DockPanel.ShowDocumentIcon) { rectText.X += rectIcon.Width + DocumentIconGapRight; rectText.Y = rect.Y; rectText.Width = rect.Width - rectIcon.Width - DocumentIconGapLeft - DocumentIconGapRight - DocumentTextGapRight - rectCloseButton.Width; rectText.Height = rect.Height; } else rectText.Width = rect.Width - DocumentIconGapLeft - DocumentTextGapRight - rectCloseButton.Width; Rectangle rectTab = DrawHelper.RtlTransform(this, rect); Rectangle rectBack = DrawHelper.RtlTransform(this, rect); rectBack.Width += rect.X; rectBack.X = 0; rectText = DrawHelper.RtlTransform(this, rectText); rectIcon = DrawHelper.RtlTransform(this, rectIcon); Color activeColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor; Color lostFocusColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor; Color inactiveColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.StartColor; Color mouseHoverColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.EndColor; Color activeText = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.TextColor; Color inactiveText = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.TextColor; Color lostFocusText = SystemColors.GrayText; if (DockPane.ActiveContent == tab.Content) { if (DockPane.IsActiveDocumentPane) { g.FillRectangle(new SolidBrush(activeColor), rect); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, activeText, DocumentTextFormat); g.DrawImage(rectCloseButton == ActiveClose ? Resources.ActiveTabHover_Close : Resources.ActiveTab_Close, rectCloseButton); } else { g.FillRectangle(new SolidBrush(lostFocusColor), rect); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, lostFocusText, DocumentTextFormat); g.DrawImage(rectCloseButton == ActiveClose ? Resources.LostFocusTabHover_Close : Resources.LostFocusTab_Close, rectCloseButton); } } else { if (tab.Content == DockPane.MouseOverTab) { g.FillRectangle(new SolidBrush(mouseHoverColor), rect); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, activeText, DocumentTextFormat); g.DrawImage(rectCloseButton == ActiveClose ? Resources.InactiveTabHover_Close : Resources.ActiveTabHover_Close, rectCloseButton); } else { g.FillRectangle(new SolidBrush(inactiveColor), rect); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, inactiveText, DocumentTextFormat); } } if (rectTab.Contains(rectIcon) && DockPane.DockPanel.ShowDocumentIcon) g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon); } protected override void OnMouseClick(MouseEventArgs e) { base.OnMouseClick(e); if (e.Button != MouseButtons.Left || Appearance != DockPane.AppearanceStyle.Document) return; var indexHit = HitTest(); if (indexHit > -1) TabCloseButtonHit(indexHit); } private void TabCloseButtonHit(int index) { var mousePos = PointToClient(MousePosition); var tabRect = GetTabRectangle(index); var closeButtonRect = GetCloseButtonRect(tabRect); var mouseRect = new Rectangle(mousePos, new Size(1, 1)); if (closeButtonRect.IntersectsWith(mouseRect)) DockPane.CloseActiveContent(); } private Rectangle GetCloseButtonRect(Rectangle rectTab) { if (Appearance != Docking.DockPane.AppearanceStyle.Document) { return Rectangle.Empty; } const int gap = 3; const int imageSize = 15; return new Rectangle(rectTab.X + rectTab.Width - imageSize - gap - 1, rectTab.Y + gap, imageSize, imageSize); } private void WindowList_Click(object sender, EventArgs e) { SelectMenu.Items.Clear(); foreach (TabVS2012Light tab in Tabs) { IDockContent content = tab.Content; ToolStripItem item = SelectMenu.Items.Add(content.DockHandler.TabText, content.DockHandler.Icon.ToBitmap()); item.Tag = tab.Content; item.Click += new EventHandler(ContextMenuItem_Click); } var workingArea = Screen.GetWorkingArea(ButtonWindowList.PointToScreen(new Point(ButtonWindowList.Width / 2, ButtonWindowList.Height / 2))); var menu = new Rectangle(ButtonWindowList.PointToScreen(new Point(0, ButtonWindowList.Location.Y + ButtonWindowList.Height)), SelectMenu.Size); var menuMargined = new Rectangle(menu.X - SelectMenuMargin, menu.Y - SelectMenuMargin, menu.Width + SelectMenuMargin, menu.Height + SelectMenuMargin); if (workingArea.Contains(menuMargined)) { SelectMenu.Show(menu.Location); } else { var newPoint = menu.Location; newPoint.X = DrawHelper.Balance(SelectMenu.Width, SelectMenuMargin, newPoint.X, workingArea.Left, workingArea.Right); newPoint.Y = DrawHelper.Balance(SelectMenu.Size.Height, SelectMenuMargin, newPoint.Y, workingArea.Top, workingArea.Bottom); var button = ButtonWindowList.PointToScreen(new Point(0, ButtonWindowList.Height)); if (newPoint.Y < button.Y) { // flip the menu up to be above the button. newPoint.Y = button.Y - ButtonWindowList.Height; SelectMenu.Show(newPoint, ToolStripDropDownDirection.AboveRight); } else { SelectMenu.Show(newPoint); } } } private void ContextMenuItem_Click(object sender, EventArgs e) { ToolStripMenuItem item = sender as ToolStripMenuItem; if (item != null) { IDockContent content = (IDockContent)item.Tag; DockPane.ActiveContent = content; } } private void SetInertButtons() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) { if (m_buttonClose != null) m_buttonClose.Left = -m_buttonClose.Width; if (m_buttonWindowList != null) m_buttonWindowList.Left = -m_buttonWindowList.Width; } else { ButtonClose.Enabled = false; m_closeButtonVisible = false; ButtonClose.Visible = m_closeButtonVisible; ButtonClose.RefreshChanges(); ButtonWindowList.RefreshChanges(); } } protected override void OnLayout(LayoutEventArgs levent) { if (Appearance == DockPane.AppearanceStyle.Document) { LayoutButtons(); OnRefreshChanges(); } base.OnLayout(levent); } private void LayoutButtons() { Rectangle rectTabStrip = TabStripRectangle; // Set position and size of the buttons int buttonWidth = ButtonClose.Image.Width; int buttonHeight = ButtonClose.Image.Height; int height = rectTabStrip.Height - DocumentButtonGapTop - DocumentButtonGapBottom; if (buttonHeight < height) { buttonWidth = buttonWidth * (height / buttonHeight); buttonHeight = height; } Size buttonSize = new Size(buttonWidth, buttonHeight); int x = rectTabStrip.X + rectTabStrip.Width - DocumentTabGapLeft - DocumentButtonGapRight - buttonWidth; int y = rectTabStrip.Y + DocumentButtonGapTop; Point point = new Point(x, y); ButtonClose.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); // If the close button is not visible draw the window list button overtop. // Otherwise it is drawn to the left of the close button. if (m_closeButtonVisible) point.Offset(-(DocumentButtonGapBetween + buttonWidth), 0); ButtonWindowList.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); } private void Close_Click(object sender, EventArgs e) { DockPane.CloseActiveContent(); } protected internal override int HitTest(Point ptMouse) { if (!TabsRectangle.Contains(ptMouse)) return -1; foreach (Tab tab in Tabs) { GraphicsPath path = GetTabOutline(tab, true, false); if (path.IsVisible(ptMouse)) return Tabs.IndexOf(tab); } return -1; } private Rectangle ActiveClose { get { return _activeClose; } } private bool SetActiveClose(Rectangle rectangle) { if (_activeClose == rectangle) return false; _activeClose = rectangle; return true; } private bool SetMouseOverTab(IDockContent content) { if (DockPane.MouseOverTab == content) return false; DockPane.MouseOverTab = content; return true; } protected override void OnMouseHover(EventArgs e) { int index = HitTest(PointToClient(MousePosition)); string toolTip = string.Empty; base.OnMouseHover(e); bool tabUpdate = false; bool buttonUpdate = false; if (index != -1) { var tab = Tabs[index] as TabVS2012Light; if (Appearance == DockPane.AppearanceStyle.ToolWindow || Appearance == DockPane.AppearanceStyle.Document) { tabUpdate = SetMouseOverTab(tab.Content == DockPane.ActiveContent ? null : tab.Content); } if (!String.IsNullOrEmpty(tab.Content.DockHandler.ToolTipText)) toolTip = tab.Content.DockHandler.ToolTipText; else if (tab.MaxWidth > tab.TabWidth) toolTip = tab.Content.DockHandler.TabText; var mousePos = PointToClient(MousePosition); var tabRect = GetTabRectangle(index); var closeButtonRect = GetCloseButtonRect(tabRect); var mouseRect = new Rectangle(mousePos, new Size(1, 1)); buttonUpdate = SetActiveClose(closeButtonRect.IntersectsWith(mouseRect) ? closeButtonRect : Rectangle.Empty); } else { tabUpdate = SetMouseOverTab(null); buttonUpdate = SetActiveClose(Rectangle.Empty); } if (tabUpdate || buttonUpdate) Invalidate(); if (m_toolTip.GetToolTip(this) != toolTip) { m_toolTip.Active = false; m_toolTip.SetToolTip(this, toolTip); m_toolTip.Active = true; } // requires further tracking of mouse hover behavior, ResetMouseEventArgs(); } protected override void OnMouseLeave(EventArgs e) { var tabUpdate = SetMouseOverTab(null); var buttonUpdate = SetActiveClose(Rectangle.Empty); if (tabUpdate || buttonUpdate) Invalidate(); base.OnMouseLeave(e); } protected override void OnRightToLeftChanged(EventArgs e) { base.OnRightToLeftChanged(e); PerformLayout(); } } }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.ComponentModel; using System.Collections; using System.Collections.Generic; namespace WeifenLuo.WinFormsUI.Docking { internal class VS2005DockPaneStrip : DockPaneStripBase { private class TabVS2005 : Tab { public TabVS2005(IDockContent content) : base(content) { } private int m_tabX; public int TabX { get { return m_tabX; } set { m_tabX = value; } } private int m_tabWidth; public int TabWidth { get { return m_tabWidth; } set { m_tabWidth = value; } } private int m_maxWidth; public int MaxWidth { get { return m_maxWidth; } set { m_maxWidth = value; } } private bool m_flag; protected internal bool Flag { get { return m_flag; } set { m_flag = value; } } } protected internal override DockPaneStripBase.Tab CreateTab(IDockContent content) { return new TabVS2005(content); } private sealed class InertButton : InertButtonBase { private Bitmap m_image0, m_image1; public InertButton(Bitmap image0, Bitmap image1) : base() { m_image0 = image0; m_image1 = image1; } private int m_imageCategory = 0; public int ImageCategory { get { return m_imageCategory; } set { if (m_imageCategory == value) return; m_imageCategory = value; Invalidate(); } } public override Bitmap Image { get { return ImageCategory == 0 ? m_image0 : m_image1; } } } #region Constants private const int _ToolWindowStripGapTop = 0; private const int _ToolWindowStripGapBottom = 1; private const int _ToolWindowStripGapLeft = 0; private const int _ToolWindowStripGapRight = 0; private const int _ToolWindowImageHeight = 16; private const int _ToolWindowImageWidth = 16; private const int _ToolWindowImageGapTop = 3; private const int _ToolWindowImageGapBottom = 1; private const int _ToolWindowImageGapLeft = 2; private const int _ToolWindowImageGapRight = 0; private const int _ToolWindowTextGapRight = 3; private const int _ToolWindowTabSeperatorGapTop = 3; private const int _ToolWindowTabSeperatorGapBottom = 3; private const int _DocumentStripGapTop = 0; private const int _DocumentStripGapBottom = 1; private const int _DocumentTabMaxWidth = 200; private const int _DocumentButtonGapTop = 4; private const int _DocumentButtonGapBottom = 4; private const int _DocumentButtonGapBetween = 0; private const int _DocumentButtonGapRight = 3; private const int _DocumentTabGapTop = 3; private const int _DocumentTabGapLeft = 3; private const int _DocumentTabGapRight = 3; private const int _DocumentIconGapBottom = 2; private const int _DocumentIconGapLeft = 12; private const int _DocumentIconGapRight = 0; private const int _DocumentIconHeight = 16; private const int _DocumentIconWidth = 16; private const int _DocumentTextGapRight = 3; #endregion #region Members private ContextMenuStrip m_selectMenu; private static Bitmap m_imageButtonClose; private InertButton m_buttonClose; private static Bitmap m_imageButtonWindowList; private static Bitmap m_imageButtonWindowListOverflow; private InertButton m_buttonWindowList; private IContainer m_components; private ToolTip m_toolTip; private Font m_font; private Font m_boldFont; private int m_startDisplayingTab = 0; private int m_endDisplayingTab = 0; private int m_firstDisplayingTab = 0; private bool m_documentTabsOverflow = false; private static string m_toolTipSelect; private static string m_toolTipClose; private bool m_closeButtonVisible = false; #endregion #region Properties private Rectangle TabStripRectangle { get { if (Appearance == DockPane.AppearanceStyle.Document) return TabStripRectangle_Document; else return TabStripRectangle_ToolWindow; } } private Rectangle TabStripRectangle_ToolWindow { get { Rectangle rect = ClientRectangle; return new Rectangle(rect.X, rect.Top + ToolWindowStripGapTop, rect.Width, rect.Height - ToolWindowStripGapTop - ToolWindowStripGapBottom); } } private Rectangle TabStripRectangle_Document { get { Rectangle rect = ClientRectangle; return new Rectangle(rect.X, rect.Top + DocumentStripGapTop, rect.Width, rect.Height - DocumentStripGapTop - ToolWindowStripGapBottom); } } private Rectangle TabsRectangle { get { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return TabStripRectangle; Rectangle rectWindow = TabStripRectangle; int x = rectWindow.X; int y = rectWindow.Y; int width = rectWindow.Width; int height = rectWindow.Height; x += DocumentTabGapLeft; width -= DocumentTabGapLeft + DocumentTabGapRight + DocumentButtonGapRight + ButtonClose.Width + ButtonWindowList.Width + 2 * DocumentButtonGapBetween; return new Rectangle(x, y, width, height); } } private ContextMenuStrip SelectMenu { get { return m_selectMenu; } } private static Bitmap ImageButtonClose { get { if (m_imageButtonClose == null) m_imageButtonClose = Resources.DockPane_Close; return m_imageButtonClose; } } private InertButton ButtonClose { get { if (m_buttonClose == null) { m_buttonClose = new InertButton(ImageButtonClose, ImageButtonClose); m_toolTip.SetToolTip(m_buttonClose, ToolTipClose); m_buttonClose.Click += new EventHandler(Close_Click); Controls.Add(m_buttonClose); } return m_buttonClose; } } private static Bitmap ImageButtonWindowList { get { if (m_imageButtonWindowList == null) m_imageButtonWindowList = Resources.DockPane_Option; return m_imageButtonWindowList; } } private static Bitmap ImageButtonWindowListOverflow { get { if (m_imageButtonWindowListOverflow == null) m_imageButtonWindowListOverflow = Resources.DockPane_OptionOverflow; return m_imageButtonWindowListOverflow; } } private InertButton ButtonWindowList { get { if (m_buttonWindowList == null) { m_buttonWindowList = new InertButton(ImageButtonWindowList, ImageButtonWindowListOverflow); m_toolTip.SetToolTip(m_buttonWindowList, ToolTipSelect); m_buttonWindowList.Click += new EventHandler(WindowList_Click); Controls.Add(m_buttonWindowList); } return m_buttonWindowList; } } private static GraphicsPath GraphicsPath { get { return VS2005AutoHideStrip.GraphicsPath; } } private IContainer Components { get { return m_components; } } public Font TextFont { get { return DockPane.DockPanel.Skin.DockPaneStripSkin.TextFont; } } private Font BoldFont { get { if (IsDisposed) return null; if (m_boldFont == null) { m_font = TextFont; m_boldFont = new Font(TextFont, FontStyle.Bold); } else if (m_font != TextFont) { m_boldFont.Dispose(); m_font = TextFont; m_boldFont = new Font(TextFont, FontStyle.Bold); } return m_boldFont; } } private int StartDisplayingTab { get { return m_startDisplayingTab; } set { m_startDisplayingTab = value; Invalidate(); } } private int EndDisplayingTab { get { return m_endDisplayingTab; } set { m_endDisplayingTab = value; } } private int FirstDisplayingTab { get { return m_firstDisplayingTab; } set { m_firstDisplayingTab = value; } } private bool DocumentTabsOverflow { set { if (m_documentTabsOverflow == value) return; m_documentTabsOverflow = value; if (value) ButtonWindowList.ImageCategory = 1; else ButtonWindowList.ImageCategory = 0; } } #region Customizable Properties private static int ToolWindowStripGapTop { get { return _ToolWindowStripGapTop; } } private static int ToolWindowStripGapBottom { get { return _ToolWindowStripGapBottom; } } private static int ToolWindowStripGapLeft { get { return _ToolWindowStripGapLeft; } } private static int ToolWindowStripGapRight { get { return _ToolWindowStripGapRight; } } private static int ToolWindowImageHeight { get { return _ToolWindowImageHeight; } } private static int ToolWindowImageWidth { get { return _ToolWindowImageWidth; } } private static int ToolWindowImageGapTop { get { return _ToolWindowImageGapTop; } } private static int ToolWindowImageGapBottom { get { return _ToolWindowImageGapBottom; } } private static int ToolWindowImageGapLeft { get { return _ToolWindowImageGapLeft; } } private static int ToolWindowImageGapRight { get { return _ToolWindowImageGapRight; } } private static int ToolWindowTextGapRight { get { return _ToolWindowTextGapRight; } } private static int ToolWindowTabSeperatorGapTop { get { return _ToolWindowTabSeperatorGapTop; } } private static int ToolWindowTabSeperatorGapBottom { get { return _ToolWindowTabSeperatorGapBottom; } } private static string ToolTipClose { get { if (m_toolTipClose == null) m_toolTipClose = Strings.DockPaneStrip_ToolTipClose; return m_toolTipClose; } } private static string ToolTipSelect { get { if (m_toolTipSelect == null) m_toolTipSelect = Strings.DockPaneStrip_ToolTipWindowList; return m_toolTipSelect; } } private TextFormatFlags ToolWindowTextFormat { get { TextFormatFlags textFormat = TextFormatFlags.EndEllipsis | TextFormatFlags.HorizontalCenter | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter; if (RightToLeft == RightToLeft.Yes) return textFormat | TextFormatFlags.RightToLeft | TextFormatFlags.Right; else return textFormat; } } private static int DocumentStripGapTop { get { return _DocumentStripGapTop; } } private static int DocumentStripGapBottom { get { return _DocumentStripGapBottom; } } private TextFormatFlags DocumentTextFormat { get { TextFormatFlags textFormat = TextFormatFlags.EndEllipsis | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.HorizontalCenter; if (RightToLeft == RightToLeft.Yes) return textFormat | TextFormatFlags.RightToLeft; else return textFormat; } } private static int DocumentTabMaxWidth { get { return _DocumentTabMaxWidth; } } private static int DocumentButtonGapTop { get { return _DocumentButtonGapTop; } } private static int DocumentButtonGapBottom { get { return _DocumentButtonGapBottom; } } private static int DocumentButtonGapBetween { get { return _DocumentButtonGapBetween; } } private static int DocumentButtonGapRight { get { return _DocumentButtonGapRight; } } private static int DocumentTabGapTop { get { return _DocumentTabGapTop; } } private static int DocumentTabGapLeft { get { return _DocumentTabGapLeft; } } private static int DocumentTabGapRight { get { return _DocumentTabGapRight; } } private static int DocumentIconGapBottom { get { return _DocumentIconGapBottom; } } private static int DocumentIconGapLeft { get { return _DocumentIconGapLeft; } } private static int DocumentIconGapRight { get { return _DocumentIconGapRight; } } private static int DocumentIconWidth { get { return _DocumentIconWidth; } } private static int DocumentIconHeight { get { return _DocumentIconHeight; } } private static int DocumentTextGapRight { get { return _DocumentTextGapRight; } } private static Pen PenToolWindowTabBorder { get { return SystemPens.GrayText; } } private static Pen PenDocumentTabActiveBorder { get { return SystemPens.ControlDarkDark; } } private static Pen PenDocumentTabInactiveBorder { get { return SystemPens.GrayText; } } #endregion #endregion public VS2005DockPaneStrip(DockPane pane) : base(pane) { SetStyle(ControlStyles.ResizeRedraw | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true); SuspendLayout(); m_components = new Container(); m_toolTip = new ToolTip(Components); m_selectMenu = new ContextMenuStrip(Components); ResumeLayout(); } protected override void Dispose(bool disposing) { if (disposing) { Components.Dispose(); if (m_boldFont != null) { m_boldFont.Dispose(); m_boldFont = null; } } base.Dispose(disposing); } protected internal override int MeasureHeight() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return MeasureHeight_ToolWindow(); else return MeasureHeight_Document(); } private int MeasureHeight_ToolWindow() { if (DockPane.IsAutoHide || Tabs.Count <= 1) return 0; int height = Math.Max(TextFont.Height, ToolWindowImageHeight + ToolWindowImageGapTop + ToolWindowImageGapBottom) + ToolWindowStripGapTop + ToolWindowStripGapBottom; return height; } private int MeasureHeight_Document() { int height = Math.Max(TextFont.Height + DocumentTabGapTop, ButtonClose.Height + DocumentButtonGapTop + DocumentButtonGapBottom) + DocumentStripGapBottom + DocumentStripGapTop; return height; } protected override void OnPaint(PaintEventArgs e) { Rectangle rect = TabsRectangle; if (Appearance == DockPane.AppearanceStyle.Document) { rect.X -= DocumentTabGapLeft; // Add these values back in so that the DockStrip color is drawn // beneath the close button and window list button. rect.Width += DocumentTabGapLeft + DocumentTabGapRight + DocumentButtonGapRight + ButtonClose.Width + ButtonWindowList.Width; // It is possible depending on the DockPanel DocumentStyle to have // a Document without a DockStrip. if (rect.Width > 0 && rect.Height > 0) { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.LinearGradientMode; using (LinearGradientBrush brush = new LinearGradientBrush(rect, startColor, endColor, gradientMode)) { e.Graphics.FillRectangle(brush, rect); } } } else { if (rect.Width > 0 && rect.Height > 0) { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.LinearGradientMode; using (LinearGradientBrush brush = new LinearGradientBrush(rect, startColor, endColor, gradientMode)) { e.Graphics.FillRectangle(brush, rect); } } } base.OnPaint(e); CalculateTabs(); if (Appearance == DockPane.AppearanceStyle.Document && DockPane.ActiveContent != null) { if (EnsureDocumentTabVisible(DockPane.ActiveContent, false)) CalculateTabs(); } DrawTabStrip(e.Graphics); } protected override void OnRefreshChanges() { SetInertButtons(); Invalidate(); } protected internal override GraphicsPath GetOutline(int index) { if (Appearance == DockPane.AppearanceStyle.Document) return GetOutline_Document(index); else return GetOutline_ToolWindow(index); } private GraphicsPath GetOutline_Document(int index) { Rectangle rectTab = GetTabRectangle(index); rectTab.X -= rectTab.Height / 2; rectTab.Intersect(TabsRectangle); rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab)); Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle); GraphicsPath path = new GraphicsPath(); GraphicsPath pathTab = GetTabOutline_Document(Tabs[index], true, true, true); path.AddPath(pathTab, true); if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { path.AddLine(rectTab.Right, rectTab.Top, rectPaneClient.Right, rectTab.Top); path.AddLine(rectPaneClient.Right, rectTab.Top, rectPaneClient.Right, rectPaneClient.Top); path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Left, rectPaneClient.Top); path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Left, rectTab.Top); path.AddLine(rectPaneClient.Left, rectTab.Top, rectTab.Right, rectTab.Top); } else { path.AddLine(rectTab.Right, rectTab.Bottom, rectPaneClient.Right, rectTab.Bottom); path.AddLine(rectPaneClient.Right, rectTab.Bottom, rectPaneClient.Right, rectPaneClient.Bottom); path.AddLine(rectPaneClient.Right, rectPaneClient.Bottom, rectPaneClient.Left, rectPaneClient.Bottom); path.AddLine(rectPaneClient.Left, rectPaneClient.Bottom, rectPaneClient.Left, rectTab.Bottom); path.AddLine(rectPaneClient.Left, rectTab.Bottom, rectTab.Right, rectTab.Bottom); } return path; } private GraphicsPath GetOutline_ToolWindow(int index) { Rectangle rectTab = GetTabRectangle(index); rectTab.Intersect(TabsRectangle); rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab)); Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle); GraphicsPath path = new GraphicsPath(); GraphicsPath pathTab = GetTabOutline(Tabs[index], true, true); path.AddPath(pathTab, true); path.AddLine(rectTab.Left, rectTab.Top, rectPaneClient.Left, rectTab.Top); path.AddLine(rectPaneClient.Left, rectTab.Top, rectPaneClient.Left, rectPaneClient.Top); path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Right, rectPaneClient.Top); path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Right, rectTab.Top); path.AddLine(rectPaneClient.Right, rectTab.Top, rectTab.Right, rectTab.Top); return path; } private void CalculateTabs() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) CalculateTabs_ToolWindow(); else CalculateTabs_Document(); } private void CalculateTabs_ToolWindow() { if (Tabs.Count <= 1 || DockPane.IsAutoHide) return; Rectangle rectTabStrip = TabStripRectangle; // Calculate tab widths int countTabs = Tabs.Count; foreach (TabVS2005 tab in Tabs) { tab.MaxWidth = GetMaxTabWidth(Tabs.IndexOf(tab)); tab.Flag = false; } // Set tab whose max width less than average width bool anyWidthWithinAverage = true; int totalWidth = rectTabStrip.Width - ToolWindowStripGapLeft - ToolWindowStripGapRight; int totalAllocatedWidth = 0; int averageWidth = totalWidth / countTabs; int remainedTabs = countTabs; for (anyWidthWithinAverage = true; anyWidthWithinAverage && remainedTabs > 0; ) { anyWidthWithinAverage = false; foreach (TabVS2005 tab in Tabs) { if (tab.Flag) continue; if (tab.MaxWidth <= averageWidth) { tab.Flag = true; tab.TabWidth = tab.MaxWidth; totalAllocatedWidth += tab.TabWidth; anyWidthWithinAverage = true; remainedTabs--; } } if (remainedTabs != 0) averageWidth = (totalWidth - totalAllocatedWidth) / remainedTabs; } // If any tab width not set yet, set it to the average width if (remainedTabs > 0) { int roundUpWidth = (totalWidth - totalAllocatedWidth) - (averageWidth * remainedTabs); foreach (TabVS2005 tab in Tabs) { if (tab.Flag) continue; tab.Flag = true; if (roundUpWidth > 0) { tab.TabWidth = averageWidth + 1; roundUpWidth--; } else tab.TabWidth = averageWidth; } } // Set the X position of the tabs int x = rectTabStrip.X + ToolWindowStripGapLeft; foreach (TabVS2005 tab in Tabs) { tab.TabX = x; x += tab.TabWidth; } } private bool CalculateDocumentTab(Rectangle rectTabStrip, ref int x, int index) { bool overflow = false; TabVS2005 tab = Tabs[index] as TabVS2005; tab.MaxWidth = GetMaxTabWidth(index); int width = Math.Min(tab.MaxWidth, DocumentTabMaxWidth); if (x + width < rectTabStrip.Right || index == StartDisplayingTab) { tab.TabX = x; tab.TabWidth = width; EndDisplayingTab = index; } else { tab.TabX = 0; tab.TabWidth = 0; overflow = true; } x += width; return overflow; } /// <summary> /// Calculate which tabs are displayed and in what order. /// </summary> private void CalculateTabs_Document() { if (m_startDisplayingTab >= Tabs.Count) m_startDisplayingTab = 0; Rectangle rectTabStrip = TabsRectangle; int x = rectTabStrip.X + rectTabStrip.Height / 2; bool overflow = false; // Originally all new documents that were considered overflow // (not enough pane strip space to show all tabs) were added to // the far left (assuming not right to left) and the tabs on the // right were dropped from view. If StartDisplayingTab is not 0 // then we are dealing with making sure a specific tab is kept in focus. if (m_startDisplayingTab > 0) { int tempX = x; TabVS2005 tab = Tabs[m_startDisplayingTab] as TabVS2005; tab.MaxWidth = GetMaxTabWidth(m_startDisplayingTab); // Add the active tab and tabs to the left for (int i = StartDisplayingTab; i >= 0; i--) CalculateDocumentTab(rectTabStrip, ref tempX, i); // Store which tab is the first one displayed so that it // will be drawn correctly (without part of the tab cut off) FirstDisplayingTab = EndDisplayingTab; tempX = x; // Reset X location because we are starting over // Start with the first tab displayed - name is a little misleading. // Loop through each tab and set its location. If there is not enough // room for all of them overflow will be returned. for (int i = EndDisplayingTab; i < Tabs.Count; i++) overflow = CalculateDocumentTab(rectTabStrip, ref tempX, i); // If not all tabs are shown then we have an overflow. if (FirstDisplayingTab != 0) overflow = true; } else { for (int i = StartDisplayingTab; i < Tabs.Count; i++) overflow = CalculateDocumentTab(rectTabStrip, ref x, i); for (int i = 0; i < StartDisplayingTab; i++) overflow = CalculateDocumentTab(rectTabStrip, ref x, i); FirstDisplayingTab = StartDisplayingTab; } if (!overflow) { m_startDisplayingTab = 0; FirstDisplayingTab = 0; x = rectTabStrip.X + rectTabStrip.Height / 2; foreach (TabVS2005 tab in Tabs) { tab.TabX = x; x += tab.TabWidth; } } DocumentTabsOverflow = overflow; } protected internal override void EnsureTabVisible(IDockContent content) { if (Appearance != DockPane.AppearanceStyle.Document || !Tabs.Contains(content)) return; CalculateTabs(); EnsureDocumentTabVisible(content, true); } private bool EnsureDocumentTabVisible(IDockContent content, bool repaint) { int index = Tabs.IndexOf(content); TabVS2005 tab = Tabs[index] as TabVS2005; if (tab.TabWidth != 0) return false; StartDisplayingTab = index; if (repaint) Invalidate(); return true; } private int GetMaxTabWidth(int index) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetMaxTabWidth_ToolWindow(index); else return GetMaxTabWidth_Document(index); } private int GetMaxTabWidth_ToolWindow(int index) { IDockContent content = Tabs[index].Content; Size sizeString = TextRenderer.MeasureText(content.DockHandler.TabText, TextFont); return ToolWindowImageWidth + sizeString.Width + ToolWindowImageGapLeft + ToolWindowImageGapRight + ToolWindowTextGapRight; } private int GetMaxTabWidth_Document(int index) { IDockContent content = Tabs[index].Content; int height = GetTabRectangle_Document(index).Height; Size sizeText = TextRenderer.MeasureText(content.DockHandler.TabText, BoldFont, new Size(DocumentTabMaxWidth, height), DocumentTextFormat); if (DockPane.DockPanel.ShowDocumentIcon) return sizeText.Width + DocumentIconWidth + DocumentIconGapLeft + DocumentIconGapRight + DocumentTextGapRight; else return sizeText.Width + DocumentIconGapLeft + DocumentTextGapRight; } private void DrawTabStrip(Graphics g) { if (Appearance == DockPane.AppearanceStyle.Document) DrawTabStrip_Document(g); else DrawTabStrip_ToolWindow(g); } private void DrawTabStrip_Document(Graphics g) { int count = Tabs.Count; if (count == 0) return; Rectangle rectTabStrip = TabStripRectangle; // Draw the tabs Rectangle rectTabOnly = TabsRectangle; Rectangle rectTab = Rectangle.Empty; TabVS2005 tabActive = null; g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly)); for (int i = 0; i < count; i++) { rectTab = GetTabRectangle(i); if (Tabs[i].Content == DockPane.ActiveContent) { tabActive = Tabs[i] as TabVS2005; continue; } if (rectTab.IntersectsWith(rectTabOnly)) DrawTab(g, Tabs[i] as TabVS2005, rectTab); } g.SetClip(rectTabStrip); if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) g.DrawLine(PenDocumentTabActiveBorder, rectTabStrip.Left, rectTabStrip.Top + 1, rectTabStrip.Right, rectTabStrip.Top + 1); else g.DrawLine(PenDocumentTabActiveBorder, rectTabStrip.Left, rectTabStrip.Bottom - 1, rectTabStrip.Right, rectTabStrip.Bottom - 1); g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly)); if (tabActive != null) { rectTab = GetTabRectangle(Tabs.IndexOf(tabActive)); if (rectTab.IntersectsWith(rectTabOnly)) DrawTab(g, tabActive, rectTab); } } private void DrawTabStrip_ToolWindow(Graphics g) { Rectangle rectTabStrip = TabStripRectangle; g.DrawLine(PenToolWindowTabBorder, rectTabStrip.Left, rectTabStrip.Top, rectTabStrip.Right, rectTabStrip.Top); for (int i = 0; i < Tabs.Count; i++) DrawTab(g, Tabs[i] as TabVS2005, GetTabRectangle(i)); } private Rectangle GetTabRectangle(int index) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetTabRectangle_ToolWindow(index); else return GetTabRectangle_Document(index); } private Rectangle GetTabRectangle_ToolWindow(int index) { Rectangle rectTabStrip = TabStripRectangle; TabVS2005 tab = (TabVS2005)(Tabs[index]); return new Rectangle(tab.TabX, rectTabStrip.Y, tab.TabWidth, rectTabStrip.Height); } private Rectangle GetTabRectangle_Document(int index) { Rectangle rectTabStrip = TabStripRectangle; TabVS2005 tab = (TabVS2005)Tabs[index]; Rectangle rect = new Rectangle(); rect.X = tab.TabX; rect.Width = tab.TabWidth; rect.Height = rectTabStrip.Height - DocumentTabGapTop; if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) rect.Y = rectTabStrip.Y + DocumentStripGapBottom; else rect.Y = rectTabStrip.Y + DocumentTabGapTop; return rect; } private void DrawTab(Graphics g, TabVS2005 tab, Rectangle rect) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) DrawTab_ToolWindow(g, tab, rect); else DrawTab_Document(g, tab, rect); } private GraphicsPath GetTabOutline(Tab tab, bool rtlTransform, bool toScreen) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetTabOutline_ToolWindow(tab, rtlTransform, toScreen); else return GetTabOutline_Document(tab, rtlTransform, toScreen, false); } private GraphicsPath GetTabOutline_ToolWindow(Tab tab, bool rtlTransform, bool toScreen) { Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab)); if (rtlTransform) rect = DrawHelper.RtlTransform(this, rect); if (toScreen) rect = RectangleToScreen(rect); DrawHelper.GetRoundedCornerTab(GraphicsPath, rect, false); return GraphicsPath; } private GraphicsPath GetTabOutline_Document(Tab tab, bool rtlTransform, bool toScreen, bool full) { int curveSize = 6; GraphicsPath.Reset(); Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab)); if (rtlTransform) rect = DrawHelper.RtlTransform(this, rect); if (toScreen) rect = RectangleToScreen(rect); // Draws the full angle piece for active content (or first tab) if (tab.Content == DockPane.ActiveContent || full || Tabs.IndexOf(tab) == FirstDisplayingTab) { if (RightToLeft == RightToLeft.Yes) { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { // For some reason the next line draws a line that is not hidden like it is when drawing the tab strip on top. // It is not needed so it has been commented out. //GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right + rect.Height / 2, rect.Bottom); GraphicsPath.AddLine(rect.Right + rect.Height / 2, rect.Top, rect.Right - rect.Height / 2 + curveSize / 2, rect.Bottom - curveSize / 2); } else { GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right + rect.Height / 2, rect.Bottom); GraphicsPath.AddLine(rect.Right + rect.Height / 2, rect.Bottom, rect.Right - rect.Height / 2 + curveSize / 2, rect.Top + curveSize / 2); } } else { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { // For some reason the next line draws a line that is not hidden like it is when drawing the tab strip on top. // It is not needed so it has been commented out. //GraphicsPath.AddLine(rect.Left, rect.Top, rect.Left - rect.Height / 2, rect.Top); GraphicsPath.AddLine(rect.Left - rect.Height / 2, rect.Top, rect.Left + rect.Height / 2 - curveSize / 2, rect.Bottom - curveSize / 2); } else { GraphicsPath.AddLine(rect.Left, rect.Bottom, rect.Left - rect.Height / 2, rect.Bottom); GraphicsPath.AddLine(rect.Left - rect.Height / 2, rect.Bottom, rect.Left + rect.Height / 2 - curveSize / 2, rect.Top + curveSize / 2); } } } // Draws the partial angle for non-active content else { if (RightToLeft == RightToLeft.Yes) { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { GraphicsPath.AddLine(rect.Right, rect.Top, rect.Right, rect.Top + rect.Height / 2); GraphicsPath.AddLine(rect.Right, rect.Top + rect.Height / 2, rect.Right - rect.Height / 2 + curveSize / 2, rect.Bottom - curveSize / 2); } else { GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right, rect.Bottom - rect.Height / 2); GraphicsPath.AddLine(rect.Right, rect.Bottom - rect.Height / 2, rect.Right - rect.Height / 2 + curveSize / 2, rect.Top + curveSize / 2); } } else { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { GraphicsPath.AddLine(rect.Left, rect.Top, rect.Left, rect.Top + rect.Height / 2); GraphicsPath.AddLine(rect.Left, rect.Top + rect.Height / 2, rect.Left + rect.Height / 2 - curveSize / 2, rect.Bottom - curveSize / 2); } else { GraphicsPath.AddLine(rect.Left, rect.Bottom, rect.Left, rect.Bottom - rect.Height / 2); GraphicsPath.AddLine(rect.Left, rect.Bottom - rect.Height / 2, rect.Left + rect.Height / 2 - curveSize / 2, rect.Top + curveSize / 2); } } } if (RightToLeft == RightToLeft.Yes) { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { // Draws the bottom horizontal line (short side) GraphicsPath.AddLine(rect.Right - rect.Height / 2 - curveSize / 2, rect.Bottom, rect.Left + curveSize / 2, rect.Bottom); // Drawing the rounded corner is not necessary. The path is automatically connected //GraphicsPath.AddArc(new Rectangle(rect.Left, rect.Top, curveSize, curveSize), 180, 90); } else { // Draws the bottom horizontal line (short side) GraphicsPath.AddLine(rect.Right - rect.Height / 2 - curveSize / 2, rect.Top, rect.Left + curveSize / 2, rect.Top); GraphicsPath.AddArc(new Rectangle(rect.Left, rect.Top, curveSize, curveSize), 180, 90); } } else { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { // Draws the bottom horizontal line (short side) GraphicsPath.AddLine(rect.Left + rect.Height / 2 + curveSize / 2, rect.Bottom, rect.Right - curveSize / 2, rect.Bottom); // Drawing the rounded corner is not necessary. The path is automatically connected //GraphicsPath.AddArc(new Rectangle(rect.Right - curveSize, rect.Bottom, curveSize, curveSize), 90, -90); } else { // Draws the top horizontal line (short side) GraphicsPath.AddLine(rect.Left + rect.Height / 2 + curveSize / 2, rect.Top, rect.Right - curveSize / 2, rect.Top); // Draws the rounded corner oppposite the angled side GraphicsPath.AddArc(new Rectangle(rect.Right - curveSize, rect.Top, curveSize, curveSize), -90, 90); } } if (Tabs.IndexOf(tab) != EndDisplayingTab && (Tabs.IndexOf(tab) != Tabs.Count - 1 && Tabs[Tabs.IndexOf(tab) + 1].Content == DockPane.ActiveContent) && !full) { if (RightToLeft == RightToLeft.Yes) { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { GraphicsPath.AddLine(rect.Left, rect.Bottom - curveSize / 2, rect.Left, rect.Bottom - rect.Height / 2); GraphicsPath.AddLine(rect.Left, rect.Bottom - rect.Height / 2, rect.Left + rect.Height / 2, rect.Top); } else { GraphicsPath.AddLine(rect.Left, rect.Top + curveSize / 2, rect.Left, rect.Top + rect.Height / 2); GraphicsPath.AddLine(rect.Left, rect.Top + rect.Height / 2, rect.Left + rect.Height / 2, rect.Bottom); } } else { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { GraphicsPath.AddLine(rect.Right, rect.Bottom - curveSize / 2, rect.Right, rect.Bottom - rect.Height / 2); GraphicsPath.AddLine(rect.Right, rect.Bottom - rect.Height / 2, rect.Right - rect.Height / 2, rect.Top); } else { GraphicsPath.AddLine(rect.Right, rect.Top + curveSize / 2, rect.Right, rect.Top + rect.Height / 2); GraphicsPath.AddLine(rect.Right, rect.Top + rect.Height / 2, rect.Right - rect.Height / 2, rect.Bottom); } } } else { // Draw the vertical line opposite the angled side if (RightToLeft == RightToLeft.Yes) { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) GraphicsPath.AddLine(rect.Left, rect.Bottom - curveSize / 2, rect.Left, rect.Top); else GraphicsPath.AddLine(rect.Left, rect.Top + curveSize / 2, rect.Left, rect.Bottom); } else { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) GraphicsPath.AddLine(rect.Right, rect.Bottom - curveSize / 2, rect.Right, rect.Top); else GraphicsPath.AddLine(rect.Right, rect.Top + curveSize / 2, rect.Right, rect.Bottom); } } return GraphicsPath; } private void DrawTab_ToolWindow(Graphics g, TabVS2005 tab, Rectangle rect) { Rectangle rectIcon = new Rectangle( rect.X + ToolWindowImageGapLeft, rect.Y + rect.Height - 1 - ToolWindowImageGapBottom - ToolWindowImageHeight, ToolWindowImageWidth, ToolWindowImageHeight); Rectangle rectText = rectIcon; rectText.X += rectIcon.Width + ToolWindowImageGapRight; rectText.Width = rect.Width - rectIcon.Width - ToolWindowImageGapLeft - ToolWindowImageGapRight - ToolWindowTextGapRight; Rectangle rectTab = DrawHelper.RtlTransform(this, rect); rectText = DrawHelper.RtlTransform(this, rectText); rectIcon = DrawHelper.RtlTransform(this, rectIcon); GraphicsPath path = GetTabOutline(tab, true, false); if (DockPane.ActiveContent == tab.Content) { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.LinearGradientMode; g.FillPath(new LinearGradientBrush(rectTab, startColor, endColor, gradientMode), path); g.DrawPath(PenToolWindowTabBorder, path); Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor; TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat); } else { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.LinearGradientMode; g.FillPath(new LinearGradientBrush(rectTab, startColor, endColor, gradientMode), path); if (Tabs.IndexOf(DockPane.ActiveContent) != Tabs.IndexOf(tab) + 1) { Point pt1 = new Point(rect.Right, rect.Top + ToolWindowTabSeperatorGapTop); Point pt2 = new Point(rect.Right, rect.Bottom - ToolWindowTabSeperatorGapBottom); g.DrawLine(PenToolWindowTabBorder, DrawHelper.RtlTransform(this, pt1), DrawHelper.RtlTransform(this, pt2)); } Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.TextColor; TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat); } if (rectTab.Contains(rectIcon)) g.DrawIcon(new Icon(tab.Content.DockHandler.Icon, new Size(rectIcon.Width, rectIcon.Height)), rectIcon); } private void DrawTab_Document(Graphics g, TabVS2005 tab, Rectangle rect) { if (tab.TabWidth == 0) return; Rectangle rectIcon = new Rectangle( rect.X + DocumentIconGapLeft, rect.Y + rect.Height - 1 - DocumentIconGapBottom - DocumentIconHeight, DocumentIconWidth, DocumentIconHeight); Rectangle rectText = rectIcon; rectIcon.Y += 1; if (DockPane.DockPanel.ShowDocumentIcon) { rectText.X += rectIcon.Width + DocumentIconGapRight; rectText.Y = rect.Y; rectText.Width = rect.Width - rectIcon.Width - DocumentIconGapLeft - DocumentIconGapRight - DocumentTextGapRight; rectText.Height = rect.Height; } else rectText.Width = rect.Width - DocumentIconGapLeft - DocumentTextGapRight; Rectangle rectTab = DrawHelper.RtlTransform(this, rect); Rectangle rectBack = DrawHelper.RtlTransform(this, rect); rectBack.Width += rect.X; rectBack.X = 0; rectText = DrawHelper.RtlTransform(this, rectText); rectIcon = DrawHelper.RtlTransform(this, rectIcon); GraphicsPath path = GetTabOutline(tab, true, false); if (DockPane.ActiveContent == tab.Content) { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.LinearGradientMode; g.FillPath(new LinearGradientBrush(rectBack, startColor, endColor, gradientMode), path); g.DrawPath(PenDocumentTabActiveBorder, path); Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.TextColor; if (DockPane.IsActiveDocumentPane) TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, BoldFont, rectText, textColor, DocumentTextFormat); else TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, DocumentTextFormat); } else { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.LinearGradientMode; g.FillPath(new LinearGradientBrush(rectBack, startColor, endColor, gradientMode), path); g.DrawPath(PenDocumentTabInactiveBorder, path); Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.TextColor; TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, DocumentTextFormat); } if (rectTab.Contains(rectIcon) && DockPane.DockPanel.ShowDocumentIcon) g.DrawIcon(new Icon(tab.Content.DockHandler.Icon, new Size(rectIcon.Width, rectIcon.Height)), rectIcon); } private void WindowList_Click(object sender, EventArgs e) { int x = 0; int y = ButtonWindowList.Location.Y + ButtonWindowList.Height; SelectMenu.Items.Clear(); foreach (TabVS2005 tab in Tabs) { IDockContent content = tab.Content; ToolStripItem item = SelectMenu.Items.Add(content.DockHandler.TabText, content.DockHandler.Icon.ToBitmap()); item.Tag = tab.Content; item.Click += new EventHandler(ContextMenuItem_Click); } SelectMenu.Show(ButtonWindowList, x, y); } private void ContextMenuItem_Click(object sender, EventArgs e) { ToolStripMenuItem item = sender as ToolStripMenuItem; if (item != null) { IDockContent content = (IDockContent)item.Tag; DockPane.ActiveContent = content; } } private void SetInertButtons() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) { if (m_buttonClose != null) m_buttonClose.Left = -m_buttonClose.Width; if (m_buttonWindowList != null) m_buttonWindowList.Left = -m_buttonWindowList.Width; } else { ButtonClose.Enabled = DockPane.ActiveContent == null ? true : DockPane.ActiveContent.DockHandler.CloseButton; m_closeButtonVisible = DockPane.ActiveContent == null ? true : DockPane.ActiveContent.DockHandler.CloseButtonVisible; ButtonClose.Visible = m_closeButtonVisible; ButtonClose.RefreshChanges(); ButtonWindowList.RefreshChanges(); } } protected override void OnLayout(LayoutEventArgs levent) { if (Appearance == DockPane.AppearanceStyle.Document) { LayoutButtons(); OnRefreshChanges(); } base.OnLayout(levent); } private void LayoutButtons() { Rectangle rectTabStrip = TabStripRectangle; // Set position and size of the buttons int buttonWidth = ButtonClose.Image.Width; int buttonHeight = ButtonClose.Image.Height; int height = rectTabStrip.Height - DocumentButtonGapTop - DocumentButtonGapBottom; if (buttonHeight < height) { buttonWidth = buttonWidth * (height / buttonHeight); buttonHeight = height; } Size buttonSize = new Size(buttonWidth, buttonHeight); int x = rectTabStrip.X + rectTabStrip.Width - DocumentTabGapLeft - DocumentButtonGapRight - buttonWidth; int y = rectTabStrip.Y + DocumentButtonGapTop; Point point = new Point(x, y); ButtonClose.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); // If the close button is not visible draw the window list button overtop. // Otherwise it is drawn to the left of the close button. if (m_closeButtonVisible) point.Offset(-(DocumentButtonGapBetween + buttonWidth), 0); ButtonWindowList.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); } private void Close_Click(object sender, EventArgs e) { DockPane.CloseActiveContent(); } public override int HitTest(Point ptMouse) { if (!TabsRectangle.Contains(ptMouse)) return -1; foreach (Tab tab in Tabs) { GraphicsPath path = GetTabOutline(tab, true, false); if (path.IsVisible(ptMouse)) return Tabs.IndexOf(tab); } return -1; } protected override void OnMouseHover(EventArgs e) { int index = HitTest(PointToClient(Control.MousePosition)); string toolTip = string.Empty; base.OnMouseHover(e); if (index != -1) { TabVS2005 tab = Tabs[index] as TabVS2005; if (!String.IsNullOrEmpty(tab.Content.DockHandler.ToolTipText)) toolTip = tab.Content.DockHandler.ToolTipText; else if (tab.MaxWidth > tab.TabWidth) toolTip = tab.Content.DockHandler.TabText; } if (m_toolTip.GetToolTip(this) != toolTip) { m_toolTip.Active = false; m_toolTip.SetToolTip(this, toolTip); m_toolTip.Active = true; } // requires further tracking of mouse hover behavior, ResetMouseEventArgs(); } protected override void OnRightToLeftChanged(EventArgs e) { base.OnRightToLeftChanged(e); PerformLayout(); } } }
using System; using System.Text; using Signum.Entities.Authorization; using Signum.Entities.Processes; using Signum.Utilities; using Signum.Entities.Basics; using System.ComponentModel; using System.Net.Mail; using System.Linq.Expressions; using Signum.Entities.Files; using System.Security.Cryptography; using System.Reflection; using Signum.Entities; namespace Signum.Entities.Mailing { [Serializable, EntityKind(EntityKind.Main, EntityData.Transactional)] public class EmailMessageEntity : Entity, IProcessLineDataEntity { public EmailMessageEntity() { this.UniqueIdentifier = Guid.NewGuid(); this.RebindEvents(); } [CountIsValidator(ComparisonType.GreaterThan, 0)] public MList<EmailRecipientEmbedded> Recipients { get; set; } = new MList<EmailRecipientEmbedded>(); [ImplementedByAll] public Lite<Entity>? Target { get; set; } public EmailFromEmbedded From { get; set; } public Lite<EmailTemplateEntity>? Template { get; set; } public DateTime CreationDate { get; private set; } = TimeZoneManager.Now; public DateTime? Sent { get; set; } public DateTime? ReceptionNotified { get; set; } [DbType(Size = int.MaxValue)] string? subject; [StringLengthValidator(AllowLeadingSpaces = true, AllowTrailingSpaces = true)] public string? Subject { get { return subject; } set { if (Set(ref subject, value)) SetCalculateHash(); } } [DbType(Size = int.MaxValue)] BigStringEmbedded body = new BigStringEmbedded(); [NotifyChildProperty] public BigStringEmbedded Body { get { return body; } set { if (Set(ref body, value)) SetCalculateHash(); } } static readonly char[] spaceChars = new[] { '\r', '\n', ' ' }; public string CalculateHash() { var str = subject + body.Text; return Convert.ToBase64String(SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(str.Trim(spaceChars)))); } public void SetCalculateHash() { BodyHash = CalculateHash(); } [StringLengthValidator(Min = 1, Max = 150)] public string? BodyHash { get; set; } public bool IsBodyHtml { get; set; } = false; public Lite<ExceptionEntity>? Exception { get; set; } public EmailMessageState State { get; set; } public Guid? UniqueIdentifier { get; set; } public bool EditableMessage { get; set; } = true; public Lite<EmailPackageEntity>? Package { get; set; } public Guid? ProcessIdentifier { get; set; } public int SendRetries { get; set; } [NoRepeatValidator] public MList<EmailAttachmentEmbedded> Attachments { get; set; } = new MList<EmailAttachmentEmbedded>(); static StateValidator<EmailMessageEntity, EmailMessageState> validator = new StateValidator<EmailMessageEntity, EmailMessageState>( m => m.State, m => m.Exception, m => m.Sent, m => m.ReceptionNotified, m => m.Package) { {EmailMessageState.Created, false, false, false, null }, {EmailMessageState.Draft, false, false, false, null }, {EmailMessageState.ReadyToSend, false, false, false, null }, {EmailMessageState.RecruitedForSending, false, false, false, null }, {EmailMessageState.Sent, false, true, false, null }, {EmailMessageState.SentException, true, null, false, null }, {EmailMessageState.ReceptionNotified, true, true, true, null }, {EmailMessageState.Received, false, false, false, false }, {EmailMessageState.Outdated, false, false, false, null }, }; [AutoExpressionField] public override string ToString() => As.Expression(() => Subject!); protected override string? PropertyValidation(PropertyInfo pi) { return validator.Validate(this, pi); } protected override void PreSaving(PreSavingContext ctx) { SetCalculateHash(); base.PreSaving(ctx); } } [Serializable] public class EmailReceptionMixin : MixinEntity { protected EmailReceptionMixin(ModifiableEntity mainEntity, MixinEntity next) : base(mainEntity, next) { } public EmailReceptionInfoEmbedded? ReceptionInfo { get; set; } } [Serializable] public class EmailReceptionInfoEmbedded : EmbeddedEntity { [UniqueIndex(AllowMultipleNulls = true)] [StringLengthValidator(Min = 1, Max = 100)] public string UniqueId { get; set; } public Lite<Pop3ReceptionEntity> Reception { get; set; } [DbType(Size = int.MaxValue), ForceNotNullable] public string RawContent { get; set; } public DateTime SentDate { get; set; } public DateTime ReceivedDate { get; set; } public DateTime? DeletionDate { get; set; } } [Serializable] public class EmailAttachmentEmbedded : EmbeddedEntity { public EmailAttachmentType Type { get; set; } FilePathEmbedded file; //[DefaultFileType(nameof(EmailFileType.Attachment), nameof(EmailFileType))] is optional to register it public FilePathEmbedded File { get { return file; } set { if (Set(ref file, value)) { if (ContentId == null && File != null) ContentId = Guid.NewGuid() + File.FileName; } } } [StringLengthValidator(Min = 1, Max = 300)] public string ContentId { get; set; } public EmailAttachmentEmbedded Clone() { return new EmailAttachmentEmbedded { ContentId = ContentId, File = file.Clone(), Type = Type, }; } internal bool Similar(EmailAttachmentEmbedded a) { return ContentId == a.ContentId || File.FileName == a.File.FileName; } public override string ToString() { return file?.ToString() ?? ""; } } public enum EmailAttachmentType { Attachment, LinkedResource } [Serializable] public class EmailRecipientEmbedded : EmailAddressEmbedded, IEquatable<EmailRecipientEmbedded> { public EmailRecipientEmbedded() { } public EmailRecipientEmbedded(EmailOwnerData data) : base(data) { Kind = EmailRecipientKind.To; } public EmailRecipientEmbedded(MailAddress ma, EmailRecipientKind kind) : base(ma) { this.Kind = kind; } public EmailRecipientKind Kind { get; set; } public EmailRecipientEmbedded Clone() { return new EmailRecipientEmbedded { DisplayName = DisplayName, EmailAddress = EmailAddress, EmailOwner = EmailOwner, Kind = Kind, }; } public override bool Equals(object? obj) => obj is EmailAddressEmbedded eae && Equals(eae); public bool Equals(EmailRecipientEmbedded? other) => other != null && base.Equals(other) && Kind == other.Kind; public override int GetHashCode() => HashCode.Combine(base.GetHashCode(), Kind.GetHashCode()); public string BaseToString() { return base.ToString(); } public override string ToString() { return "{0}: {1}".FormatWith(Kind.NiceToString(), base.ToString()); } } public enum EmailRecipientKind { To, Cc, Bcc } [Serializable] public abstract class EmailAddressEmbedded : EmbeddedEntity, IEquatable<EmailAddressEmbedded> { public EmailAddressEmbedded() { } public EmailAddressEmbedded(EmailOwnerData data) { EmailOwner = data.Owner; EmailAddress = data.Email!; DisplayName = data.DisplayName; } public EmailAddressEmbedded(MailAddress mailAddress) { DisplayName = mailAddress.DisplayName; EmailAddress = mailAddress.Address; } public Lite<IEmailOwnerEntity>? EmailOwner { get; set; } [StringLengthValidator(Min = 3, Max = 100)] public string EmailAddress { get; set; } public bool InvalidEmail { get; set; } protected override string? PropertyValidation(PropertyInfo pi) { if (pi.Name == nameof(EmailAddress) && !InvalidEmail && !EMailValidatorAttribute.EmailRegex.IsMatch(EmailAddress)) return ValidationMessage._0DoesNotHaveAValid1Format.NiceToString().FormatWith("{0}", pi.NiceName()); return base.PropertyValidation(pi); } public string? DisplayName { get; set; } public override string ToString() { return "{0} <{1}>".FormatWith(DisplayName, EmailAddress); } public override bool Equals(object? obj) => obj is EmailAddressEmbedded eae && Equals(eae); public bool Equals(EmailAddressEmbedded? other) => other != null && other.EmailAddress == EmailAddress && other.DisplayName == DisplayName; public override int GetHashCode() => HashCode.Combine((EmailAddress ?? "").GetHashCode(), (DisplayName ?? "").GetHashCode()); } [Serializable] public class EmailFromEmbedded : EmailAddressEmbedded, IEquatable<EmailFromEmbedded> { public EmailFromEmbedded() { } public EmailFromEmbedded(EmailOwnerData data) : base(data) { AzureUserId = data.AzureUserId; } public Guid? AzureUserId { get; set; } public EmailFromEmbedded Clone() { return new EmailFromEmbedded { DisplayName = DisplayName, EmailAddress = EmailAddress, EmailOwner = EmailOwner, AzureUserId = AzureUserId, }; } public override bool Equals(object? obj) => obj is EmailFromEmbedded eae && Equals(eae); public bool Equals(EmailFromEmbedded? other) => other != null && base.Equals(other) && other.AzureUserId == AzureUserId; public override int GetHashCode() => base.GetHashCode(); } public enum EmailMessageState { [Ignore] Created, Draft, ReadyToSend, RecruitedForSending, Sent, SentException, ReceptionNotified, Received, Outdated } public interface IEmailOwnerEntity : IEntity { } [DescriptionOptions(DescriptionOptions.Description | DescriptionOptions.Members)] public class EmailOwnerData : IEquatable<EmailOwnerData> { public Lite<IEmailOwnerEntity>? Owner { get; set; } public string? Email { get; set; } public string? DisplayName { get; set; } public CultureInfoEntity? CultureInfo { get; set; } public Guid? AzureUserId { get; set; } public override bool Equals(object? obj) => obj is EmailOwnerData eod && Equals(eod); public bool Equals(EmailOwnerData? other) { return Owner != null && other != null && other.Owner != null && Owner.Equals(other.Owner); } public override int GetHashCode() { return Owner == null ? base.GetHashCode() : Owner.GetHashCode(); } public override string ToString() { return "{0} <{1}> ({2})".FormatWith(DisplayName, Email, Owner); } } [AutoInit] public static class EmailMessageProcess { public static readonly ProcessAlgorithmSymbol CreateEmailsSendAsync; public static ProcessAlgorithmSymbol SendEmails; } [AutoInit] public static class EmailMessageOperation { public static ExecuteSymbol<EmailMessageEntity> Save; public static ExecuteSymbol<EmailMessageEntity> ReadyToSend; public static ExecuteSymbol<EmailMessageEntity> Send; public static ConstructSymbol<EmailMessageEntity>.From<EmailMessageEntity> ReSend; public static ConstructSymbol<ProcessEntity>.FromMany<EmailMessageEntity> ReSendEmails; public static ConstructSymbol<EmailMessageEntity>.Simple CreateMail; public static ConstructSymbol<EmailMessageEntity>.From<EmailTemplateEntity> CreateEmailFromTemplate; public static DeleteSymbol<EmailMessageEntity> Delete; } public enum EmailMessageMessage { [Description("The email message cannot be sent from state {0}")] TheEmailMessageCannotBeSentFromState0, [Description("Message")] Message, Messages, RemainingMessages, ExceptionMessages, [Description("{0} {1} requires extra parameters")] _01requiresExtraParameters } [Serializable, EntityKind(EntityKind.System, EntityData.Transactional), TicksColumn(false)] public class EmailPackageEntity : Entity, IProcessDataEntity { [StringLengthValidator(Max = 200)] public string? Name { get; set; } public override string ToString() { return "EmailPackage {0}".FormatWith(Name); } } [AutoInit] public static class EmailFileType { public static FileTypeSymbol Attachment; } [AutoInit] public static class AsyncEmailSenderPermission { public static PermissionSymbol ViewAsyncEmailSenderPanel; } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.ObjectModel; using System.Management.Automation.Internal; using System.Management.Automation.Runspaces.Internal; using System.Runtime.Serialization; using System.Threading; using PSHost = System.Management.Automation.Host.PSHost; namespace System.Management.Automation.Runspaces { #region Exceptions /// <summary> /// Exception thrown when state of the runspace pool is different from /// expected state of runspace pool. /// </summary> [Serializable] public class InvalidRunspacePoolStateException : SystemException { /// <summary> /// Creates a new instance of InvalidRunspacePoolStateException class. /// </summary> public InvalidRunspacePoolStateException() : base ( StringUtil.Format(RunspacePoolStrings.InvalidRunspacePoolStateGeneral) ) { } /// <summary> /// Creates a new instance of InvalidRunspacePoolStateException class. /// </summary> /// <param name="message"> /// The error message that explains the reason for the exception. /// </param> public InvalidRunspacePoolStateException(string message) : base(message) { } /// <summary> /// Creates a new instance of InvalidRunspacePoolStateException class. /// </summary> /// <param name="message"> /// The error message that explains the reason for the exception. /// </param> /// <param name="innerException"> /// The exception that is the cause of the current exception. /// </param> public InvalidRunspacePoolStateException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Initializes a new instance of the InvalidRunspacePoolStateException /// with a specified error message and current and expected state. /// </summary> /// <param name="message">The message that describes the error.</param> /// <param name="currentState">Current state of runspace pool.</param> /// <param name="expectedState">Expected state of the runspace pool.</param> internal InvalidRunspacePoolStateException ( string message, RunspacePoolState currentState, RunspacePoolState expectedState ) : base(message) { _expectedState = expectedState; _currentState = currentState; } #region ISerializable Members // No need to implement GetObjectData // if all fields are static or [NonSerialized] /// <summary> /// Initializes a new instance of the InvalidRunspacePoolStateException /// class with serialized data. /// </summary> /// <param name="info"> /// The <see cref="SerializationInfo"/> that holds /// the serialized object data about the exception being thrown. /// </param> /// <param name="context"> /// The <see cref="StreamingContext"/> that contains /// contextual information about the source or destination. /// </param> protected InvalidRunspacePoolStateException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endregion /// <summary> /// Access CurrentState of the runspace pool. /// </summary> /// <remarks> /// This is the state of the runspace pool when exception was thrown. /// </remarks> public RunspacePoolState CurrentState { get { return _currentState; } } /// <summary> /// Expected state of runspace pool by the operation which has thrown /// this exception. /// </summary> public RunspacePoolState ExpectedState { get { return _expectedState; } } /// <summary> /// Converts the current to an InvalidRunspaceStateException. /// </summary> internal InvalidRunspaceStateException ToInvalidRunspaceStateException() { InvalidRunspaceStateException exception = new InvalidRunspaceStateException( RunspaceStrings.InvalidRunspaceStateGeneral, this); exception.CurrentState = RunspacePoolStateToRunspaceState(this.CurrentState); exception.ExpectedState = RunspacePoolStateToRunspaceState(this.ExpectedState); return exception; } /// <summary> /// Converts a RunspacePoolState to a RunspaceState. /// </summary> private static RunspaceState RunspacePoolStateToRunspaceState(RunspacePoolState state) { switch (state) { case RunspacePoolState.BeforeOpen: return RunspaceState.BeforeOpen; case RunspacePoolState.Opening: return RunspaceState.Opening; case RunspacePoolState.Opened: return RunspaceState.Opened; case RunspacePoolState.Closed: return RunspaceState.Closed; case RunspacePoolState.Closing: return RunspaceState.Closing; case RunspacePoolState.Broken: return RunspaceState.Broken; case RunspacePoolState.Disconnecting: return RunspaceState.Disconnecting; case RunspacePoolState.Disconnected: return RunspaceState.Disconnected; case RunspacePoolState.Connecting: return RunspaceState.Connecting; default: Diagnostics.Assert(false, "Unexpected RunspacePoolState"); return 0; } } /// <summary> /// State of the runspace pool when exception was thrown. /// </summary> [NonSerialized] private readonly RunspacePoolState _currentState = 0; /// <summary> /// State of the runspace pool expected in method which throws this exception. /// </summary> [NonSerialized] private readonly RunspacePoolState _expectedState = 0; } #endregion #region State /// <summary> /// Defines various states of a runspace pool. /// </summary> public enum RunspacePoolState { /// <summary> /// Beginning state upon creation. /// </summary> BeforeOpen = 0, /// <summary> /// A RunspacePool is being created. /// </summary> Opening = 1, /// <summary> /// The RunspacePool is created and valid. /// </summary> Opened = 2, /// <summary> /// The RunspacePool is closed. /// </summary> Closed = 3, /// <summary> /// The RunspacePool is being closed. /// </summary> Closing = 4, /// <summary> /// The RunspacePool has been disconnected abnormally. /// </summary> Broken = 5, /// <summary> /// The RunspacePool is being disconnected. /// </summary> Disconnecting = 6, /// <summary> /// The RunspacePool has been disconnected. /// </summary> Disconnected = 7, /// <summary> /// The RunspacePool is being connected. /// </summary> Connecting = 8, } /// <summary> /// Event arguments passed to runspacepool state change handlers /// <see cref="RunspacePool.StateChanged"/> event. /// </summary> public sealed class RunspacePoolStateChangedEventArgs : EventArgs { #region Constructors /// <summary> /// Constructor. /// </summary> /// <param name="state"> /// state to raise the event with. /// </param> internal RunspacePoolStateChangedEventArgs(RunspacePoolState state) { RunspacePoolStateInfo = new RunspacePoolStateInfo(state, null); } /// <summary> /// </summary> /// <param name="stateInfo"></param> internal RunspacePoolStateChangedEventArgs(RunspacePoolStateInfo stateInfo) { RunspacePoolStateInfo = stateInfo; } #endregion #region Public Properties /// <summary> /// Gets the stateinfo of RunspacePool when this event occurred. /// </summary> public RunspacePoolStateInfo RunspacePoolStateInfo { get; } #endregion #region Private Data #endregion } /// <summary> /// Event arguments passed to RunspaceCreated event of RunspacePool. /// </summary> internal sealed class RunspaceCreatedEventArgs : EventArgs { #region Private Data #endregion #region Constructors /// <summary> /// </summary> /// <param name="runspace"></param> internal RunspaceCreatedEventArgs(Runspace runspace) { Runspace = runspace; } #endregion #region Internal Properties internal Runspace Runspace { get; } #endregion } #endregion #region RunspacePool Availability /// <summary> /// Defines runspace pool availability. /// </summary> public enum RunspacePoolAvailability { /// <summary> /// RunspacePool is not in the Opened state. /// </summary> None = 0, /// <summary> /// RunspacePool is Opened and available to accept commands. /// </summary> Available = 1, /// <summary> /// RunspacePool on the server is connected to another /// client and is not available to this client for connection /// or running commands. /// </summary> Busy = 2 } #endregion #region RunspacePool Capabilities /// <summary> /// Defines runspace capabilities. /// </summary> public enum RunspacePoolCapability { /// <summary> /// No additional capabilities beyond a default runspace. /// </summary> Default = 0x0, /// <summary> /// Runspacepool and remoting layer supports disconnect/connect feature. /// </summary> SupportsDisconnect = 0x1 } #endregion #region AsyncResult /// <summary> /// Encapsulated the AsyncResult for pool's Open/Close async operations. /// </summary> internal sealed class RunspacePoolAsyncResult : AsyncResult { #region Private Data #endregion #region Constructor /// <summary> /// Constructor. /// </summary> /// <param name="ownerId"> /// Instance Id of the pool creating this instance /// </param> /// <param name="callback"> /// Callback to call when the async operation completes. /// </param> /// <param name="state"> /// A user supplied state to call the "callback" with. /// </param> /// <param name="isCalledFromOpenAsync"> /// true if AsyncResult monitors Async Open. /// false otherwise /// </param> internal RunspacePoolAsyncResult(Guid ownerId, AsyncCallback callback, object state, bool isCalledFromOpenAsync) : base(ownerId, callback, state) { IsAssociatedWithAsyncOpen = isCalledFromOpenAsync; } #endregion #region Internal Properties /// <summary> /// True if AsyncResult monitors Async Open. /// false otherwise. /// </summary> internal bool IsAssociatedWithAsyncOpen { get; } #endregion } /// <summary> /// Encapsulated the results of a RunspacePool.BeginGetRunspace method. /// </summary> internal sealed class GetRunspaceAsyncResult : AsyncResult { #region Private Data private bool _isActive; #endregion #region Constructor /// <summary> /// Constructor. /// </summary> /// <param name="ownerId"> /// Instance Id of the pool creating this instance /// </param> /// <param name="callback"> /// Callback to call when the async operation completes. /// </param> /// <param name="state"> /// A user supplied state to call the "callback" with. /// </param> internal GetRunspaceAsyncResult(Guid ownerId, AsyncCallback callback, object state) : base(ownerId, callback, state) { _isActive = true; } #endregion #region Internal Methods/Properties /// <summary> /// Gets the runspace that is assigned to the async operation. /// </summary> /// <remarks> /// This can be null if the async Get operation is not completed. /// </remarks> internal Runspace Runspace { get; set; } /// <summary> /// Gets or sets a value indicating whether this operation /// is active or not. /// </summary> internal bool IsActive { get { lock (SyncObject) { return _isActive; } } set { lock (SyncObject) { _isActive = value; } } } /// <summary> /// Marks the async operation as completed and releases /// waiting threads. /// </summary> /// <param name="state"> /// This is not used /// </param> /// <remarks> /// This method is called from a thread pool thread to release /// the async operation. /// </remarks> internal void DoComplete(object state) { SetAsCompleted(null); } #endregion } #endregion #region RunspacePool /// <summary> /// Public interface which supports pooling PowerShell Runspaces. /// </summary> public sealed class RunspacePool : IDisposable { #region Private Data private readonly RunspacePoolInternal _internalPool; private readonly object _syncObject = new object(); private event EventHandler<RunspacePoolStateChangedEventArgs> InternalStateChanged = null; private event EventHandler<PSEventArgs> InternalForwardEvent = null; private event EventHandler<RunspaceCreatedEventArgs> InternalRunspaceCreated = null; #endregion #region Internal Constructor /// <summary> /// Constructor which creates a RunspacePool using the /// supplied <paramref name="configuration"/>, /// <paramref name="minRunspaces"/> and <paramref name="maxRunspaces"/> /// </summary> /// <param name="minRunspaces"> /// The minimum number of Runspaces that can exist in this pool. /// Should be greater than or equal to 1. /// </param> /// <param name="maxRunspaces"> /// The maximum number of Runspaces that can exist in this pool. /// Should be greater than or equal to 1. /// </param> /// <param name="host"> /// The explicit PSHost implementation. /// </param> /// <exception cref="ArgumentNullException"> /// Host is null. /// </exception> /// <exception cref="ArgumentException"> /// Maximum runspaces is less than 1. /// Minimum runspaces is less than 1. /// </exception> internal RunspacePool(int minRunspaces, int maxRunspaces, PSHost host) { // Currently we support only Local Runspace Pool.. // this needs to be changed once remote runspace pool // is implemented _internalPool = new RunspacePoolInternal(minRunspaces, maxRunspaces, host); } /// <summary> /// Constructor which creates a RunspacePool using the /// supplied <paramref name="initialSessionState"/>, /// <paramref name="minRunspaces"/> and <paramref name="maxRunspaces"/> /// </summary> /// <param name="minRunspaces"> /// The minimum number of Runspaces that can exist in this pool. /// Should be greater than or equal to 1. /// </param> /// <param name="maxRunspaces"> /// The maximum number of Runspaces that can exist in this pool. /// Should be greater than or equal to 1. /// </param> /// <param name="initialSessionState"> /// InitialSessionState object to use when creating a new Runspace. /// </param> /// <param name="host"> /// The explicit PSHost implementation. /// </param> /// <exception cref="ArgumentNullException"> /// initialSessionState is null. /// Host is null. /// </exception> /// <exception cref="ArgumentException"> /// Maximum runspaces is less than 1. /// Minimum runspaces is less than 1. /// </exception> internal RunspacePool(int minRunspaces, int maxRunspaces, InitialSessionState initialSessionState, PSHost host) { // Currently we support only Local Runspace Pool.. // this needs to be changed once remote runspace pool // is implemented _internalPool = new RunspacePoolInternal(minRunspaces, maxRunspaces, initialSessionState, host); } /// <summary> /// Construct a runspace pool object. /// </summary> /// <param name="minRunspaces">Min runspaces.</param> /// <param name="maxRunspaces">Max runspaces.</param> /// <param name="typeTable">TypeTable.</param> /// <param name="host">Host.</param> /// <param name="applicationArguments">App arguments.</param> /// <param name="connectionInfo">Connection information.</param> /// <param name="name">Session name.</param> internal RunspacePool( int minRunspaces, int maxRunspaces, TypeTable typeTable, PSHost host, PSPrimitiveDictionary applicationArguments, RunspaceConnectionInfo connectionInfo, string name = null) { _internalPool = new RemoteRunspacePoolInternal( minRunspaces, maxRunspaces, typeTable, host, applicationArguments, connectionInfo, name); IsRemote = true; } /// <summary> /// Creates a runspace pool object in a disconnected state that is /// ready to connect to a remote runspace pool session specified by /// the instanceId parameter. /// </summary> /// <param name="isDisconnected">Indicates whether the shell/runspace pool is disconnected.</param> /// <param name="instanceId">Identifies a remote runspace pool session to connect to.</param> /// <param name="name">Friendly name for runspace pool.</param> /// <param name="connectCommands">Runspace pool running commands information.</param> /// <param name="connectionInfo">Connection information of remote server.</param> /// <param name="host">PSHost object.</param> /// <param name="typeTable">TypeTable used for serialization/deserialization of remote objects.</param> internal RunspacePool( bool isDisconnected, Guid instanceId, string name, ConnectCommandInfo[] connectCommands, RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable) { // Disconnect-Connect semantics are currently only supported in WSMan transport. if (connectionInfo is not WSManConnectionInfo) { throw new NotSupportedException(); } _internalPool = new RemoteRunspacePoolInternal(instanceId, name, isDisconnected, connectCommands, connectionInfo, host, typeTable); IsRemote = true; } #endregion #region Public Properties /// <summary> /// Get unique id for this instance of runspace pool. It is primarily used /// for logging purposes. /// </summary> public Guid InstanceId { get { return _internalPool.InstanceId; } } /// <summary> /// Gets a boolean which describes if the runspace pool is disposed. /// </summary> public bool IsDisposed { get { return _internalPool.IsDisposed; } } /// <summary> /// Gets State of the current runspace pool. /// </summary> public RunspacePoolStateInfo RunspacePoolStateInfo { get { return _internalPool.RunspacePoolStateInfo; } } /// <summary> /// Gets the InitialSessionState object that this pool uses /// to create the runspaces. /// </summary> public InitialSessionState InitialSessionState { get { return _internalPool.InitialSessionState; } } /// <summary> /// Connection information for remote RunspacePools, null for local RunspacePools. /// </summary> public RunspaceConnectionInfo ConnectionInfo { get { return _internalPool.ConnectionInfo; } } /// <summary> /// Specifies how often unused runspaces are disposed. /// </summary> public TimeSpan CleanupInterval { get { return _internalPool.CleanupInterval; } set { _internalPool.CleanupInterval = value; } } /// <summary> /// Returns runspace pool availability. /// </summary> public RunspacePoolAvailability RunspacePoolAvailability { get { return _internalPool.RunspacePoolAvailability; } } #endregion #region events /// <summary> /// Event raised when RunspacePoolState changes. /// </summary> public event EventHandler<RunspacePoolStateChangedEventArgs> StateChanged { add { lock (_syncObject) { bool firstEntry = (InternalStateChanged == null); InternalStateChanged += value; if (firstEntry) { // call any event handlers on this object, replacing the // internalPool sender with 'this' since receivers // are expecting a RunspacePool. _internalPool.StateChanged += OnStateChanged; } } } remove { lock (_syncObject) { InternalStateChanged -= value; if (InternalStateChanged == null) { _internalPool.StateChanged -= OnStateChanged; } } } } /// <summary> /// Handle internal Pool state changed events. /// </summary> /// <param name="source"></param> /// <param name="args"></param> private void OnStateChanged(object source, RunspacePoolStateChangedEventArgs args) { if (ConnectionInfo is NewProcessConnectionInfo) { NewProcessConnectionInfo connectionInfo = ConnectionInfo as NewProcessConnectionInfo; if (connectionInfo.Process != null && (args.RunspacePoolStateInfo.State == RunspacePoolState.Opened || args.RunspacePoolStateInfo.State == RunspacePoolState.Broken)) { connectionInfo.Process.RunspacePool = this; } } // call any event handlers on this, replacing the // internalPool sender with 'this' since receivers // are expecting a RunspacePool InternalStateChanged.SafeInvoke(this, args); } /// <summary> /// Event raised when one of the runspaces in the pool forwards an event to this instance. /// </summary> internal event EventHandler<PSEventArgs> ForwardEvent { add { lock (_syncObject) { bool firstEntry = InternalForwardEvent == null; InternalForwardEvent += value; if (firstEntry) { _internalPool.ForwardEvent += OnInternalPoolForwardEvent; } } } remove { lock (_syncObject) { InternalForwardEvent -= value; if (InternalForwardEvent == null) { _internalPool.ForwardEvent -= OnInternalPoolForwardEvent; } } } } /// <summary> /// Pass thru of the ForwardEvent event from the internal pool. /// </summary> private void OnInternalPoolForwardEvent(object sender, PSEventArgs e) { OnEventForwarded(e); } /// <summary> /// Raises the ForwardEvent event. /// </summary> private void OnEventForwarded(PSEventArgs e) { InternalForwardEvent?.Invoke(this, e); } /// <summary> /// Event raised when a new Runspace is created by the pool. /// </summary> internal event EventHandler<RunspaceCreatedEventArgs> RunspaceCreated { add { lock (_syncObject) { bool firstEntry = (InternalRunspaceCreated == null); InternalRunspaceCreated += value; if (firstEntry) { // call any event handlers on this object, replacing the // internalPool sender with 'this' since receivers // are expecting a RunspacePool. _internalPool.RunspaceCreated += OnRunspaceCreated; } } } remove { lock (_syncObject) { InternalRunspaceCreated -= value; if (InternalRunspaceCreated == null) { _internalPool.RunspaceCreated -= OnRunspaceCreated; } } } } /// <summary> /// Handle internal Pool RunspaceCreated events. /// </summary> /// <param name="source"></param> /// <param name="args"></param> private void OnRunspaceCreated(object source, RunspaceCreatedEventArgs args) { // call any event handlers on this, replacing the // internalPool sender with 'this' since receivers // are expecting a RunspacePool InternalRunspaceCreated.SafeInvoke(this, args); } #endregion events #region Public static methods. /// <summary> /// Queries the server for disconnected runspace pools and creates an array of runspace /// pool objects associated with each disconnected runspace pool on the server. Each /// runspace pool object in the returned array is in the Disconnected state and can be /// connected to the server by calling the Connect() method on the runspace pool. /// </summary> /// <param name="connectionInfo">Connection object for the target server.</param> /// <returns>Array of RunspacePool objects each in the Disconnected state.</returns> public static RunspacePool[] GetRunspacePools(RunspaceConnectionInfo connectionInfo) { return GetRunspacePools(connectionInfo, null, null); } /// <summary> /// Queries the server for disconnected runspace pools and creates an array of runspace /// pool objects associated with each disconnected runspace pool on the server. Each /// runspace pool object in the returned array is in the Disconnected state and can be /// connected to the server by calling the Connect() method on the runspace pool. /// </summary> /// <param name="connectionInfo">Connection object for the target server.</param> /// <param name="host">Client host object.</param> /// <returns>Array of RunspacePool objects each in the Disconnected state.</returns> public static RunspacePool[] GetRunspacePools(RunspaceConnectionInfo connectionInfo, PSHost host) { return GetRunspacePools(connectionInfo, host, null); } /// <summary> /// Queries the server for disconnected runspace pools and creates an array of runspace /// pool objects associated with each disconnected runspace pool on the server. Each /// runspace pool object in the returned array is in the Disconnected state and can be /// connected to the server by calling the Connect() method on the runspace pool. /// </summary> /// <param name="connectionInfo">Connection object for the target server.</param> /// <param name="host">Client host object.</param> /// <param name="typeTable">TypeTable object.</param> /// <returns>Array of RunspacePool objects each in the Disconnected state.</returns> public static RunspacePool[] GetRunspacePools(RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable) { return RemoteRunspacePoolInternal.GetRemoteRunspacePools(connectionInfo, host, typeTable); } #endregion #region Public Disconnect-Connect API /// <summary> /// Disconnects the runspace pool synchronously. Runspace pool must be in Opened state. /// </summary> public void Disconnect() { _internalPool.Disconnect(); } /// <summary> /// Disconnects the runspace pool asynchronously. Runspace pool must be in Opened state. /// </summary> /// <param name="callback">An AsyncCallback to call once the BeginClose completes.</param> /// <param name="state">A user supplied state to call the callback with.</param> public IAsyncResult BeginDisconnect(AsyncCallback callback, object state) { return _internalPool.BeginDisconnect(callback, state); } /// <summary> /// Waits for the pending asynchronous BeginDisconnect to complete. /// </summary> /// <param name="asyncResult">Asynchronous call result object.</param> public void EndDisconnect(IAsyncResult asyncResult) { _internalPool.EndDisconnect(asyncResult); } /// <summary> /// Connects the runspace pool synchronously. Runspace pool must be in disconnected state. /// </summary> public void Connect() { _internalPool.Connect(); } /// <summary> /// Connects the runspace pool asynchronously. Runspace pool must be in disconnected state. /// </summary> /// <param name="callback"></param> /// <param name="state"></param> public IAsyncResult BeginConnect(AsyncCallback callback, object state) { return _internalPool.BeginConnect(callback, state); } /// <summary> /// Waits for the pending asynchronous BeginConnect to complete. /// </summary> /// <param name="asyncResult">Asynchronous call result object.</param> public void EndConnect(IAsyncResult asyncResult) { _internalPool.EndConnect(asyncResult); } /// <summary> /// Creates an array of PowerShell objects that are in the Disconnected state for /// all currently disconnected running commands associated with this runspace pool. /// </summary> /// <returns></returns> public Collection<PowerShell> CreateDisconnectedPowerShells() { return _internalPool.CreateDisconnectedPowerShells(this); } ///<summary> /// Returns RunspacePool capabilities. /// </summary> /// <returns>RunspacePoolCapability.</returns> public RunspacePoolCapability GetCapabilities() { return _internalPool.GetCapabilities(); } #endregion #region Public API /// <summary> /// Sets the maximum number of Runspaces that can be active concurrently /// in the pool. All requests above that number remain queued until /// runspaces become available. /// </summary> /// <param name="maxRunspaces"> /// The maximum number of runspaces in the pool. /// </param> /// <returns> /// true if the change is successful; otherwise, false. /// </returns> /// <remarks> /// You cannot set the number of runspaces to a number smaller than /// the minimum runspaces. /// </remarks> public bool SetMaxRunspaces(int maxRunspaces) { return _internalPool.SetMaxRunspaces(maxRunspaces); } /// <summary> /// Retrieves the maximum number of runspaces the pool maintains. /// </summary> /// <returns> /// The maximum number of runspaces in the pool /// </returns> public int GetMaxRunspaces() { return _internalPool.GetMaxRunspaces(); } /// <summary> /// Sets the minimum number of Runspaces that the pool maintains /// in anticipation of new requests. /// </summary> /// <param name="minRunspaces"> /// The minimum number of runspaces in the pool. /// </param> /// <returns> /// true if the change is successful; otherwise, false. /// </returns> /// <remarks> /// You cannot set the number of idle runspaces to a number smaller than /// 1 or greater than maximum number of active runspaces. /// </remarks> public bool SetMinRunspaces(int minRunspaces) { return _internalPool.SetMinRunspaces(minRunspaces); } /// <summary> /// Retrieves the minimum number of runspaces the pool maintains. /// </summary> /// <returns> /// The minimum number of runspaces in the pool /// </returns> public int GetMinRunspaces() { return _internalPool.GetMinRunspaces(); } /// <summary> /// Retrieves the number of runspaces available at the time of calling /// this method. /// </summary> /// <returns> /// The number of available runspace in the pool. /// </returns> public int GetAvailableRunspaces() { return _internalPool.GetAvailableRunspaces(); } /// <summary> /// Opens the runspacepool synchronously. RunspacePool must /// be opened before it can be used. /// </summary> /// <exception cref="InvalidRunspacePoolStateException"> /// RunspacePoolState is not BeforeOpen /// </exception> public void Open() { _internalPool.Open(); } /// <summary> /// Opens the RunspacePool asynchronously. RunspacePool must /// be opened before it can be used. /// To get the exceptions that might have occurred, call /// EndOpen. /// </summary> /// <param name="callback"> /// A AsyncCallback to call once the BeginOpen completes. /// </param> /// <param name="state"> /// A user supplied state to call the <paramref name="callback"/> /// with. /// </param> /// <returns> /// An AsyncResult object to monitor the state of the async /// operation. /// </returns> public IAsyncResult BeginOpen(AsyncCallback callback, object state) { return _internalPool.BeginOpen(callback, state); } /// <summary> /// Waits for the pending asynchronous BeginOpen to complete. /// </summary> /// <exception cref="ArgumentNullException"> /// asyncResult is a null reference. /// </exception> /// <exception cref="ArgumentException"> /// asyncResult object was not created by calling BeginOpen /// on this runspacepool instance. /// </exception> /// <exception cref="InvalidRunspacePoolStateException"> /// RunspacePoolState is not BeforeOpen. /// </exception> /// <remarks> /// TODO: Behavior if EndOpen is called multiple times. /// </remarks> public void EndOpen(IAsyncResult asyncResult) { _internalPool.EndOpen(asyncResult); } /// <summary> /// Closes the RunspacePool and cleans all the internal /// resources. This will close all the runspaces in the /// runspacepool and release all the async operations /// waiting for a runspace. If the pool is already closed /// or broken or closing this will just return. /// </summary> /// <exception cref="InvalidRunspacePoolStateException"> /// Cannot close the RunspacePool because RunspacePool is /// in Closing state. /// </exception> public void Close() { _internalPool.Close(); } /// <summary> /// Closes the RunspacePool asynchronously and cleans all the internal /// resources. This will close all the runspaces in the /// runspacepool and release all the async operations /// waiting for a runspace. If the pool is already closed /// or broken or closing this will just return. /// </summary> /// <param name="callback"> /// A AsyncCallback to call once the BeginClose completes. /// </param> /// <param name="state"> /// A user supplied state to call the <paramref name="callback"/> /// with. /// </param> /// <returns> /// An AsyncResult object to monitor the state of the async /// operation. /// </returns> public IAsyncResult BeginClose(AsyncCallback callback, object state) { return _internalPool.BeginClose(callback, state); } /// <summary> /// Waits for the pending asynchronous BeginClose to complete. /// </summary> /// <exception cref="ArgumentNullException"> /// asyncResult is a null reference. /// </exception> /// <exception cref="ArgumentException"> /// asyncResult object was not created by calling BeginClose /// on this runspacepool instance. /// </exception> public void EndClose(IAsyncResult asyncResult) { _internalPool.EndClose(asyncResult); } /// <summary> /// Dispose the current runspacepool. /// </summary> public void Dispose() { _internalPool.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Private data to be used by applications built on top of PowerShell. /// /// Local runspace pool is created with application private data set to an empty <see cref="PSPrimitiveDictionary"/>. /// /// Remote runspace pool gets its application private data from the server (when creating the remote runspace pool) /// Calling this method on a remote runspace pool will block until the data is received from the server. /// The server will send application private data before reaching <see cref="RunspacePoolState.Opened"/> state. /// /// Runspaces that are part of a <see cref="RunspacePool"/> inherit application private data from the pool. /// </summary> public PSPrimitiveDictionary GetApplicationPrivateData() { return _internalPool.GetApplicationPrivateData(); } #endregion #region Internal API /// <summary> /// This property determines whether a new thread is created for each invocation. /// </summary> /// <remarks> /// Any updates to the value of this property must be done before the RunspacePool is opened /// </remarks> /// <exception cref="InvalidRunspacePoolStateException"> /// An attempt to change this property was made after opening the RunspacePool /// </exception> public PSThreadOptions ThreadOptions { get { return _internalPool.ThreadOptions; } set { if (this.RunspacePoolStateInfo.State != RunspacePoolState.BeforeOpen) { throw new InvalidRunspacePoolStateException(RunspacePoolStrings.ChangePropertyAfterOpen); } _internalPool.ThreadOptions = value; } } /// <summary> /// ApartmentState of the thread used to execute commands within this RunspacePool. /// </summary> /// <remarks> /// Any updates to the value of this property must be done before the RunspacePool is opened /// </remarks> /// <exception cref="InvalidRunspacePoolStateException"> /// An attempt to change this property was made after opening the RunspacePool /// </exception> public ApartmentState ApartmentState { get { return _internalPool.ApartmentState; } set { if (this.RunspacePoolStateInfo.State != RunspacePoolState.BeforeOpen) { throw new InvalidRunspacePoolStateException(RunspacePoolStrings.ChangePropertyAfterOpen); } _internalPool.ApartmentState = value; } } /// <summary> /// Gets Runspace asynchronously from the runspace pool. The caller /// will get notified with the runspace using <paramref name="callback"/> /// </summary> /// <param name="callback"> /// A AsyncCallback to call once the runspace is available. /// </param> /// <param name="state"> /// A user supplied state to call the <paramref name="callback"/> /// with. /// </param> /// <returns> /// An IAsyncResult object to track the status of the Async operation. /// </returns> internal IAsyncResult BeginGetRunspace( AsyncCallback callback, object state) { return _internalPool.BeginGetRunspace(callback, state); } /// <summary> /// Cancels the pending asynchronous BeginGetRunspace operation. /// </summary> /// <param name="asyncResult"> /// </param> internal void CancelGetRunspace(IAsyncResult asyncResult) { _internalPool.CancelGetRunspace(asyncResult); } /// <summary> /// Waits for the pending asynchronous BeginGetRunspace to complete. /// </summary> /// <param name="asyncResult"> /// </param> /// <exception cref="ArgumentNullException"> /// asyncResult is a null reference. /// </exception> /// <exception cref="ArgumentException"> /// asyncResult object was not created by calling BeginGetRunspace /// on this runspacepool instance. /// </exception> /// <exception cref="InvalidRunspacePoolStateException"> /// RunspacePoolState is not BeforeOpen. /// </exception> internal Runspace EndGetRunspace(IAsyncResult asyncResult) { return _internalPool.EndGetRunspace(asyncResult); } /// <summary> /// Releases a Runspace to the pool. If pool is closed, this /// will be a no-op. /// </summary> /// <param name="runspace"> /// Runspace to release to the pool. /// </param> /// <exception cref="ArgumentException"> /// <paramref name="runspace"/> is null. /// </exception> /// <exception cref="InvalidOperationException"> /// Cannot release the runspace to this pool as the runspace /// doesn't belong to this pool. /// </exception> /// <exception cref="InvalidRunspaceStateException"> /// Only opened runspaces can be released back to the pool. /// </exception> internal void ReleaseRunspace(Runspace runspace) { _internalPool.ReleaseRunspace(runspace); } /// <summary> /// Indicates whether the RunspacePool is a remote one. /// </summary> internal bool IsRemote { get; } = false; /// <summary> /// RemoteRunspacePoolInternal associated with this /// runspace pool. /// </summary> internal RemoteRunspacePoolInternal RemoteRunspacePoolInternal { get { if (_internalPool is RemoteRunspacePoolInternal) { return (RemoteRunspacePoolInternal)_internalPool; } else { return null; } } } internal void AssertPoolIsOpen() { _internalPool.AssertPoolIsOpen(); } #endregion } #endregion }