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.Data.Common; using System.Data.SqlTypes; using System.Diagnostics; using System.Globalization; using System.Xml; using System.IO; using MSS = Microsoft.SqlServer.Server; namespace System.Data.SqlClient { internal sealed class MetaType { internal readonly Type ClassType; // com+ type internal readonly Type SqlType; internal readonly int FixedLength; // fixed length size in bytes (-1 for variable) internal readonly bool IsFixed; // true if fixed length, note that sqlchar and sqlbinary are not considered fixed length internal readonly bool IsLong; // true if long internal readonly bool IsPlp; // Column is Partially Length Prefixed (MAX) internal readonly byte Precision; // maximum precision for numeric types internal readonly byte Scale; internal readonly byte TDSType; internal readonly byte NullableType; internal readonly string TypeName; // string name of this type internal readonly SqlDbType SqlDbType; internal readonly DbType DbType; // holds count of property bytes expected for a SQLVariant structure internal readonly byte PropBytes; // pre-computed fields internal readonly bool IsAnsiType; internal readonly bool IsBinType; internal readonly bool IsCharType; internal readonly bool IsNCharType; internal readonly bool IsSizeInCharacters; internal readonly bool IsNewKatmaiType; internal readonly bool IsVarTime; internal readonly bool Is70Supported; internal readonly bool Is80Supported; internal readonly bool Is90Supported; internal readonly bool Is100Supported; public MetaType(byte precision, byte scale, int fixedLength, bool isFixed, bool isLong, bool isPlp, byte tdsType, byte nullableTdsType, string typeName, Type classType, Type sqlType, SqlDbType sqldbType, DbType dbType, byte propBytes) { this.Precision = precision; this.Scale = scale; this.FixedLength = fixedLength; this.IsFixed = isFixed; this.IsLong = isLong; this.IsPlp = isPlp; // can we get rid of this (?just have a mapping?) this.TDSType = tdsType; this.NullableType = nullableTdsType; this.TypeName = typeName; this.SqlDbType = sqldbType; this.DbType = dbType; this.ClassType = classType; this.SqlType = sqlType; this.PropBytes = propBytes; IsAnsiType = _IsAnsiType(sqldbType); IsBinType = _IsBinType(sqldbType); IsCharType = _IsCharType(sqldbType); IsNCharType = _IsNCharType(sqldbType); IsSizeInCharacters = _IsSizeInCharacters(sqldbType); IsNewKatmaiType = _IsNewKatmaiType(sqldbType); IsVarTime = _IsVarTime(sqldbType); Is70Supported = _Is70Supported(SqlDbType); Is80Supported = _Is80Supported(SqlDbType); Is90Supported = _Is90Supported(SqlDbType); Is100Supported = _Is100Supported(SqlDbType); } // properties should be inlined so there should be no perf penalty for using these accessor functions public int TypeId { // partial length prefixed (xml, nvarchar(max),...) get { return 0; } } private static bool _IsAnsiType(SqlDbType type) { return (type == SqlDbType.Char || type == SqlDbType.VarChar || type == SqlDbType.Text); } // is this type size expressed as count of characters or bytes? private static bool _IsSizeInCharacters(SqlDbType type) { return (type == SqlDbType.NChar || type == SqlDbType.NVarChar || type == SqlDbType.Xml || type == SqlDbType.NText); } private static bool _IsCharType(SqlDbType type) { return (type == SqlDbType.NChar || type == SqlDbType.NVarChar || type == SqlDbType.NText || type == SqlDbType.Char || type == SqlDbType.VarChar || type == SqlDbType.Text || type == SqlDbType.Xml); } private static bool _IsNCharType(SqlDbType type) { return (type == SqlDbType.NChar || type == SqlDbType.NVarChar || type == SqlDbType.NText || type == SqlDbType.Xml); } private static bool _IsBinType(SqlDbType type) { return (type == SqlDbType.Image || type == SqlDbType.Binary || type == SqlDbType.VarBinary || type == SqlDbType.Timestamp || type == SqlDbType.Udt || (int)type == 24 /*SqlSmallVarBinary*/); } private static bool _Is70Supported(SqlDbType type) { return ((type != SqlDbType.BigInt) && ((int)type > 0) && ((int)type <= (int)SqlDbType.VarChar)); } private static bool _Is80Supported(SqlDbType type) { return ((int)type >= 0 && ((int)type <= (int)SqlDbType.Variant)); } private static bool _Is90Supported(SqlDbType type) { return _Is80Supported(type) || SqlDbType.Xml == type || SqlDbType.Udt == type; } private static bool _Is100Supported(SqlDbType type) { return _Is90Supported(type) || SqlDbType.Date == type || SqlDbType.Time == type || SqlDbType.DateTime2 == type || SqlDbType.DateTimeOffset == type; } private static bool _IsNewKatmaiType(SqlDbType type) { return SqlDbType.Structured == type; } internal static bool _IsVarTime(SqlDbType type) { return (type == SqlDbType.Time || type == SqlDbType.DateTime2 || type == SqlDbType.DateTimeOffset); } // // map SqlDbType to MetaType class // internal static MetaType GetMetaTypeFromSqlDbType(SqlDbType target, bool isMultiValued) { // WebData 113289 switch (target) { case SqlDbType.BigInt: return s_metaBigInt; case SqlDbType.Binary: return s_metaBinary; case SqlDbType.Bit: return s_metaBit; case SqlDbType.Char: return s_metaChar; case SqlDbType.DateTime: return s_metaDateTime; case SqlDbType.Decimal: return MetaDecimal; case SqlDbType.Float: return s_metaFloat; case SqlDbType.Image: return MetaImage; case SqlDbType.Int: return s_metaInt; case SqlDbType.Money: return s_metaMoney; case SqlDbType.NChar: return s_metaNChar; case SqlDbType.NText: return MetaNText; case SqlDbType.NVarChar: return MetaNVarChar; case SqlDbType.Real: return s_metaReal; case SqlDbType.UniqueIdentifier: return s_metaUniqueId; case SqlDbType.SmallDateTime: return s_metaSmallDateTime; case SqlDbType.SmallInt: return s_metaSmallInt; case SqlDbType.SmallMoney: return s_metaSmallMoney; case SqlDbType.Text: return MetaText; case SqlDbType.Timestamp: return s_metaTimestamp; case SqlDbType.TinyInt: return s_metaTinyInt; case SqlDbType.VarBinary: return MetaVarBinary; case SqlDbType.VarChar: return s_metaVarChar; case SqlDbType.Variant: return s_metaVariant; case (SqlDbType)TdsEnums.SmallVarBinary: return s_metaSmallVarBinary; case SqlDbType.Xml: return MetaXml; case SqlDbType.Structured: if (isMultiValued) { return s_metaTable; } else { return s_metaSUDT; } case SqlDbType.Date: return s_metaDate; case SqlDbType.Time: return MetaTime; case SqlDbType.DateTime2: return s_metaDateTime2; case SqlDbType.DateTimeOffset: return MetaDateTimeOffset; default: throw SQL.InvalidSqlDbType(target); } } // // map DbType to MetaType class // internal static MetaType GetMetaTypeFromDbType(DbType target) { // if we can't map it, we need to throw switch (target) { case DbType.AnsiString: return s_metaVarChar; case DbType.AnsiStringFixedLength: return s_metaChar; case DbType.Binary: return MetaVarBinary; case DbType.Byte: return s_metaTinyInt; case DbType.Boolean: return s_metaBit; case DbType.Currency: return s_metaMoney; case DbType.Date: case DbType.DateTime: return s_metaDateTime; case DbType.Decimal: return MetaDecimal; case DbType.Double: return s_metaFloat; case DbType.Guid: return s_metaUniqueId; case DbType.Int16: return s_metaSmallInt; case DbType.Int32: return s_metaInt; case DbType.Int64: return s_metaBigInt; case DbType.Object: return s_metaVariant; case DbType.Single: return s_metaReal; case DbType.String: return MetaNVarChar; case DbType.StringFixedLength: return s_metaNChar; case DbType.Time: return s_metaDateTime; case DbType.Xml: return MetaXml; case DbType.DateTime2: return s_metaDateTime2; case DbType.DateTimeOffset: return MetaDateTimeOffset; case DbType.SByte: // unsupported case DbType.UInt16: case DbType.UInt32: case DbType.UInt64: case DbType.VarNumeric: default: throw ADP.DbTypeNotSupported(target, typeof(SqlDbType)); // no direct mapping, error out } } internal static MetaType GetMaxMetaTypeFromMetaType(MetaType mt) { // if we can't map it, we need to throw switch (mt.SqlDbType) { case SqlDbType.VarBinary: case SqlDbType.Binary: return MetaMaxVarBinary; case SqlDbType.VarChar: case SqlDbType.Char: return MetaMaxVarChar; case SqlDbType.NVarChar: case SqlDbType.NChar: return MetaMaxNVarChar; case SqlDbType.Udt: Debug.Assert(false, "UDT is not supported"); return mt; default: return mt; } } // // map COM+ Type to MetaType class // static internal MetaType GetMetaTypeFromType(Type dataType, bool streamAllowed = true) { if (dataType == typeof(System.Byte[])) return MetaVarBinary; else if (dataType == typeof(System.Guid)) return s_metaUniqueId; else if (dataType == typeof(System.Object)) return s_metaVariant; else if (dataType == typeof(SqlBinary)) return MetaVarBinary; else if (dataType == typeof(SqlBoolean)) return s_metaBit; else if (dataType == typeof(SqlByte)) return s_metaTinyInt; else if (dataType == typeof(SqlBytes)) return MetaVarBinary; else if (dataType == typeof(SqlChars)) return MetaNVarChar; else if (dataType == typeof(SqlDateTime)) return s_metaDateTime; else if (dataType == typeof(SqlDouble)) return s_metaFloat; else if (dataType == typeof(SqlGuid)) return s_metaUniqueId; else if (dataType == typeof(SqlInt16)) return s_metaSmallInt; else if (dataType == typeof(SqlInt32)) return s_metaInt; else if (dataType == typeof(SqlInt64)) return s_metaBigInt; else if (dataType == typeof(SqlMoney)) return s_metaMoney; else if (dataType == typeof(SqlDecimal)) return MetaDecimal; else if (dataType == typeof(SqlSingle)) return s_metaReal; else if (dataType == typeof(SqlXml)) return MetaXml; else if (dataType == typeof(SqlString)) return MetaNVarChar; else if (dataType == typeof(IEnumerable<DbDataRecord>)) return s_metaTable; else if (dataType == typeof(TimeSpan)) return MetaTime; else if (dataType == typeof(DateTimeOffset)) return MetaDateTimeOffset; else if (dataType == typeof(DBNull)) throw ADP.InvalidDataType("DBNull"); else if (dataType == typeof(Boolean)) return s_metaBit; else if (dataType == typeof(Char)) throw ADP.InvalidDataType("Char"); else if (dataType == typeof(SByte)) throw ADP.InvalidDataType("SByte"); else if (dataType == typeof(Byte)) return s_metaTinyInt; else if (dataType == typeof(Int16)) return s_metaSmallInt; else if (dataType == typeof(UInt16)) throw ADP.InvalidDataType("UInt16"); else if (dataType == typeof(Int32)) return s_metaInt; else if (dataType == typeof(UInt32)) throw ADP.InvalidDataType("UInt32"); else if (dataType == typeof(Int64)) return s_metaBigInt; else if (dataType == typeof(UInt64)) throw ADP.InvalidDataType("UInt64"); else if (dataType == typeof(Single)) return s_metaReal; else if (dataType == typeof(Double)) return s_metaFloat; else if (dataType == typeof(Decimal)) return MetaDecimal; else if (dataType == typeof(DateTime)) return s_metaDateTime; else if (dataType == typeof(String)) return MetaNVarChar; else throw ADP.UnknownDataType(dataType); } static internal MetaType GetMetaTypeFromValue(object value, bool inferLen = true, bool streamAllowed = true) { if (value == null) { throw ADP.InvalidDataType("null"); } if (value is DBNull) { throw ADP.InvalidDataType(nameof(DBNull)); } Type dataType = value.GetType(); switch (Convert.GetTypeCode(value)) { case TypeCode.Empty: throw ADP.InvalidDataType(nameof(TypeCode.Empty)); case TypeCode.Object: if (dataType == typeof (System.Byte[])) { if (!inferLen || ((byte[]) value).Length <= TdsEnums.TYPE_SIZE_LIMIT) { return MetaVarBinary; } else { return MetaImage; } } if (dataType == typeof (System.Guid)) { return s_metaUniqueId; } if (dataType == typeof (System.Object)) { return s_metaVariant; } // check sql types now if (dataType == typeof (SqlBinary)) return MetaVarBinary; if (dataType == typeof (SqlBoolean)) return s_metaBit; if (dataType == typeof (SqlByte)) return s_metaTinyInt; if (dataType == typeof (SqlBytes)) return MetaVarBinary; if (dataType == typeof (SqlChars)) return MetaNVarChar; if (dataType == typeof (SqlDateTime)) return s_metaDateTime; if (dataType == typeof (SqlDouble)) return s_metaFloat; if (dataType == typeof (SqlGuid)) return s_metaUniqueId; if (dataType == typeof (SqlInt16)) return s_metaSmallInt; if (dataType == typeof (SqlInt32)) return s_metaInt; if (dataType == typeof (SqlInt64)) return s_metaBigInt; if (dataType == typeof (SqlMoney)) return s_metaMoney; if (dataType == typeof (SqlDecimal)) return MetaDecimal; if (dataType == typeof (SqlSingle)) return s_metaReal; if (dataType == typeof (SqlXml)) return MetaXml; if (dataType == typeof (SqlString)) { return ((inferLen && !((SqlString) value).IsNull) ? PromoteStringType(((SqlString) value).Value) : MetaNVarChar); } if (dataType == typeof (IEnumerable<DbDataRecord>) || dataType == typeof (DataTable)) { return s_metaTable; } if (dataType == typeof (TimeSpan)) { return MetaTime; } if (dataType == typeof (DateTimeOffset)) { return MetaDateTimeOffset; } if (streamAllowed) { // Derived from Stream ? if (value is Stream) { return MetaVarBinary; } // Derived from TextReader ? if (value is TextReader) { return MetaNVarChar; } // Derived from XmlReader ? if (value is XmlReader) { return MetaXml; } } throw ADP.UnknownDataType(dataType); case TypeCode.Boolean: return s_metaBit; case TypeCode.Char: throw ADP.InvalidDataType(nameof(TypeCode.Char)); case TypeCode.SByte: throw ADP.InvalidDataType(nameof(TypeCode.SByte)); case TypeCode.Byte: return s_metaTinyInt; case TypeCode.Int16: return s_metaSmallInt; case TypeCode.UInt16: throw ADP.InvalidDataType(nameof(TypeCode.UInt16)); case TypeCode.Int32: return s_metaInt; case TypeCode.UInt32: throw ADP.InvalidDataType(nameof(TypeCode.UInt32)); case TypeCode.Int64: return s_metaBigInt; case TypeCode.UInt64: throw ADP.InvalidDataType(nameof(TypeCode.UInt64)); case TypeCode.Single: return s_metaReal; case TypeCode.Double: return s_metaFloat; case TypeCode.Decimal: return MetaDecimal; case TypeCode.DateTime: return s_metaDateTime; case TypeCode.String: return (inferLen ? PromoteStringType((string) value) : MetaNVarChar); default: throw ADP.UnknownDataType(dataType); } } internal static object GetNullSqlValue(Type sqlType) { if (sqlType == typeof(SqlSingle)) return SqlSingle.Null; else if (sqlType == typeof(SqlString)) return SqlString.Null; else if (sqlType == typeof(SqlDouble)) return SqlDouble.Null; else if (sqlType == typeof(SqlBinary)) return SqlBinary.Null; else if (sqlType == typeof(SqlGuid)) return SqlGuid.Null; else if (sqlType == typeof(SqlBoolean)) return SqlBoolean.Null; else if (sqlType == typeof(SqlByte)) return SqlByte.Null; else if (sqlType == typeof(SqlInt16)) return SqlInt16.Null; else if (sqlType == typeof(SqlInt32)) return SqlInt32.Null; else if (sqlType == typeof(SqlInt64)) return SqlInt64.Null; else if (sqlType == typeof(SqlDecimal)) return SqlDecimal.Null; else if (sqlType == typeof(SqlDateTime)) return SqlDateTime.Null; else if (sqlType == typeof(SqlMoney)) return SqlMoney.Null; else if (sqlType == typeof(SqlXml)) return SqlXml.Null; else if (sqlType == typeof(object)) return DBNull.Value; else if (sqlType == typeof(IEnumerable<DbDataRecord>)) return DBNull.Value; else if (sqlType == typeof(DateTime)) return DBNull.Value; else if (sqlType == typeof(TimeSpan)) return DBNull.Value; else if (sqlType == typeof(DateTimeOffset)) return DBNull.Value; else { Debug.Assert(false, "Unknown SqlType!"); return DBNull.Value; } } internal static MetaType PromoteStringType(string s) { int len = s.Length; if ((len << 1) > TdsEnums.TYPE_SIZE_LIMIT) { return s_metaVarChar; // try as var char since we can send a 8K characters } return MetaNVarChar; // send 4k chars, but send as unicode } internal static object GetComValueFromSqlVariant(object sqlVal) { object comVal = null; if (ADP.IsNull(sqlVal)) return comVal; if (sqlVal is SqlSingle) comVal = ((SqlSingle)sqlVal).Value; else if (sqlVal is SqlString) comVal = ((SqlString)sqlVal).Value; else if (sqlVal is SqlDouble) comVal = ((SqlDouble)sqlVal).Value; else if (sqlVal is SqlBinary) comVal = ((SqlBinary)sqlVal).Value; else if (sqlVal is SqlGuid) comVal = ((SqlGuid)sqlVal).Value; else if (sqlVal is SqlBoolean) comVal = ((SqlBoolean)sqlVal).Value; else if (sqlVal is SqlByte) comVal = ((SqlByte)sqlVal).Value; else if (sqlVal is SqlInt16) comVal = ((SqlInt16)sqlVal).Value; else if (sqlVal is SqlInt32) comVal = ((SqlInt32)sqlVal).Value; else if (sqlVal is SqlInt64) comVal = ((SqlInt64)sqlVal).Value; else if (sqlVal is SqlDecimal) comVal = ((SqlDecimal)sqlVal).Value; else if (sqlVal is SqlDateTime) comVal = ((SqlDateTime)sqlVal).Value; else if (sqlVal is SqlMoney) comVal = ((SqlMoney)sqlVal).Value; else if (sqlVal is SqlXml) comVal = ((SqlXml)sqlVal).Value; else { Debug.Assert(false, "unknown SqlType class stored in sqlVal"); } return comVal; } // devnote: This method should not be used with SqlDbType.Date and SqlDbType.DateTime2. // With these types the values should be used directly as CLR types instead of being converted to a SqlValue internal static object GetSqlValueFromComVariant(object comVal) { object sqlVal = null; if ((null != comVal) && (DBNull.Value != comVal)) { if (comVal is float) sqlVal = new SqlSingle((float)comVal); else if (comVal is string) sqlVal = new SqlString((string)comVal); else if (comVal is double) sqlVal = new SqlDouble((double)comVal); else if (comVal is System.Byte[]) sqlVal = new SqlBinary((byte[])comVal); else if (comVal is System.Char) sqlVal = new SqlString(((char)comVal).ToString()); else if (comVal is System.Char[]) sqlVal = new SqlChars((System.Char[])comVal); else if (comVal is System.Guid) sqlVal = new SqlGuid((Guid)comVal); else if (comVal is bool) sqlVal = new SqlBoolean((bool)comVal); else if (comVal is byte) sqlVal = new SqlByte((byte)comVal); else if (comVal is Int16) sqlVal = new SqlInt16((Int16)comVal); else if (comVal is Int32) sqlVal = new SqlInt32((Int32)comVal); else if (comVal is Int64) sqlVal = new SqlInt64((Int64)comVal); else if (comVal is Decimal) sqlVal = new SqlDecimal((Decimal)comVal); else if (comVal is DateTime) { // devnote: Do not use with SqlDbType.Date and SqlDbType.DateTime2. See comment at top of method. sqlVal = new SqlDateTime((DateTime)comVal); } else if (comVal is XmlReader) sqlVal = new SqlXml((XmlReader)comVal); else if (comVal is TimeSpan || comVal is DateTimeOffset) sqlVal = comVal; #if DEBUG else Debug.Assert(false, "unknown SqlType class stored in sqlVal"); #endif } return sqlVal; } internal static MetaType GetSqlDataType(int tdsType, UInt32 userType, int length) { switch (tdsType) { case TdsEnums.SQLMONEYN: return ((4 == length) ? s_metaSmallMoney : s_metaMoney); case TdsEnums.SQLDATETIMN: return ((4 == length) ? s_metaSmallDateTime : s_metaDateTime); case TdsEnums.SQLINTN: return ((4 <= length) ? ((4 == length) ? s_metaInt : s_metaBigInt) : ((2 == length) ? s_metaSmallInt : s_metaTinyInt)); case TdsEnums.SQLFLTN: return ((4 == length) ? s_metaReal : s_metaFloat); case TdsEnums.SQLTEXT: return MetaText; case TdsEnums.SQLVARBINARY: return s_metaSmallVarBinary; case TdsEnums.SQLBIGVARBINARY: return MetaVarBinary; case TdsEnums.SQLVARCHAR: //goto TdsEnums.SQLBIGVARCHAR; case TdsEnums.SQLBIGVARCHAR: return s_metaVarChar; case TdsEnums.SQLBINARY: //goto TdsEnums.SQLBIGBINARY; case TdsEnums.SQLBIGBINARY: return ((TdsEnums.SQLTIMESTAMP == userType) ? s_metaTimestamp : s_metaBinary); case TdsEnums.SQLIMAGE: return MetaImage; case TdsEnums.SQLCHAR: //goto TdsEnums.SQLBIGCHAR; case TdsEnums.SQLBIGCHAR: return s_metaChar; case TdsEnums.SQLINT1: return s_metaTinyInt; case TdsEnums.SQLBIT: //goto TdsEnums.SQLBITN; case TdsEnums.SQLBITN: return s_metaBit; case TdsEnums.SQLINT2: return s_metaSmallInt; case TdsEnums.SQLINT4: return s_metaInt; case TdsEnums.SQLINT8: return s_metaBigInt; case TdsEnums.SQLMONEY: return s_metaMoney; case TdsEnums.SQLDATETIME: return s_metaDateTime; case TdsEnums.SQLFLT8: return s_metaFloat; case TdsEnums.SQLFLT4: return s_metaReal; case TdsEnums.SQLMONEY4: return s_metaSmallMoney; case TdsEnums.SQLDATETIM4: return s_metaSmallDateTime; case TdsEnums.SQLDECIMALN: //goto TdsEnums.SQLNUMERICN; case TdsEnums.SQLNUMERICN: return MetaDecimal; case TdsEnums.SQLUNIQUEID: return s_metaUniqueId; case TdsEnums.SQLNCHAR: return s_metaNChar; case TdsEnums.SQLNVARCHAR: return MetaNVarChar; case TdsEnums.SQLNTEXT: return MetaNText; case TdsEnums.SQLVARIANT: return s_metaVariant; case TdsEnums.SQLUDT: return s_metaUdt; case TdsEnums.SQLXMLTYPE: return MetaXml; case TdsEnums.SQLTABLE: return s_metaTable; case TdsEnums.SQLDATE: return s_metaDate; case TdsEnums.SQLTIME: return MetaTime; case TdsEnums.SQLDATETIME2: return s_metaDateTime2; case TdsEnums.SQLDATETIMEOFFSET: return MetaDateTimeOffset; case TdsEnums.SQLVOID: default: Debug.Assert(false, "Unknown type " + tdsType.ToString(CultureInfo.InvariantCulture)); throw SQL.InvalidSqlDbType((SqlDbType)tdsType); }// case } internal static MetaType GetDefaultMetaType() { return MetaNVarChar; } // Converts an XmlReader into String internal static String GetStringFromXml(XmlReader xmlreader) { SqlXml sxml = new SqlXml(xmlreader); return sxml.Value; } private static readonly MetaType s_metaBigInt = new MetaType (19, 255, 8, true, false, false, TdsEnums.SQLINT8, TdsEnums.SQLINTN, MetaTypeName.BIGINT, typeof(System.Int64), typeof(SqlInt64), SqlDbType.BigInt, DbType.Int64, 0); private static readonly MetaType s_metaFloat = new MetaType (15, 255, 8, true, false, false, TdsEnums.SQLFLT8, TdsEnums.SQLFLTN, MetaTypeName.FLOAT, typeof(System.Double), typeof(SqlDouble), SqlDbType.Float, DbType.Double, 0); private static readonly MetaType s_metaReal = new MetaType (7, 255, 4, true, false, false, TdsEnums.SQLFLT4, TdsEnums.SQLFLTN, MetaTypeName.REAL, typeof(System.Single), typeof(SqlSingle), SqlDbType.Real, DbType.Single, 0); // MetaBinary has two bytes of properties for binary and varbinary // 2 byte maxlen private static readonly MetaType s_metaBinary = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGBINARY, TdsEnums.SQLBIGBINARY, MetaTypeName.BINARY, typeof(System.Byte[]), typeof(SqlBinary), SqlDbType.Binary, DbType.Binary, 2); // Syntactic sugar for the user...timestamps are 8-byte fixed length binary columns private static readonly MetaType s_metaTimestamp = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGBINARY, TdsEnums.SQLBIGBINARY, MetaTypeName.TIMESTAMP, typeof(System.Byte[]), typeof(SqlBinary), SqlDbType.Timestamp, DbType.Binary, 2); internal static readonly MetaType MetaVarBinary = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGVARBINARY, TdsEnums.SQLBIGVARBINARY, MetaTypeName.VARBINARY, typeof(System.Byte[]), typeof(SqlBinary), SqlDbType.VarBinary, DbType.Binary, 2); internal static readonly MetaType MetaMaxVarBinary = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLBIGVARBINARY, TdsEnums.SQLBIGVARBINARY, MetaTypeName.VARBINARY, typeof(System.Byte[]), typeof(SqlBinary), SqlDbType.VarBinary, DbType.Binary, 2); // HACK!!! We have an internal type for smallvarbinarys stored on TdsEnums. We // store on TdsEnums instead of SqlDbType because we do not want to expose // this type to the user! private static readonly MetaType s_metaSmallVarBinary = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLVARBINARY, TdsEnums.SQLBIGBINARY, ADP.StrEmpty, typeof(System.Byte[]), typeof(SqlBinary), TdsEnums.SmallVarBinary, DbType.Binary, 2); internal static readonly MetaType MetaImage = new MetaType (255, 255, -1, false, true, false, TdsEnums.SQLIMAGE, TdsEnums.SQLIMAGE, MetaTypeName.IMAGE, typeof(System.Byte[]), typeof(SqlBinary), SqlDbType.Image, DbType.Binary, 0); private static readonly MetaType s_metaBit = new MetaType (255, 255, 1, true, false, false, TdsEnums.SQLBIT, TdsEnums.SQLBITN, MetaTypeName.BIT, typeof(System.Boolean), typeof(SqlBoolean), SqlDbType.Bit, DbType.Boolean, 0); private static readonly MetaType s_metaTinyInt = new MetaType (3, 255, 1, true, false, false, TdsEnums.SQLINT1, TdsEnums.SQLINTN, MetaTypeName.TINYINT, typeof(System.Byte), typeof(SqlByte), SqlDbType.TinyInt, DbType.Byte, 0); private static readonly MetaType s_metaSmallInt = new MetaType (5, 255, 2, true, false, false, TdsEnums.SQLINT2, TdsEnums.SQLINTN, MetaTypeName.SMALLINT, typeof(System.Int16), typeof(SqlInt16), SqlDbType.SmallInt, DbType.Int16, 0); private static readonly MetaType s_metaInt = new MetaType (10, 255, 4, true, false, false, TdsEnums.SQLINT4, TdsEnums.SQLINTN, MetaTypeName.INT, typeof(System.Int32), typeof(SqlInt32), SqlDbType.Int, DbType.Int32, 0); // MetaVariant has seven bytes of properties for MetaChar and MetaVarChar // 5 byte tds collation // 2 byte maxlen private static readonly MetaType s_metaChar = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGCHAR, TdsEnums.SQLBIGCHAR, MetaTypeName.CHAR, typeof(System.String), typeof(SqlString), SqlDbType.Char, DbType.AnsiStringFixedLength, 7); private static readonly MetaType s_metaVarChar = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLBIGVARCHAR, TdsEnums.SQLBIGVARCHAR, MetaTypeName.VARCHAR, typeof(System.String), typeof(SqlString), SqlDbType.VarChar, DbType.AnsiString, 7); internal static readonly MetaType MetaMaxVarChar = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLBIGVARCHAR, TdsEnums.SQLBIGVARCHAR, MetaTypeName.VARCHAR, typeof(System.String), typeof(SqlString), SqlDbType.VarChar, DbType.AnsiString, 7); internal static readonly MetaType MetaText = new MetaType (255, 255, -1, false, true, false, TdsEnums.SQLTEXT, TdsEnums.SQLTEXT, MetaTypeName.TEXT, typeof(System.String), typeof(SqlString), SqlDbType.Text, DbType.AnsiString, 0); // MetaVariant has seven bytes of properties for MetaNChar and MetaNVarChar // 5 byte tds collation // 2 byte maxlen private static readonly MetaType s_metaNChar = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLNCHAR, TdsEnums.SQLNCHAR, MetaTypeName.NCHAR, typeof(System.String), typeof(SqlString), SqlDbType.NChar, DbType.StringFixedLength, 7); internal static readonly MetaType MetaNVarChar = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLNVARCHAR, TdsEnums.SQLNVARCHAR, MetaTypeName.NVARCHAR, typeof(System.String), typeof(SqlString), SqlDbType.NVarChar, DbType.String, 7); internal static readonly MetaType MetaMaxNVarChar = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLNVARCHAR, TdsEnums.SQLNVARCHAR, MetaTypeName.NVARCHAR, typeof(System.String), typeof(SqlString), SqlDbType.NVarChar, DbType.String, 7); internal static readonly MetaType MetaNText = new MetaType (255, 255, -1, false, true, false, TdsEnums.SQLNTEXT, TdsEnums.SQLNTEXT, MetaTypeName.NTEXT, typeof(System.String), typeof(SqlString), SqlDbType.NText, DbType.String, 7); // MetaVariant has two bytes of properties for numeric/decimal types // 1 byte precision // 1 byte scale internal static readonly MetaType MetaDecimal = new MetaType (38, 4, 17, true, false, false, TdsEnums.SQLNUMERICN, TdsEnums.SQLNUMERICN, MetaTypeName.DECIMAL, typeof(System.Decimal), typeof(SqlDecimal), SqlDbType.Decimal, DbType.Decimal, 2); internal static readonly MetaType MetaXml = new MetaType (255, 255, -1, false, true, true, TdsEnums.SQLXMLTYPE, TdsEnums.SQLXMLTYPE, MetaTypeName.XML, typeof(System.String), typeof(SqlXml), SqlDbType.Xml, DbType.Xml, 0); private static readonly MetaType s_metaDateTime = new MetaType (23, 3, 8, true, false, false, TdsEnums.SQLDATETIME, TdsEnums.SQLDATETIMN, MetaTypeName.DATETIME, typeof(System.DateTime), typeof(SqlDateTime), SqlDbType.DateTime, DbType.DateTime, 0); private static readonly MetaType s_metaSmallDateTime = new MetaType (16, 0, 4, true, false, false, TdsEnums.SQLDATETIM4, TdsEnums.SQLDATETIMN, MetaTypeName.SMALLDATETIME, typeof(System.DateTime), typeof(SqlDateTime), SqlDbType.SmallDateTime, DbType.DateTime, 0); private static readonly MetaType s_metaMoney = new MetaType (19, 255, 8, true, false, false, TdsEnums.SQLMONEY, TdsEnums.SQLMONEYN, MetaTypeName.MONEY, typeof(System.Decimal), typeof(SqlMoney), SqlDbType.Money, DbType.Currency, 0); private static readonly MetaType s_metaSmallMoney = new MetaType (10, 255, 4, true, false, false, TdsEnums.SQLMONEY4, TdsEnums.SQLMONEYN, MetaTypeName.SMALLMONEY, typeof(System.Decimal), typeof(SqlMoney), SqlDbType.SmallMoney, DbType.Currency, 0); private static readonly MetaType s_metaUniqueId = new MetaType (255, 255, 16, true, false, false, TdsEnums.SQLUNIQUEID, TdsEnums.SQLUNIQUEID, MetaTypeName.ROWGUID, typeof(System.Guid), typeof(SqlGuid), SqlDbType.UniqueIdentifier, DbType.Guid, 0); private static readonly MetaType s_metaVariant = new MetaType (255, 255, -1, true, false, false, TdsEnums.SQLVARIANT, TdsEnums.SQLVARIANT, MetaTypeName.VARIANT, typeof(System.Object), typeof(System.Object), SqlDbType.Variant, DbType.Object, 0); private static readonly MetaType s_metaUdt = new MetaType (255, 255, -1, false, false, true, TdsEnums.SQLUDT, TdsEnums.SQLUDT, MetaTypeName.UDT, typeof(System.Object), typeof(System.Object), SqlDbType.Udt, DbType.Object, 0); private static readonly MetaType s_metaTable = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLTABLE, TdsEnums.SQLTABLE, MetaTypeName.TABLE, typeof(IEnumerable<DbDataRecord>), typeof(IEnumerable<DbDataRecord>), SqlDbType.Structured, DbType.Object, 0); private static readonly MetaType s_metaSUDT = new MetaType (255, 255, -1, false, false, false, TdsEnums.SQLVOID, TdsEnums.SQLVOID, "", typeof(MSS.SqlDataRecord), typeof(MSS.SqlDataRecord), SqlDbType.Structured, DbType.Object, 0); private static readonly MetaType s_metaDate = new MetaType (255, 255, 3, true, false, false, TdsEnums.SQLDATE, TdsEnums.SQLDATE, MetaTypeName.DATE, typeof(System.DateTime), typeof(System.DateTime), SqlDbType.Date, DbType.Date, 0); internal static readonly MetaType MetaTime = new MetaType (255, 7, -1, false, false, false, TdsEnums.SQLTIME, TdsEnums.SQLTIME, MetaTypeName.TIME, typeof(System.TimeSpan), typeof(System.TimeSpan), SqlDbType.Time, DbType.Time, 1); private static readonly MetaType s_metaDateTime2 = new MetaType (255, 7, -1, false, false, false, TdsEnums.SQLDATETIME2, TdsEnums.SQLDATETIME2, MetaTypeName.DATETIME2, typeof(System.DateTime), typeof(System.DateTime), SqlDbType.DateTime2, DbType.DateTime2, 1); internal static readonly MetaType MetaDateTimeOffset = new MetaType (255, 7, -1, false, false, false, TdsEnums.SQLDATETIMEOFFSET, TdsEnums.SQLDATETIMEOFFSET, MetaTypeName.DATETIMEOFFSET, typeof(System.DateTimeOffset), typeof(System.DateTimeOffset), SqlDbType.DateTimeOffset, DbType.DateTimeOffset, 1); public static TdsDateTime FromDateTime(DateTime dateTime, byte cb) { SqlDateTime sqlDateTime; TdsDateTime tdsDateTime = new TdsDateTime(); Debug.Assert(cb == 8 || cb == 4, "Invalid date time size!"); if (cb == 8) { sqlDateTime = new SqlDateTime(dateTime); tdsDateTime.time = sqlDateTime.TimeTicks; } else { // note that smalldatetime is days & minutes. // Adding 30 seconds ensures proper roundup if the seconds are >= 30 // The AddSeconds function handles eventual carryover sqlDateTime = new SqlDateTime(dateTime.AddSeconds(30)); tdsDateTime.time = sqlDateTime.TimeTicks / SqlDateTime.SQLTicksPerMinute; } tdsDateTime.days = sqlDateTime.DayTicks; return tdsDateTime; } public static DateTime ToDateTime(int sqlDays, int sqlTime, int length) { if (length == 4) { return new SqlDateTime(sqlDays, sqlTime * SqlDateTime.SQLTicksPerMinute).Value; } else { Debug.Assert(length == 8, "invalid length for DateTime"); return new SqlDateTime(sqlDays, sqlTime).Value; } } internal static int GetTimeSizeFromScale(byte scale) { if (scale <= 2) return 3; if (scale <= 4) return 4; return 5; } // // please leave string sorted alphabetically // note that these names should only be used in the context of parameters. We always send over BIG* and nullable types for SQL Server // private static class MetaTypeName { public const string BIGINT = "bigint"; public const string BINARY = "binary"; public const string BIT = "bit"; public const string CHAR = "char"; public const string DATETIME = "datetime"; public const string DECIMAL = "decimal"; public const string FLOAT = "float"; public const string IMAGE = "image"; public const string INT = "int"; public const string MONEY = "money"; public const string NCHAR = "nchar"; public const string NTEXT = "ntext"; public const string NVARCHAR = "nvarchar"; public const string REAL = "real"; public const string ROWGUID = "uniqueidentifier"; public const string SMALLDATETIME = "smalldatetime"; public const string SMALLINT = "smallint"; public const string SMALLMONEY = "smallmoney"; public const string TEXT = "text"; public const string TIMESTAMP = "timestamp"; public const string TINYINT = "tinyint"; public const string UDT = "udt"; public const string VARBINARY = "varbinary"; public const string VARCHAR = "varchar"; public const string VARIANT = "sql_variant"; public const string XML = "xml"; public const string TABLE = "table"; public const string DATE = "date"; public const string TIME = "time"; public const string DATETIME2 = "datetime2"; public const string DATETIMEOFFSET = "datetimeoffset"; } } // // note: it is the client's responsibility to know what size date time he is working with // internal struct TdsDateTime { public int days; // offset in days from 1/1/1900 // private UInt32 time; // if smalldatetime, this is # of minutes since midnight // otherwise: # of 1/300th of a second since midnight public int time; } }
// 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. // // An AppDomainManager gives a hosting application the chance to // participate in the creation and control the settings of new AppDomains. // namespace System { using System.Collections; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; using System.Security.Policy; using System.Threading; #if FEATURE_CLICKONCE using System.Runtime.Hosting; #endif using System.Runtime.Versioning; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; #if FEATURE_APPDOMAINMANAGER_INITOPTIONS [Flags] [System.Runtime.InteropServices.ComVisible(true)] public enum AppDomainManagerInitializationOptions { None = 0x0000, RegisterWithHost = 0x0001 } #endif // FEATURE_APPDOMAINMANAGER_INITOPTIONS [System.Security.SecurityCritical] // auto-generated_required [System.Runtime.InteropServices.ComVisible(true)] #if !FEATURE_CORECLR [SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags = SecurityPermissionFlag.Infrastructure)] #endif #if FEATURE_REMOTING public class AppDomainManager : MarshalByRefObject { #else // FEATURE_REMOTING public class AppDomainManager { #endif // FEATURE_REMOTING public AppDomainManager () {} #if FEATURE_REMOTING [System.Security.SecurityCritical] // auto-generated public virtual AppDomain CreateDomain (string friendlyName, Evidence securityInfo, AppDomainSetup appDomainInfo) { return CreateDomainHelper(friendlyName, securityInfo, appDomainInfo); } [System.Security.SecurityCritical] // auto-generated_required [SecurityPermissionAttribute(SecurityAction.Demand, ControlAppDomain = true)] protected static AppDomain CreateDomainHelper (string friendlyName, Evidence securityInfo, AppDomainSetup appDomainInfo) { if (friendlyName == null) throw new ArgumentNullException("friendlyName", Environment.GetResourceString("ArgumentNull_String")); Contract.EndContractBlock(); // If evidence is provided, we check to make sure that is allowed. if (securityInfo != null) { new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Demand(); // Check the evidence to ensure that if it expects a sandboxed domain, it actually gets one. AppDomain.CheckDomainCreationEvidence(appDomainInfo, securityInfo); } if (appDomainInfo == null) { appDomainInfo = new AppDomainSetup(); } // If there was no specified AppDomainManager for the new domain, default it to being the same // as the current domain's AppDomainManager. if (appDomainInfo.AppDomainManagerAssembly == null || appDomainInfo.AppDomainManagerType == null) { string inheritedDomainManagerAssembly; string inheritedDomainManagerType; AppDomain.CurrentDomain.GetAppDomainManagerType(out inheritedDomainManagerAssembly, out inheritedDomainManagerType); if (appDomainInfo.AppDomainManagerAssembly == null) { appDomainInfo.AppDomainManagerAssembly = inheritedDomainManagerAssembly; } if (appDomainInfo.AppDomainManagerType == null) { appDomainInfo.AppDomainManagerType = inheritedDomainManagerType; } } // If there was no specified TargetFrameworkName for the new domain, default it to the current domain's. if (appDomainInfo.TargetFrameworkName == null) appDomainInfo.TargetFrameworkName = AppDomain.CurrentDomain.GetTargetFrameworkName(); return AppDomain.nCreateDomain(friendlyName, appDomainInfo, securityInfo, securityInfo == null ? AppDomain.CurrentDomain.InternalEvidence : null, AppDomain.CurrentDomain.GetSecurityDescriptor()); } #endif // FEATURE_REMOTING [System.Security.SecurityCritical] public virtual void InitializeNewDomain (AppDomainSetup appDomainInfo) { // By default, InitializeNewDomain does nothing. AppDomain.CreateAppDomainManager relies on this fact. } #if FEATURE_APPDOMAINMANAGER_INITOPTIONS private AppDomainManagerInitializationOptions m_flags = AppDomainManagerInitializationOptions.None; public AppDomainManagerInitializationOptions InitializationFlags { get { return m_flags; } set { m_flags = value; } } #endif // FEATURE_APPDOMAINMANAGER_INITOPTIONS #if FEATURE_CLICKONCE private ApplicationActivator m_appActivator = null; public virtual ApplicationActivator ApplicationActivator { get { if (m_appActivator == null) m_appActivator = new ApplicationActivator(); return m_appActivator; } } #endif //#if FEATURE_CLICKONCE #if FEATURE_CAS_POLICY public virtual HostSecurityManager HostSecurityManager { get { return null; } } public virtual HostExecutionContextManager HostExecutionContextManager { get { // By default, the AppDomainManager returns the HostExecutionContextManager. return HostExecutionContextManager.GetInternalHostExecutionContextManager(); } } #endif // FEATURE_CAS_POLICY [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] private static extern void GetEntryAssembly(ObjectHandleOnStack retAssembly); private Assembly m_entryAssembly = null; public virtual Assembly EntryAssembly { [System.Security.SecurityCritical] // auto-generated get { // The default AppDomainManager sets the EntryAssembly depending on whether the // AppDomain is a manifest application domain or not. In the first case, we parse // the application manifest to find out the entry point assembly and return that assembly. // In the second case, we maintain the old behavior by calling GetEntryAssembly(). if (m_entryAssembly == null) { #if FEATURE_CLICKONCE AppDomain domain = AppDomain.CurrentDomain; if (domain.IsDefaultAppDomain() && domain.ActivationContext != null) { ManifestRunner runner = new ManifestRunner(domain, domain.ActivationContext); m_entryAssembly = runner.EntryAssembly; } else #endif //#if FEATURE_CLICKONCE { RuntimeAssembly entryAssembly = null; GetEntryAssembly(JitHelpers.GetObjectHandleOnStack(ref entryAssembly)); m_entryAssembly = entryAssembly; } } return m_entryAssembly; } } internal static AppDomainManager CurrentAppDomainManager { [System.Security.SecurityCritical] // auto-generated get { return AppDomain.CurrentDomain.DomainManager; } } public virtual bool CheckSecuritySettings (SecurityState state) { return false; } #if FEATURE_APPDOMAINMANAGER_INITOPTIONS [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool HasHost(); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SecurityCritical] [SuppressUnmanagedCodeSecurity] private static extern void RegisterWithHost(IntPtr appDomainManager); internal void RegisterWithHost() { if (HasHost()) { IntPtr punkAppDomainManager = IntPtr.Zero; RuntimeHelpers.PrepareConstrainedRegions(); try { punkAppDomainManager = Marshal.GetIUnknownForObject(this); RegisterWithHost(punkAppDomainManager); } finally { if (!punkAppDomainManager.IsNull()) { Marshal.Release(punkAppDomainManager); } } } } #endif // FEATURE_APPDOMAINMANAGER_INITOPTIONS } }
#region Using directives using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Reflection; using System.Diagnostics; using System.Runtime.Remoting.Messaging; using System.Workflow.ComponentModel; using System.Workflow.ComponentModel.Design; using System.Workflow.Runtime; using System.Workflow.Runtime.Hosting; #endregion Using directives namespace System.Workflow.Activities { [Serializable] internal class StateMachineSubscriptionManager { private SetStateSubscription _setStateSubscription; private List<StateMachineSubscription> _eventQueue = new List<StateMachineSubscription>(); private Dictionary<IComparable, StateMachineSubscription> _subscriptions = new Dictionary<IComparable, StateMachineSubscription>(); private StateMachineExecutionState _executionState; internal StateMachineSubscriptionManager(StateMachineExecutionState executionState, Guid instanceId) { _executionState = executionState; _setStateSubscription = new SetStateSubscription(instanceId); } #region Properties private List<StateMachineSubscription> EventQueue { get { return this._eventQueue; } } internal StateMachineExecutionState ExecutionState { get { return _executionState; } } internal Dictionary<IComparable, StateMachineSubscription> Subscriptions { get { return this._subscriptions; } } internal SetStateSubscription SetStateSubscription { get { return _setStateSubscription; } } #endregion Properties internal void UnsubscribeState(ActivityExecutionContext context) { StateActivity state = (StateActivity)context.Activity; foreach (Activity childActivity in state.EnabledActivities) { EventDrivenActivity eventDriven = childActivity as EventDrivenActivity; if (eventDriven != null) { if (IsEventDrivenSubscribed(eventDriven)) UnsubscribeEventDriven(context, eventDriven); } } } internal void ReevaluateSubscriptions(ActivityExecutionContext context) { Dictionary<IComparable, StateMachineSubscription> subscriptions = this.GetSubscriptionsShallowCopy(); List<IComparable> subscribed = new List<IComparable>(); StateActivity state = StateMachineHelpers.GetCurrentState(context); while (state != null) { foreach (Activity activity in state.EnabledActivities) { EventDrivenActivity eventDriven = activity as EventDrivenActivity; if (eventDriven == null) continue; IEventActivity eventActivity = StateMachineHelpers.GetEventActivity(eventDriven); IComparable queueName = eventActivity.QueueName; if (queueName == null) continue; StateMachineSubscription subscription; subscriptions.TryGetValue(queueName, out subscription); EventActivitySubscription eventActivitySubscription = subscription as EventActivitySubscription; if (eventActivitySubscription != null) { if (eventActivitySubscription.EventDrivenName.Equals(eventDriven.QualifiedName)) { // this EventDriven is already subscribed subscribed.Add(queueName); continue; } else { // Check if this state already subscribe to this event // if so, throws, since it is not valid to subscribe to the // same event twice if (eventActivitySubscription.StateName.Equals(state.QualifiedName)) throw new InvalidOperationException(SR.GetStateAlreadySubscribesToThisEvent(state.QualifiedName, queueName)); // some other EventDriven is subscribed, so we need to unsubscribe if // the event driven belongs to one of our parents if (IsParentState(state, eventActivitySubscription.StateName)) { UnsubscribeAction unsubscribe = new UnsubscribeAction(eventActivitySubscription.StateName, eventActivitySubscription.EventDrivenName); this.ExecutionState.EnqueueAction(unsubscribe); subscriptions.Remove(queueName); } } } // Tests if a child state already subscribes to this event // is so, skip, since the child takes precedence if (subscribed.Contains(queueName)) continue; SubscribeAction subscribe = new SubscribeAction(state.QualifiedName, eventDriven.QualifiedName); this.ExecutionState.EnqueueAction(subscribe); subscribed.Add(queueName); } state = state.Parent as StateActivity; } StateActivity currentState = StateMachineHelpers.GetCurrentState(context); DisableQueuesAction disableQueues = new DisableQueuesAction(currentState.QualifiedName); this.ExecutionState.EnqueueAction(disableQueues); } private bool IsParentState(StateActivity state, string stateName) { StateActivity parentState = state.Parent as StateActivity; while (parentState != null) { if (parentState.QualifiedName.Equals(stateName)) return true; parentState = parentState.Parent as StateActivity; } return false; } internal void SubscribeEventDriven(ActivityExecutionContext context, EventDrivenActivity eventDriven) { IEventActivity eventActivity = StateMachineHelpers.GetEventActivity(eventDriven); Activity activity = (Activity)eventActivity; IComparable queueName = GetQueueName(eventActivity); Debug.Assert(!this.Subscriptions.ContainsKey(queueName)); SubscribeEventActivity(context, eventActivity); } internal void UnsubscribeEventDriven(ActivityExecutionContext context, EventDrivenActivity eventDriven) { Debug.Assert(IsEventDrivenSubscribed(eventDriven)); IEventActivity eventActivity = StateMachineHelpers.GetEventActivity(eventDriven); UnsubscribeEventActivity(context, eventActivity); } private StateMachineSubscription SubscribeEventActivity(ActivityExecutionContext context, IEventActivity eventActivity) { EventActivitySubscription subscription = new EventActivitySubscription(); StateActivity state = (StateActivity)context.Activity; subscription.Subscribe(context, state, eventActivity); WorkflowQueue workflowQueue = GetWorkflowQueue(context, subscription.QueueName); if (workflowQueue != null) workflowQueue.Enabled = true; Debug.Assert(subscription.QueueName != null); this.Subscriptions[subscription.QueueName] = subscription; return subscription; } private void UnsubscribeEventActivity(ActivityExecutionContext context, IEventActivity eventActivity) { if (context == null) throw new ArgumentNullException("context"); if (eventActivity == null) throw new ArgumentNullException("eventActivity"); EventActivitySubscription subscription = GetSubscription(eventActivity); WorkflowQueue workflowQueue = GetWorkflowQueue(context, subscription.QueueName); if (workflowQueue != null) workflowQueue.Enabled = false; UnsubscribeEventActivity(context, eventActivity, subscription); } private void UnsubscribeEventActivity(ActivityExecutionContext context, IEventActivity eventActivity, EventActivitySubscription subscription) { if (context == null) throw new ArgumentNullException("context"); if (eventActivity == null) throw new ArgumentNullException("eventActivity"); if (subscription == null) throw new ArgumentNullException("subscription"); subscription.Unsubscribe(context, eventActivity); RemoveFromQueue(subscription.SubscriptionId); Debug.Assert(subscription.QueueName != null); this.Subscriptions.Remove(subscription.QueueName); } internal void CreateSetStateEventQueue(ActivityExecutionContext context) { this.SetStateSubscription.CreateQueue(context); this.Subscriptions[this.SetStateSubscription.SubscriptionId] = this.SetStateSubscription; } internal void DeleteSetStateEventQueue(ActivityExecutionContext context) { this.Subscriptions[this.SetStateSubscription.SubscriptionId] = null; this.SetStateSubscription.DeleteQueue(context); } internal void SubscribeToSetStateEvent(ActivityExecutionContext context) { this.SetStateSubscription.Subscribe(context); this.Subscriptions[this.SetStateSubscription.SubscriptionId] = this.SetStateSubscription; } internal void UnsubscribeToSetStateEvent(ActivityExecutionContext context) { this.Subscriptions[this.SetStateSubscription.SubscriptionId] = null; this.SetStateSubscription.Unsubscribe(context); } private bool IsEventDrivenSubscribed(EventDrivenActivity eventDriven) { IEventActivity eventActivity = StateMachineHelpers.GetEventActivity(eventDriven); EventActivitySubscription subscription = GetSubscription(eventActivity); return (subscription != null); } private EventActivitySubscription GetSubscription(IEventActivity eventActivity) { IComparable queueName = GetQueueName(eventActivity); if ((queueName == null) || (!this.Subscriptions.ContainsKey(queueName))) return null; EventActivitySubscription subscription = this.Subscriptions[queueName] as EventActivitySubscription; Activity activity = (Activity)eventActivity; if (subscription == null || subscription.EventActivityName != activity.QualifiedName) return null; return subscription; } private StateMachineSubscription GetSubscription(IComparable queueName) { StateMachineSubscription subscription; this.Subscriptions.TryGetValue(queueName, out subscription); return subscription; } /* Currently not used, left here for completeness internal static void EnableStateWorkflowQueues(ActivityExecutionContext context, StateActivity state) { ChangeStateWorkflowQueuesState(context, state, true); } */ internal static void DisableStateWorkflowQueues(ActivityExecutionContext context, StateActivity state) { ChangeStateWorkflowQueuesState(context, state, false); } private static void ChangeStateWorkflowQueuesState(ActivityExecutionContext context, StateActivity state, bool enabled) { foreach (Activity activity in state.EnabledActivities) { EventDrivenActivity eventDriven = activity as EventDrivenActivity; if (eventDriven != null) ChangeEventDrivenQueueState(context, eventDriven, enabled); } } internal static void ChangeEventDrivenQueueState(ActivityExecutionContext context, EventDrivenActivity eventDriven, bool enabled) { IEventActivity eventActivity = StateMachineHelpers.GetEventActivity(eventDriven); IComparable queueName = GetQueueName(eventActivity); if (queueName == null) return; // skip unitialized follower WorkflowQueue workflowQueue = GetWorkflowQueue(context, queueName); if (workflowQueue != null) workflowQueue.Enabled = enabled; } internal static WorkflowQueue GetWorkflowQueue(ActivityExecutionContext context, IComparable queueName) { WorkflowQueuingService workflowQueuingService = context.GetService<WorkflowQueuingService>(); if (workflowQueuingService.Exists(queueName)) { WorkflowQueue workflowQueue = workflowQueuingService.GetWorkflowQueue(queueName); return workflowQueue; } return null; } private static IComparable GetQueueName(IEventActivity eventActivity) { IComparable queueName = eventActivity.QueueName; return queueName; } private Dictionary<IComparable, StateMachineSubscription> GetSubscriptionsShallowCopy() { Dictionary<IComparable, StateMachineSubscription> subscriptions = new Dictionary<IComparable, StateMachineSubscription>(); foreach (KeyValuePair<IComparable, StateMachineSubscription> dictionaryEntry in this.Subscriptions) { subscriptions.Add(dictionaryEntry.Key, dictionaryEntry.Value); } return subscriptions; } #region Event Queue Methods internal void Enqueue(ActivityExecutionContext context, Guid subscriptionId) { StateMachineSubscription subscription = GetSubscription(subscriptionId); if (subscription != null) { // subscription can be null if we already unsubscribed to // this event this.EventQueue.Add(subscription); } ProcessQueue(context); } internal void Enqueue(ActivityExecutionContext context, IComparable queueName) { StateMachineSubscription subscription = GetSubscription(queueName); if (subscription != null) { // subscription can be null if we already unsubscribed to // this event this.EventQueue.Add(subscription); } ProcessQueue(context); } internal StateMachineSubscription Dequeue() { StateMachineSubscription subscription = this.EventQueue[0]; this.EventQueue.RemoveAt(0); return subscription; } private void RemoveFromQueue(Guid subscriptionId) { this.EventQueue.RemoveAll(delegate(StateMachineSubscription subscription) { return subscription.SubscriptionId.Equals(subscriptionId); }); } internal void ProcessQueue(ActivityExecutionContext context) { StateActivity currentState = StateMachineHelpers.GetCurrentState(context); if (this.EventQueue.Count == 0 || this.ExecutionState.HasEnqueuedActions || this.ExecutionState.SchedulerBusy || currentState == null) return; StateMachineSubscription subscription = Dequeue(); subscription.ProcessEvent(context); } #endregion Event Queue Methods } }
using UnityEngine; using System.Collections; public class SBCharacterController : MonoBehaviour { #region Variables public string m_CharacterName = ""; public float m_SbmScale = 1.0f; public string m_PrevState = ""; public string m_LocomotionStateName = "allLocomotion"; public bool m_ShowVelocityNumbers = false; //float m_LastTriggerVal = 0; public float m_LinearAccel = 2.0f; public float m_LinearDeccel = 1.0f; public float m_AngularAccel = 150.0f; public float m_AngularDeccel = 100.0f; public float m_StrafeAccel = 1.0f; public float m_CurLinearSpeedLimit = 4.0f; public float m_CurAngularSpeedLimit = 140.0f; float v; float w; float s; float vPrev; float wPrev; float sPrev; bool starting = false; bool stopping = false; bool inTransition = false; // HACK - for TAB bool startedInTransition = false; bool startedOutTransition = false; float startTransitionTime = 0; #endregion #region Functions void Start() { if (string.IsNullOrEmpty(m_CharacterName)) { m_CharacterName = gameObject.name; } } void Update() { DoMovement(); } void ResetMovement() { v = w = s = 0; starting = stopping = false; } void DoMovement() { float verticalAxis = Input.GetAxis("Vertical"); float horizontalAxis = Input.GetAxis("Horizontal"); string currentStateName = SmartbodyManager.Get().SBGetCurrentStateName(m_CharacterName); m_PrevState = currentStateName; float unitScale = 1.0f / m_SbmScale;// / m_sbm.m_PositionScale; float scale = 1.0f; float linearAcc = m_LinearAccel * scale * unitScale; float angularAcc = m_AngularAccel * scale; //float strifeAcc = m_StrafeAccel * scale * unitScale; // automatic de-acceleration when the key is not pressed float linearDcc = m_LinearDeccel; float angularDcc = m_AngularDeccel; //float straifeDc = strifeAcc*2.5f; // speed limits float runSpeedLimit = 1.0f*unitScale; //float walkSpeedLimit = 1.2f*unitScale; float angSpeedLimit = 140.0f; float strifeSpeedLimit = 1.0f*unitScale; // do not perform any speed update during start if (currentStateName == m_LocomotionStateName) inTransition = false; if (!inTransition) { if (verticalAxis > 0) { v += verticalAxis * linearAcc * Time.deltaTime; runSpeedLimit *= verticalAxis; } else if (verticalAxis < 0) { v += verticalAxis * linearAcc * Time.deltaTime; // verticalAxis is negative } else // gradually de-accelerate { if (v > 0) { v -= linearDcc * Time.deltaTime; } } /*if (Input.GetKey(KeyCode.End) || Input.GetButton("StrafeRight")) { s += strifeAcc * Time.deltaTime; } else if (Input.GetKey(KeyCode.Delete) || Input.GetButton("StrafeLeft")) { s -= strifeAcc * Time.deltaTime; } else // gradually de-accelerate { if (s > 0) { s -= straifeDc * Time.deltaTime; if (s < 0) s = 0; } else if (s < 0) { s += straifeDc * Time.deltaTime; if (s > 0) w = s; } }*/ if (horizontalAxis < 0) { //Debug.Log("horizontalAxis: " + horizontalAxis); w += Mathf.Abs(horizontalAxis) * angularAcc * Time.deltaTime; angSpeedLimit *= Mathf.Abs(horizontalAxis); } else if (horizontalAxis > 0) { //Debug.Log("horizontalAxis: " + horizontalAxis); w -= Mathf.Abs(horizontalAxis) * angularAcc * Time.deltaTime; angSpeedLimit *= Mathf.Abs(horizontalAxis); } else // gradually de-accelerate { if (w > 0) { w -= angularDcc * Time.deltaTime; if (w < 0) w = 0; } else if (w < 0) { w += angularDcc * Time.deltaTime; if (w > 0) w = 0; } } // gradually change the angular speed limit to avoid sudden change if (m_CurAngularSpeedLimit > angSpeedLimit) { m_CurAngularSpeedLimit -= angularDcc * Time.deltaTime; if (m_CurAngularSpeedLimit < angSpeedLimit) m_CurAngularSpeedLimit = angSpeedLimit; } else if (m_CurAngularSpeedLimit < angSpeedLimit) { m_CurAngularSpeedLimit += angularAcc * Time.deltaTime; if (m_CurAngularSpeedLimit > angSpeedLimit) m_CurAngularSpeedLimit = angSpeedLimit; } if (m_CurLinearSpeedLimit > runSpeedLimit) { m_CurLinearSpeedLimit -= linearDcc * Time.deltaTime; if (m_CurLinearSpeedLimit < runSpeedLimit) m_CurLinearSpeedLimit = runSpeedLimit; } else if (m_CurLinearSpeedLimit < runSpeedLimit) { m_CurLinearSpeedLimit += linearAcc * Time.deltaTime; if (m_CurLinearSpeedLimit > runSpeedLimit) m_CurLinearSpeedLimit = runSpeedLimit; } // make sure the control parameter does not exceed limits if (w > m_CurAngularSpeedLimit) w = m_CurAngularSpeedLimit; if (w < -m_CurAngularSpeedLimit) w = -m_CurAngularSpeedLimit; if (s > strifeSpeedLimit) s = strifeSpeedLimit; if (s < -strifeSpeedLimit) s = -strifeSpeedLimit; if (v > m_CurLinearSpeedLimit) v = m_CurLinearSpeedLimit; if (v < 0) v = 0; // we don't allow backward walking....yet } if (m_ShowVelocityNumbers) { Debug.Log(currentStateName + " - v: " + v + " w: " + w + " s: " + s + " vert: " + verticalAxis + " horiz: " + horizontalAxis); } // HACK - for TAB if (startedInTransition) { if (Time.time - startTransitionTime > 0.666f) { if (v != vPrev || w != wPrev || s != sPrev) { SmartbodyManager.Get().SBStateChange(m_CharacterName, m_LocomotionStateName, "schedule", "Loop", "Now", v, w, s); vPrev = v; wPrev = w; sPrev = s; starting = true; stopping = false; inTransition = true; startedInTransition = false; } } } // HACK - for TAB if (startedOutTransition) { if (Time.time - startTransitionTime > 0.666f) { v = w = 0; SmartbodyManager.Get().SBStateChange(m_CharacterName, "PseudoIdle", "schedule", "Loop", "Now"); stopping = true; starting = false; startedOutTransition = false; } } float speedEps = 0.001f * unitScale; float angleEps = 0.01f; if ( (Mathf.Abs(v) > 0 || Mathf.Abs(w) > 0 || Mathf.Abs(s) > 0) && currentStateName == "PseudoIdle" && !starting) { #if false if (v != vPrev || w != wPrev || s != sPrev) { SBHelpers.SBStateChange(m_CharacterName, m_LocomotionStateName, "schedule", "Loop", "Now", v, w, s); vPrev = v; wPrev = w; sPrev = s; starting = true; stopping = false; inTransition = true; } #else // HACK - for TAB if (!startedInTransition) { SmartbodyManager.Get().SBPlayAnim(m_CharacterName, "ChrBrad@Idle01_ToLocIdle01"); startedInTransition = true; startTransitionTime = Time.time; } #endif } else if (Mathf.Abs(v) < speedEps && Mathf.Abs(w) < angleEps && Mathf.Abs(s) < speedEps && currentStateName == m_LocomotionStateName && !stopping) { #if false v = w = 0; SBHelpers.SBStateChange(m_CharacterName, "PseudoIdle", "schedule", "Loop", "Now"); stopping = true; starting = false; #else // HACK - for TAB if (!startedOutTransition) { SmartbodyManager.Get().SBPlayAnim(m_CharacterName, "ChrBrad@LocIdle01_ToIdle01"); startedOutTransition = true; startTransitionTime = Time.time; } #endif } else if (currentStateName == m_LocomotionStateName)// update moving parameter { if (v != vPrev || w != wPrev || s != sPrev) { SmartbodyManager.Get().SBStateChange(m_CharacterName, m_LocomotionStateName, "update", "Loop", "Now", v, w, s); vPrev = v; wPrev = w; sPrev = s; } } } /*public override void VHOnDisable() { ResetMovement(); SBHelpers.SBWalkImmediate(charName, m_LocomotionStateName, 0, 0, 0); }*/ #endregion }
using System; using System.Collections.Generic; using System.Text; namespace axiomPdfTest { public class Company { private int id; public int Id { get { return id; } set { id = value; } } private string name; public string Name { get { return name; } set { name = value; } } private string logo; public string Logo { get { return logo; } set { logo = value; } } private byte[] binaryLogo; public byte[] BinaryLogo { get { return binaryLogo; } set { binaryLogo = value; } } private string description; public string Description { get { return description; } set { description = value; } } public override string ToString() { return string.Format("{0} {1} [{2}]", id, name, description); } } public class Manufacturer { private string name; public string Name { get { return name; } set { name = value; } } private int id; public int Id { get { return id; } set { id = value; } } private string description; public string Description { get { return description; } set { description = value; } } private List<Product> products = new List<Product>(); public List<Product> Products { get { return products; } } public override string ToString() { return string.Format("{0} {1} [{2}]", id, name, description); } } public class Product { private int manufacturerId; public int ManufacturerId { get { return manufacturerId; } set { manufacturerId = value; } } private int id; public int Id { get { return id; } set { id = value; } } private string name; public string Name { get { return name; } set { name = value; } } private string description; public string Description { get { return description; } set { description = value; } } private float quantity; public float Quantity { get { return quantity; } set { quantity = value; } } private float price = 0; public float Price { get { return price; } set { price = value; } } private List<Price> prices = new List<Price>(); public List<Price> Prices { get { return prices; } set { prices = value; } } public override string ToString() { return string.Format("{0}, {1} - Qnt:{2}, Price:{3}, [{4}]", id, name, quantity, price, description); } } public class Price { private int productId; public int ProductId { get { return productId; } set { productId = value; } } private int id; public int Id { get { return id; } set { id = value; } } private float value = 0; public float Value { get { return value; } set { this.value = value; } } private string date; public string Date { get { return date; } set { date = value; } } private float quantity; public float Quantity { get { return quantity; } set { quantity = value; } } public override string ToString() { return string.Format("{0} Date:{1}, Qnt:{2}, Price:{3}", id, date, quantity, value); } } public class Bank { private int id; public int Id { get { return id; } set { id = value; } } private string name; public string Name { get { return name; } set { name = value; } } private string description; public string Description { get { return description; } set { description = value; } } private string address; public string Address { get { return address; } set { address = value; } } private List<Client> clients = new List<Client>(); public List<Client> Clients { get { return clients; } } public override string ToString() { return string.Format("{0} {1}, Addr:{2} [{3}]", id, name, address, description); } } public class Client { private int bankId; public int BankId { get { return bankId; } set { bankId = value; } } private int id; public int Id { get { return id; } set { id = value; } } private string name; public string Name { get { return name; } set { name = value; } } private byte[] photoInline; public byte[] PhotoInline { get { return photoInline; } set { photoInline = value; } } private string description; public string Description { get { return description; } set { description = value; } } private List<Account> accounts = new List<Account>(); public List<Account> Accounts { get { return accounts; } } public override string ToString() { return string.Format("{0} {1} [{2}]", id, name, description); } } public class Account { private int id; public int Id { get { return id; } set { id = value; } } private int clientId; public int ClientId { get { return clientId; } set { clientId = value; } } private string accNumber; public string AccNumber { get { return accNumber; } set { accNumber = value; } } private string lastChange; public string LastChange { get { return lastChange; } set { lastChange = value; } } private float balance; public float Balance { get { return balance; } set { balance = value; } } public override string ToString() { return string.Format("{0}, {1}, LastChange:{2}, Balance:{3}", id, AccNumber, lastChange, Balance); } } /// <summary> /// This will generate data /// </summary> public static class Generator { private static string[] firstNames = new string[] { "Mathew", "Carmella", "Kurt", "Serena", "Zelma", "Penelope", "Javier", "Jeorge", "Nicolas", "David", "Ted", "Christian", "Ana", "Darren", "Kenya", "Johana", "Sebastian", "Ditrich", "Emanuel", "Eluise", "Elise", "Elenore", "Maria", "Janice", "Luke", "Drake", "Will", "Wendy", "Sara", "Sonya", "Crendy", "Cody", "Lance", "Lucy", "Anabel", "George", "Hugh", "Tia", "Nathan", "Florian" }; private static string[] lastNames = new string[] { "Bangallow", "Edelen", "Sharber", "Gleeson", "Woodtrust", "Seearch", "Cohan", "Rusum", "Molland", "Holly", "Heidreich", "Liskey", "Oncly", "Pavlak", "Islen", "Tully", "Abbe", "Lady", "Schefield", "Milkinson", "Presgraves", "Gravelword", "Dismukes", "Hogan" }; private static string[] descriptions = new string[] { "This is awesome thing", "Exceptional to have this", "Must join this club", "Invitations to this are not required", "This is the best thing to see", "Something worth of having", "There is nothing like home", "Always check this twice", "Comes in different variaties", "Always enjoy it, never lose it", "Its nice", "A MUST HAVE thing", "Very bad non reliable", "Entering level is really hard for this", "Uses 10% discount", "Uses 20% discount", "Buy one, get one free", "This is B class", "This is A Class" }; private static string[] addresses = new string[] { "Mike Arandjica 4/13", "Bulevar Oslobodjenja 10", "Mite Andrica 10B", "Stefana Sremca 13", "SunSet Boulevard 11034", "River Street AKF190", "London Street 12C", "Trg Majke Jevrosime 1", "Avenija 5", "Bil Klintona 34" }; private static string[] companyNames = new string[] { "Astral Ltd", "AxiomCoders", "Azirious Soft", "TechnoMarket", "Bee Ltd", "Megasoft", "Ziro Ltd.", "Nitesa Technologies", "Funky Music Instruments Ltd.", "Exotic Tech", "Furious Lid", "Nikees", "Oukland Public Producers", "Bennetony", "McLaren", "Communication Globe", "Word Press Studios", "General Electronics" }; private static string[] productNames = new string[] { "Tooth Brush 100NB", "Mouse Genius A4", "Samsung LCD 21\"", "Jeans Ripley XNO", "XBOXY 360ZX", "Sony Playstation 3", "Nitesa Washing Machine LK2300", "Nivea Hand Cream 100g", "Pistol CZ33", "Ice cream Mochito", "Bacardi Dark Rum 1l", "Grand Piano System 10LE", "Toshiba Satellite A345N", "Dell ISOK223", "Hybernation armour 10cc", "Chocolate Milk 1l", "Sour cream 0.5l", "Minced pork meat 1kg", "Fuji Apples", "Casio CTK810", "Casio CTK4000 Keyboard", "Shower soup MaxFactor", "Dinning table IKEA", "SF Oranges", "Sparkling Water 1l", "Strawberry icecream 1kg", "Entertainment studio LK10", "Panosanoic Phone 3004K", "Gentlmens Hat", "Dinning Plate Green", "Snorkling full gear KW1"}; private static Random rnd = new Random(); private static string GenerateName() { int fid = rnd.Next(firstNames.Length-1); int lid = rnd.Next(lastNames.Length-1); return firstNames[fid] + " " + lastNames[lid]; } private static string GenerateProductName() { return productNames[rnd.Next(productNames.Length - 1)]; } private static string GenerateCompanyName() { return companyNames[rnd.Next(companyNames.Length - 1)]; } private static string GenerateDescription() { return descriptions[rnd.Next(descriptions.Length-1)]; } private static float GenerateQuantity() { return (float)(rnd.NextDouble() * 100 + 5.0); } private static float GeneratePrice() { return (float)rnd.Next(50, 10000) / 2.0f; } private static string GenerateLogo() { return ""; } private static string GenerateAddress() { return addresses[rnd.Next(addresses.Length - 1)]; } private static Company GenerateCompany() { Company newCompany = new Company(); newCompany.Description = GenerateDescription(); newCompany.Name = GenerateCompanyName(); newCompany.Id = lastCompanyId++; newCompany.Logo = GenerateLogo(); return newCompany; } private static Manufacturer GenerateManufacturer() { Manufacturer newMan = new Manufacturer(); newMan.Name = GenerateCompanyName(); newMan.Id = lastManufacturerId++; newMan.Description = GenerateDescription(); return newMan; } private static Product GenerateProduct(Manufacturer manufacturer) { Product newProduct = new Product(); if (manufacturer != null) { newProduct.ManufacturerId = manufacturer.Id; } newProduct.Name = GenerateProductName(); newProduct.Description = GenerateDescription(); newProduct.Id = lastProductId++; newProduct.Price = GeneratePrice(); newProduct.Quantity = GenerateQuantity(); return newProduct; } private static Price GeneratePrice(Product owner) { Price newPrice = new Price(); if (owner != null) { newPrice.ProductId = owner.Id; } newPrice.Id = lastPriceId++; newPrice.Value = GeneratePrice(); newPrice.Quantity = GenerateQuantity(); newPrice.Date = DateTime.FromBinary(rnd.Next()).ToString(); return newPrice; } private static Bank GenerateBank() { Bank newBank = new Bank(); newBank.Address = GenerateAddress(); newBank.Description = GenerateDescription(); newBank.Id = lastBankId++; newBank.Name = GenerateCompanyName(); return newBank; } private static Client GenerateClient(Bank owner) { Client newClient = new Client(); newClient.Name = GenerateName(); newClient.Description = GenerateDescription(); newClient.BankId = owner.Id; newClient.Id = lastClientId++; return newClient; } private static Account GenerateAccount(Client owner) { Account newAccount = new Account(); newAccount.AccNumber = string.Format("{0}-{1}-{2}", rnd.Next(10, 10000).ToString(), rnd.Next(100, 1000).ToString(), rnd.Next(0, 1000000).ToString()); newAccount.Id = lastAccountId++; newAccount.ClientId = owner.Id; newAccount.Balance = GeneratePrice(); newAccount.LastChange = string.Format("{0}/{1}/{2} {3}:{4}:{5}", rnd.Next(1, 28), rnd.Next(1,12), rnd.Next(1996, 2009), rnd.Next(0,23), rnd.Next(0,59), rnd.Next(0,59)); return newAccount; } private static int lastAccountId = 1; private static int lastClientId = 1; private static int lastBankId = 1; private static int lastPriceId = 1; private static int lastProductId = 1; private static int lastCompanyId = 1; private static int lastManufacturerId = 1; private static Company generatedCompany; public static axiomPdfTest.Company GeneratedCompany { get { return generatedCompany; } } private static List<Manufacturer> manufacturers = new List<Manufacturer>(); public static List<Manufacturer> Manufacturers { get { return manufacturers; } } private static List<Product> products = new List<Product>(); public static List<Product> Products { get { return Generator.products; } set { Generator.products = value; } } private static List<Bank> banks = new List<Bank>(); public static List<Bank> Banks { get { return Generator.banks; } set { Generator.banks = value; } } /// <summary> /// Generate demo 1 /// </summary> public static void GenerateDemo1(int numberOfRows) { generatedCompany = GenerateCompany(); int tmp = rnd.Next(numberOfRows, (int)(numberOfRows * 1.1)); for(int i = 0; i < tmp; i++) { Manufacturer man = GenerateManufacturer(); manufacturers.Add(man); // create products for (int j = 0; j < numberOfRows; j++) { Product product = GenerateProduct(man); man.Products.Add(product); } } } /// <summary> /// Generate Demo2 /// </summary> /// <param name="numberOfRows"></param> public static void GenerateDemo2(int numberOfRows) { generatedCompany = GenerateCompany(); for (int i = 0; i < numberOfRows; i++) { Product product = GenerateProduct(null); products.Add(product); // create prices (each product have 1 - 10% of number of rows prices int tmp = rnd.Next(numberOfRows, (int)(numberOfRows * 1.1)); for (int j = 0; j < tmp; j++) { Price price = GeneratePrice(product); product.Prices.Add(price); } } } /// <summary> /// Generate Demo3 /// </summary> /// <param name="numberOfRows"></param> public static void GenerateDemo3(int numberOfRows) { int noOfBanks = numberOfRows;// rnd.Next(1, numberOfRows / 10); for(int i = 0; i < noOfBanks; i++) { Bank bank = GenerateBank(); banks.Add(bank); // generate 10% - 300% of clients int noOfClients = rnd.Next(noOfBanks, (int)(noOfBanks * 1.1)); for(int j = 0; j < noOfClients; j++) { Client client = GenerateClient(bank); bank.Clients.Add(client); // for each client generate (1 - 10% accounts) int noOfAccounts = rnd.Next(noOfClients, (int)(noOfClients * 1.1)); for(int k = 0; k < noOfAccounts; k++) { Account account = GenerateAccount(client); client.Accounts.Add(account); } } } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Compute.V1.Snippets { using Google.Api.Gax; using System; using System.Linq; using System.Threading.Tasks; using lro = Google.LongRunning; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedRoutesClientSnippets { /// <summary>Snippet for Delete</summary> public void DeleteRequestObject() { // Snippet: Delete(DeleteRouteRequest, CallSettings) // Create client RoutesClient routesClient = RoutesClient.Create(); // Initialize request argument(s) DeleteRouteRequest request = new DeleteRouteRequest { RequestId = "", Route = "", Project = "", }; // Make the request lro::Operation<Operation, Operation> response = routesClient.Delete(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = routesClient.PollOnceDelete(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteAsync</summary> public async Task DeleteRequestObjectAsync() { // Snippet: DeleteAsync(DeleteRouteRequest, CallSettings) // Additional: DeleteAsync(DeleteRouteRequest, CancellationToken) // Create client RoutesClient routesClient = await RoutesClient.CreateAsync(); // Initialize request argument(s) DeleteRouteRequest request = new DeleteRouteRequest { RequestId = "", Route = "", Project = "", }; // Make the request lro::Operation<Operation, Operation> response = await routesClient.DeleteAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await routesClient.PollOnceDeleteAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Delete</summary> public void Delete() { // Snippet: Delete(string, string, CallSettings) // Create client RoutesClient routesClient = RoutesClient.Create(); // Initialize request argument(s) string project = ""; string route = ""; // Make the request lro::Operation<Operation, Operation> response = routesClient.Delete(project, route); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = routesClient.PollOnceDelete(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteAsync</summary> public async Task DeleteAsync() { // Snippet: DeleteAsync(string, string, CallSettings) // Additional: DeleteAsync(string, string, CancellationToken) // Create client RoutesClient routesClient = await RoutesClient.CreateAsync(); // Initialize request argument(s) string project = ""; string route = ""; // Make the request lro::Operation<Operation, Operation> response = await routesClient.DeleteAsync(project, route); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await routesClient.PollOnceDeleteAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Get</summary> public void GetRequestObject() { // Snippet: Get(GetRouteRequest, CallSettings) // Create client RoutesClient routesClient = RoutesClient.Create(); // Initialize request argument(s) GetRouteRequest request = new GetRouteRequest { Route = "", Project = "", }; // Make the request Route response = routesClient.Get(request); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetRequestObjectAsync() { // Snippet: GetAsync(GetRouteRequest, CallSettings) // Additional: GetAsync(GetRouteRequest, CancellationToken) // Create client RoutesClient routesClient = await RoutesClient.CreateAsync(); // Initialize request argument(s) GetRouteRequest request = new GetRouteRequest { Route = "", Project = "", }; // Make the request Route response = await routesClient.GetAsync(request); // End snippet } /// <summary>Snippet for Get</summary> public void Get() { // Snippet: Get(string, string, CallSettings) // Create client RoutesClient routesClient = RoutesClient.Create(); // Initialize request argument(s) string project = ""; string route = ""; // Make the request Route response = routesClient.Get(project, route); // End snippet } /// <summary>Snippet for GetAsync</summary> public async Task GetAsync() { // Snippet: GetAsync(string, string, CallSettings) // Additional: GetAsync(string, string, CancellationToken) // Create client RoutesClient routesClient = await RoutesClient.CreateAsync(); // Initialize request argument(s) string project = ""; string route = ""; // Make the request Route response = await routesClient.GetAsync(project, route); // End snippet } /// <summary>Snippet for Insert</summary> public void InsertRequestObject() { // Snippet: Insert(InsertRouteRequest, CallSettings) // Create client RoutesClient routesClient = RoutesClient.Create(); // Initialize request argument(s) InsertRouteRequest request = new InsertRouteRequest { RequestId = "", RouteResource = new Route(), Project = "", }; // Make the request lro::Operation<Operation, Operation> response = routesClient.Insert(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = routesClient.PollOnceInsert(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for InsertAsync</summary> public async Task InsertRequestObjectAsync() { // Snippet: InsertAsync(InsertRouteRequest, CallSettings) // Additional: InsertAsync(InsertRouteRequest, CancellationToken) // Create client RoutesClient routesClient = await RoutesClient.CreateAsync(); // Initialize request argument(s) InsertRouteRequest request = new InsertRouteRequest { RequestId = "", RouteResource = new Route(), Project = "", }; // Make the request lro::Operation<Operation, Operation> response = await routesClient.InsertAsync(request); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await routesClient.PollOnceInsertAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for Insert</summary> public void Insert() { // Snippet: Insert(string, Route, CallSettings) // Create client RoutesClient routesClient = RoutesClient.Create(); // Initialize request argument(s) string project = ""; Route routeResource = new Route(); // Make the request lro::Operation<Operation, Operation> response = routesClient.Insert(project, routeResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = routesClient.PollOnceInsert(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for InsertAsync</summary> public async Task InsertAsync() { // Snippet: InsertAsync(string, Route, CallSettings) // Additional: InsertAsync(string, Route, CancellationToken) // Create client RoutesClient routesClient = await RoutesClient.CreateAsync(); // Initialize request argument(s) string project = ""; Route routeResource = new Route(); // Make the request lro::Operation<Operation, Operation> response = await routesClient.InsertAsync(project, routeResource); // Poll until the returned long-running operation is complete lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Operation result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name lro::Operation<Operation, Operation> retrievedResponse = await routesClient.PollOnceInsertAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Operation retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for List</summary> public void ListRequestObject() { // Snippet: List(ListRoutesRequest, CallSettings) // Create client RoutesClient routesClient = RoutesClient.Create(); // Initialize request argument(s) ListRoutesRequest request = new ListRoutesRequest { OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedEnumerable<RouteList, Route> response = routesClient.List(request); // Iterate over all response items, lazily performing RPCs as required foreach (Route item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (RouteList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Route item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Route> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Route item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAsync</summary> public async Task ListRequestObjectAsync() { // Snippet: ListAsync(ListRoutesRequest, CallSettings) // Create client RoutesClient routesClient = await RoutesClient.CreateAsync(); // Initialize request argument(s) ListRoutesRequest request = new ListRoutesRequest { OrderBy = "", Project = "", Filter = "", ReturnPartialSuccess = false, }; // Make the request PagedAsyncEnumerable<RouteList, Route> response = routesClient.ListAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Route item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((RouteList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Route item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Route> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Route item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for List</summary> public void List() { // Snippet: List(string, string, int?, CallSettings) // Create client RoutesClient routesClient = RoutesClient.Create(); // Initialize request argument(s) string project = ""; // Make the request PagedEnumerable<RouteList, Route> response = routesClient.List(project); // Iterate over all response items, lazily performing RPCs as required foreach (Route item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (RouteList page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Route item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Route> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Route item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAsync</summary> public async Task ListAsync() { // Snippet: ListAsync(string, string, int?, CallSettings) // Create client RoutesClient routesClient = await RoutesClient.CreateAsync(); // Initialize request argument(s) string project = ""; // Make the request PagedAsyncEnumerable<RouteList, Route> response = routesClient.ListAsync(project); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Route item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((RouteList page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Route item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Route> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Route item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim 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 OpenMetaverse; using OpenMetaverse.StructuredData; namespace Aurora.Framework { /// <summary> /// Inventory Item - contains all the properties associated with an individual inventory piece. /// </summary> public sealed class InventoryItemBase : InventoryNodeBase, ICloneable { private UUID m_assetID; private int m_assetType; private uint m_basePermissions; private int m_creationDate = (int) (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; private string m_creatorData = string.Empty; private string m_creatorId; private UUID m_creatorIdAsUuid = UUID.Zero; private uint m_currentPermissions; private string m_description = String.Empty; private uint m_everyonePermissions; private uint m_flags; private UUID m_folder; private UUID m_groupID; private bool m_groupOwned; private uint m_groupPermissions; private int m_invType; private uint m_nextPermissions; private int m_salePrice; private byte m_saleType; public InventoryItemBase() { } public InventoryItemBase(UUID id) { ID = id; } public InventoryItemBase(UUID id, UUID owner) { ID = id; Owner = owner; } /// <value> /// The inventory type of the item. This is slightly different from the asset type in some situations. /// </value> public int InvType { get { return m_invType; } set { m_invType = value; } } /// <value> /// The folder this item is contained in /// </value> public UUID Folder { get { return m_folder; } set { m_folder = value; } } /// <value> /// The creator of this item /// </value> public string CreatorId { get { return m_creatorId; } set { m_creatorId = value; } } ///<value> /// The UUID for the creator. This may be different from the canonical CreatorId. This property is used /// for communication with the client over the Second Life protocol, since that protocol can only understand /// UUIDs. As this is a basic framework class, this means that both the string creator id and the uuid /// reference have to be settable separately /// /// Database plugins don't need to set this, it will be set by /// upstream code (or set by the get accessor if left unset). /// /// XXX: An alternative to having a separate uuid property would be to hash the CreatorId appropriately /// every time there was communication with a UUID-only client. This may be much more expensive. ///</value> public UUID CreatorIdAsUuid { get { if (UUID.Zero == m_creatorIdAsUuid) { UUID.TryParse(CreatorId, out m_creatorIdAsUuid); } return m_creatorIdAsUuid; } set { m_creatorIdAsUuid = value; } } public string CreatorData // = <profile url>;<name> { get { return m_creatorData; } set { m_creatorData = value; } } /// <summary> /// Used by the DB layer to retrieve / store the entire user identification. /// The identification can either be a simple UUID or a string of the form /// uuid[;profile_url[;name]] /// </summary> public string CreatorIdentification { get { if (!string.IsNullOrEmpty(m_creatorData)) return m_creatorId + ';' + m_creatorData; else return m_creatorId; } set { if ((value == null) || (value != null && value == string.Empty)) { m_creatorData = string.Empty; return; } if (!value.Contains(";")) // plain UUID { m_creatorId = value; } else // <uuid>[;<endpoint>[;name]] { string name = "Unknown User"; string[] parts = value.Split(';'); if (parts.Length >= 1) m_creatorId = parts[0]; if (parts.Length >= 2) m_creatorData = parts[1]; if (parts.Length >= 3) name = parts[2]; m_creatorData += ';' + name; } } } /// <value> /// The description of the inventory item (must be less than 64 characters) /// </value> public string Description { get { return m_description; } set { m_description = value; } } ///<value> /// ///</value> public uint NextPermissions { get { return m_nextPermissions; } set { m_nextPermissions = value; } } /// <value> /// A mask containing permissions for the current owner (cannot be enforced) /// </value> public uint CurrentPermissions { get { return m_currentPermissions; } set { m_currentPermissions = value; } } ///<value> /// ///</value> public uint BasePermissions { get { return m_basePermissions; } set { m_basePermissions = value; } } ///<value> /// ///</value> public uint EveryOnePermissions { get { return m_everyonePermissions; } set { m_everyonePermissions = value; } } ///<value> /// ///</value> public uint GroupPermissions { get { return m_groupPermissions; } set { m_groupPermissions = value; } } /// <value> /// This is an enumerated value determining the type of asset (eg Notecard, Sound, Object, etc) /// </value> public int AssetType { get { return m_assetType; } set { m_assetType = value; } } /// <value> /// The UUID of the associated asset on the asset server /// </value> public UUID AssetID { get { return m_assetID; } set { m_assetID = value; } } ///<value> /// ///</value> public UUID GroupID { get { return m_groupID; } set { m_groupID = value; } } ///<value> /// ///</value> public bool GroupOwned { get { return m_groupOwned; } set { m_groupOwned = value; } } ///<value> /// ///</value> public int SalePrice { get { return m_salePrice; } set { m_salePrice = value; } } ///<value> /// ///</value> public byte SaleType { get { return m_saleType; } set { m_saleType = value; } } ///<value> /// ///</value> public uint Flags { get { return m_flags; } set { m_flags = value; } } ///<value> /// ///</value> public int CreationDate { get { return m_creationDate; } set { m_creationDate = value; } } #region ICloneable Members public object Clone() { return MemberwiseClone(); } #endregion #region IDataTransferable Members public override OSDMap ToOSD() { OSDMap map = new OSDMap(); map["AssetID"] = AssetID; map["AssetType"] = AssetType; map["BasePermissions"] = BasePermissions; map["CreationDate"] = CreationDate; map["CreatorData"] = CreatorData; map["CreatorId"] = CreatorId; map["CreatorIdentification"] = CreatorIdentification; map["CurrentPermissions"] = CurrentPermissions; map["Description"] = Description; map["EveryOnePermissions"] = EveryOnePermissions; map["Flags"] = Flags; map["Folder"] = Folder; map["GroupID"] = GroupID; map["GroupOwned"] = GroupOwned; map["GroupPermissions"] = GroupPermissions; map["ID"] = ID; map["InvType"] = InvType; map["Name"] = Name; map["NextPermissions"] = NextPermissions; map["Owner"] = Owner; map["SalePrice"] = SalePrice; map["SaleType"] = (int)SaleType; return map; } public override void FromOSD(OSDMap map) { this.AssetID = map["AssetID"]; this.AssetType = map["AssetType"]; this.BasePermissions = map["BasePermissions"]; this.CreationDate = map["CreationDate"]; this.CreatorData = map["CreatorData"]; this.CreatorId = map["CreatorId"]; this.CreatorIdentification = map["CreatorIdentification"]; this.CurrentPermissions = map["CurrentPermissions"]; this.Description = map["Description"]; this.EveryOnePermissions = map["EveryOnePermissions"]; this.Flags = map["Flags"]; this.Folder = map["Folder"]; this.GroupID = map["GroupID"]; this.GroupOwned = map["GroupOwned"]; this.GroupPermissions = map["GroupPermissions"]; this.ID = map["ID"]; this.InvType = map["InvType"]; this.Name = map["Name"]; this.NextPermissions = map["NextPermissions"]; this.Owner = map["Owner"]; this.SalePrice = map["SalePrice"]; this.SaleType = (byte)(int)map["SaleType"]; } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Rest.Generator.CSharp.Templates { #line 1 "MethodTemplate.cshtml" using System.Linq; #line default #line hidden #line 2 "MethodTemplate.cshtml" using Microsoft.Rest.Generator.ClientModel #line default #line hidden ; #line 3 "MethodTemplate.cshtml" using Microsoft.Rest.Generator.CSharp #line default #line hidden ; #line 4 "MethodTemplate.cshtml" using Microsoft.Rest.Generator.CSharp.TemplateModels #line default #line hidden ; #line 5 "MethodTemplate.cshtml" using Microsoft.Rest.Generator.Utilities #line default #line hidden ; using System.Threading.Tasks; public class MethodTemplate : Microsoft.Rest.Generator.Template<Microsoft.Rest.Generator.CSharp.MethodTemplateModel> { #line hidden public MethodTemplate() { } #pragma warning disable 1998 public override async Task ExecuteAsync() { WriteLiteral("/// <summary>\r\n"); #line 8 "MethodTemplate.cshtml" Write(WrapComment("/// ", Model.Documentation.EscapeXmlComment())); #line default #line hidden WriteLiteral("\r\n/// </summary>\r\n"); #line 10 "MethodTemplate.cshtml" foreach (var parameter in Model.LocalParameters) { #line default #line hidden WriteLiteral("/// <param name=\'"); #line 12 "MethodTemplate.cshtml" Write(parameter.Name); #line default #line hidden WriteLiteral("\'>\r\n"); #line 13 "MethodTemplate.cshtml" #line default #line hidden #line 13 "MethodTemplate.cshtml" Write(WrapComment("/// ", parameter.Documentation.EscapeXmlComment())); #line default #line hidden WriteLiteral("\r\n/// </param> \r\n"); #line 15 "MethodTemplate.cshtml" } #line default #line hidden WriteLiteral("/// <param name=\'customHeaders\'>\r\n/// Headers that will be added to request.\r\n///" + " </param>\r\n/// <param name=\'cancellationToken\'>\r\n/// Cancellation token.\r\n/// </" + "param>\r\npublic async Task<"); #line 22 "MethodTemplate.cshtml" Write(Model.OperationResponseReturnTypeString); #line default #line hidden WriteLiteral("> "); #line 22 "MethodTemplate.cshtml" Write(Model.Name); #line default #line hidden WriteLiteral("WithHttpMessagesAsync("); #line 22 "MethodTemplate.cshtml" Write(Model.GetAsyncMethodParameterDeclaration(true)); #line default #line hidden WriteLiteral(")\r\n{\r\n"); #line 24 "MethodTemplate.cshtml" #line default #line hidden #line 24 "MethodTemplate.cshtml" foreach (var parameter in Model.ParameterTemplateModels) { if (parameter.IsRequired) { #line default #line hidden WriteLiteral(" if ("); #line 28 "MethodTemplate.cshtml" Write(parameter.Name); #line default #line hidden WriteLiteral(" == null)\r\n {\r\n throw new ValidationException(ValidationRules.CannotBeN" + "ull, \""); #line 30 "MethodTemplate.cshtml" Write(parameter.Name); #line default #line hidden WriteLiteral("\");\r\n }\r\n\r\n"); #line 33 "MethodTemplate.cshtml" } if(parameter.Location != ParameterLocation.Query && (Model.HttpMethod != HttpMethod.Patch || parameter.Location != ParameterLocation.Body)) { #line default #line hidden WriteLiteral(" "); #line 37 "MethodTemplate.cshtml" Write(parameter.Type.ValidateType(Model.Scope, parameter.Name)); #line default #line hidden WriteLiteral("\r\n"); #line 38 "MethodTemplate.cshtml" } } #line default #line hidden WriteLiteral(@" // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); "); #line 47 "MethodTemplate.cshtml" #line default #line hidden #line 47 "MethodTemplate.cshtml" foreach (var parameter in Model.LocalParameters) { #line default #line hidden WriteLiteral(" tracingParameters.Add(\""); #line 49 "MethodTemplate.cshtml" Write(parameter.Name); #line default #line hidden WriteLiteral("\", "); #line 49 "MethodTemplate.cshtml" Write(parameter.Name); #line default #line hidden WriteLiteral(");\r\n"); #line 50 "MethodTemplate.cshtml" } #line default #line hidden WriteLiteral(" tracingParameters.Add(\"cancellationToken\", cancellationToken);\r\n S" + "erviceClientTracing.Enter(invocationId, this, \""); #line 52 "MethodTemplate.cshtml" Write(Model.Name); #line default #line hidden WriteLiteral("\", tracingParameters);\r\n }\r\n\r\n // Construct URL\r\n"); #line 56 "MethodTemplate.cshtml" #line default #line hidden #line 56 "MethodTemplate.cshtml" if (Model.IsAbsoluteUrl) { #line default #line hidden WriteLiteral(" string url = \""); #line 58 "MethodTemplate.cshtml" Write(Model.Url); #line default #line hidden WriteLiteral("\"; \r\n"); #line 59 "MethodTemplate.cshtml" } else { #line default #line hidden WriteLiteral(" string url = "); #line 62 "MethodTemplate.cshtml" Write(Model.ClientReference); #line default #line hidden WriteLiteral(".BaseUri.AbsoluteUri + \r\n \"/"); #line 63 "MethodTemplate.cshtml" Write(Model.Url); #line default #line hidden WriteLiteral("\";\r\n"); #line 64 "MethodTemplate.cshtml" } #line default #line hidden WriteLiteral(" "); #line 65 "MethodTemplate.cshtml" Write(Model.BuildUrl("url")); #line default #line hidden WriteLiteral("\r\n "); #line 66 "MethodTemplate.cshtml" Write(Model.RemoveDuplicateForwardSlashes("url")); #line default #line hidden WriteLiteral("\r\n // Create HTTP transport objects\r\n HttpRequestMessage httpRequest = new " + "HttpRequestMessage();\r\n httpRequest.Method = new HttpMethod(\""); #line 69 "MethodTemplate.cshtml" Write(Model.HttpMethod.ToString().ToUpper()); #line default #line hidden WriteLiteral("\");\r\n httpRequest.RequestUri = new Uri(url);\r\n // Set Headers\r\n"); #line 72 "MethodTemplate.cshtml" #line default #line hidden #line 72 "MethodTemplate.cshtml" foreach (var parameter in Model.Parameters.Where(p => p.Location == ParameterLocation.Header)) { #line default #line hidden WriteLiteral(" if ("); #line 74 "MethodTemplate.cshtml" Write(parameter.Name); #line default #line hidden WriteLiteral(" != null)\r\n {\r\n httpRequest.Headers.Add(\""); #line 76 "MethodTemplate.cshtml" Write(parameter.SerializedName); #line default #line hidden WriteLiteral("\", "); #line 76 "MethodTemplate.cshtml" Write(parameter.Type.ToString(Model.ClientReference, parameter.Name)); #line default #line hidden WriteLiteral(");\r\n }\r\n"); #line 78 "MethodTemplate.cshtml" } #line default #line hidden WriteLiteral(" if (customHeaders != null)\r\n {\r\n foreach(var header in customHeader" + "s)\r\n {\r\n httpRequest.Headers.Add(header.Key, header.Value);\r\n " + " }\r\n }\r\n "); #line 86 "MethodTemplate.cshtml" Write(EmptyLine); #line default #line hidden WriteLiteral("\r\n"); #line 87 "MethodTemplate.cshtml" #line default #line hidden #line 87 "MethodTemplate.cshtml" if (Settings.AddCredentials) { #line default #line hidden WriteLiteral(" \r\n // Set Credentials\r\n cancellationToken.ThrowIfCancellationReques" + "ted();\r\n await "); #line 92 "MethodTemplate.cshtml" Write(Model.ClientReference); #line default #line hidden WriteLiteral(".Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwa" + "it(false);\r\n \r\n"); #line 94 "MethodTemplate.cshtml" } #line default #line hidden WriteLiteral("\r\n\r\n"); #line 97 "MethodTemplate.cshtml" #line default #line hidden #line 97 "MethodTemplate.cshtml" if (Model.RequestBody != null) { #line default #line hidden WriteLiteral(" \r\n // Serialize Request \r\n string requestContent = JsonConvert.Ser" + "ializeObject("); #line 101 "MethodTemplate.cshtml" Write(Model.RequestBody.Name); #line default #line hidden WriteLiteral(", "); #line 101 "MethodTemplate.cshtml" Write(Model.GetSerializationSettingsReference(Model.RequestBody.Type)); #line default #line hidden WriteLiteral(");\r\n httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);\r\n" + " httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(\"applic" + "ation/json; charset=utf-8\");\r\n \r\n"); #line 105 "MethodTemplate.cshtml" } #line default #line hidden WriteLiteral(" // Send Request\r\n if (shouldTrace)\r\n {\r\n ServiceClientTracing.Se" + "ndRequest(invocationId, httpRequest);\r\n }\r\n\r\n cancellationToken.ThrowIfCan" + "cellationRequested();\r\n HttpResponseMessage httpResponse = await "); #line 113 "MethodTemplate.cshtml" Write(Model.ClientReference); #line default #line hidden WriteLiteral(@".HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (!("); #line 121 "MethodTemplate.cshtml" Write(Model.SuccessStatusCodePredicate); #line default #line hidden WriteLiteral("))\r\n {\r\n var ex = new "); #line 123 "MethodTemplate.cshtml" Write(Model.OperationExceptionTypeString); #line default #line hidden WriteLiteral("(string.Format(\"Operation returned an invalid status code \'{0}\'\", statusCode));\r\n" + ""); #line 124 "MethodTemplate.cshtml" #line default #line hidden #line 124 "MethodTemplate.cshtml" if (Model.DefaultResponse != null) { if (Model.DefaultResponse == PrimaryType.Stream) { #line default #line hidden WriteLiteral(" "); #line 128 "MethodTemplate.cshtml" Write(Model.DefaultResponse.Name); #line default #line hidden WriteLiteral(" errorBody = await httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false)" + ";\r\n"); #line 129 "MethodTemplate.cshtml" } else { #line default #line hidden WriteLiteral(" string responseContent = await httpResponse.Content.ReadAsStringAsync().C" + "onfigureAwait(false);\r\n "); #line 133 "MethodTemplate.cshtml" Write(Model.DefaultResponse.Name); #line default #line hidden WriteLiteral(" errorBody = JsonConvert.DeserializeObject<"); #line 133 "MethodTemplate.cshtml" Write(Model.DefaultResponse.Name); #line default #line hidden WriteLiteral(">(responseContent, "); #line 133 "MethodTemplate.cshtml" Write(Model.GetDeserializationSettingsReference(Model.DefaultResponse)); #line default #line hidden WriteLiteral(");\r\n"); #line 134 "MethodTemplate.cshtml" } #line default #line hidden WriteLiteral(" if (errorBody != null)\r\n {\r\n "); #line 137 "MethodTemplate.cshtml" Write(Model.InitializeExceptionWithMessage); #line default #line hidden WriteLiteral("\r\n ex.Body = errorBody;\r\n }\r\n"); #line 140 "MethodTemplate.cshtml" } #line default #line hidden WriteLiteral(" ex.Request = httpRequest;\r\n ex.Response = httpResponse;\r\n i" + "f (shouldTrace)\r\n {\r\n ServiceClientTracing.Error(invocationId," + " ex);\r\n }\r\n\r\n throw ex;\r\n }\r\n\r\n // Create Result\r\n var re" + "sult = new "); #line 152 "MethodTemplate.cshtml" Write(Model.OperationResponseReturnTypeString); #line default #line hidden WriteLiteral("();\r\n result.Request = httpRequest;\r\n result.Response = httpResponse;\r\n " + ""); #line 155 "MethodTemplate.cshtml" Write(Model.InitializeResponseBody); #line default #line hidden WriteLiteral("\r\n\r\n"); #line 157 "MethodTemplate.cshtml" #line default #line hidden #line 157 "MethodTemplate.cshtml" foreach (var responsePair in Model.Responses.Where(r => r.Value != null)) { #line default #line hidden WriteLiteral(" \r\n // Deserialize Response\r\n if (statusCode == "); #line 161 "MethodTemplate.cshtml" Write(MethodTemplateModel.GetStatusCodeReference(responsePair.Key)); #line default #line hidden WriteLiteral(")\r\n {\r\n"); #line 163 "MethodTemplate.cshtml" #line default #line hidden #line 163 "MethodTemplate.cshtml" if (responsePair.Value == PrimaryType.Stream) { #line default #line hidden WriteLiteral(" result.Body = await httpResponse.Content.ReadAsStreamAsync().ConfigureAwa" + "it(false);\r\n"); #line 166 "MethodTemplate.cshtml" } else { #line default #line hidden WriteLiteral(" string responseContent = await httpResponse.Content.ReadAsStringAsync().C" + "onfigureAwait(false);\r\n result.Body = JsonConvert.DeserializeObject<"); #line 170 "MethodTemplate.cshtml" Write(responsePair.Value.Name); #line default #line hidden WriteLiteral(">(responseContent, "); #line 170 "MethodTemplate.cshtml" Write(Model.GetDeserializationSettingsReference(responsePair.Value)); #line default #line hidden WriteLiteral(");\r\n"); #line 171 "MethodTemplate.cshtml" } #line default #line hidden WriteLiteral(" }\r\n \r\n"); #line 174 "MethodTemplate.cshtml" } #line default #line hidden WriteLiteral(" "); #line 175 "MethodTemplate.cshtml" if (Model.ReturnType != null && Model.DefaultResponse != null && !Model.Responses.Any()) { if (Model.DefaultResponse == PrimaryType.Stream) { #line default #line hidden WriteLiteral(" result.Body = await httpResponse.Content.ReadAsStreamAsync().Configur" + "eAwait(false);\r\n"); #line 180 "MethodTemplate.cshtml" } else { #line default #line hidden WriteLiteral(" string defaultResponseContent = await httpResponse.Content.ReadAsStri" + "ngAsync().ConfigureAwait(false);\r\n result.Body = JsonConvert.Deserial" + "izeObject<"); #line 184 "MethodTemplate.cshtml" Write(Model.DefaultResponse.Name); #line default #line hidden WriteLiteral(">(defaultResponseContent, "); #line 184 "MethodTemplate.cshtml" Write(Model.GetDeserializationSettingsReference(Model.DefaultResponse)); #line default #line hidden WriteLiteral(");\r\n"); #line 185 "MethodTemplate.cshtml" } } #line default #line hidden WriteLiteral(" \r\n if (shouldTrace)\r\n {\r\n ServiceClientTracing.Exit(invocationId" + ", result);\r\n }\r\n\r\n return result;\r\n}"); } #pragma warning restore 1998 } }
// Copyright 2017, Google LLC 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. // Generated code. DO NOT EDIT! using Google.Api.Gax; using Google.Api.Gax.Grpc; using Google.LongRunning; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; using System.Threading.Tasks; namespace Google.Cloud.Speech.V1 { /// <summary> /// Settings for a <see cref="SpeechClient"/>. /// </summary> public sealed partial class SpeechSettings : ServiceSettingsBase { /// <summary> /// Get a new instance of the default <see cref="SpeechSettings"/>. /// </summary> /// <returns> /// A new instance of the default <see cref="SpeechSettings"/>. /// </returns> public static SpeechSettings GetDefault() => new SpeechSettings(); /// <summary> /// Constructs a new <see cref="SpeechSettings"/> object with default settings. /// </summary> public SpeechSettings() { } private SpeechSettings(SpeechSettings existing) : base(existing) { GaxPreconditions.CheckNotNull(existing, nameof(existing)); RecognizeSettings = existing.RecognizeSettings; LongRunningRecognizeSettings = existing.LongRunningRecognizeSettings; LongRunningRecognizeOperationsSettings = existing.LongRunningRecognizeOperationsSettings?.Clone(); StreamingRecognizeSettings = existing.StreamingRecognizeSettings; StreamingRecognizeStreamingSettings = existing.StreamingRecognizeStreamingSettings; OnCopy(existing); } partial void OnCopy(SpeechSettings existing); /// <summary> /// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry /// for "Idempotent" <see cref="SpeechClient"/> RPC methods. /// </summary> /// <remarks> /// The eligible RPC <see cref="StatusCode"/>s for retry for "Idempotent" RPC methods are: /// <list type="bullet"> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// </remarks> public static Predicate<RpcException> IdempotentRetryFilter { get; } = RetrySettings.FilterForStatusCodes(StatusCode.DeadlineExceeded, StatusCode.Unavailable); /// <summary> /// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry /// for "NonIdempotent" <see cref="SpeechClient"/> RPC methods. /// </summary> /// <remarks> /// There are no RPC <see cref="StatusCode"/>s eligible for retry for "NonIdempotent" RPC methods. /// </remarks> public static Predicate<RpcException> NonIdempotentRetryFilter { get; } = RetrySettings.FilterForStatusCodes(); /// <summary> /// "Default" retry backoff for <see cref="SpeechClient"/> RPC methods. /// </summary> /// <returns> /// The "Default" retry backoff for <see cref="SpeechClient"/> RPC methods. /// </returns> /// <remarks> /// The "Default" retry backoff for <see cref="SpeechClient"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial delay: 100 milliseconds</description></item> /// <item><description>Maximum delay: 60000 milliseconds</description></item> /// <item><description>Delay multiplier: 1.3</description></item> /// </list> /// </remarks> public static BackoffSettings GetDefaultRetryBackoff() => new BackoffSettings( delay: TimeSpan.FromMilliseconds(100), maxDelay: TimeSpan.FromMilliseconds(60000), delayMultiplier: 1.3 ); /// <summary> /// "Default" timeout backoff for <see cref="SpeechClient"/> RPC methods. /// </summary> /// <returns> /// The "Default" timeout backoff for <see cref="SpeechClient"/> RPC methods. /// </returns> /// <remarks> /// The "Default" timeout backoff for <see cref="SpeechClient"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial timeout: 190000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Maximum timeout: 190000 milliseconds</description></item> /// </list> /// </remarks> public static BackoffSettings GetDefaultTimeoutBackoff() => new BackoffSettings( delay: TimeSpan.FromMilliseconds(190000), maxDelay: TimeSpan.FromMilliseconds(190000), delayMultiplier: 1.0 ); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>SpeechClient.Recognize</c> and <c>SpeechClient.RecognizeAsync</c>. /// </summary> /// <remarks> /// The default <c>SpeechClient.Recognize</c> and /// <c>SpeechClient.RecognizeAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 190000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 190000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings RecognizeSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>SpeechClient.LongRunningRecognize</c> and <c>SpeechClient.LongRunningRecognizeAsync</c>. /// </summary> /// <remarks> /// The default <c>SpeechClient.LongRunningRecognize</c> and /// <c>SpeechClient.LongRunningRecognizeAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 190000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 190000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description>No status codes</description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings LongRunningRecognizeSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)), retryFilter: NonIdempotentRetryFilter ))); /// <summary> /// Long Running Operation settings for calls to <c>SpeechClient.LongRunningRecognize</c>. /// </summary> /// <remarks> /// Uses default <see cref="PollSettings"/> of: /// <list type="bullet"> /// <item><description>Initial delay: 20000 milliseconds</description></item> /// <item><description>Delay multiplier: 1.5</description></item> /// <item><description>Maximum delay: 45000 milliseconds</description></item> /// <item><description>Total timeout: 86400000 milliseconds</description></item> /// </list> /// </remarks> public OperationsSettings LongRunningRecognizeOperationsSettings { get; set; } = new OperationsSettings { DefaultPollSettings = new PollSettings( Expiration.FromTimeout(TimeSpan.FromMilliseconds(86400000L)), TimeSpan.FromMilliseconds(20000L), 1.5, TimeSpan.FromMilliseconds(45000L)) }; /// <summary> /// <see cref="CallSettings"/> for calls to <c>SpeechClient.StreamingRecognize</c>. /// </summary> /// <remarks> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings StreamingRecognizeSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromTimeout(TimeSpan.FromMilliseconds(600000))); /// <summary> /// <see cref="BidirectionalStreamingSettings"/> for calls to /// <c>SpeechClient.StreamingRecognize</c>. /// </summary> /// <remarks> /// The default local send queue size is 100. /// </remarks> public BidirectionalStreamingSettings StreamingRecognizeStreamingSettings { get; set; } = new BidirectionalStreamingSettings(100); /// <summary> /// Creates a deep clone of this object, with all the same property values. /// </summary> /// <returns>A deep clone of this <see cref="SpeechSettings"/> object.</returns> public SpeechSettings Clone() => new SpeechSettings(this); } /// <summary> /// Speech client wrapper, for convenient use. /// </summary> public abstract partial class SpeechClient { /// <summary> /// The default endpoint for the Speech service, which is a host of "speech.googleapis.com" and a port of 443. /// </summary> public static ServiceEndpoint DefaultEndpoint { get; } = new ServiceEndpoint("speech.googleapis.com", 443); /// <summary> /// The default Speech scopes. /// </summary> /// <remarks> /// The default Speech scopes are: /// <list type="bullet"> /// <item><description>"https://www.googleapis.com/auth/cloud-platform"</description></item> /// </list> /// </remarks> public static IReadOnlyList<string> DefaultScopes { get; } = new ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", }); private static readonly ChannelPool s_channelPool = new ChannelPool(DefaultScopes); // Note: we could have parameterless overloads of Create and CreateAsync, // documented to just use the default endpoint, settings and credentials. // Pros: // - Might be more reassuring on first use // - Allows method group conversions // Con: overloads! /// <summary> /// Asynchronously creates a <see cref="SpeechClient"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. /// </summary> /// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="SpeechSettings"/>.</param> /// <returns>The task representing the created <see cref="SpeechClient"/>.</returns> public static async Task<SpeechClient> CreateAsync(ServiceEndpoint endpoint = null, SpeechSettings settings = null) { Channel channel = await s_channelPool.GetChannelAsync(endpoint ?? DefaultEndpoint).ConfigureAwait(false); return Create(channel, settings); } /// <summary> /// Synchronously creates a <see cref="SpeechClient"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. /// </summary> /// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="SpeechSettings"/>.</param> /// <returns>The created <see cref="SpeechClient"/>.</returns> public static SpeechClient Create(ServiceEndpoint endpoint = null, SpeechSettings settings = null) { Channel channel = s_channelPool.GetChannel(endpoint ?? DefaultEndpoint); return Create(channel, settings); } /// <summary> /// Creates a <see cref="SpeechClient"/> which uses the specified channel for remote operations. /// </summary> /// <param name="channel">The <see cref="Channel"/> for remote operations. Must not be null.</param> /// <param name="settings">Optional <see cref="SpeechSettings"/>.</param> /// <returns>The created <see cref="SpeechClient"/>.</returns> public static SpeechClient Create(Channel channel, SpeechSettings settings = null) { GaxPreconditions.CheckNotNull(channel, nameof(channel)); Speech.SpeechClient grpcClient = new Speech.SpeechClient(channel); return new SpeechClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create(ServiceEndpoint, SpeechSettings)"/> /// and <see cref="CreateAsync(ServiceEndpoint, SpeechSettings)"/>. Channels which weren't automatically /// created are not affected. /// </summary> /// <remarks>After calling this method, further calls to <see cref="Create(ServiceEndpoint, SpeechSettings)"/> /// and <see cref="CreateAsync(ServiceEndpoint, SpeechSettings)"/> will create new channels, which could /// in turn be shut down by another call to this method.</remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static Task ShutdownDefaultChannelsAsync() => s_channelPool.ShutdownChannelsAsync(); /// <summary> /// The underlying gRPC Speech client. /// </summary> public virtual Speech.SpeechClient GrpcClient { get { throw new NotImplementedException(); } } /// <summary> /// Performs synchronous speech recognition: receive results after all audio /// has been sent and processed. /// </summary> /// <param name="config"> /// *Required* Provides information to the recognizer that specifies how to /// process the request. /// </param> /// <param name="audio"> /// *Required* The audio data to be recognized. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<RecognizeResponse> RecognizeAsync( RecognitionConfig config, RecognitionAudio audio, CallSettings callSettings = null) => RecognizeAsync( new RecognizeRequest { Config = GaxPreconditions.CheckNotNull(config, nameof(config)), Audio = GaxPreconditions.CheckNotNull(audio, nameof(audio)), }, callSettings); /// <summary> /// Performs synchronous speech recognition: receive results after all audio /// has been sent and processed. /// </summary> /// <param name="config"> /// *Required* Provides information to the recognizer that specifies how to /// process the request. /// </param> /// <param name="audio"> /// *Required* The audio data to be recognized. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<RecognizeResponse> RecognizeAsync( RecognitionConfig config, RecognitionAudio audio, CancellationToken cancellationToken) => RecognizeAsync( config, audio, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Performs synchronous speech recognition: receive results after all audio /// has been sent and processed. /// </summary> /// <param name="config"> /// *Required* Provides information to the recognizer that specifies how to /// process the request. /// </param> /// <param name="audio"> /// *Required* The audio data to be recognized. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual RecognizeResponse Recognize( RecognitionConfig config, RecognitionAudio audio, CallSettings callSettings = null) => Recognize( new RecognizeRequest { Config = GaxPreconditions.CheckNotNull(config, nameof(config)), Audio = GaxPreconditions.CheckNotNull(audio, nameof(audio)), }, callSettings); /// <summary> /// Performs synchronous speech recognition: receive results after all audio /// has been sent and processed. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<RecognizeResponse> RecognizeAsync( RecognizeRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Performs synchronous speech recognition: receive results after all audio /// has been sent and processed. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual RecognizeResponse Recognize( RecognizeRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Performs asynchronous speech recognition: receive results via the /// google.longrunning.Operations interface. Returns either an /// `Operation.error` or an `Operation.response` which contains /// a `LongRunningRecognizeResponse` message. /// </summary> /// <param name="config"> /// *Required* Provides information to the recognizer that specifies how to /// process the request. /// </param> /// <param name="audio"> /// *Required* The audio data to be recognized. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata>> LongRunningRecognizeAsync( RecognitionConfig config, RecognitionAudio audio, CallSettings callSettings = null) => LongRunningRecognizeAsync( new LongRunningRecognizeRequest { Config = GaxPreconditions.CheckNotNull(config, nameof(config)), Audio = GaxPreconditions.CheckNotNull(audio, nameof(audio)), }, callSettings); /// <summary> /// Performs asynchronous speech recognition: receive results via the /// google.longrunning.Operations interface. Returns either an /// `Operation.error` or an `Operation.response` which contains /// a `LongRunningRecognizeResponse` message. /// </summary> /// <param name="config"> /// *Required* Provides information to the recognizer that specifies how to /// process the request. /// </param> /// <param name="audio"> /// *Required* The audio data to be recognized. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata>> LongRunningRecognizeAsync( RecognitionConfig config, RecognitionAudio audio, CancellationToken cancellationToken) => LongRunningRecognizeAsync( config, audio, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Performs asynchronous speech recognition: receive results via the /// google.longrunning.Operations interface. Returns either an /// `Operation.error` or an `Operation.response` which contains /// a `LongRunningRecognizeResponse` message. /// </summary> /// <param name="config"> /// *Required* Provides information to the recognizer that specifies how to /// process the request. /// </param> /// <param name="audio"> /// *Required* The audio data to be recognized. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> LongRunningRecognize( RecognitionConfig config, RecognitionAudio audio, CallSettings callSettings = null) => LongRunningRecognize( new LongRunningRecognizeRequest { Config = GaxPreconditions.CheckNotNull(config, nameof(config)), Audio = GaxPreconditions.CheckNotNull(audio, nameof(audio)), }, callSettings); /// <summary> /// Performs asynchronous speech recognition: receive results via the /// google.longrunning.Operations interface. Returns either an /// `Operation.error` or an `Operation.response` which contains /// a `LongRunningRecognizeResponse` message. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata>> LongRunningRecognizeAsync( LongRunningRecognizeRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of <c>LongRunningRecognizeAsync</c>. /// </summary> /// <param name="operationName">The name of a previously invoked operation. Must not be <c>null</c> or empty.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A task representing the result of polling the operation.</returns> public virtual Task<Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata>> PollOnceLongRunningRecognizeAsync( string operationName, CallSettings callSettings = null) => Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata>.PollOnceFromNameAsync( GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), LongRunningRecognizeOperationsClient, callSettings); /// <summary> /// Performs asynchronous speech recognition: receive results via the /// google.longrunning.Operations interface. Returns either an /// `Operation.error` or an `Operation.response` which contains /// a `LongRunningRecognizeResponse` message. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> LongRunningRecognize( LongRunningRecognizeRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// The long-running operations client for <c>LongRunningRecognize</c>. /// </summary> public virtual OperationsClient LongRunningRecognizeOperationsClient { get { throw new NotImplementedException(); } } /// <summary> /// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>LongRunningRecognize</c>. /// </summary> /// <param name="operationName">The name of a previously invoked operation. Must not be <c>null</c> or empty.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The result of polling the operation.</returns> public virtual Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> PollOnceLongRunningRecognize( string operationName, CallSettings callSettings = null) => Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata>.PollOnceFromName( GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), LongRunningRecognizeOperationsClient, callSettings); /// <summary> /// Performs bidirectional streaming speech recognition: receive results while /// sending audio. This method is only available via the gRPC API (not REST). /// </summary> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <param name="streamingSettings"> /// If not null, applies streaming overrides to this RPC call. /// </param> /// <returns> /// The client-server stream. /// </returns> public virtual StreamingRecognizeStream StreamingRecognize( CallSettings callSettings = null, BidirectionalStreamingSettings streamingSettings = null) { throw new NotImplementedException(); } /// <summary> /// Bidirectional streaming methods for <c>StreamingRecognize</c>. /// </summary> public abstract partial class StreamingRecognizeStream : BidirectionalStreamingBase<StreamingRecognizeRequest, StreamingRecognizeResponse> { } } /// <summary> /// Speech client wrapper implementation, for convenient use. /// </summary> public sealed partial class SpeechClientImpl : SpeechClient { private readonly ApiCall<RecognizeRequest, RecognizeResponse> _callRecognize; private readonly ApiCall<LongRunningRecognizeRequest, Operation> _callLongRunningRecognize; private readonly ApiBidirectionalStreamingCall<StreamingRecognizeRequest, StreamingRecognizeResponse> _callStreamingRecognize; /// <summary> /// Constructs a client wrapper for the Speech service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="SpeechSettings"/> used within this client </param> public SpeechClientImpl(Speech.SpeechClient grpcClient, SpeechSettings settings) { GrpcClient = grpcClient; SpeechSettings effectiveSettings = settings ?? SpeechSettings.GetDefault(); ClientHelper clientHelper = new ClientHelper(effectiveSettings); LongRunningRecognizeOperationsClient = new OperationsClientImpl( grpcClient.CreateOperationsClient(), effectiveSettings.LongRunningRecognizeOperationsSettings); _callRecognize = clientHelper.BuildApiCall<RecognizeRequest, RecognizeResponse>( GrpcClient.RecognizeAsync, GrpcClient.Recognize, effectiveSettings.RecognizeSettings); _callLongRunningRecognize = clientHelper.BuildApiCall<LongRunningRecognizeRequest, Operation>( GrpcClient.LongRunningRecognizeAsync, GrpcClient.LongRunningRecognize, effectiveSettings.LongRunningRecognizeSettings); _callStreamingRecognize = clientHelper.BuildApiCall<StreamingRecognizeRequest, StreamingRecognizeResponse>( GrpcClient.StreamingRecognize, effectiveSettings.StreamingRecognizeSettings, effectiveSettings.StreamingRecognizeStreamingSettings); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void OnConstruction(Speech.SpeechClient grpcClient, SpeechSettings effectiveSettings, ClientHelper clientHelper); /// <summary> /// The underlying gRPC Speech client. /// </summary> public override Speech.SpeechClient GrpcClient { get; } // Partial modifier methods contain '_' to ensure no name conflicts with RPC methods. partial void Modify_RecognizeRequest(ref RecognizeRequest request, ref CallSettings settings); partial void Modify_LongRunningRecognizeRequest(ref LongRunningRecognizeRequest request, ref CallSettings settings); partial void Modify_StreamingRecognizeRequestCallSettings(ref CallSettings settings); partial void Modify_StreamingRecognizeRequestRequest(ref StreamingRecognizeRequest request); /// <summary> /// Performs synchronous speech recognition: receive results after all audio /// has been sent and processed. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task<RecognizeResponse> RecognizeAsync( RecognizeRequest request, CallSettings callSettings = null) { Modify_RecognizeRequest(ref request, ref callSettings); return _callRecognize.Async(request, callSettings); } /// <summary> /// Performs synchronous speech recognition: receive results after all audio /// has been sent and processed. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override RecognizeResponse Recognize( RecognizeRequest request, CallSettings callSettings = null) { Modify_RecognizeRequest(ref request, ref callSettings); return _callRecognize.Sync(request, callSettings); } /// <summary> /// Performs asynchronous speech recognition: receive results via the /// google.longrunning.Operations interface. Returns either an /// `Operation.error` or an `Operation.response` which contains /// a `LongRunningRecognizeResponse` message. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override async Task<Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata>> LongRunningRecognizeAsync( LongRunningRecognizeRequest request, CallSettings callSettings = null) { Modify_LongRunningRecognizeRequest(ref request, ref callSettings); return new Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata>( await _callLongRunningRecognize.Async(request, callSettings).ConfigureAwait(false), LongRunningRecognizeOperationsClient); } /// <summary> /// Performs asynchronous speech recognition: receive results via the /// google.longrunning.Operations interface. Returns either an /// `Operation.error` or an `Operation.response` which contains /// a `LongRunningRecognizeResponse` message. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata> LongRunningRecognize( LongRunningRecognizeRequest request, CallSettings callSettings = null) { Modify_LongRunningRecognizeRequest(ref request, ref callSettings); return new Operation<LongRunningRecognizeResponse, LongRunningRecognizeMetadata>( _callLongRunningRecognize.Sync(request, callSettings), LongRunningRecognizeOperationsClient); } /// <summary> /// The long-running operations client for <c>LongRunningRecognize</c>. /// </summary> public override OperationsClient LongRunningRecognizeOperationsClient { get; } /// <summary> /// Performs bidirectional streaming speech recognition: receive results while /// sending audio. This method is only available via the gRPC API (not REST). /// </summary> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <param name="streamingSettings"> /// If not null, applies streaming overrides to this RPC call. /// </param> /// <returns> /// The client-server stream. /// </returns> public override StreamingRecognizeStream StreamingRecognize( CallSettings callSettings = null, BidirectionalStreamingSettings streamingSettings = null) { Modify_StreamingRecognizeRequestCallSettings(ref callSettings); BidirectionalStreamingSettings effectiveStreamingSettings = streamingSettings ?? _callStreamingRecognize.StreamingSettings; AsyncDuplexStreamingCall<StreamingRecognizeRequest, StreamingRecognizeResponse> call = _callStreamingRecognize.Call(callSettings); BufferedClientStreamWriter<StreamingRecognizeRequest> writeBuffer = new BufferedClientStreamWriter<StreamingRecognizeRequest>( call.RequestStream, effectiveStreamingSettings.BufferedClientWriterCapacity); return new StreamingRecognizeStreamImpl(this, call, writeBuffer); } internal sealed partial class StreamingRecognizeStreamImpl : StreamingRecognizeStream { /// <summary> /// Construct the bidirectional streaming method for <c>StreamingRecognize</c>. /// </summary> /// <param name="service">The service containing this streaming method.</param> /// <param name="call">The underlying gRPC duplex streaming call.</param> /// <param name="writeBuffer">The <see cref="BufferedClientStreamWriter{StreamingRecognizeRequest}"/> /// instance associated with this streaming call.</param> public StreamingRecognizeStreamImpl( SpeechClientImpl service, AsyncDuplexStreamingCall<StreamingRecognizeRequest, StreamingRecognizeResponse> call, BufferedClientStreamWriter<StreamingRecognizeRequest> writeBuffer) { _service = service; GrpcCall = call; _writeBuffer = writeBuffer; } private SpeechClientImpl _service; private BufferedClientStreamWriter<StreamingRecognizeRequest> _writeBuffer; private StreamingRecognizeRequest ModifyRequest(StreamingRecognizeRequest request) { _service.Modify_StreamingRecognizeRequestRequest(ref request); return request; } /// <inheritdoc/> public override AsyncDuplexStreamingCall<StreamingRecognizeRequest, StreamingRecognizeResponse> GrpcCall { get; } /// <inheritdoc/> public override Task TryWriteAsync(StreamingRecognizeRequest message) => _writeBuffer.TryWriteAsync(ModifyRequest(message)); /// <inheritdoc/> public override Task WriteAsync(StreamingRecognizeRequest message) => _writeBuffer.WriteAsync(ModifyRequest(message)); /// <inheritdoc/> public override Task TryWriteAsync(StreamingRecognizeRequest message, WriteOptions options) => _writeBuffer.TryWriteAsync(ModifyRequest(message), options); /// <inheritdoc/> public override Task WriteAsync(StreamingRecognizeRequest message, WriteOptions options) => _writeBuffer.WriteAsync(ModifyRequest(message), options); /// <inheritdoc/> public override Task TryWriteCompleteAsync() => _writeBuffer.TryWriteCompleteAsync(); /// <inheritdoc/> public override Task WriteCompleteAsync() => _writeBuffer.WriteCompleteAsync(); /// <inheritdoc/> public override IAsyncEnumerator<StreamingRecognizeResponse> ResponseStream => GrpcCall.ResponseStream; } } // Partial classes to enable page-streaming // Partial Grpc class to enable LRO client creation public static partial class Speech { public partial class SpeechClient { /// <summary> /// Creates a new instance of <see cref="Operations.OperationsClient"/> using the same call invoker as this client. /// </summary> /// <returns>A new Operations client for the same target as this client.</returns> public virtual Operations.OperationsClient CreateOperationsClient() => new Operations.OperationsClient(CallInvoker); } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the elastictranscoder-2012-09-25.normal.json service model. */ using System; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.ElasticTranscoder.Model; using Amazon.ElasticTranscoder.Model.Internal.MarshallTransformations; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Auth; using Amazon.Runtime.Internal.Transform; namespace Amazon.ElasticTranscoder { /// <summary> /// Implementation for accessing ElasticTranscoder /// /// AWS Elastic Transcoder Service /// <para> /// The AWS Elastic Transcoder Service. /// </para> /// </summary> public partial class AmazonElasticTranscoderClient : AmazonServiceClient, IAmazonElasticTranscoder { #region Constructors /// <summary> /// Constructs AmazonElasticTranscoderClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> public AmazonElasticTranscoderClient(AWSCredentials credentials) : this(credentials, new AmazonElasticTranscoderConfig()) { } /// <summary> /// Constructs AmazonElasticTranscoderClient with AWS Credentials /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="region">The region to connect.</param> public AmazonElasticTranscoderClient(AWSCredentials credentials, RegionEndpoint region) : this(credentials, new AmazonElasticTranscoderConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonElasticTranscoderClient with AWS Credentials and an /// AmazonElasticTranscoderClient Configuration object. /// </summary> /// <param name="credentials">AWS Credentials</param> /// <param name="clientConfig">The AmazonElasticTranscoderClient Configuration Object</param> public AmazonElasticTranscoderClient(AWSCredentials credentials, AmazonElasticTranscoderConfig clientConfig) : base(credentials, clientConfig) { } /// <summary> /// Constructs AmazonElasticTranscoderClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> public AmazonElasticTranscoderClient(string awsAccessKeyId, string awsSecretAccessKey) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonElasticTranscoderConfig()) { } /// <summary> /// Constructs AmazonElasticTranscoderClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="region">The region to connect.</param> public AmazonElasticTranscoderClient(string awsAccessKeyId, string awsSecretAccessKey, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, new AmazonElasticTranscoderConfig() {RegionEndpoint=region}) { } /// <summary> /// Constructs AmazonElasticTranscoderClient with AWS Access Key ID, AWS Secret Key and an /// AmazonElasticTranscoderClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="clientConfig">The AmazonElasticTranscoderClient Configuration Object</param> public AmazonElasticTranscoderClient(string awsAccessKeyId, string awsSecretAccessKey, AmazonElasticTranscoderConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, clientConfig) { } /// <summary> /// Constructs AmazonElasticTranscoderClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> public AmazonElasticTranscoderClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonElasticTranscoderConfig()) { } /// <summary> /// Constructs AmazonElasticTranscoderClient with AWS Access Key ID and AWS Secret Key /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="region">The region to connect.</param> public AmazonElasticTranscoderClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, RegionEndpoint region) : this(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, new AmazonElasticTranscoderConfig{RegionEndpoint = region}) { } /// <summary> /// Constructs AmazonElasticTranscoderClient with AWS Access Key ID, AWS Secret Key and an /// AmazonElasticTranscoderClient Configuration object. /// </summary> /// <param name="awsAccessKeyId">AWS Access Key ID</param> /// <param name="awsSecretAccessKey">AWS Secret Access Key</param> /// <param name="awsSessionToken">AWS Session Token</param> /// <param name="clientConfig">The AmazonElasticTranscoderClient Configuration Object</param> public AmazonElasticTranscoderClient(string awsAccessKeyId, string awsSecretAccessKey, string awsSessionToken, AmazonElasticTranscoderConfig clientConfig) : base(awsAccessKeyId, awsSecretAccessKey, awsSessionToken, clientConfig) { } #endregion #region Overrides /// <summary> /// Creates the signer for the service. /// </summary> protected override AbstractAWSSigner CreateSigner() { return new AWS4Signer(); } #endregion #region Dispose /// <summary> /// Disposes the service client. /// </summary> protected override void Dispose(bool disposing) { base.Dispose(disposing); } #endregion #region CancelJob internal CancelJobResponse CancelJob(CancelJobRequest request) { var marshaller = new CancelJobRequestMarshaller(); var unmarshaller = CancelJobResponseUnmarshaller.Instance; return Invoke<CancelJobRequest,CancelJobResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CancelJob operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CancelJob operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<CancelJobResponse> CancelJobAsync(CancelJobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CancelJobRequestMarshaller(); var unmarshaller = CancelJobResponseUnmarshaller.Instance; return InvokeAsync<CancelJobRequest,CancelJobResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreateJob internal CreateJobResponse CreateJob(CreateJobRequest request) { var marshaller = new CreateJobRequestMarshaller(); var unmarshaller = CreateJobResponseUnmarshaller.Instance; return Invoke<CreateJobRequest,CreateJobResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreateJob operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateJob operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<CreateJobResponse> CreateJobAsync(CreateJobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreateJobRequestMarshaller(); var unmarshaller = CreateJobResponseUnmarshaller.Instance; return InvokeAsync<CreateJobRequest,CreateJobResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreatePipeline internal CreatePipelineResponse CreatePipeline(CreatePipelineRequest request) { var marshaller = new CreatePipelineRequestMarshaller(); var unmarshaller = CreatePipelineResponseUnmarshaller.Instance; return Invoke<CreatePipelineRequest,CreatePipelineResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreatePipeline operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreatePipeline operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<CreatePipelineResponse> CreatePipelineAsync(CreatePipelineRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreatePipelineRequestMarshaller(); var unmarshaller = CreatePipelineResponseUnmarshaller.Instance; return InvokeAsync<CreatePipelineRequest,CreatePipelineResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region CreatePreset internal CreatePresetResponse CreatePreset(CreatePresetRequest request) { var marshaller = new CreatePresetRequestMarshaller(); var unmarshaller = CreatePresetResponseUnmarshaller.Instance; return Invoke<CreatePresetRequest,CreatePresetResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the CreatePreset operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreatePreset operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<CreatePresetResponse> CreatePresetAsync(CreatePresetRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new CreatePresetRequestMarshaller(); var unmarshaller = CreatePresetResponseUnmarshaller.Instance; return InvokeAsync<CreatePresetRequest,CreatePresetResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeletePipeline internal DeletePipelineResponse DeletePipeline(DeletePipelineRequest request) { var marshaller = new DeletePipelineRequestMarshaller(); var unmarshaller = DeletePipelineResponseUnmarshaller.Instance; return Invoke<DeletePipelineRequest,DeletePipelineResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeletePipeline operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeletePipeline operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DeletePipelineResponse> DeletePipelineAsync(DeletePipelineRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeletePipelineRequestMarshaller(); var unmarshaller = DeletePipelineResponseUnmarshaller.Instance; return InvokeAsync<DeletePipelineRequest,DeletePipelineResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region DeletePreset internal DeletePresetResponse DeletePreset(DeletePresetRequest request) { var marshaller = new DeletePresetRequestMarshaller(); var unmarshaller = DeletePresetResponseUnmarshaller.Instance; return Invoke<DeletePresetRequest,DeletePresetResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the DeletePreset operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeletePreset operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<DeletePresetResponse> DeletePresetAsync(DeletePresetRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DeletePresetRequestMarshaller(); var unmarshaller = DeletePresetResponseUnmarshaller.Instance; return InvokeAsync<DeletePresetRequest,DeletePresetResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListJobsByPipeline internal ListJobsByPipelineResponse ListJobsByPipeline(ListJobsByPipelineRequest request) { var marshaller = new ListJobsByPipelineRequestMarshaller(); var unmarshaller = ListJobsByPipelineResponseUnmarshaller.Instance; return Invoke<ListJobsByPipelineRequest,ListJobsByPipelineResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ListJobsByPipeline operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListJobsByPipeline operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ListJobsByPipelineResponse> ListJobsByPipelineAsync(ListJobsByPipelineRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListJobsByPipelineRequestMarshaller(); var unmarshaller = ListJobsByPipelineResponseUnmarshaller.Instance; return InvokeAsync<ListJobsByPipelineRequest,ListJobsByPipelineResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListJobsByStatus internal ListJobsByStatusResponse ListJobsByStatus(ListJobsByStatusRequest request) { var marshaller = new ListJobsByStatusRequestMarshaller(); var unmarshaller = ListJobsByStatusResponseUnmarshaller.Instance; return Invoke<ListJobsByStatusRequest,ListJobsByStatusResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ListJobsByStatus operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListJobsByStatus operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ListJobsByStatusResponse> ListJobsByStatusAsync(ListJobsByStatusRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListJobsByStatusRequestMarshaller(); var unmarshaller = ListJobsByStatusResponseUnmarshaller.Instance; return InvokeAsync<ListJobsByStatusRequest,ListJobsByStatusResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListPipelines internal ListPipelinesResponse ListPipelines() { return ListPipelines(new ListPipelinesRequest()); } internal ListPipelinesResponse ListPipelines(ListPipelinesRequest request) { var marshaller = new ListPipelinesRequestMarshaller(); var unmarshaller = ListPipelinesResponseUnmarshaller.Instance; return Invoke<ListPipelinesRequest,ListPipelinesResponse>(request, marshaller, unmarshaller); } /// <summary> /// The ListPipelines operation gets a list of the pipelines associated with the current /// AWS account. /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListPipelines service method, as returned by ElasticTranscoder.</returns> /// <exception cref="Amazon.ElasticTranscoder.Model.AccessDeniedException"> /// General authentication failure. The request was not signed correctly. /// </exception> /// <exception cref="Amazon.ElasticTranscoder.Model.IncompatibleVersionException"> /// /// </exception> /// <exception cref="Amazon.ElasticTranscoder.Model.InternalServiceException"> /// Elastic Transcoder encountered an unexpected exception while trying to fulfill the /// request. /// </exception> /// <exception cref="Amazon.ElasticTranscoder.Model.ValidationException"> /// One or more required parameter values were not provided in the request. /// </exception> public Task<ListPipelinesResponse> ListPipelinesAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { return ListPipelinesAsync(new ListPipelinesRequest(), cancellationToken); } /// <summary> /// Initiates the asynchronous execution of the ListPipelines operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListPipelines operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ListPipelinesResponse> ListPipelinesAsync(ListPipelinesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListPipelinesRequestMarshaller(); var unmarshaller = ListPipelinesResponseUnmarshaller.Instance; return InvokeAsync<ListPipelinesRequest,ListPipelinesResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ListPresets internal ListPresetsResponse ListPresets() { return ListPresets(new ListPresetsRequest()); } internal ListPresetsResponse ListPresets(ListPresetsRequest request) { var marshaller = new ListPresetsRequestMarshaller(); var unmarshaller = ListPresetsResponseUnmarshaller.Instance; return Invoke<ListPresetsRequest,ListPresetsResponse>(request, marshaller, unmarshaller); } /// <summary> /// The ListPresets operation gets a list of the default presets included with Elastic /// Transcoder and the presets that you've added in an AWS region. /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListPresets service method, as returned by ElasticTranscoder.</returns> /// <exception cref="Amazon.ElasticTranscoder.Model.AccessDeniedException"> /// General authentication failure. The request was not signed correctly. /// </exception> /// <exception cref="Amazon.ElasticTranscoder.Model.IncompatibleVersionException"> /// /// </exception> /// <exception cref="Amazon.ElasticTranscoder.Model.InternalServiceException"> /// Elastic Transcoder encountered an unexpected exception while trying to fulfill the /// request. /// </exception> /// <exception cref="Amazon.ElasticTranscoder.Model.ValidationException"> /// One or more required parameter values were not provided in the request. /// </exception> public Task<ListPresetsResponse> ListPresetsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { return ListPresetsAsync(new ListPresetsRequest(), cancellationToken); } /// <summary> /// Initiates the asynchronous execution of the ListPresets operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListPresets operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ListPresetsResponse> ListPresetsAsync(ListPresetsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ListPresetsRequestMarshaller(); var unmarshaller = ListPresetsResponseUnmarshaller.Instance; return InvokeAsync<ListPresetsRequest,ListPresetsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ReadJob internal ReadJobResponse ReadJob(ReadJobRequest request) { var marshaller = new ReadJobRequestMarshaller(); var unmarshaller = ReadJobResponseUnmarshaller.Instance; return Invoke<ReadJobRequest,ReadJobResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ReadJob operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ReadJob operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ReadJobResponse> ReadJobAsync(ReadJobRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ReadJobRequestMarshaller(); var unmarshaller = ReadJobResponseUnmarshaller.Instance; return InvokeAsync<ReadJobRequest,ReadJobResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ReadPipeline internal ReadPipelineResponse ReadPipeline(ReadPipelineRequest request) { var marshaller = new ReadPipelineRequestMarshaller(); var unmarshaller = ReadPipelineResponseUnmarshaller.Instance; return Invoke<ReadPipelineRequest,ReadPipelineResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ReadPipeline operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ReadPipeline operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ReadPipelineResponse> ReadPipelineAsync(ReadPipelineRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ReadPipelineRequestMarshaller(); var unmarshaller = ReadPipelineResponseUnmarshaller.Instance; return InvokeAsync<ReadPipelineRequest,ReadPipelineResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region ReadPreset internal ReadPresetResponse ReadPreset(ReadPresetRequest request) { var marshaller = new ReadPresetRequestMarshaller(); var unmarshaller = ReadPresetResponseUnmarshaller.Instance; return Invoke<ReadPresetRequest,ReadPresetResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the ReadPreset operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ReadPreset operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<ReadPresetResponse> ReadPresetAsync(ReadPresetRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new ReadPresetRequestMarshaller(); var unmarshaller = ReadPresetResponseUnmarshaller.Instance; return InvokeAsync<ReadPresetRequest,ReadPresetResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region TestRole internal TestRoleResponse TestRole(TestRoleRequest request) { var marshaller = new TestRoleRequestMarshaller(); var unmarshaller = TestRoleResponseUnmarshaller.Instance; return Invoke<TestRoleRequest,TestRoleResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the TestRole operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the TestRole operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<TestRoleResponse> TestRoleAsync(TestRoleRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new TestRoleRequestMarshaller(); var unmarshaller = TestRoleResponseUnmarshaller.Instance; return InvokeAsync<TestRoleRequest,TestRoleResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region UpdatePipeline internal UpdatePipelineResponse UpdatePipeline(UpdatePipelineRequest request) { var marshaller = new UpdatePipelineRequestMarshaller(); var unmarshaller = UpdatePipelineResponseUnmarshaller.Instance; return Invoke<UpdatePipelineRequest,UpdatePipelineResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the UpdatePipeline operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdatePipeline operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<UpdatePipelineResponse> UpdatePipelineAsync(UpdatePipelineRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new UpdatePipelineRequestMarshaller(); var unmarshaller = UpdatePipelineResponseUnmarshaller.Instance; return InvokeAsync<UpdatePipelineRequest,UpdatePipelineResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region UpdatePipelineNotifications internal UpdatePipelineNotificationsResponse UpdatePipelineNotifications(UpdatePipelineNotificationsRequest request) { var marshaller = new UpdatePipelineNotificationsRequestMarshaller(); var unmarshaller = UpdatePipelineNotificationsResponseUnmarshaller.Instance; return Invoke<UpdatePipelineNotificationsRequest,UpdatePipelineNotificationsResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the UpdatePipelineNotifications operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdatePipelineNotifications operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<UpdatePipelineNotificationsResponse> UpdatePipelineNotificationsAsync(UpdatePipelineNotificationsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new UpdatePipelineNotificationsRequestMarshaller(); var unmarshaller = UpdatePipelineNotificationsResponseUnmarshaller.Instance; return InvokeAsync<UpdatePipelineNotificationsRequest,UpdatePipelineNotificationsResponse>(request, marshaller, unmarshaller, cancellationToken); } #endregion #region UpdatePipelineStatus internal UpdatePipelineStatusResponse UpdatePipelineStatus(UpdatePipelineStatusRequest request) { var marshaller = new UpdatePipelineStatusRequestMarshaller(); var unmarshaller = UpdatePipelineStatusResponseUnmarshaller.Instance; return Invoke<UpdatePipelineStatusRequest,UpdatePipelineStatusResponse>(request, marshaller, unmarshaller); } /// <summary> /// Initiates the asynchronous execution of the UpdatePipelineStatus operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdatePipelineStatus operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> public Task<UpdatePipelineStatusResponse> UpdatePipelineStatusAsync(UpdatePipelineStatusRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new UpdatePipelineStatusRequestMarshaller(); var unmarshaller = UpdatePipelineStatusResponseUnmarshaller.Instance; return InvokeAsync<UpdatePipelineStatusRequest,UpdatePipelineStatusResponse>(request, marshaller, unmarshaller, cancellationToken); } #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: A wrapper class for the primitive type float. ** ** ===========================================================*/ using System.Globalization; using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Diagnostics.Contracts; namespace System { [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] [System.Runtime.InteropServices.ComVisible(true)] public struct Single : IComparable, IFormattable, IComparable<Single>, IEquatable<Single>, IConvertible { internal float m_value; // // Public constants // public const float MinValue = (float)-3.40282346638528859e+38; public const float Epsilon = (float)1.4e-45; public const float MaxValue = (float)3.40282346638528859e+38; public const float PositiveInfinity = (float)1.0 / (float)0.0; public const float NegativeInfinity = (float)-1.0 / (float)0.0; public const float NaN = (float)0.0 / (float)0.0; [Pure] public unsafe static bool IsInfinity(float f) { return (*(int*)(&f) & 0x7FFFFFFF) == 0x7F800000; } [Pure] public unsafe static bool IsPositiveInfinity(float f) { return *(int*)(&f) == 0x7F800000; } [Pure] public unsafe static bool IsNegativeInfinity(float f) { return *(int*)(&f) == unchecked((int)0xFF800000); } [Pure] public unsafe static bool IsNaN(float f) { return (*(int*)(&f) & 0x7FFFFFFF) > 0x7F800000; } // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type Single, this method throws an ArgumentException. // int IComparable.CompareTo(Object value) { if (value == null) { return 1; } if (value is Single) { float f = (float)value; if (m_value < f) return -1; if (m_value > f) return 1; if (m_value == f) return 0; // At least one of the values is NaN. if (IsNaN(m_value)) return (IsNaN(f) ? 0 : -1); else // f is NaN. return 1; } throw new ArgumentException(SR.Arg_MustBeSingle); } public int CompareTo(Single value) { if (m_value < value) return -1; if (m_value > value) return 1; if (m_value == value) return 0; // At least one of the values is NaN. if (IsNaN(m_value)) return (IsNaN(value) ? 0 : -1); else // f is NaN. return 1; } public static bool operator ==(Single left, Single right) { return left == right; } public static bool operator !=(Single left, Single right) { return left != right; } public static bool operator <(Single left, Single right) { return left < right; } public static bool operator >(Single left, Single right) { return left > right; } public static bool operator <=(Single left, Single right) { return left <= right; } public static bool operator >=(Single left, Single right) { return left >= right; } public override bool Equals(Object obj) { if (!(obj is Single)) { return false; } float temp = ((Single)obj).m_value; if (temp == m_value) { return true; } return IsNaN(temp) && IsNaN(m_value); } public bool Equals(Single obj) { if (obj == m_value) { return true; } return IsNaN(obj) && IsNaN(m_value); } public unsafe override int GetHashCode() { float f = m_value; if (f == 0) { // Ensure that 0 and -0 have the same hash code return 0; } int v = *(int*)(&f); return v; } public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatSingle(m_value, null, null); } public String ToString(IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatSingle(m_value, null, provider); } public String ToString(String format) { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatSingle(m_value, format, null); } public String ToString(String format, IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatSingle(m_value, format, provider); } // Parses a float from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. // // This method will not throw an OverflowException, but will return // PositiveInfinity or NegativeInfinity for a number that is too // large or too small. // public static float Parse(String s) { return Parse(s, NumberStyles.Float | NumberStyles.AllowThousands, null); } public static float Parse(String s, NumberStyles style) { Decimal.ValidateParseStyleFloatingPoint(style); return Parse(s, style, null); } public static float Parse(String s, IFormatProvider provider) { return Parse(s, NumberStyles.Float | NumberStyles.AllowThousands, provider); } public static float Parse(String s, NumberStyles style, IFormatProvider provider) { Decimal.ValidateParseStyleFloatingPoint(style); return FormatProvider.ParseSingle(s, style, provider); } public static Boolean TryParse(String s, out Single result) { return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, null, out result); } public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out Single result) { Decimal.ValidateParseStyleFloatingPoint(style); if (s == null) { result = 0; return false; } bool success = FormatProvider.TryParseSingle(s, style, provider, out result); if (!success) { String sTrim = s.Trim(); if (FormatProvider.IsPositiveInfinity(sTrim, provider)) { result = PositiveInfinity; } else if (FormatProvider.IsNegativeInfinity(sTrim, provider)) { result = NegativeInfinity; } else if (FormatProvider.IsNaNSymbol(sTrim, provider)) { result = NaN; } else return false; // We really failed } return true; } // // IConvertible implementation // TypeCode IConvertible.GetTypeCode() { return TypeCode.Single; } /// <internalonly/> bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(m_value); } /// <internalonly/> char IConvertible.ToChar(IFormatProvider provider) { throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Single", "Char")); } /// <internalonly/> sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } /// <internalonly/> byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } /// <internalonly/> short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } /// <internalonly/> ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } /// <internalonly/> int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } /// <internalonly/> uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } /// <internalonly/> long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } /// <internalonly/> ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } /// <internalonly/> float IConvertible.ToSingle(IFormatProvider provider) { return m_value; } /// <internalonly/> double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } /// <internalonly/> Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } /// <internalonly/> DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Single", "DateTime")); } /// <internalonly/> Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
// // ImageLoaderThread.cs // // Author: // Ruben Vermeersch <ruben@savanne.be> // Larry Ewing <lewing@novell.com> // Ettore Perazzoli <ettore@src.gnome.org> // // Copyright (C) 2003-2010 Novell, Inc. // Copyright (C) 2009-2010 Ruben Vermeersch // Copyright (C) 2003-2006 Larry Ewing // Copyright (C) 2003 Ettore Perazzoli // // 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 Gdk; using Gtk; using System.Collections; using System.Collections.Generic; using System.Threading; using System; using Hyena; using FSpot.Utils; using FSpot.Imaging; public class ImageLoaderThread { // Types. public class RequestItem { /// <summary> /// Gets or Sets image uri /// </summary> /// <value> /// Image Uri /// </value> public SafeUri Uri { get; set; } /* Order value; requests with a lower value get performed first. */ public int Order { get; set; } /* The pixbuf obtained from the operation. */ private Pixbuf result; public Pixbuf Result { get { if (result == null) { return null; } return result.ShallowCopy (); } set { result = value; } } /* the maximium size both must be greater than zero if either is */ public int Width { get; set; } public int Height { get; set; } public RequestItem (SafeUri uri, int order, int width, int height) { this.Uri = uri; this.Order = order; this.Width = width; this.Height = height; if ((width <= 0 && height > 0) || (height <= 0 && width > 0)) { throw new System.Exception ("Invalid arguments"); } } ~RequestItem () { if (result != null) { result.Dispose (); } result = null; } } #region Private members. static List<ImageLoaderThread> instances = new List<ImageLoaderThread> (); /* The thread used to handle the requests. */ private Thread worker_thread; /* The request queue; it's shared between the threads so it needs to be locked prior to access. */ private List<RequestItem> queue; /* A dict of all the requests; note that the current request isn't in the dict. */ Dictionary<SafeUri, RequestItem> requests_by_uri; /* Current request. Request currently being handled by the auxiliary thread. Should be modified only by the auxiliary thread (the GTK thread can only read it). */ private RequestItem current_request; /* The queue of processed requests. */ private Queue processed_requests; /* This is used by the helper thread to notify the main GLib thread that there are pending items in the `processed_requests' queue. */ ThreadNotify pending_notify; /* Whether a notification is pending on `pending_notify' already or not. */ private bool pending_notify_notified; volatile bool should_cancel = false; #endregion #region Public API public delegate void PixbufLoadedHandler (ImageLoaderThread loader,RequestItem result); public event PixbufLoadedHandler OnPixbufLoaded; public ImageLoaderThread () { queue = new List<RequestItem> (); requests_by_uri = new Dictionary<SafeUri, RequestItem> (); // requests_by_path = Hashtable.Synchronized (new Hashtable ()); processed_requests = new Queue (); pending_notify = new ThreadNotify (new Gtk.ReadyEvent (HandleProcessedRequests)); instances.Add (this); } void StartWorker () { if (worker_thread != null) { return; } should_cancel = false; worker_thread = new Thread (new ThreadStart (WorkerThread)); worker_thread.Start (); } int block_count; public void PushBlock () { System.Threading.Interlocked.Increment (ref block_count); } public void PopBlock () { if (System.Threading.Interlocked.Decrement (ref block_count) == 0) { lock (queue) { Monitor.Pulse (queue); } } } public void Cleanup () { should_cancel = true; if (worker_thread != null) { lock (queue) { Monitor.Pulse (queue); } worker_thread.Join (); } worker_thread = null; } public static void CleanAll () { foreach (var thread in instances) { thread.Cleanup (); } } public void Request (SafeUri uri, int order) { Request (uri, order, 0, 0); } public virtual void Request (SafeUri uri, int order, int width, int height) { lock (queue) { if (InsertRequest (uri, order, width, height)) { Monitor.Pulse (queue); } } } public void Cancel (SafeUri uri) { lock (queue) { RequestItem r = requests_by_uri [uri]; if (r != null) { requests_by_uri.Remove (uri); queue.Remove (r); } } } #endregion #region Private utility methods. protected virtual void ProcessRequest (RequestItem request) { Pixbuf orig_image; try { using (var img = ImageFile.Create (request.Uri)) { if (request.Width > 0) { orig_image = img.Load (request.Width, request.Height); } else { orig_image = img.Load (); } } } catch (GLib.GException e) { Log.Exception (e); return; } if (orig_image == null) { return; } request.Result = orig_image; } /* Insert the request in the queue, return TRUE if the queue actually grew. NOTE: Lock the queue before calling. */ private bool InsertRequest (SafeUri uri, int order, int width, int height) { StartWorker (); /* Check if this is the same as the request currently being processed. */ lock (processed_requests) { if (current_request != null && current_request.Uri == uri) { return false; } } /* Check if a request for this path has already been queued. */ RequestItem existing_request; if (requests_by_uri.TryGetValue (uri, out existing_request)) { /* FIXME: At least for now, this shouldn't happen. */ if (existing_request.Order != order) { Log.WarningFormat ("BUG: Filing another request of order {0} (previously {1}) for `{2}'", order, existing_request.Order, uri); } queue.Remove (existing_request); queue.Add (existing_request); return false; } /* New request, just put it on the queue with the right order. */ RequestItem new_request = new RequestItem (uri, order, width, height); queue.Add (new_request); lock (queue) { requests_by_uri.Add (uri, new_request); } return true; } /* The worker thread's main function. */ private void WorkerThread () { Log.Debug (this.ToString (), "Worker starting"); try { while (!should_cancel) { lock (processed_requests) { if (current_request != null) { processed_requests.Enqueue (current_request); if (! pending_notify_notified) { pending_notify.WakeupMain (); pending_notify_notified = true; } current_request = null; } } lock (queue) { while ((queue.Count == 0 || block_count > 0) && !should_cancel) { Monitor.Wait (queue); } if (should_cancel) { return; } int pos = queue.Count - 1; current_request = queue [pos]; queue.RemoveAt (pos); requests_by_uri.Remove (current_request.Uri); } ProcessRequest (current_request); } } catch (ThreadAbortException) { //Aborting } } protected virtual void EmitLoaded (Queue results) { if (OnPixbufLoaded != null) { foreach (RequestItem r in results) { OnPixbufLoaded (this, r); } } } private void HandleProcessedRequests () { Queue results; lock (processed_requests) { /* Copy the queued items out of the shared queue so we hold the lock for as little time as possible. */ results = processed_requests.Clone () as Queue; processed_requests.Clear (); pending_notify_notified = false; } EmitLoaded (results); } #endregion }
/*************************************************************************** * Preferences.cs * * Copyright (C) 2008 Novell, Inc. * Written by: * Calvin Gaisford <calvinrg@gmail.com> * Boyd Timothy <btimothy@gmail.com> ****************************************************************************/ /* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: * * 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.Xml; using System.IO; namespace Tasque { // <summary> // Class used to store Tasque preferences // </summary> public class Preferences { private System.Xml.XmlDocument document; private string location; public const string AuthTokenKey = "AuthToken"; public const string CurrentBackend = "CurrentBackend"; public const string InactivateTimeoutKey = "InactivateTimeout"; public const string SelectedCategoryKey = "SelectedCategory"; public const string ParseDateEnabledKey = "ParseDateEnabled"; public const string TodayTaskTextColor = "TodayTaskTextColor"; public const string OverdueTaskTextColor = "OverdueTaskTextColor"; /// <summary> /// A list of category names to show in the TaskWindow when the "All" /// category is selected. /// </summary> public const string HideInAllCategory = "HideInAllCategory"; public const string ShowCompletedTasksKey = "ShowCompletedTasks"; public const string UserNameKey = "UserName"; public const string UserIdKey = "UserID"; /// <summary> /// This setting allows a user to specify how many completed tasks to /// show in the Completed Tasks Category. The setting should be one of: /// "Yesterday", "Last7Days", "LastMonth", "LastYear", or "All". /// </summary> /// <param name="settingKey"> /// A <see cref="System.String"/> /// </param> /// <returns> /// A <see cref="System.String"/> /// </returns> public const string CompletedTasksRange = "CompletedTasksRange"; public delegate void SettingChangedHandler (Preferences preferences, string settingKey); public event SettingChangedHandler SettingChanged; public string Get (string settingKey) { if (settingKey == null || settingKey.Trim () == string.Empty) throw new ArgumentNullException ("settingKey", "Preferences.Get() called with a null/empty settingKey"); string xPath = string.Format ("//{0}", settingKey.Trim ()); XmlNode node = document.SelectSingleNode (xPath); if (node == null || !(node is XmlElement)) return SetDefault (settingKey); XmlElement element = node as XmlElement; if( (element == null) || (element.InnerText.Length < 1) ) return SetDefault (settingKey); else return element.InnerText; } private string SetDefault (string settingKey) { string val = GetDefault (settingKey); if (val != null) Set (settingKey, val); return val; } private string GetDefault (string settingKey) { switch (settingKey) { case ParseDateEnabledKey: return true.ToString (); case TodayTaskTextColor: return "#181AB7"; case OverdueTaskTextColor: return "#EB3320"; default: return null; } } public void Set (string settingKey, string settingValue) { if (settingKey == null || settingKey.Trim () == string.Empty) throw new ArgumentNullException ("settingKey", "Preferences.Set() called with a null/empty settingKey"); string xPath = string.Format ("//{0}", settingKey.Trim ()); XmlNode node = document.SelectSingleNode (xPath); XmlElement element = null; if (node != null && node is XmlElement) element = node as XmlElement; if (element == null) { element = document.CreateElement(settingKey); document.DocumentElement.AppendChild (element); } if (settingValue == null) element.InnerText = string.Empty; else element.InnerText = settingValue; SavePrefs(); NotifyHandlersOfSettingChange (settingKey.Trim ()); } public int GetInt (string settingKey) { string val = Get (settingKey); if (val == null) return -1; return int.Parse (val); } public void SetInt (string settingKey, int settingValue) { Set (settingKey, string.Format ("{0}", settingValue)); } public bool GetBool (string settingKey) { string val = Get (settingKey); if (val == null) return false; return bool.Parse (val); } public void SetBool (string settingKey, bool settingValue) { Set (settingKey, settingValue.ToString ()); } public List<string> GetStringList (string settingKey) { if (settingKey == null || settingKey.Trim () == string.Empty) throw new ArgumentNullException ("settingKey", "Preferences.GetStringList() called with a null/empty settingKey"); List<string> stringList = new List<string> (); // Select all nodes whose parent is the settingKey string xPath = string.Format ("//{0}/*", settingKey.Trim ()); XmlNodeList list = document.SelectNodes (xPath); if (list == null) return stringList; foreach (XmlNode node in list) { if (node.InnerText != null && node.InnerText.Length > 0) stringList.Add (node.InnerText); } return stringList; } public void SetStringList (string settingKey, List<string> stringList) { if (settingKey == null || settingKey.Trim () == string.Empty) throw new ArgumentNullException ("settingKey", "Preferences.SetStringList() called with null/empty settingKey"); // Assume that the caller meant to null out an existing list if (stringList == null) stringList = new List<string> (); // Select the specific node string xPath = string.Format ("//{0}", settingKey.Trim ()); XmlNode node = document.SelectSingleNode (xPath); XmlElement element = null; if (node != null && node is XmlElement) { element = node as XmlElement; // Clear out any old children if (element.HasChildNodes) { element.RemoveAll (); } } if (element == null) { element = document.CreateElement(settingKey); document.DocumentElement.AppendChild (element); } foreach (string listItem in stringList) { XmlElement child = document.CreateElement ("list-item"); child.InnerText = listItem; element.AppendChild (child); } SavePrefs(); NotifyHandlersOfSettingChange (settingKey.Trim ()); } public Preferences (string confDir) { document = new XmlDocument(); location = Path.Combine (confDir, "preferences"); if(!File.Exists(location)) { CreateDefaultPrefs(); } else { try { document.Load(location); } catch { CreateDefaultPrefs (); document.Load (location); } } ValidatePrefs (); } /// <summary> /// Validate existing preferences just in case we're running on a /// machine that already has an existing file without having the /// settings specified here. /// </summary> private void ValidatePrefs () { if (GetInt (Preferences.InactivateTimeoutKey) <= 0) SetInt (Preferences.InactivateTimeoutKey, 5); } private void SavePrefs() { XmlTextWriter writer = new XmlTextWriter(location, System.Text.Encoding.UTF8); writer.Formatting = Formatting.Indented; document.WriteTo( writer ); writer.Flush(); writer.Close(); } private void CreateDefaultPrefs() { try { Directory.CreateDirectory(Path.GetDirectoryName(location)); document.LoadXml( "<tasqueprefs></tasqueprefs>"); SavePrefs(); /* // Create a new element node. XmlNode newElem = doc.CreateNode("element", "pages", ""); newElem.InnerText = "290"; Console.WriteLine("Add the new element to the document..."); XmlElement root = doc.DocumentElement; root.AppendChild(newElem); Console.WriteLine("Display the modified XML document..."); Console.WriteLine(doc.OuterXml); */ } catch (Exception e) { Logger.Debug("Exception thrown in Preferences {0}", e); return; } } /// <summary> /// Notify all SettingChanged event handlers that the specified /// setting has changed. /// </summary> /// <param name="settingKey"> /// A <see cref="System.String"/>. The setting that changed. /// </param> private void NotifyHandlersOfSettingChange (string settingKey) { // Notify SettingChanged handlers of the change if (SettingChanged != null) { try { SettingChanged (this, settingKey); } catch (Exception e) { Logger.Warn ("Exception calling SettingChangedHandlers for setting '{0}': {1}", settingKey, e.Message); } } } } }
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using System.Drawing; using OpenQA.Selenium.Interactions; namespace OpenQA.Selenium { [TestFixture] public class RenderedWebElementTest : DriverTestFixture { [Test] [Category("Javascript")] public void ShouldPickUpStyleOfAnElement() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("green-parent")); string backgroundColour = element.GetCssValue("background-color"); Assert.That(backgroundColour, Is.EqualTo("#008000").Or.EqualTo("rgba(0, 128, 0, 1)")); element = driver.FindElement(By.Id("red-item")); backgroundColour = element.GetCssValue("background-color"); Assert.That(backgroundColour, Is.EqualTo("#ff0000").Or.EqualTo("rgba(255, 0, 0, 1)")); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.Chrome, "WebKit bug 28804")] [IgnoreBrowser(Browser.PhantomJS, "WebKit bug 28804")] [IgnoreBrowser(Browser.IE, "Position and size are always integer in IE")] public void ShouldHandleNonIntegerPositionAndSize() { driver.Url = rectanglesPage; IWebElement r2 = driver.FindElement(By.Id("r2")); string left = r2.GetCssValue("left"); Assert.IsTrue(left.StartsWith("10.9"), "left (\"" + left + "\") should start with \"10.9\"."); string top = r2.GetCssValue("top"); Assert.IsTrue(top.StartsWith("10.1"), "top (\"" + top + "\") should start with \"10.1\"."); Assert.AreEqual(new Point(11, 10), r2.Location); string width = r2.GetCssValue("width"); Assert.IsTrue(width.StartsWith("48.6"), "width (\"" + left + "\") should start with \"48.6\"."); string height = r2.GetCssValue("height"); Assert.IsTrue(height.StartsWith("49.3"), "height (\"" + left + "\") should start with \"49.3\"."); Assert.AreEqual(r2.Size, new Size(49, 49)); } [Test] [Category("Javascript")] public void ShouldAllowInheritedStylesToBeUsed() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("green-item")); string backgroundColour = element.GetCssValue("background-color"); Assert.That(backgroundColour, Is.EqualTo("transparent").Or.EqualTo("rgba(0, 0, 0, 0)")); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.IPhone)] [IgnoreBrowser(Browser.HtmlUnit)] public void ShouldAllowUsersToHoverOverElements() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("menu1")); if (!Platform.CurrentPlatform.IsPlatformType(PlatformType.Windows)) { Assert.Ignore("Skipping test: Simulating hover needs native events"); } IHasInputDevices inputDevicesDriver = driver as IHasInputDevices; if (inputDevicesDriver == null) { return; } IWebElement item = driver.FindElement(By.Id("item1")); Assert.AreEqual("", item.Text); ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].style.background = 'green'", element); //element.Hover(); Actions actionBuilder = new Actions(driver); actionBuilder.MoveToElement(element).Perform(); item = driver.FindElement(By.Id("item1")); Assert.AreEqual("Item 1", item.Text); } [Test] [Category("Javascript")] public void ShouldCorrectlyIdentifyThatAnElementHasWidth() { driver.Url = xhtmlTestPage; IWebElement shrinko = driver.FindElement(By.Id("linkId")); Size size = shrinko.Size; Assert.IsTrue(size.Width > 0, "Width expected to be greater than 0"); Assert.IsTrue(size.Height > 0, "Height expected to be greater than 0"); } [Test] [Category("Javascript")] public void CorrectlyDetectMapElementsAreShown() { driver.Url = mapVisibilityPage; IWebElement area = driver.FindElement(By.Id("mtgt_unnamed_0")); bool isShown = area.Displayed; Assert.IsTrue(isShown, "The element and the enclosing map should be considered shown."); } //[Test] //[Category("Javascript")] //[Ignore] public void CanClickOnSuckerFishMenuItem() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.Id("menu1")); if (!Platform.CurrentPlatform.IsPlatformType(PlatformType.Windows)) { Assert.Ignore("Skipping test: Simulating hover needs native events"); } IWebElement target = driver.FindElement(By.Id("item1")); Assert.IsTrue(target.Displayed); target.Click(); String text = driver.FindElement(By.Id("result")).Text; Assert.IsTrue(text.Contains("item 1")); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "Advanced mouse actions only implemented in rendered browsers")] public void MovingMouseByRelativeOffset() { driver.Url = mouseTrackerPage; IWebElement trackerDiv = driver.FindElement(By.Id("mousetracker")); new Actions(driver).MoveToElement(trackerDiv).Build().Perform(); IWebElement reporter = driver.FindElement(By.Id("status")); WaitFor(FuzzyMatchingOfCoordinates(reporter, 50, 200)); new Actions(driver).MoveByOffset(10, 20).Build().Perform(); WaitFor(FuzzyMatchingOfCoordinates(reporter, 60, 220)); } [Test] [Category("Javascript")] [IgnoreBrowser(Browser.HtmlUnit, "Advanced mouse actions only implemented in rendered browsers")] public void MovingMouseToRelativeElementOffset() { driver.Url = mouseTrackerPage; IWebElement trackerDiv = driver.FindElement(By.Id("mousetracker")); new Actions(driver).MoveToElement(trackerDiv, 95, 195).Build().Perform(); IWebElement reporter = driver.FindElement(By.Id("status")); WaitFor(FuzzyMatchingOfCoordinates(reporter, 95, 195)); } [Test] [Category("Javascript")] [NeedsFreshDriver(BeforeTest = true)] [IgnoreBrowser(Browser.HtmlUnit, "Advanced mouse actions only implemented in rendered browsers")] public void MoveRelativeToBody() { driver.Url = mouseTrackerPage; new Actions(driver).MoveByOffset(50, 100).Build().Perform(); IWebElement reporter = driver.FindElement(By.Id("status")); WaitFor(FuzzyMatchingOfCoordinates(reporter, 40, 20)); } private Func<bool> FuzzyMatchingOfCoordinates(IWebElement element, int x, int y) { return () => { return FuzzyPositionMatching(x, y, element.Text); }; } private bool FuzzyPositionMatching(int expectedX, int expectedY, String locationTuple) { string[] splitString = locationTuple.Split(','); int gotX = int.Parse(splitString[0].Trim()); int gotY = int.Parse(splitString[1].Trim()); // Everything within 5 pixels range is OK const int ALLOWED_DEVIATION = 5; return Math.Abs(expectedX - gotX) < ALLOWED_DEVIATION && Math.Abs(expectedY - gotY) < ALLOWED_DEVIATION; } } }
// 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.Globalization; using System.IO; using System.Reflection; using System.Reflection.Emit; using System.Runtime.Remoting; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.Tests { public partial class ActivatorTests { [Fact] public void CreateInstance_NonPublicValueTypeWithPrivateDefaultConstructor_Success() { AssemblyName assemblyName = new AssemblyName("Assembly"); AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Module"); TypeBuilder typeBuilder = moduleBuilder.DefineType("Type", TypeAttributes.Public, typeof(ValueType)); FieldBuilder fieldBuilder = typeBuilder.DefineField("_field", typeof(int), FieldAttributes.Public); ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Private | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName | MethodAttributes.HideBySig, CallingConventions.Standard, new Type[0]); ILGenerator generator = constructorBuilder.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldc_I4, -1); generator.Emit(OpCodes.Stfld, fieldBuilder); generator.Emit(OpCodes.Ret); Type type = typeBuilder.CreateType(); FieldInfo field = type.GetField("_field"); // Activator holds a cache of constructors and the types to which they belong. // Test caching behaviour by activating multiple times. object v1 = Activator.CreateInstance(type, nonPublic: true); Assert.Equal(-1, field.GetValue(v1)); object v2 = Activator.CreateInstance(type, nonPublic: true); Assert.Equal(-1, field.GetValue(v2)); } [Fact] public void CreateInstance_PublicOnlyValueTypeWithPrivateDefaultConstructor_ThrowsMissingMethodException() { AssemblyName assemblyName = new AssemblyName("Assembly"); AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Module"); TypeBuilder typeBuilder = moduleBuilder.DefineType("Type", TypeAttributes.Public, typeof(ValueType)); FieldBuilder fieldBuilder = typeBuilder.DefineField("_field", typeof(int), FieldAttributes.Public); ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Private | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName | MethodAttributes.HideBySig, CallingConventions.Standard, new Type[0]); ILGenerator generator = constructorBuilder.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Ldc_I4, -1); generator.Emit(OpCodes.Stfld, fieldBuilder); generator.Emit(OpCodes.Ret); Type type = typeBuilder.CreateType(); Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(type)); Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(type, nonPublic: false)); // Put the private default constructor into the cache and make sure we still throw if public only. Assert.NotNull(Activator.CreateInstance(type, nonPublic: true)); Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(type)); Assert.Throws<MissingMethodException>(() => Activator.CreateInstance(type, nonPublic: false)); } [Theory] [MemberData(nameof(TestingCreateInstanceFromObjectHandleData))] public static void TestingCreateInstanceFromObjectHandle(string physicalFileName, string assemblyFile, string type, string returnedFullNameType, Type exceptionType) { ObjectHandle oh = null; if (exceptionType != null) { Assert.Throws(exceptionType, () => Activator.CreateInstanceFrom(assemblyFile: assemblyFile, typeName: type)); } else { oh = Activator.CreateInstanceFrom(assemblyFile: assemblyFile, typeName: type); CheckValidity(oh, returnedFullNameType); } if (exceptionType != null) { Assert.Throws(exceptionType, () => Activator.CreateInstanceFrom(assemblyFile: assemblyFile, typeName: type, null)); } else { oh = Activator.CreateInstanceFrom(assemblyFile: assemblyFile, typeName: type, null); CheckValidity(oh, returnedFullNameType); } Assert.True(File.Exists(physicalFileName)); } public static TheoryData<string, string, string, string, Type> TestingCreateInstanceFromObjectHandleData => new TheoryData<string, string, string, string, Type>() { // string physicalFileName, string assemblyFile, string typeName, returnedFullNameType, expectedException { "TestLoadAssembly.dll", "TestLoadAssembly.dll", "PublicClassSample", "PublicClassSample", null }, { "TestLoadAssembly.dll", "testloadassembly.dll", "publicclasssample", "PublicClassSample", typeof(TypeLoadException) }, { "TestLoadAssembly.dll", "TestLoadAssembly.dll", "PrivateClassSample", "PrivateClassSample", null }, { "TestLoadAssembly.dll", "testloadassembly.dll", "privateclasssample", "PrivateClassSample", typeof(TypeLoadException) }, { "TestLoadAssembly.dll", "TestLoadAssembly.dll", "PublicClassNoDefaultConstructorSample", "PublicClassNoDefaultConstructorSample", typeof(MissingMethodException) }, { "TestLoadAssembly.dll", "testloadassembly.dll", "publicclassnodefaultconstructorsample", "PublicClassNoDefaultConstructorSample", typeof(TypeLoadException) } }; [Theory] [MemberData(nameof(TestingCreateInstanceObjectHandleData))] public static void TestingCreateInstanceObjectHandle(string assemblyName, string type, string returnedFullNameType, Type exceptionType, bool returnNull) { ObjectHandle oh = null; if (exceptionType != null) { Assert.Throws(exceptionType, () => Activator.CreateInstance(assemblyName: assemblyName, typeName: type)); } else { oh = Activator.CreateInstance(assemblyName: assemblyName, typeName: type); if (returnNull) { Assert.Null(oh); } else { CheckValidity(oh, returnedFullNameType); } } if (exceptionType != null) { Assert.Throws(exceptionType, () => Activator.CreateInstance(assemblyName: assemblyName, typeName: type, null)); } else { oh = Activator.CreateInstance(assemblyName: assemblyName, typeName: type, null); if (returnNull) { Assert.Null(oh); } else { CheckValidity(oh, returnedFullNameType); } } } public static TheoryData<string, string, string, Type, bool> TestingCreateInstanceObjectHandleData => new TheoryData<string, string, string, Type, bool>() { // string assemblyName, string typeName, returnedFullNameType, expectedException { "TestLoadAssembly", "PublicClassSample", "PublicClassSample", null, false }, { "testloadassembly", "publicclasssample", "PublicClassSample", typeof(TypeLoadException), false }, { "TestLoadAssembly", "PrivateClassSample", "PrivateClassSample", null, false }, { "testloadassembly", "privateclasssample", "PrivateClassSample", typeof(TypeLoadException), false }, { "TestLoadAssembly", "PublicClassNoDefaultConstructorSample", "PublicClassNoDefaultConstructorSample", typeof(MissingMethodException), false }, { "testloadassembly", "publicclassnodefaultconstructorsample", "PublicClassNoDefaultConstructorSample", typeof(TypeLoadException), false }, { "mscorlib", "System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", "", null, true } }; [Theory] [MemberData(nameof(TestingCreateInstanceFromObjectHandleFullSignatureData))] public static void TestingCreateInstanceFromObjectHandleFullSignature(string physicalFileName, string assemblyFile, string type, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, string returnedFullNameType) { ObjectHandle oh = Activator.CreateInstanceFrom(assemblyFile: assemblyFile, typeName: type, ignoreCase: ignoreCase, bindingAttr: bindingAttr, binder: binder, args: args, culture: culture, activationAttributes: activationAttributes); CheckValidity(oh, returnedFullNameType); Assert.True(File.Exists(physicalFileName)); } public static IEnumerable<object[]> TestingCreateInstanceFromObjectHandleFullSignatureData() { // string physicalFileName, string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, returnedFullNameType yield return new object[] { "TestLoadAssembly.dll", "TestLoadAssembly.dll", "PublicClassSample", false, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PublicClassSample" }; yield return new object[] { "TestLoadAssembly.dll", "testloadassembly.dll", "publicclasssample", true, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PublicClassSample" }; yield return new object[] { "TestLoadAssembly.dll", "TestLoadAssembly.dll", "PublicClassSample", false, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PublicClassSample" }; yield return new object[] { "TestLoadAssembly.dll", "testloadassembly.dll", "publicclasssample", true, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PublicClassSample" }; yield return new object[] { "TestLoadAssembly.dll", "TestLoadAssembly.dll", "PrivateClassSample", false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PrivateClassSample" }; yield return new object[] { "TestLoadAssembly.dll", "testloadassembly.dll", "privateclasssample", true, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PrivateClassSample" }; yield return new object[] { "TestLoadAssembly.dll", "TestLoadAssembly.dll", "PrivateClassSample", false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PrivateClassSample" }; yield return new object[] { "TestLoadAssembly.dll", "testloadassembly.dll", "privateclasssample", true, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PrivateClassSample" }; } [Theory] [MemberData(nameof(TestingCreateInstanceObjectHandleFullSignatureData))] public static void TestingCreateInstanceObjectHandleFullSignature(string assemblyName, string type, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, string returnedFullNameType, bool returnNull) { ObjectHandle oh = Activator.CreateInstance(assemblyName: assemblyName, typeName: type, ignoreCase: ignoreCase, bindingAttr: bindingAttr, binder: binder, args: args, culture: culture, activationAttributes: activationAttributes); if (returnNull) { Assert.Null(oh); } else { CheckValidity(oh, returnedFullNameType); } } public static IEnumerable<object[]> TestingCreateInstanceObjectHandleFullSignatureData() { // string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, returnedFullNameType yield return new object[] { "TestLoadAssembly", "PublicClassSample", false, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PublicClassSample" , false }; yield return new object[] { "testloadassembly", "publicclasssample", true, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PublicClassSample" , false }; yield return new object[] { "TestLoadAssembly", "PublicClassSample", false, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PublicClassSample" , false }; yield return new object[] { "testloadassembly", "publicclasssample", true, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PublicClassSample" , false }; yield return new object[] { "TestLoadAssembly", "PrivateClassSample", false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PrivateClassSample", false }; yield return new object[] { "testloadassembly", "privateclasssample", true, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PrivateClassSample", false }; yield return new object[] { "TestLoadAssembly", "PrivateClassSample", false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PrivateClassSample", false }; yield return new object[] { "testloadassembly", "privateclasssample", true, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PrivateClassSample", false }; yield return new object[] { null, typeof(PublicType).FullName, false, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, typeof(PublicType).FullName, false }; yield return new object[] { null, typeof(PrivateType).FullName, false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, typeof(PrivateType).FullName, false }; yield return new object[] { "mscorlib", "System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", true, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "", true }; yield return new object[] { "mscorlib", "SyStEm.NULLABLE`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", true, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "", true }; } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsWinUISupported))] [PlatformSpecific(TestPlatforms.Windows)] [MemberData(nameof(TestingCreateInstanceObjectHandleFullSignatureWinRTData))] public static void TestingCreateInstanceObjectHandleFullSignatureWinRT(string assemblyName, string type, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, string returnedFullNameType) { ObjectHandle oh = Activator.CreateInstance(assemblyName: assemblyName, typeName: type, ignoreCase: ignoreCase, bindingAttr: bindingAttr, binder: binder, args: args, culture: culture, activationAttributes: activationAttributes); CheckValidity(oh, returnedFullNameType); } public static IEnumerable<object[]> TestingCreateInstanceObjectHandleFullSignatureWinRTData() { // string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, returnedFullNameType yield return new object[] { "Windows, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime", "Windows.Foundation.Collections.StringMap", false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "Windows.Foundation.Collections.StringMap" }; } private static void CheckValidity(ObjectHandle instance, string expected) { Assert.NotNull(instance); Assert.Equal(expected, instance.Unwrap().GetType().FullName); } public class PublicType { public PublicType() { } } [Fact] public static void CreateInstanceAssemblyResolve() { RemoteExecutor.Invoke(() => { AppDomain.CurrentDomain.AssemblyResolve += (object sender, ResolveEventArgs args) => Assembly.LoadFile(Path.Combine(Directory.GetCurrentDirectory(), "TestLoadAssembly.dll")); Assert.Throws<FileLoadException>(() => Activator.CreateInstance(",,,,", "PublicClassSample")); }).Dispose(); } [Fact] public void CreateInstance_TypeBuilder_ThrowsNotSupportedException() { AssemblyName assemblyName = new AssemblyName("Assembly"); AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("Module"); TypeBuilder typeBuilder = moduleBuilder.DefineType("Type", TypeAttributes.Public); Assert.Throws<ArgumentException>("type", () => Activator.CreateInstance(typeBuilder)); Assert.Throws<NotSupportedException>(() => Activator.CreateInstance(typeBuilder, new object[0])); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Reflection; using System.Threading; using System.Text; using System.Xml; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Framework.Communications.Osp; using OpenSim.Framework.Serialization; using OpenSim.Framework.Serialization.External; using OpenSim.Region.CoreModules.World.Archiver; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver { public class InventoryArchiveReadRequest { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected TarArchiveReader archive; private UserAccount m_userInfo; private string m_invPath; /// <value> /// We only use this to request modules /// </value> protected Scene m_scene; /// <value> /// The stream from which the inventory archive will be loaded. /// </value> private Stream m_loadStream; public InventoryArchiveReadRequest( Scene scene, UserAccount userInfo, string invPath, string loadPath) : this( scene, userInfo, invPath, new GZipStream(ArchiveHelpers.GetStream(loadPath), CompressionMode.Decompress)) { } public InventoryArchiveReadRequest( Scene scene, UserAccount userInfo, string invPath, Stream loadStream) { m_scene = scene; m_userInfo = userInfo; m_invPath = invPath; m_loadStream = loadStream; } /// <summary> /// Execute the request /// </summary> /// <returns> /// A list of the inventory nodes loaded. If folders were loaded then only the root folders are /// returned /// </returns> public List<InventoryNodeBase> Execute() { string filePath = "ERROR"; int successfulAssetRestores = 0; int failedAssetRestores = 0; int successfulItemRestores = 0; List<InventoryNodeBase> loadedNodes = new List<InventoryNodeBase>(); List<InventoryFolderBase> folderCandidates = InventoryArchiveUtils.FindFolderByPath( m_scene.InventoryService, m_userInfo.PrincipalID, m_invPath); if (folderCandidates.Count == 0) { // Possibly provide an option later on to automatically create this folder if it does not exist m_log.ErrorFormat("[INVENTORY ARCHIVER]: Inventory path {0} does not exist", m_invPath); return loadedNodes; } InventoryFolderBase rootDestinationFolder = folderCandidates[0]; archive = new TarArchiveReader(m_loadStream); // In order to load identically named folders, we need to keep track of the folders that we have already // resolved Dictionary <string, InventoryFolderBase> resolvedFolders = new Dictionary<string, InventoryFolderBase>(); byte[] data; TarArchiveReader.TarEntryType entryType; try { while ((data = archive.ReadEntry(out filePath, out entryType)) != null) { if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH)) { if (LoadAsset(filePath, data)) successfulAssetRestores++; else failedAssetRestores++; if ((successfulAssetRestores) % 50 == 0) m_log.DebugFormat( "[INVENTORY ARCHIVER]: Loaded {0} assets...", successfulAssetRestores); } else if (filePath.StartsWith(ArchiveConstants.INVENTORY_PATH)) { filePath = filePath.Substring(ArchiveConstants.INVENTORY_PATH.Length); // Trim off the file portion if we aren't already dealing with a directory path if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY != entryType) filePath = filePath.Remove(filePath.LastIndexOf("/") + 1); InventoryFolderBase foundFolder = ReplicateArchivePathToUserInventory( filePath, rootDestinationFolder, resolvedFolders, loadedNodes); if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY != entryType) { InventoryItemBase item = LoadItem(data, foundFolder); if (item != null) { successfulItemRestores++; // If we're loading an item directly into the given destination folder then we need to record // it separately from any loaded root folders if (rootDestinationFolder == foundFolder) loadedNodes.Add(item); } } } } } finally { archive.Close(); } m_log.DebugFormat( "[INVENTORY ARCHIVER]: Successfully loaded {0} assets with {1} failures", successfulAssetRestores, failedAssetRestores); m_log.InfoFormat("[INVENTORY ARCHIVER]: Successfully loaded {0} items", successfulItemRestores); return loadedNodes; } public void Close() { if (m_loadStream != null) m_loadStream.Close(); } /// <summary> /// Replicate the inventory paths in the archive to the user's inventory as necessary. /// </summary> /// <param name="iarPath">The item archive path to replicate</param> /// <param name="rootDestinationFolder">The root folder for the inventory load</param> /// <param name="resolvedFolders"> /// The folders that we have resolved so far for a given archive path. /// This method will add more folders if necessary /// </param> /// <param name="loadedNodes"> /// Track the inventory nodes created. /// </param> /// <returns>The last user inventory folder created or found for the archive path</returns> public InventoryFolderBase ReplicateArchivePathToUserInventory( string iarPath, InventoryFolderBase rootDestFolder, Dictionary <string, InventoryFolderBase> resolvedFolders, List<InventoryNodeBase> loadedNodes) { string iarPathExisting = iarPath; // m_log.DebugFormat( // "[INVENTORY ARCHIVER]: Loading folder {0} {1}", rootDestFolder.Name, rootDestFolder.ID); InventoryFolderBase destFolder = ResolveDestinationFolder(rootDestFolder, ref iarPathExisting, resolvedFolders); // m_log.DebugFormat( // "[INVENTORY ARCHIVER]: originalArchivePath [{0}], section already loaded [{1}]", // iarPath, iarPathExisting); string iarPathToCreate = iarPath.Substring(iarPathExisting.Length); CreateFoldersForPath(destFolder, iarPathExisting, iarPathToCreate, resolvedFolders, loadedNodes); return destFolder; } /// <summary> /// Resolve a destination folder /// </summary> /// /// We require here a root destination folder (usually the root of the user's inventory) and the archive /// path. We also pass in a list of previously resolved folders in case we've found this one previously. /// /// <param name="archivePath"> /// The item archive path to resolve. The portion of the path passed back is that /// which corresponds to the resolved desintation folder. /// <param name="rootDestinationFolder"> /// The root folder for the inventory load /// </param> /// <param name="resolvedFolders"> /// The folders that we have resolved so far for a given archive path. /// </param> /// <returns> /// The folder in the user's inventory that matches best the archive path given. If no such folder was found /// then the passed in root destination folder is returned. /// </returns> protected InventoryFolderBase ResolveDestinationFolder( InventoryFolderBase rootDestFolder, ref string archivePath, Dictionary <string, InventoryFolderBase> resolvedFolders) { string originalArchivePath = archivePath; InventoryFolderBase destFolder = null; if (archivePath.Length > 0) { while (null == destFolder && archivePath.Length > 0) { // m_log.DebugFormat("[INVENTORY ARCHIVER]: Trying to resolve destination folder {0}", archivePath); if (resolvedFolders.ContainsKey(archivePath)) { // m_log.DebugFormat( // "[INVENTORY ARCHIVER]: Found previously created folder from archive path {0}", archivePath); destFolder = resolvedFolders[archivePath]; } else { // Don't include the last slash so find the penultimate one int penultimateSlashIndex = archivePath.LastIndexOf("/", archivePath.Length - 2); if (penultimateSlashIndex >= 0) { // Remove the last section of path so that we can see if we've already resolved the parent archivePath = archivePath.Remove(penultimateSlashIndex + 1); } else { // m_log.DebugFormat( // "[INVENTORY ARCHIVER]: Found no previously created folder for archive path {0}", // originalArchivePath); archivePath = string.Empty; destFolder = rootDestFolder; } } } } if (null == destFolder) destFolder = rootDestFolder; return destFolder; } /// <summary> /// Create a set of folders for the given path. /// </summary> /// <param name="destFolder"> /// The root folder from which the creation will take place. /// </param> /// <param name="iarPathExisting"> /// the part of the iar path that already exists /// </param> /// <param name="iarPathToReplicate"> /// The path to replicate in the user's inventory from iar /// </param> /// <param name="resolvedFolders"> /// The folders that we have resolved so far for a given archive path. /// </param> /// <param name="loadedNodes"> /// Track the inventory nodes created. /// </param> protected void CreateFoldersForPath( InventoryFolderBase destFolder, string iarPathExisting, string iarPathToReplicate, Dictionary <string, InventoryFolderBase> resolvedFolders, List<InventoryNodeBase> loadedNodes) { string[] rawDirsToCreate = iarPathToReplicate.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); int i = 0; while (i < rawDirsToCreate.Length) { // m_log.DebugFormat("[INVENTORY ARCHIVER]: Creating folder {0} from IAR", rawDirsToCreate[i]); int identicalNameIdentifierIndex = rawDirsToCreate[i].LastIndexOf( ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR); if (identicalNameIdentifierIndex < 0) { i++; continue; } string newFolderName = rawDirsToCreate[i].Remove(identicalNameIdentifierIndex); newFolderName = InventoryArchiveUtils.UnescapeArchivePath(newFolderName); UUID newFolderId = UUID.Random(); // Asset type has to be Unknown here rather than Folder, otherwise the created folder can't be // deleted once the client has relogged. // The root folder appears to be labelled AssetType.Folder (shows up as "Category" in the client) // even though there is a AssetType.RootCategory destFolder = new InventoryFolderBase( newFolderId, newFolderName, m_userInfo.PrincipalID, (short)AssetType.Unknown, destFolder.ID, 1); m_scene.InventoryService.AddFolder(destFolder); // Record that we have now created this folder iarPathExisting += rawDirsToCreate[i] + "/"; m_log.DebugFormat("[INVENTORY ARCHIVER]: Created folder {0} from IAR", iarPathExisting); resolvedFolders[iarPathExisting] = destFolder; if (0 == i) loadedNodes.Add(destFolder); i++; } } /// <summary> /// Load an item from the archive /// </summary> /// <param name="filePath">The archive path for the item</param> /// <param name="data">The raw item data</param> /// <param name="rootDestinationFolder">The root destination folder for loaded items</param> /// <param name="nodesLoaded">All the inventory nodes (items and folders) loaded so far</param> protected InventoryItemBase LoadItem(byte[] data, InventoryFolderBase loadFolder) { InventoryItemBase item = UserInventoryItemSerializer.Deserialize(data); // Don't use the item ID that's in the file item.ID = UUID.Random(); UUID ospResolvedId = OspResolver.ResolveOspa(item.CreatorId, m_scene.UserAccountService); if (UUID.Zero != ospResolvedId) { item.CreatorIdAsUuid = ospResolvedId; // XXX: For now, don't preserve the OSPA in the creator id (which actually gets persisted to the // database). Instead, replace with the UUID that we found. item.CreatorId = ospResolvedId.ToString(); } else { item.CreatorIdAsUuid = m_userInfo.PrincipalID; } item.Owner = m_userInfo.PrincipalID; // Reset folder ID to the one in which we want to load it item.Folder = loadFolder.ID; //m_userInfo.AddItem(item); m_scene.InventoryService.AddItem(item); return item; } /// <summary> /// Load an asset /// </summary> /// <param name="assetFilename"></param> /// <param name="data"></param> /// <returns>true if asset was successfully loaded, false otherwise</returns> private bool LoadAsset(string assetPath, byte[] data) { //IRegionSerialiser serialiser = scene.RequestModuleInterface<IRegionSerialiser>(); // Right now we're nastily obtaining the UUID from the filename string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length); int i = filename.LastIndexOf(ArchiveConstants.ASSET_EXTENSION_SEPARATOR); if (i == -1) { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Could not find extension information in asset path {0} since it's missing the separator {1}. Skipping", assetPath, ArchiveConstants.ASSET_EXTENSION_SEPARATOR); return false; } string extension = filename.Substring(i); string uuid = filename.Remove(filename.Length - extension.Length); if (ArchiveConstants.EXTENSION_TO_ASSET_TYPE.ContainsKey(extension)) { sbyte assetType = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension]; if (assetType == (sbyte)AssetType.Unknown) m_log.WarnFormat("[INVENTORY ARCHIVER]: Importing {0} byte asset {1} with unknown type", data.Length, uuid); //m_log.DebugFormat("[INVENTORY ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType); AssetBase asset = new AssetBase(new UUID(uuid), "RandomName", assetType, UUID.Zero.ToString()); asset.Data = data; m_scene.AssetService.Store(asset); return true; } else { m_log.ErrorFormat( "[INVENTORY ARCHIVER]: Tried to dearchive data with path {0} with an unknown type extension {1}", assetPath, extension); 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. namespace System.Xml.Schema { #if SILVERLIGHT public class XmlSchema : XmlSchemaObject { //Empty XmlSchema class to enable backward compatibility of interface method IXmlSerializable.GetSchema() //Add private ctor to prevent constructing of this class XmlSchema() { } } #else using System.IO; using System.Collections; using System.ComponentModel; using System.Xml.Serialization; using System.Threading; using System.Diagnostics; using System.Collections.Generic; /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlRoot("schema", Namespace = XmlSchema.Namespace)] public class XmlSchema : XmlSchemaObject { /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Namespace"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const string Namespace = XmlReservedNs.NsXs; /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.InstanceNamespace"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public const string InstanceNamespace = XmlReservedNs.NsXsi; private XmlSchemaForm _attributeFormDefault = XmlSchemaForm.None; private XmlSchemaForm _elementFormDefault = XmlSchemaForm.None; private XmlSchemaDerivationMethod _blockDefault = XmlSchemaDerivationMethod.None; private XmlSchemaDerivationMethod _finalDefault = XmlSchemaDerivationMethod.None; private string _targetNs; private string _version; private XmlSchemaObjectCollection _includes = new XmlSchemaObjectCollection(); private XmlSchemaObjectCollection _items = new XmlSchemaObjectCollection(); private string _id; private XmlAttribute[] _moreAttributes; // compiled info private bool _isCompiled = false; private bool _isCompiledBySet = false; private bool _isPreprocessed = false; private bool _isRedefined = false; private int _errorCount = 0; private XmlSchemaObjectTable _attributes; private XmlSchemaObjectTable _attributeGroups = new XmlSchemaObjectTable(); private XmlSchemaObjectTable _elements = new XmlSchemaObjectTable(); private XmlSchemaObjectTable _types = new XmlSchemaObjectTable(); private XmlSchemaObjectTable _groups = new XmlSchemaObjectTable(); private XmlSchemaObjectTable _notations = new XmlSchemaObjectTable(); private XmlSchemaObjectTable _identityConstraints = new XmlSchemaObjectTable(); private static int s_globalIdCounter = -1; private ArrayList _importedSchemas; private ArrayList _importedNamespaces; private int _schemaId = -1; //Not added to a set private Uri _baseUri; private bool _isChameleon; private Hashtable _ids = new Hashtable(); private XmlDocument _document; private XmlNameTable _nameTable; /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.XmlSchema"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSchema() { } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Read"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static XmlSchema Read(TextReader reader, ValidationEventHandler validationEventHandler) { return Read(new XmlTextReader(reader), validationEventHandler); } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Read1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static XmlSchema Read(Stream stream, ValidationEventHandler validationEventHandler) { return Read(new XmlTextReader(stream), validationEventHandler); } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Read2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public static XmlSchema Read(XmlReader reader, ValidationEventHandler validationEventHandler) { XmlNameTable nameTable = reader.NameTable; Parser parser = new Parser(SchemaType.XSD, nameTable, new SchemaNames(nameTable), validationEventHandler); try { parser.Parse(reader, null); } catch (XmlSchemaException e) { if (validationEventHandler != null) { validationEventHandler(null, new ValidationEventArgs(e)); } else { throw; } return null; } return parser.XmlSchema; } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Write"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Write(Stream stream) { Write(stream, null); } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Write1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Write(Stream stream, XmlNamespaceManager namespaceManager) { XmlTextWriter xmlWriter = new XmlTextWriter(stream, null); xmlWriter.Formatting = Formatting.Indented; Write(xmlWriter, namespaceManager); } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Write2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Write(TextWriter writer) { Write(writer, null); } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Write3"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Write(TextWriter writer, XmlNamespaceManager namespaceManager) { XmlTextWriter xmlWriter = new XmlTextWriter(writer); xmlWriter.Formatting = Formatting.Indented; Write(xmlWriter, namespaceManager); } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Write4"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Write(XmlWriter writer) { Write(writer, null); } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Write5"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Write(XmlWriter writer, XmlNamespaceManager namespaceManager) { XmlSerializer serializer = new XmlSerializer(typeof(XmlSchema)); XmlSerializerNamespaces ns; if (namespaceManager != null) { ns = new XmlSerializerNamespaces(); bool ignoreXS = false; if (this.Namespaces != null) { //User may have set both nsManager and Namespaces property on the XmlSchema object ignoreXS = this.Namespaces.Namespaces["xs"] != null || this.Namespaces.Namespaces.ContainsValue(XmlReservedNs.NsXs); } if (!ignoreXS && namespaceManager.LookupPrefix(XmlReservedNs.NsXs) == null && namespaceManager.LookupNamespace("xs") == null) { ns.Add("xs", XmlReservedNs.NsXs); } foreach (string prefix in namespaceManager) { if (prefix != "xml" && prefix != "xmlns") { ns.Add(prefix, namespaceManager.LookupNamespace(prefix)); } } } else if (this.Namespaces != null && this.Namespaces.Count > 0) { Dictionary<string, string> serializerNS = this.Namespaces.Namespaces; if (!serializerNS.ContainsKey("xs") && !serializerNS.ContainsValue(XmlReservedNs.NsXs)) { //Prefix xs not defined AND schema namespace not already mapped to a prefix serializerNS.Add("xs", XmlReservedNs.NsXs); } ns = this.Namespaces; } else { ns = new XmlSerializerNamespaces(); ns.Add("xs", XmlSchema.Namespace); if (_targetNs != null && _targetNs.Length != 0) { ns.Add("tns", _targetNs); } } serializer.Serialize(writer, this, ns); } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Compile"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [Obsolete("Use System.Xml.Schema.XmlSchemaSet for schema compilation and validation. http://go.microsoft.com/fwlink/?linkid=14202")] public void Compile(ValidationEventHandler validationEventHandler) { SchemaInfo sInfo = new SchemaInfo(); sInfo.SchemaType = SchemaType.XSD; CompileSchema(null, null, sInfo, null, validationEventHandler, NameTable, false); } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Compileq"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [Obsolete("Use System.Xml.Schema.XmlSchemaSet for schema compilation and validation. http://go.microsoft.com/fwlink/?linkid=14202")] public void Compile(ValidationEventHandler validationEventHandler, XmlResolver resolver) { SchemaInfo sInfo = new SchemaInfo(); sInfo.SchemaType = SchemaType.XSD; CompileSchema(null, resolver, sInfo, null, validationEventHandler, NameTable, false); } #pragma warning disable 618 internal bool CompileSchema(XmlSchemaCollection xsc, XmlResolver resolver, SchemaInfo schemaInfo, string ns, ValidationEventHandler validationEventHandler, XmlNameTable nameTable, bool CompileContentModel) { //Need to lock here to prevent multi-threading problems when same schema is added to set and compiled lock (this) { //Preprocessing SchemaCollectionPreprocessor prep = new SchemaCollectionPreprocessor(nameTable, null, validationEventHandler); prep.XmlResolver = resolver; if (!prep.Execute(this, ns, true, xsc)) { return false; } //Compilation SchemaCollectionCompiler compiler = new SchemaCollectionCompiler(nameTable, validationEventHandler); _isCompiled = compiler.Execute(this, schemaInfo, CompileContentModel); this.SetIsCompiled(_isCompiled); //TODO includes isCompiled flag return _isCompiled; } } #pragma warning restore 618 internal void CompileSchemaInSet(XmlNameTable nameTable, ValidationEventHandler eventHandler, XmlSchemaCompilationSettings compilationSettings) { Debug.Assert(_isPreprocessed); Compiler setCompiler = new Compiler(nameTable, eventHandler, null, compilationSettings); setCompiler.Prepare(this, true); _isCompiledBySet = setCompiler.Compile(); } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.AttributeFormDefault"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("attributeFormDefault"), DefaultValue(XmlSchemaForm.None)] public XmlSchemaForm AttributeFormDefault { get { return _attributeFormDefault; } set { _attributeFormDefault = value; } } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.BlockDefault"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("blockDefault"), DefaultValue(XmlSchemaDerivationMethod.None)] public XmlSchemaDerivationMethod BlockDefault { get { return _blockDefault; } set { _blockDefault = value; } } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.FinalDefault"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("finalDefault"), DefaultValue(XmlSchemaDerivationMethod.None)] public XmlSchemaDerivationMethod FinalDefault { get { return _finalDefault; } set { _finalDefault = value; } } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.ElementFormDefault"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("elementFormDefault"), DefaultValue(XmlSchemaForm.None)] public XmlSchemaForm ElementFormDefault { get { return _elementFormDefault; } set { _elementFormDefault = value; } } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.TargetNamespace"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("targetNamespace", DataType = "anyURI")] public string TargetNamespace { get { return _targetNs; } set { _targetNs = value; } } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Version"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("version", DataType = "token")] public string Version { get { return _version; } set { _version = value; } } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Includes"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlElement("include", typeof(XmlSchemaInclude)), XmlElement("import", typeof(XmlSchemaImport)), XmlElement("redefine", typeof(XmlSchemaRedefine))] public XmlSchemaObjectCollection Includes { get { return _includes; } } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Items"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlElement("annotation", typeof(XmlSchemaAnnotation)), XmlElement("attribute", typeof(XmlSchemaAttribute)), XmlElement("attributeGroup", typeof(XmlSchemaAttributeGroup)), XmlElement("complexType", typeof(XmlSchemaComplexType)), XmlElement("simpleType", typeof(XmlSchemaSimpleType)), XmlElement("element", typeof(XmlSchemaElement)), XmlElement("group", typeof(XmlSchemaGroup)), XmlElement("notation", typeof(XmlSchemaNotation))] public XmlSchemaObjectCollection Items { get { return _items; } } // Compiled info /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.IsCompiled"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] public bool IsCompiled { get { return _isCompiled || _isCompiledBySet; } } [XmlIgnore] internal bool IsCompiledBySet { get { return _isCompiledBySet; } set { _isCompiledBySet = value; } } [XmlIgnore] internal bool IsPreprocessed { get { return _isPreprocessed; } set { _isPreprocessed = value; } } [XmlIgnore] internal bool IsRedefined { get { return _isRedefined; } set { _isRedefined = value; } } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Attributes"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] public XmlSchemaObjectTable Attributes { get { if (_attributes == null) { _attributes = new XmlSchemaObjectTable(); } return _attributes; } } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.AttributeGroups"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] public XmlSchemaObjectTable AttributeGroups { get { if (_attributeGroups == null) { _attributeGroups = new XmlSchemaObjectTable(); } return _attributeGroups; } } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.SchemaTypes"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] public XmlSchemaObjectTable SchemaTypes { get { if (_types == null) { _types = new XmlSchemaObjectTable(); } return _types; } } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Elements"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] public XmlSchemaObjectTable Elements { get { if (_elements == null) { _elements = new XmlSchemaObjectTable(); } return _elements; } } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Id"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAttribute("id", DataType = "ID")] public string Id { get { return _id; } set { _id = value; } } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.UnhandledAttributes"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlAnyAttribute] public XmlAttribute[] UnhandledAttributes { get { return _moreAttributes; } set { _moreAttributes = value; } } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Groups"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] public XmlSchemaObjectTable Groups { get { return _groups; } } /// <include file='doc\XmlSchema.uex' path='docs/doc[@for="XmlSchema.Notations"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [XmlIgnore] public XmlSchemaObjectTable Notations { get { return _notations; } } [XmlIgnore] internal XmlSchemaObjectTable IdentityConstraints { get { return _identityConstraints; } } [XmlIgnore] internal Uri BaseUri { get { return _baseUri; } set { _baseUri = value; } } [XmlIgnore] // Please be careful with this property. Since it lazy initialized and its value depends on a global state // if it gets called on multiple schemas in a different order the schemas will end up with different IDs // Unfortunately the IDs are used to sort the schemas in the schema set and thus changing the IDs might change // the order which would be a breaking change!! // Simply put if you are planning to add or remove a call to this getter you need to be extra carefull // or better don't do it at all. internal int SchemaId { get { if (_schemaId == -1) { _schemaId = Interlocked.Increment(ref s_globalIdCounter); } return _schemaId; } } [XmlIgnore] internal bool IsChameleon { get { return _isChameleon; } set { _isChameleon = value; } } [XmlIgnore] internal Hashtable Ids { get { return _ids; } } [XmlIgnore] internal XmlDocument Document { get { if (_document == null) _document = new XmlDocument(); return _document; } } [XmlIgnore] internal int ErrorCount { get { return _errorCount; } set { _errorCount = value; } } internal new XmlSchema Clone() { XmlSchema that = new XmlSchema(); that._attributeFormDefault = _attributeFormDefault; that._elementFormDefault = _elementFormDefault; that._blockDefault = _blockDefault; that._finalDefault = _finalDefault; that._targetNs = _targetNs; that._version = _version; that._includes = _includes; that.Namespaces = this.Namespaces; that._items = _items; that.BaseUri = this.BaseUri; SchemaCollectionCompiler.Cleanup(that); return that; } internal XmlSchema DeepClone() { XmlSchema that = new XmlSchema(); that._attributeFormDefault = _attributeFormDefault; that._elementFormDefault = _elementFormDefault; that._blockDefault = _blockDefault; that._finalDefault = _finalDefault; that._targetNs = _targetNs; that._version = _version; that._isPreprocessed = _isPreprocessed; //that.IsProcessing = this.IsProcessing; //Not sure if this is needed //Clone its Items for (int i = 0; i < _items.Count; ++i) { XmlSchemaObject newItem; XmlSchemaComplexType complexType; XmlSchemaElement element; XmlSchemaGroup group; if ((complexType = _items[i] as XmlSchemaComplexType) != null) { newItem = complexType.Clone(this); } else if ((element = _items[i] as XmlSchemaElement) != null) { newItem = element.Clone(this); } else if ((group = _items[i] as XmlSchemaGroup) != null) { newItem = group.Clone(this); } else { newItem = _items[i].Clone(); } that.Items.Add(newItem); } //Clone Includes for (int i = 0; i < _includes.Count; ++i) { XmlSchemaExternal newInclude = (XmlSchemaExternal)_includes[i].Clone(); that.Includes.Add(newInclude); } that.Namespaces = this.Namespaces; //that.includes = this.includes; //Need to verify this is OK for redefines that.BaseUri = this.BaseUri; return that; } [XmlIgnore] internal override string IdAttribute { get { return Id; } set { Id = value; } } internal void SetIsCompiled(bool isCompiled) { _isCompiled = isCompiled; } internal override void SetUnhandledAttributes(XmlAttribute[] moreAttributes) { _moreAttributes = moreAttributes; } internal override void AddAnnotation(XmlSchemaAnnotation annotation) { _items.Add(annotation); } internal XmlNameTable NameTable { get { if (_nameTable == null) _nameTable = new System.Xml.NameTable(); return _nameTable; } } internal ArrayList ImportedSchemas { get { if (_importedSchemas == null) { _importedSchemas = new ArrayList(); } return _importedSchemas; } } internal ArrayList ImportedNamespaces { get { if (_importedNamespaces == null) { _importedNamespaces = new ArrayList(); } return _importedNamespaces; } } internal void GetExternalSchemasList(IList extList, XmlSchema schema) { Debug.Assert(extList != null && schema != null); if (extList.Contains(schema)) { return; } extList.Add(schema); for (int i = 0; i < schema.Includes.Count; ++i) { XmlSchemaExternal ext = (XmlSchemaExternal)schema.Includes[i]; if (ext.Schema != null) { GetExternalSchemasList(extList, ext.Schema); } } } #if TRUST_COMPILE_STATE internal void AddCompiledInfo(SchemaInfo schemaInfo) { XmlQualifiedName itemName; foreach (XmlSchemaElement element in elements.Values) { itemName = element.QualifiedName; schemaInfo.TargetNamespaces[itemName.Namespace] = true; if (schemaInfo.ElementDecls[itemName] == null) { schemaInfo.ElementDecls.Add(itemName, element.ElementDecl); } } foreach (XmlSchemaAttribute attribute in attributes.Values) { itemName = attribute.QualifiedName; schemaInfo.TargetNamespaces[itemName.Namespace] = true; if (schemaInfo.ElementDecls[itemName] == null) { schemaInfo.AttributeDecls.Add(itemName, attribute.AttDef); } } foreach (XmlSchemaType type in types.Values) { itemName = type.QualifiedName; schemaInfo.TargetNamespaces[itemName.Namespace] = true; XmlSchemaComplexType complexType = type as XmlSchemaComplexType; if ((complexType == null || type != XmlSchemaComplexType.AnyType) && schemaInfo.ElementDeclsByType[itemName] == null) { schemaInfo.ElementDeclsByType.Add(itemName, type.ElementDecl); } } foreach (XmlSchemaNotation notation in notations.Values) { itemName = notation.QualifiedName; schemaInfo.TargetNamespaces[itemName.Namespace] = true; SchemaNotation no = new SchemaNotation(itemName); no.SystemLiteral = notation.System; no.Pubid = notation.Public; if (schemaInfo.Notations[itemName.Name] == null) { schemaInfo.Notations.Add(itemName.Name, no); } } } #endif//TRUST_COMPILE_STATE } #endif//!SILVERLIGHT }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- function TerrainMaterialDlg::show( %this, %matIndex, %terrMat, %onApplyCallback ) { Canvas.pushDialog( %this ); %this.matIndex = %matIndex; %this.onApplyCallback = %onApplyCallback; %matLibTree = %this-->matLibTree; %item = %matLibTree.findItemByObjectId( %terrMat ); if ( %item != -1 ) { %matLibTree.selectItem( %item ); %matLibTree.scrollVisible( %item ); } else { for( %i = 1; %i < %matLibTree.getItemCount(); %i++ ) { %terrMat = TerrainMaterialDlg-->matLibTree.getItemValue(%i); if( %terrMat.getClassName() $= "TerrainMaterial" ) { %matLibTree.selectItem( %i, true ); %matLibTree.scrollVisible( %i ); break; } } } } //----------------------------------------------------------------------------- function TerrainMaterialDlg::showByObjectId( %this, %matObjectId, %onApplyCallback ) { Canvas.pushDialog( %this ); %this.matIndex = -1; %this.onApplyCallback = %onApplyCallback; %matLibTree = %this-->matLibTree; %matLibTree.clearSelection(); %item = %matLibTree.findItemByObjectId( %matObjectId ); if ( %item != -1 ) { %matLibTree.selectItem( %item ); %matLibTree.scrollVisible( %item ); } } //----------------------------------------------------------------------------- function TerrainMaterialDlg::onWake( %this ) { if( !isObject( ETerrainMaterialPersistMan ) ) new PersistenceManager( ETerrainMaterialPersistMan ); if( !isObject( TerrainMaterialDlgNewGroup ) ) new SimGroup( TerrainMaterialDlgNewGroup ); if( !isObject( TerrainMaterialDlgDeleteGroup ) ) new SimGroup( TerrainMaterialDlgDeleteGroup ); // Snapshot the materials. %this.snapshotMaterials(); // Refresh the material list. %matLibTree = %this-->matLibTree; %matLibTree.clear(); %matLibTree.open( TerrainMaterialSet, false ); %matLibTree.buildVisibleTree( true ); %item = %matLibTree.getFirstRootItem(); %matLibTree.expandItem( %item ); %this.activateMaterialCtrls( true ); } //----------------------------------------------------------------------------- function TerrainMaterialDlg::onSleep( %this ) { if( isObject( TerrainMaterialDlgSnapshot ) ) TerrainMaterialDlgSnapshot.delete(); %this-->matLibTree.clear(); } //----------------------------------------------------------------------------- function TerrainMaterialDlg::dialogApply( %this ) { // Move all new materials we have created to the root group. %newCount = TerrainMaterialDlgNewGroup.getCount(); for( %i = 0; %i < %newCount; %i ++ ) RootGroup.add( TerrainMaterialDlgNewGroup.getObject( %i ) ); // Finalize deletion of all removed materials. %deletedCount = TerrainMaterialDlgDeleteGroup.getCount(); for( %i = 0; %i < %deletedCount; %i ++ ) { %mat = TerrainMaterialDlgDeleteGroup.getObject( %i ); ETerrainMaterialPersistMan.removeObjectFromFile( %mat ); %matIndex = ETerrainEditor.getMaterialIndex( %mat.internalName ); if( %matIndex != -1 ) { ETerrainEditor.removeMaterial( %matIndex ); EPainter.updateLayers(); } %mat.delete(); } // Make sure we save any changes to the current selection. %this.saveDirtyMaterial( %this.activeMat ); // Save all changes. ETerrainMaterialPersistMan.saveDirty(); // Delete the snapshot. TerrainMaterialDlgSnapshot.delete(); // Remove ourselves from the canvas. Canvas.popDialog( TerrainMaterialDlg ); call( %this.onApplyCallback, %this.activeMat, %this.matIndex ); } //----------------------------------------------------------------------------- function TerrainMaterialDlg::dialogCancel( %this ) { // Restore material properties we have changed. %this.restoreMaterials(); // Clear the persistence manager state. ETerrainMaterialPersistMan.clearAll(); // Delete all new object we have created. TerrainMaterialDlgNewGroup.clear(); // Restore materials we have marked for deletion. %deletedCount = TerrainMaterialDlgDeleteGroup.getCount(); for( %i = 0; %i < %deletedCount; %i ++ ) { %mat = TerrainMaterialDlgDeleteGroup.getObject( %i ); %mat.parentGroup = RootGroup; TerrainMaterialSet.add( %mat ); } Canvas.popDialog( TerrainMaterialDlg ); } //----------------------------------------------------------------------------- function TerrainMaterialDlg::setMaterialName( %this, %newName ) { %mat = %this.activeMat; if( %mat.internalName !$= %newName ) { %existingMat = TerrainMaterialSet.findObjectByInternalName( %newName ); if( isObject( %existingMat ) ) { MessageBoxOK( "Error", "There already is a terrain material called '" @ %newName @ "'.", "", "" ); } else { %mat.setInternalName( %newName ); %this-->matLibTree.buildVisibleTree( false ); } } } //----------------------------------------------------------------------------- function TerrainMaterialDlg::changeBase( %this ) { %ctrl = %this-->baseTexCtrl; %file = %ctrl.bitmap; if( getSubStr( %file, 0 , 6 ) $= "tools/" ) %file = ""; %file = TerrainMaterialDlg._selectTextureFileDialog( %file ); if( %file $= "" ) { if( %ctrl.bitmap !$= "" ) %file = %ctrl.bitmap; else %file = "tools/materialeditor/gui/unknownImage"; } %file = makeRelativePath( %file, getMainDotCsDir() ); %ctrl.setBitmap( %file ); } //----------------------------------------------------------------------------- function TerrainMaterialDlg::changeDetail( %this ) { %ctrl = %this-->detailTexCtrl; %file = %ctrl.bitmap; if( getSubStr( %file, 0 , 6 ) $= "tools/" ) %file = ""; %file = TerrainMaterialDlg._selectTextureFileDialog( %file ); if( %file $= "" ) { if( %ctrl.bitmap !$= "" ) %file = %ctrl.bitmap; else %file = "tools/materialeditor/gui/unknownImage"; } %file = makeRelativePath( %file, getMainDotCsDir() ); %ctrl.setBitmap( %file ); } //---------------------------------------------------------------------------- function TerrainMaterialDlg::changeMacro( %this ) { %ctrl = %this-->macroTexCtrl; %file = %ctrl.bitmap; if( getSubStr( %file, 0 , 6 ) $= "tools/" ) %file = ""; %file = TerrainMaterialDlg._selectTextureFileDialog( %file ); if( %file $= "" ) { if( %ctrl.bitmap !$= "" ) %file = %ctrl.bitmap; else %file = "tools/materialeditor/gui/unknownImage"; } %file = makeRelativePath( %file, getMainDotCsDir() ); %ctrl.setBitmap( %file ); } //----------------------------------------------------------------------------- function TerrainMaterialDlg::changeNormal( %this ) { %ctrl = %this-->normTexCtrl; %file = %ctrl.bitmap; if( getSubStr( %file, 0 , 6 ) $= "tools/" ) %file = ""; %file = TerrainMaterialDlg._selectTextureFileDialog( %file ); if( %file $= "" ) { if( %ctrl.bitmap !$= "" ) %file = %ctrl.bitmap; else %file = "tools/materialeditor/gui/unknownImage"; } %file = makeRelativePath( %file, getMainDotCsDir() ); %ctrl.setBitmap( %file ); } //----------------------------------------------------------------------------- function TerrainMaterialDlg::newMat( %this ) { // Create a unique material name. %matName = getUniqueInternalName( "newMaterial", TerrainMaterialSet, true ); // Create the new material. %newMat = new TerrainMaterial() { internalName = %matName; parentGroup = TerrainMaterialDlgNewGroup; }; %newMat.setFileName( "art/terrains/materials.cs" ); // Mark it as dirty and to be saved in the default location. ETerrainMaterialPersistMan.setDirty( %newMat, "art/terrains/materials.cs" ); %matLibTree = %this-->matLibTree; %matLibTree.buildVisibleTree( true ); %item = %matLibTree.findItemByObjectId( %newMat ); %matLibTree.selectItem( %item ); } //----------------------------------------------------------------------------- function TerrainMaterialDlg::deleteMat( %this ) { if( !isObject( %this.activeMat ) ) return; // Cannot delete this material if it is the only one left on the Terrain if ( ( ETerrainEditor.getMaterialCount() == 1 ) && ( ETerrainEditor.getMaterialIndex( %this.activeMat.internalName ) != -1 ) ) { MessageBoxOK( "Error", "Cannot delete this Material, it is the only " @ "Material still in use by the active Terrain." ); return; } TerrainMaterialSet.remove( %this.activeMat ); TerrainMaterialDlgDeleteGroup.add( %this.activeMat ); %matLibTree = %this-->matLibTree; %matLibTree.open( TerrainMaterialSet, false ); %matLibTree.selectItem( 1 ); } //----------------------------------------------------------------------------- function TerrainMaterialDlg::activateMaterialCtrls( %this, %active ) { %parent = %this-->matSettingsParent; %count = %parent.getCount(); for ( %i = 0; %i < %count; %i++ ) %parent.getObject( %i ).setActive( %active ); } //----------------------------------------------------------------------------- function TerrainMaterialTreeCtrl::onSelect( %this, %item ) { TerrainMaterialDlg.setActiveMaterial( %item ); } //----------------------------------------------------------------------------- function TerrainMaterialTreeCtrl::onUnSelect( %this, %item ) { TerrainMaterialDlg.saveDirtyMaterial( %item ); TerrainMaterialDlg.setActiveMaterial( 0 ); } //----------------------------------------------------------------------------- function TerrainMaterialDlg::setActiveMaterial( %this, %mat ) { if ( isObject( %mat ) && %mat.isMemberOfClass( TerrainMaterial ) ) { %this.activeMat = %mat; %this-->matNameCtrl.setText( %mat.internalName ); if (%mat.diffuseMap $= ""){ %this-->baseTexCtrl.setBitmap( "tools/materialeditor/gui/unknownImage" ); }else{ %this-->baseTexCtrl.setBitmap( %mat.diffuseMap ); } if (%mat.detailMap $= ""){ %this-->detailTexCtrl.setBitmap( "tools/materialeditor/gui/unknownImage" ); }else{ %this-->detailTexCtrl.setBitmap( %mat.detailMap ); } if (%mat.macroMap $= ""){ %this-->macroTexCtrl.setBitmap( "tools/materialeditor/gui/unknownImage" ); }else{ %this-->macroTexCtrl.setBitmap( %mat.macroMap ); } if (%mat.normalMap $= ""){ %this-->normTexCtrl.setBitmap( "tools/materialeditor/gui/unknownImage" ); }else{ %this-->normTexCtrl.setBitmap( %mat.normalMap ); } %this-->detSizeCtrl.setText( %mat.detailSize ); %this-->baseSizeCtrl.setText( %mat.diffuseSize ); %this-->detStrengthCtrl.setText( %mat.detailStrength ); %this-->detDistanceCtrl.setText( %mat.detailDistance ); %this-->sideProjectionCtrl.setValue( %mat.useSideProjection ); %this-->parallaxScaleCtrl.setText( %mat.parallaxScale ); %this-->macroSizeCtrl.setText( %mat.macroSize ); %this-->macroStrengthCtrl.setText( %mat.macroStrength ); %this-->macroDistanceCtrl.setText( %mat.macroDistance ); %this.activateMaterialCtrls( true ); } else { %this.activeMat = 0; %this.activateMaterialCtrls( false ); } } //----------------------------------------------------------------------------- function TerrainMaterialDlg::saveDirtyMaterial( %this, %mat ) { // Skip over obviously bad cases. if ( !isObject( %mat ) || !%mat.isMemberOfClass( TerrainMaterial ) ) return; // Read out properties from the dialog. %newName = %this-->matNameCtrl.getText(); if (%this-->baseTexCtrl.bitmap $= "tools/materialeditor/gui/unknownImage"){ %newDiffuse = ""; }else{ %newDiffuse = %this-->baseTexCtrl.bitmap; } if (%this-->normTexCtrl.bitmap $= "tools/materialeditor/gui/unknownImage"){ %newNormal = ""; }else{ %newNormal = %this-->normTexCtrl.bitmap; } if (%this-->detailTexCtrl.bitmap $= "tools/materialeditor/gui/unknownImage"){ %newDetail = ""; }else{ %newDetail = %this-->detailTexCtrl.bitmap; } if (%this-->macroTexCtrl.bitmap $= "tools/materialeditor/gui/unknownImage"){ %newMacro = ""; }else{ %newMacro = %this-->macroTexCtrl.bitmap; } %detailSize = %this-->detSizeCtrl.getText(); %diffuseSize = %this-->baseSizeCtrl.getText(); %detailStrength = %this-->detStrengthCtrl.getText(); %detailDistance = %this-->detDistanceCtrl.getText(); %useSideProjection = %this-->sideProjectionCtrl.getValue(); %parallaxScale = %this-->parallaxScaleCtrl.getText(); %macroSize = %this-->macroSizeCtrl.getText(); %macroStrength = %this-->macroStrengthCtrl.getText(); %macroDistance = %this-->macroDistanceCtrl.getText(); // If no properties of this materials have changed, // return. if ( %mat.internalName $= %newName && %mat.diffuseMap $= %newDiffuse && %mat.normalMap $= %newNormal && %mat.detailMap $= %newDetail && %mat.macroMap $= %newMacro && %mat.detailSize == %detailSize && %mat.diffuseSize == %diffuseSize && %mat.detailStrength == %detailStrength && %mat.detailDistance == %detailDistance && %mat.useSideProjection == %useSideProjection && %mat.macroSize == %macroSize && %mat.macroStrength == %macroStrength && %mat.macroDistance == %macroDistance && %mat.parallaxScale == %parallaxScale ) return; // Make sure the material name is unique. if( %mat.internalName !$= %newName ) { %existingMat = TerrainMaterialSet.findObjectByInternalName( %newName ); if( isObject( %existingMat ) ) { MessageBoxOK( "Error", "There already is a terrain material called '" @ %newName @ "'.", "", "" ); // Reset the name edit control to the old name. %this-->matNameCtrl.setText( %mat.internalName ); } else %mat.setInternalName( %newName ); } %mat.diffuseMap = %newDiffuse; %mat.normalMap = %newNormal; %mat.detailMap = %newDetail; %mat.macroMap = %newMacro; %mat.detailSize = %detailSize; %mat.diffuseSize = %diffuseSize; %mat.detailStrength = %detailStrength; %mat.detailDistance = %detailDistance; %mat.macroSize = %macroSize; %mat.macroStrength = %macroStrength; %mat.macroDistance = %macroDistance; %mat.useSideProjection = %useSideProjection; %mat.parallaxScale = %parallaxScale; // Mark the material as dirty and needing saving. %fileName = %mat.getFileName(); if( %fileName $= "" ) %fileName = "art/terrains/materials.cs"; ETerrainMaterialPersistMan.setDirty( %mat, %fileName ); } //----------------------------------------------------------------------------- function TerrainMaterialDlg::snapshotMaterials( %this ) { if( !isObject( TerrainMaterialDlgSnapshot ) ) new SimGroup( TerrainMaterialDlgSnapshot ); %group = TerrainMaterialDlgSnapshot; %group.clear(); %matCount = TerrainMaterialSet.getCount(); for( %i = 0; %i < %matCount; %i ++ ) { %mat = TerrainMaterialSet.getObject( %i ); if( !isMemberOfClass( %mat.getClassName(), "TerrainMaterial" ) ) continue; %snapshot = new ScriptObject() { parentGroup = %group; material = %mat; internalName = %mat.internalName; diffuseMap = %mat.diffuseMap; normalMap = %mat.normalMap; detailMap = %mat.detailMap; macroMap = %mat.macroMap; detailSize = %mat.detailSize; diffuseSize = %mat.diffuseSize; detailStrength = %mat.detailStrength; detailDistance = %mat.detailDistance; macroSize = %mat.macroSize; macroStrength = %mat.macroStrength; macroDistance = %mat.macroDistance; useSideProjection = %mat.useSideProjection; parallaxScale = %mat.parallaxScale; }; } } //----------------------------------------------------------------------------- function TerrainMaterialDlg::restoreMaterials( %this ) { if( !isObject( TerrainMaterialDlgSnapshot ) ) { error( "TerrainMaterial::restoreMaterials - no snapshot present" ); return; } %count = TerrainMaterialDlgSnapshot.getCount(); for( %i = 0; %i < %count; %i ++ ) { %obj = TerrainMaterialDlgSnapshot.getObject( %i ); %mat = %obj.material; %mat.setInternalName( %obj.internalName ); %mat.diffuseMap = %obj.diffuseMap; %mat.normalMap = %obj.normalMap; %mat.detailMap = %obj.detailMap; %mat.macroMap = %obj.macroMap; %mat.detailSize = %obj.detailSize; %mat.diffuseSize = %obj.diffuseSize; %mat.detailStrength = %obj.detailStrength; %mat.detailDistance = %obj.detailDistance; %mat.macroSize = %obj.macroSize; %mat.macroStrength = %obj.macroStrength; %mat.macroDistance = %obj.macroDistance; %mat.useSideProjection = %obj.useSideProjection; %mat.parallaxScale = %obj.parallaxScale; } } //----------------------------------------------------------------------------- function TerrainMaterialDlg::_selectTextureFileDialog( %this, %defaultFileName ) { if( $Pref::TerrainEditor::LastPath $= "" ) $Pref::TerrainEditor::LastPath = "art/terrains"; %dlg = new OpenFileDialog() { Filters = $TerrainEditor::TextureFileSpec; DefaultPath = $Pref::TerrainEditor::LastPath; DefaultFile = %defaultFileName; ChangePath = false; MustExist = true; }; %ret = %dlg.Execute(); if ( %ret ) { $Pref::TerrainEditor::LastPath = filePath( %dlg.FileName ); %file = %dlg.FileName; } %dlg.delete(); if ( !%ret ) return; %file = filePath(%file) @ "/" @ fileBase(%file); return %file; }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Routing; namespace Microsoft.AspNetCore.Builder.Extensions { public class MapPathMiddlewareTests { private static Task Success(HttpContext context) { context.Response.StatusCode = 200; context.Items["test.PathBase"] = context.Request.PathBase.Value; context.Items["test.Path"] = context.Request.Path.Value; return Task.FromResult<object?>(null); } private static void UseSuccess(IApplicationBuilder app) { app.Run(Success); } private static Task NotImplemented(HttpContext context) { throw new NotImplementedException(); } private static void UseNotImplemented(IApplicationBuilder app) { app.Run(NotImplemented); } [Fact] public void NullArguments_ArgumentNullException() { var builder = new ApplicationBuilder(serviceProvider: null!); var noMiddleware = new ApplicationBuilder(serviceProvider: null!).Build(); var noOptions = new MapOptions(); Assert.Throws<ArgumentNullException>(() => builder.Map("/foo", configuration: null!)); Assert.Throws<ArgumentNullException>(() => new MapMiddleware(noMiddleware, null!)); } [Theory] [InlineData("/foo", "", "/foo")] [InlineData("/foo", "", "/foo/")] [InlineData("/foo", "/Bar", "/foo")] [InlineData("/foo", "/Bar", "/foo/cho")] [InlineData("/foo", "/Bar", "/foo/cho/")] [InlineData("/foo/cho", "/Bar", "/foo/cho")] [InlineData("/foo/cho", "/Bar", "/foo/cho/do")] public async Task PathMatchFunc_BranchTaken(string matchPath, string basePath, string requestPath) { HttpContext context = CreateRequest(basePath, requestPath); var builder = new ApplicationBuilder(serviceProvider: null!); builder.Map(matchPath, UseSuccess); var app = builder.Build(); await app.Invoke(context); Assert.Equal(200, context.Response.StatusCode); Assert.Equal(basePath, context.Request.PathBase.Value); Assert.Equal(requestPath, context.Request.Path.Value); } [Theory] [InlineData("/foo", "", "/foo")] [InlineData("/foo", "", "/foo/")] [InlineData("/foo", "/Bar", "/foo")] [InlineData("/foo", "/Bar", "/foo/cho")] [InlineData("/foo", "/Bar", "/foo/cho/")] [InlineData("/foo/cho", "/Bar", "/foo/cho")] [InlineData("/foo/cho", "/Bar", "/foo/cho/do")] [InlineData("/foo", "", "/Foo")] [InlineData("/foo", "", "/Foo/")] [InlineData("/foo", "/Bar", "/Foo")] [InlineData("/foo", "/Bar", "/Foo/Cho")] [InlineData("/foo", "/Bar", "/Foo/Cho/")] [InlineData("/foo/cho", "/Bar", "/Foo/Cho")] [InlineData("/foo/cho", "/Bar", "/Foo/Cho/do")] public async Task PathMatchAction_BranchTaken(string matchPath, string basePath, string requestPath) { HttpContext context = CreateRequest(basePath, requestPath); var builder = new ApplicationBuilder(serviceProvider: null!); builder.Map(matchPath, subBuilder => subBuilder.Run(Success)); var app = builder.Build(); await app.Invoke(context); Assert.Equal(200, context.Response.StatusCode); Assert.Equal(string.Concat(basePath, requestPath.AsSpan(0, matchPath.Length)), (string)context.Items["test.PathBase"]!); Assert.Equal(requestPath.Substring(matchPath.Length), context.Items["test.Path"]); } [Theory] [InlineData("/foo", "", "/foo")] [InlineData("/foo", "", "/foo/")] [InlineData("/foo", "/Bar", "/foo")] [InlineData("/foo", "/Bar", "/foo/cho")] [InlineData("/foo", "/Bar", "/foo/cho/")] [InlineData("/foo/cho", "/Bar", "/foo/cho")] [InlineData("/foo/cho", "/Bar", "/foo/cho/do")] [InlineData("/foo", "", "/Foo")] [InlineData("/foo", "", "/Foo/")] [InlineData("/foo", "/Bar", "/Foo")] [InlineData("/foo", "/Bar", "/Foo/Cho")] [InlineData("/foo", "/Bar", "/Foo/Cho/")] [InlineData("/foo/cho", "/Bar", "/Foo/Cho")] [InlineData("/foo/cho", "/Bar", "/Foo/Cho/do")] public async Task PathMatchAction_BranchTaken_WithPreserveMatchedPathSegment(string matchPath, string basePath, string requestPath) { HttpContext context = CreateRequest(basePath, requestPath); var builder = new ApplicationBuilder(serviceProvider: null!); builder.Map(matchPath, true, subBuilder => subBuilder.Run(Success)); var app = builder.Build(); await app.Invoke(context); Assert.Equal(200, context.Response.StatusCode); Assert.Equal(basePath, (string)context.Items["test.PathBase"]!); Assert.Equal(requestPath, context.Items["test.Path"]); } [Theory] [InlineData("/")] [InlineData("/foo/")] [InlineData("/foo/cho/")] public void MatchPathWithTrailingSlashThrowsException(string matchPath) { Assert.Throws<ArgumentException>(() => new ApplicationBuilder(serviceProvider: null!).Map(matchPath, map => { }).Build()); } [Theory] [InlineData("/foo", "", "")] [InlineData("/foo", "/bar", "")] [InlineData("/foo", "", "/bar")] [InlineData("/foo", "/foo", "")] [InlineData("/foo", "/foo", "/bar")] [InlineData("/foo", "", "/bar/foo")] [InlineData("/foo/bar", "/foo", "/bar")] public async Task PathMismatchFunc_PassedThrough(string matchPath, string basePath, string requestPath) { HttpContext context = CreateRequest(basePath, requestPath); var builder = new ApplicationBuilder(serviceProvider: null!); builder.Map(matchPath, UseNotImplemented); builder.Run(Success); var app = builder.Build(); await app.Invoke(context); Assert.Equal(200, context.Response.StatusCode); Assert.Equal(basePath, context.Request.PathBase.Value); Assert.Equal(requestPath, context.Request.Path.Value); } [Theory] [InlineData("/foo", "", "")] [InlineData("/foo", "/bar", "")] [InlineData("/foo", "", "/bar")] [InlineData("/foo", "/foo", "")] [InlineData("/foo", "/foo", "/bar")] [InlineData("/foo", "", "/bar/foo")] [InlineData("/foo/bar", "/foo", "/bar")] public async Task PathMismatchAction_PassedThrough(string matchPath, string basePath, string requestPath) { HttpContext context = CreateRequest(basePath, requestPath); var builder = new ApplicationBuilder(serviceProvider: null!); builder.Map(matchPath, UseNotImplemented); builder.Run(Success); var app = builder.Build(); await app.Invoke(context); Assert.Equal(200, context.Response.StatusCode); Assert.Equal(basePath, context.Request.PathBase.Value); Assert.Equal(requestPath, context.Request.Path.Value); } [Fact] public async Task ChainedRoutes_Success() { var builder = new ApplicationBuilder(serviceProvider: null!); builder.Map("/route1", map => { map.Map("/subroute1", UseSuccess); map.Run(NotImplemented); }); builder.Map("/route2/subroute2", UseSuccess); var app = builder.Build(); HttpContext context = CreateRequest(string.Empty, "/route1"); await Assert.ThrowsAsync<NotImplementedException>(() => app.Invoke(context)); context = CreateRequest(string.Empty, "/route1/subroute1"); await app.Invoke(context); Assert.Equal(200, context.Response.StatusCode); Assert.Equal(string.Empty, context.Request.PathBase.Value); Assert.Equal("/route1/subroute1", context.Request.Path.Value); context = CreateRequest(string.Empty, "/route2"); await app.Invoke(context); Assert.Equal(404, context.Response.StatusCode); Assert.Equal(string.Empty, context.Request.PathBase.Value); Assert.Equal("/route2", context.Request.Path.Value); context = CreateRequest(string.Empty, "/route2/subroute2"); await app.Invoke(context); Assert.Equal(200, context.Response.StatusCode); Assert.Equal(string.Empty, context.Request.PathBase.Value); Assert.Equal("/route2/subroute2", context.Request.Path.Value); context = CreateRequest(string.Empty, "/route2/subroute2/subsub2"); await app.Invoke(context); Assert.Equal(200, context.Response.StatusCode); Assert.Equal(string.Empty, context.Request.PathBase.Value); Assert.Equal("/route2/subroute2/subsub2", context.Request.Path.Value); } [Fact] public void ApplicationBuilderMapOverloadPreferredOverEndpointBuilderGivenStringPathAndImplicitLambdaParameterType() { var mockWebApplication = new MockWebApplication(); mockWebApplication.Map("/foo", app => { }); Assert.True(mockWebApplication.UseCalled); } [Fact] public void ApplicationBuilderMapOverloadPreferredOverEndpointBuilderGivenStringPathAndExplicitLambdaParameterType() { var mockWebApplication = new MockWebApplication(); mockWebApplication.Map("/foo", (IApplicationBuilder app) => { }); Assert.True(mockWebApplication.UseCalled); } private HttpContext CreateRequest(string basePath, string requestPath) { HttpContext context = new DefaultHttpContext(); context.Request.PathBase = new PathString(basePath); context.Request.Path = new PathString(requestPath); return context; } private class MockWebApplication : IApplicationBuilder, IEndpointRouteBuilder { public bool UseCalled { get; set; } public IServiceProvider ApplicationServices { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public IFeatureCollection ServerFeatures => throw new NotImplementedException(); public IDictionary<string, object?> Properties => throw new NotImplementedException(); public IServiceProvider ServiceProvider => throw new NotImplementedException(); public ICollection<EndpointDataSource> DataSources => throw new NotImplementedException(); public IApplicationBuilder CreateApplicationBuilder() => throw new NotImplementedException(); public IApplicationBuilder New() => this; public IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware) { UseCalled = true; return this; } public RequestDelegate Build() { return context => Task.CompletedTask; } } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the devicefarm-2015-06-23.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.DeviceFarm.Model { /// <summary> /// Represents an app on a set of devices with a specific test and configuration. /// </summary> public partial class Run { private string _arn; private BillingMethod _billingMethod; private int? _completedJobs; private Counters _counters; private DateTime? _created; private string _message; private string _name; private DevicePlatform _platform; private ExecutionResult _result; private DateTime? _started; private ExecutionStatus _status; private DateTime? _stopped; private int? _totalJobs; private TestType _type; /// <summary> /// Gets and sets the property Arn. /// <para> /// The run's ARN. /// </para> /// </summary> public string Arn { get { return this._arn; } set { this._arn = value; } } // Check to see if Arn property is set internal bool IsSetArn() { return this._arn != null; } /// <summary> /// Gets and sets the property BillingMethod. /// <para> /// Specifies the billing method for a test run: <code>metered</code> or <code>unmetered</code>. /// If the parameter is not specified, the default value is <code>unmetered</code>. /// </para> /// </summary> public BillingMethod BillingMethod { get { return this._billingMethod; } set { this._billingMethod = value; } } // Check to see if BillingMethod property is set internal bool IsSetBillingMethod() { return this._billingMethod != null; } /// <summary> /// Gets and sets the property CompletedJobs. /// <para> /// The total number of completed jobs. /// </para> /// </summary> public int CompletedJobs { get { return this._completedJobs.GetValueOrDefault(); } set { this._completedJobs = value; } } // Check to see if CompletedJobs property is set internal bool IsSetCompletedJobs() { return this._completedJobs.HasValue; } /// <summary> /// Gets and sets the property Counters. /// <para> /// The run's result counters. /// </para> /// </summary> public Counters Counters { get { return this._counters; } set { this._counters = value; } } // Check to see if Counters property is set internal bool IsSetCounters() { return this._counters != null; } /// <summary> /// Gets and sets the property Created. /// <para> /// When the run was created. /// </para> /// </summary> public DateTime Created { get { return this._created.GetValueOrDefault(); } set { this._created = value; } } // Check to see if Created property is set internal bool IsSetCreated() { return this._created.HasValue; } /// <summary> /// Gets and sets the property Message. /// <para> /// A message about the run's result. /// </para> /// </summary> public string Message { get { return this._message; } set { this._message = value; } } // Check to see if Message property is set internal bool IsSetMessage() { return this._message != null; } /// <summary> /// Gets and sets the property Name. /// <para> /// The run's name. /// </para> /// </summary> public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property Platform. /// <para> /// The run's platform. /// </para> /// /// <para> /// Allowed values include: /// </para> /// <ul> <li> /// <para> /// ANDROID: The Android platform. /// </para> /// </li> <li> /// <para> /// IOS: The iOS platform. /// </para> /// </li> </ul> /// </summary> public DevicePlatform Platform { get { return this._platform; } set { this._platform = value; } } // Check to see if Platform property is set internal bool IsSetPlatform() { return this._platform != null; } /// <summary> /// Gets and sets the property Result. /// <para> /// The run's result. /// </para> /// /// <para> /// Allowed values include: /// </para> /// <ul> <li> /// <para> /// ERRORED: An error condition. /// </para> /// </li> <li> /// <para> /// FAILED: A failed condition. /// </para> /// </li> <li> /// <para> /// SKIPPED: A skipped condition. /// </para> /// </li> <li> /// <para> /// STOPPED: A stopped condition. /// </para> /// </li> <li> /// <para> /// PASSED: A passing condition. /// </para> /// </li> <li> /// <para> /// PENDING: A pending condition. /// </para> /// </li> <li> /// <para> /// WARNED: A warning condition. /// </para> /// </li> </ul> /// </summary> public ExecutionResult Result { get { return this._result; } set { this._result = value; } } // Check to see if Result property is set internal bool IsSetResult() { return this._result != null; } /// <summary> /// Gets and sets the property Started. /// <para> /// The run's start time. /// </para> /// </summary> public DateTime Started { get { return this._started.GetValueOrDefault(); } set { this._started = value; } } // Check to see if Started property is set internal bool IsSetStarted() { return this._started.HasValue; } /// <summary> /// Gets and sets the property Status. /// <para> /// The run's status. /// </para> /// /// <para> /// Allowed values include: /// </para> /// <ul> <li> /// <para> /// COMPLETED: A completed status. /// </para> /// </li> <li> /// <para> /// PENDING: A pending status. /// </para> /// </li> <li> /// <para> /// PROCESSING: A processing status. /// </para> /// </li> <li> /// <para> /// RUNNING: A running status. /// </para> /// </li> <li> /// <para> /// SCHEDULING: A scheduling status. /// </para> /// </li> </ul> /// </summary> public ExecutionStatus Status { get { return this._status; } set { this._status = value; } } // Check to see if Status property is set internal bool IsSetStatus() { return this._status != null; } /// <summary> /// Gets and sets the property Stopped. /// <para> /// The run's stop time. /// </para> /// </summary> public DateTime Stopped { get { return this._stopped.GetValueOrDefault(); } set { this._stopped = value; } } // Check to see if Stopped property is set internal bool IsSetStopped() { return this._stopped.HasValue; } /// <summary> /// Gets and sets the property TotalJobs. /// <para> /// The total number of jobs for the run. /// </para> /// </summary> public int TotalJobs { get { return this._totalJobs.GetValueOrDefault(); } set { this._totalJobs = value; } } // Check to see if TotalJobs property is set internal bool IsSetTotalJobs() { return this._totalJobs.HasValue; } /// <summary> /// Gets and sets the property Type. /// <para> /// The run's type. /// </para> /// /// <para> /// Must be one of the following values: /// </para> /// <ul> <li> /// <para> /// BUILTIN_FUZZ: The built-in fuzz type. /// </para> /// </li> <li> /// <para> /// BUILTIN_EXPLORER: For Android, an app explorer that will traverse an Android app, /// interacting with it and capturing screenshots at the same time. /// </para> /// </li> <li> /// <para> /// APPIUM_JAVA_JUNIT: The Appium Java JUnit type. /// </para> /// </li> <li> /// <para> /// APPIUM_JAVA_TESTNG: The Appium Java TestNG type. /// </para> /// </li> <li> /// <para> /// CALABASH: The Calabash type. /// </para> /// </li> <li> /// <para> /// INSTRUMENTATION: The Instrumentation type. /// </para> /// </li> <li> /// <para> /// UIAUTOMATION: The uiautomation type. /// </para> /// </li> <li> /// <para> /// UIAUTOMATOR: The uiautomator type. /// </para> /// </li> <li> /// <para> /// XCTEST: The XCode test type. /// </para> /// </li> </ul> /// </summary> public TestType Type { get { return this._type; } set { this._type = value; } } // Check to see if Type property is set internal bool IsSetType() { return this._type != null; } } }
// Copyright (c) Rotorz Limited. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root. using System; using System.Collections.Generic; namespace Rotorz.Tile { /// <summary> /// Two-dimensional index of tile in a tile system. /// </summary> [Serializable] public struct TileIndex : IEquatable<TileIndex> { /// <summary> /// Index of first tile in system. /// </summary> public static readonly TileIndex zero = new TileIndex(); /// <summary> /// Represents an invalid tile index. /// </summary> public static readonly TileIndex invalid = new TileIndex(-1, -1); #region Equality Comparer private static readonly IEqualityComparer<TileIndex> s_EqualityComparer = new TileIndexEqualityComparer(); /// <summary> /// Gets the <see cref="IEqualityComparer{T}"/> that should be passed to generic /// collections of <see cref="TileIndex"/> values instead of the default <see cref="EqualityComparer"/> /// implementation when deploying to platforms that require AOT. /// </summary> /// <remarks> /// <para>The <see cref="System.ExecutionEngineException"/> exception is thrown when /// attempting to construct a <see cref="HashSet{T}"/> or <see cref="Dictionary{TKey, TValue}"/> /// with <see cref="TileIndex"/> values on iOS platforms since <see cref="EqualityComparer"/> /// is unable to generate its comparer at runtime.</para> /// </remarks> /// <example> /// <para>Example construction of a <see cref="HashSet{T}"/> instance using /// <see cref="TileIndex.EqualityComparer"/>:</para> /// <code language="csharp"><![CDATA[ /// var set = new HashSet<TileIndex>(TileIndex.EqualityComparer); /// ]]></code> /// </example> public static IEqualityComparer<TileIndex> EqualityComparer { get { return s_EqualityComparer; } } #endregion /// <summary> /// Zero-based row index. /// </summary> public int row; /// <summary> /// Zero-based column index. /// </summary> public int column; /// <summary> /// Initializes a new instance of the <see cref="Rotorz.Tile.TileIndex"/> struct. /// </summary> /// <param name="row">Zero-based row index.</param> /// <param name="column">Zero-based column index.</param> public TileIndex(int row, int column) { this.row = row; this.column = column; } /// <summary> /// Returns a <see cref="System.String"/> that represents the current <see cref="Rotorz.Tile.TileIndex"/>. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents the current <see cref="Rotorz.Tile.TileIndex"/>. /// </returns> public override string ToString() { return string.Format("row: {0}, column: {1}", this.row, this.column); } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to the /// current <see cref="Rotorz.Tile.TileIndex"/>. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with the current /// <see cref="Rotorz.Tile.TileIndex"/>.</param> /// <returns> /// A value of <c>true</c> if the specified <see cref="System.Object"/> is equal /// to the current <see cref="Rotorz.Tile.TileIndex"/>; otherwise <c>false</c>. /// </returns> public override bool Equals(object obj) { if (!(obj is TileIndex)) { return false; } TileIndex other = (TileIndex)obj; return this.row == other.row & this.column == other.column; } /// <summary> /// Determines whether the specified <see cref="Rotorz.Tile.TileIndex"/> is equal to /// the current <see cref="Rotorz.Tile.TileIndex"/>. /// </summary> /// <param name="other">The <see cref="Rotorz.Tile.TileIndex"/> to compare with the /// current <see cref="Rotorz.Tile.TileIndex"/>.</param> /// <returns> /// A value of <c>true</c> if the specified <see cref="Rotorz.Tile.TileIndex"/> is /// equal to the current <see cref="Rotorz.Tile.TileIndex"/>; otherwise <c>false</c>. /// </returns> public bool Equals(TileIndex other) { return this.row == other.row & this.column == other.column; } /// <summary> /// Serves as a hash function for a <see cref="Rotorz.Tile.TileIndex"/> object. /// </summary> /// <returns> /// A hash code for this instance that is suitable for use in hashing algorithms /// and data structures such as a hash table. /// </returns> public override int GetHashCode() { return this.row ^ this.column; } /// <summary> /// Determines whether a specified instance of <see cref="TileIndex"/> is equal to /// another specified <see cref="TileIndex"/>. /// </summary> /// <param name="lhs">The first <see cref="TileIndex"/> to compare.</param> /// <param name="rhs">The second <see cref="TileIndex"/> to compare.</param> /// <returns> /// A value of <c>true</c> if <c>left</c> and <c>right</c> are equal; otherwise /// <c>false</c>. /// </returns> public static bool operator ==(TileIndex lhs, TileIndex rhs) { return lhs.row == rhs.row & lhs.column == rhs.column; } /// <summary> /// Determines whether a specified instance of <see cref="TileIndex"/> is not equal /// to another specified <see cref="TileIndex"/>. /// </summary> /// <param name="lhs">The first <see cref="TileIndex"/> to compare.</param> /// <param name="rhs">The second <see cref="TileIndex"/> to compare.</param> /// <returns> /// A value of <c>true</c> if <c>left</c> and <c>right</c> are not equal; /// otherwise <c>false</c>. /// </returns> public static bool operator !=(TileIndex lhs, TileIndex rhs) { return lhs.row != rhs.row | lhs.column != rhs.column; } /// <summary> /// Add row and column indices of two <see cref="TileIndex"/> arguments. /// </summary> /// <param name="lhs">Left <see cref="TileIndex"/> operand.</param> /// <param name="rhs">Right <see cref="TileIndex"/> operand.</param> /// <returns> /// Sum of input <see cref="TileIndex"/> operands. /// </returns> public static TileIndex operator +(TileIndex lhs, TileIndex rhs) { lhs.row += rhs.row; lhs.column += rhs.column; return lhs; } /// <summary> /// Subtract row and column indices of two <see cref="TileIndex"/> arguments. /// </summary> /// <param name="lhs">Left <see cref="TileIndex"/> operand.</param> /// <param name="rhs">Right <see cref="TileIndex"/> operand.</param> /// <returns> /// Difference between input <see cref="TileIndex"/> operands. /// </returns> public static TileIndex operator -(TileIndex lhs, TileIndex rhs) { lhs.row -= rhs.row; lhs.column -= rhs.column; return lhs; } /// <summary> /// Negate row and column indices of <see cref="TileIndex"/> argument. /// </summary> /// <param name="value">Input value.</param> /// <returns> /// Negated value. /// </returns> public static TileIndex operator -(TileIndex value) { value.row = -value.row; value.column = -value.column; return value; } } /// <summary> /// An explicit implementation of <see cref="IEqualityComparer{TileIndex}"/> which /// should be used instead of <see cref="EqualityComparer.Default"/> when deploying /// to a platform that requires AOT. /// </summary> internal sealed class TileIndexEqualityComparer : IEqualityComparer<TileIndex> { public bool Equals(TileIndex x, TileIndex y) { return x.Equals(y); } public int GetHashCode(TileIndex obj) { return obj.GetHashCode(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Debug = System.Diagnostics.Debug; using Interlocked = System.Threading.Interlocked; namespace System.Xml.Linq { /// <summary> /// This is a thread-safe hash table which maps string keys to values of type TValue. It is assumed that the string key is embedded in the hashed value /// and can be extracted via a call to ExtractKeyDelegate (in order to save space and allow cleanup of key if value is released due to a WeakReference /// TValue releasing its target). /// </summary> /// <remarks> /// All methods on this class are thread-safe. /// /// When the hash table fills up, it is necessary to resize it and rehash all contents. Because this can be expensive, /// a lock is taken, and one thread is responsible for the resize. Other threads which need to add values must wait /// for the resize to be complete. /// /// Thread-Safety Notes /// =================== /// /// 1. Because performance and scalability are such a concern with the global name table, I have avoided the use of /// BIFALOs (Big Fat Locks). Instead, I use CompareExchange, Interlocked.Increment, memory barriers, atomic state objects, /// etc. to avoid locks. Any changes to code which accesses these variables should be carefully reviewed and tested, /// as it can be *very* tricky. In particular, if you don't understand the CLR memory model or if you don't know /// what a memory barrier is, DON'T attempt to modify this code. A good discussion of these topics can be found at /// <![CDATA[http://discuss.develop.com/archives/wa.exe?A2=ind0203B&L=DOTNET&P=R375]]>. /// /// 2. Because I am not sure if the CLR spec has changed since versions 1.0/1.1, I am assuming the weak memory model that /// is described in the ECMA spec, in which normal writes can be reordered. This means I must introduce more memory /// barriers than otherwise would be necessary. /// /// 3. There are several thread-safety concepts and patterns I utilize in this code: /// a. Publishing -- There are a small number of places where state is exposed, or published, to multiple threads. /// These places are marked with the comment "PUBLISH", and are key locations to consider when /// reviewing the code for thread-safety. /// /// b. Immutable objects -- Immutable objects initialize their fields once in their constructor and then never modify /// them again. As long as care is taken to ensure that initial field values are visible to /// other threads before publishing the immutable object itself, immutable objects are /// completely thread-safe. /// /// c. Atomic state objects -- Locks typically are taken when several pieces of state must be updated atomically. In /// other words, there is a window in which state is inconsistent, and that window must /// be protected from view by locking. However, if a new object is created each time state /// changes (or state changes substantially), then during creation the new object is only /// visible to a single thread. Once construction is complete, an assignment (guaranteed /// atomic) can replace the old state object with the new state object, thus publishing a /// consistent view to all threads. /// /// d. Retry -- When several threads contend over shared state which only one is allowed to possess, it is possible /// to avoid locking by repeatedly attempting to acquire the shared state. The CompareExchange method /// is useful for atomically ensuring that only one thread succeeds, and other threads are notified that /// they must retry. /// /// 4. All variables which can be written by multiple threads are marked "SHARED STATE". /// </remarks> internal sealed class XHashtable<TValue> { private XHashtableState state; // SHARED STATE: Contains all XHashtable state, so it can be atomically swapped when resizes occur private const int StartingHash = (5381 << 16) + 5381; // Starting hash code value for string keys to be hashed /// <summary> /// Prototype of function which is called to extract a string key value from a hashed value. /// Returns null if the hashed value is invalid (e.g. value has been released due to a WeakReference TValue being cleaned up). /// </summary> public delegate string ExtractKeyDelegate(TValue value); /// <summary> /// Construct a new XHashtable with the specified starting capacity. /// </summary> public XHashtable(ExtractKeyDelegate extractKey, int capacity) { state = new XHashtableState(extractKey, capacity); } /// <summary> /// Get an existing value from the hash table. Return false if no such value exists. /// </summary> public bool TryGetValue(string key, int index, int count, out TValue value) { return state.TryGetValue(key, index, count, out value); } /// <summary> /// Add a value to the hash table, hashed based on a string key embedded in it. Return the added value (may be a different object than "value"). /// </summary> public TValue Add(TValue value) { TValue newValue; // Loop until value is in hash table while (true) { // Add new value // XHashtableState.TryAdd returns false if hash table is not big enough if (state.TryAdd(value, out newValue)) return newValue; // PUBLISH (state) // Hash table was not big enough, so resize it. // We only want one thread to perform a resize, as it is an expensive operation // First thread will perform resize; waiting threads will call Resize(), but should immediately // return since there will almost always be space in the hash table resized by the first thread. lock (this) { XHashtableState newState = state.Resize(); // Use memory barrier to ensure that the resized XHashtableState object is fully constructed before it is assigned #if !SILVERLIGHT Thread.MemoryBarrier(); #else // SILVERLIGHT // According to this document "http://my/sites/juddhall/ThreadingFeatureCrew/Shared Documents/System.Threading - FX Audit Proposal.docx" // The MemoryBarrier method usage is busted (mostly - don't know about ours) and should be removed. // Replacing with Interlocked.CompareExchange for now (with no effect) // which will do a very similar thing to MemoryBarrier (it's just slower) System.Threading.Interlocked.CompareExchange<XHashtableState>(ref state, null, null); #endif // SILVERLIGHT state = newState; } } } /// <summary> /// This class contains all the hash table state. Rather than creating a bucket object, buckets are structs /// packed into an array. Buckets with the same truncated hash code are linked into lists, so that collisions /// can be disambiguated. /// </summary> /// <remarks> /// Note that the "buckets" and "entries" arrays are never themselves written by multiple threads. Instead, the /// *contents* of the array are written by multiple threads. Resizing the hash table does not modify these variables, /// or even modify the contents of these variables. Instead, resizing makes an entirely new XHashtableState object /// in which all entries are rehashed. This strategy allows reader threads to continue finding values in the "old" /// XHashtableState, while writer threads (those that need to add a new value to the table) are blocked waiting for /// the resize to complete. /// </remarks> private sealed class XHashtableState { private int[] buckets; // Buckets contain indexes into entries array (bucket values are SHARED STATE) private Entry[] entries; // Entries contain linked lists of buckets (next pointers are SHARED STATE) private int numEntries; // SHARED STATE: Current number of entries (including orphaned entries) private ExtractKeyDelegate extractKey; // Delegate called in order to extract string key embedded in hashed TValue private const int EndOfList = 0; // End of linked list marker private const int FullList = -1; // Indicates entries should not be added to end of linked list /// <summary> /// Construct a new XHashtableState object with the specified capacity. /// </summary> public XHashtableState(ExtractKeyDelegate extractKey, int capacity) { Debug.Assert((capacity & (capacity - 1)) == 0, "capacity must be a power of 2"); Debug.Assert(extractKey != null, "extractKey may not be null"); // Initialize hash table data structures, with specified maximum capacity buckets = new int[capacity]; entries = new Entry[capacity]; // Save delegate this.extractKey = extractKey; } /// <summary> /// If this table is not full, then just return "this". Otherwise, create and return a new table with /// additional capacity, and rehash all values in the table. /// </summary> public XHashtableState Resize() { // No need to resize if there are open entries if (numEntries < buckets.Length) return this; int newSize = 0; // Determine capacity of resized hash table by first counting number of valid, non-orphaned entries // As this count proceeds, close all linked lists so that no additional entries can be added to them for (int bucketIdx = 0; bucketIdx < buckets.Length; bucketIdx++) { int entryIdx = buckets[bucketIdx]; if (entryIdx == EndOfList) { // Replace EndOfList with FullList, so that any threads still attempting to add will be forced to resize entryIdx = Interlocked.CompareExchange(ref buckets[bucketIdx], FullList, EndOfList); } // Loop until we've guaranteed that the list has been counted and closed to further adds while (entryIdx > EndOfList) { // Count each valid entry if (extractKey(entries[entryIdx].Value) != null) newSize++; if (entries[entryIdx].Next == EndOfList) { // Replace EndOfList with FullList, so that any threads still attempting to add will be forced to resize entryIdx = Interlocked.CompareExchange(ref entries[entryIdx].Next, FullList, EndOfList); } else { // Move to next entry in the list entryIdx = entries[entryIdx].Next; } } Debug.Assert(entryIdx == EndOfList, "Resize() should only be called by one thread"); } // Double number of valid entries; if result is less than current capacity, then use current capacity if (newSize < buckets.Length / 2) { newSize = buckets.Length; } else { newSize = buckets.Length * 2; if (newSize < 0) throw new OverflowException(); } // Create new hash table with additional capacity XHashtableState newHashtable = new XHashtableState(extractKey, newSize); // Rehash names (TryAdd will always succeed, since we won't fill the new table) // Do not simply walk over entries and add them to table, as that would add orphaned // entries. Instead, walk the linked lists and add each name. for (int bucketIdx = 0; bucketIdx < buckets.Length; bucketIdx++) { int entryIdx = buckets[bucketIdx]; TValue newValue; while (entryIdx > EndOfList) { newHashtable.TryAdd(entries[entryIdx].Value, out newValue); entryIdx = entries[entryIdx].Next; } Debug.Assert(entryIdx == FullList, "Linked list should have been closed when it was counted"); } return newHashtable; } /// <summary> /// Attempt to find "key" in the table. If the key exists, return the associated value in "value" and /// return true. Otherwise return false. /// </summary> public bool TryGetValue(string key, int index, int count, out TValue value) { int hashCode = ComputeHashCode(key, index, count); int entryIndex = 0; // If a matching entry is found, return its value if (FindEntry(hashCode, key, index, count, ref entryIndex)) { value = entries[entryIndex].Value; return true; } // No matching entry found, so return false value = default(TValue); return false; } /// <summary> /// Attempt to add "value" to the table, hashed by an embedded string key. If a value having the same key already exists, /// then return the existing value in "newValue". Otherwise, return the newly added value in "newValue". /// /// If the hash table is full, return false. Otherwise, return true. /// </summary> public bool TryAdd(TValue value, out TValue newValue) { int newEntry, entryIndex; string key; int hashCode; // Assume "value" will be added and returned as "newValue" newValue = value; // Extract the key from the value. If it's null, then value is invalid and does not need to be added to table. key = extractKey(value); if (key == null) return true; // Compute hash code over entire length of key hashCode = ComputeHashCode(key, 0, key.Length); // Assume value is not yet in the hash table, and prepare to add it (if table is full, return false). // Use the entry index returned from Increment, which will never be zero, as zero conflicts with EndOfList. // Although this means that the first entry will never be used, it avoids the need to initialize all // starting buckets to the EndOfList value. newEntry = Interlocked.Increment(ref numEntries); if (newEntry < 0 || newEntry >= buckets.Length) return false; entries[newEntry].Value = value; entries[newEntry].HashCode = hashCode; // Ensure that all writes to the entry can't be reordered past this barrier (or other threads might see new entry // in list before entry has been initialized!). #if !SILVERLIGHT Thread.MemoryBarrier(); #else // SILVERLIGHT // According to this document "http://my/sites/juddhall/ThreadingFeatureCrew/Shared Documents/System.Threading - FX Audit Proposal.docx" // The MemoryBarrier method usage is busted (mostly - don't know about ours) and should be removed. // Replacing with Interlocked.CompareExchange for now (with no effect) // which will do a very similar thing to MemoryBarrier (it's just slower) System.Threading.Interlocked.CompareExchange<Entry[]>(ref entries, null, null); #endif // SILVERLIGHT // Loop until a matching entry is found, a new entry is added, or linked list is found to be full entryIndex = 0; while (!FindEntry(hashCode, key, 0, key.Length, ref entryIndex)) { // PUBLISH (buckets slot) // No matching entry found, so add the new entry to the end of the list ("entryIndex" is index of last entry) if (entryIndex == 0) entryIndex = Interlocked.CompareExchange(ref buckets[hashCode & (buckets.Length - 1)], newEntry, EndOfList); else entryIndex = Interlocked.CompareExchange(ref entries[entryIndex].Next, newEntry, EndOfList); // Return true only if the CompareExchange succeeded (happens when replaced value is EndOfList). // Return false if the linked list turned out to be full because another thread is currently resizing // the hash table. In this case, entries[newEntry] is orphaned (not part of any linked list) and the // Add needs to be performed on the new hash table. Otherwise, keep looping, looking for new end of list. if (entryIndex <= EndOfList) return entryIndex == EndOfList; } // Another thread already added the value while this thread was trying to add, so return that instance instead. // Note that entries[newEntry] will be orphaned (not part of any linked list) in this case newValue = entries[entryIndex].Value; return true; } /// <summary> /// Searches a linked list of entries, beginning at "entryIndex". If "entryIndex" is 0, then search starts at a hash bucket instead. /// Each entry in the list is matched against the (hashCode, key, index, count) key. If a matching entry is found, then its /// entry index is returned in "entryIndex" and true is returned. If no matching entry is found, then the index of the last entry /// in the list (or 0 if list is empty) is returned in "entryIndex" and false is returned. /// </summary> /// <remarks> /// This method has the side effect of removing invalid entries from the list as it is traversed. /// </remarks> private bool FindEntry(int hashCode, string key, int index, int count, ref int entryIndex) { int previousIndex = entryIndex; int currentIndex; // Set initial value of currentIndex to index of the next entry following entryIndex if (previousIndex == 0) currentIndex = buckets[hashCode & (buckets.Length - 1)]; else currentIndex = previousIndex; // Loop while not at end of list while (currentIndex > EndOfList) { // Check for matching hash code, then matching key if (entries[currentIndex].HashCode == hashCode) { string keyCompare = extractKey(entries[currentIndex].Value); // If the key is invalid, then attempt to remove the current entry from the linked list. // This is thread-safe in the case where the Next field points to another entry, since once a Next field points // to another entry, it will never be modified to be EndOfList or FullList. if (keyCompare == null) { if (entries[currentIndex].Next > EndOfList) { // PUBLISH (buckets slot or entries slot) // Entry is invalid, so modify previous entry to point to its next entry entries[currentIndex].Value = default(TValue); currentIndex = entries[currentIndex].Next; if (previousIndex == 0) buckets[hashCode & (buckets.Length - 1)] = currentIndex; else entries[previousIndex].Next = currentIndex; continue; } } else { // Valid key, so compare keys if (count == keyCompare.Length && string.CompareOrdinal(key, index, keyCompare, 0, count) == 0) { // Found match, so return true and matching entry in list entryIndex = currentIndex; return true; } } } // Move to next entry previousIndex = currentIndex; currentIndex = entries[currentIndex].Next; } // Return false and last entry in list entryIndex = previousIndex; return false; } /// <summary> /// Compute hash code for a string key (index, count substring of "key"). The algorithm used is the same on used in NameTable.cs in System.Xml. /// </summary> private static int ComputeHashCode(string key, int index, int count) { int hashCode = StartingHash; int end = index + count; Debug.Assert(key != null, "key should have been checked previously for null"); // Hash the key for (int i = index; i < end; i++) hashCode += (hashCode << 7) ^ key[i]; // Mix up hash code a bit more and clear the sign bit. This code was taken from NameTable.cs in System.Xml. hashCode -= hashCode >> 17; hashCode -= hashCode >> 11; hashCode -= hashCode >> 5; return hashCode & 0x7FFFFFFF; } /// <summary> /// Hash table entry. The "Value" and "HashCode" fields are filled during initialization, and are never changed. The "Next" /// field is updated when a new entry is chained to this one, and therefore care must be taken to ensure that updates to /// this field are thread-safe. /// </summary> private struct Entry { public TValue Value; // Hashed value public int HashCode; // Hash code of string key (equal to extractKey(Value).GetHashCode()) public int Next; // SHARED STATE: Points to next entry in linked list } } } }
/* Matali Physics Demo Copyright (c) 2013 KOMIRES Sp. z o. o. */ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics.OpenGL; using Komires.MataliPhysics; namespace MataliPhysicsDemo { /// <summary> /// This is the main type for your game /// </summary> public class DefaultShapes { Demo demo; PhysicsScene scene; public DefaultShapes(Demo demo) { this.demo = demo; } public void Initialize(PhysicsScene scene) { this.scene = scene; } public static void CreateShapes(Demo demo, PhysicsScene scene) { TriangleMesh triangleMesh = null; ShapePrimitive shapePrimitive = null; Shape shape = null; triangleMesh = scene.Factory.TriangleMeshManager.Create("TorusMesh1"); triangleMesh.CreateTorusY(10, 15, 3.0f, 1.0f); if (!demo.Meshes.ContainsKey("TorusMesh1")) demo.Meshes.Add("TorusMesh1", new DemoMesh(demo, triangleMesh, demo.Textures["Default"], Vector2.One, true, true, true, false, true, CullFaceMode.Back, false, false)); scene.Factory.CreatePhysicsObjectsFromConcave("ConcaveTorus1", triangleMesh); scene.Factory.CreatePhysicsObjectsFromConcave("ConcaveTorus2", triangleMesh); shapePrimitive = scene.Factory.ShapePrimitiveManager.Create("ConvexTorus1"); shapePrimitive.CreateConvexHull(triangleMesh); shape = scene.Factory.ShapeManager.Create("ConvexTorus1"); shape.Set(shapePrimitive, Matrix4.Identity, 0.0f); triangleMesh = scene.Factory.TriangleMeshManager.Create("UserMesh1"); TriangleMeshRegion r01 = triangleMesh.TriangleMeshRegionManager.Create("r01"); Vertex v1 = r01.VertexManager.Create("v1"); v1.SetPosition(-1.0f, -1.0f, -1.0f); Vertex v2 = r01.VertexManager.Create("v2"); v2.SetPosition(0.0f, -1.0f, 1.0f); Vertex v3 = r01.VertexManager.Create("v3"); v3.SetPosition(1.0f, -1.0f, -1.0f); Vertex v4 = r01.VertexManager.Create("v4"); v4.SetPosition(0.0f, 1.0f, 0.0f); Triangle t01 = r01.TriangleManager.Create("t01"); t01.Index1 = 0; t01.Index2 = 1; t01.Index3 = 3; Triangle t02 = r01.TriangleManager.Create("t02"); t02.Index1 = 0; t02.Index2 = 3; t02.Index3 = 2; Triangle t03 = r01.TriangleManager.Create("t03"); t03.Index1 = 2; t03.Index2 = 3; t03.Index3 = 1; Triangle t04 = r01.TriangleManager.Create("t04"); t04.Index1 = 0; t04.Index2 = 2; t04.Index3 = 1; triangleMesh.Update(true, true); if (!demo.Meshes.ContainsKey("UserMesh1")) demo.Meshes.Add("UserMesh1", new DemoMesh(demo, triangleMesh, demo.Textures["Default"], Vector2.One, false, false, true, false, false, CullFaceMode.Back, false, false)); shapePrimitive = scene.Factory.ShapePrimitiveManager.Create("UserMesh1"); shapePrimitive.CreateConvex(triangleMesh); shape = scene.Factory.ShapeManager.Create("UserMesh1"); shape.Set(shapePrimitive, Matrix4.Identity, 0.0f); shapePrimitive = scene.Factory.ShapePrimitiveManager.Create("Cylinder2RY"); shapePrimitive.CreateCylinder2RY(2.0f, 2.0f, 1.0f); shape = scene.Factory.ShapeManager.Create("Cylinder2RY"); shape.Set(shapePrimitive, Matrix4.Identity, 0.0f); triangleMesh = scene.Factory.TriangleMeshManager.Create("Cylinder2RY"); triangleMesh.CreateCylinder2RY(1, 15, 2.0f, 2.0f, 1.0f); if (!demo.Meshes.ContainsKey("Cylinder2RY")) demo.Meshes.Add("Cylinder2RY", new DemoMesh(demo, triangleMesh, demo.Textures["Default"], Vector2.One, true, true, true, false, true, CullFaceMode.Back, false, false)); triangleMesh = scene.Factory.TriangleMeshManager.Create("TubeMesh1"); triangleMesh.CreateTubeY(1, 15, 2.0f, 1.0f, 0.5f, 1.0f, 0.5f); if (!demo.Meshes.ContainsKey("TubeMesh1")) demo.Meshes.Add("TubeMesh1", new DemoMesh(demo, triangleMesh, demo.Textures["Default"], Vector2.One, true, true, true, false, true, CullFaceMode.Back, false, false)); } public void Create() { Shape point = scene.Factory.ShapeManager.Find("Point"); Shape edge = scene.Factory.ShapeManager.Find("Edge"); Shape box = scene.Factory.ShapeManager.Find("Box"); Shape cylinderY = scene.Factory.ShapeManager.Find("CylinderY"); Shape sphere = scene.Factory.ShapeManager.Find("Sphere"); Shape hemisphereZ = scene.Factory.ShapeManager.Find("HemisphereZ"); Shape coneY = scene.Factory.ShapeManager.Find("ConeY"); Shape capsuleY = scene.Factory.ShapeManager.Find("CapsuleY"); Shape triangle1 = scene.Factory.ShapeManager.Find("Triangle1"); Shape triangle2 = scene.Factory.ShapeManager.Find("Triangle2"); Shape convexTorus1 = scene.Factory.ShapeManager.Find("ConvexTorus1"); Shape userMesh1 = scene.Factory.ShapeManager.Find("UserMesh1"); Shape cylinder2RY = scene.Factory.ShapeManager.Find("Cylinder2RY"); PhysicsObject objectBase = null; objectBase = scene.Factory.PhysicsObjectManager.Create("Cylinder2R 1"); objectBase.Shape = cylinder2RY; objectBase.UserDataStr = "Cylinder2RY"; objectBase.CreateSound(true); objectBase.Sound.HitPitch = 0.5f; objectBase.Sound.RollPitch = 0.5f; objectBase.Sound.SlidePitch = 0.5f; objectBase.InitLocalTransform.SetPosition(10.0f, 20.0f, 10.0f); objectBase.InitLocalTransform.SetScale(1.5f); objectBase.Integral.SetDensity(1.0f); scene.UpdateFromInitLocalTransform(objectBase); objectBase = scene.Factory.PhysicsObjectManager.Create("Cylinder 1"); objectBase.Shape = cylinderY; objectBase.UserDataStr = "CylinderY"; objectBase.CreateSound(true); objectBase.InitLocalTransform.SetPosition(0.0f, 20.0f, 20.0f); objectBase.InitLocalTransform.SetScale(2.0f); objectBase.Integral.SetDensity(1.0f); scene.UpdateFromInitLocalTransform(objectBase); objectBase = scene.Factory.PhysicsObjectManager.Create("Cone 1"); objectBase.Shape = coneY; objectBase.UserDataStr = "ConeY"; objectBase.Material.RigidGroup = true; objectBase.CreateSound(true); objectBase.InitLocalTransform.SetPosition(-10.0f, 20.0f, 20.0f); objectBase.InitLocalTransform.SetScale(3.0f); objectBase.Integral.SetDensity(1.0f); scene.UpdateFromInitLocalTransform(objectBase); objectBase = scene.Factory.PhysicsObjectManager.Create("Capsule 1"); objectBase.Shape = capsuleY; objectBase.UserDataStr = "CapsuleY"; objectBase.CreateSound(true); objectBase.Sound.MinNextImpactForce = 1500.0f; objectBase.InitLocalTransform.SetPosition(-20.0f, 20.0f, 20.0f); objectBase.InitLocalTransform.SetScale(2.0f); objectBase.Integral.SetDensity(1.0f); scene.UpdateFromInitLocalTransform(objectBase); objectBase = scene.Factory.PhysicsObjectManager.Create("Sphere 1"); objectBase.Shape = sphere; objectBase.UserDataStr = "Sphere"; objectBase.Material.SetSpecular(0.1f, 0.1f, 0.1f); objectBase.CreateSound(true); objectBase.InitLocalTransform.SetPosition(-30.0f, 20.0f, 20.0f); objectBase.InitLocalTransform.SetScale(2.0f); objectBase.Integral.SetDensity(1.0f); scene.UpdateFromInitLocalTransform(objectBase); objectBase = scene.Factory.PhysicsObjectManager.Create("Cylinder 2"); objectBase.Shape = cylinderY; objectBase.UserDataStr = "CylinderY"; objectBase.CreateSound(true); objectBase.InitLocalTransform.SetPosition(0.0f, 20.0f, 10.0f); objectBase.InitLocalTransform.SetScale(1.0f, 2.0f, 2.0f); objectBase.Integral.SetDensity(1.0f); scene.UpdateFromInitLocalTransform(objectBase); objectBase = scene.Factory.PhysicsObjectManager.Create("Cone 2"); objectBase.Shape = coneY; objectBase.UserDataStr = "ConeY"; objectBase.Material.RigidGroup = true; objectBase.CreateSound(true); objectBase.InitLocalTransform.SetPosition(-10.0f, 20.0f, 10.0f); objectBase.InitLocalTransform.SetScale(2.0f, 3.0f, 3.0f); objectBase.Integral.SetDensity(1.0f); scene.UpdateFromInitLocalTransform(objectBase); objectBase = scene.Factory.PhysicsObjectManager.Create("Capsule 2"); objectBase.Shape = capsuleY; objectBase.UserDataStr = "CapsuleY"; objectBase.Material.SetSpecular(0.1f, 0.1f, 0.1f); objectBase.CreateSound(true); objectBase.InitLocalTransform.SetPosition(-20.0f, 20.0f, 10.0f); objectBase.InitLocalTransform.SetScale(2.0f, 2.0f, 1.0f); objectBase.Integral.SetDensity(1.0f); scene.UpdateFromInitLocalTransform(objectBase); objectBase = scene.Factory.PhysicsObjectManager.Create("Sphere 2"); objectBase.Shape = sphere; objectBase.UserDataStr = "Sphere"; objectBase.CreateSound(true); objectBase.InitLocalTransform.SetPosition(-30.0f, 20.0f, 10.0f); objectBase.InitLocalTransform.SetScale(1.0f, 2.0f, 2.0f); objectBase.Integral.SetDensity(1.0f); objectBase.Integral.EnableInertia = false; scene.UpdateFromInitLocalTransform(objectBase); objectBase = scene.Factory.PhysicsObjectManager.Create("Box 1"); objectBase.Shape = box; objectBase.UserDataStr = "Box"; objectBase.CreateSound(true); objectBase.InitLocalTransform.SetPosition(-5.0f, 40.0f, 20.0f); objectBase.InitLocalTransform.SetScale(0.1f, 10.0f, 0.1f); objectBase.Integral.SetDensity(1.0f); scene.UpdateFromInitLocalTransform(objectBase); objectBase = scene.Factory.PhysicsObjectManager.Create("Torus 1"); objectBase.Shape = convexTorus1; objectBase.UserDataStr = "TorusMesh1"; objectBase.CreateSound(true); objectBase.InitLocalTransform.SetPosition(-30.0f, 50.0f, 30.0f); objectBase.Integral.SetDensity(1.0f); scene.UpdateFromInitLocalTransform(objectBase); objectBase = scene.Factory.PhysicsObjectManager.Create("Tube 1"); objectBase.Shape = cylinderY; objectBase.UserDataStr = "TubeMesh1"; objectBase.CreateSound(true); objectBase.InitLocalTransform.SetPosition(-20.0f, 50.0f, 30.0f); objectBase.InitLocalTransform.SetScale(2.0f); objectBase.Integral.SetDensity(1.0f); scene.UpdateFromInitLocalTransform(objectBase); objectBase = scene.Factory.PhysicsObjectManager.Create("Hemisphere 1"); objectBase.Shape = hemisphereZ; objectBase.UserDataStr = "HemisphereZ"; objectBase.Material.SetSpecular(0.1f, 0.1f, 0.1f); objectBase.CreateSound(true); objectBase.InitLocalTransform.SetPosition(-40.0f, 20.0f, 20.0f); objectBase.InitLocalTransform.SetScale(2.0f); objectBase.Integral.SetDensity(1.0f); scene.UpdateFromInitLocalTransform(objectBase); objectBase = scene.Factory.PhysicsObjectManager.Create("Hemisphere 2"); objectBase.Shape = hemisphereZ; objectBase.UserDataStr = "HemisphereZ"; objectBase.CreateSound(true); objectBase.InitLocalTransform.SetPosition(-40.0f, 20.0f, 10.0f); objectBase.InitLocalTransform.SetScale(1.0f, 2.0f, 2.0f); objectBase.Integral.SetDensity(1.0f); scene.UpdateFromInitLocalTransform(objectBase); objectBase = scene.Factory.PhysicsObjectManager.Create("User TriangleMesh 1"); objectBase.Shape = userMesh1; objectBase.UserDataStr = "UserMesh1"; objectBase.CreateSound(true); objectBase.InitLocalTransform.SetPosition(-40.0f, 50.0f, 30.0f); objectBase.InitLocalTransform.SetScale(3.0f); objectBase.Integral.SetDensity(1.0f); objectBase.Integral.EnableInertia = false; scene.UpdateFromInitLocalTransform(objectBase); objectBase = scene.Factory.PhysicsObjectManager.Create("Point"); objectBase.Shape = point; objectBase.UserDataStr = "Point"; objectBase.CreateSound(true); objectBase.InitLocalTransform.SetPosition(0.0f, 20.0f, 0.0f); objectBase.InitLocalTransform.SetScale(0.1f); objectBase.Integral.SetDensity(2.0f); scene.UpdateFromInitLocalTransform(objectBase); objectBase = scene.Factory.PhysicsObjectManager.Create("Edge"); objectBase.Shape = edge; objectBase.UserDataStr = "Edge"; objectBase.CreateSound(true); objectBase.InitLocalTransform.SetPosition(10.0f, 20.0f, 0.0f); objectBase.InitLocalTransform.SetScale(0.1f, 1.0f, 0.1f); objectBase.Integral.SetDensity(1.0f); scene.UpdateFromInitLocalTransform(objectBase); objectBase = scene.Factory.PhysicsObjectManager.Create("Triangle 1"); objectBase.Shape = triangle1; objectBase.UserDataStr = "Triangle1"; objectBase.CreateSound(true); objectBase.Sound.UserDataStr = "RollSlide"; objectBase.InitLocalTransform.SetPosition(-10.0f, 10.0f, 30.0f); objectBase.InitLocalTransform.SetScale(3.0f, 10.0f, 3.0f); objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitZ, MathHelper.DegreesToRadians(180.0f))); objectBase.Integral.SetDensity(0.1f); scene.UpdateFromInitLocalTransform(objectBase); objectBase = scene.Factory.PhysicsObjectManager.Create("Triangle 2"); objectBase.Shape = triangle2; objectBase.UserDataStr = "Triangle2"; objectBase.CreateSound(true); objectBase.Sound.UserDataStr = "RollSlide"; objectBase.InitLocalTransform.SetPosition(0.0f, 10.0f, 30.0f); objectBase.InitLocalTransform.SetScale(3.0f, 5.0f, 3.0f); objectBase.Integral.SetDensity(0.1f); scene.UpdateFromInitLocalTransform(objectBase); PhysicsObject objectRoot = scene.Factory.PhysicsObjectManager.Create("ConcaveTorus1"); objectRoot.UserDataStr = "TorusMesh1"; int i = 1; while ((objectBase = scene.Factory.PhysicsObjectManager.Find("ConcaveTorus1 " + i.ToString())) != null) { objectBase.Shape.CreateMesh(0.0f); if (!demo.Meshes.ContainsKey("ConcaveTorus1 " + i.ToString())) demo.Meshes.Add("ConcaveTorus1 " + i.ToString(), new DemoMesh(demo, objectBase.Shape, demo.Textures["Default"], Vector2.One, false, false, false, false, true, CullFaceMode.Back, false, false)); objectBase.UserDataStr = "ConcaveTorus1 " + i.ToString(); objectBase.Material.RigidGroup = true; objectBase.CreateSound(true); objectBase.Integral.SetMass(1.0f); objectRoot.AddChildPhysicsObject(objectBase); i++; } objectRoot.InitLocalTransform.SetScale(0.5f); objectRoot.InitLocalTransform.SetPosition(18.0f, 20.0f, 10.0f); scene.UpdateFromInitLocalTransform(objectRoot); objectRoot = scene.Factory.PhysicsObjectManager.Create("ConcaveTorus2"); objectRoot.UserDataStr = "TorusMesh1"; i = 1; while ((objectBase = scene.Factory.PhysicsObjectManager.Find("ConcaveTorus2 " + i.ToString())) != null) { objectBase.Shape.CreateMesh(0.0f); if (!demo.Meshes.ContainsKey("ConcaveTorus2 " + i.ToString())) demo.Meshes.Add("ConcaveTorus2 " + i.ToString(), new DemoMesh(demo, objectBase.Shape, demo.Textures["Default"], Vector2.One, false, false, false, false, true, CullFaceMode.Back, false, false)); objectBase.UserDataStr = "ConcaveTorus2 " + i.ToString(); objectBase.Material.RigidGroup = true; objectBase.CreateSound(true); objectBase.Integral.SetMass(1.0f); objectRoot.AddChildPhysicsObject(objectBase); i++; } objectRoot.InitLocalTransform.SetScale(0.5f); objectRoot.InitLocalTransform.SetPosition(19.0f, 20.0f, 10.0f); objectRoot.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitX, MathHelper.DegreesToRadians(90.0f))); scene.UpdateFromInitLocalTransform(objectRoot); } } }
// Copyright (c) 2015, Outercurve Foundation. // 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 the Outercurve Foundation 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Web.UI; using System.Web.UI.WebControls; using WebsitePanel.Providers.HostedSolution; using System.Linq; using WebsitePanel.Providers.Web; using WebsitePanel.EnterpriseServer.Base.HostedSolution; using WebsitePanel.Providers.RemoteDesktopServices; using AjaxControlToolkit; namespace WebsitePanel.Portal.RDS.UserControls { public partial class RDSCollectionServers : WebsitePanelControlBase { public const string DirectionString = "DirectionString"; public event EventHandler OnRefreshClicked; protected enum SelectedState { All, Selected, Unselected } public void SetServers(RdsServer[] servers) { BindServers(servers, false); } public void BindServers(RdsServer[] servers) { gvServers.DataSource = servers; gvServers.DataBind(); } public void HideRefreshButton() { btnRefresh.Visible = false; } public List<RdsServer> GetServers() { return GetGridViewServers(SelectedState.All); } protected void Page_Load(object sender, EventArgs e) { // register javascript if (!Page.ClientScript.IsClientScriptBlockRegistered("SelectAllCheckboxes")) { string script = @" function SelectAllCheckboxes(box) { var state = box.checked; var elm = box.parentElement.parentElement.parentElement.parentElement.getElementsByTagName(""INPUT""); for(i = 0; i < elm.length; i++) if(elm[i].type == ""checkbox"" && elm[i].id != box.id && elm[i].checked != state && !elm[i].disabled) elm[i].checked = state; }"; Page.ClientScript.RegisterClientScriptBlock(typeof(RDSCollectionUsers), "SelectAllCheckboxes", script, true); } if (!IsPostBack && PanelRequest.CollectionID > 0) { BindOrganizationServers(); } } protected void btnAdd_Click(object sender, EventArgs e) { // bind all servers BindPopupServers(); // show modal AddServersModal.Show(); } protected void btnDelete_Click(object sender, EventArgs e) { List<RdsServer> selectedServers = GetGridViewServers(SelectedState.Unselected); BindServers(selectedServers.ToArray(), false); } protected void btnAddSelected_Click(object sender, EventArgs e) { List<RdsServer> selectedServers = GetPopUpGridViewServers(); BindServers(selectedServers.ToArray(), true); } protected void BindPopupServers() { RdsServer[] servers = ES.Services.RDS.GetOrganizationFreeRdsServersPaged(PanelRequest.ItemID, "FqdName", txtSearchValue.Text, null, 0, 1000).Servers; servers = servers.Where(x => !GetServers().Select(p => p.Id).Contains(x.Id)).ToArray(); Array.Sort(servers, CompareAccount); if (Direction == SortDirection.Ascending) { Array.Reverse(servers); Direction = SortDirection.Descending; } else Direction = SortDirection.Ascending; gvPopupServers.DataSource = servers; gvPopupServers.DataBind(); } protected void BindServers(RdsServer[] newServers, bool preserveExisting) { // get binded addresses List<RdsServer> servers = new List<RdsServer>(); if(preserveExisting) servers.AddRange(GetGridViewServers(SelectedState.All)); // add new servers if (newServers != null) { foreach (RdsServer newServer in newServers) { // check if exists bool exists = false; foreach (RdsServer server in servers) { if (server.Id == newServer.Id) { exists = true; break; } } if (exists) continue; servers.Add(newServer); } } gvServers.DataSource = servers; gvServers.DataBind(); } protected List<RdsServer> GetGridViewServers(SelectedState state) { List<RdsServer> servers = new List<RdsServer>(); for (int i = 0; i < gvServers.Rows.Count; i++) { GridViewRow row = gvServers.Rows[i]; CheckBox chkSelect = (CheckBox)row.FindControl("chkSelect"); if (chkSelect == null) continue; RdsServer server = new RdsServer(); server.Id = (int)gvServers.DataKeys[i][0]; server.FqdName = ((Literal)row.FindControl("litFqdName")).Text; server.Status = ((Literal)row.FindControl("litStatus")).Text; var rdsCollectionId = ((HiddenField)row.FindControl("hdnRdsCollectionId")).Value; if (!string.IsNullOrEmpty(rdsCollectionId)) { server.RdsCollectionId = Convert.ToInt32(rdsCollectionId); } if (state == SelectedState.All || (state == SelectedState.Selected && chkSelect.Checked) || (state == SelectedState.Unselected && !chkSelect.Checked)) servers.Add(server); } return servers; } protected List<RdsServer> GetPopUpGridViewServers() { List<RdsServer> servers = new List<RdsServer>(); for (int i = 0; i < gvPopupServers.Rows.Count; i++) { GridViewRow row = gvPopupServers.Rows[i]; CheckBox chkSelect = (CheckBox)row.FindControl("chkSelect"); if (chkSelect == null) continue; if (chkSelect.Checked) { servers.Add(new RdsServer { Id = (int)gvPopupServers.DataKeys[i][0], FqdName = ((Literal)row.FindControl("litName")).Text }); } } return servers; } protected void BindOrganizationServers() { RdsServer[] servers = ES.Services.RDS.GetOrganizationRdsServersPaged(PanelRequest.ItemID, PanelRequest.CollectionID, "FqdName", txtSearchValue.Text, null, 0, 1000).Servers; foreach(var rdsServer in servers) { rdsServer.Status = ES.Services.RDS.GetRdsServerStatus(PanelRequest.ItemID, rdsServer.FqdName); } Array.Sort(servers, CompareAccount); if (Direction == SortDirection.Ascending) { Array.Reverse(servers); Direction = SortDirection.Descending; } else { Direction = SortDirection.Ascending; } gvServers.DataSource = servers; gvServers.DataBind(); } protected void cmdSearch_Click(object sender, ImageClickEventArgs e) { BindPopupServers(); } protected SortDirection Direction { get { return ViewState[DirectionString] == null ? SortDirection.Descending : (SortDirection)ViewState[DirectionString]; } set { ViewState[DirectionString] = value; } } protected static int CompareAccount(RdsServer server1, RdsServer server2) { return string.Compare(server1.FqdName, server2.FqdName); } protected void gvServers_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "ViewInfo") { try { ShowInfo(e.CommandArgument.ToString()); } catch (Exception) { } } else if (e.CommandName == "Restart") { Restart(e.CommandArgument.ToString()); } else if (e.CommandName == "ShutDown") { ShutDown(e.CommandArgument.ToString()); } } protected void btnRefresh_Click(object sender, EventArgs e) { if (OnRefreshClicked != null) { OnRefreshClicked(GetServers(), new EventArgs()); } } private void ShowInfo(string serverName) { ViewInfoModal.Show(); var serverInfo = ES.Services.RDS.GetRdsServerInfo(PanelRequest.ItemID, serverName); litProcessor.Text = string.Format("{0}x{1} MHz", serverInfo.NumberOfCores, serverInfo.MaxClockSpeed); litLoadPercentage.Text = string.Format("{0}%", serverInfo.LoadPercentage); litMemoryAllocated.Text = string.Format("{0} MB", serverInfo.MemoryAllocatedMb); litFreeMemory.Text = string.Format("{0} MB", serverInfo.FreeMemoryMb); rpServerDrives.DataSource = serverInfo.Drives; rpServerDrives.DataBind(); } private void Restart(string serverName) { ES.Services.RDS.RestartRdsServer(PanelRequest.ItemID, serverName); Response.Redirect(EditUrl("SpaceID", PanelSecurity.PackageId.ToString(), "rds_edit_collection", "CollectionId=" + PanelRequest.CollectionID, "ItemID=" + PanelRequest.ItemID)); } private void ShutDown(string serverName) { ES.Services.RDS.ShutDownRdsServer(PanelRequest.ItemID, serverName); Response.Redirect(EditUrl("SpaceID", PanelSecurity.PackageId.ToString(), "rds_edit_collection", "CollectionId=" + PanelRequest.CollectionID, "ItemID=" + PanelRequest.ItemID)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers.Operations; using System.Buffers.Text; using System.Buffers.Writer; using System.Diagnostics; using System.Text; using System.Text.Utf8; using Xunit; namespace System.Buffers.Tests { public class BasicUnitTests { private static readonly Utf8String _crlf = (Utf8String)"\r\n"; private static readonly Utf8String _eoh = (Utf8String)"\r\n\r\n"; // End Of Headers private static readonly Utf8String _http11OK = (Utf8String)"HTTP/1.1 200 OK\r\n"; private static readonly Utf8String _headerServer = (Utf8String)"Server: Custom"; private static readonly Utf8String _headerContentLength = (Utf8String)"Content-Length: "; private static readonly Utf8String _headerContentLengthZero = (Utf8String)"Content-Length: 0\r\n"; private static readonly Utf8String _headerContentTypeText = (Utf8String)"Content-Type: text/plain\r\n"; private static Utf8String _plainTextBody = (Utf8String)"Hello, World!"; private static Sink _sink = new Sink(4096); private static readonly string s_response = "HTTP/1.1 200 OK\r\nServer: Custom\r\nDate: Fri, 16 Mar 2018 10:22:15 GMT\r\nContent-Type: text/plain\r\nContent-Length: 13\r\n\r\nHello, World!"; [Fact] public void WritePlainText() { DateHeader.SetDateValues(new DateTimeOffset(2018, 3, 16, 10, 22, 15, 10, TimeSpan.FromMilliseconds(0))); _sink.Reset(); var writer = BufferWriter.Create(_sink); // HTTP 1.1 OK writer.Write(_http11OK); // Server headers writer.Write(_headerServer); // Date header writer.Write(DateHeader.HeaderBytes); // Content-Type header writer.Write(_headerContentTypeText); // Content-Length header writer.Write(_headerContentLength); writer.Write((ulong)_plainTextBody.Bytes.Length); // End of headers writer.Write(_eoh); // Body writer.Write(_plainTextBody); writer.Flush(); var result = _sink.ToString(); Assert.Equal(s_response, _sink.ToString()); } [Fact] public void BufferWriterTransform() { byte[] buffer = new byte[10]; var writer = BufferWriter.Create(buffer.AsSpan()); var transformation = new TransformationFormat(new RemoveTransformation(2)); ReadOnlyMemory<byte> value = new byte[] { 1, 2, 3 }; writer.WriteBytes(value, transformation); Assert.Equal(-1, buffer.AsSpan().IndexOf((byte)2)); } [Fact] public void WriteLineString() { _sink.Reset(); var writer = BufferWriter.Create(_sink); var newLine = new byte[] { (byte)'X', (byte)'Y' }; writer.WriteLine("hello world", newLine); writer.WriteLine("!", newLine); writer.Flush(); var result = _sink.ToString(); Assert.Equal("hello worldXY!XY", result); } [Fact] public void WriteLineUtf8String() { _sink.Reset(); var writer = BufferWriter.Create(_sink); var newLine = new byte[] { (byte)'X', (byte)'Y' }; writer.WriteLine((Utf8String)"hello world", newLine); writer.WriteLine((Utf8String)"!", newLine); writer.Flush(); var result = _sink.ToString(); Assert.Equal("hello worldXY!XY", result); } [Fact] public void WriteInt32Transformed() { TransformationFormat widen = new TransformationFormat(new AsciiToUtf16()); _sink.Reset(); var writer = BufferWriter.Create(_sink); writer.Write(255, widen); writer.Flush(); var result = _sink.ToStringAssumingUtf16Buffer(); Assert.Equal("255", result); } } internal class Sink : IBufferWriter<byte> { private byte[] _buffer; private int _written; public Sink(int size) { _buffer = new byte[4096]; _written = 0; } public void Reset() => _written = 0; public void Advance(int count) { _written += count; if (_written > _buffer.Length) throw new ArgumentOutOfRangeException(nameof(count)); } public Memory<byte> GetMemory(int sizeHint = 0) => _buffer.AsMemory(_written, _buffer.Length - _written); public Span<byte> GetSpan(int sizeHint = 0) => _buffer.AsSpan(_written, _buffer.Length - _written); public Span<byte> WrittenBytes => _buffer.AsSpan(0, _written); public override string ToString() { return Encoding.UTF8.GetString(_buffer, 0, _written); } public string ToStringAssumingUtf16Buffer() { return Encoding.Unicode.GetString(_buffer, 0, _written); } } internal static class DateHeader { private const int prefixLength = 8; // "\r\nDate: ".Length private const int dateTimeRLength = 29; // Wed, 14 Mar 2018 14:20:00 GMT private const int suffixLength = 2; // crlf private const int suffixIndex = dateTimeRLength + prefixLength; private static byte[] s_headerBytesMaster = new byte[prefixLength + dateTimeRLength + suffixLength]; private static byte[] s_headerBytesScratch = new byte[prefixLength + dateTimeRLength + suffixLength]; static DateHeader() { var utf8 = Encoding.ASCII.GetBytes("\r\nDate: ").AsSpan(); utf8.CopyTo(s_headerBytesMaster); utf8.CopyTo(s_headerBytesScratch); s_headerBytesMaster[suffixIndex] = (byte)'\r'; s_headerBytesMaster[suffixIndex + 1] = (byte)'\n'; s_headerBytesScratch[suffixIndex] = (byte)'\r'; s_headerBytesScratch[suffixIndex + 1] = (byte)'\n'; SetDateValues(DateTimeOffset.UtcNow); } public static ReadOnlySpan<byte> HeaderBytes => s_headerBytesMaster; public static void SetDateValues(DateTimeOffset value) { lock (s_headerBytesScratch) { if (!Utf8Formatter.TryFormat(value, s_headerBytesScratch.AsSpan(prefixLength), out int written, 'R')) { throw new Exception("date time format failed"); } Debug.Assert(written == dateTimeRLength); var temp = s_headerBytesMaster; s_headerBytesMaster = s_headerBytesScratch; s_headerBytesScratch = temp; } } } internal class AsciiToUtf16 : IBufferTransformation { public OperationStatus Execute(ReadOnlySpan<byte> input, Span<byte> output, out int consumed, out int written) { throw new NotImplementedException(); } public OperationStatus Transform(Span<byte> buffer, int dataLength, out int written) { written = dataLength * 2; if (buffer.Length < written) return OperationStatus.DestinationTooSmall; for(int i = written - 1; i > 0; i-=2) { buffer[i] = 0; buffer[i - 1] = buffer[i / 2]; } return OperationStatus.Done; } } }
using System; using System.Collections.Generic; using System.Linq; using Moq; using NuGet.Test.Mocks; using Xunit; namespace NuGet.Test { public class PackageWalkerTest { [Fact] public void ResolvingDependencyForUpdateWithConflictingDependents() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); // A 1.0 -> B [1.0] IPackage A10 = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "[1.0]") }, content: new[] { "a1" }); // A 2.0 -> B (any version) IPackage A20 = PackageUtility.CreatePackage("A", "2.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }, content: new[] { "a2" }); IPackage B10 = PackageUtility.CreatePackage("B", "1.0", content: new[] { "b1" }); IPackage B101 = PackageUtility.CreatePackage("B", "1.0.1", content: new[] { "b101" }); IPackage B20 = PackageUtility.CreatePackage("B", "2.0", content: new[] { "a2" }); localRepository.Add(A10); localRepository.Add(B10); sourceRepository.AddPackage(A10); sourceRepository.AddPackage(A20); sourceRepository.AddPackage(B10); sourceRepository.AddPackage(B101); sourceRepository.AddPackage(B20); IPackageOperationResolver resolver = new UpdateWalker(localRepository, new DependencyResolverFromRepo(sourceRepository), new DependentsWalker(localRepository), NullConstraintProvider.Instance, NullLogger.Instance, updateDependencies: true, allowPrereleaseVersions: false) { AcceptedTargets = PackageTargets.Project }; // Act var packages = resolver.ResolveOperations(B101).ToList(); // Assert Assert.Equal(4, packages.Count); AssertOperation("A", "1.0", PackageAction.Uninstall, packages[0]); AssertOperation("B", "1.0", PackageAction.Uninstall, packages[1]); AssertOperation("A", "2.0", PackageAction.Install, packages[2]); AssertOperation("B", "1.0.1", PackageAction.Install, packages[3]); IPackageOperationResolver resolver = new UpdateWalker(localRepository, ew DependencyResolverFromRepo(sourceRepository), new DependentsWalker(localRepository), NullConstraintProvider.Instance, NullLogger.Instance, updateDependencies: true, allowPrereleaseVersions: false); var operations = resolver.ResolveOperations(packageA2).ToList(); } [Fact] public void ReverseDependencyWalkerUsersVersionAndIdToDetermineVisited() { // Arrange // A 1.0 -> B 1.0 IPackage packageA1 = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "[1.0]") }); // A 2.0 -> B 2.0 IPackage packageA2 = PackageUtility.CreatePackage("A", "2.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "[2.0]") }); IPackage packageB1 = PackageUtility.CreatePackage("B", "1.0"); IPackage packageB2 = PackageUtility.CreatePackage("B", "2.0"); var mockRepository = new MockPackageRepository(); mockRepository.AddPackage(packageA1); mockRepository.AddPackage(packageA2); mockRepository.AddPackage(packageB1); mockRepository.AddPackage(packageB2); // Act IDependentsResolver lookup = new DependentsWalker(mockRepository); // Assert Assert.Equal(0, lookup.GetDependents(packageA1).Count()); Assert.Equal(0, lookup.GetDependents(packageA2).Count()); Assert.Equal(1, lookup.GetDependents(packageB1).Count()); Assert.Equal(1, lookup.GetDependents(packageB2).Count()); } [Fact] public void ResolveDependenciesForInstallPackageWithUnknownDependencyThrows() { // Arrange IPackage package = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }); IPackageOperationResolver resolver = new InstallWalker(new MockPackageRepository(), new MockPackageRepository(), NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false, dependencyVersion: DependencyVersion.Lowest); // Act & Assert ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(package), "Unable to resolve dependency 'B'."); } [Fact] public void ResolveDependenciesForInstallPackageResolvesDependencyUsingDependencyProvider() { // Arrange IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }); IPackage packageB = PackageUtility.CreatePackage("B"); var repository = new Mock<PackageRepositoryBase>(); repository.Setup(c => c.GetPackages()).Returns(new[] { packageA }.AsQueryable()); var dependencyProvider = repository.As<IDependencyResolver>(); dependencyProvider.Setup(c => c.ResolveDependency(It.Is<PackageDependency>(p => p.Id == "B"), It.IsAny<IPackageConstraintProvider>(), false, true, DependencyVersion.Lowest)) .Returns(packageB).Verifiable(); var localRepository = new MockPackageRepository(); IPackageOperationResolver resolver = new InstallWalker(localRepository, repository.Object, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false, dependencyVersion: DependencyVersion.Lowest); // Act var operations = resolver.ResolveOperations(packageA).ToList(); // Assert Assert.Equal(2, operations.Count); Assert.Equal(PackageAction.Install, operations.First().Action); Assert.Equal(packageB, operations.First().Package); Assert.Equal(PackageAction.Install, operations.Last().Action); Assert.Equal(packageA, operations.Last().Package); dependencyProvider.Verify(); } [Fact] public void ResolveDependenciesForInstallPackageResolvesDependencyWithConstraintsUsingDependencyResolver() { // Arrange var packageDependency = new PackageDependency("B", new VersionSpec { MinVersion = new SemanticVersion("1.1") }); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { packageDependency }); IPackage packageB12 = PackageUtility.CreatePackage("B", "1.2"); var repository = new Mock<PackageRepositoryBase>(MockBehavior.Strict); repository.Setup(c => c.GetPackages()).Returns(new[] { packageA }.AsQueryable()); var dependencyProvider = repository.As<IDependencyResolver>(); dependencyProvider.Setup(c => c.ResolveDependency(packageDependency, It.IsAny<IPackageConstraintProvider>(), false, true, DependencyVersion.Lowest)) .Returns(packageB12).Verifiable(); var localRepository = new MockPackageRepository(); IPackageOperationResolver resolver = new InstallWalker(localRepository, repository.Object, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false, dependencyVersion: DependencyVersion.Lowest); // Act var operations = resolver.ResolveOperations(packageA).ToList(); // Assert Assert.Equal(2, operations.Count); Assert.Equal(PackageAction.Install, operations.First().Action); Assert.Equal(packageB12, operations.First().Package); Assert.Equal(PackageAction.Install, operations.Last().Action); Assert.Equal(packageA, operations.Last().Package); dependencyProvider.Verify(); } [Fact] public void ResolveDependenciesForInstallCircularReferenceThrows() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("A") }); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageB); IPackageOperationResolver resolver = new InstallWalker(localRepository, sourceRepository, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false, dependencyVersion: DependencyVersion.Lowest); // Act & Assert ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageA), "Circular dependency detected 'A 1.0 => B 1.0 => A 1.0'."); } [Fact] public void ResolveDependenciesForInstallDiamondDependencyGraph() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); // A -> [B, C] // B -> [D] // C -> [D] // A // / \ // B C // \ / // D IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B"), new PackageDependency("C") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("D") }); IPackage packageC = PackageUtility.CreatePackage("C", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("D") }); IPackage packageD = PackageUtility.CreatePackage("D", "1.0"); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageB); sourceRepository.AddPackage(packageC); sourceRepository.AddPackage(packageD); IPackageOperationResolver resolver = new InstallWalker(localRepository, sourceRepository, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false, dependencyVersion: DependencyVersion.Lowest); // Act var packages = resolver.ResolveOperations(packageA).ToList(); // Assert var dict = packages.ToDictionary(p => p.Package.Id); Assert.Equal(4, packages.Count); Assert.NotNull(dict["A"]); Assert.NotNull(dict["B"]); Assert.NotNull(dict["C"]); Assert.NotNull(dict["D"]); } [Fact] public void ResolveDependenciesForInstallDiamondDependencyGraphWithDifferntVersionOfSamePackage() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); // A -> [B, C] // B -> [D >= 1, E >= 2] // C -> [D >= 2, E >= 1] // A // / \ // B C // | \ | \ // D1 E2 D2 E1 IPackage packageA = PackageUtility.CreateProjectLevelPackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B"), new PackageDependency("C") }); IPackage packageB = PackageUtility.CreateProjectLevelPackage("B", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("D", "1.0"), PackageDependency.CreateDependency("E", "2.0") }); IPackage packageC = PackageUtility.CreateProjectLevelPackage("C", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("D", "2.0"), PackageDependency.CreateDependency("E", "1.0") }); IPackage packageD10 = PackageUtility.CreateProjectLevelPackage("D", "1.0"); IPackage packageD20 = PackageUtility.CreateProjectLevelPackage("D", "2.0"); IPackage packageE10 = PackageUtility.CreateProjectLevelPackage("E", "1.0"); IPackage packageE20 = PackageUtility.CreateProjectLevelPackage("E", "2.0"); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageB); sourceRepository.AddPackage(packageC); sourceRepository.AddPackage(packageD20); sourceRepository.AddPackage(packageD10); sourceRepository.AddPackage(packageE20); sourceRepository.AddPackage(packageE10); IPackageOperationResolver resolver = new InstallWalker(localRepository, sourceRepository, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false, dependencyVersion: DependencyVersion.Lowest); // Act var operations = resolver.ResolveOperations(packageA).ToList(); var projectOperations = resolver.ResolveOperations(packageA).ToList(); // Assert Assert.Equal(5, operations.Count); Assert.Equal("E", operations[0].Package.Id); Assert.Equal(new SemanticVersion("2.0"), operations[0].Package.Version); Assert.Equal("B", operations[1].Package.Id); Assert.Equal("D", operations[2].Package.Id); Assert.Equal(new SemanticVersion("2.0"), operations[2].Package.Version); Assert.Equal("C", operations[3].Package.Id); Assert.Equal("A", operations[4].Package.Id); Assert.Equal(5, projectOperations.Count); Assert.Equal("E", projectOperations[0].Package.Id); Assert.Equal(new SemanticVersion("2.0"), projectOperations[0].Package.Version); Assert.Equal("B", projectOperations[1].Package.Id); Assert.Equal("D", projectOperations[2].Package.Id); Assert.Equal(new SemanticVersion("2.0"), projectOperations[2].Package.Version); Assert.Equal("C", projectOperations[3].Package.Id); Assert.Equal("A", projectOperations[4].Package.Id); } [Fact] public void UninstallWalkerIgnoresMissingDependencies() { // Arrange var localRepository = new MockPackageRepository(); // A -> [B, C] // B -> [D] // C -> [D] IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B"), new PackageDependency("C") }); IPackage packageC = PackageUtility.CreatePackage("C", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("D") }); IPackage packageD = PackageUtility.CreatePackage("D", "1.0"); localRepository.AddPackage(packageA); localRepository.AddPackage(packageC); localRepository.AddPackage(packageD); IPackageOperationResolver resolver = new UninstallWalker(localRepository, new DependentsWalker(localRepository), NullLogger.Instance, removeDependencies: true, forceRemove: false); // Act var packages = resolver.ResolveOperations(packageA) .ToDictionary(p => p.Package.Id); // Assert Assert.Equal(3, packages.Count); Assert.NotNull(packages["A"]); Assert.NotNull(packages["C"]); Assert.NotNull(packages["D"]); } [Fact] public void ResolveDependenciesForUninstallDiamondDependencyGraph() { // Arrange var localRepository = new MockPackageRepository(); // A -> [B, C] // B -> [D] // C -> [D] // A // / \ // B C // \ / // D IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B"), new PackageDependency("C") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("D") }); IPackage packageC = PackageUtility.CreatePackage("C", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("D") }); IPackage packageD = PackageUtility.CreatePackage("D", "1.0"); localRepository.AddPackage(packageA); localRepository.AddPackage(packageB); localRepository.AddPackage(packageC); localRepository.AddPackage(packageD); IPackageOperationResolver resolver = new UninstallWalker(localRepository, new DependentsWalker(localRepository), NullLogger.Instance, removeDependencies: true, forceRemove: false); // Act var packages = resolver.ResolveOperations(packageA) .ToDictionary(p => p.Package.Id); // Assert Assert.Equal(4, packages.Count); Assert.NotNull(packages["A"]); Assert.NotNull(packages["B"]); Assert.NotNull(packages["C"]); Assert.NotNull(packages["D"]); } [Fact] public void ResolveDependencyForInstallCircularReferenceWithDifferentVersionOfPackageReferenceThrows() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); IPackage packageA10 = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }); IPackage packageA15 = PackageUtility.CreatePackage("A", "1.5", dependencies: new List<PackageDependency> { new PackageDependency("B") }); IPackage packageB10 = PackageUtility.CreatePackage("B", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("A", "[1.5]") }); sourceRepository.AddPackage(packageA10); sourceRepository.AddPackage(packageA15); sourceRepository.AddPackage(packageB10); IPackageOperationResolver resolver = new InstallWalker(localRepository, sourceRepository, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false, dependencyVersion: DependencyVersion.Lowest); // Act & Assert ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageA10), "Circular dependency detected 'A 1.0 => B 1.0 => A 1.5'."); } [Fact] public void ResolvingDependencyForUpdateThatHasAnUnsatisfiedConstraint() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var constraintProvider = new Mock<IPackageConstraintProvider>(); constraintProvider.Setup(m => m.GetConstraint("B")).Returns(VersionUtility.ParseVersionSpec("[1.4]")); constraintProvider.Setup(m => m.Source).Returns("foo"); IPackage A10 = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "1.5") }); IPackage A20 = PackageUtility.CreatePackage("A", "2.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "2.0") }); IPackage B15 = PackageUtility.CreatePackage("B", "1.5"); IPackage B20 = PackageUtility.CreatePackage("B", "2.0"); localRepository.Add(A10); localRepository.Add(B15); sourceRepository.AddPackage(A10); sourceRepository.AddPackage(A20); sourceRepository.AddPackage(B15); sourceRepository.AddPackage(B20); IPackageOperationResolver resolver = new InstallWalker(localRepository, sourceRepository, constraintProvider.Object, null, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false, dependencyVersion: DependencyVersion.Lowest); // Act & Assert ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(A20), "Unable to resolve dependency 'B (\u2265 2.0)'.'B' has an additional constraint (= 1.4) defined in foo."); } [Fact] public void ResolveDependencyForInstallPackageWithDependencyThatDoesntMeetMinimumVersionThrows() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "1.5") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.4"); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageB); IPackageOperationResolver resolver = new InstallWalker(localRepository, sourceRepository, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false, dependencyVersion: DependencyVersion.Lowest); // Act & Assert ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageA), "Unable to resolve dependency 'B (\u2265 1.5)'."); } [Fact] public void ResolveDependencyForInstallPackageWithDependencyThatDoesntMeetExactVersionThrows() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "[1.5]") }); sourceRepository.AddPackage(packageA); IPackage packageB = PackageUtility.CreatePackage("B", "1.4"); sourceRepository.AddPackage(packageB); IPackageOperationResolver resolver = new InstallWalker(localRepository, sourceRepository, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false, dependencyVersion: DependencyVersion.Lowest); // Act & Assert ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageA), "Unable to resolve dependency 'B (= 1.5)'."); } [Fact] public void ResolveOperationsForInstallSameDependencyAtDifferentLevelsInGraph() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); // A1 -> B1, C1 IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "1.0"), PackageDependency.CreateDependency("C", "1.0") }); // B1 IPackage packageB = PackageUtility.CreatePackage("B", "1.0"); // C1 -> B1, D1 IPackage packageC = PackageUtility.CreatePackage("C", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "1.0"), PackageDependency.CreateDependency("D", "1.0") }); // D1 -> B1 IPackage packageD = PackageUtility.CreatePackage("D", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "1.0") }); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageB); sourceRepository.AddPackage(packageC); sourceRepository.AddPackage(packageD); IPackageOperationResolver resolver = new InstallWalker(localRepository, sourceRepository, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false, dependencyVersion: DependencyVersion.Lowest); // Act & Assert var packages = resolver.ResolveOperations(packageA).ToList(); Assert.Equal(4, packages.Count); Assert.Equal("B", packages[0].Package.Id); Assert.Equal("D", packages[1].Package.Id); Assert.Equal("C", packages[2].Package.Id); Assert.Equal("A", packages[3].Package.Id); } [Fact] public void ResolveDependenciesForInstallSameDependencyAtDifferentLevelsInGraphDuringUpdate() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); // A1 -> B1, C1 IPackage packageA = PackageUtility.CreatePackage("A", "1.0", content: new[] { "A1" }, dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "1.0"), PackageDependency.CreateDependency("C", "1.0") }); // B1 IPackage packageB = PackageUtility.CreatePackage("B", "1.0", new[] { "B1" }); // C1 -> B1, D1 IPackage packageC = PackageUtility.CreatePackage("C", "1.0", content: new[] { "C1" }, dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "1.0"), PackageDependency.CreateDependency("D", "1.0") }); // D1 -> B1 IPackage packageD = PackageUtility.CreatePackage("D", "1.0", content: new[] { "A1" }, dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "1.0") }); // A2 -> B2, C2 IPackage packageA2 = PackageUtility.CreatePackage("A", "2.0", content: new[] { "A2" }, dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "2.0"), PackageDependency.CreateDependency("C", "2.0") }); // B2 IPackage packageB2 = PackageUtility.CreatePackage("B", "2.0", new[] { "B2" }); // C2 -> B2, D2 IPackage packageC2 = PackageUtility.CreatePackage("C", "2.0", content: new[] { "C2" }, dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "2.0"), PackageDependency.CreateDependency("D", "2.0") }); // D2 -> B2 IPackage packageD2 = PackageUtility.CreatePackage("D", "2.0", content: new[] { "D2" }, dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "2.0") }); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageB); sourceRepository.AddPackage(packageC); sourceRepository.AddPackage(packageD); sourceRepository.AddPackage(packageA2); sourceRepository.AddPackage(packageB2); sourceRepository.AddPackage(packageC2); sourceRepository.AddPackage(packageD2); localRepository.AddPackage(packageA); localRepository.AddPackage(packageB); localRepository.AddPackage(packageC); localRepository.AddPackage(packageD); IPackageOperationResolver resolver = new UpdateWalker(localRepository, sourceRepository, new DependentsWalker(localRepository), NullConstraintProvider.Instance, NullLogger.Instance, updateDependencies: true, allowPrereleaseVersions: false); var operations = resolver.ResolveOperations(packageA2).ToList(); Assert.Equal(8, operations.Count); AssertOperation("A", "1.0", PackageAction.Uninstall, operations[0]); AssertOperation("C", "1.0", PackageAction.Uninstall, operations[1]); AssertOperation("D", "1.0", PackageAction.Uninstall, operations[2]); AssertOperation("B", "1.0", PackageAction.Uninstall, operations[3]); AssertOperation("B", "2.0", PackageAction.Install, operations[4]); AssertOperation("D", "2.0", PackageAction.Install, operations[5]); AssertOperation("C", "2.0", PackageAction.Install, operations[6]); AssertOperation("A", "2.0", PackageAction.Install, operations[7]); } [Fact] public void ResolveDependenciesForInstallPackageWithDependencyReturnsPackageAndDependency() { // Arrange var localRepository = new MockPackageRepository(); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.0"); localRepository.AddPackage(packageA); localRepository.AddPackage(packageB); IPackageOperationResolver resolver = new UninstallWalker(localRepository, new DependentsWalker(localRepository), NullLogger.Instance, removeDependencies: true, forceRemove: false); // Act var packages = resolver.ResolveOperations(packageA) .ToDictionary(p => p.Package.Id); // Assert Assert.Equal(2, packages.Count); Assert.NotNull(packages["A"]); Assert.NotNull(packages["B"]); } [Fact] public void ResolveDependenciesForUninstallPackageWithDependentThrows() { // Arrange var localRepository = new MockPackageRepository(); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.0"); localRepository.AddPackage(packageA); localRepository.AddPackage(packageB); IPackageOperationResolver resolver = new UninstallWalker(localRepository, new DependentsWalker(localRepository), NullLogger.Instance, removeDependencies: false, forceRemove: false); // Act & Assert ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageB), "Unable to uninstall 'B 1.0' because 'A 1.0' depends on it."); } [Fact] public void ResolveDependenciesForUninstallPackageWithDependentAndRemoveDependenciesThrows() { // Arrange var localRepository = new MockPackageRepository(); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.0"); localRepository.AddPackage(packageA); localRepository.AddPackage(packageB); IPackageOperationResolver resolver = new UninstallWalker(localRepository, new DependentsWalker(localRepository), NullLogger.Instance, removeDependencies: true, forceRemove: false); // Act & Assert ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageB), "Unable to uninstall 'B 1.0' because 'A 1.0' depends on it."); } [Fact] public void ResolveDependenciesForUninstallPackageWithDependentAndForceReturnsPackage() { // Arrange var localRepository = new MockPackageRepository(); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.0"); localRepository.AddPackage(packageA); localRepository.AddPackage(packageB); IPackageOperationResolver resolver = new UninstallWalker(localRepository, new DependentsWalker(localRepository), NullLogger.Instance, removeDependencies: false, forceRemove: true); // Act var packages = resolver.ResolveOperations(packageB) .ToDictionary(p => p.Package.Id); // Assert Assert.Equal(1, packages.Count); Assert.NotNull(packages["B"]); } [Fact] public void ResolveDependenciesForUninstallPackageWithRemoveDependenciesExcludesDependencyIfDependencyInUse() { // Arrange var localRepository = new MockPackageRepository(); // A 1.0 -> [B, C] IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B"), new PackageDependency("C") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.0"); IPackage packageC = PackageUtility.CreatePackage("C", "1.0"); // D -> [C] IPackage packageD = PackageUtility.CreatePackage("D", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("C"), }); localRepository.AddPackage(packageD); localRepository.AddPackage(packageA); localRepository.AddPackage(packageB); localRepository.AddPackage(packageC); IPackageOperationResolver resolver = new UninstallWalker(localRepository, new DependentsWalker(localRepository), NullLogger.Instance, removeDependencies: true, forceRemove: false); // Act var packages = resolver.ResolveOperations(packageA) .ToDictionary(p => p.Package.Id); // Assert Assert.Equal(2, packages.Count); Assert.NotNull(packages["A"]); Assert.NotNull(packages["B"]); } [Fact] public void ResolveDependenciesForUninstallPackageWithRemoveDependenciesSetAndForceReturnsAllDependencies() { // Arrange var localRepository = new MockPackageRepository(); // A 1.0 -> [B, C] IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B"), new PackageDependency("C") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.0"); IPackage packageC = PackageUtility.CreatePackage("C", "1.0"); // D -> [C] IPackage packageD = PackageUtility.CreatePackage("D", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("C"), }); localRepository.AddPackage(packageA); localRepository.AddPackage(packageB); localRepository.AddPackage(packageC); localRepository.AddPackage(packageD); IPackageOperationResolver resolver = new UninstallWalker(localRepository, new DependentsWalker(localRepository), NullLogger.Instance, removeDependencies: true, forceRemove: true); // Act var packages = resolver.ResolveOperations(packageA) .ToDictionary(p => p.Package.Id); // Assert Assert.NotNull(packages["A"]); Assert.NotNull(packages["B"]); Assert.NotNull(packages["C"]); } [Fact] public void ProjectInstallWalkerIgnoresSolutionLevelPackages() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); IPackage projectPackage = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "[1.5]") }, content: new[] { "content" }); sourceRepository.AddPackage(projectPackage); IPackage toolsPackage = PackageUtility.CreatePackage("B", "1.5", content: Enumerable.Empty<string>(), tools: new[] { "init.ps1" }); sourceRepository.AddPackage(toolsPackage); IPackageOperationResolver resolver = new UpdateWalker(localRepository, sourceRepository, new DependentsWalker(localRepository), NullConstraintProvider.Instance, NullLogger.Instance, updateDependencies: true, allowPrereleaseVersions: false) { AcceptedTargets = PackageTargets.Project }; // Act var packages = resolver.ResolveOperations(projectPackage) .ToDictionary(p => p.Package.Id); // Assert Assert.Equal(1, packages.Count); Assert.NotNull(packages["A"]); } [Fact] public void AfterPackageWalkMetaPackageIsClassifiedTheSameAsDependencies() { // Arrange var mockRepository = new MockPackageRepository(); var walker = new TestWalker(mockRepository); IPackage metaPackage = PackageUtility.CreatePackage( "A", "1.0", content: Enumerable.Empty<string>(), dependencies: new List<PackageDependency> { new PackageDependency("B"), new PackageDependency("C") }, createRealStream: false); IPackage projectPackageA = PackageUtility.CreatePackage("B", "1.0", content: new[] { "contentB" }); IPackage projectPackageB = PackageUtility.CreatePackage("C", "1.0", content: new[] { "contentC" }); mockRepository.AddPackage(projectPackageA); mockRepository.AddPackage(projectPackageB); Assert.Equal(PackageTargets.None, walker.GetPackageInfo(metaPackage).Target); // Act walker.Walk(metaPackage); // Assert Assert.Equal(PackageTargets.Project, walker.GetPackageInfo(metaPackage).Target); } [Fact] public void LocalizedIntelliSenseFileCountsAsProjectTarget() { // Arrange var mockRepository = new MockPackageRepository(); var walker = new TestWalker(mockRepository); IPackage runtimePackage = PackageUtility.CreatePackage("A", "1.0", assemblyReferences: new[] { @"lib\A.dll", @"lib\A.xml" }); IPackage satellitePackage = PackageUtility.CreatePackage("A.fr-fr", "1.0", dependencies: new[] { new PackageDependency("A") }, satelliteAssemblies: new[] { @"lib\fr-fr\A.xml" }, language: "fr-fr"); mockRepository.AddPackage(runtimePackage); mockRepository.AddPackage(satellitePackage); // Act walker.Walk(satellitePackage); // Assert Assert.Equal(PackageTargets.Project, walker.GetPackageInfo(satellitePackage).Target); } [Fact] public void AfterPackageWalkSatellitePackageIsClassifiedTheSameAsDependencies() { // Arrange var mockRepository = new MockPackageRepository(); var walker = new TestWalker(mockRepository); IPackage runtimePackage = PackageUtility.CreatePackage("A", "1.0", assemblyReferences: new[] { @"lib\A.dll" }); IPackage satellitePackage = PackageUtility.CreatePackage("A.fr-fr", "1.0", dependencies: new[] { new PackageDependency("A") }, satelliteAssemblies: new[] { @"lib\fr-fr\A.resources.dll" }, language: "fr-fr"); mockRepository.AddPackage(runtimePackage); mockRepository.AddPackage(satellitePackage); // Act walker.Walk(satellitePackage); // Assert Assert.Equal(PackageTargets.Project, walker.GetPackageInfo(satellitePackage).Target); } [Fact] public void MetaPackageWithMixedTargetsThrows() { // Arrange var mockRepository = new MockPackageRepository(); var walker = new TestWalker(mockRepository); IPackage metaPackage = PackageUtility.CreatePackage("A", "1.0", content: Enumerable.Empty<string>(), dependencies: new List<PackageDependency> { new PackageDependency("B"), new PackageDependency("C") }, createRealStream: false); IPackage projectPackageA = PackageUtility.CreatePackage("B", "1.0", content: new[] { "contentB" }); IPackage solutionPackage = PackageUtility.CreatePackage("C", "1.0", content: Enumerable.Empty<string>(), tools: new[] { "tools" }); mockRepository.AddPackage(projectPackageA); mockRepository.AddPackage(solutionPackage); // Act && Assert ExceptionAssert.Throws<InvalidOperationException>(() => walker.Walk(metaPackage), "Child dependencies of dependency only packages cannot mix external and project packages."); } [Fact] public void ExternalPackagesThatDepdendOnProjectLevelPackagesThrows() { // Arrange var mockRepository = new MockPackageRepository(); var walker = new TestWalker(mockRepository); IPackage solutionPackage = PackageUtility.CreatePackage( "A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }, content: Enumerable.Empty<string>(), tools: new[] { "install.ps1" }); IPackage projectPackageA = PackageUtility.CreatePackage("B", "1.0", content: new[] { "contentB" }); mockRepository.AddPackage(projectPackageA); mockRepository.AddPackage(solutionPackage); // Act && Assert ExceptionAssert.Throws<InvalidOperationException>(() => walker.Walk(solutionPackage), "External packages cannot depend on packages that target projects."); } [Fact] public void InstallWalkerResolvesLowestMajorAndMinorVersionForDependencies() { // Arrange // A 1.0 -> B 1.0 // B 1.0 -> C 1.1 // C 1.1 -> D 1.0 var A10 = PackageUtility.CreatePackage("A", "1.0", dependencies: new[] { PackageDependency.CreateDependency("B", "1.0") }); var repository = new MockPackageRepository() { PackageUtility.CreatePackage("B", "2.0", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }), PackageUtility.CreatePackage("B", "1.0", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }), PackageUtility.CreatePackage("B", "1.0.1"), A10, PackageUtility.CreatePackage("D", "2.0"), PackageUtility.CreatePackage("C", "1.1.3", dependencies: new[] { PackageDependency.CreateDependency("D", "1.0") }), PackageUtility.CreatePackage("C", "1.1.1", dependencies: new[] { PackageDependency.CreateDependency("D", "1.0") }), PackageUtility.CreatePackage("C", "1.5.1", dependencies: new[] { PackageDependency.CreateDependency("D", "1.0") }), PackageUtility.CreatePackage("B", "1.0.9", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }), PackageUtility.CreatePackage("B", "1.1", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }) }; IPackageOperationResolver resolver = new InstallWalker( new MockPackageRepository(), repository, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false, dependencyVersion: DependencyVersion.HighestPatch); // Act var packages = resolver.ResolveOperations(A10).ToList(); // Assert Assert.Equal(4, packages.Count); Assert.Equal("D", packages[0].Package.Id); Assert.Equal(new SemanticVersion("2.0"), packages[0].Package.Version); Assert.Equal("C", packages[1].Package.Id); Assert.Equal(new SemanticVersion("1.1.3"), packages[1].Package.Version); Assert.Equal("B", packages[2].Package.Id); Assert.Equal(new SemanticVersion("1.0.9"), packages[2].Package.Version); Assert.Equal("A", packages[3].Package.Id); Assert.Equal(new SemanticVersion("1.0"), packages[3].Package.Version); } // Tests that when DependencyVersion is lowest, the dependency with the lowest major minor and patch version // is picked. [Fact] public void InstallWalkerResolvesLowestMajorAndMinorAndPatchVersionOfListedPackagesForDependencies() { // Arrange // A 1.0 -> B 1.0 // B 1.0 -> C 1.1 // C 1.1 -> D 1.0 var A10 = PackageUtility.CreatePackage("A", "1.0", dependencies: new[] { PackageDependency.CreateDependency("B", "1.0") }); var repository = new MockPackageRepository() { PackageUtility.CreatePackage("B", "2.0", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }), PackageUtility.CreatePackage("B", "1.0", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }, listed: false), PackageUtility.CreatePackage("B", "1.0.1"), A10, PackageUtility.CreatePackage("D", "2.0"), PackageUtility.CreatePackage("C", "1.1.3", dependencies: new[] { PackageDependency.CreateDependency("D", "1.0") }), PackageUtility.CreatePackage("C", "1.1.1", dependencies: new[] { PackageDependency.CreateDependency("D", "1.0") }, listed: false), PackageUtility.CreatePackage("C", "1.5.1", dependencies: new[] { PackageDependency.CreateDependency("D", "1.0") }), PackageUtility.CreatePackage("B", "1.0.9", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }), PackageUtility.CreatePackage("B", "1.1", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }) }; IPackageOperationResolver resolver = new InstallWalker(new MockPackageRepository(), repository, constraintProvider: null, logger: NullLogger.Instance, targetFramework: null, ignoreDependencies: false, allowPrereleaseVersions: false, dependencyVersion: DependencyVersion.Lowest); // Act var packages = resolver.ResolveOperations(A10).ToList(); // Assert Assert.Equal(2, packages.Count); Assert.Equal("B", packages[0].Package.Id); Assert.Equal(new SemanticVersion("1.0.1"), packages[0].Package.Version); Assert.Equal("A", packages[1].Package.Id); Assert.Equal(new SemanticVersion("1.0"), packages[1].Package.Version); } // Tests that when DependencyVersion is HighestPatch, the dependency with the lowest major minor and highest patch version // is picked. [Fact] public void InstallWalkerResolvesLowestMajorAndMinorHighestPatchVersionOfListedPackagesForDependencies() { // Arrange // A 1.0 -> B 1.0 // B 1.0 -> C 1.1 // C 1.1 -> D 1.0 var A10 = PackageUtility.CreatePackage("A", "1.0", dependencies: new[] { PackageDependency.CreateDependency("B", "1.0") }); var repository = new MockPackageRepository() { PackageUtility.CreatePackage("B", "2.0", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }), PackageUtility.CreatePackage("B", "1.0", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }, listed: false), PackageUtility.CreatePackage("B", "1.0.1"), A10, PackageUtility.CreatePackage("D", "2.0"), PackageUtility.CreatePackage("C", "1.1.3", dependencies: new[] { PackageDependency.CreateDependency("D", "1.0") }), PackageUtility.CreatePackage("C", "1.1.1", dependencies: new[] { PackageDependency.CreateDependency("D", "1.0") }, listed: false), PackageUtility.CreatePackage("C", "1.5.1", dependencies: new[] { PackageDependency.CreateDependency("D", "1.0") }), PackageUtility.CreatePackage("B", "1.0.9", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }), PackageUtility.CreatePackage("B", "1.1", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }) }; IPackageOperationResolver resolver = new InstallWalker(new MockPackageRepository(), repository, constraintProvider: null, logger: NullLogger.Instance, targetFramework: null, ignoreDependencies: false, allowPrereleaseVersions: false, dependencyVersion: DependencyVersion.HighestPatch); // Act var packages = resolver.ResolveOperations(A10).ToList(); // Assert Assert.Equal(4, packages.Count); Assert.Equal("D", packages[0].Package.Id); Assert.Equal(new SemanticVersion("2.0"), packages[0].Package.Version); Assert.Equal("C", packages[1].Package.Id); Assert.Equal(new SemanticVersion("1.1.3"), packages[1].Package.Version); Assert.Equal("B", packages[2].Package.Id); Assert.Equal(new SemanticVersion("1.0.9"), packages[2].Package.Version); Assert.Equal("A", packages[3].Package.Id); Assert.Equal(new SemanticVersion("1.0"), packages[3].Package.Version); } [Fact] public void ResolveOperationsForPackagesWherePackagesOrderIsDifferentFromItsDependencyOrder() { // Arrange // A 1.0 -> B 1.0 to 1.5 // A 2.0 -> B 1.8 // B 1.0 // B 2.0 // C 1.0 // C 2.0 var A10 = PackageUtility.CreatePackage("A", "1.0", dependencies: new[] { PackageDependency.CreateDependency("B", "[1.0, 1.5]") }); var A20 = PackageUtility.CreatePackage("A", "2.0", dependencies: new[] { PackageDependency.CreateDependency("B", "1.8") }); var B10 = PackageUtility.CreatePackage("B", "1.0"); var B20 = PackageUtility.CreatePackage("B", "2.0"); var C10 = PackageUtility.CreatePackage("C", "1.0"); var C20 = PackageUtility.CreatePackage("C", "2.0"); var sourceRepository = new MockPackageRepository() { A10, A20, B10, B20, C10, C20, }; var localRepository = new MockPackageRepository() { A10, B10, C10 }; var resolver = new InstallWalker(localRepository, sourceRepository, constraintProvider: NullConstraintProvider.Instance, logger: NullLogger.Instance, targetFramework: null, ignoreDependencies: false, allowPrereleaseVersions: false, dependencyVersion: DependencyVersion.Lowest); var updatePackages = new List<IPackage> { A20, B20, C20 }; IList<IPackage> allUpdatePackagesByDependencyOrder; // Act var operations = resolver.ResolveOperations(updatePackages, out allUpdatePackagesByDependencyOrder); // Assert Assert.True(operations.Count == 3); Assert.True(operations[0].Package == B20 && operations[0].Action == PackageAction.Install); Assert.True(operations[1].Package == A20 && operations[1].Action == PackageAction.Install); Assert.True(operations[2].Package == C20 && operations[2].Action == PackageAction.Install); Assert.True(allUpdatePackagesByDependencyOrder[0] == B20); Assert.True(allUpdatePackagesByDependencyOrder[1] == A20); Assert.True(allUpdatePackagesByDependencyOrder[2] == C20); } private void AssertOperation(string expectedId, string expectedVersion, PackageAction expectedAction, PackageOperation operation) { Assert.Equal(expectedAction, operation.Action); Assert.Equal(expectedId, operation.Package.Id); Assert.Equal(new SemanticVersion(expectedVersion), operation.Package.Version); } private class TestWalker : PackageWalker { private readonly IPackageRepository _repository; public TestWalker(IPackageRepository repository) { _repository = repository; } protected override IPackage ResolveDependency(PackageDependency dependency) { return PackageRepositoryExtensions.ResolveDependency(_repository, dependency, AllowPrereleaseVersions, false); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using NLog.AzureStorage.Samples.WebAPI.Areas.HelpPage.ModelDescriptions; using NLog.AzureStorage.Samples.WebAPI.Areas.HelpPage.Models; namespace NLog.AzureStorage.Samples.WebAPI.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 media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), 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 description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <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) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.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}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.Threading; namespace BTDB.Reactive { interface IStoppedSubjectMarker { } static class FastSubjectHelpers<T> { internal interface IUnsubscribableSubject { void Unsubscribe(IObserver<T> observer); } internal interface IHasValue { T Value { get; } } internal static readonly DisposedSubject DisposedSubjectMarker = new DisposedSubject(); internal sealed class DisposedSubject : IObserver<T>, IStoppedSubjectMarker { public void OnNext(T value) { throw new ObjectDisposedException(""); } public void OnError(Exception error) { throw new ObjectDisposedException(""); } public void OnCompleted() { throw new ObjectDisposedException(""); } } internal sealed class ExceptionedSubject : IObserver<T>, IStoppedSubjectMarker { readonly Exception _error; public ExceptionedSubject(Exception error) { _error = error; } internal Exception Error => _error; public void OnNext(T value) { } public void OnError(Exception error) { } public void OnCompleted() { } } internal static readonly CompletedSubject CompletedSubjectMarker = new CompletedSubject(); internal sealed class CompletedSubject : IObserver<T>, IStoppedSubjectMarker { public void OnNext(T value) { } public void OnError(Exception error) { } public void OnCompleted() { } } internal static readonly EmptySubject EmptySubjectMarker = new EmptySubject(); internal sealed class EmptySubject : IObserver<T> { public void OnNext(T value) { } public void OnError(Exception error) { } public void OnCompleted() { } } internal sealed class MultiSubject : IObserver<T> { readonly IObserver<T>[] _array; public MultiSubject(IObserver<T>[] array) { _array = array; } public IObserver<T>[] Array => _array; public void OnNext(T value) { foreach (var observer in _array) { observer.OnNext(value); } } public void OnError(Exception error) { foreach (var observer in _array) { observer.OnError(error); } } public void OnCompleted() { foreach (var observer in _array) { observer.OnCompleted(); } } } internal sealed class EmptySubjectWithValue : IObserver<T>, IHasValue { readonly T _value; internal EmptySubjectWithValue(T value) { _value = value; } public void OnNext(T value) { } public void OnError(Exception error) { } public void OnCompleted() { } public T Value => _value; } internal sealed class MultiSubjectWithValue : IObserver<T>, IHasValue { readonly IObserver<T>[] _array; readonly T _value; public MultiSubjectWithValue(IObserver<T>[] array, T value) { _array = array; _value = value; } public IObserver<T>[] Array => _array; public void OnNext(T value) { foreach (var observer in _array) { observer.OnNext(value); } } public void OnError(Exception error) { foreach (var observer in _array) { observer.OnError(error); } } public void OnCompleted() { foreach (var observer in _array) { observer.OnCompleted(); } } public T Value => _value; } internal sealed class SingleSubjectWithValue : IObserver<T>, IHasValue { readonly IObserver<T> _observer; readonly T _value; public SingleSubjectWithValue(IObserver<T> observer, T value) { _observer = observer; _value = value; } public void OnNext(T value) { Observer.OnNext(value); } public void OnError(Exception error) { Observer.OnError(error); } public void OnCompleted() { Observer.OnCompleted(); } public T Value => _value; internal IObserver<T> Observer => _observer; } internal sealed class Subscription : IDisposable { IObserver<T> _observer; IUnsubscribableSubject _subject; public Subscription(IUnsubscribableSubject subject, IObserver<T> observer) { _subject = subject; _observer = observer; } public void Dispose() { var observer = Interlocked.Exchange(ref _observer, null); if (observer == null) return; _subject.Unsubscribe(observer); _subject = null; } } } }
using System; using System.Diagnostics; using Torshify.Core.Managers; namespace Torshify.Core.Native { internal class NativePlaylistContainer : NativeObject, IPlaylistContainer { #region Fields private NativePlaylistContainerCallbacks _callbacks; private Lazy<NativePlaylistList> _playlists; #endregion Fields #region Constructors public NativePlaylistContainer(ISession session, IntPtr handle) : base(session, handle) { } #endregion Constructors #region Events public event EventHandler Loaded; public event EventHandler<PlaylistEventArgs> PlaylistAdded; public event EventHandler<PlaylistMovedEventArgs> PlaylistMoved; public event EventHandler<PlaylistEventArgs> PlaylistRemoved; #endregion Events #region Properties public bool IsLoaded { get { AssertHandle(); lock (Spotify.Mutex) { return Spotify.sp_playlistcontainer_is_loaded(Handle); } } } public IUser Owner { get { AssertHandle(); lock (Spotify.Mutex) { return UserManager.Get(Session, Spotify.sp_playlistcontainer_owner(Handle)); } } } public IPlaylistList Playlists { get { AssertHandle(); return _playlists.Value; } } #endregion Properties #region Methods public override void Initialize() { lock (Spotify.Mutex) { Spotify.sp_playlistcontainer_add_ref(Handle); } _callbacks = new NativePlaylistContainerCallbacks(this); _playlists = new Lazy<NativePlaylistList>(() => new NativePlaylistList( GetContainerLength, GetPlaylistAtIndex, AddNewPlaylist, AddExistingPlaylist, AddFolder, AddPlaylist, RemovePlaylist, RemovePlaylistAt, () => false, MovePlaylists)); } internal virtual void OnLoaded(EventArgs e) { Loaded.RaiseEvent(this, e); } internal virtual void OnPlaylistAdded(PlaylistEventArgs e) { PlaylistAdded.RaiseEvent(this, e); } internal virtual void OnPlaylistMoved(PlaylistMovedEventArgs e) { PlaylistMoved.RaiseEvent(this, e); } internal virtual void OnPlaylistRemoved(PlaylistEventArgs e) { PlaylistRemoved.RaiseEvent(this, e); } protected override void Dispose(bool disposing) { // Dispose managed if (disposing) { } if (!IsInvalid) { if (_callbacks != null) { _callbacks.Dispose(); _callbacks = null; } try { lock (Spotify.Mutex) { Spotify.sp_playlistcontainer_release(Handle); } } catch { } finally { PlaylistContainerManager.Remove(Handle); Debug.WriteLine("Playlist container disposed"); } } base.Dispose(disposing); } private IContainerPlaylist AddExistingPlaylist(ILink<IPlaylist> link) { INativeObject nativeObject = (INativeObject)link; AssertHandle(); lock (Spotify.Mutex) { IntPtr playlistPtr = Spotify.sp_playlistcontainer_add_playlist(Handle, nativeObject.Handle); return ContainerPlaylistManager.Get( Session, this, playlistPtr, IntPtr.Zero, PlaylistType.Playlist); } } private Error AddFolder(int index, string name) { AssertHandle(); lock (Spotify.Mutex) { return Spotify.sp_playlistcontainer_add_folder(Handle, index, name); } } private IContainerPlaylist AddNewPlaylist(string name) { AssertHandle(); lock (Spotify.Mutex) { IntPtr playlistPtr = Spotify.sp_playlistcontainer_add_new_playlist(Handle, name); return ContainerPlaylistManager.Get( Session, this, playlistPtr, IntPtr.Zero, PlaylistType.Playlist); } } private void AddPlaylist(IContainerPlaylist playlist, int index) { AssertHandle(); IntPtr playlistPtr; int newIndex; lock (Spotify.Mutex) { playlistPtr = Spotify.sp_playlistcontainer_add_new_playlist(Handle, playlist.Name); newIndex = Spotify.sp_playlistcontainer_num_playlists(Handle); } if (playlistPtr != IntPtr.Zero) { lock (Spotify.Mutex) { Spotify.sp_playlistcontainer_move_playlist(Handle, newIndex, index, false); } } } private int GetContainerLength() { AssertHandle(); lock (Spotify.Mutex) { return Spotify.sp_playlistcontainer_num_playlists(Handle); } } private IContainerPlaylist GetPlaylistAtIndex(int index) { lock (Spotify.Mutex) { return ContainerPlaylistManager.Get( Session, this, Spotify.sp_playlistcontainer_playlist(Handle, index), Spotify.sp_playlistcontainer_playlist_folder_id(Handle, index), Spotify.sp_playlistcontainer_playlist_type(Handle, index)); } } private void MovePlaylists(int oldIndex, int newIndex) { AssertHandle(); lock (Spotify.Mutex) { Spotify.sp_playlistcontainer_move_playlist(Handle, oldIndex, newIndex, false); } } private void RemovePlaylist(int index) { RemovePlaylistAt(index); } private Error RemovePlaylistAt(int index) { AssertHandle(); PlaylistType playlistType; Error status; lock (Spotify.Mutex) { playlistType = Spotify.sp_playlistcontainer_playlist_type(Handle, index); status = Spotify.sp_playlistcontainer_remove_playlist(Handle, index); } if (playlistType == PlaylistType.StartFolder) { for (int i = index; i < Playlists.Count; i++) { PlaylistType currentPlaylistType; lock (Spotify.Mutex) { currentPlaylistType = Spotify.sp_playlistcontainer_playlist_type(Handle, i); } if (currentPlaylistType == PlaylistType.EndFolder || currentPlaylistType == PlaylistType.Placeholder) { lock (Spotify.Mutex) { status = Spotify.sp_playlistcontainer_remove_playlist(Handle, i); } break; } } } return status; } #endregion Methods } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // (C) 2002 Ville Palo // (C) 2003 Martin Willemoes Hansen // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // 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 Xunit; using System.Xml; using System.Data.SqlTypes; namespace System.Data.Tests.SqlTypes { public class SqlBinaryTest { private SqlBinary _test1; private SqlBinary _test2; private SqlBinary _test3; public SqlBinaryTest() { byte[] b1 = new byte[2]; byte[] b2 = new byte[3]; byte[] b3 = new byte[2]; b1[0] = 240; b1[1] = 15; b2[0] = 10; b2[1] = 10; b2[2] = 10; b3[0] = 240; b3[1] = 15; _test1 = new SqlBinary(b1); _test2 = new SqlBinary(b2); _test3 = new SqlBinary(b3); } // Test constructor [Fact] public void Create() { byte[] b = new byte[3]; SqlBinary Test = new SqlBinary(b); Assert.True(!(Test.IsNull)); } // Test public fields [Fact] public void PublicFields() { Assert.True(SqlBinary.Null.IsNull); } // Test properties [Fact] public void Properties() { byte[] b = new byte[2]; b[0] = 64; b[1] = 128; SqlBinary TestBinary = new SqlBinary(b); // IsNull Assert.True(SqlBinary.Null.IsNull); // Item Assert.Equal((byte)128, TestBinary[1]); Assert.Equal((byte)64, TestBinary[0]); // FIXME: MSDN says that should throw SqlNullValueException // but throws IndexOutOfRangeException try { byte test = TestBinary[TestBinary.Length]; Assert.False(true); } catch (Exception e) { Assert.Equal(typeof(IndexOutOfRangeException), e.GetType()); } try { byte test = SqlBinary.Null[2]; Assert.False(true); } catch (Exception e) { Assert.Equal(typeof(SqlNullValueException), e.GetType()); } // Length Assert.Equal(2, TestBinary.Length); try { int test = SqlBinary.Null.Length; Assert.False(true); } catch (Exception e) { Assert.Equal(typeof(SqlNullValueException), e.GetType()); } // Value Assert.Equal((byte)128, TestBinary[1]); Assert.Equal((byte)64, TestBinary[0]); try { byte[] test = SqlBinary.Null.Value; Assert.False(true); } catch (Exception e) { Assert.Equal(typeof(SqlNullValueException), e.GetType()); } } // Methods [Fact] public void ComparisonMethods() { // GreaterThan Assert.True(SqlBinary.GreaterThan(_test1, _test2).Value); Assert.True(SqlBinary.GreaterThan(_test3, _test2).Value); Assert.True(!SqlBinary.GreaterThan(_test2, _test1).Value); // GreaterThanOrEqual Assert.True(SqlBinary.GreaterThanOrEqual(_test1, _test2).Value); Assert.True(SqlBinary.GreaterThanOrEqual(_test1, _test2).Value); Assert.True(!SqlBinary.GreaterThanOrEqual(_test2, _test1).Value); // LessThan Assert.True(!SqlBinary.LessThan(_test1, _test2).Value); Assert.True(!SqlBinary.LessThan(_test3, _test2).Value); Assert.True(SqlBinary.LessThan(_test2, _test1).Value); // LessThanOrEqual Assert.True(!SqlBinary.LessThanOrEqual(_test1, _test2).Value); Assert.True(SqlBinary.LessThanOrEqual(_test3, _test1).Value); Assert.True(SqlBinary.LessThanOrEqual(_test2, _test1).Value); // Equals Assert.True(!_test1.Equals(_test2)); Assert.True(!_test3.Equals(_test2)); Assert.True(_test3.Equals(_test1)); // NotEquals Assert.True(SqlBinary.NotEquals(_test1, _test2).Value); Assert.True(!SqlBinary.NotEquals(_test3, _test1).Value); Assert.True(SqlBinary.NotEquals(_test2, _test1).Value); } [Fact] public void CompareTo() { SqlString TestString = new SqlString("This is a test"); Assert.True(_test1.CompareTo(_test2) > 0); Assert.True(_test2.CompareTo(_test1) < 0); Assert.True(_test1.CompareTo(_test3) == 0); try { _test1.CompareTo(TestString); Assert.False(true); } catch (Exception e) { Assert.Equal(typeof(ArgumentException), e.GetType()); } } [Fact] public void GetHashCodeTest() { Assert.Equal(_test1.GetHashCode(), _test1.GetHashCode()); Assert.True(_test2.GetHashCode() != _test1.GetHashCode()); } [Fact] public void GetTypeTest() { Assert.Equal("System.Data.SqlTypes.SqlBinary", _test1.GetType().ToString()); } [Fact] public void Concat() { SqlBinary TestBinary; TestBinary = SqlBinary.Concat(_test2, _test3); Assert.Equal((byte)15, TestBinary[4]); TestBinary = SqlBinary.Concat(_test1, _test2); Assert.Equal((byte)240, TestBinary[0]); Assert.Equal((byte)15, TestBinary[1]); } [Fact] public void ToSqlGuid() { SqlBinary TestBinary = new SqlBinary(new byte[16]); SqlGuid TestGuid = TestBinary.ToSqlGuid(); Assert.True(!TestGuid.IsNull); } [Fact] public void ToStringTest() { Assert.Equal("SqlBinary(3)", _test2.ToString()); Assert.Equal("SqlBinary(2)", _test1.ToString()); } // OPERATORS [Fact] public void AdditionOperator() { SqlBinary TestBinary = _test1 + _test2; Assert.Equal((byte)240, TestBinary[0]); Assert.Equal((byte)15, TestBinary[1]); } [Fact] public void ComparisonOperators() { // Equality Assert.True(!(_test1 == _test2).Value); Assert.True((_test3 == _test1).Value); // Greater than Assert.True((_test1 > _test2).Value); Assert.True(!(_test3 > _test1).Value); // Greater than or equal Assert.True((_test1 >= _test2).Value); Assert.True((_test3 >= _test2).Value); // Inequality Assert.True((_test1 != _test2).Value); Assert.True(!(_test3 != _test1).Value); // Less than Assert.True(!(_test1 < _test2).Value); Assert.True(!(_test3 < _test2).Value); // Less than or equal Assert.True(!(_test1 <= _test2).Value); Assert.True((_test3 <= _test1).Value); } [Fact] public void SqlBinaryToByteArray() { byte[] TestByteArray = (byte[])_test1; Assert.Equal((byte)240, TestByteArray[0]); } [Fact] public void SqlGuidToSqlBinary() { byte[] TestByteArray = new byte[16]; TestByteArray[0] = 15; TestByteArray[1] = 200; SqlGuid TestGuid = new SqlGuid(TestByteArray); SqlBinary TestBinary = (SqlBinary)TestGuid; Assert.Equal((byte)15, TestBinary[0]); } [Fact] public void ByteArrayToSqlBinary() { byte[] TestByteArray = new byte[2]; TestByteArray[0] = 15; TestByteArray[1] = 200; SqlBinary TestBinary = TestByteArray; Assert.Equal((byte)15, TestBinary[0]); } [Fact] public void GetXsdTypeTest() { XmlQualifiedName qualifiedName = SqlBinary.GetXsdType(null); Assert.Equal("base64Binary", qualifiedName.Name); } } }
using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Umeng.Analytics { // Metadata.xml XPath class reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']" [global::Android.Runtime.Register ("com/umeng/analytics/MobclickAgent", DoNotGenerateAcw=true)] public partial class MobclickAgent : global::Java.Lang.Object { internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/umeng/analytics/MobclickAgent", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (MobclickAgent); } } protected MobclickAgent (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor; // Metadata.xml XPath constructor reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/constructor[@name='MobclickAgent' and count(parameter)=0]" [Register (".ctor", "()V", "")] public MobclickAgent () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; if (GetType () != typeof (MobclickAgent)) { SetHandle (global::Android.Runtime.JNIEnv.CreateInstance (GetType (), "()V"), JniHandleOwnership.TransferLocalRef); return; } if (id_ctor == IntPtr.Zero) id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V"); SetHandle (JNIEnv.NewObject (class_ref, id_ctor), JniHandleOwnership.TransferLocalRef); } static IntPtr id_flush_Landroid_content_Context_; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='flush' and count(parameter)=1 and parameter[1][@type='android.content.Context']]" [Register ("flush", "(Landroid/content/Context;)V", "")] public static void Flush (global::Android.Content.Context p0) { if (id_flush_Landroid_content_Context_ == IntPtr.Zero) id_flush_Landroid_content_Context_ = JNIEnv.GetStaticMethodID (class_ref, "flush", "(Landroid/content/Context;)V"); JNIEnv.CallStaticVoidMethod (class_ref, id_flush_Landroid_content_Context_, new JValue (p0)); } static IntPtr id_getConfigParams_Landroid_content_Context_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='getConfigParams' and count(parameter)=2 and parameter[1][@type='android.content.Context'] and parameter[2][@type='java.lang.String']]" [Register ("getConfigParams", "(Landroid/content/Context;Ljava/lang/String;)Ljava/lang/String;", "")] public static string GetConfigParams (global::Android.Content.Context p0, string p1) { if (id_getConfigParams_Landroid_content_Context_Ljava_lang_String_ == IntPtr.Zero) id_getConfigParams_Landroid_content_Context_Ljava_lang_String_ = JNIEnv.GetStaticMethodID (class_ref, "getConfigParams", "(Landroid/content/Context;Ljava/lang/String;)Ljava/lang/String;"); IntPtr native_p1 = JNIEnv.NewString (p1); string __ret = JNIEnv.GetString (JNIEnv.CallStaticObjectMethod (class_ref, id_getConfigParams_Landroid_content_Context_Ljava_lang_String_, new JValue (p0), new JValue (native_p1)), JniHandleOwnership.TransferLocalRef); JNIEnv.DeleteLocalRef (native_p1); return __ret; } static IntPtr id_onError_Landroid_content_Context_; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='onError' and count(parameter)=1 and parameter[1][@type='android.content.Context']]" [Register ("onError", "(Landroid/content/Context;)V", "")] public static void OnError (global::Android.Content.Context p0) { if (id_onError_Landroid_content_Context_ == IntPtr.Zero) id_onError_Landroid_content_Context_ = JNIEnv.GetStaticMethodID (class_ref, "onError", "(Landroid/content/Context;)V"); JNIEnv.CallStaticVoidMethod (class_ref, id_onError_Landroid_content_Context_, new JValue (p0)); } static IntPtr id_onError_Landroid_content_Context_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='onError' and count(parameter)=2 and parameter[1][@type='android.content.Context'] and parameter[2][@type='java.lang.String']]" [Register ("onError", "(Landroid/content/Context;Ljava/lang/String;)V", "")] public static void OnError (global::Android.Content.Context p0, string p1) { if (id_onError_Landroid_content_Context_Ljava_lang_String_ == IntPtr.Zero) id_onError_Landroid_content_Context_Ljava_lang_String_ = JNIEnv.GetStaticMethodID (class_ref, "onError", "(Landroid/content/Context;Ljava/lang/String;)V"); IntPtr native_p1 = JNIEnv.NewString (p1); JNIEnv.CallStaticVoidMethod (class_ref, id_onError_Landroid_content_Context_Ljava_lang_String_, new JValue (p0), new JValue (native_p1)); JNIEnv.DeleteLocalRef (native_p1); } static IntPtr id_onEvent_Landroid_content_Context_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='onEvent' and count(parameter)=2 and parameter[1][@type='android.content.Context'] and parameter[2][@type='java.lang.String']]" [Register ("onEvent", "(Landroid/content/Context;Ljava/lang/String;)V", "")] public static void OnEvent (global::Android.Content.Context p0, string p1) { if (id_onEvent_Landroid_content_Context_Ljava_lang_String_ == IntPtr.Zero) id_onEvent_Landroid_content_Context_Ljava_lang_String_ = JNIEnv.GetStaticMethodID (class_ref, "onEvent", "(Landroid/content/Context;Ljava/lang/String;)V"); IntPtr native_p1 = JNIEnv.NewString (p1); JNIEnv.CallStaticVoidMethod (class_ref, id_onEvent_Landroid_content_Context_Ljava_lang_String_, new JValue (p0), new JValue (native_p1)); JNIEnv.DeleteLocalRef (native_p1); } static IntPtr id_onEvent_Landroid_content_Context_Ljava_lang_String_I; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='onEvent' and count(parameter)=3 and parameter[1][@type='android.content.Context'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='int']]" [Register ("onEvent", "(Landroid/content/Context;Ljava/lang/String;I)V", "")] public static void OnEvent (global::Android.Content.Context p0, string p1, int p2) { if (id_onEvent_Landroid_content_Context_Ljava_lang_String_I == IntPtr.Zero) id_onEvent_Landroid_content_Context_Ljava_lang_String_I = JNIEnv.GetStaticMethodID (class_ref, "onEvent", "(Landroid/content/Context;Ljava/lang/String;I)V"); IntPtr native_p1 = JNIEnv.NewString (p1); JNIEnv.CallStaticVoidMethod (class_ref, id_onEvent_Landroid_content_Context_Ljava_lang_String_I, new JValue (p0), new JValue (native_p1), new JValue (p2)); JNIEnv.DeleteLocalRef (native_p1); } static IntPtr id_onEvent_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='onEvent' and count(parameter)=3 and parameter[1][@type='android.content.Context'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='java.lang.String']]" [Register ("onEvent", "(Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;)V", "")] public static void OnEvent (global::Android.Content.Context p0, string p1, string p2) { if (id_onEvent_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_ == IntPtr.Zero) id_onEvent_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_ = JNIEnv.GetStaticMethodID (class_ref, "onEvent", "(Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;)V"); IntPtr native_p1 = JNIEnv.NewString (p1); IntPtr native_p2 = JNIEnv.NewString (p2); JNIEnv.CallStaticVoidMethod (class_ref, id_onEvent_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_, new JValue (p0), new JValue (native_p1), new JValue (native_p2)); JNIEnv.DeleteLocalRef (native_p1); JNIEnv.DeleteLocalRef (native_p2); } static IntPtr id_onEvent_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_I; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='onEvent' and count(parameter)=4 and parameter[1][@type='android.content.Context'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='java.lang.String'] and parameter[4][@type='int']]" [Register ("onEvent", "(Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;I)V", "")] public static void OnEvent (global::Android.Content.Context p0, string p1, string p2, int p3) { if (id_onEvent_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_I == IntPtr.Zero) id_onEvent_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_I = JNIEnv.GetStaticMethodID (class_ref, "onEvent", "(Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;I)V"); IntPtr native_p1 = JNIEnv.NewString (p1); IntPtr native_p2 = JNIEnv.NewString (p2); JNIEnv.CallStaticVoidMethod (class_ref, id_onEvent_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_I, new JValue (p0), new JValue (native_p1), new JValue (native_p2), new JValue (p3)); JNIEnv.DeleteLocalRef (native_p1); JNIEnv.DeleteLocalRef (native_p2); } static IntPtr id_onEvent_Landroid_content_Context_Ljava_lang_String_Ljava_util_HashMap_; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='onEvent' and count(parameter)=3 and parameter[1][@type='android.content.Context'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='java.util.HashMap']]" [Register ("onEvent", "(Landroid/content/Context;Ljava/lang/String;Ljava/util/HashMap;)V", "")] public static void OnEvent (global::Android.Content.Context p0, string p1, global::System.Collections.Generic.IDictionary<string, string> p2) { if (id_onEvent_Landroid_content_Context_Ljava_lang_String_Ljava_util_HashMap_ == IntPtr.Zero) id_onEvent_Landroid_content_Context_Ljava_lang_String_Ljava_util_HashMap_ = JNIEnv.GetStaticMethodID (class_ref, "onEvent", "(Landroid/content/Context;Ljava/lang/String;Ljava/util/HashMap;)V"); IntPtr native_p1 = JNIEnv.NewString (p1); IntPtr native_p2 = global::Android.Runtime.JavaDictionary<string, string>.ToLocalJniHandle (p2); JNIEnv.CallStaticVoidMethod (class_ref, id_onEvent_Landroid_content_Context_Ljava_lang_String_Ljava_util_HashMap_, new JValue (p0), new JValue (native_p1), new JValue (Java.Interop.JavaObjectExtensions.ToInteroperableCollection (p2))); JNIEnv.DeleteLocalRef (native_p1); JNIEnv.DeleteLocalRef (native_p2); } static IntPtr id_onEventBegin_Landroid_content_Context_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='onEventBegin' and count(parameter)=2 and parameter[1][@type='android.content.Context'] and parameter[2][@type='java.lang.String']]" [Register ("onEventBegin", "(Landroid/content/Context;Ljava/lang/String;)V", "")] public static void OnEventBegin (global::Android.Content.Context p0, string p1) { if (id_onEventBegin_Landroid_content_Context_Ljava_lang_String_ == IntPtr.Zero) id_onEventBegin_Landroid_content_Context_Ljava_lang_String_ = JNIEnv.GetStaticMethodID (class_ref, "onEventBegin", "(Landroid/content/Context;Ljava/lang/String;)V"); IntPtr native_p1 = JNIEnv.NewString (p1); JNIEnv.CallStaticVoidMethod (class_ref, id_onEventBegin_Landroid_content_Context_Ljava_lang_String_, new JValue (p0), new JValue (native_p1)); JNIEnv.DeleteLocalRef (native_p1); } static IntPtr id_onEventBegin_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='onEventBegin' and count(parameter)=3 and parameter[1][@type='android.content.Context'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='java.lang.String']]" [Register ("onEventBegin", "(Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;)V", "")] public static void OnEventBegin (global::Android.Content.Context p0, string p1, string p2) { if (id_onEventBegin_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_ == IntPtr.Zero) id_onEventBegin_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_ = JNIEnv.GetStaticMethodID (class_ref, "onEventBegin", "(Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;)V"); IntPtr native_p1 = JNIEnv.NewString (p1); IntPtr native_p2 = JNIEnv.NewString (p2); JNIEnv.CallStaticVoidMethod (class_ref, id_onEventBegin_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_, new JValue (p0), new JValue (native_p1), new JValue (native_p2)); JNIEnv.DeleteLocalRef (native_p1); JNIEnv.DeleteLocalRef (native_p2); } static IntPtr id_onEventDuration_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_J; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='onEventDuration' and count(parameter)=4 and parameter[1][@type='android.content.Context'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='java.lang.String'] and parameter[4][@type='long']]" [Register ("onEventDuration", "(Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;J)V", "")] public static void OnEventDuration (global::Android.Content.Context p0, string p1, string p2, long p3) { if (id_onEventDuration_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_J == IntPtr.Zero) id_onEventDuration_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_J = JNIEnv.GetStaticMethodID (class_ref, "onEventDuration", "(Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;J)V"); IntPtr native_p1 = JNIEnv.NewString (p1); IntPtr native_p2 = JNIEnv.NewString (p2); JNIEnv.CallStaticVoidMethod (class_ref, id_onEventDuration_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_J, new JValue (p0), new JValue (native_p1), new JValue (native_p2), new JValue (p3)); JNIEnv.DeleteLocalRef (native_p1); JNIEnv.DeleteLocalRef (native_p2); } static IntPtr id_onEventDuration_Landroid_content_Context_Ljava_lang_String_Ljava_util_HashMap_J; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='onEventDuration' and count(parameter)=4 and parameter[1][@type='android.content.Context'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='java.util.HashMap'] and parameter[4][@type='long']]" [Register ("onEventDuration", "(Landroid/content/Context;Ljava/lang/String;Ljava/util/HashMap;J)V", "")] public static void OnEventDuration (global::Android.Content.Context p0, string p1, global::System.Collections.Generic.IDictionary<string, string> p2, long p3) { if (id_onEventDuration_Landroid_content_Context_Ljava_lang_String_Ljava_util_HashMap_J == IntPtr.Zero) id_onEventDuration_Landroid_content_Context_Ljava_lang_String_Ljava_util_HashMap_J = JNIEnv.GetStaticMethodID (class_ref, "onEventDuration", "(Landroid/content/Context;Ljava/lang/String;Ljava/util/HashMap;J)V"); IntPtr native_p1 = JNIEnv.NewString (p1); IntPtr native_p2 = global::Android.Runtime.JavaDictionary<string, string>.ToLocalJniHandle (p2); JNIEnv.CallStaticVoidMethod (class_ref, id_onEventDuration_Landroid_content_Context_Ljava_lang_String_Ljava_util_HashMap_J, new JValue (p0), new JValue (native_p1), new JValue (Java.Interop.JavaObjectExtensions.ToInteroperableCollection (p2)), new JValue (p3)); JNIEnv.DeleteLocalRef (native_p1); JNIEnv.DeleteLocalRef (native_p2); } static IntPtr id_onEventDuration_Landroid_content_Context_Ljava_lang_String_J; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='onEventDuration' and count(parameter)=3 and parameter[1][@type='android.content.Context'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='long']]" [Register ("onEventDuration", "(Landroid/content/Context;Ljava/lang/String;J)V", "")] public static void OnEventDuration (global::Android.Content.Context p0, string p1, long p2) { if (id_onEventDuration_Landroid_content_Context_Ljava_lang_String_J == IntPtr.Zero) id_onEventDuration_Landroid_content_Context_Ljava_lang_String_J = JNIEnv.GetStaticMethodID (class_ref, "onEventDuration", "(Landroid/content/Context;Ljava/lang/String;J)V"); IntPtr native_p1 = JNIEnv.NewString (p1); JNIEnv.CallStaticVoidMethod (class_ref, id_onEventDuration_Landroid_content_Context_Ljava_lang_String_J, new JValue (p0), new JValue (native_p1), new JValue (p2)); JNIEnv.DeleteLocalRef (native_p1); } static IntPtr id_onEventEnd_Landroid_content_Context_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='onEventEnd' and count(parameter)=2 and parameter[1][@type='android.content.Context'] and parameter[2][@type='java.lang.String']]" [Register ("onEventEnd", "(Landroid/content/Context;Ljava/lang/String;)V", "")] public static void OnEventEnd (global::Android.Content.Context p0, string p1) { if (id_onEventEnd_Landroid_content_Context_Ljava_lang_String_ == IntPtr.Zero) id_onEventEnd_Landroid_content_Context_Ljava_lang_String_ = JNIEnv.GetStaticMethodID (class_ref, "onEventEnd", "(Landroid/content/Context;Ljava/lang/String;)V"); IntPtr native_p1 = JNIEnv.NewString (p1); JNIEnv.CallStaticVoidMethod (class_ref, id_onEventEnd_Landroid_content_Context_Ljava_lang_String_, new JValue (p0), new JValue (native_p1)); JNIEnv.DeleteLocalRef (native_p1); } static IntPtr id_onEventEnd_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='onEventEnd' and count(parameter)=3 and parameter[1][@type='android.content.Context'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='java.lang.String']]" [Register ("onEventEnd", "(Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;)V", "")] public static void OnEventEnd (global::Android.Content.Context p0, string p1, string p2) { if (id_onEventEnd_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_ == IntPtr.Zero) id_onEventEnd_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_ = JNIEnv.GetStaticMethodID (class_ref, "onEventEnd", "(Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;)V"); IntPtr native_p1 = JNIEnv.NewString (p1); IntPtr native_p2 = JNIEnv.NewString (p2); JNIEnv.CallStaticVoidMethod (class_ref, id_onEventEnd_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_, new JValue (p0), new JValue (native_p1), new JValue (native_p2)); JNIEnv.DeleteLocalRef (native_p1); JNIEnv.DeleteLocalRef (native_p2); } static IntPtr id_onKVEventBegin_Landroid_content_Context_Ljava_lang_String_Ljava_util_HashMap_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='onKVEventBegin' and count(parameter)=4 and parameter[1][@type='android.content.Context'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='java.util.HashMap'] and parameter[4][@type='java.lang.String']]" [Register ("onKVEventBegin", "(Landroid/content/Context;Ljava/lang/String;Ljava/util/HashMap;Ljava/lang/String;)V", "")] public static void OnKVEventBegin (global::Android.Content.Context p0, string p1, global::System.Collections.Generic.IDictionary<string, string> p2, string p3) { if (id_onKVEventBegin_Landroid_content_Context_Ljava_lang_String_Ljava_util_HashMap_Ljava_lang_String_ == IntPtr.Zero) id_onKVEventBegin_Landroid_content_Context_Ljava_lang_String_Ljava_util_HashMap_Ljava_lang_String_ = JNIEnv.GetStaticMethodID (class_ref, "onKVEventBegin", "(Landroid/content/Context;Ljava/lang/String;Ljava/util/HashMap;Ljava/lang/String;)V"); IntPtr native_p1 = JNIEnv.NewString (p1); IntPtr native_p2 = global::Android.Runtime.JavaDictionary<string, string>.ToLocalJniHandle (p2); IntPtr native_p3 = JNIEnv.NewString (p3); JNIEnv.CallStaticVoidMethod (class_ref, id_onKVEventBegin_Landroid_content_Context_Ljava_lang_String_Ljava_util_HashMap_Ljava_lang_String_, new JValue (p0), new JValue (native_p1), new JValue (Java.Interop.JavaObjectExtensions.ToInteroperableCollection (p2)), new JValue (native_p3)); JNIEnv.DeleteLocalRef (native_p1); JNIEnv.DeleteLocalRef (native_p2); JNIEnv.DeleteLocalRef (native_p3); } static IntPtr id_onKVEventEnd_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='onKVEventEnd' and count(parameter)=3 and parameter[1][@type='android.content.Context'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='java.lang.String']]" [Register ("onKVEventEnd", "(Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;)V", "")] public static void OnKVEventEnd (global::Android.Content.Context p0, string p1, string p2) { if (id_onKVEventEnd_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_ == IntPtr.Zero) id_onKVEventEnd_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_ = JNIEnv.GetStaticMethodID (class_ref, "onKVEventEnd", "(Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;)V"); IntPtr native_p1 = JNIEnv.NewString (p1); IntPtr native_p2 = JNIEnv.NewString (p2); JNIEnv.CallStaticVoidMethod (class_ref, id_onKVEventEnd_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_, new JValue (p0), new JValue (native_p1), new JValue (native_p2)); JNIEnv.DeleteLocalRef (native_p1); JNIEnv.DeleteLocalRef (native_p2); } static IntPtr id_onKillProcess_Landroid_content_Context_; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='onKillProcess' and count(parameter)=1 and parameter[1][@type='android.content.Context']]" [Register ("onKillProcess", "(Landroid/content/Context;)V", "")] public static void OnKillProcess (global::Android.Content.Context p0) { if (id_onKillProcess_Landroid_content_Context_ == IntPtr.Zero) id_onKillProcess_Landroid_content_Context_ = JNIEnv.GetStaticMethodID (class_ref, "onKillProcess", "(Landroid/content/Context;)V"); JNIEnv.CallStaticVoidMethod (class_ref, id_onKillProcess_Landroid_content_Context_, new JValue (p0)); } static IntPtr id_onPause_Landroid_content_Context_; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='onPause' and count(parameter)=1 and parameter[1][@type='android.content.Context']]" [Register ("onPause", "(Landroid/content/Context;)V", "")] public static void OnPause (global::Android.Content.Context p0) { if (id_onPause_Landroid_content_Context_ == IntPtr.Zero) id_onPause_Landroid_content_Context_ = JNIEnv.GetStaticMethodID (class_ref, "onPause", "(Landroid/content/Context;)V"); JNIEnv.CallStaticVoidMethod (class_ref, id_onPause_Landroid_content_Context_, new JValue (p0)); } static IntPtr id_onResume_Landroid_content_Context_; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='onResume' and count(parameter)=1 and parameter[1][@type='android.content.Context']]" [Register ("onResume", "(Landroid/content/Context;)V", "")] public static void OnResume (global::Android.Content.Context p0) { if (id_onResume_Landroid_content_Context_ == IntPtr.Zero) id_onResume_Landroid_content_Context_ = JNIEnv.GetStaticMethodID (class_ref, "onResume", "(Landroid/content/Context;)V"); JNIEnv.CallStaticVoidMethod (class_ref, id_onResume_Landroid_content_Context_, new JValue (p0)); } static IntPtr id_onResume_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='onResume' and count(parameter)=3 and parameter[1][@type='android.content.Context'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='java.lang.String']]" [Register ("onResume", "(Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;)V", "")] public static void OnResume (global::Android.Content.Context p0, string p1, string p2) { if (id_onResume_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_ == IntPtr.Zero) id_onResume_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_ = JNIEnv.GetStaticMethodID (class_ref, "onResume", "(Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;)V"); IntPtr native_p1 = JNIEnv.NewString (p1); IntPtr native_p2 = JNIEnv.NewString (p2); JNIEnv.CallStaticVoidMethod (class_ref, id_onResume_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_, new JValue (p0), new JValue (native_p1), new JValue (native_p2)); JNIEnv.DeleteLocalRef (native_p1); JNIEnv.DeleteLocalRef (native_p2); } static IntPtr id_openActivityDurationTrack_Z; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='openActivityDurationTrack' and count(parameter)=1 and parameter[1][@type='boolean']]" [Register ("openActivityDurationTrack", "(Z)V", "")] public static void OpenActivityDurationTrack (bool p0) { if (id_openActivityDurationTrack_Z == IntPtr.Zero) id_openActivityDurationTrack_Z = JNIEnv.GetStaticMethodID (class_ref, "openActivityDurationTrack", "(Z)V"); JNIEnv.CallStaticVoidMethod (class_ref, id_openActivityDurationTrack_Z, new JValue (p0)); } static IntPtr id_reportError_Landroid_content_Context_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='reportError' and count(parameter)=2 and parameter[1][@type='android.content.Context'] and parameter[2][@type='java.lang.String']]" [Register ("reportError", "(Landroid/content/Context;Ljava/lang/String;)V", "")] public static void ReportError (global::Android.Content.Context p0, string p1) { if (id_reportError_Landroid_content_Context_Ljava_lang_String_ == IntPtr.Zero) id_reportError_Landroid_content_Context_Ljava_lang_String_ = JNIEnv.GetStaticMethodID (class_ref, "reportError", "(Landroid/content/Context;Ljava/lang/String;)V"); IntPtr native_p1 = JNIEnv.NewString (p1); JNIEnv.CallStaticVoidMethod (class_ref, id_reportError_Landroid_content_Context_Ljava_lang_String_, new JValue (p0), new JValue (native_p1)); JNIEnv.DeleteLocalRef (native_p1); } static IntPtr id_reportError_Landroid_content_Context_Ljava_lang_Throwable_; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='reportError' and count(parameter)=2 and parameter[1][@type='android.content.Context'] and parameter[2][@type='java.lang.Throwable']]" [Register ("reportError", "(Landroid/content/Context;Ljava/lang/Throwable;)V", "")] public static void ReportError (global::Android.Content.Context p0, global::Java.Lang.Throwable p1) { if (id_reportError_Landroid_content_Context_Ljava_lang_Throwable_ == IntPtr.Zero) id_reportError_Landroid_content_Context_Ljava_lang_Throwable_ = JNIEnv.GetStaticMethodID (class_ref, "reportError", "(Landroid/content/Context;Ljava/lang/Throwable;)V"); JNIEnv.CallStaticVoidMethod (class_ref, id_reportError_Landroid_content_Context_Ljava_lang_Throwable_, new JValue (p0), new JValue (p1)); } static Delegate cb_setAge_Landroid_content_Context_I; #pragma warning disable 0169 static Delegate GetSetAge_Landroid_content_Context_IHandler () { if (cb_setAge_Landroid_content_Context_I == null) cb_setAge_Landroid_content_Context_I = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr, int>) n_SetAge_Landroid_content_Context_I); return cb_setAge_Landroid_content_Context_I; } static void n_SetAge_Landroid_content_Context_I (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, int p1) { global::Com.Umeng.Analytics.MobclickAgent __this = global::Java.Lang.Object.GetObject<global::Com.Umeng.Analytics.MobclickAgent> (native__this, JniHandleOwnership.DoNotTransfer); global::Android.Content.Context p0 = global::Java.Lang.Object.GetObject<global::Android.Content.Context> (native_p0, JniHandleOwnership.DoNotTransfer); __this.SetAge (p0, p1); } #pragma warning restore 0169 static IntPtr id_setAge_Landroid_content_Context_I; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='setAge' and count(parameter)=2 and parameter[1][@type='android.content.Context'] and parameter[2][@type='int']]" [Register ("setAge", "(Landroid/content/Context;I)V", "GetSetAge_Landroid_content_Context_IHandler")] public virtual void SetAge (global::Android.Content.Context p0, int p1) { if (id_setAge_Landroid_content_Context_I == IntPtr.Zero) id_setAge_Landroid_content_Context_I = JNIEnv.GetMethodID (class_ref, "setAge", "(Landroid/content/Context;I)V"); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_setAge_Landroid_content_Context_I, new JValue (p0), new JValue (p1)); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_setAge_Landroid_content_Context_I, new JValue (p0), new JValue (p1)); } static IntPtr id_setAutoLocation_Z; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='setAutoLocation' and count(parameter)=1 and parameter[1][@type='boolean']]" [Register ("setAutoLocation", "(Z)V", "")] public static void SetAutoLocation (bool p0) { if (id_setAutoLocation_Z == IntPtr.Zero) id_setAutoLocation_Z = JNIEnv.GetStaticMethodID (class_ref, "setAutoLocation", "(Z)V"); JNIEnv.CallStaticVoidMethod (class_ref, id_setAutoLocation_Z, new JValue (p0)); } static IntPtr id_setDebugMode_Z; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='setDebugMode' and count(parameter)=1 and parameter[1][@type='boolean']]" [Register ("setDebugMode", "(Z)V", "")] public static void SetDebugMode (bool p0) { if (id_setDebugMode_Z == IntPtr.Zero) id_setDebugMode_Z = JNIEnv.GetStaticMethodID (class_ref, "setDebugMode", "(Z)V"); JNIEnv.CallStaticVoidMethod (class_ref, id_setDebugMode_Z, new JValue (p0)); } static IntPtr id_setDefaultReportPolicy_Landroid_content_Context_I; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='setDefaultReportPolicy' and count(parameter)=2 and parameter[1][@type='android.content.Context'] and parameter[2][@type='int']]" [Register ("setDefaultReportPolicy", "(Landroid/content/Context;I)V", "")] public static void SetDefaultReportPolicy (global::Android.Content.Context p0, int p1) { if (id_setDefaultReportPolicy_Landroid_content_Context_I == IntPtr.Zero) id_setDefaultReportPolicy_Landroid_content_Context_I = JNIEnv.GetStaticMethodID (class_ref, "setDefaultReportPolicy", "(Landroid/content/Context;I)V"); JNIEnv.CallStaticVoidMethod (class_ref, id_setDefaultReportPolicy_Landroid_content_Context_I, new JValue (p0), new JValue (p1)); } static IntPtr id_setEnableEventBuffer_Z; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='setEnableEventBuffer' and count(parameter)=1 and parameter[1][@type='boolean']]" [Register ("setEnableEventBuffer", "(Z)V", "")] public static void SetEnableEventBuffer (bool p0) { if (id_setEnableEventBuffer_Z == IntPtr.Zero) id_setEnableEventBuffer_Z = JNIEnv.GetStaticMethodID (class_ref, "setEnableEventBuffer", "(Z)V"); JNIEnv.CallStaticVoidMethod (class_ref, id_setEnableEventBuffer_Z, new JValue (p0)); } static Delegate cb_setGender_Landroid_content_Context_Lcom_umeng_analytics_Gender_; #pragma warning disable 0169 static Delegate GetSetGender_Landroid_content_Context_Lcom_umeng_analytics_Gender_Handler () { if (cb_setGender_Landroid_content_Context_Lcom_umeng_analytics_Gender_ == null) cb_setGender_Landroid_content_Context_Lcom_umeng_analytics_Gender_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr, IntPtr>) n_SetGender_Landroid_content_Context_Lcom_umeng_analytics_Gender_); return cb_setGender_Landroid_content_Context_Lcom_umeng_analytics_Gender_; } static void n_SetGender_Landroid_content_Context_Lcom_umeng_analytics_Gender_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1) { global::Com.Umeng.Analytics.MobclickAgent __this = global::Java.Lang.Object.GetObject<global::Com.Umeng.Analytics.MobclickAgent> (native__this, JniHandleOwnership.DoNotTransfer); global::Android.Content.Context p0 = global::Java.Lang.Object.GetObject<global::Android.Content.Context> (native_p0, JniHandleOwnership.DoNotTransfer); global::Com.Umeng.Analytics.Gender p1 = global::Java.Lang.Object.GetObject<global::Com.Umeng.Analytics.Gender> (native_p1, JniHandleOwnership.DoNotTransfer); __this.SetGender (p0, p1); } #pragma warning restore 0169 static IntPtr id_setGender_Landroid_content_Context_Lcom_umeng_analytics_Gender_; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='setGender' and count(parameter)=2 and parameter[1][@type='android.content.Context'] and parameter[2][@type='com.umeng.analytics.Gender']]" [Register ("setGender", "(Landroid/content/Context;Lcom/umeng/analytics/Gender;)V", "GetSetGender_Landroid_content_Context_Lcom_umeng_analytics_Gender_Handler")] public virtual void SetGender (global::Android.Content.Context p0, global::Com.Umeng.Analytics.Gender p1) { if (id_setGender_Landroid_content_Context_Lcom_umeng_analytics_Gender_ == IntPtr.Zero) id_setGender_Landroid_content_Context_Lcom_umeng_analytics_Gender_ = JNIEnv.GetMethodID (class_ref, "setGender", "(Landroid/content/Context;Lcom/umeng/analytics/Gender;)V"); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_setGender_Landroid_content_Context_Lcom_umeng_analytics_Gender_, new JValue (p0), new JValue (p1)); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_setGender_Landroid_content_Context_Lcom_umeng_analytics_Gender_, new JValue (p0), new JValue (p1)); } static IntPtr id_setOnlineConfigureListener_Lcom_umeng_analytics_onlineconfig_UmengOnlineConfigureListener_; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='setOnlineConfigureListener' and count(parameter)=1 and parameter[1][@type='com.umeng.analytics.onlineconfig.UmengOnlineConfigureListener']]" [Register ("setOnlineConfigureListener", "(Lcom/umeng/analytics/onlineconfig/UmengOnlineConfigureListener;)V", "")] public static void SetOnlineConfigureListener (global::Com.Umeng.Analytics.Onlineconfig.IUmengOnlineConfigureListener p0) { if (id_setOnlineConfigureListener_Lcom_umeng_analytics_onlineconfig_UmengOnlineConfigureListener_ == IntPtr.Zero) id_setOnlineConfigureListener_Lcom_umeng_analytics_onlineconfig_UmengOnlineConfigureListener_ = JNIEnv.GetStaticMethodID (class_ref, "setOnlineConfigureListener", "(Lcom/umeng/analytics/onlineconfig/UmengOnlineConfigureListener;)V"); JNIEnv.CallStaticVoidMethod (class_ref, id_setOnlineConfigureListener_Lcom_umeng_analytics_onlineconfig_UmengOnlineConfigureListener_, new JValue (p0)); } static IntPtr id_setOpenGLContext_Ljavax_microedition_khronos_opengles_GL10_; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='setOpenGLContext' and count(parameter)=1 and parameter[1][@type='javax.microedition.khronos.opengles.GL10']]" [Register ("setOpenGLContext", "(Ljavax/microedition/khronos/opengles/GL10;)V", "")] public static void SetOpenGLContext (global::Javax.Microedition.Khronos.Opengles.IGL10 p0) { if (id_setOpenGLContext_Ljavax_microedition_khronos_opengles_GL10_ == IntPtr.Zero) id_setOpenGLContext_Ljavax_microedition_khronos_opengles_GL10_ = JNIEnv.GetStaticMethodID (class_ref, "setOpenGLContext", "(Ljavax/microedition/khronos/opengles/GL10;)V"); JNIEnv.CallStaticVoidMethod (class_ref, id_setOpenGLContext_Ljavax_microedition_khronos_opengles_GL10_, new JValue (p0)); } static IntPtr id_setSessionContinueMillis_J; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='setSessionContinueMillis' and count(parameter)=1 and parameter[1][@type='long']]" [Register ("setSessionContinueMillis", "(J)V", "")] public static void SetSessionContinueMillis (long p0) { if (id_setSessionContinueMillis_J == IntPtr.Zero) id_setSessionContinueMillis_J = JNIEnv.GetStaticMethodID (class_ref, "setSessionContinueMillis", "(J)V"); JNIEnv.CallStaticVoidMethod (class_ref, id_setSessionContinueMillis_J, new JValue (p0)); } static Delegate cb_setUserID_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_; #pragma warning disable 0169 static Delegate GetSetUserID_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_Handler () { if (cb_setUserID_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_ == null) cb_setUserID_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr, IntPtr, IntPtr>) n_SetUserID_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_); return cb_setUserID_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_; } static void n_SetUserID_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1, IntPtr native_p2) { global::Com.Umeng.Analytics.MobclickAgent __this = global::Java.Lang.Object.GetObject<global::Com.Umeng.Analytics.MobclickAgent> (native__this, JniHandleOwnership.DoNotTransfer); global::Android.Content.Context p0 = global::Java.Lang.Object.GetObject<global::Android.Content.Context> (native_p0, JniHandleOwnership.DoNotTransfer); string p1 = JNIEnv.GetString (native_p1, JniHandleOwnership.DoNotTransfer); string p2 = JNIEnv.GetString (native_p2, JniHandleOwnership.DoNotTransfer); __this.SetUserID (p0, p1, p2); } #pragma warning restore 0169 static IntPtr id_setUserID_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='setUserID' and count(parameter)=3 and parameter[1][@type='android.content.Context'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='java.lang.String']]" [Register ("setUserID", "(Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;)V", "GetSetUserID_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_Handler")] public virtual void SetUserID (global::Android.Content.Context p0, string p1, string p2) { if (id_setUserID_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_ == IntPtr.Zero) id_setUserID_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "setUserID", "(Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;)V"); IntPtr native_p1 = JNIEnv.NewString (p1); IntPtr native_p2 = JNIEnv.NewString (p2); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_setUserID_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_, new JValue (p0), new JValue (native_p1), new JValue (native_p2)); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_setUserID_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_, new JValue (p0), new JValue (native_p1), new JValue (native_p2)); JNIEnv.DeleteLocalRef (native_p1); JNIEnv.DeleteLocalRef (native_p2); } static IntPtr id_setWrapper_Ljava_lang_String_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='setWrapper' and count(parameter)=2 and parameter[1][@type='java.lang.String'] and parameter[2][@type='java.lang.String']]" [Register ("setWrapper", "(Ljava/lang/String;Ljava/lang/String;)V", "")] public static void SetWrapper (string p0, string p1) { if (id_setWrapper_Ljava_lang_String_Ljava_lang_String_ == IntPtr.Zero) id_setWrapper_Ljava_lang_String_Ljava_lang_String_ = JNIEnv.GetStaticMethodID (class_ref, "setWrapper", "(Ljava/lang/String;Ljava/lang/String;)V"); IntPtr native_p0 = JNIEnv.NewString (p0); IntPtr native_p1 = JNIEnv.NewString (p1); JNIEnv.CallStaticVoidMethod (class_ref, id_setWrapper_Ljava_lang_String_Ljava_lang_String_, new JValue (native_p0), new JValue (native_p1)); JNIEnv.DeleteLocalRef (native_p0); JNIEnv.DeleteLocalRef (native_p1); } static IntPtr id_updateOnlineConfig_Landroid_content_Context_; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='updateOnlineConfig' and count(parameter)=1 and parameter[1][@type='android.content.Context']]" [Register ("updateOnlineConfig", "(Landroid/content/Context;)V", "")] public static void UpdateOnlineConfig (global::Android.Content.Context p0) { if (id_updateOnlineConfig_Landroid_content_Context_ == IntPtr.Zero) id_updateOnlineConfig_Landroid_content_Context_ = JNIEnv.GetStaticMethodID (class_ref, "updateOnlineConfig", "(Landroid/content/Context;)V"); JNIEnv.CallStaticVoidMethod (class_ref, id_updateOnlineConfig_Landroid_content_Context_, new JValue (p0)); } static IntPtr id_updateOnlineConfig_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_; // Metadata.xml XPath method reference: path="/api/package[@name='com.umeng.analytics']/class[@name='MobclickAgent']/method[@name='updateOnlineConfig' and count(parameter)=3 and parameter[1][@type='android.content.Context'] and parameter[2][@type='java.lang.String'] and parameter[3][@type='java.lang.String']]" [Register ("updateOnlineConfig", "(Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;)V", "")] public static void UpdateOnlineConfig (global::Android.Content.Context p0, string p1, string p2) { if (id_updateOnlineConfig_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_ == IntPtr.Zero) id_updateOnlineConfig_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_ = JNIEnv.GetStaticMethodID (class_ref, "updateOnlineConfig", "(Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;)V"); IntPtr native_p1 = JNIEnv.NewString (p1); IntPtr native_p2 = JNIEnv.NewString (p2); JNIEnv.CallStaticVoidMethod (class_ref, id_updateOnlineConfig_Landroid_content_Context_Ljava_lang_String_Ljava_lang_String_, new JValue (p0), new JValue (native_p1), new JValue (native_p2)); JNIEnv.DeleteLocalRef (native_p1); JNIEnv.DeleteLocalRef (native_p2); } #region "Event implementation for Com.Umeng.Analytics.Onlineconfig.IUmengOnlineConfigureListener" public event EventHandler<global::Com.Umeng.Analytics.Onlineconfig.UmengOnlineConfigureEventArgs> lineConfigure { add { global::Java.Interop.EventHelper.AddEventHandler<global::Com.Umeng.Analytics.Onlineconfig.IUmengOnlineConfigureListener, global::Com.Umeng.Analytics.Onlineconfig.IUmengOnlineConfigureListenerImplementor>( ref weak_implementor_SetOnlineConfigureListener, __CreateIUmengOnlineConfigureListenerImplementor, SetOnlineConfigureListener, __h => __h.Handler += value); } remove { global::Java.Interop.EventHelper.RemoveEventHandler<global::Com.Umeng.Analytics.Onlineconfig.IUmengOnlineConfigureListener, global::Com.Umeng.Analytics.Onlineconfig.IUmengOnlineConfigureListenerImplementor>( ref weak_implementor_SetOnlineConfigureListener, global::Com.Umeng.Analytics.Onlineconfig.IUmengOnlineConfigureListenerImplementor.__IsEmpty, __v => SetOnlineConfigureListener (null), __h => __h.Handler -= value); } } WeakReference weak_implementor_SetOnlineConfigureListener; global::Com.Umeng.Analytics.Onlineconfig.IUmengOnlineConfigureListenerImplementor __CreateIUmengOnlineConfigureListenerImplementor () { return new global::Com.Umeng.Analytics.Onlineconfig.IUmengOnlineConfigureListenerImplementor (this); } #endregion } }
// // XslVariable.cs // // Authors: // Ben Maurer (bmaurer@users.sourceforge.net) // Atsushi Enomoto (ginga@kit.hi-ho.ne.jp) // // (C) 2003 Ben Maurer // (C) 2003 Atsushi Enomoto // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Xml; using System.Xml.XPath; using System.Xml.Xsl; using Mono.Xml.XPath; using QName = System.Xml.XmlQualifiedName; namespace Mono.Xml.Xsl.Operations { internal class XslVariableInformation { QName name; XPathExpression select; XslOperation content; public XslVariableInformation (Compiler c) { c.CheckExtraAttributes (c.Input.LocalName, "name", "select"); c.AssertAttribute ("name"); name = c.ParseQNameAttribute ("name"); try { XmlConvert.VerifyName (name.Name); } catch (XmlException ex) { throw new XsltCompileException ("Variable name is not qualified name", ex, c.Input); } string sel = c.GetAttribute ("select"); if (sel != null && sel != "" ) { select = c.CompileExpression (c.GetAttribute ("select")); // TODO assert empty } else if (c.Input.MoveToFirstChild ()) { content = c.CompileTemplateContent (); c.Input.MoveToParent (); } } public object Evaluate (XslTransformProcessor p) { if (select != null) { object o = p.Evaluate (select); // To resolve variable references correctly, we // have to collect all the target nodes here. // (otherwise, variables might be resolved with // different level of variable stack in // XslTransformProcessor). if (o is XPathNodeIterator) { ArrayList al = new ArrayList (); XPathNodeIterator iter = (XPathNodeIterator) o; while (iter.MoveNext ()) al.Add (iter.Current.Clone ()); o = new ListIterator (al, p.XPathContext); } return o; } else if (content != null) { DTMXPathDocumentWriter2 w = new DTMXPathDocumentWriter2 (p.Root.NameTable, 200); Outputter outputter = new GenericOutputter(w, p.Outputs, null, true); p.PushOutput (outputter); if (p.CurrentNodeset.CurrentPosition == 0) p.NodesetMoveNext (); content.Evaluate (p); p.PopOutput (); return w.CreateDocument ().CreateNavigator (); } else { return ""; } } public QName Name { get { return name; }} internal XPathExpression Select { get { return select; } } internal XslOperation Content { get { return content; } } } internal abstract class XslGeneralVariable : XslCompiledElement, IXsltContextVariable { protected XslVariableInformation var; public XslGeneralVariable (Compiler c) : base (c) {} protected override void Compile (Compiler c) { if (c.Debugger != null) c.Debugger.DebugCompile (this.DebugInput); this.var = new XslVariableInformation (c); } public override abstract void Evaluate (XslTransformProcessor p); protected abstract object GetValue (XslTransformProcessor p); public object Evaluate (XsltContext xsltContext) { object value = GetValue (((XsltCompiledContext)xsltContext).Processor); if (value is XPathNodeIterator) return new WrapperIterator (((XPathNodeIterator)value).Clone (), xsltContext); return value; } public QName Name {get {return var.Name;}} public XPathResultType VariableType { get {return XPathResultType.Any;}} public abstract bool IsLocal { get; } public abstract bool IsParam { get; } } internal class XslGlobalVariable : XslGeneralVariable { public XslGlobalVariable (Compiler c) : base (c) {} static object busyObject = new Object (); public override void Evaluate (XslTransformProcessor p) { if (p.Debugger != null) p.Debugger.DebugExecute (p, this.DebugInput); Hashtable varInfo = p.globalVariableTable; if (varInfo.Contains (this)) { if (varInfo [this] == busyObject) throw new XsltException ("Circular dependency was detected", null, p.CurrentNode); return; } varInfo [this] = busyObject; varInfo [this] = var.Evaluate (p); } protected override object GetValue (XslTransformProcessor p) { Evaluate (p); return p.globalVariableTable [this]; } public override bool IsLocal { get { return false; }} public override bool IsParam { get { return false; }} } internal class XslGlobalParam : XslGlobalVariable { public XslGlobalParam (Compiler c) : base (c) {} public void Override (XslTransformProcessor p, object paramVal) { Debug.Assert (!p.globalVariableTable.Contains (this), "Shouldn't have been evaluated by this point"); p.globalVariableTable [this] = paramVal; } public override bool IsParam { get { return true; }} } internal class XslLocalVariable : XslGeneralVariable { protected int slot; public XslLocalVariable (Compiler c) : base (c) { slot = c.AddVariable (this); } public override void Evaluate (XslTransformProcessor p) { if (p.Debugger != null) p.Debugger.DebugExecute (p, this.DebugInput); p.SetStackItem (slot, var.Evaluate (p)); } protected override object GetValue (XslTransformProcessor p) { return p.GetStackItem (slot); } public bool IsEvaluated (XslTransformProcessor p) { return p.GetStackItem (slot) != null; } public override bool IsLocal { get { return true; }} public override bool IsParam { get { return false; }} } internal class XslLocalParam : XslLocalVariable { public XslLocalParam (Compiler c) : base (c) {} public override void Evaluate (XslTransformProcessor p) { if (p.Debugger != null) p.Debugger.DebugExecute (p, this.DebugInput); if (p.GetStackItem (slot) != null) return; // evaluated already if (p.Arguments != null && var.Select == null && var.Content == null) { object val = p.Arguments.GetParam (Name.Name, Name.Namespace); if (val != null) { Override (p, val); return; } } base.Evaluate (p); } public void Override (XslTransformProcessor p, object paramVal) { p.SetStackItem (slot, paramVal); } public override bool IsParam { get { return true; }} } internal class XPathVariableBinding : Expression { XslGeneralVariable v; public XPathVariableBinding (XslGeneralVariable v) { this.v = v; } public override String ToString () { return "$" + v.Name.ToString (); } public override XPathResultType ReturnType { get { return XPathResultType.Any; }} public override XPathResultType GetReturnType (BaseIterator iter) { return XPathResultType.Any; } public override object Evaluate (BaseIterator iter) { return v.Evaluate (iter.NamespaceManager as XsltContext); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace VirtualSales.Web.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// 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.Win32.SafeHandles; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Net.Sockets; using System.Security; using System.Threading; using System.Threading.Tasks; namespace System.IO.Pipes { public abstract partial class PipeStream : Stream { // The Windows implementation of PipeStream sets the stream's handle during // creation, and as such should always have a handle, but the Unix implementation // sometimes sets the handle not during creation but later during connection. // As such, validation during member access needs to verify a valid handle on // Windows, but can't assume a valid handle on Unix. internal const bool CheckOperationsRequiresSetHandle = false; /// <summary>Characters that can't be used in a pipe's name.</summary> private static readonly char[] s_invalidFileNameChars = Path.GetInvalidFileNameChars(); /// <summary>Prefix to prepend to all pipe names.</summary> private static readonly string s_pipePrefix = Path.Combine(Path.GetTempPath(), "CoreFxPipe_"); internal static string GetPipePath(string serverName, string pipeName) { if (serverName != "." && serverName != Interop.Sys.GetHostName()) { // Cross-machine pipes are not supported. throw new PlatformNotSupportedException(SR.PlatformNotSupported_RemotePipes); } if (string.Equals(pipeName, AnonymousPipeName, StringComparison.OrdinalIgnoreCase)) { // Match Windows constraint throw new ArgumentOutOfRangeException(nameof(pipeName), SR.ArgumentOutOfRange_AnonymousReserved); } if (pipeName.IndexOfAny(s_invalidFileNameChars) >= 0) { // Since pipes are stored as files in the file system, we don't support // pipe names that are actually paths or that otherwise have invalid // filename characters in them. throw new PlatformNotSupportedException(SR.PlatformNotSupproted_InvalidNameChars); } // Return the pipe path. The pipe is created directly under %TMPDIR%. We previously // didn't put it into a subdirectory because it only existed on disk for the duration // between when the server started listening in WaitForConnection and when the client // connected, after which the pipe was deleted. We now create the pipe when the // server stream is created, which leaves it on disk longer, but we can't change the // naming scheme used as that breaks the ability for code running on an older // runtime to connect to code running on the newer runtime. That means we're stuck // with a tmp file for the lifetime of the server stream. return s_pipePrefix + pipeName; } /// <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) { if (safePipeHandle.NamedPipeSocket == null) { Interop.Sys.FileStatus status; int result = CheckPipeCall(Interop.Sys.FStat(safePipeHandle, out status)); if (result == 0) { if ((status.Mode & Interop.Sys.FileTypes.S_IFMT) != Interop.Sys.FileTypes.S_IFIFO && (status.Mode & Interop.Sys.FileTypes.S_IFMT) != Interop.Sys.FileTypes.S_IFSOCK) { throw new IOException(SR.IO_InvalidPipeHandle); } } } } /// <summary>Initializes the handle to be used asynchronously.</summary> /// <param name="handle">The handle.</param> [SecurityCritical] private void InitializeAsyncHandle(SafePipeHandle handle) { // nop } internal virtual void DisposeCore(bool disposing) { // nop } private unsafe int ReadCore(Span<byte> buffer) { DebugAssertHandleValid(_handle); // For named pipes, receive on the socket. Socket socket = _handle.NamedPipeSocket; if (socket != null) { // For a blocking socket, we could simply use the same Read syscall as is done // for reading an anonymous pipe. However, for a non-blocking socket, Read could // end up returning EWOULDBLOCK rather than blocking waiting for data. Such a case // is already handled by Socket.Receive, so we use it here. try { return socket.Receive(buffer, SocketFlags.None); } catch (SocketException e) { throw GetIOExceptionForSocketException(e); } } // For anonymous pipes, read from the file descriptor. fixed (byte* bufPtr = &buffer.DangerousGetPinnableReference()) { int result = CheckPipeCall(Interop.Sys.Read(_handle, bufPtr, buffer.Length)); Debug.Assert(result <= buffer.Length); return result; } } private unsafe void WriteCore(ReadOnlySpan<byte> buffer) { DebugAssertHandleValid(_handle); // For named pipes, send to the socket. Socket socket = _handle.NamedPipeSocket; if (socket != null) { // For a blocking socket, we could simply use the same Write syscall as is done // for writing to anonymous pipe. However, for a non-blocking socket, Write could // end up returning EWOULDBLOCK rather than blocking waiting for space available. // Such a case is already handled by Socket.Send, so we use it here. try { while (buffer.Length > 0) { int bytesWritten = socket.Send(buffer, SocketFlags.None); buffer = buffer.Slice(bytesWritten); } } catch (SocketException e) { throw GetIOExceptionForSocketException(e); } } // For anonymous pipes, write the file descriptor. fixed (byte* bufPtr = &buffer.DangerousGetPinnableReference()) { while (buffer.Length > 0) { int bytesWritten = CheckPipeCall(Interop.Sys.Write(_handle, bufPtr, buffer.Length)); buffer = buffer.Slice(bytesWritten); } } } private async Task<int> ReadAsyncCore(Memory<byte> destination, CancellationToken cancellationToken) { Debug.Assert(this is NamedPipeClientStream || this is NamedPipeServerStream, $"Expected a named pipe, got a {GetType()}"); Socket socket = InternalHandle.NamedPipeSocket; try { // TODO #22608: // Remove all of this cancellation workaround once Socket.ReceiveAsync // that accepts a CancellationToken is available. // If a cancelable token is used and there's no data, issue a zero-length read so that // we're asynchronously notified when data is available, and concurrently monitor the // supplied cancellation token. If cancellation is requested, we will end up "leaking" // the zero-length read until data becomes available, at which point it'll be satisfied. // But it's very rare to reuse a stream after an operation has been canceled, so even if // we do incur such a situation, it's likely to be very short lived. if (cancellationToken.CanBeCanceled) { cancellationToken.ThrowIfCancellationRequested(); if (socket.Available == 0) { Task<int> t = socket.ReceiveAsync(Array.Empty<byte>(), SocketFlags.None); if (!t.IsCompletedSuccessfully) { var cancelTcs = new TaskCompletionSource<bool>(); using (cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).TrySetResult(true), cancelTcs)) { if (t == await Task.WhenAny(t, cancelTcs.Task).ConfigureAwait(false)) { t.GetAwaiter().GetResult(); // propagate any failure } cancellationToken.ThrowIfCancellationRequested(); // At this point there was data available. In the rare case where multiple concurrent // ReadAsyncs are issued against the PipeStream, worst case is the reads that lose // the race condition for the data will end up in a non-cancelable state as part of // the actual async receive operation. } } } } // Issue the asynchronous read. return await (destination.TryGetArray(out ArraySegment<byte> buffer) ? socket.ReceiveAsync(buffer, SocketFlags.None) : socket.ReceiveAsync(destination.ToArray(), SocketFlags.None)).ConfigureAwait(false); } catch (SocketException e) { throw GetIOExceptionForSocketException(e); } } private async Task WriteAsyncCore(ReadOnlyMemory<byte> source, CancellationToken cancellationToken) { Debug.Assert(this is NamedPipeClientStream || this is NamedPipeServerStream, $"Expected a named pipe, got a {GetType()}"); try { // TODO #22608: Remove this terribly inefficient special-case once Socket.SendAsync // accepts a Memory<T> in the near future. byte[] buffer; int offset, count; if (source.DangerousTryGetArray(out ArraySegment<byte> segment)) { buffer = segment.Array; offset = segment.Offset; count = segment.Count; } else { buffer = source.ToArray(); offset = 0; count = buffer.Length; } while (count > 0) { // cancellationToken is (mostly) ignored. We could institute a polling loop like we do for reads if // cancellationToken.CanBeCanceled, but that adds costs regardless of whether the operation will be canceled, and // most writes will complete immediately as they simply store data into the socket's buffer. The only time we end // up using it in a meaningful way is if a write completes partially, we'll check it on each individual write operation. cancellationToken.ThrowIfCancellationRequested(); int bytesWritten = await _handle.NamedPipeSocket.SendAsync(new ArraySegment<byte>(buffer, offset, count), SocketFlags.None).ConfigureAwait(false); Debug.Assert(bytesWritten <= count); count -= bytesWritten; offset += bytesWritten; } } catch (SocketException e) { throw GetIOExceptionForSocketException(e); } } private IOException GetIOExceptionForSocketException(SocketException e) { if (e.SocketErrorCode == SocketError.Shutdown) // EPIPE { State = PipeState.Broken; } return new IOException(e.Message, e); } // Blocks until the other end of the pipe has read in all written buffer. [SecurityCritical] public void WaitForPipeDrain() { CheckWriteOperations(); if (!CanWrite) { throw Error.GetWriteNotSupported(); } // For named pipes on sockets, we could potentially partially implement this // via ioctl and TIOCOUTQ, which provides the number of unsent bytes. However, // that would require polling, and it wouldn't actually mean that the other // end has read all of the data, just that the data has left this end's buffer. throw new PlatformNotSupportedException(); // not fully implementable on unix } // 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(); return PipeTransmissionMode.Byte; // Unix pipes are only byte-based, not message-based } } // 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); } return GetPipeBufferSize(); } } // 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); } return GetPipeBufferSize(); } } public virtual PipeTransmissionMode ReadMode { [SecurityCritical] get { CheckPipePropertyOperations(); return PipeTransmissionMode.Byte; // Unix pipes are only byte-based, not message-based } [SecurityCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")] set { CheckPipePropertyOperations(); if (value < PipeTransmissionMode.Byte || value > PipeTransmissionMode.Message) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_TransmissionModeByteOrMsg); } if (value != PipeTransmissionMode.Byte) // Unix pipes are only byte-based, not message-based { throw new PlatformNotSupportedException(SR.PlatformNotSupported_MessageTransmissionMode); } // nop, since it's already the only valid value } } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- /// <summary> /// We want to ensure that only one asynchronous operation is actually in flight /// at a time. The base Stream class ensures this by serializing execution via a /// semaphore. Since we don't delegate to the base stream for Read/WriteAsync due /// to having specialized support for cancellation, we do the same serialization here. /// </summary> private SemaphoreSlim _asyncActiveSemaphore; private SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized() { return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1)); } private static void CreateDirectory(string directoryPath) { int result = Interop.Sys.MkDir(directoryPath, (int)Interop.Sys.Permissions.Mask); // If successful created, we're done. if (result >= 0) return; // If the directory already exists, consider it a success. Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.EEXIST) return; // Otherwise, fail. throw Interop.GetExceptionForIoErrno(errorInfo, directoryPath, isDirectory: true); } /// <summary>Creates an anonymous pipe.</summary> /// <param name="inheritability">The inheritability to try to use. This may not always be honored, depending on platform.</param> /// <param name="reader">The resulting reader end of the pipe.</param> /// <param name="writer">The resulting writer end of the pipe.</param> internal static unsafe void CreateAnonymousPipe( HandleInheritability inheritability, out SafePipeHandle reader, out SafePipeHandle writer) { // Allocate the safe handle objects prior to calling pipe/pipe2, in order to help slightly in low-mem situations reader = new SafePipeHandle(); writer = new SafePipeHandle(); // Create the OS pipe int* fds = stackalloc int[2]; CreateAnonymousPipe(inheritability, fds); // Store the file descriptors into our safe handles reader.SetHandle(fds[Interop.Sys.ReadEndOfPipe]); writer.SetHandle(fds[Interop.Sys.WriteEndOfPipe]); } internal int CheckPipeCall(int result) { if (result == -1) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.EPIPE) State = PipeState.Broken; throw Interop.GetExceptionForIoErrno(errorInfo); } return result; } private int GetPipeBufferSize() { if (!Interop.Sys.Fcntl.CanGetSetPipeSz) { throw new PlatformNotSupportedException(); // OS does not support getting pipe size } // If we have a handle, get the capacity of the pipe (there's no distinction between in/out direction). // If we don't, just return the buffer size that was passed to the constructor. return _handle != null ? CheckPipeCall(Interop.Sys.Fcntl.GetPipeSz(_handle)) : _outBufferSize; } internal static unsafe void CreateAnonymousPipe(HandleInheritability inheritability, int* fdsptr) { var flags = (inheritability & HandleInheritability.Inheritable) == 0 ? Interop.Sys.PipeFlags.O_CLOEXEC : 0; Interop.CheckIo(Interop.Sys.Pipe(fdsptr, flags)); } internal static void ConfigureSocket( Socket s, SafePipeHandle pipeHandle, PipeDirection direction, int inBufferSize, int outBufferSize, HandleInheritability inheritability) { if (inBufferSize > 0) { s.ReceiveBufferSize = inBufferSize; } if (outBufferSize > 0) { s.SendBufferSize = outBufferSize; } if (inheritability != HandleInheritability.Inheritable) { Interop.Sys.Fcntl.SetCloseOnExec(pipeHandle); // ignore failures, best-effort attempt } switch (direction) { case PipeDirection.In: s.Shutdown(SocketShutdown.Send); break; case PipeDirection.Out: s.Shutdown(SocketShutdown.Receive); break; } } } }
#if !UNITY_WINRT || UNITY_EDITOR || UNITY_WP8 #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 #pragma warning disable 436 using System; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime.Serialization; #if !((UNITY_WINRT && !UNITY_EDITOR)) using System.Security.Permissions; #endif using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Serialization { internal interface IMetadataTypeAttribute { Type MetadataClassType { get; } } internal static class JsonTypeReflector { public const string IdPropertyName = "$id"; public const string RefPropertyName = "$ref"; public const string TypePropertyName = "$type"; public const string ValuePropertyName = "$value"; public const string ArrayValuesPropertyName = "$values"; public const string ShouldSerializePrefix = "ShouldSerialize"; public const string SpecifiedPostfix = "Specified"; private static readonly ThreadSafeStore<ICustomAttributeProvider, Type> JsonConverterTypeCache = new ThreadSafeStore<ICustomAttributeProvider, Type>(GetJsonConverterTypeFromAttribute); #if !UNITY_WP8 && (!UNITY_WINRT || UNITY_EDITOR) private static readonly ThreadSafeStore<Type, Type> AssociatedMetadataTypesCache = new ThreadSafeStore<Type, Type>(GetAssociateMetadataTypeFromAttribute); private const string MetadataTypeAttributeTypeName = "System.ComponentModel.DataAnnotations.MetadataTypeAttribute, System.ComponentModel.DataAnnotations, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; private static Type _cachedMetadataTypeAttributeType; #endif public static JsonContainerAttribute GetJsonContainerAttribute(Type type) { return CachedAttributeGetter<JsonContainerAttribute>.GetAttribute(type); } public static JsonObjectAttribute GetJsonObjectAttribute(Type type) { return GetJsonContainerAttribute(type) as JsonObjectAttribute; } public static JsonArrayAttribute GetJsonArrayAttribute(Type type) { return GetJsonContainerAttribute(type) as JsonArrayAttribute; } public static DataContractAttribute GetDataContractAttribute(Type type) { // DataContractAttribute does not have inheritance DataContractAttribute result = null; Type currentType = type; while (result == null && currentType != null) { result = CachedAttributeGetter<DataContractAttribute>.GetAttribute(currentType); currentType = currentType.BaseType; } return result; } public static DataMemberAttribute GetDataMemberAttribute(MemberInfo memberInfo) { // DataMemberAttribute does not have inheritance // can't override a field if (memberInfo.MemberType == MemberTypes.Field) return CachedAttributeGetter<DataMemberAttribute>.GetAttribute(memberInfo); // search property and then search base properties if nothing is returned and the property is virtual PropertyInfo propertyInfo = (PropertyInfo) memberInfo; DataMemberAttribute result = CachedAttributeGetter<DataMemberAttribute>.GetAttribute(propertyInfo); if (result == null) { if (propertyInfo.IsVirtual()) { Type currentType = propertyInfo.DeclaringType; while (result == null && currentType != null) { PropertyInfo baseProperty = (PropertyInfo)ReflectionUtils.GetMemberInfoFromType(currentType, propertyInfo); if (baseProperty != null && baseProperty.IsVirtual()) result = CachedAttributeGetter<DataMemberAttribute>.GetAttribute(baseProperty); currentType = currentType.BaseType; } } } return result; } public static MemberSerialization GetObjectMemberSerialization(Type objectType) { JsonObjectAttribute objectAttribute = GetJsonObjectAttribute(objectType); if (objectAttribute == null) { DataContractAttribute dataContractAttribute = GetDataContractAttribute(objectType); if (dataContractAttribute != null) return MemberSerialization.OptIn; return MemberSerialization.OptOut; } return objectAttribute.MemberSerialization; } private static Type GetJsonConverterType(ICustomAttributeProvider attributeProvider) { return JsonConverterTypeCache.Get(attributeProvider); } private static Type GetJsonConverterTypeFromAttribute(ICustomAttributeProvider attributeProvider) { JsonConverterAttribute converterAttribute = GetAttribute<JsonConverterAttribute>(attributeProvider); return (converterAttribute != null) ? converterAttribute.ConverterType : null; } public static JsonConverter GetJsonConverter(ICustomAttributeProvider attributeProvider, Type targetConvertedType) { Type converterType = GetJsonConverterType(attributeProvider); if (converterType != null) { JsonConverter memberConverter = JsonConverterAttribute.CreateJsonConverterInstance(converterType); if (!memberConverter.CanConvert(targetConvertedType)) throw new JsonSerializationException("JsonConverter {0} on {1} is not compatible with member type {2}.".FormatWith(CultureInfo.InvariantCulture, memberConverter.GetType().Name, attributeProvider, targetConvertedType.Name)); return memberConverter; } return null; } #if !(UNITY_WP8 || (UNITY_WINRT && !UNITY_EDITOR)) public static TypeConverter GetTypeConverter(Type type) { #if !(UNITY_WP8 || (UNITY_WINRT && !UNITY_EDITOR)) return TypeDescriptor.GetConverter(type); #else Type converterType = GetTypeConverterType(type); if (converterType != null) return (TypeConverter)ReflectionUtils.CreateInstance(converterType); return null; #endif } #endif #if !(UNITY_WP8 || (UNITY_WINRT && !UNITY_EDITOR)) private static Type GetAssociatedMetadataType(Type type) { return AssociatedMetadataTypesCache.Get(type); } private static Type GetAssociateMetadataTypeFromAttribute(Type type) { Type metadataTypeAttributeType = GetMetadataTypeAttributeType(); if (metadataTypeAttributeType == null) return null; object attribute = type.GetCustomAttributes(metadataTypeAttributeType, true).SingleOrDefault(); if (attribute == null) return null; IMetadataTypeAttribute metadataTypeAttribute = (DynamicCodeGeneration) ? DynamicWrapper.CreateWrapper<IMetadataTypeAttribute>(attribute) : new LateBoundMetadataTypeAttribute(attribute); return metadataTypeAttribute.MetadataClassType; } private static Type GetMetadataTypeAttributeType() { // always attempt to get the metadata type attribute type // the assembly may have been loaded since last time if (_cachedMetadataTypeAttributeType == null) { Type metadataTypeAttributeType = Type.GetType(MetadataTypeAttributeTypeName); if (metadataTypeAttributeType != null) _cachedMetadataTypeAttributeType = metadataTypeAttributeType; else return null; } return _cachedMetadataTypeAttributeType; } #endif private static T GetAttribute<T>(Type type) where T : Attribute { T attribute; #if !(UNITY_WP8 || (UNITY_WINRT && !UNITY_EDITOR)) Type metadataType = GetAssociatedMetadataType(type); if (metadataType != null) { attribute = ReflectionUtils.GetAttribute<T>(metadataType, true); if (attribute != null) return attribute; } #endif attribute = ReflectionUtils.GetAttribute<T>(type, true); if (attribute != null) return attribute; foreach (Type typeInterface in type.GetInterfaces()) { attribute = ReflectionUtils.GetAttribute<T>(typeInterface, true); if (attribute != null) return attribute; } return null; } private static T GetAttribute<T>(MemberInfo memberInfo) where T : Attribute { T attribute; #if !(UNITY_WP8 || (UNITY_WINRT && !UNITY_EDITOR)) Type metadataType = GetAssociatedMetadataType(memberInfo.DeclaringType); if (metadataType != null) { MemberInfo metadataTypeMemberInfo = ReflectionUtils.GetMemberInfoFromType(metadataType, memberInfo); if (metadataTypeMemberInfo != null) { attribute = ReflectionUtils.GetAttribute<T>(metadataTypeMemberInfo, true); if (attribute != null) return attribute; } } #endif attribute = ReflectionUtils.GetAttribute<T>(memberInfo, true); if (attribute != null) return attribute; foreach (Type typeInterface in memberInfo.DeclaringType.GetInterfaces()) { MemberInfo interfaceTypeMemberInfo = ReflectionUtils.GetMemberInfoFromType(typeInterface, memberInfo); if (interfaceTypeMemberInfo != null) { attribute = ReflectionUtils.GetAttribute<T>(interfaceTypeMemberInfo, true); if (attribute != null) return attribute; } } return null; } public static T GetAttribute<T>(ICustomAttributeProvider attributeProvider) where T : Attribute { Type type = attributeProvider as Type; if (type != null) return GetAttribute<T>(type); MemberInfo memberInfo = attributeProvider as MemberInfo; if (memberInfo != null) return GetAttribute<T>(memberInfo); return ReflectionUtils.GetAttribute<T>(attributeProvider, true); } private static bool? _dynamicCodeGeneration; public static bool DynamicCodeGeneration { get { if (_dynamicCodeGeneration == null) { #if !(UNITY_ANDROID || UNITY_WEBPLAYER || (UNITY_IOS || UNITY_IPHONE) || UNITY_WP8 || (UNITY_WINRT && !UNITY_EDITOR)) try { new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand(); new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess).Demand(); #pragma warning disable 618 new SecurityPermission(SecurityPermissionFlag.SkipVerification).Demand(); new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); #pragma warning restore 108 new SecurityPermission(PermissionState.Unrestricted).Demand(); _dynamicCodeGeneration = true; } catch (Exception) { _dynamicCodeGeneration = false; } #else _dynamicCodeGeneration = false; #endif } return _dynamicCodeGeneration.Value; } } public static ReflectionDelegateFactory ReflectionDelegateFactory { get { #if !(UNITY_WP8 || (UNITY_WINRT && !UNITY_EDITOR)) if (DynamicCodeGeneration) return DynamicReflectionDelegateFactory.Instance; #endif return LateBoundReflectionDelegateFactory.Instance; } } } } #pragma warning restore 436 #endif
using System; using System.Diagnostics; using System.IO; using System.Reflection; using csscript; using CSScripting; using CSScriptLib; using Xunit; namespace EvaluatorTests { public class Generic_CodeDom { [Fact] public void using_CompilerOptions() { // Note if you give AssemblyFile the name with the extension .dll xUnit runtime will lock the file simply // because it was present in the local dir. So hide the assembly by dropping the file extension and giving the name "using_CompilerOptions". var info = new CompileInfo { CompilerOptions = "-define:test", AssemblyFile = nameof(using_CompilerOptions).GetFullPath() }; Assembly asm = CSScript.CodeDomEvaluator.CompileCode( @"using System; public class Script { public int Sum(int a, int b) { #if test return -(a+b); #else return a+b; #endif } }", info); dynamic script = asm.CreateObject("*"); var result = script.Sum(7, 3); Assert.Equal(-10, result); } [Fact] public void call_UnloadAssembly() { dynamic script = CSScript.CodeDomEvaluator .With(eval => eval.IsAssemblyUnloadingEnabled = true) .LoadMethod(@"public object func() { return new[] {0,5}; }"); var result = (int[])script.func(); var asm_type = (Type)script.GetType(); asm_type.Assembly.Unload(); } [Fact] public void call_LoadMethod() { CSScript.EvaluatorConfig.DebugBuild = true; CodeDomEvaluator.CompileOnServer = true; dynamic script = CSScript.CodeDomEvaluator .LoadMethod(@"public object func() { return new[] {0,5}; }"); var result = (int[])script.func(); Profiler.Stopwatch.Start(); script = CSScript.CodeDomEvaluator .LoadMethod(@"public object func() { return 77; }"); var resultsum = (int)script.func(); var time = Profiler.Stopwatch.ElapsedMilliseconds; Assert.Equal(0, result[0]); Assert.Equal(5, result[1]); } [Fact] public void call_CompileMethod() { dynamic script = CSScript.CodeDomEvaluator .CompileMethod(@"public object func() => new[] {0,5}; ") .CreateObject("*.DynamicClass"); var result = (int[])script.func(); Assert.Equal(0, result[0]); Assert.Equal(5, result[1]); } [Fact] public void referencing_script_types_from_another_script() { CSScript.EvaluatorConfig.DebugBuild = true; CSScript.EvaluatorConfig.ReferenceDomainAssemblies = false; var info = new CompileInfo { AssemblyFile = "utils_asm" }; try { var utils_code = @"using System; using System.Collections.Generic; using System.Linq; public class Utils { public class Printer { } static void Main(string[] args) { var x = new List<int> {1, 2, 3, 4, 5}; var y = Enumerable.Range(0, 5); x.ForEach(Console.WriteLine); var z = y.First(); Console.WriteLine(z); } }"; var asm = CSScript.CodeDomEvaluator .CompileCode(utils_code, info); dynamic script = CSScript.CodeDomEvaluator .ReferenceAssembly(info.AssemblyFile) .CompileMethod(@"public Utils NewUtils() => new Utils(); public Utils.Printer NewPrinter() => new Utils.Printer();") .CreateObject("*"); object utils = script.NewUtils(); object printer = script.NewPrinter(); Assert.Equal("Utils", utils.GetType().ToString()); Assert.Equal("Utils+Printer", printer.GetType().ToString()); } finally { info.AssemblyFile.FileDelete(rethrow: false); // assembly is locked so only showing the intention } } [Fact] public void use_ScriptCaching() { var code = "object func() => new[] { 0, 5 };"; // cache is created and the compilation result is saved CSScript.CodeDomEvaluator .With(eval => eval.IsCachingEnabled = true) .LoadMethod(code); // cache is used instead of recompilation var sw = Stopwatch.StartNew(); CSScript.CodeDomEvaluator .With(eval => eval.IsCachingEnabled = true) .LoadMethod(code); var cachedLoadingTime = sw.ElapsedMilliseconds; sw.Restart(); // cache is not used and the script is recompiled again CSScript.CodeDomEvaluator .With(eval => eval.IsCachingEnabled = false) .LoadMethod(code); var noncachedLoadingTime = sw.ElapsedMilliseconds; Assert.True(cachedLoadingTime < noncachedLoadingTime); } [Fact] public void use_interfaces_between_scripts() { IPrinter printer = CSScript.CodeDomEvaluator .ReferenceAssemblyOf<IPrinter>() .LoadCode<IPrinter>(@"using System; public class Printer : IPrinter { public void Print() => Console.Write(""Printing...""); }"); dynamic script = CSScript.Evaluator .ReferenceAssemblyOf<IPrinter>() .LoadMethod(@"void Test(IPrinter printer) { printer.Print(); }"); script.Test(printer); // does not throw :) } [Fact] public void import_script_from_another_scripts() { var script_math = "math.cs".GetFullPath(); var script_calc = "calc.cs".GetFullPath(); File.WriteAllText(script_math, @"using System; public class math { public static int add(int a, int b) => a+b; }"); File.WriteAllText(script_calc, $@"//css_inc {script_math} using System; public class Calc {{ public int Add(int a, int b) => math.add(a, b); }}"); dynamic calc = CSScript.CodeDomEvaluator .LoadFile(script_calc); var result = calc.Add(1, 4); Assert.Equal(5, result); } // [Fact(Skip = "VB is not supported yet")] // public void VB_Generic_Test() // { // Assembly asm = CSScript.CodeDomEvaluator // .CompileCode(@"' //css_ref System // Imports System // Class Script // Function Sum(a As Integer, b As Integer) // Sum = a + b // End Function // End Class"); // dynamic script = asm.CreateObject("*"); // var result = script.Sum(7, 3); // } } }
// 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 0.13.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// VirtualNetworkGatewayConnectionsOperations operations. /// </summary> internal partial class VirtualNetworkGatewayConnectionsOperations : IServiceOperations<NetworkManagementClient>, IVirtualNetworkGatewayConnectionsOperations { /// <summary> /// Initializes a new instance of the VirtualNetworkGatewayConnectionsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal VirtualNetworkGatewayConnectionsOperations(NetworkManagementClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the NetworkManagementClient /// </summary> public NetworkManagementClient Client { get; private set; } /// <summary> /// The Put VirtualNetworkGatewayConnection operation creates/updates a /// virtual network gateway connection in the specified resource group /// through Network resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway conenction. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Create or update Virtual Network Gateway /// connection operation through Network resource provider. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<VirtualNetworkGatewayConnection>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnection parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<VirtualNetworkGatewayConnection> response = await BeginCreateOrUpdateWithHttpMessagesAsync( resourceGroupName, virtualNetworkGatewayConnectionName, parameters, customHeaders, cancellationToken); return await this.Client.GetPutOrPatchOperationResultAsync<VirtualNetworkGatewayConnection>(response, customHeaders, cancellationToken); } /// <summary> /// The Put VirtualNetworkGatewayConnection operation creates/updates a /// virtual network gateway connection in the specified resource group /// through Network resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway conenction. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Create or update Virtual Network Gateway /// connection operation through Network resource provider. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<VirtualNetworkGatewayConnection>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnection parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkGatewayConnectionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkGatewayConnectionName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkGatewayConnectionName", virtualNetworkGatewayConnectionName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var baseUrl = this.Client.BaseUri.AbsoluteUri; var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}").ToString(); url = url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); url = url.Replace("{virtualNetworkGatewayConnectionName}", Uri.EscapeDataString(virtualNetworkGatewayConnectionName)); url = url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("PUT"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.Client.AcceptLanguage != null) { if (httpRequest.Headers.Contains("accept-language")) { httpRequest.Headers.Remove("accept-language"); } httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Serialize Request string requestContent = JsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)statusCode != 200 && (int)statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex = new CloudException(errorBody.Message); ex.Body = errorBody; } ex.Request = new HttpRequestMessageWrapper(httpRequest, null); ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent); if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse<VirtualNetworkGatewayConnection>(); result.Request = httpRequest; result.Response = httpResponse; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)statusCode == 200) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<VirtualNetworkGatewayConnection>(responseContent, this.Client.DeserializationSettings); } // Deserialize Response if ((int)statusCode == 201) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<VirtualNetworkGatewayConnection>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// The Get VirtualNetworkGatewayConnection operation retrieves information /// about the specified virtual network gateway connection through Network /// resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway connection. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<VirtualNetworkGatewayConnection>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkGatewayConnectionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkGatewayConnectionName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkGatewayConnectionName", virtualNetworkGatewayConnectionName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "Get", tracingParameters); } // Construct URL var baseUrl = this.Client.BaseUri.AbsoluteUri; var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}").ToString(); url = url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); url = url.Replace("{virtualNetworkGatewayConnectionName}", Uri.EscapeDataString(virtualNetworkGatewayConnectionName)); url = url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.Client.AcceptLanguage != null) { if (httpRequest.Headers.Contains("accept-language")) { httpRequest.Headers.Remove("accept-language"); } httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex = new CloudException(errorBody.Message); ex.Body = errorBody; } ex.Request = new HttpRequestMessageWrapper(httpRequest, null); ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent); if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse<VirtualNetworkGatewayConnection>(); result.Request = httpRequest; result.Response = httpResponse; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)statusCode == 200) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<VirtualNetworkGatewayConnection>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// The Delete VirtualNetworkGatewayConnection operation deletes the specifed /// virtual network Gateway connection through Network resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway connection. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse response = await BeginDeleteWithHttpMessagesAsync( resourceGroupName, virtualNetworkGatewayConnectionName, customHeaders, cancellationToken); return await this.Client.GetPostOrDeleteOperationResultAsync(response, customHeaders, cancellationToken); } /// <summary> /// The Delete VirtualNetworkGatewayConnection operation deletes the specifed /// virtual network Gateway connection through Network resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway connection. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkGatewayConnectionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkGatewayConnectionName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkGatewayConnectionName", virtualNetworkGatewayConnectionName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var baseUrl = this.Client.BaseUri.AbsoluteUri; var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}").ToString(); url = url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); url = url.Replace("{virtualNetworkGatewayConnectionName}", Uri.EscapeDataString(virtualNetworkGatewayConnectionName)); url = url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("DELETE"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.Client.AcceptLanguage != null) { if (httpRequest.Headers.Contains("accept-language")) { httpRequest.Headers.Remove("accept-language"); } httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)statusCode != 200 && (int)statusCode != 202 && (int)statusCode != 204) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); ex.Request = new HttpRequestMessageWrapper(httpRequest, null); ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent); if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse(); result.Request = httpRequest; result.Response = httpResponse; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// The Get VirtualNetworkGatewayConnectionSharedKey operation retrieves /// information about the specified virtual network gateway connection shared /// key through Network resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='connectionSharedKeyName'> /// The virtual network gateway connection shared key name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<ConnectionSharedKeyResult>> GetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string connectionSharedKeyName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (connectionSharedKeyName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "connectionSharedKeyName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("connectionSharedKeyName", connectionSharedKeyName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetSharedKey", tracingParameters); } // Construct URL var baseUrl = this.Client.BaseUri.AbsoluteUri; var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{connectionSharedKeyName}/sharedkey").ToString(); url = url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); url = url.Replace("{connectionSharedKeyName}", Uri.EscapeDataString(connectionSharedKeyName)); url = url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.Client.AcceptLanguage != null) { if (httpRequest.Headers.Contains("accept-language")) { httpRequest.Headers.Remove("accept-language"); } httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex = new CloudException(errorBody.Message); ex.Body = errorBody; } ex.Request = new HttpRequestMessageWrapper(httpRequest, null); ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent); if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse<ConnectionSharedKeyResult>(); result.Request = httpRequest; result.Response = httpResponse; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)statusCode == 200) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<ConnectionSharedKeyResult>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// The List VirtualNetworkGatewayConnections operation retrieves all the /// virtual network gateways connections created. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<IPage<VirtualNetworkGatewayConnection>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "List", tracingParameters); } // Construct URL var baseUrl = this.Client.BaseUri.AbsoluteUri; var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections").ToString(); url = url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); url = url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.Client.AcceptLanguage != null) { if (httpRequest.Headers.Contains("accept-language")) { httpRequest.Headers.Remove("accept-language"); } httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex = new CloudException(errorBody.Message); ex.Body = errorBody; } ex.Request = new HttpRequestMessageWrapper(httpRequest, null); ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent); if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse<IPage<VirtualNetworkGatewayConnection>>(); result.Request = httpRequest; result.Response = httpResponse; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)statusCode == 200) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<Page<VirtualNetworkGatewayConnection>>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// The VirtualNetworkGatewayConnectionResetSharedKey operation resets the /// virtual network gateway connection shared key for passed virtual network /// gateway connection in the specified resource group through Network /// resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection reset shared key Name. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Reset Virtual Network Gateway connection /// shared key operation through Network resource provider. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<ConnectionResetSharedKey>> ResetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionResetSharedKey parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse<ConnectionResetSharedKey> response = await BeginResetSharedKeyWithHttpMessagesAsync( resourceGroupName, virtualNetworkGatewayConnectionName, parameters, customHeaders, cancellationToken); return await this.Client.GetPostOrDeleteOperationResultAsync(response, customHeaders, cancellationToken); } /// <summary> /// The VirtualNetworkGatewayConnectionResetSharedKey operation resets the /// virtual network gateway connection shared key for passed virtual network /// gateway connection in the specified resource group through Network /// resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection reset shared key Name. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Reset Virtual Network Gateway connection /// shared key operation through Network resource provider. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<ConnectionResetSharedKey>> BeginResetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionResetSharedKey parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkGatewayConnectionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkGatewayConnectionName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkGatewayConnectionName", virtualNetworkGatewayConnectionName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "BeginResetSharedKey", tracingParameters); } // Construct URL var baseUrl = this.Client.BaseUri.AbsoluteUri; var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/sharedkey/reset").ToString(); url = url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); url = url.Replace("{virtualNetworkGatewayConnectionName}", Uri.EscapeDataString(virtualNetworkGatewayConnectionName)); url = url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("POST"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.Client.AcceptLanguage != null) { if (httpRequest.Headers.Contains("accept-language")) { httpRequest.Headers.Remove("accept-language"); } httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Serialize Request string requestContent = JsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)statusCode != 200 && (int)statusCode != 202) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex = new CloudException(errorBody.Message); ex.Body = errorBody; } ex.Request = new HttpRequestMessageWrapper(httpRequest, null); ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent); if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse<ConnectionResetSharedKey>(); result.Request = httpRequest; result.Response = httpResponse; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)statusCode == 200) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<ConnectionResetSharedKey>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// The Put VirtualNetworkGatewayConnectionSharedKey operation sets the /// virtual network gateway connection shared key for passed virtual network /// gateway connection in the specified resource group through Network /// resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection name. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Set Virtual Network Gateway conection /// Shared key operation throughNetwork resource provider. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<ConnectionSharedKey>> SetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionSharedKey parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<ConnectionSharedKey> response = await BeginSetSharedKeyWithHttpMessagesAsync( resourceGroupName, virtualNetworkGatewayConnectionName, parameters, customHeaders, cancellationToken); return await this.Client.GetPutOrPatchOperationResultAsync<ConnectionSharedKey>(response, customHeaders, cancellationToken); } /// <summary> /// The Put VirtualNetworkGatewayConnectionSharedKey operation sets the /// virtual network gateway connection shared key for passed virtual network /// gateway connection in the specified resource group through Network /// resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection name. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Set Virtual Network Gateway conection /// Shared key operation throughNetwork resource provider. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<ConnectionSharedKey>> BeginSetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionSharedKey parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkGatewayConnectionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkGatewayConnectionName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("virtualNetworkGatewayConnectionName", virtualNetworkGatewayConnectionName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "BeginSetSharedKey", tracingParameters); } // Construct URL var baseUrl = this.Client.BaseUri.AbsoluteUri; var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/connections/{virtualNetworkGatewayConnectionName}/sharedkey").ToString(); url = url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); url = url.Replace("{virtualNetworkGatewayConnectionName}", Uri.EscapeDataString(virtualNetworkGatewayConnectionName)); url = url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("PUT"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.Client.AcceptLanguage != null) { if (httpRequest.Headers.Contains("accept-language")) { httpRequest.Headers.Remove("accept-language"); } httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Serialize Request string requestContent = JsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)statusCode != 201 && (int)statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex = new CloudException(errorBody.Message); ex.Body = errorBody; } ex.Request = new HttpRequestMessageWrapper(httpRequest, null); ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent); if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse<ConnectionSharedKey>(); result.Request = httpRequest; result.Response = httpResponse; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)statusCode == 201) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<ConnectionSharedKey>(responseContent, this.Client.DeserializationSettings); } // Deserialize Response if ((int)statusCode == 200) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<ConnectionSharedKey>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } /// <summary> /// The List VirtualNetworkGatewayConnections operation retrieves all the /// virtual network gateways connections created. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<IPage<VirtualNetworkGatewayConnection>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "ListNext", tracingParameters); } // Construct URL string url = "{nextLink}"; url = url.Replace("{nextLink}", nextPageLink); List<string> queryParameters = new List<string>(); if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("GET"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); if (this.Client.AcceptLanguage != null) { if (httpRequest.Headers.Contains("accept-language")) { httpRequest.Headers.Remove("accept-language"); } httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var header in customHeaders) { if (httpRequest.Headers.Contains(header.Key)) { httpRequest.Headers.Remove(header.Key); } httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); } } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError errorBody = JsonConvert.DeserializeObject<CloudError>(responseContent, this.Client.DeserializationSettings); if (errorBody != null) { ex = new CloudException(errorBody.Message); ex.Body = errorBody; } ex.Request = new HttpRequestMessageWrapper(httpRequest, null); ex.Response = new HttpResponseMessageWrapper(httpResponse, responseContent); if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result var result = new AzureOperationResponse<IPage<VirtualNetworkGatewayConnection>>(); result.Request = httpRequest; result.Response = httpResponse; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)statusCode == 200) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result.Body = JsonConvert.DeserializeObject<Page<VirtualNetworkGatewayConnection>>(responseContent, this.Client.DeserializationSettings); } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return result; } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type CalendarRequest. /// </summary> public partial class CalendarRequest : BaseRequest, ICalendarRequest { /// <summary> /// Constructs a new CalendarRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public CalendarRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified Calendar using POST. /// </summary> /// <param name="calendarToCreate">The Calendar to create.</param> /// <returns>The created Calendar.</returns> public System.Threading.Tasks.Task<Calendar> CreateAsync(Calendar calendarToCreate) { return this.CreateAsync(calendarToCreate, CancellationToken.None); } /// <summary> /// Creates the specified Calendar using POST. /// </summary> /// <param name="calendarToCreate">The Calendar to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created Calendar.</returns> public async System.Threading.Tasks.Task<Calendar> CreateAsync(Calendar calendarToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<Calendar>(calendarToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified Calendar. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified Calendar. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<Calendar>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified Calendar. /// </summary> /// <returns>The Calendar.</returns> public System.Threading.Tasks.Task<Calendar> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified Calendar. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The Calendar.</returns> public async System.Threading.Tasks.Task<Calendar> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<Calendar>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified Calendar using PATCH. /// </summary> /// <param name="calendarToUpdate">The Calendar to update.</param> /// <returns>The updated Calendar.</returns> public System.Threading.Tasks.Task<Calendar> UpdateAsync(Calendar calendarToUpdate) { return this.UpdateAsync(calendarToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified Calendar using PATCH. /// </summary> /// <param name="calendarToUpdate">The Calendar to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated Calendar.</returns> public async System.Threading.Tasks.Task<Calendar> UpdateAsync(Calendar calendarToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<Calendar>(calendarToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public ICalendarRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public ICalendarRequest Expand(Expression<Func<Calendar, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public ICalendarRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public ICalendarRequest Select(Expression<Func<Calendar, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="calendarToInitialize">The <see cref="Calendar"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(Calendar calendarToInitialize) { if (calendarToInitialize != null && calendarToInitialize.AdditionalData != null) { if (calendarToInitialize.Events != null && calendarToInitialize.Events.CurrentPage != null) { calendarToInitialize.Events.AdditionalData = calendarToInitialize.AdditionalData; object nextPageLink; calendarToInitialize.AdditionalData.TryGetValue("events@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { calendarToInitialize.Events.InitializeNextPageRequest( this.Client, nextPageLinkString); } } if (calendarToInitialize.CalendarView != null && calendarToInitialize.CalendarView.CurrentPage != null) { calendarToInitialize.CalendarView.AdditionalData = calendarToInitialize.AdditionalData; object nextPageLink; calendarToInitialize.AdditionalData.TryGetValue("calendarView@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { calendarToInitialize.CalendarView.InitializeNextPageRequest( this.Client, nextPageLinkString); } } } } } }
// // 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.Automation; using Microsoft.Azure.Management.Automation.Models; namespace Microsoft.Azure.Management.Automation { public static partial class JobOperationsExtensions { /// <summary> /// Create a job of the runbook. (see /// http://aka.ms/azureautomationsdk/joboperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IJobOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the create job operation. /// </param> /// <returns> /// The response model for the create job operation. /// </returns> public static JobCreateResponse Create(this IJobOperations operations, string resourceGroupName, string automationAccount, JobCreateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).CreateAsync(resourceGroupName, automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create a job of the runbook. (see /// http://aka.ms/azureautomationsdk/joboperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IJobOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The parameters supplied to the create job operation. /// </param> /// <returns> /// The response model for the create job operation. /// </returns> public static Task<JobCreateResponse> CreateAsync(this IJobOperations operations, string resourceGroupName, string automationAccount, JobCreateParameters parameters) { return operations.CreateAsync(resourceGroupName, automationAccount, parameters, CancellationToken.None); } /// <summary> /// Retrieve the job identified by job id. (see /// http://aka.ms/azureautomationsdk/joboperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IJobOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='jobId'> /// Required. The job id. /// </param> /// <returns> /// The response model for the get job operation. /// </returns> public static JobGetResponse Get(this IJobOperations operations, string resourceGroupName, string automationAccount, Guid jobId) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).GetAsync(resourceGroupName, automationAccount, jobId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve the job identified by job id. (see /// http://aka.ms/azureautomationsdk/joboperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IJobOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='jobId'> /// Required. The job id. /// </param> /// <returns> /// The response model for the get job operation. /// </returns> public static Task<JobGetResponse> GetAsync(this IJobOperations operations, string resourceGroupName, string automationAccount, Guid jobId) { return operations.GetAsync(resourceGroupName, automationAccount, jobId, CancellationToken.None); } /// <summary> /// Retrieve the job output identified by job id. (see /// http://aka.ms/azureautomationsdk/joboperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IJobOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='jobId'> /// Required. The job id. /// </param> /// <returns> /// The response model for the get job output operation. /// </returns> public static JobGetOutputResponse GetOutput(this IJobOperations operations, string resourceGroupName, string automationAccount, Guid jobId) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).GetOutputAsync(resourceGroupName, automationAccount, jobId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve the job output identified by job id. (see /// http://aka.ms/azureautomationsdk/joboperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IJobOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='jobId'> /// Required. The job id. /// </param> /// <returns> /// The response model for the get job output operation. /// </returns> public static Task<JobGetOutputResponse> GetOutputAsync(this IJobOperations operations, string resourceGroupName, string automationAccount, Guid jobId) { return operations.GetOutputAsync(resourceGroupName, automationAccount, jobId, CancellationToken.None); } /// <summary> /// Retrieve the runbook content of the job identified by job id. (see /// http://aka.ms/azureautomationsdk/joboperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IJobOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='jobId'> /// Required. The job id. /// </param> /// <returns> /// The response model for the get runbook content of the job operation. /// </returns> public static JobGetRunbookContentResponse GetRunbookContent(this IJobOperations operations, string resourceGroupName, string automationAccount, Guid jobId) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).GetRunbookContentAsync(resourceGroupName, automationAccount, jobId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve the runbook content of the job identified by job id. (see /// http://aka.ms/azureautomationsdk/joboperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IJobOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='jobId'> /// Required. The job id. /// </param> /// <returns> /// The response model for the get runbook content of the job operation. /// </returns> public static Task<JobGetRunbookContentResponse> GetRunbookContentAsync(this IJobOperations operations, string resourceGroupName, string automationAccount, Guid jobId) { return operations.GetRunbookContentAsync(resourceGroupName, automationAccount, jobId, CancellationToken.None); } /// <summary> /// Retrieve a list of jobs. (see /// http://aka.ms/azureautomationsdk/joboperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IJobOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Optional. The parameters supplied to the list operation. /// </param> /// <returns> /// The response model for the list job operation. /// </returns> public static JobListResponse List(this IJobOperations operations, string resourceGroupName, string automationAccount, JobListParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).ListAsync(resourceGroupName, automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of jobs. (see /// http://aka.ms/azureautomationsdk/joboperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IJobOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Optional. The parameters supplied to the list operation. /// </param> /// <returns> /// The response model for the list job operation. /// </returns> public static Task<JobListResponse> ListAsync(this IJobOperations operations, string resourceGroupName, string automationAccount, JobListParameters parameters) { return operations.ListAsync(resourceGroupName, automationAccount, parameters, CancellationToken.None); } /// <summary> /// Retrieve next list of jobs. (see /// http://aka.ms/azureautomationsdk/joboperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IJobOperations. /// </param> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <returns> /// The response model for the list job operation. /// </returns> public static JobListResponse ListNext(this IJobOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve next list of jobs. (see /// http://aka.ms/azureautomationsdk/joboperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IJobOperations. /// </param> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <returns> /// The response model for the list job operation. /// </returns> public static Task<JobListResponse> ListNextAsync(this IJobOperations operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } /// <summary> /// Resume the job identified by jobId. (see /// http://aka.ms/azureautomationsdk/joboperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IJobOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='jobId'> /// Required. The job id. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Resume(this IJobOperations operations, string resourceGroupName, string automationAccount, Guid jobId) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).ResumeAsync(resourceGroupName, automationAccount, jobId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Resume the job identified by jobId. (see /// http://aka.ms/azureautomationsdk/joboperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IJobOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='jobId'> /// Required. The job id. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> ResumeAsync(this IJobOperations operations, string resourceGroupName, string automationAccount, Guid jobId) { return operations.ResumeAsync(resourceGroupName, automationAccount, jobId, CancellationToken.None); } /// <summary> /// Stop the job identified by jobId. (see /// http://aka.ms/azureautomationsdk/joboperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IJobOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='jobId'> /// Required. The job id. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Stop(this IJobOperations operations, string resourceGroupName, string automationAccount, Guid jobId) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).StopAsync(resourceGroupName, automationAccount, jobId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Stop the job identified by jobId. (see /// http://aka.ms/azureautomationsdk/joboperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IJobOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='jobId'> /// Required. The job id. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> StopAsync(this IJobOperations operations, string resourceGroupName, string automationAccount, Guid jobId) { return operations.StopAsync(resourceGroupName, automationAccount, jobId, CancellationToken.None); } /// <summary> /// Suspend the job identified by jobId. (see /// http://aka.ms/azureautomationsdk/joboperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IJobOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='jobId'> /// Required. The job id. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Suspend(this IJobOperations operations, string resourceGroupName, string automationAccount, Guid jobId) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).SuspendAsync(resourceGroupName, automationAccount, jobId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Suspend the job identified by jobId. (see /// http://aka.ms/azureautomationsdk/joboperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IJobOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='jobId'> /// Required. The job id. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> SuspendAsync(this IJobOperations operations, string resourceGroupName, string automationAccount, Guid jobId) { return operations.SuspendAsync(resourceGroupName, automationAccount, jobId, CancellationToken.None); } } }
// 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.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SymbolId { public partial class SymbolKeyTest : SymbolKeyTestBase { #region "No change to symbol" [Fact] public void C2CTypeSymbolUnchanged01() { var src1 = @"using System; public delegate void DFoo(int p1, string p2); namespace N1.N2 { public interface IFoo { } namespace N3 { public class CFoo { public struct SFoo { public enum EFoo { Zero, One } } } } } "; var src2 = @"using System; public delegate void DFoo(int p1, string p2); namespace N1.N2 { public interface IFoo { // Add member N3.CFoo GetClass(); } namespace N3 { public class CFoo { public struct SFoo { // Update member public enum EFoo { Zero, One, Two } } // Add member public void M(int n) { Console.WriteLine(n); } } } } "; var comp1 = CreateCompilationWithMscorlib(src1, assemblyName: "Test"); var comp2 = CreateCompilationWithMscorlib(src2, assemblyName: "Test"); var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name); var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name); ResolveAndVerifySymbolList(newSymbols, comp2, originalSymbols, comp1); } [Fact, WorkItem(530171)] public void C2CErrorSymbolUnchanged01() { var src1 = @"public void Method() { }"; var src2 = @" public void Method() { System.Console.WriteLine(12345); } "; var comp1 = CreateCompilationWithMscorlib(src1); var comp2 = CreateCompilationWithMscorlib(src2); var symbol01 = comp1.SourceModule.GlobalNamespace.GetMembers().FirstOrDefault() as NamedTypeSymbol; var symbol02 = comp1.SourceModule.GlobalNamespace.GetMembers().FirstOrDefault() as NamedTypeSymbol; Assert.NotNull(symbol01); Assert.NotNull(symbol02); Assert.NotEqual(symbol01.Kind, SymbolKind.ErrorType); Assert.NotEqual(symbol02.Kind, SymbolKind.ErrorType); var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name); var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name); ResolveAndVerifySymbolList(newSymbols, comp2, originalSymbols, comp1); } [Fact] [WorkItem(820263)] public void PartialDefinitionAndImplementationResolveCorrectly() { var src = @"using System; namespace NS { public partial class C1 { partial void M() { } partial void M(); } } "; var comp = CreateCompilationWithMscorlib(src, assemblyName: "Test"); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type = ns.GetTypeMembers("C1").FirstOrDefault() as NamedTypeSymbol; var definition = type.GetMembers("M").First() as IMethodSymbol; var implementation = definition.PartialImplementationPart; // Assert that both the definition and implementation resolve back to themselves Assert.Equal(definition, ResolveSymbol(definition, comp, comp, SymbolKeyComparison.None)); Assert.Equal(implementation, ResolveSymbol(implementation, comp, comp, SymbolKeyComparison.None)); } [Fact] [WorkItem(916341)] public void ExplicitIndexerImplementationResolvesCorrectly() { var src = @" interface I { object this[int index] { get; } } interface I<T> { T this[int index] { get; } } class C<T> : I<T>, I { object I.this[int index] { get { throw new System.NotImplementedException(); } } T I<T>.this[int index] { get { throw new System.NotImplementedException(); } } } "; var compilation = CreateCompilationWithMscorlib(src, assemblyName: "Test"); var type = compilation.SourceModule.GlobalNamespace.GetTypeMembers("C").Single() as NamedTypeSymbol; var indexer1 = type.GetMembers().Where(m => m.MetadataName == "I.Item").Single() as IPropertySymbol; var indexer2 = type.GetMembers().Where(m => m.MetadataName == "I<T>.Item").Single() as IPropertySymbol; AssertSymbolKeysEqual(indexer1, compilation, indexer2, compilation, SymbolKeyComparison.None, expectEqual: false); Assert.Equal(indexer1, ResolveSymbol(indexer1, compilation, compilation, SymbolKeyComparison.None)); Assert.Equal(indexer2, ResolveSymbol(indexer2, compilation, compilation, SymbolKeyComparison.None)); } #endregion #region "Change to symbol" [Fact] public void C2CTypeSymbolChanged01() { var src1 = @"using System; public delegate void DFoo(int p1); namespace N1.N2 { public interface IBase { } public interface IFoo { } namespace N3 { public class CFoo { public struct SFoo { public enum EFoo { Zero, One } } } } } "; var src2 = @"using System; public delegate void DFoo(int p1, string p2); // add 1 more parameter namespace N1.N2 { public interface IBase { } public interface IFoo : IBase // add base interface { } namespace N3 { public class CFoo : IFoo // impl interface { private struct SFoo // change modifier { internal enum EFoo : long { Zero, One } // change base class, and modifier } } } } "; var comp1 = CreateCompilationWithMscorlib(src1, assemblyName: "Test"); var comp2 = CreateCompilationWithMscorlib(src2, assemblyName: "Test"); var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType); var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType); ResolveAndVerifySymbolList(newSymbols, comp2, originalSymbols, comp1); } [Fact] public void C2CTypeSymbolChanged02() { var src1 = @"using System; namespace NS { public class C1 { public void M() {} } } "; var src2 = @" namespace NS { internal class C1 // add new C1 { public string P { get; set; } } public class C2 // rename C1 to C2 { public void M() {} } } "; var comp1 = CreateCompilationWithMscorlib(src1, assemblyName: "Test"); var comp2 = CreateCompilationWithMscorlib(src2, assemblyName: "Test"); var namespace1 = comp1.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var typeSym00 = namespace1.GetTypeMembers("C1").FirstOrDefault() as NamedTypeSymbol; var namespace2 = comp2.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var typeSym01 = namespace2.GetTypeMembers("C1").FirstOrDefault() as NamedTypeSymbol; var typeSym02 = namespace2.GetTypeMembers("C2").Single() as NamedTypeSymbol; // new C1 resolve to old C1 ResolveAndVerifySymbol(typeSym01, comp2, typeSym00, comp1); // old C1 (new C2) NOT resolve to old C1 var symkey = SymbolKey.Create(typeSym02, comp1, CancellationToken.None); var syminfo = symkey.Resolve(comp1); Assert.Null(syminfo.Symbol); } [Fact] public void C2CMemberSymbolChanged01() { var src1 = @"using System; using System.Collections.Generic; public class Test { private byte field = 123; internal string P { get; set; } public void M(ref int n) { } event Action<string> myEvent; } "; var src2 = @"using System; public class Test { internal protected byte field = 255; // change modifier and init-value internal string P { get { return null; } } // remove 'set' public int M(ref int n) { return 0; } // change ret type event Action<string> myEvent // add add/remove { add { } remove { } } } "; var comp1 = CreateCompilationWithMscorlib(src1, assemblyName: "Test"); var comp2 = CreateCompilationWithMscorlib(src2, assemblyName: "Test"); var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.NonTypeMember | SymbolCategory.Parameter) .Where(s => !s.IsAccessor()).OrderBy(s => s.Name); var newSymbols = GetSourceSymbols(comp2, SymbolCategory.NonTypeMember | SymbolCategory.Parameter) .Where(s => !s.IsAccessor()).OrderBy(s => s.Name); ResolveAndVerifySymbolList(newSymbols, comp2, originalSymbols, comp1); } [WorkItem(542700)] [Fact] public void C2CIndexerSymbolChanged01() { var src1 = @"using System; using System.Collections.Generic; public class Test { public string this[string p1] { set { } } protected long this[long p1] { set { } } } "; var src2 = @"using System; public class Test { internal string this[string p1] { set { } } // change modifier protected long this[long p1] { get { return 0; } set { } } // add 'get' } "; var comp1 = CreateCompilationWithMscorlib(src1, assemblyName: "Test"); var comp2 = CreateCompilationWithMscorlib(src2, assemblyName: "Test"); var typeSym1 = comp1.SourceModule.GlobalNamespace.GetTypeMembers("Test").Single() as NamedTypeSymbol; var originalSymbols = typeSym1.GetMembers(WellKnownMemberNames.Indexer); var typeSym2 = comp2.SourceModule.GlobalNamespace.GetTypeMembers("Test").Single() as NamedTypeSymbol; var newSymbols = typeSym2.GetMembers(WellKnownMemberNames.Indexer); ResolveAndVerifySymbol(newSymbols.First(), comp2, originalSymbols.First(), comp1, SymbolKeyComparison.CaseSensitive); ResolveAndVerifySymbol(newSymbols.Last(), comp2, originalSymbols.Last(), comp1, SymbolKeyComparison.CaseSensitive); } [Fact] public void C2CAssemblyChanged01() { var src = @" namespace NS { public class C1 { public void M() {} } } "; var comp1 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly1"); var comp2 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly2"); var namespace1 = comp1.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var typeSym01 = namespace1.GetTypeMembers("C1").FirstOrDefault() as NamedTypeSymbol; var namespace2 = comp2.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var typeSym02 = namespace2.GetTypeMembers("C1").FirstOrDefault() as NamedTypeSymbol; // new C1 resolves to old C1 if we ignore assembly and module ids ResolveAndVerifySymbol(typeSym02, comp2, typeSym01, comp1, SymbolKeyComparison.CaseSensitive | SymbolKeyComparison.IgnoreAssemblyIds); // new C1 DOES NOT resolve to old C1 if we don't ignore assembly and module ids Assert.Null(ResolveSymbol(typeSym02, comp2, comp1, SymbolKeyComparison.CaseSensitive)); } [WpfFact(Skip = "530169"), WorkItem(530169)] public void C2CAssemblyChanged02() { var src = @"[assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] public class C {}"; // same identity var comp1 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly"); var comp2 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly"); Symbol sym1 = comp1.Assembly; Symbol sym2 = comp2.Assembly; // Not ignoreAssemblyAndModules ResolveAndVerifySymbol(sym1, comp2, sym2, comp2); AssertSymbolKeysEqual(sym1, comp1, sym2, comp2, SymbolKeyComparison.IgnoreAssemblyIds, true); Assert.NotNull(ResolveSymbol(sym1, comp1, comp2, SymbolKeyComparison.IgnoreAssemblyIds)); // Module sym1 = comp1.Assembly.Modules[0]; sym2 = comp2.Assembly.Modules[0]; ResolveAndVerifySymbol(sym1, comp1, sym2, comp2); AssertSymbolKeysEqual(sym2, comp2, sym1, comp1, SymbolKeyComparison.IgnoreAssemblyIds, true); Assert.NotNull(ResolveSymbol(sym2, comp2, comp1, SymbolKeyComparison.IgnoreAssemblyIds)); } [Fact, WorkItem(530170)] public void C2CAssemblyChanged03() { var src = @"[assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] public class C {}"; // ------------------------------------------------------- // different name var compilation1 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly1"); var compilation2 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly2"); ISymbol assembly1 = compilation1.Assembly; ISymbol assembly2 = compilation2.Assembly; // different AssertSymbolKeysEqual(assembly2, compilation2, assembly1, compilation1, SymbolKeyComparison.CaseSensitive, expectEqual: false); Assert.Null(ResolveSymbol(assembly2, compilation2, compilation1, SymbolKeyComparison.CaseSensitive)); // ignore means ALL assembly/module symbols have same ID AssertSymbolKeysEqual(assembly2, compilation2, assembly1, compilation1, SymbolKeyComparison.IgnoreAssemblyIds, expectEqual: true); // But can NOT be resolved Assert.Null(ResolveSymbol(assembly2, compilation2, compilation1, SymbolKeyComparison.IgnoreAssemblyIds)); // Module var module1 = compilation1.Assembly.Modules[0]; var module2 = compilation2.Assembly.Modules[0]; // different AssertSymbolKeysEqual(module1, compilation1, module2, compilation2, SymbolKeyComparison.CaseSensitive, expectEqual: false); Assert.Null(ResolveSymbol(module1, compilation1, compilation2, SymbolKeyComparison.CaseSensitive)); AssertSymbolKeysEqual(module2, compilation2, module1, compilation1, SymbolKeyComparison.IgnoreAssemblyIds); Assert.Null(ResolveSymbol(module2, compilation2, compilation1, SymbolKeyComparison.IgnoreAssemblyIds)); } [Fact, WorkItem(546254)] public void C2CAssemblyChanged04() { var src = @" [assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] [assembly: System.Reflection.AssemblyTitle(""One Hundred Years of Solitude"")] public class C {} "; var src2 = @" [assembly: System.Reflection.AssemblyVersion(""1.2.3.42"")] [assembly: System.Reflection.AssemblyTitle(""One Hundred Years of Solitude"")] public class C {} "; // different versions var comp1 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly"); var comp2 = CreateCompilationWithMscorlib(src2, assemblyName: "Assembly"); Symbol sym1 = comp1.Assembly; Symbol sym2 = comp2.Assembly; // comment is changed to compare Name ONLY AssertSymbolKeysEqual(sym1, comp1, sym2, comp2, SymbolKeyComparison.CaseSensitive, expectEqual: true); var resolved = ResolveSymbol(sym2, comp2, comp1, SymbolKeyComparison.CaseSensitive); Assert.Equal(sym1, resolved); AssertSymbolKeysEqual(sym1, comp1, sym2, comp2, SymbolKeyComparison.IgnoreAssemblyIds); Assert.Null(ResolveSymbol(sym2, comp2, comp1, SymbolKeyComparison.IgnoreAssemblyIds)); } #endregion } }
using System; using System.Linq; using Cake.Common.Tools.Chocolatey.Pack; using Cake.Common.Tools.Chocolatey.Push; using Cake.Common.Tools.DotNetCore; using Cake.Common.Tools.DotNetCore.Build; using Cake.Common.Tools.DotNetCore.Pack; using Cake.Common.Tools.DotNetCore.Publish; using Cake.Common.Tools.DotNetCore.Restore; using Cake.Common.Tools.DotNetCore.Test; using Cake.Common.Tools.GitReleaseManager.Create; using Cake.Common.Tools.NuGet.Pack; using Cake.Common.Tools.NuGet.Push; using Cake.Common.Tools.OpenCover; using Cake.Core; using Cake.Core.Diagnostics; using Cake.Core.IO; using Cake.Coveralls; namespace CakeIdeas { public class CakeBuild : CakeFileIntellisense { public override void Execute() { // Install addins. Addin("nuget:https://www.nuget.org/api/v2?package=Newtonsoft.Json&version=9.0.1"); Addin("nuget:https://www.nuget.org/api/v2?package=Cake.Coveralls&version=0.2.0"); // Install tools. Tool("nuget:https://www.nuget.org/api/v2?package=gitreleasemanager&version=0.5.0"); Tool("nuget:https://www.nuget.org/api/v2?package=GitVersion.CommandLine&version=3.6.2"); Tool("nuget:https://www.nuget.org/api/v2?package=coveralls.io&version=1.3.4"); Tool("nuget:https://www.nuget.org/api/v2?package=OpenCover&version=4.6.519"); Tool("nuget:https://www.nuget.org/api/v2?package=ReportGenerator&version=2.4.5"); // Load other scripts. Load("./build/parameters.cake"); ////////////////////////////////////////////////////////////////////// // PARAMETERS ////////////////////////////////////////////////////////////////////// BuildParameters parameters = BuildParameters.GetParameters(Context); bool publishingError = false; /////////////////////////////////////////////////////////////////////////////// // SETUP / TEARDOWN /////////////////////////////////////////////////////////////////////////////// Setup(context => { parameters.Initialize(context); // Increase verbosity? if (parameters.IsMainCakeBranch && (context.Log.Verbosity != Verbosity.Diagnostic)) { Information("Increasing verbosity to diagnostic."); context.Log.Verbosity = Verbosity.Diagnostic; } Information("Building version {0} of Cake ({1}, {2}) using version {3} of Cake. (IsTagged: {4})", parameters.Version.SemVersion, parameters.Configuration, parameters.Target, parameters.Version.CakeVersion, parameters.IsTagged); }); ////////////////////////////////////////////////////////////////////// // TASKS ////////////////////////////////////////////////////////////////////// Task("Clean") .Does(() => { CleanDirectories(parameters.Paths.Directories.ToClean); }); Task("Patch-Project-Json") .IsDependentOn("Clean") .Does(() => { var projects = GetFiles("./src/**/project.json"); foreach (var project in projects) { if (!parameters.Version.PatchProjectJson(project)) { Warning("No version specified in {0}.", project.FullPath); } } }); Task("Restore-NuGet-Packages") .IsDependentOn("Clean") .Does(() => { DotNetCoreRestore("./", new DotNetCoreRestoreSettings { Verbose = false, Verbosity = DotNetCoreRestoreVerbosity.Warning, Sources = new[] { "https://www.myget.org/F/xunit/api/v3/index.json", "https://dotnet.myget.org/F/dotnet-core/api/v3/index.json", "https://dotnet.myget.org/F/cli-deps/api/v3/index.json", "https://api.nuget.org/v3/index.json", } }); }); Task("Build") .IsDependentOn("Patch-Project-Json") .IsDependentOn("Restore-NuGet-Packages") .Does(() => { var projects = GetFiles("./**/*.xproj"); foreach (var project in projects) { DotNetCoreBuild(project.GetDirectory().FullPath, new DotNetCoreBuildSettings { VersionSuffix = parameters.Version.DotNetAsterix, Configuration = parameters.Configuration }); } }); Task("Run-Unit-Tests") .IsDependentOn("Build") .Does(() => { var projects = GetFiles("./src/**/*.Tests.xproj"); foreach (var project in projects) { if (IsRunningOnWindows()) { var apiUrl = EnvironmentVariable("APPVEYOR_API_URL"); try { if (!string.IsNullOrEmpty(apiUrl)) { // Disable XUnit AppVeyorReporter see https://github.com/cake-build/cake/issues/1200 System.Environment.SetEnvironmentVariable("APPVEYOR_API_URL", null); } Action<ICakeContext> testAction = tool => { tool.DotNetCoreTest(project.GetDirectory().FullPath, new DotNetCoreTestSettings { Configuration = parameters.Configuration, NoBuild = true, Verbose = false, ArgumentCustomization = args => args.Append("-xml").Append(parameters.Paths.Directories.TestResults.CombineWithFilePath(project.GetFilenameWithoutExtension()).FullPath + ".xml") }); }; if (!parameters.SkipOpenCover) { OpenCover(testAction, parameters.Paths.Files.TestCoverageOutputFilePath, new OpenCoverSettings { ReturnTargetCodeOffset = 0, ArgumentCustomization = args => args.Append("-mergeoutput") } .WithFilter("+[*]* -[xunit.*]* -[*.Tests]* -[Cake.Testing]* -[Cake.Testing.Xunit]* ") .ExcludeByAttribute("*.ExcludeFromCodeCoverage*") .ExcludeByFile("*/*Designer.cs;*/*.g.cs;*/*.g.i.cs")); } else { testAction(Context); } } finally { if (!string.IsNullOrEmpty(apiUrl)) { System.Environment.SetEnvironmentVariable("APPVEYOR_API_URL", apiUrl); } } } else { var name = project.GetFilenameWithoutExtension(); var dirPath = project.GetDirectory().FullPath; var config = parameters.Configuration; var xunit = GetFiles(dirPath + "/bin/" + config + "/net451/*/dotnet-test-xunit.exe").First().FullPath; var testfile = GetFiles(dirPath + "/bin/" + config + "/net451/*/" + name + ".dll").First().FullPath; using (var process = StartAndReturnProcess("mono", new ProcessSettings { Arguments = xunit + " " + testfile })) { process.WaitForExit(); if (process.GetExitCode() != 0) { throw new Exception("Mono tests failed!"); } } } } // Generate the HTML version of the Code Coverage report if the XML file exists if (FileExists(parameters.Paths.Files.TestCoverageOutputFilePath)) { ReportGenerator(parameters.Paths.Files.TestCoverageOutputFilePath, parameters.Paths.Directories.TestResults); } }); Task("Copy-Files") .IsDependentOn("Run-Unit-Tests") .Does(() => { // .NET 4.5 DotNetCorePublish("./src/Cake", new DotNetCorePublishSettings { Framework = "net45", VersionSuffix = parameters.Version.DotNetAsterix, Configuration = parameters.Configuration, OutputDirectory = parameters.Paths.Directories.ArtifactsBinNet45, NoBuild = true, Verbose = false }); // .NET Core DotNetCorePublish("./src/Cake", new DotNetCorePublishSettings { Framework = "netcoreapp1.0", Configuration = parameters.Configuration, VersionSuffix = "alpha", OutputDirectory = parameters.Paths.Directories.ArtifactsBinNetCoreApp10, NoBuild = true, Verbose = false }); // Copy license CopyFileToDirectory("./LICENSE", parameters.Paths.Directories.ArtifactsBinNet45); CopyFileToDirectory("./LICENSE", parameters.Paths.Directories.ArtifactsBinNetCoreApp10); }); Task("Zip-Files") .IsDependentOn("Copy-Files") .Does(() => { // .NET 4.5 var homebrewFiles = GetFiles(parameters.Paths.Directories.ArtifactsBinNet45.FullPath + "/**/*"); Zip(parameters.Paths.Directories.ArtifactsBinNet45, parameters.Paths.Files.ZipArtifactPathDesktop, homebrewFiles); // .NET Core var coreclrFiles = GetFiles(parameters.Paths.Directories.ArtifactsBinNetCoreApp10.FullPath + "/**/*"); Zip(parameters.Paths.Directories.ArtifactsBinNetCoreApp10, parameters.Paths.Files.ZipArtifactPathCoreClr, coreclrFiles); }); Task("Create-Chocolatey-Packages") .IsDependentOn("Copy-Files") .IsDependentOn("Package") .WithCriteria(() => parameters.IsRunningOnWindows) .Does(() => { foreach (var package in parameters.Packages.Chocolatey) { // Create package. ChocolateyPack(package.NuspecPath, new ChocolateyPackSettings { Version = parameters.Version.SemVersion, ReleaseNotes = parameters.ReleaseNotes.Notes.ToArray(), OutputDirectory = parameters.Paths.Directories.NugetRoot, Files = parameters.Paths.ChocolateyFiles }); } }); Task("Create-NuGet-Packages") .IsDependentOn("Copy-Files") .Does(() => { // Build libraries var projects = GetFiles("./**/*.xproj"); foreach (var project in projects) { var name = project.GetDirectory().FullPath; if (name.EndsWith("Cake") || name.EndsWith("Tests") || name.EndsWith("Xunit") || name.EndsWith("NuGet")) { continue; } DotNetCorePack(project.GetDirectory().FullPath, new DotNetCorePackSettings { VersionSuffix = parameters.Version.DotNetAsterix, Configuration = parameters.Configuration, OutputDirectory = parameters.Paths.Directories.NugetRoot, NoBuild = true, Verbose = false }); } // Cake - Symbols - .NET 4.5 NuGetPack("./nuspec/Cake.symbols.nuspec", new NuGetPackSettings { Version = parameters.Version.SemVersion, ReleaseNotes = parameters.ReleaseNotes.Notes.ToArray(), BasePath = parameters.Paths.Directories.ArtifactsBinNet45, OutputDirectory = parameters.Paths.Directories.NugetRoot, Symbols = true, NoPackageAnalysis = true }); // Cake - .NET 4.5 NuGetPack("./nuspec/Cake.nuspec", new NuGetPackSettings { Version = parameters.Version.SemVersion, ReleaseNotes = parameters.ReleaseNotes.Notes.ToArray(), BasePath = parameters.Paths.Directories.ArtifactsBinNet45, OutputDirectory = parameters.Paths.Directories.NugetRoot, Symbols = false, NoPackageAnalysis = true }); // Cake Symbols - .NET Core NuGetPack("./nuspec/Cake.CoreCLR.symbols.nuspec", new NuGetPackSettings { Version = parameters.Version.SemVersion, ReleaseNotes = parameters.ReleaseNotes.Notes.ToArray(), BasePath = parameters.Paths.Directories.ArtifactsBinNetCoreApp10, OutputDirectory = parameters.Paths.Directories.NugetRoot, Symbols = true, NoPackageAnalysis = true }); // Cake - .NET Core NuGetPack("./nuspec/Cake.CoreCLR.nuspec", new NuGetPackSettings { Version = parameters.Version.SemVersion, ReleaseNotes = parameters.ReleaseNotes.Notes.ToArray(), BasePath = parameters.Paths.Directories.ArtifactsBinNetCoreApp10, OutputDirectory = parameters.Paths.Directories.NugetRoot, Symbols = false, NoPackageAnalysis = true }); }); Task("Upload-AppVeyor-Artifacts") .IsDependentOn("Create-Chocolatey-Packages") .WithCriteria(() => parameters.IsRunningOnAppVeyor) .Does(() => { AppVeyor.UploadArtifact(parameters.Paths.Files.ZipArtifactPathDesktop); AppVeyor.UploadArtifact(parameters.Paths.Files.ZipArtifactPathCoreClr); foreach (var package in GetFiles(parameters.Paths.Directories.NugetRoot + "/*")) { AppVeyor.UploadArtifact(package); } }); Task("Upload-Coverage-Report") .WithCriteria(() => FileExists(parameters.Paths.Files.TestCoverageOutputFilePath)) .WithCriteria(() => !parameters.IsLocalBuild) .WithCriteria(() => !parameters.IsPullRequest) .WithCriteria(() => parameters.IsMainCakeRepo) .IsDependentOn("Run-Unit-Tests") .Does(() => { CoverallsIo(parameters.Paths.Files.TestCoverageOutputFilePath, new CoverallsIoSettings() { RepoToken = parameters.Coveralls.RepoToken }); }); Task("Publish-MyGet") .IsDependentOn("Package") .WithCriteria(() => parameters.ShouldPublishToMyGet) .Does(() => { // Resolve the API key. var apiKey = EnvironmentVariable("MYGET_API_KEY"); if (string.IsNullOrEmpty(apiKey)) { throw new InvalidOperationException("Could not resolve MyGet API key."); } // Resolve the API url. var apiUrl = EnvironmentVariable("MYGET_API_URL"); if (string.IsNullOrEmpty(apiUrl)) { throw new InvalidOperationException("Could not resolve MyGet API url."); } foreach (var package in parameters.Packages.All) { // Push the package. NuGetPush(package.PackagePath, new NuGetPushSettings { Source = apiUrl, ApiKey = apiKey }); } }) .OnError(exception => { Information("Publish-MyGet Task failed, but continuing with next Task..."); publishingError = true; }); Task("Publish-NuGet") .IsDependentOn("Create-NuGet-Packages") .WithCriteria(() => parameters.ShouldPublish) .Does(() => { // Resolve the API key. var apiKey = EnvironmentVariable("NUGET_API_KEY"); if (string.IsNullOrEmpty(apiKey)) { throw new InvalidOperationException("Could not resolve NuGet API key."); } // Resolve the API url. var apiUrl = EnvironmentVariable("NUGET_API_URL"); if (string.IsNullOrEmpty(apiUrl)) { throw new InvalidOperationException("Could not resolve NuGet API url."); } foreach (var package in parameters.Packages.Nuget) { // Push the package. NuGetPush(package.PackagePath, new NuGetPushSettings { ApiKey = apiKey, Source = apiUrl }); } }) .OnError(exception => { Information("Publish-NuGet Task failed, but continuing with next Task..."); publishingError = true; }); Task("Publish-Chocolatey") .IsDependentOn("Create-Chocolatey-Packages") .WithCriteria(() => parameters.ShouldPublish) .Does(() => { // Resolve the API key. var apiKey = EnvironmentVariable("CHOCOLATEY_API_KEY"); if (string.IsNullOrEmpty(apiKey)) { throw new InvalidOperationException("Could not resolve Chocolatey API key."); } // Resolve the API url. var apiUrl = EnvironmentVariable("CHOCOLATEY_API_URL"); if (string.IsNullOrEmpty(apiUrl)) { throw new InvalidOperationException("Could not resolve Chocolatey API url."); } foreach (var package in parameters.Packages.Chocolatey) { // Push the package. ChocolateyPush(package.PackagePath, new ChocolateyPushSettings { ApiKey = apiKey, Source = apiUrl }); } }) .OnError(exception => { Information("Publish-Chocolatey Task failed, but continuing with next Task..."); publishingError = true; }); Task("Publish-HomeBrew") .WithCriteria(() => parameters.ShouldPublish) .IsDependentOn("Zip-Files") .Does(() => { var hash = CalculateFileHash(parameters.Paths.Files.ZipArtifactPathDesktop).ToHex(); Information("Hash for creating HomeBrew PullRequest: {0}", hash); }) .OnError(exception => { Information("Publish-HomeBrew Task failed, but continuing with next Task..."); publishingError = true; }); Task("Publish-GitHub-Release") .WithCriteria(() => parameters.ShouldPublish) .Does(() => { GitReleaseManagerAddAssets(parameters.GitHub.UserName, parameters.GitHub.Password, "cake-build", "cake", parameters.Version.Milestone, parameters.Paths.Files.ZipArtifactPathDesktop.ToString()); GitReleaseManagerAddAssets(parameters.GitHub.UserName, parameters.GitHub.Password, "cake-build", "cake", parameters.Version.Milestone, parameters.Paths.Files.ZipArtifactPathCoreClr.ToString()); GitReleaseManagerClose(parameters.GitHub.UserName, parameters.GitHub.Password, "cake-build", "cake", parameters.Version.Milestone); }) .OnError(exception => { Information("Publish-GitHub-Release Task failed, but continuing with next Task..."); publishingError = true; }); Task("Create-Release-Notes") .Does(() => { GitReleaseManagerCreate(parameters.GitHub.UserName, parameters.GitHub.Password, "cake-build", "cake", new GitReleaseManagerCreateSettings { Milestone = parameters.Version.Milestone, Name = parameters.Version.Milestone, Prerelease = true, TargetCommitish = "main" }); }); ////////////////////////////////////////////////////////////////////// // TASK TARGETS ////////////////////////////////////////////////////////////////////// Task("Package") .IsDependentOn("Zip-Files") .IsDependentOn("Create-NuGet-Packages"); Task("Default") .IsDependentOn("Package"); Task("AppVeyor") .IsDependentOn("Upload-AppVeyor-Artifacts") .IsDependentOn("Upload-Coverage-Report") .IsDependentOn("Publish-MyGet") .IsDependentOn("Publish-NuGet") .IsDependentOn("Publish-Chocolatey") .IsDependentOn("Publish-HomeBrew") .IsDependentOn("Publish-GitHub-Release") .Finally(() => { if (publishingError) { throw new Exception("An error occurred during the publishing of Cake. All publishing tasks have been attempted."); } }); Task("Travis") .IsDependentOn("Run-Unit-Tests"); Task("ReleaseNotes") .IsDependentOn("Create-Release-Notes"); ////////////////////////////////////////////////////////////////////// // EXECUTION ////////////////////////////////////////////////////////////////////// RunTarget(parameters.Target); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Text; using System.IO; using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Xml.Schema; using System.Globalization; #if NET_NATIVE namespace System.Xml { internal class XmlNodeReader : XmlReader, IXmlNamespaceResolver { public XmlNodeReader() { throw NotImplemented.ByDesign; } // Gets the type of the current node. public override XmlNodeType NodeType { get { throw NotImplemented.ByDesign; } } // Gets the name of // the current node, including the namespace prefix. public override string Name { get { throw NotImplemented.ByDesign; } } // Gets the name of the current node without the namespace prefix. public override string LocalName { get { throw NotImplemented.ByDesign; } } // Gets the namespace URN (as defined in the W3C Namespace Specification) // of the current namespace scope. public override string NamespaceURI { get { throw NotImplemented.ByDesign; } } // Gets the namespace prefix associated with the current node. public override string Prefix { get { throw NotImplemented.ByDesign; } } // Gets a value indicating whether // XmlNodeReader.Value has a value to return. public override bool HasValue { get { throw NotImplemented.ByDesign; } } // Gets the text value of the current node. public override string Value { get { throw NotImplemented.ByDesign; } } // Gets the depth of the // current node in the XML element stack. public override int Depth { get { throw NotImplemented.ByDesign; } } // Gets the base URI of the current node. public override String BaseURI { get { throw NotImplemented.ByDesign; } } public override bool CanResolveEntity { get { throw NotImplemented.ByDesign; } } // Gets a value indicating whether the current // node is an empty element (for example, <MyElement/>. public override bool IsEmptyElement { get { throw NotImplemented.ByDesign; } } // Gets a value indicating whether the current node is an // attribute that was generated from the default value defined // in the DTD or schema. public override bool IsDefault { get { throw NotImplemented.ByDesign; } } // Gets the current xml:space scope. public override XmlSpace XmlSpace { get { throw NotImplemented.ByDesign; } } // Gets the current xml:lang scope. public override string XmlLang { get { throw NotImplemented.ByDesign; } } // // Attribute Accessors // // Gets the number of attributes on the current node. public override int AttributeCount { get { throw NotImplemented.ByDesign; } } // Gets the value of the attribute with the specified name. public override string GetAttribute(string name) { throw NotImplemented.ByDesign; } // Gets the value of the attribute with the specified name and namespace. public override string GetAttribute(string name, string namespaceURI) { throw NotImplemented.ByDesign; } // Gets the value of the attribute with the specified index. public override string GetAttribute(int attributeIndex) { throw NotImplemented.ByDesign; } // Moves to the attribute with the specified name. public override bool MoveToAttribute(string name) { throw NotImplemented.ByDesign; } // Moves to the attribute with the specified name and namespace. public override bool MoveToAttribute(string name, string namespaceURI) { throw NotImplemented.ByDesign; } // Moves to the attribute with the specified index. public override void MoveToAttribute(int attributeIndex) { throw NotImplemented.ByDesign; } // Moves to the first attribute. public override bool MoveToFirstAttribute() { throw NotImplemented.ByDesign; } // Moves to the next attribute. public override bool MoveToNextAttribute() { throw NotImplemented.ByDesign; } // Moves to the element that contains the current attribute node. public override bool MoveToElement() { throw NotImplemented.ByDesign; } // // Moving through the Stream // // Reads the next node from the stream. public override bool Read() { throw NotImplemented.ByDesign; } // Gets a value indicating whether the reader is positioned at the // end of the stream. public override bool EOF { get { throw NotImplemented.ByDesign; } } // Closes the stream, changes the XmlNodeReader.ReadState // to Closed, and sets all the properties back to zero. protected override void Dispose(bool disposing) { throw NotImplemented.ByDesign; } // Gets the read state of the stream. public override ReadState ReadState { get { throw NotImplemented.ByDesign; } } // Skips to the end tag of the current element. public override void Skip() { throw NotImplemented.ByDesign; } // // Partial Content Read Methods // // Gets a value indicating whether the current node // has any attributes. public override bool HasAttributes { get { return (AttributeCount > 0); } } // // Nametable and Namespace Helpers // // Gets the XmlNameTable associated with this implementation. public override XmlNameTable NameTable { get { throw NotImplemented.ByDesign; } } // Resolves a namespace prefix in the current element's scope. public override String LookupNamespace(string prefix) { throw NotImplemented.ByDesign; } // Resolves the entity reference for nodes of NodeType EntityReference. public override void ResolveEntity() { throw NotImplemented.ByDesign; } // Parses the attribute value into one or more Text and/or // EntityReference node types. public override bool ReadAttributeValue() { throw NotImplemented.ByDesign; } public override bool CanReadBinaryContent { get { return true; } } public override int ReadContentAsBase64(byte[] buffer, int index, int count) { throw NotImplemented.ByDesign; } public override int ReadContentAsBinHex(byte[] buffer, int index, int count) { throw NotImplemented.ByDesign; } public override int ReadElementContentAsBase64(byte[] buffer, int index, int count) { throw NotImplemented.ByDesign; } public override int ReadElementContentAsBinHex(byte[] buffer, int index, int count) { throw NotImplemented.ByDesign; } // // IXmlNamespaceResolver // IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope) { throw NotImplemented.ByDesign; } string IXmlNamespaceResolver.LookupPrefix(string namespaceName) { throw NotImplemented.ByDesign; } String IXmlNamespaceResolver.LookupNamespace(string prefix) { throw NotImplemented.ByDesign; } } } #endif
using System; using System.Collections.Generic; using System.Windows.Forms; using System.Threading; using System.ServiceProcess; using WSMailPDF; using WSMailSupport; using WSMailTryBuy; namespace WindowsServiceWrapper { static class Program { static Configuration objConfiguration; static NotifyIcon appIcon; static System.Timers.Timer timer; static ServiceController sc; private static string SERVICE_NAME = WindowsServiceWrapper.Properties.Settings.Default.SERVICE_NAME; static ContextMenu mnu; /// <summary> /// The main entry point for the application. /// A simple wrapper app which allows the developer to see the current status of a Windows Service /// without using Control Panel>Services. /// The application uses a timer to refresh the "status" of a Windows Service. Obviously /// the status can be changed manually through Control Panel>Services, but you can also use /// this app to change the status also. /// Nothing complicated, just a simple "right-click" context menu which allows you to start /// and stop the service. /// Note that the service name ( SERVICE_NAME ) is read from the App.Config, you must ensure /// that the Windows Service itself has it's "DISPLAYNAME" property equal to the App.Config /// setting, or else this app will not be able to find the service in the registry and conseqently /// fire it up!!! /// </summary> [STAThread] static void Main() { System.Diagnostics.EventLog el; el = new System.Diagnostics.EventLog("CC_EMAIL"); //,"DEV",); if (!System.Diagnostics.EventLog.SourceExists("CC_EMAIL")) { System.Diagnostics.EventLog.CreateEventSource("CC_EMAIL", "CC_EMAIL"); } el.Source = "CC_EMAIL"; //el.WriteEntry("Starting timer"); //TestMailPDF m = new TestMailPDF(); //m.WithWebClient(); //COMMENT WHEN BUILDING THE SERVICE!! //MAIL PDF //NewMailPDF m = new NewMailPDF(); //m.ServiceMail(); ////m.WithIntegrationFramework(); //return; //MAIL SUPPORT //MailSupport ms = new MailSupport(); //ms.ServiceMail(); //return; //MAIL TRY/BUY //MailTryBuy ms = new MailTryBuy(); //ms.ServiceMail(); //MAIL PARTNER PROGRAMME //MailApplicationRequestsService ms = new MailApplicationRequestsService(); //ms.ServicePartnerProgramme(); //MAIL SEND TO COLLEAGUE MailApplicationRequestsService ms = new MailApplicationRequestsService(); ms.ServiceSendToColleague(); return; System.Threading.Mutex appSingleTon = new Mutex(false, "Service Monitor"); if (appSingleTon.WaitOne(0, false)) { Application.EnableVisualStyles(); Program.IntializeIcon(); Microsoft.Win32.SystemEvents.SessionEnded += new Microsoft.Win32.SessionEndedEventHandler(SystemEvent_SessionEnded); timer = new System.Timers.Timer(10000); timer.Elapsed += new System.Timers.ElapsedEventHandler(ServiceChecker); timer.Enabled = true; sc = new ServiceController(SERVICE_NAME); Application.Run(); } appSingleTon.Close(); } /// <summary> /// The delegated method to execute in conjunction with the timer. Simply refreshes the context /// menu depending on the status of the service. /// </summary> /// <param name="source"></param> /// <param name="e"></param> private static void ServiceChecker(object source, System.Timers.ElapsedEventArgs e) { sc.Refresh(); try { if (sc.Status == ServiceControllerStatus.Running) { appIcon.Icon = WindowsServiceWrapper.Properties.Resources.ServiceStart; appIcon.Text = "Service Monitor"; } else if (sc.Status == ServiceControllerStatus.Stopped) { appIcon.Icon = WindowsServiceWrapper.Properties.Resources.ServiceStop; appIcon.Text = "Service Stopped !!!"; } if (sc.Status != ServiceControllerStatus.Running) { //sc.Start(); mnu.MenuItems["Start Compare Cloudware EMailer Service"].Enabled = true; mnu.MenuItems["Stop Compare Cloudware EMailer Service"].Enabled = false; } else { mnu.MenuItems["Start Compare Cloudware EMailer Service"].Enabled = false; mnu.MenuItems["Stop Compare Cloudware EMailer Service"].Enabled = true; } } catch { } } /// <summary> /// Construct the toolbar icon, context menu and click events. /// </summary> private static void IntializeIcon() { appIcon = new NotifyIcon(); appIcon.Icon = WindowsServiceWrapper.Properties.Resources.ServiceStart; appIcon.Visible = true; mnu = new ContextMenu(); MenuItem configItem = new MenuItem("Configuration Manager"); configItem.DefaultItem = true; configItem.Click += new EventHandler(ConfigItem_Click); mnu.MenuItems.Add(configItem); mnu.MenuItems.Add("-"); MenuItem startItem = new MenuItem("Start Compare Cloudware EMailer Service"); startItem.Click += new EventHandler(StartItem_Click); startItem.Name = "Start Compare Cloudware EMailer Service"; mnu.MenuItems.Add(startItem); mnu.MenuItems.Add("-"); MenuItem stopItem = new MenuItem("Stop Compare Cloudware EMailer Service"); stopItem.Click += new EventHandler(StopItem_Click); stopItem.Name = "Stop Compare Cloudware EMailer Service"; mnu.MenuItems.Add(stopItem); mnu.MenuItems.Add("-"); MenuItem closeItem = new MenuItem("Exit"); closeItem.Click += new EventHandler(CloseItem_Click); mnu.MenuItems.Add(closeItem); appIcon.ContextMenu = mnu; appIcon.Text = "Compare Cloudware EMailer Service Monitor"; appIcon.DoubleClick += new EventHandler(ConfigItem_Click); } /// <summary> /// FOR FUTURE USE!!! /// Not used at present, was going to use so that the database connection could be /// tested from the machine/context that was running the Windows Service. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private static void ConfigItem_Click(object sender, EventArgs e) { if (objConfiguration == null) objConfiguration = new Configuration(); try { objConfiguration.Visible = true; } catch { objConfiguration = new Configuration(); objConfiguration.Visible = true; } } #region Click Events private static void StartItem_Click(object sender, EventArgs e) { if (sc.Status != ServiceControllerStatus.Running) { sc.Start(); mnu.MenuItems["Start Compare Cloudware EMailer Service"].Enabled = false; mnu.MenuItems["Stop Compare Cloudware EMailer Service"].Enabled = true; } //objConfiguration.Close(); //appIcon.Visible = true; } private static void StopItem_Click(object sender, EventArgs e) { if (sc.Status != ServiceControllerStatus.Stopped) { sc.Stop(); mnu.MenuItems["Start Compare Cloudware EMailer Service"].Enabled = true; mnu.MenuItems["Stop Compare Cloudware EMailer Service"].Enabled = false; } //objConfiguration.Close(); //appIcon.Visible = true; } private static void CloseItem_Click(object sender, EventArgs e) { if (objConfiguration != null) objConfiguration.Close(); appIcon.Visible = false; Application.Exit(); } #endregion private static void SystemEvent_SessionEnded(object sender, Microsoft.Win32.SessionEndedEventArgs e) { if (objConfiguration != null) objConfiguration.Close(); appIcon.Visible = false; Application.Exit(); } } }
namespace ServiceBusExplorer.Controls { partial class HandleRuleControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.btnCreateDelete = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.toolTip = new System.Windows.Forms.ToolTip(this.components); this.grouperFilterType = new ServiceBusExplorer.Controls.Grouper(); this.checkBoxIsCorrelationFilter = new System.Windows.Forms.CheckBox(); this.grouperCorrelationFilter = new ServiceBusExplorer.Controls.Grouper(); this.txtCorrelationFilterTo = new System.Windows.Forms.TextBox(); this.lblCorrelationFilterTo = new System.Windows.Forms.Label(); this.txtCorrelationFilterSessionId = new System.Windows.Forms.TextBox(); this.lblCorrelationFilterSessionId = new System.Windows.Forms.Label(); this.txtCorrelationFilterReplyToSessionId = new System.Windows.Forms.TextBox(); this.lblCorrelationFilterReplyToSessionId = new System.Windows.Forms.Label(); this.txtCorrelationFilterReplyTo = new System.Windows.Forms.TextBox(); this.lblCorrelationFilterReplyTo = new System.Windows.Forms.Label(); this.txtCorrelationFilterMessageId = new System.Windows.Forms.TextBox(); this.lblCorrelationFilterMessageId = new System.Windows.Forms.Label(); this.txtCorrelationFilterLabel = new System.Windows.Forms.TextBox(); this.lblCorrelationFilterLabel = new System.Windows.Forms.Label(); this.txtCorrelationFilterCorrelationId = new System.Windows.Forms.TextBox(); this.lblCorrelationFilterCorrelationId = new System.Windows.Forms.Label(); this.txtCorrelationFilterContentType = new System.Windows.Forms.TextBox(); this.lblCorrelationFilterContentType = new System.Windows.Forms.Label(); this.authorizationRulesDataGridView = new System.Windows.Forms.DataGridView(); this.grouperCreatedAt = new ServiceBusExplorer.Controls.Grouper(); this.txtCreatedAt = new System.Windows.Forms.TextBox(); this.grouperIsDefault = new ServiceBusExplorer.Controls.Grouper(); this.checkBoxDefault = new System.Windows.Forms.CheckBox(); this.grouperAction = new ServiceBusExplorer.Controls.Grouper(); this.txtSqlFilterAction = new System.Windows.Forms.TextBox(); this.grouperFilter = new ServiceBusExplorer.Controls.Grouper(); this.txtFilterExpression = new System.Windows.Forms.TextBox(); this.grouperName = new ServiceBusExplorer.Controls.Grouper(); this.txtName = new System.Windows.Forms.TextBox(); this.grouperFilterType.SuspendLayout(); this.grouperCorrelationFilter.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.authorizationRulesDataGridView)).BeginInit(); this.grouperCreatedAt.SuspendLayout(); this.grouperIsDefault.SuspendLayout(); this.grouperAction.SuspendLayout(); this.grouperFilter.SuspendLayout(); this.grouperName.SuspendLayout(); this.SuspendLayout(); // // btnCreateDelete // this.btnCreateDelete.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnCreateDelete.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(215)))), ((int)(((byte)(228)))), ((int)(((byte)(242))))); this.btnCreateDelete.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.btnCreateDelete.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.btnCreateDelete.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.btnCreateDelete.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.btnCreateDelete.ForeColor = System.Drawing.SystemColors.ControlText; this.btnCreateDelete.Location = new System.Drawing.Point(800, 360); this.btnCreateDelete.Name = "btnCreateDelete"; this.btnCreateDelete.Size = new System.Drawing.Size(72, 24); this.btnCreateDelete.TabIndex = 6; this.btnCreateDelete.Text = "Create"; this.btnCreateDelete.UseVisualStyleBackColor = false; this.btnCreateDelete.Click += new System.EventHandler(this.btnCreateDelete_Click); this.btnCreateDelete.MouseEnter += new System.EventHandler(this.button_MouseEnter); this.btnCreateDelete.MouseLeave += new System.EventHandler(this.button_MouseLeave); // // btnCancel // this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnCancel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(215)))), ((int)(((byte)(228)))), ((int)(((byte)(242))))); this.btnCancel.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.btnCancel.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.btnCancel.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.btnCancel.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.btnCancel.ForeColor = System.Drawing.SystemColors.ControlText; this.btnCancel.Location = new System.Drawing.Point(880, 360); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(72, 24); this.btnCancel.TabIndex = 7; this.btnCancel.Text = "Cancel"; this.btnCancel.UseVisualStyleBackColor = false; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); this.btnCancel.MouseEnter += new System.EventHandler(this.button_MouseEnter); this.btnCancel.MouseLeave += new System.EventHandler(this.button_MouseLeave); // // grouperFilterType // this.grouperFilterType.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.grouperFilterType.BackgroundColor = System.Drawing.Color.FromArgb(((int)(((byte)(215)))), ((int)(((byte)(228)))), ((int)(((byte)(242))))); this.grouperFilterType.BackgroundGradientColor = System.Drawing.Color.White; this.grouperFilterType.BackgroundGradientMode = ServiceBusExplorer.Controls.Grouper.GroupBoxGradientMode.None; this.grouperFilterType.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.grouperFilterType.BorderThickness = 1F; this.grouperFilterType.Controls.Add(this.checkBoxIsCorrelationFilter); this.grouperFilterType.CustomGroupBoxColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.grouperFilterType.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F); this.grouperFilterType.ForeColor = System.Drawing.Color.White; this.grouperFilterType.GroupImage = null; this.grouperFilterType.GroupTitle = "Filter Type"; this.grouperFilterType.Location = new System.Drawing.Point(685, 8); this.grouperFilterType.Name = "grouperFilterType"; this.grouperFilterType.Padding = new System.Windows.Forms.Padding(20); this.grouperFilterType.PaintGroupBox = true; this.grouperFilterType.RoundCorners = 4; this.grouperFilterType.ShadowColor = System.Drawing.Color.DarkGray; this.grouperFilterType.ShadowControl = false; this.grouperFilterType.ShadowThickness = 1; this.grouperFilterType.Size = new System.Drawing.Size(137, 80); this.grouperFilterType.TabIndex = 3; // // checkBoxIsCorrelationFilter // this.checkBoxIsCorrelationFilter.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.checkBoxIsCorrelationFilter.AutoSize = true; this.checkBoxIsCorrelationFilter.ForeColor = System.Drawing.SystemColors.ControlText; this.checkBoxIsCorrelationFilter.Location = new System.Drawing.Point(16, 40); this.checkBoxIsCorrelationFilter.Name = "checkBoxIsCorrelationFilter"; this.checkBoxIsCorrelationFilter.Size = new System.Drawing.Size(76, 17); this.checkBoxIsCorrelationFilter.TabIndex = 0; this.checkBoxIsCorrelationFilter.Text = "Correlation"; this.checkBoxIsCorrelationFilter.UseVisualStyleBackColor = true; this.checkBoxIsCorrelationFilter.CheckedChanged += new System.EventHandler(this.checkBoxIsCorrelationFilter_CheckedChanged); // // grouperCorrelationFilter // this.grouperCorrelationFilter.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.grouperCorrelationFilter.BackgroundColor = System.Drawing.Color.FromArgb(((int)(((byte)(215)))), ((int)(((byte)(228)))), ((int)(((byte)(242))))); this.grouperCorrelationFilter.BackgroundGradientColor = System.Drawing.Color.White; this.grouperCorrelationFilter.BackgroundGradientMode = ServiceBusExplorer.Controls.Grouper.GroupBoxGradientMode.None; this.grouperCorrelationFilter.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.grouperCorrelationFilter.BorderThickness = 1F; this.grouperCorrelationFilter.Controls.Add(this.txtCorrelationFilterTo); this.grouperCorrelationFilter.Controls.Add(this.lblCorrelationFilterTo); this.grouperCorrelationFilter.Controls.Add(this.txtCorrelationFilterSessionId); this.grouperCorrelationFilter.Controls.Add(this.lblCorrelationFilterSessionId); this.grouperCorrelationFilter.Controls.Add(this.txtCorrelationFilterReplyToSessionId); this.grouperCorrelationFilter.Controls.Add(this.lblCorrelationFilterReplyToSessionId); this.grouperCorrelationFilter.Controls.Add(this.txtCorrelationFilterReplyTo); this.grouperCorrelationFilter.Controls.Add(this.lblCorrelationFilterReplyTo); this.grouperCorrelationFilter.Controls.Add(this.txtCorrelationFilterMessageId); this.grouperCorrelationFilter.Controls.Add(this.lblCorrelationFilterMessageId); this.grouperCorrelationFilter.Controls.Add(this.txtCorrelationFilterLabel); this.grouperCorrelationFilter.Controls.Add(this.lblCorrelationFilterLabel); this.grouperCorrelationFilter.Controls.Add(this.txtCorrelationFilterCorrelationId); this.grouperCorrelationFilter.Controls.Add(this.lblCorrelationFilterCorrelationId); this.grouperCorrelationFilter.Controls.Add(this.txtCorrelationFilterContentType); this.grouperCorrelationFilter.Controls.Add(this.lblCorrelationFilterContentType); this.grouperCorrelationFilter.Controls.Add(this.authorizationRulesDataGridView); this.grouperCorrelationFilter.CustomGroupBoxColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.grouperCorrelationFilter.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F); this.grouperCorrelationFilter.ForeColor = System.Drawing.Color.White; this.grouperCorrelationFilter.GroupImage = null; this.grouperCorrelationFilter.GroupTitle = "Correlation Filter"; this.grouperCorrelationFilter.Location = new System.Drawing.Point(16, 96); this.grouperCorrelationFilter.Name = "grouperCorrelationFilter"; this.grouperCorrelationFilter.Padding = new System.Windows.Forms.Padding(40, 38, 40, 38); this.grouperCorrelationFilter.PaintGroupBox = true; this.grouperCorrelationFilter.RoundCorners = 4; this.grouperCorrelationFilter.ShadowColor = System.Drawing.Color.DarkGray; this.grouperCorrelationFilter.ShadowControl = false; this.grouperCorrelationFilter.ShadowThickness = 1; this.grouperCorrelationFilter.Size = new System.Drawing.Size(860, 256); this.grouperCorrelationFilter.TabIndex = 1; this.grouperCorrelationFilter.Visible = false; // // txtCorrelationFilterTo // this.txtCorrelationFilterTo.Location = new System.Drawing.Point(128, 228); this.txtCorrelationFilterTo.Margin = new System.Windows.Forms.Padding(6); this.txtCorrelationFilterTo.Name = "txtCorrelationFilterTo"; this.txtCorrelationFilterTo.Size = new System.Drawing.Size(250, 20); this.txtCorrelationFilterTo.TabIndex = 15; // // lblCorrelationFilterTo // this.lblCorrelationFilterTo.AutoSize = true; this.lblCorrelationFilterTo.ForeColor = System.Drawing.SystemColors.ControlText; this.lblCorrelationFilterTo.Location = new System.Drawing.Point(16, 228); this.lblCorrelationFilterTo.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0); this.lblCorrelationFilterTo.Name = "lblCorrelationFilterTo"; this.lblCorrelationFilterTo.Size = new System.Drawing.Size(20, 13); this.lblCorrelationFilterTo.TabIndex = 14; this.lblCorrelationFilterTo.Text = "To"; // // txtCorrelationFilterSessionId // this.txtCorrelationFilterSessionId.Location = new System.Drawing.Point(128, 200); this.txtCorrelationFilterSessionId.Margin = new System.Windows.Forms.Padding(6); this.txtCorrelationFilterSessionId.Name = "txtCorrelationFilterSessionId"; this.txtCorrelationFilterSessionId.Size = new System.Drawing.Size(250, 20); this.txtCorrelationFilterSessionId.TabIndex = 13; // // lblCorrelationFilterSessionId // this.lblCorrelationFilterSessionId.AutoSize = true; this.lblCorrelationFilterSessionId.ForeColor = System.Drawing.SystemColors.ControlText; this.lblCorrelationFilterSessionId.Location = new System.Drawing.Point(16, 200); this.lblCorrelationFilterSessionId.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0); this.lblCorrelationFilterSessionId.Name = "lblCorrelationFilterSessionId"; this.lblCorrelationFilterSessionId.Size = new System.Drawing.Size(53, 13); this.lblCorrelationFilterSessionId.TabIndex = 12; this.lblCorrelationFilterSessionId.Text = "SessionId"; // // txtCorrelationFilterReplyToSessionId // this.txtCorrelationFilterReplyToSessionId.Location = new System.Drawing.Point(128, 172); this.txtCorrelationFilterReplyToSessionId.Margin = new System.Windows.Forms.Padding(6); this.txtCorrelationFilterReplyToSessionId.Name = "txtCorrelationFilterReplyToSessionId"; this.txtCorrelationFilterReplyToSessionId.Size = new System.Drawing.Size(250, 20); this.txtCorrelationFilterReplyToSessionId.TabIndex = 11; // // lblCorrelationFilterReplyToSessionId // this.lblCorrelationFilterReplyToSessionId.AutoSize = true; this.lblCorrelationFilterReplyToSessionId.ForeColor = System.Drawing.SystemColors.ControlText; this.lblCorrelationFilterReplyToSessionId.Location = new System.Drawing.Point(16, 172); this.lblCorrelationFilterReplyToSessionId.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0); this.lblCorrelationFilterReplyToSessionId.Name = "lblCorrelationFilterReplyToSessionId"; this.lblCorrelationFilterReplyToSessionId.Size = new System.Drawing.Size(93, 13); this.lblCorrelationFilterReplyToSessionId.TabIndex = 10; this.lblCorrelationFilterReplyToSessionId.Text = "ReplyToSessionId"; // // txtCorrelationFilterReplyTo // this.txtCorrelationFilterReplyTo.Location = new System.Drawing.Point(128, 144); this.txtCorrelationFilterReplyTo.Margin = new System.Windows.Forms.Padding(6); this.txtCorrelationFilterReplyTo.Name = "txtCorrelationFilterReplyTo"; this.txtCorrelationFilterReplyTo.Size = new System.Drawing.Size(250, 20); this.txtCorrelationFilterReplyTo.TabIndex = 9; // // lblCorrelationFilterReplyTo // this.lblCorrelationFilterReplyTo.AutoSize = true; this.lblCorrelationFilterReplyTo.ForeColor = System.Drawing.SystemColors.ControlText; this.lblCorrelationFilterReplyTo.Location = new System.Drawing.Point(16, 144); this.lblCorrelationFilterReplyTo.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0); this.lblCorrelationFilterReplyTo.Name = "lblCorrelationFilterReplyTo"; this.lblCorrelationFilterReplyTo.Size = new System.Drawing.Size(47, 13); this.lblCorrelationFilterReplyTo.TabIndex = 8; this.lblCorrelationFilterReplyTo.Text = "ReplyTo"; // // txtCorrelationFilterMessageId // this.txtCorrelationFilterMessageId.Location = new System.Drawing.Point(128, 116); this.txtCorrelationFilterMessageId.Margin = new System.Windows.Forms.Padding(6); this.txtCorrelationFilterMessageId.Name = "txtCorrelationFilterMessageId"; this.txtCorrelationFilterMessageId.Size = new System.Drawing.Size(250, 20); this.txtCorrelationFilterMessageId.TabIndex = 7; // // lblCorrelationFilterMessageId // this.lblCorrelationFilterMessageId.AutoSize = true; this.lblCorrelationFilterMessageId.ForeColor = System.Drawing.SystemColors.ControlText; this.lblCorrelationFilterMessageId.Location = new System.Drawing.Point(16, 116); this.lblCorrelationFilterMessageId.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0); this.lblCorrelationFilterMessageId.Name = "lblCorrelationFilterMessageId"; this.lblCorrelationFilterMessageId.Size = new System.Drawing.Size(59, 13); this.lblCorrelationFilterMessageId.TabIndex = 6; this.lblCorrelationFilterMessageId.Text = "MessageId"; // // txtCorrelationFilterLabel // this.txtCorrelationFilterLabel.Location = new System.Drawing.Point(128, 88); this.txtCorrelationFilterLabel.Margin = new System.Windows.Forms.Padding(6); this.txtCorrelationFilterLabel.Name = "txtCorrelationFilterLabel"; this.txtCorrelationFilterLabel.Size = new System.Drawing.Size(250, 20); this.txtCorrelationFilterLabel.TabIndex = 5; // // lblCorrelationFilterLabel // this.lblCorrelationFilterLabel.AutoSize = true; this.lblCorrelationFilterLabel.ForeColor = System.Drawing.SystemColors.ControlText; this.lblCorrelationFilterLabel.Location = new System.Drawing.Point(16, 88); this.lblCorrelationFilterLabel.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0); this.lblCorrelationFilterLabel.Name = "lblCorrelationFilterLabel"; this.lblCorrelationFilterLabel.Size = new System.Drawing.Size(33, 13); this.lblCorrelationFilterLabel.TabIndex = 4; this.lblCorrelationFilterLabel.Text = "Label"; // // txtCorrelationFilterCorrelationId // this.txtCorrelationFilterCorrelationId.Location = new System.Drawing.Point(128, 60); this.txtCorrelationFilterCorrelationId.Margin = new System.Windows.Forms.Padding(6); this.txtCorrelationFilterCorrelationId.Name = "txtCorrelationFilterCorrelationId"; this.txtCorrelationFilterCorrelationId.Size = new System.Drawing.Size(250, 20); this.txtCorrelationFilterCorrelationId.TabIndex = 3; // // lblCorrelationFilterCorrelationId // this.lblCorrelationFilterCorrelationId.AutoSize = true; this.lblCorrelationFilterCorrelationId.ForeColor = System.Drawing.SystemColors.ControlText; this.lblCorrelationFilterCorrelationId.Location = new System.Drawing.Point(16, 60); this.lblCorrelationFilterCorrelationId.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0); this.lblCorrelationFilterCorrelationId.Name = "lblCorrelationFilterCorrelationId"; this.lblCorrelationFilterCorrelationId.Size = new System.Drawing.Size(66, 13); this.lblCorrelationFilterCorrelationId.TabIndex = 2; this.lblCorrelationFilterCorrelationId.Text = "CorrelationId"; // // txtCorrelationFilterContentType // this.txtCorrelationFilterContentType.Location = new System.Drawing.Point(128, 32); this.txtCorrelationFilterContentType.Margin = new System.Windows.Forms.Padding(6); this.txtCorrelationFilterContentType.Name = "txtCorrelationFilterContentType"; this.txtCorrelationFilterContentType.Size = new System.Drawing.Size(250, 20); this.txtCorrelationFilterContentType.TabIndex = 1; // // lblCorrelationFilterContentType // this.lblCorrelationFilterContentType.AutoSize = true; this.lblCorrelationFilterContentType.ForeColor = System.Drawing.SystemColors.ControlText; this.lblCorrelationFilterContentType.Location = new System.Drawing.Point(16, 32); this.lblCorrelationFilterContentType.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0); this.lblCorrelationFilterContentType.Name = "lblCorrelationFilterContentType"; this.lblCorrelationFilterContentType.Size = new System.Drawing.Size(68, 13); this.lblCorrelationFilterContentType.TabIndex = 0; this.lblCorrelationFilterContentType.Text = "ContentType"; // // authorizationRulesDataGridView // this.authorizationRulesDataGridView.AllowUserToResizeRows = false; this.authorizationRulesDataGridView.BackgroundColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.authorizationRulesDataGridView.BorderStyle = System.Windows.Forms.BorderStyle.None; this.authorizationRulesDataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.authorizationRulesDataGridView.GridColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.authorizationRulesDataGridView.Location = new System.Drawing.Point(16, 256); this.authorizationRulesDataGridView.Margin = new System.Windows.Forms.Padding(8); this.authorizationRulesDataGridView.MultiSelect = false; this.authorizationRulesDataGridView.Name = "authorizationRulesDataGridView"; this.authorizationRulesDataGridView.RowHeadersWidth = 24; this.authorizationRulesDataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.authorizationRulesDataGridView.ShowCellErrors = false; this.authorizationRulesDataGridView.ShowRowErrors = false; this.authorizationRulesDataGridView.Size = new System.Drawing.Size(400, 96); this.authorizationRulesDataGridView.TabIndex = 0; this.authorizationRulesDataGridView.RowsAdded += new System.Windows.Forms.DataGridViewRowsAddedEventHandler(this.authorizationRulesDataGridView_RowsAdded); this.authorizationRulesDataGridView.RowsRemoved += new System.Windows.Forms.DataGridViewRowsRemovedEventHandler(this.authorizationRulesDataGridView_RowsRemoved); this.authorizationRulesDataGridView.Resize += new System.EventHandler(this.authorizationRulesDataGridView_Resize); // // grouperCreatedAt // this.grouperCreatedAt.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.grouperCreatedAt.BackgroundColor = System.Drawing.Color.FromArgb(((int)(((byte)(215)))), ((int)(((byte)(228)))), ((int)(((byte)(242))))); this.grouperCreatedAt.BackgroundGradientColor = System.Drawing.Color.White; this.grouperCreatedAt.BackgroundGradientMode = ServiceBusExplorer.Controls.Grouper.GroupBoxGradientMode.None; this.grouperCreatedAt.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.grouperCreatedAt.BorderThickness = 1F; this.grouperCreatedAt.Controls.Add(this.txtCreatedAt); this.grouperCreatedAt.CustomGroupBoxColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.grouperCreatedAt.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F); this.grouperCreatedAt.ForeColor = System.Drawing.Color.White; this.grouperCreatedAt.GroupImage = null; this.grouperCreatedAt.GroupTitle = "Created At"; this.grouperCreatedAt.Location = new System.Drawing.Point(492, 8); this.grouperCreatedAt.Name = "grouperCreatedAt"; this.grouperCreatedAt.Padding = new System.Windows.Forms.Padding(20); this.grouperCreatedAt.PaintGroupBox = true; this.grouperCreatedAt.RoundCorners = 4; this.grouperCreatedAt.ShadowColor = System.Drawing.Color.DarkGray; this.grouperCreatedAt.ShadowControl = false; this.grouperCreatedAt.ShadowThickness = 1; this.grouperCreatedAt.Size = new System.Drawing.Size(187, 80); this.grouperCreatedAt.TabIndex = 2; // // txtCreatedAt // this.txtCreatedAt.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtCreatedAt.BackColor = System.Drawing.SystemColors.Window; this.txtCreatedAt.Location = new System.Drawing.Point(16, 40); this.txtCreatedAt.Name = "txtCreatedAt"; this.txtCreatedAt.ReadOnly = true; this.txtCreatedAt.Size = new System.Drawing.Size(155, 20); this.txtCreatedAt.TabIndex = 0; // // grouperIsDefault // this.grouperIsDefault.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.grouperIsDefault.BackgroundColor = System.Drawing.Color.FromArgb(((int)(((byte)(215)))), ((int)(((byte)(228)))), ((int)(((byte)(242))))); this.grouperIsDefault.BackgroundGradientColor = System.Drawing.Color.White; this.grouperIsDefault.BackgroundGradientMode = ServiceBusExplorer.Controls.Grouper.GroupBoxGradientMode.None; this.grouperIsDefault.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.grouperIsDefault.BorderThickness = 1F; this.grouperIsDefault.Controls.Add(this.checkBoxDefault); this.grouperIsDefault.CustomGroupBoxColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.grouperIsDefault.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F); this.grouperIsDefault.ForeColor = System.Drawing.Color.White; this.grouperIsDefault.GroupImage = null; this.grouperIsDefault.GroupTitle = "Is Default?"; this.grouperIsDefault.Location = new System.Drawing.Point(828, 8); this.grouperIsDefault.Name = "grouperIsDefault"; this.grouperIsDefault.Padding = new System.Windows.Forms.Padding(20); this.grouperIsDefault.PaintGroupBox = true; this.grouperIsDefault.RoundCorners = 4; this.grouperIsDefault.ShadowColor = System.Drawing.Color.DarkGray; this.grouperIsDefault.ShadowControl = false; this.grouperIsDefault.ShadowThickness = 1; this.grouperIsDefault.Size = new System.Drawing.Size(124, 80); this.grouperIsDefault.TabIndex = 4; // // checkBoxDefault // this.checkBoxDefault.AutoSize = true; this.checkBoxDefault.ForeColor = System.Drawing.SystemColors.ControlText; this.checkBoxDefault.Location = new System.Drawing.Point(16, 40); this.checkBoxDefault.Name = "checkBoxDefault"; this.checkBoxDefault.Size = new System.Drawing.Size(60, 17); this.checkBoxDefault.TabIndex = 0; this.checkBoxDefault.Text = "Default"; this.checkBoxDefault.UseVisualStyleBackColor = true; this.checkBoxDefault.CheckedChanged += new System.EventHandler(this.checkBoxDefault_CheckedChanged); // // grouperAction // this.grouperAction.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.grouperAction.BackgroundColor = System.Drawing.Color.FromArgb(((int)(((byte)(215)))), ((int)(((byte)(228)))), ((int)(((byte)(242))))); this.grouperAction.BackgroundGradientColor = System.Drawing.Color.White; this.grouperAction.BackgroundGradientMode = ServiceBusExplorer.Controls.Grouper.GroupBoxGradientMode.None; this.grouperAction.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.grouperAction.BorderThickness = 1F; this.grouperAction.Controls.Add(this.txtSqlFilterAction); this.grouperAction.CustomGroupBoxColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.grouperAction.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F); this.grouperAction.ForeColor = System.Drawing.Color.White; this.grouperAction.GroupImage = null; this.grouperAction.GroupTitle = "Action"; this.grouperAction.Location = new System.Drawing.Point(492, 96); this.grouperAction.Name = "grouperAction"; this.grouperAction.Padding = new System.Windows.Forms.Padding(20); this.grouperAction.PaintGroupBox = true; this.grouperAction.RoundCorners = 4; this.grouperAction.ShadowColor = System.Drawing.Color.DarkGray; this.grouperAction.ShadowControl = false; this.grouperAction.ShadowThickness = 1; this.grouperAction.Size = new System.Drawing.Size(460, 256); this.grouperAction.TabIndex = 5; // // txtSqlFilterAction // this.txtSqlFilterAction.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtSqlFilterAction.BackColor = System.Drawing.SystemColors.Window; this.txtSqlFilterAction.Location = new System.Drawing.Point(16, 32); this.txtSqlFilterAction.Multiline = true; this.txtSqlFilterAction.Name = "txtSqlFilterAction"; this.txtSqlFilterAction.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.txtSqlFilterAction.Size = new System.Drawing.Size(428, 208); this.txtSqlFilterAction.TabIndex = 0; // // grouperFilter // this.grouperFilter.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.grouperFilter.BackgroundColor = System.Drawing.Color.FromArgb(((int)(((byte)(215)))), ((int)(((byte)(228)))), ((int)(((byte)(242))))); this.grouperFilter.BackgroundGradientColor = System.Drawing.Color.White; this.grouperFilter.BackgroundGradientMode = ServiceBusExplorer.Controls.Grouper.GroupBoxGradientMode.None; this.grouperFilter.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.grouperFilter.BorderThickness = 1F; this.grouperFilter.Controls.Add(this.txtFilterExpression); this.grouperFilter.CustomGroupBoxColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.grouperFilter.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F); this.grouperFilter.ForeColor = System.Drawing.Color.White; this.grouperFilter.GroupImage = null; this.grouperFilter.GroupTitle = "Filter"; this.grouperFilter.Location = new System.Drawing.Point(16, 96); this.grouperFilter.Name = "grouperFilter"; this.grouperFilter.Padding = new System.Windows.Forms.Padding(20); this.grouperFilter.PaintGroupBox = true; this.grouperFilter.RoundCorners = 4; this.grouperFilter.ShadowColor = System.Drawing.Color.DarkGray; this.grouperFilter.ShadowControl = false; this.grouperFilter.ShadowThickness = 1; this.grouperFilter.Size = new System.Drawing.Size(460, 256); this.grouperFilter.TabIndex = 3; // // txtFilterExpression // this.txtFilterExpression.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtFilterExpression.BackColor = System.Drawing.SystemColors.Window; this.txtFilterExpression.Location = new System.Drawing.Point(16, 32); this.txtFilterExpression.Multiline = true; this.txtFilterExpression.Name = "txtFilterExpression"; this.txtFilterExpression.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.txtFilterExpression.Size = new System.Drawing.Size(428, 208); this.txtFilterExpression.TabIndex = 0; // // grouperName // this.grouperName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.grouperName.BackgroundColor = System.Drawing.Color.FromArgb(((int)(((byte)(215)))), ((int)(((byte)(228)))), ((int)(((byte)(242))))); this.grouperName.BackgroundGradientColor = System.Drawing.Color.White; this.grouperName.BackgroundGradientMode = ServiceBusExplorer.Controls.Grouper.GroupBoxGradientMode.None; this.grouperName.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.grouperName.BorderThickness = 1F; this.grouperName.Controls.Add(this.txtName); this.grouperName.CustomGroupBoxColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.grouperName.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F); this.grouperName.ForeColor = System.Drawing.Color.White; this.grouperName.GroupImage = null; this.grouperName.GroupTitle = "Name"; this.grouperName.Location = new System.Drawing.Point(16, 8); this.grouperName.Name = "grouperName"; this.grouperName.Padding = new System.Windows.Forms.Padding(20); this.grouperName.PaintGroupBox = true; this.grouperName.RoundCorners = 4; this.grouperName.ShadowColor = System.Drawing.Color.DarkGray; this.grouperName.ShadowControl = false; this.grouperName.ShadowThickness = 1; this.grouperName.Size = new System.Drawing.Size(460, 80); this.grouperName.TabIndex = 0; // // txtName // this.txtName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtName.BackColor = System.Drawing.SystemColors.Window; this.txtName.Location = new System.Drawing.Point(16, 40); this.txtName.Name = "txtName"; this.txtName.Size = new System.Drawing.Size(428, 20); this.txtName.TabIndex = 0; // // HandleRuleControl // this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(215)))), ((int)(((byte)(228)))), ((int)(((byte)(242))))); this.Controls.Add(this.grouperFilterType); this.Controls.Add(this.grouperCorrelationFilter); this.Controls.Add(this.grouperCreatedAt); this.Controls.Add(this.grouperIsDefault); this.Controls.Add(this.grouperAction); this.Controls.Add(this.grouperFilter); this.Controls.Add(this.grouperName); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnCreateDelete); this.Name = "HandleRuleControl"; this.Size = new System.Drawing.Size(968, 400); this.Resize += new System.EventHandler(this.HandleRuleControl_Resize); this.grouperFilterType.ResumeLayout(false); this.grouperFilterType.PerformLayout(); this.grouperCorrelationFilter.ResumeLayout(false); this.grouperCorrelationFilter.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.authorizationRulesDataGridView)).EndInit(); this.grouperCreatedAt.ResumeLayout(false); this.grouperCreatedAt.PerformLayout(); this.grouperIsDefault.ResumeLayout(false); this.grouperIsDefault.PerformLayout(); this.grouperAction.ResumeLayout(false); this.grouperAction.PerformLayout(); this.grouperFilter.ResumeLayout(false); this.grouperFilter.PerformLayout(); this.grouperName.ResumeLayout(false); this.grouperName.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button btnCreateDelete; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.ToolTip toolTip; private Grouper grouperName; private System.Windows.Forms.TextBox txtName; private Grouper grouperFilter; private System.Windows.Forms.TextBox txtFilterExpression; private Grouper grouperAction; private System.Windows.Forms.TextBox txtSqlFilterAction; private Grouper grouperIsDefault; private System.Windows.Forms.CheckBox checkBoxDefault; private Grouper grouperCreatedAt; private System.Windows.Forms.TextBox txtCreatedAt; private Grouper grouperFilterType; private Grouper grouperCorrelationFilter; private System.Windows.Forms.CheckBox checkBoxIsCorrelationFilter; private System.Windows.Forms.TextBox txtCorrelationFilterContentType; private System.Windows.Forms.Label lblCorrelationFilterContentType; private System.Windows.Forms.TextBox txtCorrelationFilterTo; private System.Windows.Forms.Label lblCorrelationFilterTo; private System.Windows.Forms.TextBox txtCorrelationFilterSessionId; private System.Windows.Forms.Label lblCorrelationFilterSessionId; private System.Windows.Forms.TextBox txtCorrelationFilterReplyToSessionId; private System.Windows.Forms.Label lblCorrelationFilterReplyToSessionId; private System.Windows.Forms.TextBox txtCorrelationFilterReplyTo; private System.Windows.Forms.Label lblCorrelationFilterReplyTo; private System.Windows.Forms.TextBox txtCorrelationFilterMessageId; private System.Windows.Forms.Label lblCorrelationFilterMessageId; private System.Windows.Forms.TextBox txtCorrelationFilterLabel; private System.Windows.Forms.Label lblCorrelationFilterLabel; private System.Windows.Forms.TextBox txtCorrelationFilterCorrelationId; private System.Windows.Forms.Label lblCorrelationFilterCorrelationId; private System.Windows.Forms.DataGridView authorizationRulesDataGridView; } }
/* * 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.Globalization; using System.IO; using System.Linq; using QuantConnect.Configuration; using QuantConnect.Interfaces; using QuantConnect.Logging; using QuantConnect.Orders.Fees; using QuantConnect.Util; namespace QuantConnect.Securities.Future { /// <summary> /// Represents a simple margin model for margin futures. Margin file contains Initial and Maintenance margins /// </summary> public class FutureMarginModel : SecurityMarginModel { private static readonly object DataFolderSymbolLock = new object(); // historical database of margin requirements private MarginRequirementsEntry[] _marginRequirementsHistory; private int _marginCurrentIndex; private readonly Security _security; private IDataProvider _dataProvider = Composer.Instance.GetExportedValueByTypeName<IDataProvider>(Config.Get("data-provider", "DefaultDataProvider")); /// <summary> /// True will enable usage of intraday margins. /// </summary> /// <remarks>Disabled by default. Note that intraday margins are less than overnight margins /// and could lead to margin calls</remarks> public bool EnableIntradayMargins { get; set; } /// <summary> /// Initial Overnight margin requirement for the contract effective from the date of change /// </summary> public virtual decimal InitialOvernightMarginRequirement => GetCurrentMarginRequirements(_security)?.InitialOvernight ?? 0m; /// <summary> /// Maintenance Overnight margin requirement for the contract effective from the date of change /// </summary> public virtual decimal MaintenanceOvernightMarginRequirement => GetCurrentMarginRequirements(_security)?.MaintenanceOvernight ?? 0m; /// <summary> /// Initial Intraday margin for the contract effective from the date of change /// </summary> public virtual decimal InitialIntradayMarginRequirement => GetCurrentMarginRequirements(_security)?.InitialIntraday ?? 0m; /// <summary> /// Maintenance Intraday margin requirement for the contract effective from the date of change /// </summary> public virtual decimal MaintenanceIntradayMarginRequirement => GetCurrentMarginRequirements(_security)?.MaintenanceIntraday ?? 0m; /// <summary> /// Initializes a new instance of the <see cref="FutureMarginModel"/> /// </summary> /// <param name="requiredFreeBuyingPowerPercent">The percentage used to determine the required unused buying power for the account.</param> /// <param name="security">The security that this model belongs to</param> public FutureMarginModel(decimal requiredFreeBuyingPowerPercent = 0, Security security = null) { RequiredFreeBuyingPowerPercent = requiredFreeBuyingPowerPercent; _security = security; } /// <summary> /// Gets the current leverage of the security /// </summary> /// <param name="security">The security to get leverage for</param> /// <returns>The current leverage in the security</returns> public override decimal GetLeverage(Security security) { return 1; } /// <summary> /// Sets the leverage for the applicable securities, i.e, futures /// </summary> /// <remarks> /// This is added to maintain backwards compatibility with the old margin/leverage system /// </remarks> /// <param name="security"></param> /// <param name="leverage">The new leverage</param> public override void SetLeverage(Security security, decimal leverage) { // Futures are leveraged products and different leverage cannot be set by user. throw new InvalidOperationException("Futures are leveraged products and different leverage cannot be set by user"); } /// <summary> /// Get the maximum market order quantity to obtain a position with a given buying power percentage. /// Will not take into account free buying power. /// </summary> /// <param name="parameters">An object containing the portfolio, the security and the target signed buying power percentage</param> /// <returns>Returns the maximum allowed market order quantity and if zero, also the reason</returns> public override GetMaximumOrderQuantityResult GetMaximumOrderQuantityForTargetBuyingPower( GetMaximumOrderQuantityForTargetBuyingPowerParameters parameters) { if (Math.Abs(parameters.TargetBuyingPower) > 1) { throw new InvalidOperationException( "Futures do not allow specifying a leveraged target, since they are traded using margin which already is leveraged. " + $"Possible target buying power goes from -1 to 1, target provided is: {parameters.TargetBuyingPower}"); } return base.GetMaximumOrderQuantityForTargetBuyingPower(parameters); } /// <summary> /// Gets the total margin required to execute the specified order in units of the account currency including fees /// </summary> /// <param name="parameters">An object containing the portfolio, the security and the order</param> /// <returns>The total margin in terms of the currency quoted in the order</returns> public override InitialMargin GetInitialMarginRequiredForOrder( InitialMarginRequiredForOrderParameters parameters ) { //Get the order value from the non-abstract order classes (MarketOrder, LimitOrder, StopMarketOrder) //Market order is approximated from the current security price and set in the MarketOrder Method in QCAlgorithm. var fees = parameters.Security.FeeModel.GetOrderFee( new OrderFeeParameters(parameters.Security, parameters.Order)).Value; var feesInAccountCurrency = parameters.CurrencyConverter. ConvertToAccountCurrency(fees).Amount; var orderMargin = this.GetInitialMarginRequirement(parameters.Security, parameters.Order.Quantity); return new InitialMargin(orderMargin + Math.Sign(orderMargin) * feesInAccountCurrency); } /// <summary> /// Gets the margin currently allotted to the specified holding /// </summary> /// <param name="parameters">An object containing the security</param> /// <returns>The maintenance margin required for the </returns> public override MaintenanceMargin GetMaintenanceMargin(MaintenanceMarginParameters parameters) { var security = parameters.Security; if (security?.GetLastData() == null || parameters.Quantity == 0m) { return 0m; } var marginReq = GetCurrentMarginRequirements(security); if (EnableIntradayMargins && security.Exchange.ExchangeOpen && !security.Exchange.ClosingSoon) { return marginReq.MaintenanceIntraday * parameters.AbsoluteQuantity; } // margin is per contract return marginReq.MaintenanceOvernight * parameters.AbsoluteQuantity; } /// <summary> /// The margin that must be held in order to increase the position by the provided quantity /// </summary> public override InitialMargin GetInitialMarginRequirement(InitialMarginParameters parameters) { var security = parameters.Security; var quantity = parameters.Quantity; if (security?.GetLastData() == null || quantity == 0m) return InitialMargin.Zero; var marginReq = GetCurrentMarginRequirements(security); if (EnableIntradayMargins && security.Exchange.ExchangeOpen && !security.Exchange.ClosingSoon) { return new InitialMargin(marginReq.InitialIntraday * quantity); } // margin is per contract return new InitialMargin(marginReq.InitialOvernight * quantity); } private MarginRequirementsEntry GetCurrentMarginRequirements(Security security) { if (security?.GetLastData() == null) return null; if (_marginRequirementsHistory == null) { _marginRequirementsHistory = LoadMarginRequirementsHistory(security.Symbol); _marginCurrentIndex = 0; } var date = security.GetLastData().Time.Date; while (_marginCurrentIndex + 1 < _marginRequirementsHistory.Length && _marginRequirementsHistory[_marginCurrentIndex + 1].Date <= date) { _marginCurrentIndex++; } return _marginRequirementsHistory[_marginCurrentIndex]; } /// <summary> /// Gets the sorted list of historical margin changes produced by reading in the margin requirements /// data found in /Data/symbol-margin/ /// </summary> /// <returns>Sorted list of historical margin changes</returns> private MarginRequirementsEntry[] LoadMarginRequirementsHistory(Symbol symbol) { var directory = Path.Combine(Globals.DataFolder, symbol.SecurityType.ToLower(), symbol.ID.Market.ToLowerInvariant(), "margins"); return FromCsvFile(Path.Combine(directory, symbol.ID.Symbol + ".csv")); } /// <summary> /// Reads margin requirements file and returns a sorted list of historical margin changes /// </summary> /// <param name="file">The csv file to be read</param> /// <returns>Sorted list of historical margin changes</returns> private MarginRequirementsEntry[] FromCsvFile(string file) { lock (DataFolderSymbolLock) { // skip the first header line, also skip #'s as these are comment lines var marginRequirementsEntries = _dataProvider.ReadLines(file) .Where(x => !x.StartsWith("#") && !string.IsNullOrWhiteSpace(x)) .Skip(1) .Select(FromCsvLine) .OrderBy(x => x.Date) .ToArray(); if(marginRequirementsEntries.Length == 0) { Log.Trace($"Unable to locate future margin requirements file. Defaulting to zero margin for this symbol. File: {file}"); return new[] { new MarginRequirementsEntry { Date = DateTime.MinValue } }; } return marginRequirementsEntries; } } /// <summary> /// Creates a new instance of <see cref="MarginRequirementsEntry"/> from the specified csv line /// </summary> /// <param name="csvLine">The csv line to be parsed</param> /// <returns>A new <see cref="MarginRequirementsEntry"/> for the specified csv line</returns> private MarginRequirementsEntry FromCsvLine(string csvLine) { var line = csvLine.Split(','); DateTime date; if (!DateTime.TryParseExact(line[0], DateFormat.EightCharacter, CultureInfo.InvariantCulture, DateTimeStyles.None, out date)) { Log.Trace($"Couldn't parse date/time while reading future margin requirement file. Line: {csvLine}"); } decimal initialOvernight; if (!decimal.TryParse(line[1], out initialOvernight)) { Log.Trace($"Couldn't parse Initial Overnight margin requirements while reading future margin requirement file. Line: {csvLine}"); } decimal maintenanceOvernight; if (!decimal.TryParse(line[2], out maintenanceOvernight)) { Log.Trace($"Couldn't parse Maintenance Overnight margin requirements while reading future margin requirement file. Line: {csvLine}"); } // default value, if present in file we try to parse decimal initialIntraday = initialOvernight * 0.4m; if (line.Length >= 4 && !decimal.TryParse(line[3], out initialIntraday)) { Log.Trace($"Couldn't parse Initial Intraday margin requirements while reading future margin requirement file. Line: {csvLine}"); } // default value, if present in file we try to parse decimal maintenanceIntraday = maintenanceOvernight * 0.4m; if (line.Length >= 5 && !decimal.TryParse(line[4], out maintenanceIntraday)) { Log.Trace($"Couldn't parse Maintenance Intraday margin requirements while reading future margin requirement file. Line: {csvLine}"); } return new MarginRequirementsEntry { Date = date, InitialOvernight = initialOvernight, MaintenanceOvernight = maintenanceOvernight, InitialIntraday = initialIntraday, MaintenanceIntraday = maintenanceIntraday }; } // Private POCO class for modeling margin requirements at given date class MarginRequirementsEntry { /// <summary> /// Date of margin requirements change /// </summary> public DateTime Date; /// <summary> /// Initial overnight margin for the contract effective from the date of change /// </summary> public decimal InitialOvernight; /// <summary> /// Maintenance overnight margin for the contract effective from the date of change /// </summary> public decimal MaintenanceOvernight; /// <summary> /// Initial intraday margin for the contract effective from the date of change /// </summary> public decimal InitialIntraday; /// <summary> /// Maintenance intraday margin for the contract effective from the date of change /// </summary> public decimal MaintenanceIntraday; } } }
using System; using System.Collections.Generic; using System.Text; using FlatRedBall.Math; #if FRB_MDX using Texture2D = FlatRedBall.Texture2D; #else//if FRB_XNA || ZUNE || SILVERLIGHT using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; #endif namespace FlatRedBall { public class SpriteList : PositionedObjectList<Sprite>, IEquatable<SpriteList> { #region Properties public float Alpha { set { for (int i = 0; i < this.Count; i++) { Sprite sprite = this[i]; sprite.Alpha = value; } } } public bool Visible { set { for (int i = 0; i < this.Count; i++) { Sprite sprite = this[i]; sprite.Visible = value; } } } #endregion #region Methods #region Constructors public SpriteList() : base() { } public SpriteList(int capacity) : base(capacity) { } #endregion #region Public Methods public SpriteList FindSpritesWithNameContaining(string stringToSearchFor) { SpriteList oneWayList = new SpriteList(); for (int i = 0; i < this.Count; i++) { Sprite sprite = this[i]; string name = sprite.Name; if (name.Contains(stringToSearchFor)) oneWayList.AddOneWay(sprite); } return oneWayList; } public Sprite FindSpriteWithTexture(Texture2D texture) { for (int i = 0; i < Count; i++) { Sprite sprite = this[i]; if (sprite.Texture == texture) { return sprite; } } return null; } #region XML Docs /// <summary> /// Returns a one-way SpriteList containing all Sprites in this SpriteList which reference the texture argument. /// </summary> /// <param name="texture">The texture to match against.</param> /// <returns>SpriteList containing Sprites with matching textures.</returns> #endregion public SpriteList FindSpritesWithTexture(Texture2D texture) { SpriteList spriteListToReturn = new SpriteList(); for (int i = 0; i < Count; i++) { Sprite sprite = this[i]; if (sprite.Texture == texture) { spriteListToReturn.AddOneWay(sprite); } } return spriteListToReturn; } public Sprite FindUnrotatedSpriteAt(float x, float y) { for (int i = 0; i < Count; i++) { if (x > (this[i]).Position.X - (this[i]).ScaleX && x < (this[i]).Position.X + (this[i]).ScaleX && y > (this[i]).Position.Y - (this[i]).ScaleY && y < (this[i]).Position.Y + (this[i]).ScaleY) { return this[i]; } } return null; } public int GetNumberOfSpritesInCameraView(int startIndex, int range) { int numberToReturn = 0; for (int i = startIndex; i < startIndex + range; i++) { Sprite sprite = this[i]; if (sprite.mInCameraView) numberToReturn++; } return numberToReturn; } public List<int> GetTextureBreaks() { List<int> textureBreaks = new List<int>(); if (Count == 0 || Count == 1) return textureBreaks; for (int i = 1; i < Count; i++) { Sprite sprite = this[i]; Sprite lastSprite = this[i - 1]; if (sprite.Texture != lastSprite.Texture) textureBreaks.Add(i); } return textureBreaks; } #region Sorting and ordering List<List<Sprite>> sSpriteListList = new List<List<Sprite>>(); public void SortTextureInsertion() { sSortTextureDictionary.Clear(); foreach (List<Sprite> spriteList in sSpriteListList) { spriteList.Clear(); } int textureID = 1; // start at 1, null is 0 for (int i = 0; i < this.mInternalList.Count; i++) { int idToAddAt = 0; if (mInternalList[i].Texture != null) { if (!sSortTextureDictionary.ContainsKey(mInternalList[i].Texture)) { sSortTextureDictionary.Add(mInternalList[i].Texture, textureID); idToAddAt = textureID; textureID++; } else { idToAddAt = sSortTextureDictionary[mInternalList[i].Texture]; } } while (sSpriteListList.Count <= idToAddAt) { sSpriteListList.Add(new List<Sprite>()); } sSpriteListList[idToAddAt].Add(mInternalList[i]); } // Now we can clear the mInternalList and add them according to what's in the list mInternalList.Clear(); foreach (List<Sprite> spriteList in sSpriteListList) { if ( spriteList.Count != 0 ) for ( int i = 0; i < spriteList.Count; i++ ) mInternalList.Add(spriteList[i]); //mInternalList.AddRange(spriteList); } } static Dictionary<Texture2D, int> sSortTextureDictionary = new Dictionary<Texture2D, int>(500); #region XML Docs /// <summary> /// Sorts a sub-array of the SpriteArray by their Texture. /// </summary> /// <param name="firstSprite">Index of the first Sprite, inclusive.</param> /// <param name="lastSpriteExclusive">Index of the last Sprite, exclusive.</param> #endregion public void SortTextureInsertion(int firstSprite, int lastSpriteExclusive) { int nextKey = 0; int i = 0; sSortTextureDictionary.Clear(); try { for (i = firstSprite; i < lastSpriteExclusive; i++) { Sprite sprite = this[i]; if (sprite.Texture != null) { if (sSortTextureDictionary.ContainsKey(sprite.Texture) == false) { sSortTextureDictionary.Add(sprite.Texture, nextKey); nextKey++; } } } } catch(ArgumentNullException e) { throw new NullReferenceException("Texture sorting failed due to Sprite " + i + " having a null Texture", e); } int numSorting = lastSpriteExclusive - firstSprite; // Biggest first if (numSorting == 1 || numSorting == 0) return; int whereSpriteBelongs; for (i = firstSprite + 1; i < lastSpriteExclusive; i++) { Sprite spriteBeforeI = this[i - 1]; Sprite spriteAtI = this[i]; Sprite spriteAt0 = this[firstSprite]; if (GetTextureIndex(spriteBeforeI) > GetTextureIndex(spriteAtI)) { if (i == 1) { base.Insert(0, spriteAtI); base.RemoveAtOneWay(i + 1); continue; } for (whereSpriteBelongs = i - 2; whereSpriteBelongs > firstSprite - 1; whereSpriteBelongs--) { Sprite spriteAtWhereSpriteBelongs = this[whereSpriteBelongs]; if (GetTextureIndex(spriteAtWhereSpriteBelongs) <= GetTextureIndex(spriteAtI)) { base.Insert(whereSpriteBelongs + 1, spriteAtI); base.RemoveAtOneWay(i + 1); break; } else if (whereSpriteBelongs == firstSprite && GetTextureIndex(spriteAt0) > GetTextureIndex(spriteAtI)) { base.Insert(firstSprite, spriteAtI); base.RemoveAtOneWay(i + 1); break; } } } } } int GetTextureIndex(Sprite sprite) { if (sprite.Texture == null) { return -1; } else { return sSortTextureDictionary[sprite.Texture]; } } public void SortTextureOnZBreaks() { List<int> zBreaks = GetZBreaks(); zBreaks.Insert(0, 0); zBreaks.Add(Count); for (int i = 0; i < zBreaks.Count - 1; i++) { SortTextureInsertion(zBreaks[i], zBreaks[i + 1]); } } #endregion public override string ToString() { return base.ToString(); } #endregion #endregion #region IEquatable<SpriteList> Members bool IEquatable<SpriteList>.Equals(SpriteList other) { return this == other; } #endregion } }
#if (UNITY_WINRT || UNITY_WP_8_1) && !UNITY_EDITOR && !UNITY_WP8 #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 PlayFab.Json.Utilities; namespace PlayFab.Json.Serialization { /// <summary> /// Maps a JSON property to a .NET member or constructor parameter. /// </summary> public class JsonProperty { internal Required? _required; internal bool _hasExplicitDefaultValue; internal object _defaultValue; private string _propertyName; private bool _skipPropertyNameEscape; // use to cache contract during deserialization internal JsonContract PropertyContract { get; set; } /// <summary> /// Gets or sets the name of the property. /// </summary> /// <value>The name of the property.</value> public string PropertyName { get { return _propertyName; } set { _propertyName = value; CalculateSkipPropertyNameEscape(); } } private void CalculateSkipPropertyNameEscape() { if (_propertyName == null) { _skipPropertyNameEscape = false; } else { _skipPropertyNameEscape = true; foreach (char c in _propertyName) { if (!char.IsLetterOrDigit(c) && c != '_' && c != '@') { _skipPropertyNameEscape = false; break; } } } } /// <summary> /// Gets or sets the type that declared this property. /// </summary> /// <value>The type that declared this property.</value> public Type DeclaringType { get; set; } /// <summary> /// Gets or sets the order of serialization and deserialization of a member. /// </summary> /// <value>The numeric order of serialization or deserialization.</value> public int? Order { get; set; } /// <summary> /// Gets or sets the name of the underlying member or parameter. /// </summary> /// <value>The name of the underlying member or parameter.</value> public string UnderlyingName { get; set; } /// <summary> /// Gets the <see cref="IValueProvider"/> that will get and set the <see cref="JsonProperty"/> during serialization. /// </summary> /// <value>The <see cref="IValueProvider"/> that will get and set the <see cref="JsonProperty"/> during serialization.</value> public IValueProvider ValueProvider { get; set; } /// <summary> /// Gets or sets the type of the property. /// </summary> /// <value>The type of the property.</value> public Type PropertyType { get; set; } /// <summary> /// Gets or sets the <see cref="JsonConverter" /> for the property. /// If set this converter takes presidence over the contract converter for the property type. /// </summary> /// <value>The converter.</value> public JsonConverter Converter { get; set; } /// <summary> /// Gets the member converter. /// </summary> /// <value>The member converter.</value> public JsonConverter MemberConverter { get; set; } /// <summary> /// Gets a value indicating whether this <see cref="JsonProperty"/> is ignored. /// </summary> /// <value><c>true</c> if ignored; otherwise, <c>false</c>.</value> public bool Ignored { get; set; } /// <summary> /// Gets a value indicating whether this <see cref="JsonProperty"/> is readable. /// </summary> /// <value><c>true</c> if readable; otherwise, <c>false</c>.</value> public bool Readable { get; set; } /// <summary> /// Gets a value indicating whether this <see cref="JsonProperty"/> is writable. /// </summary> /// <value><c>true</c> if writable; otherwise, <c>false</c>.</value> public bool Writable { get; set; } /// <summary> /// Gets a value indicating whether this <see cref="JsonProperty"/> has a member attribute. /// </summary> /// <value><c>true</c> if has a member attribute; otherwise, <c>false</c>.</value> public bool HasMemberAttribute { get; set; } /// <summary> /// Gets the default value. /// </summary> /// <value>The default value.</value> public object DefaultValue { get { return _defaultValue; } set { _hasExplicitDefaultValue = true; _defaultValue = value; } } internal object GetResolvedDefaultValue() { if (!_hasExplicitDefaultValue && PropertyType != null) return ReflectionUtils.GetDefaultValue(PropertyType); return _defaultValue; } /// <summary> /// Gets a value indicating whether this <see cref="JsonProperty"/> is required. /// </summary> /// <value>A value indicating whether this <see cref="JsonProperty"/> is required.</value> public Required Required { get { return _required ?? Required.Default; } set { _required = value; } } /// <summary> /// Gets a value indicating whether this property preserves object references. /// </summary> /// <value> /// <c>true</c> if this instance is reference; otherwise, <c>false</c>. /// </value> public bool? IsReference { get; set; } /// <summary> /// Gets the property null value handling. /// </summary> /// <value>The null value handling.</value> public NullValueHandling? NullValueHandling { get; set; } /// <summary> /// Gets the property default value handling. /// </summary> /// <value>The default value handling.</value> public DefaultValueHandling? DefaultValueHandling { get; set; } /// <summary> /// Gets the property reference loop handling. /// </summary> /// <value>The reference loop handling.</value> public ReferenceLoopHandling? ReferenceLoopHandling { get; set; } /// <summary> /// Gets the property object creation handling. /// </summary> /// <value>The object creation handling.</value> public ObjectCreationHandling? ObjectCreationHandling { get; set; } /// <summary> /// Gets or sets the type name handling. /// </summary> /// <value>The type name handling.</value> public TypeNameHandling? TypeNameHandling { get; set; } /// <summary> /// Gets or sets a predicate used to determine whether the property should be serialize. /// </summary> /// <value>A predicate used to determine whether the property should be serialize.</value> public Predicate<object> ShouldSerialize { get; set; } /// <summary> /// Gets or sets a predicate used to determine whether the property should be serialized. /// </summary> /// <value>A predicate used to determine whether the property should be serialized.</value> public Predicate<object> GetIsSpecified { get; set; } /// <summary> /// Gets or sets an action used to set whether the property has been deserialized. /// </summary> /// <value>An action used to set whether the property has been deserialized.</value> public Action<object, object> SetIsSpecified { get; set; } /// <summary> /// Returns a <see cref="String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="String"/> that represents this instance. /// </returns> public override string ToString() { return PropertyName; } /// <summary> /// Gets or sets the converter used when serializing the property's collection items. /// </summary> /// <value>The collection's items converter.</value> public JsonConverter ItemConverter { get; set; } /// <summary> /// Gets or sets whether this property's collection items are serialized as a reference. /// </summary> /// <value>Whether this property's collection items are serialized as a reference.</value> public bool? ItemIsReference { get; set; } /// <summary> /// Gets or sets the the type name handling used when serializing the property's collection items. /// </summary> /// <value>The collection's items type name handling.</value> public TypeNameHandling? ItemTypeNameHandling { get; set; } /// <summary> /// Gets or sets the the reference loop handling used when serializing the property's collection items. /// </summary> /// <value>The collection's items reference loop handling.</value> public ReferenceLoopHandling? ItemReferenceLoopHandling { get; set; } internal void WritePropertyName(JsonWriter writer) { if (_skipPropertyNameEscape) writer.WritePropertyName(PropertyName, false); else writer.WritePropertyName(PropertyName); } } } #endif
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using Xunit; namespace System.Linq.Tests.LegacyTests { public class ElementAtOrDefaultTests { public class ElementAtOrDefault013 { private static int ElementAt001() { var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 } where x > Int32.MinValue select x; var rst1 = q.ElementAt(3); var rst2 = q.ElementAt(3); return ((rst1 == rst2) ? 0 : 1); } private static int ElementAt002() { var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", String.Empty } where !String.IsNullOrEmpty(x) select x; var rst1 = q.ElementAt(4); var rst2 = q.ElementAt(4); return ((rst1 == rst2) ? 0 : 1); } public static int Main() { int ret = RunTest(ElementAt001) + RunTest(ElementAt002); if (0 != ret) Console.Write(s_errorMessage); return ret; } private static string s_errorMessage = String.Empty; private delegate int D(); private static int RunTest(D m) { int n = m(); if (0 != n) s_errorMessage += m.ToString() + " - FAILED!\r\n"; return n; } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class ElementAtOrDefault1 { // source is of type IList, index < 0; public static int Test1() { int?[] source = { 9, 8 }; int index = -1; int? expected = null; IList<int?> list = source as IList<int?>; if (list == null) return 1; var actual = source.ElementAtOrDefault(index); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test1(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class ElementAtOrDefault10 { // source is NOT of type IList, source has one element, index is zero public static int Test10() { IEnumerable<int> source = Functions.NumList(9, 1); int index = 0; int expected = 9; IList<int> list = source as IList<int>; if (list != null) return 1; var actual = source.ElementAtOrDefault(index); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test10(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class ElementAtOrDefault11 { // source is NOT of type IList, source has > 1 element, index is (# of elements - 1) public static int Test11() { IEnumerable<int> source = Functions.NumList(9, 10); int index = 9; int expected = 18; IList<int> list = source as IList<int>; if (list != null) return 1; var actual = source.ElementAtOrDefault(index); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test11(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class ElementAtOrDefault12 { // source is NOT of type IList, source has > 1 element, index is somewhere in the middle public static int Test12() { IEnumerable<int> source = Functions.NumList(-4, 10); int index = 3; int expected = -1; IList<int> list = source as IList<int>; if (list != null) return 1; var actual = source.ElementAtOrDefault(index); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test12(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class ElementAtOrDefault2 { // source is of type IList, index = Number of elements in source; public static int Test2() { int[] source = { 1, 2, 3, 4 }; int index = 4; int expected = default(int); IList<int> list = source as IList<int>; if (list == null) return 1; var actual = source.ElementAtOrDefault(index); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test2(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class ElementAtOrDefault3 { // source is of type IList, source is empty, index is zero public static int Test3() { int[] source = { }; int index = 0; int expected = default(int); IList<int> list = source as IList<int>; if (list == null) return 1; var actual = source.ElementAtOrDefault(index); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test3(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class ElementAtOrDefault4 { // source is of type IList, source has one element, index is zero public static int Test4() { int[] source = { -4 }; int index = 0; int expected = -4; IList<int> list = source as IList<int>; if (list == null) return 1; var actual = source.ElementAtOrDefault(index); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test4(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class ElementAtOrDefault5 { // source is of type IList, source has > 1 element, index is (# of elements - 1) public static int Test5() { int[] source = { 9, 8, 0, -5, 10 }; int index = 4; int expected = 10; IList<int> list = source as IList<int>; if (list == null) return 1; var actual = source.ElementAtOrDefault(index); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test5(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class ElementAtOrDefault6 { // source is of type IList, source has > 1 element, index is somewhere in the middle public static int Test6() { int?[] source = { 9, 8, null, -5, 10 }; int index = 2; int? expected = null; IList<int?> list = source as IList<int?>; if (list == null) return 1; var actual = source.ElementAtOrDefault(index); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test6(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class ElementAtOrDefault7 { // source is NOT of type IList, index < 0; public static int Test7() { IEnumerable<int> source = Functions.NumList(-4, 5); int index = -1; int expected = default(int); IList<int> list = source as IList<int>; if (list != null) return 1; var actual = source.ElementAtOrDefault(index); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test7(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class ElementAtOrDefault8 { // source is NOT of type IList, index = Number of elements in source; public static int Test8() { IEnumerable<int> source = Functions.NumList(5, 5); int index = 5; int expected = default(int); IList<int> list = source as IList<int>; if (list != null) return 1; var actual = source.ElementAtOrDefault(index); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test8(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } public class ElementAtOrDefault9 { // source is NOT of type IList, source is empty, index is zero public static int Test9() { IEnumerable<int> source = Functions.NumList(0, 0); int index = 0; int expected = default(int); IList<int> list = source as IList<int>; if (list != null) return 1; var actual = source.ElementAtOrDefault(index); return ((expected == actual) ? 0 : 1); } public static int Main() { return Test9(); } [Fact] public void Test() { Assert.Equal(0, Main()); } } } }
/* * Copyright 1999-2012 Alibaba Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Collections.Generic; using Tup.Cobar4Net.Parser.Ast.Expression; using Tup.Cobar4Net.Parser.Ast.Fragment; using Tup.Cobar4Net.Parser.Ast.Fragment.Tableref; using Tup.Cobar4Net.Parser.Ast.Stmt.Dml; using Tup.Cobar4Net.Parser.Recognizer.Mysql.Lexer; using Tup.Cobar4Net.Parser.Util; namespace Tup.Cobar4Net.Parser.Recognizer.Mysql.Syntax { /// <author> /// <a href="mailto:shuo.qius@alibaba-inc.com">QIU Shuo</a> /// </author> public class MySqlDmlSelectParser : MySqlDmlParser { private static readonly IDictionary<string, SpecialIdentifier> specialIdentifiers = new Dictionary<string, SpecialIdentifier>(); static MySqlDmlSelectParser() { specialIdentifiers["SQL_BUFFER_RESULT"] = SpecialIdentifier.SqlBufferResult; specialIdentifiers["SQL_CACHE"] = SpecialIdentifier.SqlCache; specialIdentifiers["SQL_NO_CACHE"] = SpecialIdentifier.SqlNoCache; } public MySqlDmlSelectParser(MySqlLexer lexer, MySqlExprParser exprParser) : base(lexer, exprParser) { this.exprParser.SetSelectParser(this); } /// <exception cref="System.SqlSyntaxErrorException" /> private DmlSelectStatement.SelectOption SelectOption() { for (var option = new DmlSelectStatement.SelectOption();; lexer.NextToken()) { switch (lexer.Token()) { case MySqlToken.KwAll: { option.resultDup = SelectDuplicationStrategy.All; goto outer_break; } case MySqlToken.KwDistinct: { option.resultDup = SelectDuplicationStrategy.Distinct; goto outer_break; } case MySqlToken.KwDistinctrow: { option.resultDup = SelectDuplicationStrategy.Distinctrow; goto outer_break; } case MySqlToken.KwHighPriority: { option.highPriority = true; goto outer_break; } case MySqlToken.KwStraightJoin: { option.straightJoin = true; goto outer_break; } case MySqlToken.KwSqlSmallResult: { option.resultSize = SelectSmallOrBigResult.SqlSmallResult; goto outer_break; } case MySqlToken.KwSqlBigResult: { option.resultSize = SelectSmallOrBigResult.SqlBigResult; goto outer_break; } case MySqlToken.KwSqlCalcFoundRows: { option.sqlCalcFoundRows = true; goto outer_break; } case MySqlToken.Identifier: { var optionStringUp = lexer.GetStringValueUppercase(); var specialId = specialIdentifiers.GetValue(optionStringUp); if (specialId != SpecialIdentifier.None) { switch (specialId) { case SpecialIdentifier.SqlBufferResult: { if (option.sqlBufferResult) { return option; } option.sqlBufferResult = true; goto outer_break; } case SpecialIdentifier.SqlCache: { if (option.SelectQueryCache != SelectQueryCacheStrategy.Undef) { return option; } option.SelectQueryCache = SelectQueryCacheStrategy.SqlCache; goto outer_break; } case SpecialIdentifier.SqlNoCache: { if (option.SelectQueryCache != SelectQueryCacheStrategy.Undef) { return option; } option.SelectQueryCache = SelectQueryCacheStrategy.SqlNoCache; goto outer_break; } } } goto default; } default: { return option; } } outer_break: ; } } /// <exception cref="System.SqlSyntaxErrorException" /> private IList<Pair<IExpression, string>> SelectExprList() { var expr = exprParser.Expression(); var alias = As(); IList<Pair<IExpression, string>> list; if (lexer.Token() == MySqlToken.PuncComma) { list = new List<Pair<IExpression, string>>(); list.Add(new Pair<IExpression, string>(expr, alias)); } else { list = new List<Pair<IExpression, string>>(1); list.Add(new Pair<IExpression, string>(expr, alias)); return list; } for (; lexer.Token() == MySqlToken.PuncComma; list.Add(new Pair<IExpression, string>(expr, alias))) { lexer.NextToken(); expr = exprParser.Expression(); alias = As(); } return list; } /// <exception cref="System.SqlSyntaxErrorException" /> public override DmlSelectStatement Select() { Match(MySqlToken.KwSelect); var option = SelectOption(); var exprList = SelectExprList(); TableReferences tables = null; IExpression where = null; GroupBy group = null; IExpression having = null; OrderBy order = null; Limit limit = null; var dual = false; if (lexer.Token() == MySqlToken.KwFrom) { if (lexer.NextToken() == MySqlToken.KwDual) { lexer.NextToken(); dual = true; IList<TableReference> trs = new List<TableReference>(1); trs.Add(new Dual()); tables = new TableReferences(trs); } else { tables = TableRefs(); } } if (lexer.Token() == MySqlToken.KwWhere) { lexer.NextToken(); where = exprParser.Expression(); } if (!dual) { group = GroupBy(); if (lexer.Token() == MySqlToken.KwHaving) { lexer.NextToken(); having = exprParser.Expression(); } order = OrderBy(); } limit = Limit(); if (!dual) { switch (lexer.Token()) { case MySqlToken.KwFor: { lexer.NextToken(); Match(MySqlToken.KwUpdate); option.lockMode = LockMode.ForUpdate; break; } case MySqlToken.KwLock: { lexer.NextToken(); Match(MySqlToken.KwIn); MatchIdentifier("SHARE"); MatchIdentifier("MODE"); option.lockMode = LockMode.LockInShareMode; break; } } } return new DmlSelectStatement(option, exprList, tables, where, group, having, order, limit); } /// <summary> /// first token is either /// <see cref="MySqlToken.KwSelect" /> /// or /// <see cref="MySqlToken.PuncLeftParen" /> /// which has been scanned but not yet /// consumed /// </summary> /// <returns> /// <see cref="Tup.Cobar4Net.Parser.Ast.Stmt.Dml.DmlSelectStatement" /> /// or /// <see cref="Tup.Cobar4Net.Parser.Ast.Stmt.Dml.DmlSelectUnionStatement" /> /// </returns> /// <exception cref="System.SqlSyntaxErrorException" /> public virtual DmlQueryStatement SelectUnion() { var select = SelectPrimary(); var query = BuildUnionSelect(select); return query; } private enum SpecialIdentifier { None = 0, SqlBufferResult, SqlCache, SqlNoCache } } }
// // Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !NETSTANDARD namespace NLog.LayoutRenderers { using System; using System.Collections.Generic; using System.Globalization; using System.Text; using Microsoft.Win32; using NLog; using Common; using Internal; using Config; using System.ComponentModel; using Layouts; /// <summary> /// A value from the Registry. /// </summary> [LayoutRenderer("registry")] public class RegistryLayoutRenderer : LayoutRenderer { /// <summary> /// Create new renderer /// </summary> public RegistryLayoutRenderer() { RequireEscapingSlashesInDefaultValue = true; } /// <summary> /// Gets or sets the registry value name. /// </summary> /// <docgen category='Registry Options' order='10' /> public Layout Value { get; set; } /// <summary> /// Gets or sets the value to be output when the specified registry key or value is not found. /// </summary> /// <docgen category='Registry Options' order='10' /> public Layout DefaultValue { get; set; } /// <summary> /// Require escaping backward slashes in <see cref="DefaultValue"/>. Need to be backwardscompatible. /// /// When true: /// /// `\` in value should be configured as `\\` /// `\\` in value should be configured as `\\\\`. /// </summary> /// <remarks>Default value wasn't a Layout before and needed an escape of the slash</remarks> [DefaultValue(true)] public bool RequireEscapingSlashesInDefaultValue { get; set; } #if !NET3_5 /// <summary> /// Gets or sets the registry view (see: https://msdn.microsoft.com/de-de/library/microsoft.win32.registryview.aspx). /// Allowed values: Registry32, Registry64, Default /// </summary> [DefaultValue("Default")] public RegistryView View { get; set; } #endif /// <summary> /// Gets or sets the registry key. /// </summary> /// <example> /// HKCU\Software\NLogTest /// </example> /// <remarks> /// Possible keys: /// <ul> ///<li>HKEY_LOCAL_MACHINE</li> ///<li>HKLM</li> ///<li>HKEY_CURRENT_USER</li> ///<li>HKCU</li> ///<li>HKEY_CLASSES_ROOT</li> ///<li>HKEY_USERS</li> ///<li>HKEY_CURRENT_CONFIG</li> ///<li>HKEY_DYN_DATA</li> ///<li>HKEY_PERFORMANCE_DATA</li> /// </ul> /// </remarks> /// <docgen category='Registry Options' order='10' /> [RequiredParameter] public Layout Key { get; set; } /// <summary> /// Reads the specified registry key and value and appends it to /// the passed <see cref="StringBuilder"/>. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event. Ignored.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { object registryValue = null; // Value = null is necessary for querying "unnamed values" string renderedValue = Value != null ? Value.Render(logEvent) : null; var parseResult = ParseKey(Key.Render(logEvent)); try { #if !NET3_5 using (RegistryKey rootKey = RegistryKey.OpenBaseKey(parseResult.Hive, View)) #else var rootKey = MapHiveToKey(parseResult.Hive); #endif { if (parseResult.HasSubKey) { using (RegistryKey registryKey = rootKey.OpenSubKey(parseResult.SubKey)) { if (registryKey != null) registryValue = registryKey.GetValue(renderedValue); } } else { registryValue = rootKey.GetValue(renderedValue); } } } catch (Exception ex) { InternalLogger.Error("Error when writing to registry"); if (ex.MustBeRethrown()) { throw; } } string value = null; if (registryValue != null) // valid value returned from registry will never be null { value = Convert.ToString(registryValue, CultureInfo.InvariantCulture); } else if (DefaultValue != null) { value = DefaultValue.Render(logEvent); if (RequireEscapingSlashesInDefaultValue) { //remove escape slash value = value.Replace("\\\\", "\\"); } } builder.Append(value); } private class ParseResult { public string SubKey { get; set; } public RegistryHive Hive { get; set; } /// <summary> /// Has <see cref="SubKey"/>? /// </summary> public bool HasSubKey => !string.IsNullOrEmpty(SubKey); } /// <summary> /// Parse key to <see cref="RegistryHive"/> and subkey. /// </summary> /// <param name="key">full registry key name</param> /// <returns>Result of parsing, never <c>null</c>.</returns> private static ParseResult ParseKey(string key) { string hiveName; int pos = key.IndexOfAny(new char[] { '\\', '/' }); string subkey = null; if (pos >= 0) { hiveName = key.Substring(0, pos); //normalize slashes subkey = key.Substring(pos + 1).Replace('/', '\\'); //remove starting slashes subkey = subkey.TrimStart('\\'); //replace double slashes from pre-layout times subkey = subkey.Replace("\\\\", "\\"); } else { hiveName = key; } var hive = ParseHiveName(hiveName); return new ParseResult { SubKey = subkey, Hive = hive, }; } /// <summary> /// Aliases for the hives. See https://msdn.microsoft.com/en-us/library/ctb3kd86(v=vs.110).aspx /// </summary> private static readonly Dictionary<string, RegistryHive> HiveAliases = new Dictionary<string, RegistryHive>(StringComparer.InvariantCultureIgnoreCase) { {"HKEY_LOCAL_MACHINE", RegistryHive.LocalMachine}, {"HKLM", RegistryHive.LocalMachine}, {"HKEY_CURRENT_USER", RegistryHive.CurrentUser}, {"HKCU", RegistryHive.CurrentUser}, {"HKEY_CLASSES_ROOT", RegistryHive.ClassesRoot}, {"HKEY_USERS", RegistryHive.Users}, {"HKEY_CURRENT_CONFIG", RegistryHive.CurrentConfig}, {"HKEY_DYN_DATA", RegistryHive.DynData}, {"HKEY_PERFORMANCE_DATA", RegistryHive.PerformanceData}, }; private static RegistryHive ParseHiveName(string hiveName) { RegistryHive hive; if (HiveAliases.TryGetValue(hiveName, out hive)) { return hive; } //ArgumentException is consistent throw new ArgumentException($"Key name is not supported. Root hive '{hiveName}' not recognized."); } #if NET3_5 private static RegistryKey MapHiveToKey(RegistryHive hive) { switch (hive) { case RegistryHive.LocalMachine: return Registry.LocalMachine; case RegistryHive.CurrentUser: return Registry.CurrentUser; default: throw new ArgumentException("Only RegistryHive.LocalMachine and RegistryHive.CurrentUser are supported.", "hive"); } } #endif } } #endif
using System; using FluentAssertions; using NUnit.Framework; namespace CK.Text.Tests { [TestFixture] public class StringMatcherTests { [Test] public void simple_char_matching() { string s = "ABCD"; var m = new StringMatcher( s ); m.MatchChar( 'a' ).Should().BeFalse(); m.MatchChar( 'A' ).Should().BeTrue(); m.StartIndex.Should().Be( 1 ); m.MatchChar( 'A' ).Should().BeFalse(); m.MatchChar( 'B' ).Should().BeTrue(); m.MatchChar( 'C' ).Should().BeTrue(); m.IsEnd.Should().BeFalse(); m.MatchChar( 'D' ).Should().BeTrue(); m.MatchChar( 'D' ).Should().BeFalse(); m.IsEnd.Should().BeTrue(); } [TestCase( "abcdef", 0xABCDEFUL )] [TestCase( "12abcdef", 0x12ABCDEFUL )] [TestCase( "12abcdef12abcdef", 0x12abcdef12abcdefUL )] [TestCase( "00000000FFFFFFFF", 0xFFFFFFFFUL )] [TestCase( "FFFFFFFFFFFFFFFF", 0xFFFFFFFFFFFFFFFFUL )] public void matching_hex_number( string s, ulong v ) { var m = new StringMatcher( s ); m.TryMatchHexNumber( out ulong value ).Should().BeTrue(); value.Should().Be( v ); m.IsEnd.Should().BeTrue(); } [TestCase( "0|", 0x0UL, '|' )] [TestCase( "AG", 0xAUL, 'G' )] [TestCase( "cd", 0xCUL, 'd' )] public void matching_hex_number_one_digit( string s, ulong v, char end ) { var m = new StringMatcher( s ); m.TryMatchHexNumber( out ulong value, 1, 1 ).Should().BeTrue(); value.Should().Be( v ); m.IsEnd.Should().BeFalse(); m.Head.Should().Be( end ); } [TestCase( "not a hex." )] [TestCase( "FA12 but we want 5 digits min." )] public void matching_hex_number_failures( string s ) { var m = new StringMatcher( s ); m.TryMatchHexNumber( out ulong value, 5, 5 ).Should().BeFalse(); m.IsEnd.Should().BeFalse(); m.StartIndex.Should().Be( 0 ); } [Test] public void matching_texts_and_whitespaces() { string s = " AB \t\r C"; var m = new StringMatcher( s ); Action a; m.MatchText( "A" ).Should().BeFalse(); m.StartIndex.Should().Be( 0 ); m.MatchWhiteSpaces().Should().BeTrue(); m.StartIndex.Should().Be( 1 ); m.MatchText( "A" ).Should().BeTrue(); m.MatchText( "B" ).Should().BeTrue(); m.StartIndex.Should().Be( 3 ); m.MatchWhiteSpaces( 6 ).Should().BeFalse(); m.MatchWhiteSpaces( 5 ).Should().BeTrue(); m.StartIndex.Should().Be( 8 ); m.MatchWhiteSpaces().Should().BeFalse(); m.StartIndex.Should().Be( 8 ); m.MatchText( "c" ).Should().BeTrue(); m.StartIndex.Should().Be( s.Length ); m.IsEnd.Should().BeTrue(); a = () => m.MatchText( "c" ); a.Should().NotThrow(); a = () => m.MatchWhiteSpaces(); a.Should().NotThrow(); m.MatchText( "A" ).Should().BeFalse(); m.MatchWhiteSpaces().Should().BeFalse(); } [Test] public void matching_integers() { var m = new StringMatcher( "X3712Y" ); m.MatchChar( 'X' ).Should().BeTrue(); int i; m.MatchInt32( out i ).Should().BeTrue(); i.Should().Be( 3712 ); m.MatchChar( 'Y' ).Should().BeTrue(); } [Test] public void matching_integers_with_min_max_values() { var m = new StringMatcher( "3712 -435 56" ); int i; m.MatchInt32( out i, -500, -400 ).Should().BeFalse(); m.MatchInt32( out i, 0, 3712 ).Should().BeTrue(); i.Should().Be( 3712 ); m.MatchWhiteSpaces().Should().BeTrue(); m.MatchInt32( out i, 0 ).Should().BeFalse(); m.MatchInt32( out i, -500, -400 ).Should().BeTrue(); i.Should().Be( -435 ); m.MatchWhiteSpaces().Should().BeTrue(); m.MatchInt32( out i, 1000, 2000 ).Should().BeFalse(); m.MatchInt32( out i, 56, 56 ).Should().BeTrue(); i.Should().Be( 56 ); m.IsEnd.Should().BeTrue(); } public void match_methods_must_set_an_error() { var m = new StringMatcher( "A" ); CheckMatchError( m, () => m.MatchChar( 'B' ) ); int i; CheckMatchError( m, () => m.MatchInt32( out i ) ); CheckMatchError( m, () => m.MatchText( "PP" ) ); CheckMatchError( m, () => m.MatchText( "B" ) ); CheckMatchError( m, () => m.MatchWhiteSpaces() ); } private static void CheckMatchError( StringMatcher m, Func<bool> fail ) { int idx = m.StartIndex; int len = m.Length; fail().Should().BeFalse(); m.IsError.Should().BeTrue(); m.ErrorMessage.Should().NotBeNullOrEmpty(); m.StartIndex.Should().Be( idx ); m.Length.Should().Be( len ); m.ClearError(); } [Test] public void ToString_constains_the_text_and_the_error() { var m = new StringMatcher( "The Text" ); m.SetError( "Plouf..." ); m.ToString().Contains( "The Text" ); m.ToString().Contains( "Plouf..." ); } [TestCase( @"null, true", null, ", true" )] [TestCase( @"""""X", "", "X" )] [TestCase( @"""a""X", "a", "X" )] [TestCase( @"""\\""X", @"\", "X" )] [TestCase( @"""A\\B""X", @"A\B", "X" )] [TestCase( @"""A\\B\r""X", "A\\B\r", "X" )] [TestCase( @"""A\\B\r\""""X", "A\\B\r\"", "X" )] [TestCase( @"""\u8976""X", "\u8976", "X" )] [TestCase( @"""\uABCD\u07FC""X", "\uABCD\u07FC", "X" )] [TestCase( @"""\uabCd\u07fC""X", "\uABCD\u07FC", "X" )] public void matching_JSONQuotedString( string s, string parsed, string textAfter ) { var m = new StringMatcher( s ); string result; m.TryMatchJSONQuotedString( out result, true ).Should().BeTrue(); result.Should().Be( parsed ); m.TryMatchText( textAfter ).Should().BeTrue(); m = new StringMatcher( s ); m.TryMatchJSONQuotedString( true ).Should().BeTrue(); m.TryMatchText( textAfter ).Should().BeTrue(); } [Test] public void simple_json_test() { string s = @" { ""p1"": ""n"", ""p2"" : { ""p3"": [ ""p4"": { ""p5"" : 0.989, ""p6"": [], ""p7"": {} } ] } } "; var m = new StringMatcher( s ); string pName; m.MatchWhiteSpaces().Should().BeTrue(); m.MatchChar( '{' ).Should().BeTrue(); m.MatchWhiteSpaces().Should().BeTrue(); m.TryMatchJSONQuotedString( out pName ).Should().BeTrue(); pName.Should().Be( "p1" ); m.MatchWhiteSpaces( 0 ).Should().BeTrue(); m.MatchChar( ':' ).Should().BeTrue(); m.MatchWhiteSpaces().Should().BeTrue(); m.TryMatchJSONQuotedString( out pName ).Should().BeTrue(); pName.Should().Be( "n" ); m.MatchWhiteSpaces( 0 ).Should().BeTrue(); m.MatchChar( ',' ).Should().BeTrue(); m.MatchWhiteSpaces().Should().BeTrue(); m.TryMatchJSONQuotedString( out pName ).Should().BeTrue(); pName.Should().Be( "p2" ); m.MatchWhiteSpaces( 2 ).Should().BeTrue(); m.MatchChar( ':' ).Should().BeTrue(); m.MatchWhiteSpaces().Should().BeTrue(); m.MatchChar( '{' ).Should().BeTrue(); m.MatchWhiteSpaces().Should().BeTrue(); m.TryMatchJSONQuotedString( out pName ).Should().BeTrue(); pName.Should().Be( "p3" ); m.MatchWhiteSpaces( 0 ).Should().BeTrue(); m.MatchChar( ':' ).Should().BeTrue(); m.MatchWhiteSpaces().Should().BeTrue(); m.MatchChar( '[' ).Should().BeTrue(); m.MatchWhiteSpaces().Should().BeTrue(); m.TryMatchJSONQuotedString( out pName ).Should().BeTrue(); pName.Should().Be( "p4" ); m.MatchWhiteSpaces( 0 ).Should().BeTrue(); m.MatchChar( ':' ).Should().BeTrue(); m.MatchWhiteSpaces().Should().BeTrue(); m.MatchChar( '{' ).Should().BeTrue(); m.MatchWhiteSpaces().Should().BeTrue(); m.TryMatchJSONQuotedString().Should().BeTrue(); m.MatchWhiteSpaces( 0 ).Should().BeTrue(); m.MatchChar( ':' ).Should().BeTrue(); m.MatchWhiteSpaces().Should().BeTrue(); m.TryMatchDoubleValue().Should().BeTrue(); m.MatchWhiteSpaces( 0 ).Should().BeTrue(); m.MatchChar( ',' ).Should().BeTrue(); m.MatchWhiteSpaces().Should().BeTrue(); m.TryMatchJSONQuotedString( out pName ).Should().BeTrue(); pName.Should().Be( "p6" ); m.MatchWhiteSpaces( 0 ).Should().BeTrue(); m.MatchChar( ':' ).Should().BeTrue(); m.MatchWhiteSpaces().Should().BeTrue(); m.MatchChar( '[' ).Should().BeTrue(); m.MatchWhiteSpaces( 0 ).Should().BeTrue(); m.MatchChar( ']' ).Should().BeTrue(); m.MatchWhiteSpaces( 0 ).Should().BeTrue(); m.MatchChar( ',' ).Should().BeTrue(); m.MatchWhiteSpaces().Should().BeTrue(); m.TryMatchJSONQuotedString().Should().BeTrue(); m.MatchWhiteSpaces( 0 ).Should().BeTrue(); m.MatchChar( ':' ).Should().BeTrue(); m.MatchWhiteSpaces().Should().BeTrue(); m.MatchChar( '{' ).Should().BeTrue(); m.MatchWhiteSpaces( 0 ).Should().BeTrue(); m.MatchChar( '}' ).Should().BeTrue(); m.MatchWhiteSpaces().Should().BeTrue(); m.MatchChar( '}' ).Should().BeTrue(); m.MatchWhiteSpaces().Should().BeTrue(); m.MatchChar( ']' ).Should().BeTrue(); m.MatchWhiteSpaces().Should().BeTrue(); m.MatchChar( '}' ).Should().BeTrue(); m.MatchWhiteSpaces().Should().BeTrue(); m.MatchChar( '}' ).Should().BeTrue(); m.MatchWhiteSpaces( 2 ).Should().BeTrue(); m.IsEnd.Should().BeTrue(); } [TestCase( "0", 0 )] [TestCase( "9876978", 9876978 )] [TestCase( "-9876978", -9876978 )] [TestCase( "0.0", 0 )] [TestCase( "0.00", 0 )] [TestCase( "0.34", 0.34 )] [TestCase( "4e5", 4e5 )] [TestCase( "4E5", 4E5 )] [TestCase( "29380.34e98", 29380.34e98 )] [TestCase( "29380.34E98", 29380.34E98 )] [TestCase( "-80.34e-98", -80.34e-98 )] [TestCase( "-80.34E-98", -80.34E-98 )] public void matching_double_values( string s, double d ) { StringMatcher m = new StringMatcher( "P" + s + "S" ); double parsed; m.MatchChar( 'P' ).Should().BeTrue(); int idx = m.StartIndex; m.TryMatchDoubleValue().Should().BeTrue(); m.UncheckedMove( idx - m.StartIndex ); m.TryMatchDoubleValue( out parsed ).Should().BeTrue(); parsed.Should().BeApproximately( d, 1f ); m.MatchChar( 'S' ).Should().BeTrue(); m.IsEnd.Should().BeTrue(); } [TestCase( "N" )] [TestCase( "D" )] [TestCase( "B" )] [TestCase( "P" )] [TestCase( "X" )] public void matching_the_5_forms_of_guid( string form ) { var id = Guid.NewGuid(); string sId = id.ToString( form ); { string s = sId; var m = new StringMatcher( s ); Guid readId; m.TryMatchGuid( out readId ).Should().BeTrue(); readId.Should().Be( id ); } { string s = "S" + sId; var m = new StringMatcher( s ); Guid readId; m.TryMatchChar( 'S' ).Should().BeTrue(); m.TryMatchGuid( out readId ).Should().BeTrue(); readId.Should().Be( id ); } { string s = "S" + sId + "T"; var m = new StringMatcher( s ); Guid readId; m.MatchChar( 'S' ).Should().BeTrue(); m.TryMatchGuid( out readId ).Should().BeTrue(); readId.Should().Be( id ); m.MatchChar( 'T' ).Should().BeTrue(); } sId = sId.Remove( sId.Length - 1 ); { string s = sId; var m = new StringMatcher( s ); Guid readId; m.TryMatchGuid( out readId ).Should().BeFalse(); m.StartIndex.Should().Be( 0 ); } sId = id.ToString().Insert( 3, "K" ).Remove( 4 ); { string s = sId; var m = new StringMatcher( s ); Guid readId; m.TryMatchGuid( out readId ).Should().BeFalse(); m.StartIndex.Should().Be( 0 ); } } } }
//------------------------------------------------------------------------------ // <copyright file="MD5HashStream.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation // </copyright> //------------------------------------------------------------------------------ namespace Microsoft.WindowsAzure.Storage.DataMovement { using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; /// <summary> /// Class to make thread safe stream access and calculate MD5 hash. /// </summary> internal class MD5HashStream : IDisposable { /// <summary> /// Stream object. /// </summary> private Stream stream; /// <summary> /// Semaphore object. In our case, we can only have one operation at the same time. /// </summary> private SemaphoreSlim semaphore; /// <summary> /// In restart mode, we start a separate thread to calculate MD5hash of transferred part. /// This variable indicates whether finished to calculate this part of MD5hash. /// </summary> private volatile bool finishedSeparateMd5Calculator = false; /// <summary> /// Indicates whether succeeded in calculating MD5hash of the transferred bytes. /// </summary> private bool succeededSeparateMd5Calculator = false; /// <summary> /// Running md5 hash of the blob being downloaded. /// </summary> private MD5CryptoServiceProvider md5hash; /// <summary> /// Offset of the transferred bytes. We should calculate MD5hash on all bytes before this offset. /// </summary> private long md5hashOffset; /// <summary> /// Initializes a new instance of the <see cref="MD5HashStream"/> class. /// </summary> /// <param name="stream">Stream object.</param> /// <param name="lastTransferOffset">Offset of the transferred bytes.</param> /// <param name="md5hashCheck">Whether need to calculate MD5Hash.</param> public MD5HashStream( Stream stream, long lastTransferOffset, bool md5hashCheck) { this.stream = stream; this.md5hashOffset = lastTransferOffset; if ((0 == this.md5hashOffset) || (!md5hashCheck)) { this.finishedSeparateMd5Calculator = true; this.succeededSeparateMd5Calculator = true; } else { this.semaphore = new SemaphoreSlim(1, 1); } if (md5hashCheck) { this.md5hash = new MD5CryptoServiceProvider(); } if ((!this.finishedSeparateMd5Calculator) && (!this.stream.CanRead)) { throw new NotSupportedException(string.Format( CultureInfo.CurrentCulture, Resources.StreamMustSupportReadException, "Stream")); } if (!this.stream.CanSeek) { throw new NotSupportedException(string.Format( CultureInfo.CurrentCulture, Resources.StreamMustSupportSeekException, "Stream")); } } /// <summary> /// Gets a value indicating whether need to calculate MD5 hash. /// </summary> public bool CheckMd5Hash { get { return null != this.md5hash; } } /// <summary> /// Gets MD5 hash bytes. /// </summary> public byte[] Hash { get { return null == this.md5hash ? null : this.md5hash.Hash; } } /// <summary> /// Gets a value indicating whether already finished to calculate MD5 hash of transferred bytes. /// </summary> public bool FinishedSeparateMd5Calculator { get { return this.finishedSeparateMd5Calculator; } } /// <summary> /// Gets a value indicating whether already succeeded in calculating MD5 hash of transferred bytes. /// </summary> public bool SucceededSeparateMd5Calculator { get { this.WaitMD5CalculationToFinish(); return this.succeededSeparateMd5Calculator; } } /// <summary> /// Calculate MD5 hash of transferred bytes. /// </summary> /// <param name="memoryManager">Reference to MemoryManager object to require buffer from.</param> /// <param name="checkCancellation">Action to check whether to cancel this calculation.</param> public void CalculateMd5(MemoryManager memoryManager, Action checkCancellation) { if (null == this.md5hash) { return; } byte[] buffer = null; try { buffer = Utils.RequireBuffer(memoryManager, checkCancellation); } catch (Exception) { lock (this.md5hash) { this.finishedSeparateMd5Calculator = true; } throw; } long offset = 0; int readLength = 0; while (true) { lock (this.md5hash) { if (offset >= this.md5hashOffset) { Debug.Assert( offset == this.md5hashOffset, "We should stop the separate calculator thread just at the transferred offset"); this.succeededSeparateMd5Calculator = true; this.finishedSeparateMd5Calculator = true; break; } readLength = (int)Math.Min(this.md5hashOffset - offset, buffer.Length); } try { checkCancellation(); readLength = this.Read(offset, buffer, 0, readLength); lock (this.md5hash) { this.md5hash.TransformBlock(buffer, 0, readLength, null, 0); } } catch (Exception) { lock (this.md5hash) { this.finishedSeparateMd5Calculator = true; } memoryManager.ReleaseBuffer(buffer); throw; } offset += readLength; } memoryManager.ReleaseBuffer(buffer); } /// <summary> /// Begin async read from stream. /// </summary> /// <param name="readOffset">Offset in stream to read from.</param> /// <param name="buffer">The buffer to read the data into.</param> /// <param name="offset">The byte offset in buffer at which to begin writing data read from the stream.</param> /// <param name="count">The maximum number of bytes to read.</param> /// <param name="cancellationToken">Token used to cancel the asynchronous reading.</param> /// <returns>A task that represents the asynchronous read operation. The value of the /// <c>TResult</c> parameter contains the total number of bytes read into the buffer.</returns> public async Task<int> ReadAsync(long readOffset, byte[] buffer, int offset, int count, CancellationToken cancellationToken) { await this.WaitOnSemaphoreAsync(cancellationToken); try { this.stream.Position = readOffset; return await this.stream.ReadAsync( buffer, offset, count, cancellationToken); } finally { this.ReleaseSemaphore(); } } /// <summary> /// Begin async write to stream. /// </summary> /// <param name="writeOffset">Offset in stream to write to.</param> /// <param name="buffer">The buffer to write the data from.</param> /// <param name="offset">The byte offset in buffer from which to begin writing.</param> /// <param name="count">The maximum number of bytes to write.</param> /// <param name="cancellationToken">Token used to cancel the asynchronous writing.</param> /// <returns>A task that represents the asynchronous write operation.</returns> public async Task WriteAsync(long writeOffset, byte[] buffer, int offset, int count, CancellationToken cancellationToken) { await this.WaitOnSemaphoreAsync(cancellationToken); try { this.stream.Position = writeOffset; await this.stream.WriteAsync( buffer, offset, count, cancellationToken); } finally { this.ReleaseSemaphore(); } } /// <summary> /// Computes the hash value for the specified region of the input byte array /// and copies the specified region of the input byte array to the specified /// region of the output byte array. /// </summary> /// <param name="streamOffset">Offset in stream of the block on which to calculate MD5 hash.</param> /// <param name="inputBuffer">The input to compute the hash code for.</param> /// <param name="inputOffset">The offset into the input byte array from which to begin using data.</param> /// <param name="inputCount">The number of bytes in the input byte array to use as data.</param> /// <param name="outputBuffer">A copy of the part of the input array used to compute the hash code.</param> /// <param name="outputOffset">The offset into the output byte array from which to begin writing data.</param> /// <returns>Whether succeeded in calculating MD5 hash /// or not finished the separate thread to calculate MD5 hash at the time. </returns> public bool MD5HashTransformBlock(long streamOffset, byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { if (null == this.md5hash) { return true; } if (!this.finishedSeparateMd5Calculator) { lock (this.md5hash) { if (!this.finishedSeparateMd5Calculator) { if (streamOffset == this.md5hashOffset) { this.md5hashOffset += inputCount; } return true; } else { if (!this.succeededSeparateMd5Calculator) { return false; } } } } if (streamOffset >= this.md5hashOffset) { Debug.Assert( this.finishedSeparateMd5Calculator, "The separate thread to calculate MD5 hash should have finished or md5hashOffset should get updated."); this.md5hash.TransformBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset); } return true; } /// <summary> /// Computes the hash value for the specified region of the specified byte array. /// </summary> /// <param name="inputBuffer">The input to compute the hash code for.</param> /// <param name="inputOffset">The offset into the byte array from which to begin using data.</param> /// <param name="inputCount">The number of bytes in the byte array to use as data.</param> /// <returns>An array that is a copy of the part of the input that is hashed.</returns> public byte[] MD5HashTransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { this.WaitMD5CalculationToFinish(); if (!this.succeededSeparateMd5Calculator) { return null; } return null == this.md5hash ? null : this.md5hash.TransformFinalBlock(inputBuffer, inputOffset, inputCount); } /// <summary> /// Releases or resets unmanaged resources. /// </summary> public virtual void Dispose() { this.Dispose(true); } /// <summary> /// Private dispose method to release managed/unmanaged objects. /// If disposing = true clean up managed resources as well as unmanaged resources. /// If disposing = false only clean up unmanaged resources. /// </summary> /// <param name="disposing">Indicates whether or not to dispose managed resources.</param> protected virtual void Dispose(bool disposing) { if (disposing) { if (null != this.md5hash) { this.md5hash.Clear(); this.md5hash = null; } if (null != this.semaphore) { this.semaphore.Dispose(); this.semaphore = null; } } } /// <summary> /// Read from stream. /// </summary> /// <param name="readOffset">Offset in stream to read from.</param> /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified /// byte array with the values between offset and (offset + count - 1) replaced /// by the bytes read from the current source.</param> /// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param> /// <param name="count">The maximum number of bytes to be read from the current stream.</param> /// <returns>The total number of bytes read into the buffer.</returns> private int Read(long readOffset, byte[] buffer, int offset, int count) { if (!this.finishedSeparateMd5Calculator) { this.semaphore.Wait(); } try { this.stream.Position = readOffset; int readBytes = this.stream.Read(buffer, offset, count); return readBytes; } finally { this.ReleaseSemaphore(); } } /// <summary> /// Wait for one semaphore. /// </summary> /// <param name="cancellationToken">Token used to cancel waiting on the semaphore.</param> private async Task WaitOnSemaphoreAsync(CancellationToken cancellationToken) { if (!this.finishedSeparateMd5Calculator) { await this.semaphore.WaitAsync(cancellationToken); } } /// <summary> /// Release semaphore. /// </summary> private void ReleaseSemaphore() { if (!this.finishedSeparateMd5Calculator) { this.semaphore.Release(); } } /// <summary> /// Wait for MD5 calculation to be finished. /// In our test, MD5 calculation is really fast, /// and SpinOnce has sleep mechanism, so use Spin instead of sleep here. /// </summary> private void WaitMD5CalculationToFinish() { if (this.finishedSeparateMd5Calculator) { return; } SpinWait sw = new SpinWait(); while (!this.finishedSeparateMd5Calculator) { sw.SpinOnce(); } sw.Reset(); } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Reusable.Data; using Reusable.IOnymous; using Reusable.SmartConfig; using Xunit; using cfg = Reusable.SmartConfig.Configuration; //[assembly: SettingProvider(SettingNameStrength.Medium, Prefix = "TestPrefix")] //[assembly: SettingProvider(SettingNameStrength.Low, typeof(AppSettingProvider), Prefix = "abc")] //[assembly: SettingProvider(SettingNameStrength.Low, nameof(AppSettingProvider), Prefix = "abc")] /* - can find setting by name - can find first setting by name - can find setting by name and provider - can find setting by name and provider-type - can override type-name - can override member-name - can override setting name length - can add setting name prefix - can disable setting name prefix - can find setting for base type */ namespace Reusable.Tests.XUnit.SmartConfig { public class ConfigurationTest { [Fact] public void Can_get_setting_by_name() { var u = new User { Configuration = new cfg(new InMemoryProvider(new UriStringToSettingIdentifierConverter(), new SoftString[] { "setting" }) { { "User.Name", "Bob" } }) }; Assert.Equal("Bob", u.Name); } [Fact] public void Can_get_first_setting_by_name() { var u = new User { Configuration = new cfg(new CompositeProvider(new IResourceProvider[] { new InMemoryProvider(new UriStringToSettingIdentifierConverter(), new SoftString[] { "setting" }) { { "Person.Name", "Joe" } }, new InMemoryProvider(new UriStringToSettingIdentifierConverter(), new SoftString[] { "setting" }) { { "User.Name", "Bob" } }, new InMemoryProvider(new UriStringToSettingIdentifierConverter(), new SoftString[] { "setting" }) { { "User.Name", "Tom" } } })) }; Assert.Equal("Bob", u.Name); } [Fact] public void Can_find_setting_by_provider() { var u = new Map { Configuration = new cfg(new CompositeProvider(new IResourceProvider[] { new InMemoryProvider(new UriStringToSettingIdentifierConverter(), new SoftString[] { "setting" }, ImmutableSession.Empty.Set(Use<IProviderNamespace>.Namespace,x => x.CustomName, "OtherOne")) { { "Map.City", "Joe" } }, new InMemoryProvider(new UriStringToSettingIdentifierConverter(), new SoftString[] { "setting" }) { { "Map.City", "Tom" } }, new InMemoryProvider(new UriStringToSettingIdentifierConverter(), new SoftString[] { "setting" }, ImmutableSession.Empty.Set(Use<IProviderNamespace>.Namespace,x => x.CustomName, "ThisOne")) { { "Map.City", "Bob" } }, })) }; Assert.Equal("Bob", u.City); } [Fact] public void Can_find_setting_by_provider_type() { } [Fact] public void Can_override_type_and_member_names() { var u = new Forest { Configuration = new cfg(new CompositeProvider(new IResourceProvider[] { new InMemoryProvider(new UriStringToSettingIdentifierConverter(), new SoftString[] { "setting" }) { { "User.Name", "Joe" } }, new InMemoryProvider(new UriStringToSettingIdentifierConverter(), new SoftString[] { "setting" }) { { "Forest.Tree", "Tom" } }, new InMemoryProvider(new UriStringToSettingIdentifierConverter(), new SoftString[] { "setting" }) { { "Amazon.Timber", "Bob" } }, })) }; Assert.Equal("Bob", u.Tree); } [Fact] public void Can_override_setting_name_length() { var u = new Key { Configuration = new cfg(new CompositeProvider(new IResourceProvider[] { new InMemoryProvider(new UriStringToSettingIdentifierConverter(), new SoftString[] { "setting" }) { { "User.Name", "Joe" } }, new InMemoryProvider(new UriStringToSettingIdentifierConverter(), new SoftString[] { "setting" }) { { "Reusable.Tests.XUnit.SmartConfig+Key.Location", "Tom" } }, new InMemoryProvider(new UriStringToSettingIdentifierConverter(), new SoftString[] { "setting" }) { { "Door", "Bob" } }, })) }; Assert.Equal("Tom", u.Location); Assert.Equal("Bob", u.Door); } [Fact] public void Can_use_setting_name_prefix() { var u = new Greeting { Configuration = new cfg(new CompositeProvider(new IResourceProvider[] { new InMemoryProvider(new UriStringToSettingIdentifierConverter(), new SoftString[] { "setting" }) { { "User.Name", "Joe" } }, new InMemoryProvider(new UriStringToSettingIdentifierConverter(), new SoftString[] { "setting" }) { { "day:Greeting.Morning", "Bob" } }, new InMemoryProvider(new UriStringToSettingIdentifierConverter(), new SoftString[] { "setting" }) { { "Greeting.Morning", "Tom" } }, })) }; Assert.Equal("Bob", u.Morning); } [Fact] public async Task Can_use_setting_with_handle() { var c = new Configuration<User>(new CompositeProvider(new IResourceProvider[] { new InMemoryProvider(new UriStringToSettingIdentifierConverter(), new SoftString[] { "setting" }) { { "User.Name", "Joe" } }, new InMemoryProvider(new UriStringToSettingIdentifierConverter(), new SoftString[] { "setting" }) { { "User.Name,this", "Bob" } }, new InMemoryProvider(new UriStringToSettingIdentifierConverter(), new SoftString[] { "setting" }) { { "Greeting.Morning", "Tom" } }, })); Assert.Equal("Bob", await c.GetItemAsync(x => x.Name, "this")); } [Fact] public void Can_find_setting_on_base_type() { var u = new Admin { Configuration = new cfg(new CompositeProvider(new IResourceProvider[] { new InMemoryProvider(new UriStringToSettingIdentifierConverter(), new SoftString[] { "setting" }) { { "User.Name", "Joe" } }, new InMemoryProvider(new UriStringToSettingIdentifierConverter(), new SoftString[] { "setting" }) { { "Admin.Enabled", true } }, new InMemoryProvider(new UriStringToSettingIdentifierConverter(), new SoftString[] { "setting" }) { { "Admin.Skill", "Tom" } }, })) }; Assert.Equal(true, u.Enabled); Assert.Equal("Tom", u.Skill); } [Fact] public async Task Can_save_setting() { var c = new Configuration<Admin>(new CompositeProvider(new IResourceProvider[] { new InMemoryProvider(new UriStringToSettingIdentifierConverter(), new SoftString[] { "setting" }) { { "Admin.Name", "Joe" }, { "Admin.Enabled", true } } })); Assert.Equal("Joe", await c.GetItemAsync(x => x.Name)); Assert.Equal(true, await c.GetItemAsync(x => x.Enabled)); await c.SetItemAsync(x => x.Name, "Tom"); await c.SetItemAsync(x => x.Enabled, false); Assert.Equal("Tom", await c.GetItemAsync(x => x.Name)); Assert.Equal(false, await c.GetItemAsync(x => x.Enabled)); } } internal class Nothing { public IConfiguration Configuration { get; set; } public bool Enabled => Configuration.GetItem(() => Enabled); } // tests defaults internal class User : Nothing { public string Name => Configuration.GetItem(() => Name); } internal class Admin : User { public string Skill => Configuration.GetItem(() => Skill); } [ResourceName("Amazon")] internal class Forest : Nothing { [ResourceName("Timber")] public string Tree => Configuration.GetItem(() => Tree); } [ResourcePrefix("day")] internal class Greeting : Nothing { public string Morning => Configuration.GetItem(() => Morning); } // tests assembly annotations -- they are no longer supported // internal class Test6 : Nothing // { // public string Member1 { get; set; } // // //[SettingMember(Strength = SettingNameStrength.Low, PrefixHandling = PrefixHandling.Disable)] // public string Member2 { get; set; } // } [ResourceProvider("ThisOne")] internal class Map : Nothing { public string City => Configuration.GetItem(() => City); } [ResourceName(Level = ResourceNameLevel.NamespaceTypeMember)] internal class Key : Nothing { public string Location => Configuration.GetItem(() => Location); [ResourceName(Level = ResourceNameLevel.Member)] public string Door => Configuration.GetItem(() => Door); } internal class CustomTypes : Nothing { public TimeSpan TimeSpan => Configuration.GetItem(() => TimeSpan); } public class ConfigurationTestGeneric { [Fact] public async Task Can_find_setting_on_base_type() { var c = new Reusable.SmartConfig.Configuration<ISubConfig>(new CompositeProvider(new IResourceProvider[] { new InMemoryProvider(new UriStringToSettingIdentifierConverter(), new SoftString[] { "setting" }) { { "User.Name", "Joe" } }, new InMemoryProvider(new UriStringToSettingIdentifierConverter(), new SoftString[] { "setting" }) { { "root:Sub.Enabled", true } }, new InMemoryProvider(new UriStringToSettingIdentifierConverter(), new SoftString[] { "setting" }) { { "Sub.Name", "Tom" } }, })); Assert.Equal(true, await c.GetItemAsync(x => x.Enabled)); Assert.Equal("Tom", await c.GetItemAsync(x => x.Name)); } } [ResourcePrefix("root")] public interface IBaseConfig { bool Enabled { get; } } public interface ISubConfig : IBaseConfig { [ResourcePrefix("")] string Name { get; } } public interface ITypeConfig { string String { get; } bool Bool { get; } int Int { get; } double Double { get; } DateTime DateTime { get; } TimeSpan TimeSpan { get; } List<int> ListOfInt { get; } int Edit { get; } } }
using System; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using NUnit.Framework; using StatsdClient; using Tests.Helpers; namespace Tests { [TestFixture] public class MetricIntegrationTests { private UdpListener _udpListener; private Thread _listenThread; private const int _randomUnusedLocalPort = 23483; private const string _localhostAddress = "127.0.0.1"; private MetricsConfig _defaultMetricsConfig; const string _expectedTestPrefixRegex = @"test_prefix\."; const string _expectedTimeRegEx = @"time:(\d+)\|ms"; const string _expectedMultiSecondTimeRegEx = @"time:1\d{3}\|ms"; // Expect 1xxx milliseconds reported due to the 1+ second delay below private static readonly TimeSpan SleepDelay = TimeSpan.FromMilliseconds(200); private static readonly TimeSpan MultiSecondSleepDelay = TimeSpan.FromMilliseconds(1200); [OneTimeSetUp] public void SetUpUdpListener() { _udpListener = new UdpListener(_localhostAddress, _randomUnusedLocalPort); } [OneTimeTearDown] public void TearDownUdpListener() { _udpListener.Dispose(); } [SetUp] public void StartUdpListenerThread() { _defaultMetricsConfig = new MetricsConfig { StatsdServerName = _localhostAddress, StatsdServerPort = _randomUnusedLocalPort }; _listenThread = new Thread(_udpListener.Listen); _listenThread.Start(); } private string LastPacketMessageReceived() { // Stall until the the listener receives a message or times out. while(_listenThread.IsAlive) {} var lastMessages = _udpListener.GetAndClearLastMessages(); try { return lastMessages[0]; } catch (ArgumentOutOfRangeException) { return null; } } public class SanityCheck : MetricIntegrationTests { [Test] public void udp_listener_works() { var client = new StatsdUDPClient(_localhostAddress, _randomUnusedLocalPort); client.Send("iamnotinsane!"); Assert.That(LastPacketMessageReceived(), Is.EqualTo("iamnotinsane!")); } } public class Counter : MetricIntegrationTests { [Test] public void counter() { Metrics.Configure(_defaultMetricsConfig); Metrics.Counter("counter"); Assert.That(LastPacketMessageReceived(), Is.EqualTo("counter:1|c")); } [Test] public void counter_with_value() { Metrics.Configure(_defaultMetricsConfig); Metrics.Counter("counter", 10); Assert.That(LastPacketMessageReceived(), Is.EqualTo("counter:10|c")); } [Test] public void counter_with_prefix() { _defaultMetricsConfig.Prefix = "test_prefix"; Metrics.Configure(_defaultMetricsConfig); Metrics.Counter("counter"); Assert.That(LastPacketMessageReceived(), Is.EqualTo("test_prefix.counter:1|c")); } [Test] public void counter_with_prefix_having_a_trailing_dot() { _defaultMetricsConfig.Prefix = "test_prefix."; Metrics.Configure(_defaultMetricsConfig); Metrics.Counter("counter"); Assert.That(LastPacketMessageReceived(), Is.EqualTo("test_prefix.counter:1|c")); } [Test] public void counter_with_value_and_sampleRate() { Metrics.Configure(_defaultMetricsConfig); Metrics.Counter("counter", 10, 0.9999); Assert.That(LastPacketMessageReceived(), Is.EqualTo("counter:10|c|@0.9999")); } [Test] public void counter_with_no_config_setup_should_not_send_metric() { Metrics.Configure(new MetricsConfig()); Metrics.Counter("counter"); Assert.That(LastPacketMessageReceived(), Is.Null); } } public class Timer : MetricIntegrationTests { [Test] public void timer() { Metrics.Configure(_defaultMetricsConfig); Metrics.Timer("timer", 6); Assert.That(LastPacketMessageReceived(), Is.EqualTo("timer:6|ms")); } [Test] public void timer_with_prefix() { _defaultMetricsConfig.Prefix = "test_prefix"; Metrics.Configure(_defaultMetricsConfig); Metrics.Timer("timer", 6); Assert.That(LastPacketMessageReceived(), Is.EqualTo("test_prefix.timer:6|ms")); } [Test] public void timer_with_prefix_having_a_trailing_dot() { _defaultMetricsConfig.Prefix = "test_prefix."; Metrics.Configure(_defaultMetricsConfig); Metrics.Timer("timer", 6); Assert.That(LastPacketMessageReceived(), Is.EqualTo("test_prefix.timer:6|ms")); } [Test] public void timer_with_no_config_setup_should_not_send_metric() { Metrics.Configure(new MetricsConfig()); Metrics.Timer("timer", 6); Assert.That(LastPacketMessageReceived(), Is.Null); } } public class DisposableTimer : MetricIntegrationTests { [Test] public void disposable_timer() { Metrics.Configure(_defaultMetricsConfig); using (Metrics.StartTimer("time")) { Thread.Sleep(MultiSecondSleepDelay); } Assert.That(LastPacketMessageReceived(), Does.Match(_expectedMultiSecondTimeRegEx)); } } public class Time : MetricIntegrationTests { [Test] public void time() { Metrics.Configure(_defaultMetricsConfig); Metrics.Time(() => Thread.Sleep(MultiSecondSleepDelay), "time"); Assert.That(LastPacketMessageReceived(), Does.Match(_expectedMultiSecondTimeRegEx)); } [Test] public void time_add() { var statsd = new Statsd(new StatsdUDPClient(_localhostAddress, _randomUnusedLocalPort)); statsd.Add(() => Thread.Sleep(MultiSecondSleepDelay), "time"); statsd.Send(); Assert.That(LastPacketMessageReceived(), Does.Match(_expectedMultiSecondTimeRegEx)); } [Test] public async Task time_async() { Metrics.Configure(_defaultMetricsConfig); await Metrics.Time(async () => await Task.Delay(SleepDelay), "time"); AssertTimerLength(); } [Test] public void time_with_prefix() { _defaultMetricsConfig.Prefix = "test_prefix"; Metrics.Configure(_defaultMetricsConfig); Metrics.Time(() => Thread.Sleep(SleepDelay), "time"); Assert.That(LastPacketMessageReceived(), Does.Match(_expectedTestPrefixRegex + _expectedTimeRegEx)); } [Test] public void time_with_prefix_having_trailing_dot() { _defaultMetricsConfig.Prefix = "test_prefix."; Metrics.Configure(_defaultMetricsConfig); Metrics.Time(() => Thread.Sleep(SleepDelay), "time"); Assert.That(LastPacketMessageReceived(), Does.Match(_expectedTestPrefixRegex + _expectedTimeRegEx)); } [Test] public void time_with_no_config_setup_should_not_send_metric_but_still_run_action() { Metrics.Configure(new MetricsConfig()); var someValue = 5; Metrics.Time(() => { someValue = 10; }, "timer"); Assert.That(someValue, Is.EqualTo(10)); Assert.That(LastPacketMessageReceived(), Is.Null); } [Test] public async Task time_with_async_return_value() { Metrics.Configure(_defaultMetricsConfig); var returnValue = await Metrics.Time(async () => { await Task.Delay(SleepDelay); return 20; }, "time"); AssertTimerLength(); Assert.That(returnValue, Is.EqualTo(20)); } [Test] public void time_with_return_value() { Metrics.Configure(_defaultMetricsConfig); var returnValue = Metrics.Time(() => { Thread.Sleep(SleepDelay); return 5; }, "time"); Assert.That(LastPacketMessageReceived(), Does.Match(_expectedTimeRegEx)); Assert.That(returnValue, Is.EqualTo(5)); } [Test] public void time_with_return_value_and_prefix() { _defaultMetricsConfig.Prefix = "test_prefix"; Metrics.Configure(_defaultMetricsConfig); var returnValue = Metrics.Time(() => { Thread.Sleep(SleepDelay); return 5; }, "time"); Assert.That(LastPacketMessageReceived(), Does.Match(_expectedTestPrefixRegex + _expectedTimeRegEx)); Assert.That(returnValue, Is.EqualTo(5)); } [Test] public void time_with_return_value_and_prefix_having_a_trailing_dot() { _defaultMetricsConfig.Prefix = "test_prefix."; Metrics.Configure(_defaultMetricsConfig); var returnValue = Metrics.Time(() => { Thread.Sleep(SleepDelay); return 5; }, "time"); Assert.That(LastPacketMessageReceived(), Does.Match(_expectedTestPrefixRegex + _expectedTimeRegEx)); Assert.That(returnValue, Is.EqualTo(5)); } [Test] public void time_with_return_value_and_no_config_setup_should_not_send_metric_but_still_return_value() { Metrics.Configure(new MetricsConfig()); var returnValue = Metrics.Time(() => 5, "time"); Assert.That(LastPacketMessageReceived(), Is.Null); Assert.That(returnValue, Is.EqualTo(5)); } private void AssertTimerLength() { var lastPacketMessageReceived = LastPacketMessageReceived(); Assert.That(lastPacketMessageReceived, Does.Match(_expectedTimeRegEx)); var match = Regex.Match(lastPacketMessageReceived, _expectedTimeRegEx); var timerValue = Convert.ToInt32(match.Groups[1].Value); Assert.That(timerValue, Is.EqualTo(SleepDelay.Milliseconds).Within(100)); } } public class GaugeDelta : MetricIntegrationTests { [Test] [TestCase(123d, "gauge:+123|g")] [TestCase(-123d, "gauge:-123|g")] [TestCase(0d, "gauge:+0|g")] public void GaugeDelta_EmitsCorrect_Format(double gaugeDeltaValue, string expectedPacketMessageFormat) { Metrics.Configure(_defaultMetricsConfig); Metrics.GaugeDelta("gauge", gaugeDeltaValue); Assert.That(LastPacketMessageReceived(), Is.EqualTo(expectedPacketMessageFormat)); } } public class GaugeAbsolute : MetricIntegrationTests { [Test] public void absolute_gauge_with_double_value() { Metrics.Configure(_defaultMetricsConfig); const double value = 12345678901234567890; Metrics.GaugeAbsoluteValue("gauge", value); Assert.That(LastPacketMessageReceived(), Is.EqualTo("gauge:12345678901234600000.000000000000000|g")); } [Test] public void absolute_gauge_with_double_value_with_floating_point() { Metrics.Configure(_defaultMetricsConfig); const double value = 1.234567890123456; Metrics.GaugeAbsoluteValue("gauge", value); Assert.That(LastPacketMessageReceived(), Is.EqualTo("gauge:1.234567890123460|g")); } [Test] public void absolute_gauge_with_prefix() { _defaultMetricsConfig.Prefix = "test_prefix"; Metrics.Configure(_defaultMetricsConfig); Metrics.GaugeAbsoluteValue("gauge", 3); Assert.That(LastPacketMessageReceived(), Is.EqualTo("test_prefix.gauge:3.000000000000000|g")); } [Test] public void absolute_gauge_with_prefix_having_a_trailing_dot() { _defaultMetricsConfig.Prefix = "test_prefix."; Metrics.Configure(_defaultMetricsConfig); Metrics.GaugeAbsoluteValue("gauge", 3); Assert.That(LastPacketMessageReceived(), Is.EqualTo("test_prefix.gauge:3.000000000000000|g")); } [Test] public void gauge_with_no_config_setup_should_not_send_metric() { Metrics.Configure(new MetricsConfig()); Metrics.GaugeAbsoluteValue("gauge", 3); Assert.That(LastPacketMessageReceived(), Is.Null); } } public class Set : MetricIntegrationTests { [Test] public void set() { Metrics.Configure(_defaultMetricsConfig); Metrics.Set("timer", "value"); Assert.That(LastPacketMessageReceived(), Is.EqualTo("timer:value|s")); } [Test] public void set_with_prefix() { _defaultMetricsConfig.Prefix = "test_prefix"; Metrics.Configure(_defaultMetricsConfig); Metrics.Set("timer", "value"); Assert.That(LastPacketMessageReceived(), Is.EqualTo("test_prefix.timer:value|s")); } [Test] public void set_with_prefix_having_a_trailing_dot() { _defaultMetricsConfig.Prefix = "test_prefix."; Metrics.Configure(_defaultMetricsConfig); Metrics.Set("timer", "value"); Assert.That(LastPacketMessageReceived(), Is.EqualTo("test_prefix.timer:value|s")); } [Test] public void set_with_no_config_setup_should_not_send_metric() { Metrics.Configure(new MetricsConfig()); Metrics.Set("timer", "value"); Assert.That(LastPacketMessageReceived(), Is.Null); } } } }
//----------------------------------------------------------------------------- // <copyright file="TransactionScope.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //----------------------------------------------------------------------------- using System; using System.Diagnostics; using SysES = System.EnterpriseServices; using System.Runtime.CompilerServices; using System.Runtime.Remoting.Messaging; using System.Runtime.InteropServices; using System.Threading; using System.Transactions.Diagnostics; namespace System.Transactions { public enum TransactionScopeOption { Required, RequiresNew, Suppress, } // // The legacy TransactionScope uses TLS to store the ambient transaction. TLS data doesn't flow across thread continuations and hence legacy TransactionScope does not compose well with // new .Net async programming model constructs like Tasks and async/await. To enable TransactionScope to work with Task and async/await, a new TransactionScopeAsyncFlowOption // is introduced. When users opt-in the async flow option, ambient transaction will automatically flow across thread continuations and user can compose TransactionScope with Task and/or // async/await constructs. // public enum TransactionScopeAsyncFlowOption { Suppress, // Ambient transaction will be stored in TLS and will not flow across thread continuations. Enabled, // Ambient transaction will be stored in CallContext and will flow across thread continuations. This option will enable TransactionScope to compose well with Task and async/await. } public enum EnterpriseServicesInteropOption { None = 0, Automatic = 1, Full = 2 } public sealed class TransactionScope : IDisposable { public TransactionScope() : this( TransactionScopeOption.Required ) { } public TransactionScope(TransactionScopeOption scopeOption) : this(scopeOption, TransactionScopeAsyncFlowOption.Suppress) { } public TransactionScope(TransactionScopeAsyncFlowOption asyncFlowOption) : this(TransactionScopeOption.Required, asyncFlowOption) { } public TransactionScope( TransactionScopeOption scopeOption, TransactionScopeAsyncFlowOption asyncFlowOption ) { if ( !TransactionManager._platformValidated ) TransactionManager.ValidatePlatform(); if ( DiagnosticTrace.Verbose ) { MethodEnteredTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), "TransactionScope.ctor( TransactionScopeOption )" ); } ValidateAndSetAsyncFlowOption(asyncFlowOption); if ( NeedToCreateTransaction( scopeOption ) ) { committableTransaction = new CommittableTransaction(); expectedCurrent = committableTransaction.Clone(); } if ( DiagnosticTrace.Information ) { if ( null == expectedCurrent ) { TransactionScopeCreatedTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), TransactionTraceIdentifier.Empty, TransactionScopeResult.NoTransaction ); } else { TransactionScopeResult scopeResult; if ( null == committableTransaction ) { scopeResult = TransactionScopeResult.UsingExistingCurrent; } else { scopeResult = TransactionScopeResult.CreatedTransaction; } TransactionScopeCreatedTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), expectedCurrent.TransactionTraceId, scopeResult ); } } PushScope(); if ( DiagnosticTrace.Verbose ) { MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), "TransactionScope.ctor( TransactionScopeOption )" ); } } public TransactionScope(TransactionScopeOption scopeOption, TimeSpan scopeTimeout) : this(scopeOption, scopeTimeout, TransactionScopeAsyncFlowOption.Suppress) { } public TransactionScope( TransactionScopeOption scopeOption, TimeSpan scopeTimeout, TransactionScopeAsyncFlowOption asyncFlowOption ) { if ( !TransactionManager._platformValidated ) TransactionManager.ValidatePlatform(); if ( DiagnosticTrace.Verbose ) { MethodEnteredTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), "TransactionScope.ctor( TransactionScopeOption, TimeSpan )" ); } ValidateScopeTimeout( "scopeTimeout", scopeTimeout ); TimeSpan txTimeout = TransactionManager.ValidateTimeout( scopeTimeout ); ValidateAndSetAsyncFlowOption(asyncFlowOption); if ( NeedToCreateTransaction( scopeOption )) { this.committableTransaction = new CommittableTransaction( txTimeout ); this.expectedCurrent = committableTransaction.Clone(); } if ( (null != this.expectedCurrent) && (null == this.committableTransaction) && (TimeSpan.Zero != scopeTimeout) ) { // scopeTimer = new Timer( TransactionScope.TimerCallback, this, scopeTimeout, TimeSpan.Zero ); } if ( DiagnosticTrace.Information ) { if ( null == expectedCurrent ) { TransactionScopeCreatedTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), TransactionTraceIdentifier.Empty, TransactionScopeResult.NoTransaction ); } else { TransactionScopeResult scopeResult; if ( null == committableTransaction ) { scopeResult = TransactionScopeResult.UsingExistingCurrent; } else { scopeResult = TransactionScopeResult.CreatedTransaction; } TransactionScopeCreatedTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), expectedCurrent.TransactionTraceId, scopeResult ); } } PushScope(); if ( DiagnosticTrace.Verbose ) { MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), "TransactionScope.ctor( TransactionScopeOption, TimeSpan )" ); } } public TransactionScope(TransactionScopeOption scopeOption, TransactionOptions transactionOptions) : this(scopeOption, transactionOptions, TransactionScopeAsyncFlowOption.Suppress) { } public TransactionScope( TransactionScopeOption scopeOption, TransactionOptions transactionOptions, TransactionScopeAsyncFlowOption asyncFlowOption ) { if ( !TransactionManager._platformValidated ) TransactionManager.ValidatePlatform(); if ( DiagnosticTrace.Verbose ) { MethodEnteredTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), "TransactionScope.ctor( TransactionScopeOption, TransactionOptions )" ); } ValidateScopeTimeout( "transactionOptions.Timeout", transactionOptions.Timeout ); TimeSpan scopeTimeout = transactionOptions.Timeout; transactionOptions.Timeout = TransactionManager.ValidateTimeout( transactionOptions.Timeout ); TransactionManager.ValidateIsolationLevel( transactionOptions.IsolationLevel ); ValidateAndSetAsyncFlowOption(asyncFlowOption); if ( NeedToCreateTransaction( scopeOption ) ) { this.committableTransaction = new CommittableTransaction( transactionOptions ); this.expectedCurrent = committableTransaction.Clone(); } else { if ( null != this.expectedCurrent ) { // If the requested IsolationLevel is stronger than that of the specified transaction, throw. if ( (IsolationLevel.Unspecified != transactionOptions.IsolationLevel) && ( expectedCurrent.IsolationLevel != transactionOptions.IsolationLevel ) ) { throw new ArgumentException( SR.GetString( SR.TransactionScopeIsolationLevelDifferentFromTransaction ), "transactionOptions.IsolationLevel" ); } } } if ( (null != this.expectedCurrent) && (null == this.committableTransaction) && (TimeSpan.Zero != scopeTimeout) ) { // scopeTimer = new Timer( TransactionScope.TimerCallback, this, scopeTimeout, TimeSpan.Zero ); } if ( DiagnosticTrace.Information ) { if ( null == expectedCurrent ) { TransactionScopeCreatedTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), TransactionTraceIdentifier.Empty, TransactionScopeResult.NoTransaction ); } else { TransactionScopeResult scopeResult; if ( null == committableTransaction ) { scopeResult = TransactionScopeResult.UsingExistingCurrent; } else { scopeResult = TransactionScopeResult.CreatedTransaction; } TransactionScopeCreatedTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), expectedCurrent.TransactionTraceId, scopeResult ); } } PushScope(); if ( DiagnosticTrace.Verbose ) { MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), "TransactionScope.ctor( TransactionScopeOption, TransactionOptions )" ); } } [System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Name = "FullTrust")] public TransactionScope( TransactionScopeOption scopeOption, TransactionOptions transactionOptions, EnterpriseServicesInteropOption interopOption ) { if ( !TransactionManager._platformValidated ) TransactionManager.ValidatePlatform(); if ( DiagnosticTrace.Verbose ) { MethodEnteredTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), "TransactionScope.ctor( TransactionScopeOption, TransactionOptions, EnterpriseServicesInteropOption )" ); } ValidateScopeTimeout( "transactionOptions.Timeout", transactionOptions.Timeout ); TimeSpan scopeTimeout = transactionOptions.Timeout; transactionOptions.Timeout = TransactionManager.ValidateTimeout( transactionOptions.Timeout ); TransactionManager.ValidateIsolationLevel( transactionOptions.IsolationLevel ); ValidateInteropOption( interopOption ); this.interopModeSpecified = true; this.interopOption = interopOption; if ( NeedToCreateTransaction( scopeOption ) ) { committableTransaction = new CommittableTransaction( transactionOptions ); expectedCurrent = committableTransaction.Clone(); } else { if ( null != expectedCurrent ) { // If the requested IsolationLevel is stronger than that of the specified transaction, throw. if ( (IsolationLevel.Unspecified != transactionOptions.IsolationLevel) && ( expectedCurrent.IsolationLevel != transactionOptions.IsolationLevel ) ) { throw new ArgumentException( SR.GetString( SR.TransactionScopeIsolationLevelDifferentFromTransaction ), "transactionOptions.IsolationLevel" ); } } } if ( (null != this.expectedCurrent) && (null == this.committableTransaction) && (TimeSpan.Zero != scopeTimeout) ) { // scopeTimer = new Timer( TransactionScope.TimerCallback, this, scopeTimeout, TimeSpan.Zero ); } if ( DiagnosticTrace.Information ) { if ( null == expectedCurrent ) { TransactionScopeCreatedTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), TransactionTraceIdentifier.Empty, TransactionScopeResult.NoTransaction ); } else { TransactionScopeResult scopeResult; if ( null == committableTransaction ) { scopeResult = TransactionScopeResult.UsingExistingCurrent; } else { scopeResult = TransactionScopeResult.CreatedTransaction; } TransactionScopeCreatedTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), expectedCurrent.TransactionTraceId, scopeResult ); } } PushScope(); if ( DiagnosticTrace.Verbose ) { MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), "TransactionScope.ctor( TransactionScopeOption, TransactionOptions, EnterpriseServicesInteropOption )" ); } } public TransactionScope(Transaction transactionToUse) : this(transactionToUse, TransactionScopeAsyncFlowOption.Suppress) { } public TransactionScope( Transaction transactionToUse, TransactionScopeAsyncFlowOption asyncFlowOption ) { if ( !TransactionManager._platformValidated ) TransactionManager.ValidatePlatform(); if ( DiagnosticTrace.Verbose ) { MethodEnteredTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), "TransactionScope.ctor( Transaction )" ); } ValidateAndSetAsyncFlowOption(asyncFlowOption); Initialize( transactionToUse, TimeSpan.Zero, false ); if ( DiagnosticTrace.Verbose ) { MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), "TransactionScope.ctor( Transaction )" ); } } public TransactionScope(Transaction transactionToUse, TimeSpan scopeTimeout) : this(transactionToUse, scopeTimeout, TransactionScopeAsyncFlowOption.Suppress) { } public TransactionScope( Transaction transactionToUse, TimeSpan scopeTimeout, TransactionScopeAsyncFlowOption asyncFlowOption ) { if ( !TransactionManager._platformValidated ) TransactionManager.ValidatePlatform(); if ( DiagnosticTrace.Verbose ) { MethodEnteredTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), "TransactionScope.ctor( Transaction, TimeSpan )" ); } ValidateAndSetAsyncFlowOption(asyncFlowOption); Initialize( transactionToUse, scopeTimeout, false ); if ( DiagnosticTrace.Verbose ) { MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), "TransactionScope.ctor( Transaction, TimeSpan )" ); } } [System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.LinkDemand, Name = "FullTrust")] public TransactionScope( Transaction transactionToUse, TimeSpan scopeTimeout, EnterpriseServicesInteropOption interopOption ) { if ( !TransactionManager._platformValidated ) TransactionManager.ValidatePlatform(); if ( DiagnosticTrace.Verbose ) { MethodEnteredTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), "TransactionScope.ctor( Transaction, TimeSpan, EnterpriseServicesInteropOption )" ); } ValidateInteropOption( interopOption ); this.interopOption = interopOption; Initialize( transactionToUse, scopeTimeout, true ); if ( DiagnosticTrace.Verbose ) { MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), "TransactionScope.ctor( Transaction, TimeSpan, EnterpriseServicesInteropOption )" ); } } private bool NeedToCreateTransaction( TransactionScopeOption scopeOption ) { bool retVal = false; CommonInitialize(); // If the options specify NoTransactionNeeded, that trumps everything else. switch ( scopeOption ) { case TransactionScopeOption.Suppress: expectedCurrent = null; retVal = false; break; case TransactionScopeOption.Required: expectedCurrent = this.savedCurrent; // If current is null, we need to create one. if ( null == expectedCurrent ) { retVal = true; } break; case TransactionScopeOption.RequiresNew: retVal = true; break; default: throw new ArgumentOutOfRangeException( "scopeOption" ); } return retVal; } private void Initialize( Transaction transactionToUse, TimeSpan scopeTimeout, bool interopModeSpecified ) { if ( null == transactionToUse ) { throw new ArgumentNullException( "transactionToUse" ); } ValidateScopeTimeout( "scopeTimeout", scopeTimeout ); CommonInitialize(); if ( TimeSpan.Zero != scopeTimeout ) { scopeTimer = new Timer( TransactionScope.TimerCallback, this, scopeTimeout, TimeSpan.Zero ); } this.expectedCurrent = transactionToUse; this.interopModeSpecified = interopModeSpecified; if ( DiagnosticTrace.Information ) { TransactionScopeCreatedTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), expectedCurrent.TransactionTraceId, TransactionScopeResult.TransactionPassed ); } PushScope(); } // We don't have a finalizer (~TransactionScope) because all it would be able to do is try to // operate on other managed objects (the transaction), which is not safe to do because they may // already have been finalized. // FXCop wants us to dispose savedCurrent, which is a Transaction, and thus disposable. But we don't // want to do that here. We want to restore Current to that value. We do dispose the expected current. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed")] public void Dispose() { bool successful = false; if ( DiagnosticTrace.Verbose ) { MethodEnteredTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), "TransactionScope.Dispose" ); } if ( this.disposed ) { if ( DiagnosticTrace.Verbose ) { MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), "TransactionScope.Dispose" ); } return; } // Dispose for a scope can only be called on the thread where the scope was created. if ((this.scopeThread != Thread.CurrentThread) && !this.AsyncFlowEnabled) { if ( DiagnosticTrace.Error ) { InvalidOperationExceptionTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), SR.GetString( SR.InvalidScopeThread ) ); } throw new InvalidOperationException( SR.GetString( SR.InvalidScopeThread )); } Exception exToThrow = null; try { // Single threaded from this point this.disposed = true; // First, lets pop the "stack" of TransactionScopes and dispose each one that is above us in // the stack, making sure they are NOT consistent before disposing them. // Optimize the first lookup by getting both the actual current scope and actual current // transaction at the same time. TransactionScope actualCurrentScope = this.threadContextData.CurrentScope; Transaction contextTransaction = null; Transaction current = Transaction.FastGetTransaction( actualCurrentScope, this.threadContextData, out contextTransaction ); if ( !Equals( actualCurrentScope )) { // Ok this is bad. But just how bad is it. The worst case scenario is that someone is // poping scopes out of order and has placed a new transaction in the top level scope. // Check for that now. if ( actualCurrentScope == null ) { // Something must have gone wrong trying to clean up a bad scope // stack previously. // Make a best effort to abort the active transaction. Transaction rollbackTransaction = this.committableTransaction; if ( rollbackTransaction == null ) { rollbackTransaction = this.dependentTransaction; } Debug.Assert( rollbackTransaction != null ); rollbackTransaction.Rollback(); successful = true; throw TransactionException.CreateInvalidOperationException( SR.GetString( SR.TraceSourceBase ), SR.GetString(SR.TransactionScopeInvalidNesting), null, rollbackTransaction.DistributedTxId); } // Verify that expectedCurrent is the same as the "current" current if we the interopOption value is None. else if ( EnterpriseServicesInteropOption.None == actualCurrentScope.interopOption ) { if ( ( ( null != actualCurrentScope.expectedCurrent ) && ( ! actualCurrentScope.expectedCurrent.Equals( current ) ) ) || ( ( null != current ) && ( null == actualCurrentScope.expectedCurrent ) ) ) { if ( DiagnosticTrace.Warning ) { TransactionTraceIdentifier myId; TransactionTraceIdentifier currentId; if ( null == current ) { currentId = TransactionTraceIdentifier.Empty; } else { currentId = current.TransactionTraceId; } if ( null == this.expectedCurrent ) { myId = TransactionTraceIdentifier.Empty; } else { myId = this.expectedCurrent.TransactionTraceId; } TransactionScopeCurrentChangedTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), myId, currentId ); } exToThrow = TransactionException.CreateInvalidOperationException(SR.GetString(SR.TraceSourceBase), SR.GetString(SR.TransactionScopeIncorrectCurrent), null, current == null ? Guid.Empty : current.DistributedTxId); // If there is a current transaction, abort it. if ( null != current ) { try { current.Rollback(); } catch ( TransactionException ) { // we are already going to throw and exception, so just ignore this one. } catch ( ObjectDisposedException ) { // Dito } } } } // Now fix up the scopes while ( !Equals( actualCurrentScope )) { if ( null == exToThrow ) { exToThrow = TransactionException.CreateInvalidOperationException( SR.GetString( SR.TraceSourceBase ), SR.GetString( SR.TransactionScopeInvalidNesting ), null, current == null ? Guid.Empty : current.DistributedTxId ); } if ( DiagnosticTrace.Warning ) { if ( null == actualCurrentScope.expectedCurrent ) { TransactionScopeNestedIncorrectlyTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), TransactionTraceIdentifier.Empty ); } else { TransactionScopeNestedIncorrectlyTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), actualCurrentScope.expectedCurrent.TransactionTraceId ); } } actualCurrentScope.complete = false; try { actualCurrentScope.InternalDispose(); } catch ( TransactionException ) { // we are already going to throw an exception, so just ignore this one. } actualCurrentScope = this.threadContextData.CurrentScope; // We want to fail this scope, too, because work may have been done in one of these other // nested scopes that really should have been done in my scope. this.complete = false; } } else { // Verify that expectedCurrent is the same as the "current" current if we the interopOption value is None. // If we got here, actualCurrentScope is the same as "this". if ( EnterpriseServicesInteropOption.None == this.interopOption ) { if ((( null != this.expectedCurrent ) && ( ! this.expectedCurrent.Equals( current ))) || (( null != current ) && ( null == this.expectedCurrent )) ) { if ( DiagnosticTrace.Warning ) { TransactionTraceIdentifier myId; TransactionTraceIdentifier currentId; if ( null == current ) { currentId = TransactionTraceIdentifier.Empty; } else { currentId = current.TransactionTraceId; } if ( null == this.expectedCurrent ) { myId = TransactionTraceIdentifier.Empty; } else { myId = this.expectedCurrent.TransactionTraceId; } TransactionScopeCurrentChangedTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), myId, currentId ); } if ( null == exToThrow ) { exToThrow = TransactionException.CreateInvalidOperationException(SR.GetString(SR.TraceSourceBase), SR.GetString(SR.TransactionScopeIncorrectCurrent), null, current == null ? Guid.Empty : current.DistributedTxId); } // If there is a current transaction, abort it. if ( null != current ) { try { current.Rollback(); } catch ( TransactionException ) { // we are already going to throw and exception, so just ignore this one. } catch ( ObjectDisposedException ) { // Dito } } // Set consistent to false so that the subsequent call to // InternalDispose below will rollback this.expectedCurrent. this.complete = false; } } } successful = true; } finally { if ( !successful ) { PopScope(); } } // No try..catch here. Just let any exception thrown by InternalDispose go out. InternalDispose(); if ( null != exToThrow ) { throw exToThrow; } if ( DiagnosticTrace.Verbose ) { MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), "TransactionScope.Dispose" ); } } private void InternalDispose() { // Set this if it is called internally. this.disposed = true; try { PopScope(); if ( DiagnosticTrace.Information ) { if ( null == this.expectedCurrent ) { TransactionScopeDisposedTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), TransactionTraceIdentifier.Empty ); } else { TransactionScopeDisposedTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), this.expectedCurrent.TransactionTraceId ); } } // If Transaction.Current is not null, we have work to do. Otherwise, we don't, except to replace // the previous value. if ( null != this.expectedCurrent ) { if ( !this.complete ) { if ( DiagnosticTrace.Warning ) { TransactionScopeIncompleteTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), this.expectedCurrent.TransactionTraceId ); } // // Note: Rollback is not called on expected current because someone could conceiveably // dispose expectedCurrent out from under the transaction scope. // Transaction rollbackTransaction = this.committableTransaction; if ( rollbackTransaction == null ) { rollbackTransaction = this.dependentTransaction; } Debug.Assert( rollbackTransaction != null ); rollbackTransaction.Rollback(); } else { // If we are supposed to commit on dispose, cast to CommittableTransaction and commit it. if ( null != this.committableTransaction ) { this.committableTransaction.Commit(); } else { Debug.Assert( null != this.dependentTransaction, "null != this.dependentTransaction" ); this.dependentTransaction.Complete(); } } } } finally { if ( null != scopeTimer ) { scopeTimer.Dispose(); } if ( null != this.committableTransaction ) { this.committableTransaction.Dispose(); // If we created the committable transaction then we placed a clone in expectedCurrent // and it needs to be disposed as well. this.expectedCurrent.Dispose(); } if ( null != this.dependentTransaction ) { this.dependentTransaction.Dispose(); } } } public void Complete() { if ( DiagnosticTrace.Verbose ) { MethodEnteredTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), "TransactionScope.Complete" ); } if ( this.disposed ) { throw new ObjectDisposedException( "TransactionScope" ); } if ( this.complete ) { throw TransactionException.CreateInvalidOperationException( SR.GetString( SR.TraceSourceBase ), SR.GetString(SR.DisposeScope), null); } this.complete = true; if ( DiagnosticTrace.Verbose ) { MethodExitedTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), "TransactionScope.Complete" ); } } private static void TimerCallback( object state ) { TransactionScope scope = state as TransactionScope; if ( null == scope ) { if ( DiagnosticTrace.Critical ) { InternalErrorTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), SR.GetString( SR.TransactionScopeTimerObjectInvalid ) ); } throw TransactionException.Create( SR.GetString( SR.TraceSourceBase ), SR.GetString( SR.InternalError) + SR.GetString( SR.TransactionScopeTimerObjectInvalid ), null ); } scope.Timeout(); } private void Timeout() { if ( ( !this.complete ) && ( null != this.expectedCurrent ) ) { if ( DiagnosticTrace.Warning ) { TransactionScopeTimeoutTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), this.expectedCurrent.TransactionTraceId ); } try { this.expectedCurrent.Rollback(); } catch ( ObjectDisposedException ex ) { // Tolerate the fact that the transaction has already been disposed. if ( DiagnosticTrace.Verbose ) { ExceptionConsumedTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), ex ); } } catch ( TransactionException txEx ) { // Tolerate transaction exceptions - VSWhidbey 466868. if ( DiagnosticTrace.Verbose ) { ExceptionConsumedTraceRecord.Trace( SR.GetString( SR.TraceSourceBase ), txEx ); } } } } private void CommonInitialize() { this.ContextKey = new ContextKey(); this.complete = false; this.dependentTransaction = null; this.disposed = false; this.committableTransaction = null; this.expectedCurrent = null; this.scopeTimer = null; this.scopeThread = Thread.CurrentThread; Transaction.GetCurrentTransactionAndScope( this.AsyncFlowEnabled ? TxLookup.DefaultCallContext : TxLookup.DefaultTLS, out this.savedCurrent, out this.savedCurrentScope, out this.contextTransaction ); // Calling validate here as we need to make sure the existing parent ambient transaction scope is already looked up to see if we have ES interop enabled. ValidateAsyncFlowOptionAndESInteropOption(); } // PushScope // // Push a transaction scope onto the stack. private void PushScope() { // Fixup the interop mode before we set current. if ( !this.interopModeSpecified ) { // Transaction.InteropMode will take the interop mode on // for the scope in currentScope into account. this.interopOption = Transaction.InteropMode(this.savedCurrentScope); } // async function yield at await points and main thread can continue execution. We need to make sure the TLS data are restored appropriately. SaveTLSContextData(); if (this.AsyncFlowEnabled) { // Async Flow is enabled and CallContext will be used for ambient transaction. this.threadContextData = CallContextCurrentData.CreateOrGetCurrentData(this.ContextKey); if (this.savedCurrentScope == null && this.savedCurrent == null) { // Clear TLS data so that transaction doesn't leak from current thread. ContextData.TLSCurrentData = null; } } else { // Legacy TransactionScope. Use TLS to track ambient transaction context. this.threadContextData = ContextData.TLSCurrentData; CallContextCurrentData.ClearCurrentData(this.ContextKey, false); } // This call needs to be done first SetCurrent( expectedCurrent ); this.threadContextData.CurrentScope = this; } // PopScope // // Pop the current transaction scope off the top of the stack private void PopScope() { bool shouldRestoreContextData = true; // Clear the current TransactionScope CallContext data if (this.AsyncFlowEnabled) { CallContextCurrentData.ClearCurrentData(this.ContextKey, true); } if (this.scopeThread == Thread.CurrentThread) { // async function yield at await points and main thread can continue execution. We need to make sure the TLS data are restored appropriately. // Restore the TLS only if the thread Ids match. RestoreSavedTLSContextData(); } // Restore threadContextData to parent CallContext or TLS data if (this.savedCurrentScope != null) { if (this.savedCurrentScope.AsyncFlowEnabled) { this.threadContextData = CallContextCurrentData.CreateOrGetCurrentData(this.savedCurrentScope.ContextKey); } else { if (this.savedCurrentScope.scopeThread != Thread.CurrentThread) { // Clear TLS data so that transaction doesn't leak from current thread. shouldRestoreContextData = false; ContextData.TLSCurrentData = null; } else { this.threadContextData = ContextData.TLSCurrentData; } CallContextCurrentData.ClearCurrentData(this.savedCurrentScope.ContextKey, false); } } else { // No parent TransactionScope present // Clear any CallContext data CallContextCurrentData.ClearCurrentData(null, false); if (this.scopeThread != Thread.CurrentThread) { // Clear TLS data so that transaction doesn't leak from current thread. shouldRestoreContextData = false; ContextData.TLSCurrentData = null; } else { // Restore the current data to TLS. ContextData.TLSCurrentData = this.threadContextData; } } // prevent restoring the context in an unexpected thread due to thread switch during TransactionScope's Dispose if (shouldRestoreContextData) { this.threadContextData.CurrentScope = this.savedCurrentScope; RestoreCurrent(); } } // SetCurrent // // Place the given value in current by whatever means necessary for interop mode. private void SetCurrent( Transaction newCurrent ) { // Keep a dependent clone of current if we don't have one and we are not committable if ( this.dependentTransaction == null && this.committableTransaction == null ) { if ( newCurrent != null ) { this.dependentTransaction = newCurrent.DependentClone( DependentCloneOption.RollbackIfNotComplete ); } } switch ( this.interopOption ) { case EnterpriseServicesInteropOption.None: this.threadContextData.CurrentTransaction = newCurrent; break; case EnterpriseServicesInteropOption.Automatic: Transaction.VerifyEnterpriseServicesOk(); if ( Transaction.UseServiceDomainForCurrent() ) { PushServiceDomain( newCurrent ); } else { this.threadContextData.CurrentTransaction = newCurrent; } break; case EnterpriseServicesInteropOption.Full: Transaction.VerifyEnterpriseServicesOk(); PushServiceDomain( newCurrent ); break; } } private void SaveTLSContextData() { if (this.savedTLSContextData == null) { this.savedTLSContextData = new ContextData(false); } this.savedTLSContextData.CurrentScope = ContextData.TLSCurrentData.CurrentScope; this.savedTLSContextData.CurrentTransaction = ContextData.TLSCurrentData.CurrentTransaction; this.savedTLSContextData.DefaultComContextState = ContextData.TLSCurrentData.DefaultComContextState; this.savedTLSContextData.WeakDefaultComContext = ContextData.TLSCurrentData.WeakDefaultComContext; } private void RestoreSavedTLSContextData() { if (this.savedTLSContextData != null) { ContextData.TLSCurrentData.CurrentScope = this.savedTLSContextData.CurrentScope; ContextData.TLSCurrentData.CurrentTransaction = this.savedTLSContextData.CurrentTransaction; ContextData.TLSCurrentData.DefaultComContextState = this.savedTLSContextData.DefaultComContextState; ContextData.TLSCurrentData.WeakDefaultComContext = this.savedTLSContextData.WeakDefaultComContext; } } // PushServiceDomain // // Create a new service domain with the given transaction. [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] // PushServiceDomain will only be called if a transaction scope is created with an // EnterpriseServicesInteropOption. TransactionScope constructors that take a ESIO are protected by // a FullTrust link demand. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2116:AptcaMethodsShouldOnlyCallAptcaMethods")] private void PushServiceDomain( Transaction newCurrent ) { // If we are not changing the transaction for the current ServiceDomain then // don't call CoEnterServiceDomain if ((newCurrent != null && newCurrent.Equals( SysES.ContextUtil.SystemTransaction )) || (newCurrent == null && SysES.ContextUtil.SystemTransaction == null )) { return; } SysES.ServiceConfig serviceConfig = new SysES.ServiceConfig(); try { // If a transaction is specified place it in BYOT. Otherwise the // default transaction option for ServiceConfig is disabled. So // if this is a not supported scope it will be cleared. if ( newCurrent != null ) { // To work around an SWC bug in Com+ we need to create 2 // service domains. // Com+ will by default try to inherit synchronization from // an existing context. Turn that off. serviceConfig.Synchronization = SysES.SynchronizationOption.RequiresNew; SysES.ServiceDomain.Enter( serviceConfig ); this.createdDoubleServiceDomain = true; serviceConfig.Synchronization = SysES.SynchronizationOption.Required; serviceConfig.BringYourOwnSystemTransaction = newCurrent; } SysES.ServiceDomain.Enter( serviceConfig ); this.createdServiceDomain = true; } catch ( COMException e ) { if ( System.Transactions.Oletx.NativeMethods.XACT_E_NOTRANSACTION == e.ErrorCode ) { throw TransactionException.Create(SR.GetString(SR.TraceSourceBase), SR.GetString(SR.TransactionAlreadyOver), e, newCurrent == null ? Guid.Empty : newCurrent.DistributedTxId); } throw TransactionException.Create(SR.GetString(SR.TraceSourceBase), e.Message, e, newCurrent == null ? Guid.Empty : newCurrent.DistributedTxId); } finally { if ( !this.createdServiceDomain ) { // If we weren't successful in creating both service domains then // make sure to exit one of them. if ( this.createdDoubleServiceDomain ) { SysES.ServiceDomain.Leave(); } } } } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] // PushServiceDomain will only be called if a transaction scope is created with an // EnterpriseServicesInteropOption. TransactionScope constructors that take a ESIO are protected by // a FullTrust link demand. Therefore JitSafeLeaveServiceDomain is not exposed directly to a partial // trust caller. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2116:AptcaMethodsShouldOnlyCallAptcaMethods")] private void JitSafeLeaveServiceDomain() { if ( this.createdDoubleServiceDomain ) { // This is an ugly work around to a bug in Com+ that prevents the use of BYOT and SWC with // anything other than required synchronization. SysES.ServiceDomain.Leave(); } SysES.ServiceDomain.Leave(); } // RestoreCurrent // // Restore current to it's previous value depending on how it was changed for this scope. private void RestoreCurrent() { if ( this.createdServiceDomain ) { JitSafeLeaveServiceDomain(); } // Only restore the value that was actually in the context. this.threadContextData.CurrentTransaction = this.contextTransaction; } // ValidateInteropOption // // Validate a given interop Option private void ValidateInteropOption( EnterpriseServicesInteropOption interopOption ) { if ( interopOption < EnterpriseServicesInteropOption.None || interopOption > EnterpriseServicesInteropOption.Full ) { throw new ArgumentOutOfRangeException( "interopOption" ); } } // ValidateScopeTimeout // // Scope timeouts are not governed by MaxTimeout and therefore need a special validate function private void ValidateScopeTimeout( string paramName, TimeSpan scopeTimeout ) { if ( scopeTimeout < TimeSpan.Zero ) { throw new ArgumentOutOfRangeException( paramName ); } } private void ValidateAndSetAsyncFlowOption(TransactionScopeAsyncFlowOption asyncFlowOption) { if (asyncFlowOption < TransactionScopeAsyncFlowOption.Suppress || asyncFlowOption > TransactionScopeAsyncFlowOption.Enabled) { throw new ArgumentOutOfRangeException( "asyncFlowOption" ); } if (asyncFlowOption == TransactionScopeAsyncFlowOption.Enabled) { this.AsyncFlowEnabled = true; } } // The validate method assumes that the existing parent ambient transaction scope is already looked up. private void ValidateAsyncFlowOptionAndESInteropOption() { if (this.AsyncFlowEnabled) { EnterpriseServicesInteropOption currentInteropOption = this.interopOption; if ( !this.interopModeSpecified ) { // Transaction.InteropMode will take the interop mode on // for the scope in currentScope into account. currentInteropOption = Transaction.InteropMode(this.savedCurrentScope); } if (currentInteropOption != EnterpriseServicesInteropOption.None) { throw new NotSupportedException(SR.GetString(SR.AsyncFlowAndESInteropNotSupported)); } } } // Denotes the action to take when the scope is disposed. bool complete; internal bool ScopeComplete { get { return this.complete; } } // Storage location for the previous current transaction. Transaction savedCurrent; // To ensure that we don't restore a value for current that was // returned to us by an external entity keep the value that was actually // in TLS when the scope was created. Transaction contextTransaction; // Storage for the value to restore to current TransactionScope savedCurrentScope; // Store a reference to the context data object for this scope. ContextData threadContextData; ContextData savedTLSContextData; // Store a reference to the value that this scope expects for current Transaction expectedCurrent; // Store a reference to the committable form of this transaction if // the scope made one. CommittableTransaction committableTransaction; // Store a reference to the scopes transaction guard. DependentTransaction dependentTransaction; // Note when the scope is disposed. bool disposed; // Timer scopeTimer; // Store a reference to the thread on which the scope was created so that we can // check to make sure that the dispose pattern for scope is being used correctly. Thread scopeThread; // Store a member to let us know if a new service domain has been created for this // scope. bool createdServiceDomain; bool createdDoubleServiceDomain; // Store the interop mode for this transaction scope. bool interopModeSpecified = false; EnterpriseServicesInteropOption interopOption; internal EnterpriseServicesInteropOption InteropMode { get { return this.interopOption; } } internal ContextKey ContextKey { get; private set; } internal bool AsyncFlowEnabled { get; private set; } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using SDKTemplate; using System; using System.Collections.Generic; using System.Text; using Windows.Devices.Enumeration; using Windows.Devices.Midi; using Windows.Storage.Streams; using Windows.UI.Core; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace MIDI { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class Scenario2_ReceiveMIDIMessages : Page { /// <summary> /// Main Page /// </summary> private MainPage rootPage; /// <summary> /// Collection of active MidiInPorts /// </summary> private List<MidiInPort> midiInPorts; /// <summary> /// Device watcher for MIDI in ports /// </summary> MidiDeviceWatcher midiInDeviceWatcher; /// <summary> /// Set the rootpage context when entering the scenario /// </summary> /// <param name="e">Event arguments</param> protected override void OnNavigatedTo(NavigationEventArgs e) { this.rootPage = MainPage.Current; } /// <summary> /// Stop the device watcher when leaving the scenario /// </summary> /// <param name="e">Event arguments</param> protected override void OnNavigatedFrom(NavigationEventArgs e) { base.OnNavigatedFrom(e); // Stop the input device watcher this.midiInDeviceWatcher.Stop(); // Close all MidiInPorts foreach (MidiInPort inPort in this.midiInPorts) { inPort.Dispose(); } this.midiInPorts.Clear(); } /// <summary> /// Constructor: Start the device watcher /// </summary> public Scenario2_ReceiveMIDIMessages() { this.InitializeComponent(); // Initialize the list of active MIDI input devices this.midiInPorts = new List<MidiInPort>(); // Set up the MIDI input device watcher this.midiInDeviceWatcher = new MidiDeviceWatcher(MidiInPort.GetDeviceSelector(), Dispatcher, this.inputDevices); // Start watching for devices this.midiInDeviceWatcher.Start(); } /// <summary> /// Change the input MIDI device from which to receive messages /// </summary> /// <param name="sender">Element that fired the event</param> /// <param name="e">Event arguments</param> private async void inputDevices_SelectionChanged(object sender, SelectionChangedEventArgs e) { // Get the selected input MIDI device int selectedInputDeviceIndex = (sender as ListBox).SelectedIndex; // Try to create a MidiInPort if (selectedInputDeviceIndex < 0) { // Clear input device messages this.inputDeviceMessages.Items.Clear(); this.inputDeviceMessages.Items.Add("Select a MIDI input device to be able to see its messages"); this.inputDeviceMessages.IsEnabled = false; this.rootPage.NotifyUser("Select a MIDI input device to be able to see its messages", NotifyType.StatusMessage); return; } DeviceInformationCollection devInfoCollection = this.midiInDeviceWatcher.GetDeviceInformationCollection(); if (devInfoCollection == null) { this.inputDeviceMessages.Items.Clear(); this.inputDeviceMessages.Items.Add("Device not found!"); this.inputDeviceMessages.IsEnabled = false; this.rootPage.NotifyUser("Device not found!", NotifyType.ErrorMessage); return; } DeviceInformation devInfo = devInfoCollection[selectedInputDeviceIndex]; if (devInfo == null) { this.inputDeviceMessages.Items.Clear(); this.inputDeviceMessages.Items.Add("Device not found!"); this.inputDeviceMessages.IsEnabled = false; this.rootPage.NotifyUser("Device not found!", NotifyType.ErrorMessage); return; } var currentMidiInputDevice = await MidiInPort.FromIdAsync(devInfo.Id); if (currentMidiInputDevice == null) { this.rootPage.NotifyUser("Unable to create MidiInPort from input device", NotifyType.ErrorMessage); return; } // We have successfully created a MidiInPort; add the device to the list of active devices, and set up message receiving if (!this.midiInPorts.Contains(currentMidiInputDevice)) { this.midiInPorts.Add(currentMidiInputDevice); currentMidiInputDevice.MessageReceived += MidiInputDevice_MessageReceived; } // Clear any previous input messages this.inputDeviceMessages.Items.Clear(); this.inputDeviceMessages.IsEnabled = true; this.rootPage.NotifyUser("Input Device selected successfully! Waiting for messages...", NotifyType.StatusMessage); } /// <summary> /// Display the received MIDI message in a readable format /// </summary> /// <param name="sender">Element that fired the event</param> /// <param name="args">The received message</param> private async void MidiInputDevice_MessageReceived(MidiInPort sender, MidiMessageReceivedEventArgs args) { IMidiMessage receivedMidiMessage = args.Message; // Build the received MIDI message into a readable format StringBuilder outputMessage = new StringBuilder(); outputMessage.Append(receivedMidiMessage.Timestamp.ToString()).Append(", Type: ").Append(receivedMidiMessage.Type); // Add MIDI message parameters to the output, depending on the type of message switch (receivedMidiMessage.Type) { case MidiMessageType.NoteOff: var noteOffMessage = (MidiNoteOffMessage)receivedMidiMessage; outputMessage.Append(", Channel: ").Append(noteOffMessage.Channel).Append(", Note: ").Append(noteOffMessage.Note).Append(", Velocity: ").Append(noteOffMessage.Velocity); break; case MidiMessageType.NoteOn: var noteOnMessage = (MidiNoteOnMessage)receivedMidiMessage; outputMessage.Append(", Channel: ").Append(noteOnMessage.Channel).Append(", Note: ").Append(noteOnMessage.Note).Append(", Velocity: ").Append(noteOnMessage.Velocity); break; case MidiMessageType.PolyphonicKeyPressure: var polyphonicKeyPressureMessage = (MidiPolyphonicKeyPressureMessage)receivedMidiMessage; outputMessage.Append(", Channel: ").Append(polyphonicKeyPressureMessage.Channel).Append(", Note: ").Append(polyphonicKeyPressureMessage.Note).Append(", Pressure: ").Append(polyphonicKeyPressureMessage.Pressure); break; case MidiMessageType.ControlChange: var controlChangeMessage = (MidiControlChangeMessage)receivedMidiMessage; outputMessage.Append(", Channel: ").Append(controlChangeMessage.Channel).Append(", Controller: ").Append(controlChangeMessage.Controller).Append(", Value: ").Append(controlChangeMessage.ControlValue); break; case MidiMessageType.ProgramChange: var programChangeMessage = (MidiProgramChangeMessage)receivedMidiMessage; outputMessage.Append(", Channel: ").Append(programChangeMessage.Channel).Append(", Program: ").Append(programChangeMessage.Program); break; case MidiMessageType.ChannelPressure: var channelPressureMessage = (MidiChannelPressureMessage)receivedMidiMessage; outputMessage.Append(", Channel: ").Append(channelPressureMessage.Channel).Append(", Pressure: ").Append(channelPressureMessage.Pressure); break; case MidiMessageType.PitchBendChange: var pitchBendChangeMessage = (MidiPitchBendChangeMessage)receivedMidiMessage; outputMessage.Append(", Channel: ").Append(pitchBendChangeMessage.Channel).Append(", Bend: ").Append(pitchBendChangeMessage.Bend); break; case MidiMessageType.SystemExclusive: var systemExclusiveMessage = (MidiSystemExclusiveMessage)receivedMidiMessage; outputMessage.Append(", "); // Read the SysEx bufffer var sysExDataReader = DataReader.FromBuffer(systemExclusiveMessage.RawData); while (sysExDataReader.UnconsumedBufferLength > 0) { byte byteRead = sysExDataReader.ReadByte(); // Pad with leading zero if necessary outputMessage.Append(byteRead.ToString("X2")).Append(" "); } break; case MidiMessageType.MidiTimeCode: var timeCodeMessage = (MidiTimeCodeMessage)receivedMidiMessage; outputMessage.Append(", FrameType: ").Append(timeCodeMessage.FrameType).Append(", Values: ").Append(timeCodeMessage.Values); break; case MidiMessageType.SongPositionPointer: var songPositionPointerMessage = (MidiSongPositionPointerMessage)receivedMidiMessage; outputMessage.Append(", Beats: ").Append(songPositionPointerMessage.Beats); break; case MidiMessageType.SongSelect: var songSelectMessage = (MidiSongSelectMessage)receivedMidiMessage; outputMessage.Append(", Song: ").Append(songSelectMessage.Song); break; case MidiMessageType.TuneRequest: var tuneRequestMessage = (MidiTuneRequestMessage)receivedMidiMessage; break; case MidiMessageType.TimingClock: var timingClockMessage = (MidiTimingClockMessage)receivedMidiMessage; break; case MidiMessageType.Start: var startMessage = (MidiStartMessage)receivedMidiMessage; break; case MidiMessageType.Continue: var continueMessage = (MidiContinueMessage)receivedMidiMessage; break; case MidiMessageType.Stop: var stopMessage = (MidiStopMessage)receivedMidiMessage; break; case MidiMessageType.ActiveSensing: var activeSensingMessage = (MidiActiveSensingMessage)receivedMidiMessage; break; case MidiMessageType.SystemReset: var systemResetMessage = (MidiSystemResetMessage)receivedMidiMessage; break; case MidiMessageType.None: throw new InvalidOperationException(); default: break; } // Use the Dispatcher to update the messages on the UI thread await Dispatcher.RunAsync(CoreDispatcherPriority.High, () => { // Skip TimingClock and ActiveSensing messages to avoid overcrowding the list. Commment this check out to see all messages if ((receivedMidiMessage.Type != MidiMessageType.TimingClock) && (receivedMidiMessage.Type != MidiMessageType.ActiveSensing)) { this.inputDeviceMessages.Items.Add(outputMessage + "\n"); this.inputDeviceMessages.ScrollIntoView(this.inputDeviceMessages.Items[this.inputDeviceMessages.Items.Count - 1]); this.rootPage.NotifyUser("Message received successfully!", NotifyType.StatusMessage); } }); } } }
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Configuration; namespace Orleans.Runtime { /// <summary> /// Identifies activations that have been idle long enough to be deactivated. /// </summary> internal class ActivationCollector : IActivationCollector { internal Action<GrainId> Debug_OnDecideToCollectActivation; private readonly TimeSpan quantum; private readonly TimeSpan shortestAgeLimit; private readonly ConcurrentDictionary<DateTime, Bucket> buckets; private readonly object nextTicketLock; private DateTime nextTicket; private static readonly List<ActivationData> nothing = new List<ActivationData> { Capacity = 0 }; private readonly ILogger logger; public ActivationCollector(IOptions<GrainCollectionOptions> options, ILogger<ActivationCollector> logger) { quantum = options.Value.CollectionQuantum; shortestAgeLimit = TimeSpan.FromTicks(options.Value.ClassSpecificCollectionAge.Values .Aggregate(options.Value.CollectionAge.Ticks, (a,v) => Math.Min(a,v.Ticks))); buckets = new ConcurrentDictionary<DateTime, Bucket>(); nextTicket = MakeTicketFromDateTime(DateTime.UtcNow); nextTicketLock = new object(); this.logger = logger; } public TimeSpan Quantum { get { return quantum; } } private int ApproximateCount { get { int sum = 0; foreach (var bucket in buckets.Values) { sum += bucket.ApproximateCount; } return sum; } } // Return the number of activations that were used (touched) in the last recencyPeriod. public int GetNumRecentlyUsed(TimeSpan recencyPeriod) { var now = DateTime.UtcNow; int sum = 0; foreach (var bucket in buckets) { // Ticket is the date time when this bucket should be collected (last touched time plus age limit) // For now we take the shortest age limit as an approximation of the per-type age limit. DateTime ticket = bucket.Key; var timeTillCollection = ticket - now; var timeSinceLastUsed = shortestAgeLimit - timeTillCollection; if (timeSinceLastUsed <= recencyPeriod) { sum += bucket.Value.ApproximateCount; } } return sum; } public void ScheduleCollection(ActivationData item) { lock (item) { if (item.IsExemptFromCollection) { return; } TimeSpan timeout = item.CollectionAgeLimit; DateTime ticket = MakeTicketFromTimeSpan(timeout); if (default(DateTime) != item.CollectionTicket) { throw new InvalidOperationException("Call CancelCollection before calling ScheduleCollection."); } Add(item, ticket); } } public bool TryCancelCollection(ActivationData item) { if (item.IsExemptFromCollection) return false; lock (item) { DateTime ticket = item.CollectionTicket; if (default(DateTime) == ticket) return false; if (IsExpired(ticket)) return false; // first, we attempt to remove the ticket. Bucket bucket; if (!buckets.TryGetValue(ticket, out bucket) || !bucket.TryRemove(item)) return false; } return true; } public bool TryRescheduleCollection(ActivationData item) { if (item.IsExemptFromCollection) return false; lock (item) { if (TryRescheduleCollection_Impl(item, item.CollectionAgeLimit)) return true; item.ResetCollectionTicket(); return false; } } private bool TryRescheduleCollection_Impl(ActivationData item, TimeSpan timeout) { // note: we expect the activation lock to be held. if (default(DateTime) == item.CollectionTicket) return false; ThrowIfTicketIsInvalid(item.CollectionTicket); if (IsExpired(item.CollectionTicket)) return false; DateTime oldTicket = item.CollectionTicket; DateTime newTicket = MakeTicketFromTimeSpan(timeout); // if the ticket value doesn't change, then the source and destination bucket are the same and there's nothing to do. if (newTicket.Equals(oldTicket)) return true; Bucket bucket; if (!buckets.TryGetValue(oldTicket, out bucket) || !bucket.TryRemove(item)) { // fail: item is not associated with currentKey. return false; } // it shouldn't be possible for Add to throw an exception here, as only one concurrent competitor should be able to reach to this point in the method. item.ResetCollectionTicket(); Add(item, newTicket); return true; } private bool DequeueQuantum(out IEnumerable<ActivationData> items, DateTime now) { DateTime key; lock (nextTicketLock) { if (nextTicket > now) { items = null; return false; } key = nextTicket; nextTicket += quantum; } Bucket bucket; if (!buckets.TryRemove(key, out bucket)) { items = nothing; return true; } items = bucket.CancelAll(); return true; } public override string ToString() { var now = DateTime.UtcNow; return string.Format("<#Activations={0}, #Buckets={1}, buckets={2}>", ApproximateCount, buckets.Count, Utils.EnumerableToString( buckets.Values.OrderBy(bucket => bucket.Key), bucket => Utils.TimeSpanToString(bucket.Key - now) + "->" + bucket.ApproximateCount + " items")); } /// <summary> /// Scans for activations that are due for collection. /// </summary> /// <returns>A list of activations that are due for collection.</returns> public List<ActivationData> ScanStale() { var now = DateTime.UtcNow; List<ActivationData> result = null; IEnumerable<ActivationData> activations; while (DequeueQuantum(out activations, now)) { // at this point, all tickets associated with activations are cancelled and any attempts to reschedule will fail silently. if the activation is to be reactivated, it's our job to clear the activation's copy of the ticket. foreach (var activation in activations) { lock (activation) { activation.ResetCollectionTicket(); if (activation.State != ActivationState.Valid) { // Do nothing: don't collect, don't reschedule. // The activation can't be in Created or Activating, since we only ScheduleCollection after successfull activation. // If the activation is already in Deactivating or Invalid state, its already being collected or was collected // (both mean a bug, this activation should not be in the collector) // So in any state except for Valid we should just not collect and not reschedule. logger.Warn(ErrorCode.Catalog_ActivationCollector_BadState_1, "ActivationCollector found an activation in a non Valid state. All activation inside the ActivationCollector should be in Valid state. Activation: {0}", activation.ToDetailedString()); } else if (activation.ShouldBeKeptAlive) { // Consider: need to reschedule to what is the remaining time for ShouldBeKeptAlive, not the full CollectionAgeLimit. ScheduleCollection(activation); } else if (!activation.IsInactive) { // This is essentialy a bug, an active activation should not be in the last bucket. logger.Warn(ErrorCode.Catalog_ActivationCollector_BadState_2, "ActivationCollector found an active activation in it's last bucket. This is violation of ActivationCollector invariants. " + "For now going to defer it's collection. Activation: {0}", activation.ToDetailedString()); ScheduleCollection(activation); } else if (!activation.IsStale(now)) { // This is essentialy a bug, a non stale activation should not be in the last bucket. logger.Warn(ErrorCode.Catalog_ActivationCollector_BadState_3, "ActivationCollector found a non stale activation in it's last bucket. This is violation of ActivationCollector invariants. Now: {0}" + "For now going to defer it's collection. Activation: {1}", LogFormatter.PrintDate(now), activation.ToDetailedString()); ScheduleCollection(activation); } else { // Atomically set Deactivating state, to disallow any new requests or new timer ticks to be dispatched on this activation. activation.PrepareForDeactivation(); DecideToCollectActivation(activation, ref result); } } } } return result ?? nothing; } /// <summary> /// Scans for activations that have been idle for the specified age limit. /// </summary> /// <param name="ageLimit">The age limit.</param> /// <returns></returns> public List<ActivationData> ScanAll(TimeSpan ageLimit) { List<ActivationData> result = null; var now = DateTime.UtcNow; int bucketCount = buckets.Count; int i = 0; foreach (var bucket in buckets.Values) { if (i >= bucketCount) break; int notToExceed = bucket.ApproximateCount; int j = 0; foreach (var activation in bucket) { // theoretically, we could iterate forever on the ConcurrentDictionary. we limit ourselves to an approximation of the bucket's Count property to limit the number of iterations we perform. if (j >= notToExceed) break; lock (activation) { if (activation.State != ActivationState.Valid) { // Do nothing: don't collect, don't reschedule. } else if (activation.ShouldBeKeptAlive) { // do nothing } else if (!activation.IsInactive) { // do nothing } else { if (activation.GetIdleness(now) >= ageLimit) { if (bucket.TryRemove(activation)) { // we removed the activation from the collector. it's our responsibility to deactivate it. activation.PrepareForDeactivation(); DecideToCollectActivation(activation, ref result); } // someone else has already deactivated the activation, so there's nothing to do. } else { // activation is not idle long enough for collection. do nothing. } } } ++j; } ++i; } return result ?? nothing; } private void DecideToCollectActivation(ActivationData activation, ref List<ActivationData> condemned) { if (null == condemned) { condemned = new List<ActivationData> { activation }; } else { condemned.Add(activation); } this.Debug_OnDecideToCollectActivation?.Invoke(activation.Grain); } private static void ThrowIfTicketIsInvalid(DateTime ticket, TimeSpan quantum) { ThrowIfDefault(ticket, "ticket"); if (0 != ticket.Ticks % quantum.Ticks) { throw new ArgumentException(string.Format("invalid ticket ({0})", ticket)); } } private void ThrowIfTicketIsInvalid(DateTime ticket) { ThrowIfTicketIsInvalid(ticket, quantum); } private void ThrowIfExemptFromCollection(ActivationData activation, string name) { if (activation.IsExemptFromCollection) { throw new ArgumentException(string.Format("{0} should not refer to a system target or system grain.", name), name); } } private bool IsExpired(DateTime ticket) { return ticket < nextTicket; } private DateTime MakeTicketFromDateTime(DateTime timestamp) { // round the timestamp to the next quantum. e.g. if the quantum is 1 minute and the timestamp is 3:45:22, then the ticket will be 3:46. note that TimeStamp.Ticks and DateTime.Ticks both return a long. DateTime ticket = new DateTime(((timestamp.Ticks - 1) / quantum.Ticks + 1) * quantum.Ticks); if (ticket < nextTicket) { throw new ArgumentException(string.Format("The earliest collection that can be scheduled from now is for {0}", new DateTime(nextTicket.Ticks - quantum.Ticks + 1))); } return ticket; } private DateTime MakeTicketFromTimeSpan(TimeSpan timeout) { if (timeout < quantum) { throw new ArgumentException(String.Format("timeout must be at least {0}, but it is {1}", quantum, timeout), "timeout"); } return MakeTicketFromDateTime(DateTime.UtcNow + timeout); } private void Add(ActivationData item, DateTime ticket) { // note: we expect the activation lock to be held. item.ResetCollectionCancelledFlag(); Bucket bucket = buckets.GetOrAdd( ticket, key => new Bucket(key, quantum)); bucket.Add(item); item.SetCollectionTicket(ticket); } static private void ThrowIfDefault<T>(T value, string name) where T : IEquatable<T> { if (value.Equals(default(T))) { throw new ArgumentException(string.Format("default({0}) is not allowed in this context.", typeof(T).Name), name); } } private class Bucket : IEnumerable<ActivationData> { private readonly DateTime key; private readonly ConcurrentDictionary<ActivationId, ActivationData> items; public DateTime Key { get { return key; } } public int ApproximateCount { get { return items.Count; } } public Bucket(DateTime key, TimeSpan quantum) { ThrowIfTicketIsInvalid(key, quantum); this.key = key; items = new ConcurrentDictionary<ActivationId, ActivationData>(); } public void Add(ActivationData item) { if (!items.TryAdd(item.ActivationId, item)) { throw new InvalidOperationException("item is already associated with this bucket"); } } public bool TryRemove(ActivationData item) { if (!item.TrySetCollectionCancelledFlag()) return false; return items.TryRemove(item.ActivationId, out ActivationData unused); } public IEnumerable<ActivationData> CancelAll() { List<ActivationData> result = null; foreach (var pair in items) { // attempt to cancel the item. if we succeed, it wasn't already cancelled and we can return it. otherwise, we silently ignore it. if (pair.Value.TrySetCollectionCancelledFlag()) { if (result == null) { // we only need to ensure there's enough space left for this element and any potential entries. result = new List<ActivationData>(); } result.Add(pair.Value); } } return result ?? nothing; } public IEnumerator<ActivationData> GetEnumerator() { return items.Values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } }
// 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.CodeAnalysis; using System.Security.Permissions; namespace System.ComponentModel.Design.Serialization { /// <summary> /// A member relationship service is used by a serializer to announce that one /// property is related to a property on another object. Consider a code /// based serialization scheme where code is of the following form: /// /// object1.Property1 = object2.Property2 /// /// Upon interpretation of this code, Property1 on object1 will be /// set to the return value of object2.Property2. But the relationship /// between these two objects is lost. Serialization schemes that /// wish to maintain this relationship may install a MemberRelationshipService /// into the serialization manager. When an object is deserialized /// this service will be notified of these relationships. It is up to the service /// to act on these notifications if it wishes. During serialization, the /// service is also consulted. If a relationship exists the same /// relationship is maintained by the serializer. /// </summary> public abstract class MemberRelationshipService { private Dictionary<RelationshipEntry, RelationshipEntry> _relationships = new Dictionary<RelationshipEntry, RelationshipEntry>(); /// <summary> /// Returns the current relationship associated with the source, or MemberRelationship.Empty if /// there is no relationship. Also sets a relationship between two objects. Empty /// can also be passed as the property value, in which case the relationship will /// be cleared. /// </summary> [SuppressMessage("Microsoft.Design", "CA1043:UseIntegralOrStringArgumentForIndexers")] public MemberRelationship this[MemberRelationship source] { get { if (source.Owner == null) throw new ArgumentNullException("Owner"); if (source.Member == null) throw new ArgumentNullException("Member"); return GetRelationship(source); } set { if (source.Owner == null) throw new ArgumentNullException("Owner"); if (source.Member == null) throw new ArgumentNullException("Member"); SetRelationship(source, value); } } /// <summary> /// Returns the current relationship associated with the source, or null if /// there is no relationship. Also sets a relationship between two objects. Null /// can be passed as the property value, in which case the relationship will /// be cleared. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1023:IndexersShouldNotBeMultidimensional")] public MemberRelationship this[object sourceOwner, MemberDescriptor sourceMember] { get { if (sourceOwner == null) throw new ArgumentNullException(nameof(sourceOwner)); if (sourceMember == null) throw new ArgumentNullException(nameof(sourceMember)); return GetRelationship(new MemberRelationship(sourceOwner, sourceMember)); } set { if (sourceOwner == null) throw new ArgumentNullException(nameof(sourceOwner)); if (sourceMember == null) throw new ArgumentNullException(nameof(sourceMember)); SetRelationship(new MemberRelationship(sourceOwner, sourceMember), value); } } /// <summary> /// This is the implementation API for returning relationships. The default implementation stores the /// relationship in a table. Relationships are stored weakly, so they do not keep an object alive. /// </summary> protected virtual MemberRelationship GetRelationship(MemberRelationship source) { RelationshipEntry retVal; if (_relationships != null && _relationships.TryGetValue(new RelationshipEntry(source), out retVal) && retVal.Owner.IsAlive) { return new MemberRelationship(retVal.Owner.Target, retVal.Member); } return MemberRelationship.Empty; } /// <summary> /// This is the implementation API for returning relationships. The default implementation stores the /// relationship in a table. Relationships are stored weakly, so they do not keep an object alive. Empty can be /// passed in for relationship to remove the relationship. /// </summary> protected virtual void SetRelationship(MemberRelationship source, MemberRelationship relationship) { if (!relationship.IsEmpty && !SupportsRelationship(source, relationship)) { string sourceName = TypeDescriptor.GetComponentName(source.Owner); string relName = TypeDescriptor.GetComponentName(relationship.Owner); if (sourceName == null) { sourceName = source.Owner.ToString(); } if (relName == null) { relName = relationship.Owner.ToString(); } throw new ArgumentException(SR.Format(SR.MemberRelationshipService_RelationshipNotSupported, sourceName, source.Member.Name, relName, relationship.Member.Name)); } if (_relationships == null) { _relationships = new Dictionary<RelationshipEntry, RelationshipEntry>(); } _relationships[new RelationshipEntry(source)] = new RelationshipEntry(relationship); } /// <summary> /// Returns true if the provided relationship is supported. /// </summary> public abstract bool SupportsRelationship(MemberRelationship source, MemberRelationship relationship); /// <summary> /// Used as storage in our relationship table /// </summary> private struct RelationshipEntry { internal WeakReference Owner; internal MemberDescriptor Member; private int _hashCode; internal RelationshipEntry(MemberRelationship rel) { Owner = new WeakReference(rel.Owner); Member = rel.Member; _hashCode = rel.Owner == null ? 0 : rel.Owner.GetHashCode(); } public override bool Equals(object o) { if (o is RelationshipEntry) { RelationshipEntry e = (RelationshipEntry)o; return this == e; } return false; } public static bool operator ==(RelationshipEntry re1, RelationshipEntry re2) { object owner1 = (re1.Owner.IsAlive ? re1.Owner.Target : null); object owner2 = (re2.Owner.IsAlive ? re2.Owner.Target : null); return owner1 == owner2 && re1.Member.Equals(re2.Member); } public static bool operator !=(RelationshipEntry re1, RelationshipEntry re2) { return !(re1 == re2); } public override int GetHashCode() { return _hashCode; } } } /// <summary> /// This class represents a single relationship between an object and a member. /// </summary> public readonly struct MemberRelationship { public static readonly MemberRelationship Empty = new MemberRelationship(); /// <summary> /// Creates a new member relationship. /// </summary> public MemberRelationship(object owner, MemberDescriptor member) { if (owner == null) throw new ArgumentNullException(nameof(owner)); if (member == null) throw new ArgumentNullException(nameof(member)); Owner = owner; Member = member; } /// <summary> /// Returns true if this relationship is empty. /// </summary> public bool IsEmpty => Owner == null; /// <summary> /// The member in this relationship. /// </summary> public MemberDescriptor Member { get; } /// <summary> /// The object owning the member. /// </summary> public object Owner { get; } /// <summary> /// Infrastructure support to make this a first class struct /// </summary> public override bool Equals(object obj) { if (!(obj is MemberRelationship)) return false; MemberRelationship rel = (MemberRelationship)obj; return rel.Owner == Owner && rel.Member == Member; } /// <summary> /// Infrastructure support to make this a first class struct /// </summary> public override int GetHashCode() { if (Owner == null) return base.GetHashCode(); return Owner.GetHashCode() ^ Member.GetHashCode(); } /// <summary> /// Infrastructure support to make this a first class struct /// </summary> public static bool operator ==(MemberRelationship left, MemberRelationship right) { return left.Owner == right.Owner && left.Member == right.Member; } /// <summary> /// Infrastructure support to make this a first class struct /// </summary> public static bool operator !=(MemberRelationship left, MemberRelationship right) { return !(left == right); } } }
/** * 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 System.Threading; using Thrift.Collections; using Thrift.Protocol; using Thrift.Transport; namespace Thrift.Server { /// <summary> /// Server that uses C# threads (as opposed to the ThreadPool) when handling requests /// </summary> public class TThreadedServer : TServer { private const int DEFAULT_MAX_THREADS = 100; private volatile bool stop = false; private readonly int maxThreads; private Queue<TTransport> clientQueue; private THashSet<Thread> clientThreads; private object clientLock; private Thread workerThread; public int ClientThreadsCount { get { return clientThreads.Count; } } public TThreadedServer(TProcessor processor, TServerTransport serverTransport) : this(new TSingletonProcessorFactory(processor), serverTransport, new TTransportFactory(), new TTransportFactory(), new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(), DEFAULT_MAX_THREADS, DefaultLogDelegate) { } public TThreadedServer(TProcessor processor, TServerTransport serverTransport, LogDelegate logDelegate) : this(new TSingletonProcessorFactory(processor), serverTransport, new TTransportFactory(), new TTransportFactory(), new TBinaryProtocol.Factory(), new TBinaryProtocol.Factory(), DEFAULT_MAX_THREADS, logDelegate) { } public TThreadedServer(TProcessor processor, TServerTransport serverTransport, TTransportFactory transportFactory, TProtocolFactory protocolFactory) : this(new TSingletonProcessorFactory(processor), serverTransport, transportFactory, transportFactory, protocolFactory, protocolFactory, DEFAULT_MAX_THREADS, DefaultLogDelegate) { } public TThreadedServer(TProcessorFactory processorFactory, TServerTransport serverTransport, TTransportFactory transportFactory, TProtocolFactory protocolFactory) : this(processorFactory, serverTransport, transportFactory, transportFactory, protocolFactory, protocolFactory, DEFAULT_MAX_THREADS, DefaultLogDelegate) { } public TThreadedServer(TProcessorFactory processorFactory, TServerTransport serverTransport, TTransportFactory inputTransportFactory, TTransportFactory outputTransportFactory, TProtocolFactory inputProtocolFactory, TProtocolFactory outputProtocolFactory, int maxThreads, LogDelegate logDel) : base(processorFactory, serverTransport, inputTransportFactory, outputTransportFactory, inputProtocolFactory, outputProtocolFactory, logDel) { this.maxThreads = maxThreads; clientQueue = new Queue<TTransport>(); clientLock = new object(); clientThreads = new THashSet<Thread>(); } /// <summary> /// Use new Thread for each new client connection. block until numConnections < maxThreads /// </summary> public override void Serve() { try { //start worker thread workerThread = new Thread(new ThreadStart(Execute)); workerThread.Start(); serverTransport.Listen(); } catch (TTransportException ttx) { logDelegate("Error, could not listen on ServerTransport: " + ttx); return; } //Fire the preServe server event when server is up but before any client connections if (serverEventHandler != null) serverEventHandler.preServe(); while (!stop) { int failureCount = 0; try { TTransport client = serverTransport.Accept(); lock (clientLock) { clientQueue.Enqueue(client); Monitor.Pulse(clientLock); } } catch (TTransportException ttx) { if (!stop || ttx.Type != TTransportException.ExceptionType.Interrupted) { ++failureCount; logDelegate(ttx.ToString()); } } } if (stop) { try { serverTransport.Close(); } catch (TTransportException ttx) { logDelegate("TServeTransport failed on close: " + ttx.Message); } stop = false; } } /// <summary> /// Loops on processing a client forever /// threadContext will be a TTransport instance /// </summary> /// <param name="threadContext"></param> private void Execute() { while (!stop) { TTransport client; Thread t; lock (clientLock) { //don't dequeue if too many connections while (clientThreads.Count >= maxThreads) { Monitor.Wait(clientLock); } while (clientQueue.Count == 0) { Monitor.Wait(clientLock); } client = clientQueue.Dequeue(); t = new Thread(new ParameterizedThreadStart(ClientWorker)); clientThreads.Add(t); } //start processing requests from client on new thread t.Start(client); } } private void ClientWorker(Object context) { using( TTransport client = (TTransport)context) { TProcessor processor = processorFactory.GetProcessor(client); TTransport inputTransport = null; TTransport outputTransport = null; TProtocol inputProtocol = null; TProtocol outputProtocol = null; Object connectionContext = null; try { try { inputTransport = inputTransportFactory.GetTransport(client); outputTransport = outputTransportFactory.GetTransport(client); inputProtocol = inputProtocolFactory.GetProtocol(inputTransport); outputProtocol = outputProtocolFactory.GetProtocol(outputTransport); //Recover event handler (if any) and fire createContext server event when a client connects if (serverEventHandler != null) connectionContext = serverEventHandler.createContext(inputProtocol, outputProtocol); //Process client requests until client disconnects while (!stop) { if (!inputTransport.Peek()) break; //Fire processContext server event //N.B. This is the pattern implemented in C++ and the event fires provisionally. //That is to say it may be many minutes between the event firing and the client request //actually arriving or the client may hang up without ever makeing a request. if (serverEventHandler != null) serverEventHandler.processContext(connectionContext, inputTransport); //Process client request (blocks until transport is readable) if (!processor.Process(inputProtocol, outputProtocol)) break; } } catch (TTransportException) { //Usually a client disconnect, expected } catch (Exception x) { //Unexpected logDelegate("Error: " + x); } //Fire deleteContext server event after client disconnects if (serverEventHandler != null) serverEventHandler.deleteContext(connectionContext, inputProtocol, outputProtocol); lock (clientLock) { clientThreads.Remove(Thread.CurrentThread); Monitor.Pulse(clientLock); } } finally { //Close transports if (inputTransport != null) inputTransport.Close(); if (outputTransport != null) outputTransport.Close(); // disposable stuff should be disposed if (inputProtocol != null) inputProtocol.Dispose(); if (outputProtocol != null) outputProtocol.Dispose(); } } } public override void Stop() { stop = true; serverTransport.Close(); //clean up all the threads myself workerThread.Abort(); foreach (Thread t in clientThreads) { t.Abort(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Globalization; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Threading; using System.Transactions.Configuration; using System.Transactions.Diagnostics; using System.Transactions.Distributed; namespace System.Transactions { public delegate Transaction HostCurrentTransactionCallback(); public delegate void TransactionStartedEventHandler(object sender, TransactionEventArgs e); public static class TransactionManager { // Revovery Information Version private const int RecoveryInformationVersion1 = 1; private const int CurrentRecoveryVersion = RecoveryInformationVersion1; // Hashtable of promoted transactions, keyed by identifier guid. This is used by // FindPromotedTransaction to support transaction equivalence when a transaction is // serialized and then deserialized back in this app-domain. // Double-checked locking pattern requires volatile for read/write synchronization private static volatile Hashtable s_promotedTransactionTable; // Sorted Table of transaction timeouts // Double-checked locking pattern requires volatile for read/write synchronization private static volatile TransactionTable s_transactionTable; private static TransactionStartedEventHandler s_distributedTransactionStartedDelegate; public static event TransactionStartedEventHandler DistributedTransactionStarted { add { lock (ClassSyncObject) { s_distributedTransactionStartedDelegate = (TransactionStartedEventHandler)System.Delegate.Combine(s_distributedTransactionStartedDelegate, value); if (value != null) { ProcessExistingTransactions(value); } } } remove { lock (ClassSyncObject) { s_distributedTransactionStartedDelegate = (TransactionStartedEventHandler)System.Delegate.Remove(s_distributedTransactionStartedDelegate, value); } } } internal static void ProcessExistingTransactions(TransactionStartedEventHandler eventHandler) { lock (PromotedTransactionTable) { // Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations. IDictionaryEnumerator e = PromotedTransactionTable.GetEnumerator(); while (e.MoveNext()) { WeakReference weakRef = (WeakReference)e.Value; Transaction tx = (Transaction)weakRef.Target; if (tx != null) { TransactionEventArgs args = new TransactionEventArgs(); args._transaction = tx.InternalClone(); eventHandler(args._transaction, args); } } } } internal static void FireDistributedTransactionStarted(Transaction transaction) { TransactionStartedEventHandler localStartedEventHandler = null; lock (ClassSyncObject) { localStartedEventHandler = s_distributedTransactionStartedDelegate; } if (null != localStartedEventHandler) { TransactionEventArgs args = new TransactionEventArgs(); args._transaction = transaction.InternalClone(); localStartedEventHandler(args._transaction, args); } } // Data storage for current delegate internal static HostCurrentTransactionCallback s_currentDelegate = null; internal static bool s_currentDelegateSet = false; // CurrentDelegate // // Store a delegate to be used to query for an external current transaction. public static HostCurrentTransactionCallback HostCurrentCallback { // get_HostCurrentCallback is used from get_CurrentTransaction, which doesn't have any permission requirements. // We don't expose what is returned from this property in that case. But we don't want just anybody being able // to retrieve the value. get { // Note do not add trace notifications to this method. It is called // at the startup of SQLCLR and tracing has too much working set overhead. return s_currentDelegate; } set { // Note do not add trace notifications to this method. It is called // at the startup of SQLCLR and tracing has too much working set overhead. if (value == null) { throw new ArgumentNullException(nameof(value)); } lock (ClassSyncObject) { if (s_currentDelegateSet) { throw new InvalidOperationException(SR.CurrentDelegateSet); } s_currentDelegateSet = true; } s_currentDelegate = value; } } public static Enlistment Reenlist( Guid resourceManagerIdentifier, byte[] recoveryInformation, IEnlistmentNotification enlistmentNotification) { if (resourceManagerIdentifier == Guid.Empty) { throw new ArgumentException(SR.BadResourceManagerId, nameof(resourceManagerIdentifier)); } if (null == recoveryInformation) { throw new ArgumentNullException(nameof(recoveryInformation)); } if (null == enlistmentNotification) { throw new ArgumentNullException(nameof(enlistmentNotification)); } if (DiagnosticTrace.Verbose) { MethodEnteredTraceRecord.Trace(SR.TraceSourceBase, "TransactionManager.Reenlist"); } if (DiagnosticTrace.Information) { ReenlistTraceRecord.Trace(SR.TraceSourceBase, resourceManagerIdentifier); } // Put the recovery information into a stream. MemoryStream stream = new MemoryStream(recoveryInformation); int recoveryInformationVersion = 0; string nodeName = null; byte[] resourceManagerRecoveryInformation = null; try { BinaryReader reader = new BinaryReader(stream); recoveryInformationVersion = reader.ReadInt32(); if (recoveryInformationVersion == TransactionManager.RecoveryInformationVersion1) { nodeName = reader.ReadString(); resourceManagerRecoveryInformation = reader.ReadBytes(recoveryInformation.Length - checked((int)stream.Position)); } else { if (DiagnosticTrace.Error) { TransactionExceptionTraceRecord.Trace(SR.TraceSourceBase, SR.UnrecognizedRecoveryInformation); } throw new ArgumentException(SR.UnrecognizedRecoveryInformation, nameof(recoveryInformation)); } } catch (EndOfStreamException e) { if (DiagnosticTrace.Error) { TransactionExceptionTraceRecord.Trace(SR.TraceSourceBase, SR.UnrecognizedRecoveryInformation); } throw new ArgumentException(SR.UnrecognizedRecoveryInformation, nameof(recoveryInformation), e); } catch (FormatException e) { if (DiagnosticTrace.Error) { TransactionExceptionTraceRecord.Trace(SR.TraceSourceBase, SR.UnrecognizedRecoveryInformation); } throw new ArgumentException(SR.UnrecognizedRecoveryInformation, nameof(recoveryInformation), e); } finally { stream.Dispose(); } DistributedTransactionManager transactionManager = CheckTransactionManager(nodeName); // Now ask the Transaction Manager to reenlist. object syncRoot = new object(); Enlistment returnValue = new Enlistment(enlistmentNotification, syncRoot); EnlistmentState.EnlistmentStatePromoted.EnterState(returnValue.InternalEnlistment); returnValue.InternalEnlistment.PromotedEnlistment = transactionManager.ReenlistTransaction( resourceManagerIdentifier, resourceManagerRecoveryInformation, (RecoveringInternalEnlistment)returnValue.InternalEnlistment ); if (DiagnosticTrace.Verbose) { MethodExitedTraceRecord.Trace(SR.TraceSourceBase, "TransactionManager.Reenlist" ); } return returnValue; } private static DistributedTransactionManager CheckTransactionManager(string nodeName) { DistributedTransactionManager tm = DistributedTransactionManager; if (!((tm.NodeName == null && (nodeName == null || nodeName.Length == 0)) || (tm.NodeName != null && tm.NodeName.Equals(nodeName)))) { throw new ArgumentException(SR.InvalidRecoveryInformation, "recoveryInformation"); } return tm; } public static void RecoveryComplete(Guid resourceManagerIdentifier) { if (resourceManagerIdentifier == Guid.Empty) { throw new ArgumentException(SR.BadResourceManagerId, nameof(resourceManagerIdentifier)); } if (DiagnosticTrace.Verbose) { MethodEnteredTraceRecord.Trace(SR.TraceSourceBase, "TransactionManager.RecoveryComplete"); } if (DiagnosticTrace.Information) { RecoveryCompleteTraceRecord.Trace(SR.TraceSourceBase, resourceManagerIdentifier); } DistributedTransactionManager.ResourceManagerRecoveryComplete(resourceManagerIdentifier); if (DiagnosticTrace.Verbose) { MethodExitedTraceRecord.Trace(SR.TraceSourceBase, "TransactionManager.RecoveryComplete"); } } // Object for synchronizing access to the entire class( avoiding lock( typeof( ... )) ) private static object s_classSyncObject; // Helper object for static synchronization private static object ClassSyncObject { get { if (s_classSyncObject == null) { object o = new object(); Interlocked.CompareExchange(ref s_classSyncObject, o, null); } return s_classSyncObject; } } internal static IsolationLevel DefaultIsolationLevel { get { if (DiagnosticTrace.Verbose) { MethodEnteredTraceRecord.Trace(SR.TraceSourceBase, "TransactionManager.get_DefaultIsolationLevel"); MethodExitedTraceRecord.Trace(SR.TraceSourceBase, "TransactionManager.get_DefaultIsolationLevel"); } return IsolationLevel.Serializable; } } private static DefaultSettingsSection s_defaultSettings; private static DefaultSettingsSection DefaultSettings { get { if (s_defaultSettings == null) { s_defaultSettings = DefaultSettingsSection.GetSection(); } return s_defaultSettings; } } private static MachineSettingsSection s_machineSettings; private static MachineSettingsSection MachineSettings { get { if (s_machineSettings == null) { s_machineSettings = MachineSettingsSection.GetSection(); } return s_machineSettings; } } private static bool s_defaultTimeoutValidated; private static TimeSpan s_defaultTimeout; public static TimeSpan DefaultTimeout { get { if (DiagnosticTrace.Verbose) { MethodEnteredTraceRecord.Trace(SR.TraceSourceBase, "TransactionManager.get_DefaultTimeout"); } if (!s_defaultTimeoutValidated) { s_defaultTimeout = ValidateTimeout(DefaultSettings.Timeout); // If the timeout value got adjusted, it must have been greater than MaximumTimeout. if (s_defaultTimeout != DefaultSettings.Timeout) { if (DiagnosticTrace.Warning) { ConfiguredDefaultTimeoutAdjustedTraceRecord.Trace(SR.TraceSourceBase); } } s_defaultTimeoutValidated = true; } if (DiagnosticTrace.Verbose) { MethodExitedTraceRecord.Trace(SR.TraceSourceBase, "TransactionManager.get_DefaultTimeout"); } return s_defaultTimeout; } } // Double-checked locking pattern requires volatile for read/write synchronization private static volatile bool s_cachedMaxTimeout; private static TimeSpan s_maximumTimeout; public static TimeSpan MaximumTimeout { get { if (DiagnosticTrace.Verbose) { MethodEnteredTraceRecord.Trace(SR.TraceSourceBase, "TransactionManager.get_DefaultMaximumTimeout"); } if (!s_cachedMaxTimeout) { lock (ClassSyncObject) { if (!s_cachedMaxTimeout) { TimeSpan temp = MachineSettings.MaxTimeout; s_maximumTimeout = temp; s_cachedMaxTimeout = true; } } } if (DiagnosticTrace.Verbose) { MethodExitedTraceRecord.Trace(SR.TraceSourceBase, "TransactionManager.get_DefaultMaximumTimeout"); } return s_maximumTimeout; } } // This routine writes the "header" for the recovery information, based on the // type of the calling object and its provided parameter collection. This information // we be read back by the static Reenlist method to create the necessary transaction // manager object with the right parameters in order to do a ReenlistTransaction call. internal static byte[] GetRecoveryInformation(string startupInfo, byte[] resourceManagerRecoveryInformation) { if (DiagnosticTrace.Verbose) { MethodEnteredTraceRecord.Trace(SR.TraceSourceBase, "TransactionManager.GetRecoveryInformation"); } MemoryStream stream = new MemoryStream(); byte[] returnValue = null; try { // Manually write the recovery information BinaryWriter writer = new BinaryWriter(stream); writer.Write(TransactionManager.CurrentRecoveryVersion); if (startupInfo != null) { writer.Write(startupInfo); } else { writer.Write(""); } writer.Write(resourceManagerRecoveryInformation); writer.Flush(); returnValue = stream.ToArray(); } finally { stream.Dispose(); } if (DiagnosticTrace.Verbose) { MethodExitedTraceRecord.Trace(SR.TraceSourceBase, "TransactionManager.GetRecoveryInformation" ); } return returnValue; } internal static byte[] ConvertToByteArray(object thingToConvert) { MemoryStream streamToWrite = new MemoryStream(); byte[] returnValue = null; try { // First seralize the type to the stream. IFormatter formatter = new BinaryFormatter(); formatter.Serialize(streamToWrite, thingToConvert); returnValue = new byte[streamToWrite.Length]; streamToWrite.Position = 0; streamToWrite.Read(returnValue, 0, Convert.ToInt32(streamToWrite.Length, CultureInfo.InvariantCulture)); } finally { streamToWrite.Dispose(); } return returnValue; } /// <summary> /// This static function throws an ArgumentOutOfRange if the specified IsolationLevel is not within /// the range of valid values. /// </summary> /// <param name="transactionIsolationLevel"> /// The IsolationLevel value to validate. /// </param> internal static void ValidateIsolationLevel(IsolationLevel transactionIsolationLevel) { switch (transactionIsolationLevel) { case IsolationLevel.Serializable: case IsolationLevel.RepeatableRead: case IsolationLevel.ReadCommitted: case IsolationLevel.ReadUncommitted: case IsolationLevel.Unspecified: case IsolationLevel.Chaos: case IsolationLevel.Snapshot: break; default: throw new ArgumentOutOfRangeException(nameof(transactionIsolationLevel)); } } /// <summary> /// This static function throws an ArgumentOutOfRange if the specified TimeSpan does not meet /// requirements of a valid transaction timeout. Timeout values must be positive. /// </summary> /// <param name="transactionTimeout"> /// The TimeSpan value to validate. /// </param> internal static TimeSpan ValidateTimeout(TimeSpan transactionTimeout) { if (transactionTimeout < TimeSpan.Zero) { throw new ArgumentOutOfRangeException(nameof(transactionTimeout)); } if (MaximumTimeout != TimeSpan.Zero) { if (transactionTimeout > MaximumTimeout || transactionTimeout == TimeSpan.Zero) { return MaximumTimeout; } } return transactionTimeout; } internal static Transaction FindPromotedTransaction(Guid transactionIdentifier) { Hashtable promotedTransactionTable = PromotedTransactionTable; WeakReference weakRef = (WeakReference)promotedTransactionTable[transactionIdentifier]; if (null != weakRef) { Transaction tx = weakRef.Target as Transaction; if (null != tx) { return tx.InternalClone(); } else // an old, moldy weak reference. Let's get rid of it. { lock (promotedTransactionTable) { promotedTransactionTable.Remove(transactionIdentifier); } } } return null; } internal static Transaction FindOrCreatePromotedTransaction(Guid transactionIdentifier, DistributedTransaction dtx) { Transaction tx = null; Hashtable promotedTransactionTable = PromotedTransactionTable; lock (promotedTransactionTable) { WeakReference weakRef = (WeakReference)promotedTransactionTable[transactionIdentifier]; if (null != weakRef) { tx = weakRef.Target as Transaction; if (null != tx) { // If we found a transaction then dispose it dtx.Dispose(); return tx.InternalClone(); } else { // an old, moldy weak reference. Let's get rid of it. lock (promotedTransactionTable) { promotedTransactionTable.Remove(transactionIdentifier); } } } tx = new Transaction(dtx); // Since we are adding this reference to the table create an object that will clean that entry up. tx._internalTransaction._finalizedObject = new FinalizedObject(tx._internalTransaction, dtx.Identifier); weakRef = new WeakReference(tx, false); promotedTransactionTable[dtx.Identifier] = weakRef; } dtx.SavedLtmPromotedTransaction = tx; FireDistributedTransactionStarted(tx); return tx; } // Table for promoted transactions internal static Hashtable PromotedTransactionTable { get { if (s_promotedTransactionTable == null) { lock (ClassSyncObject) { if (s_promotedTransactionTable == null) { Hashtable temp = new Hashtable(100); s_promotedTransactionTable = temp; } } } return s_promotedTransactionTable; } } // Table for transaction timeouts internal static TransactionTable TransactionTable { get { if (s_transactionTable == null) { lock (ClassSyncObject) { if (s_transactionTable == null) { TransactionTable temp = new TransactionTable(); s_transactionTable = temp; } } } return s_transactionTable; } } // Fault in a DistributedTransactionManager if one has not already been created. // Double-checked locking pattern requires volatile for read/write synchronization internal static volatile DistributedTransactionManager distributedTransactionManager; internal static DistributedTransactionManager DistributedTransactionManager { get { // If the distributed transaction manager is not configured, throw an exception if (distributedTransactionManager == null) { lock (ClassSyncObject) { if (distributedTransactionManager == null) { distributedTransactionManager = new DistributedTransactionManager(); } } } return distributedTransactionManager; } } } }
// 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 Microsoft.Build.Utilities; using NuGet.ContentModel; using NuGet.Frameworks; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Microsoft.DotNet.Build.Tasks.Packaging { /// <summary> /// Examines assets to ensure that an OOB framework still has out-of-box /// assets if a previous version of that framework had inbox assets /// </summary> public class EnsureOOBFramework : PackagingTask { [Required] public ITaskItem[] OOBFrameworks { get; set; } [Required] public ITaskItem[] Files { get; set; } public string RuntimeJson { get; set; } public string RuntimeId { get; set; } [Output] public ITaskItem[] AdditionalFiles { get; set; } private IEnumerable<PackageItem> _packageItems; public override bool Execute() { _packageItems = Files.Select(f => new PackageItem(f)); var packageDlls = _packageItems.Where(pi => Path.GetExtension(pi.SourcePath).Equals(".dll", StringComparison.OrdinalIgnoreCase)); var packagePaths = _packageItems.Select(pi => pi.TargetPath); var packagePathsWithoutPlaceHolders = packagePaths.Where(pi => !NuGetAssetResolver.IsPlaceholder(pi)); if (!String.IsNullOrEmpty(RuntimeJson) && !File.Exists(RuntimeJson)) { Log.LogError("Could not load runtime file: {0}", RuntimeJson); RuntimeJson = null; } NuGetAssetResolver resolver = new NuGetAssetResolver(RuntimeJson, packagePaths); NuGetAssetResolver obscuredResolver = new NuGetAssetResolver(RuntimeJson, packagePathsWithoutPlaceHolders); List<ITaskItem> newItems = new List<ITaskItem>(); // determine if an inbox placeholder obscures an OOB implementation. foreach (var oobFramework in OOBFrameworks) { var oobFx = oobFramework.ItemSpec; NuGetFramework targetFramework = NuGetFramework.Parse(oobFx); // first see if any dlls are explicitly marked for this framework. IEnumerable<string> obscuredCompileFolders = packageDlls.Where(pi => pi.OriginalItem.GetMetadata("EnsureOOBFrameworkRef") == oobFx).Select(pi => pi.TargetDirectory); if (!obscuredCompileFolders.Any()) { // no dlls were marked, resolve without placeholders to determine what to promote. var compileItems = resolver.GetCompileItems(targetFramework); var obscuredCompileItems = obscuredResolver.GetCompileItems(targetFramework); obscuredCompileFolders = GetObscuredAssetFolders(compileItems, obscuredCompileItems, targetFramework, targetFrameworkName: oobFx, expectedAssetFolder: "ref", ignoredAssetFolder: "lib"); } var promotedCompileItems = ExpandAssetFoldersToItems(obscuredCompileFolders, targetAssetFolder: "ref", targetFrameworkName: oobFx); newItems.AddRange(promotedCompileItems); // don't use 'any' in paths due to https://github.com/NuGet/Home/issues/1676 string targetLibFolder = !String.IsNullOrEmpty(RuntimeId) && RuntimeId != "any" ? $"runtimes/{RuntimeId}/lib" : "lib"; IEnumerable<string> obscuredRuntimeFolders = packageDlls.Where(pi => pi.OriginalItem.GetMetadata("EnsureOOBFrameworkLib") == oobFx).Select(pi => pi.TargetDirectory); if (!obscuredRuntimeFolders.Any()) { var runtimeItems = resolver.GetRuntimeItems(targetFramework, RuntimeId); var obscuredRuntimeItems = obscuredResolver.GetRuntimeItems(targetFramework, RuntimeId); obscuredRuntimeFolders = GetObscuredAssetFolders(runtimeItems, obscuredRuntimeItems, targetFramework, targetFrameworkName: oobFx, expectedAssetFolder: targetLibFolder); } var promotedRuntimeItems = ExpandAssetFoldersToItems(obscuredRuntimeFolders, targetLibFolder, targetFrameworkName: oobFx); // If we promoted compile assets but couldn't find any runtime assets to promote we could // be missing dependencies since a dependency group will be created for the compile assets // that may differ from the runtime assets. if (promotedCompileItems.Any() && !promotedRuntimeItems.Any()) { string oobFxRid = oobFramework.GetMetadata("RuntimeId") ?? RuntimeId; // find the actual implementation that will be used. var runtimeItems = resolver.GetRuntimeItems(targetFramework, oobFxRid); var promotedRuntimeFolders = GetRuntimeAssetFoldersForPromotion(runtimeItems, targetFramework, oobFx); // use null here to indicate that this should not actually go into the package but only be used for // dependency harvesting promotedRuntimeItems = ExpandAssetFoldersToItems(promotedRuntimeFolders, "$none$", targetFrameworkName: oobFx); } newItems.AddRange(promotedRuntimeItems); } AdditionalFiles = newItems.ToArray(); return !Log.HasLoggedErrors; } private IEnumerable<string> GetObscuredAssetFolders(ContentItemGroup assets, ContentItemGroup obscuredAssets, NuGetFramework targetFramework, string targetFrameworkName, string expectedAssetFolder, string ignoredAssetFolder = null) { if (assets == null || assets.Items.Count == 0) { return Enumerable.Empty<string>(); } if (assets.Items.Any(ci => !NuGetAssetResolver.IsPlaceholder(ci.Path))) { return Enumerable.Empty<string>(); } if (targetFrameworkName == null) { targetFrameworkName = targetFramework.GetShortFolderName(); } var resolvedFramework = assets.Properties["tfm"] as NuGetFramework; if (targetFramework.Equals(resolvedFramework)) { Log.LogMessage(LogImportance.Low, $"Not overriding explicit placeholder for {targetFrameworkName}"); return Enumerable.Empty<string>(); } var obscuredAssetPaths = NuGetAssetResolver.GetPackageTargetDirectories(obscuredAssets); if (ignoredAssetFolder != null) { string ignoredFolder = ignoredAssetFolder + '/'; obscuredAssetPaths = obscuredAssetPaths.Where(i => -1 == i.IndexOf(ignoredFolder, StringComparison.OrdinalIgnoreCase)); } if (expectedAssetFolder != null) { var unexpectedAssetPaths = obscuredAssetPaths.Where(ri => !ri.StartsWith(expectedAssetFolder, StringComparison.OrdinalIgnoreCase)); foreach (var unexpectedAssetPath in unexpectedAssetPaths) { Log.LogWarning($"Unexpected targetPath {unexpectedAssetPath}. Expected only {expectedAssetFolder}."); } // filter after we've warned obscuredAssetPaths = obscuredAssetPaths.Except(unexpectedAssetPaths); } if (!obscuredAssetPaths.Any()) { // it's acceptable to have no override, this is the case for packages which // carry implementation in a runtime-specific package Log.LogMessage(LogImportance.Low, $"No {expectedAssetFolder} assets could be found to override inbox placeholder for {targetFrameworkName}."); } return obscuredAssetPaths; } private IEnumerable<string> GetRuntimeAssetFoldersForPromotion(ContentItemGroup runtimeAssets, NuGetFramework targetFramework, string targetFrameworkName) { if (runtimeAssets == null || runtimeAssets.Items.Count == 0) { return Enumerable.Empty<string>(); } if (runtimeAssets.Items.All(ci => NuGetAssetResolver.IsPlaceholder(ci.Path))) { return Enumerable.Empty<string>(); } if (targetFrameworkName == null) { targetFrameworkName = targetFramework.GetShortFolderName(); } var resolvedFramework = runtimeAssets.Properties["tfm"] as NuGetFramework; if (targetFramework.Equals(resolvedFramework)) { Log.LogMessage(LogImportance.Low, $"Not promoting explicit implementation for {targetFrameworkName}"); return Enumerable.Empty<string>(); } return NuGetAssetResolver.GetPackageTargetDirectories(runtimeAssets); } private IEnumerable<ITaskItem> ExpandAssetFoldersToItems(IEnumerable<string> keyAssets, string targetAssetFolder, string targetFrameworkName) { // Asset selection only finds dlls, but we need everything under the path. foreach (var packageItem in _packageItems) { foreach (var keyAsset in keyAssets) { if (packageItem.TargetPath.StartsWith(keyAsset)) { string subPath = packageItem.TargetPath.Substring(keyAsset.Length); Log.LogMessage(LogImportance.Low, $"Copying {packageItem.TargetPath} to {targetAssetFolder}/{targetFrameworkName}{subPath}."); yield return GetOOBItem(packageItem, $"{targetAssetFolder}/{targetFrameworkName}{subPath}", targetFrameworkName); } } } } private static ITaskItem GetOOBItem(PackageItem oobItem, string targetPath, string targetFramework) { TaskItem item = new TaskItem(oobItem.OriginalItem); item.SetMetadata("TargetPath", targetPath); item.SetMetadata("TargetFramework", targetFramework); return item; } } }
using System; using System.IO; using System.Collections.Generic; using System.Text.RegularExpressions; using UnityEngine; namespace UnityExtension { //------------------------------------------------------------------------------------------------------------ public static class Utils { //------------------------------------------------------------------------------------------------------------ public static bool HasKeys(Dictionary<string, object> lData, params string[] lKeys) { if (lKeys != null) { for (int lCount = 0; lCount < lKeys.Length; ++lCount) { if (!lData.ContainsKey(lKeys[lCount])) { return false; } } } return true; } //------------------------------------------------------------------------------------------------------------ public static void ClearChildren(GameObject lGo, string lTarget) { if (lGo != null) { Transform lTransform = null; for (int lCount = lGo.transform.childCount - 1; lCount > -1; --lCount) { lTransform = lGo.transform.GetChild(lCount); if (lTransform.name.Contains(lTarget)) { lTransform.parent = null; GameObject.Destroy(lTransform.gameObject); } } } } //------------------------------------------------------------------------------------------------------------ public static void ClearChildrenRegex(GameObject lGo, string lPattern) { if (lGo != null) { Transform lTransform = null; Regex lRegex = new Regex(lPattern); for (int lCount = lGo.transform.childCount - 1; lCount > -1; --lCount) { lTransform = lGo.transform.GetChild(lCount); if (lRegex.IsMatch(lTransform.name)) { lTransform.parent = null; GameObject.Destroy(lTransform.gameObject); } } } } //------------------------------------------------------------------------------------------------------------ public static void VerifyObjects(string lMsg, params object[] lObjects) { for (int lCount = 0; lCount < lObjects.Length; ++lCount) { if (lObjects[lCount] == null) { Debug.LogError(lMsg); break; } } } //------------------------------------------------------------------------------------------------------------ public static bool JSONCheck(string lText) { return !string.IsNullOrEmpty(lText) && lText[0] == '{'; } //------------------------------------------------------------------------------------------------------------ public static Vector3 ParseVector3Json(string lJsonData) { string[] lVector3Array = lJsonData.Replace("(", "").Replace(")", "").Replace(" ", "").Split(','); Vector3 lVector3 = Vector3.zero; if (float.TryParse(lVector3Array[0], out lVector3.x) == false) { return Vector3.zero; } if (float.TryParse(lVector3Array[1], out lVector3.y) == false) { return Vector3.zero; } if (float.TryParse(lVector3Array[2], out lVector3.z) == false) { return Vector3.zero; } return lVector3; } //------------------------------------------------------------------------------------------------------------ public static Vector4 ParseVector4Json(string lJsonData) { string[] lVector4Array = lJsonData.Replace("(", "").Replace(")", "").Replace(" ", "").Split(','); Vector4 lVector4 = Vector4.zero; if (float.TryParse(lVector4Array[0], out lVector4.x) == false) { return Vector4.zero; } if (float.TryParse(lVector4Array[1], out lVector4.y) == false) { return Vector4.zero; } if (float.TryParse(lVector4Array[2], out lVector4.z) == false) { return Vector4.zero; } if (float.TryParse(lVector4Array[3], out lVector4.w) == false) { return Vector4.zero; } return lVector4; } //------------------------------------------------------------------------------------------------------------ public static Vector2 ParseVector2String(string lData, char lSeperator = ' ') { string[] lParts = lData.Split(new char[] { lSeperator }, StringSplitOptions.RemoveEmptyEntries); float lX = lParts[0].ParseInvariantFloat(); float lY = lParts[1].ParseInvariantFloat(); return new Vector2(lX, lY); } //------------------------------------------------------------------------------------------------------------ public static Vector3 ParseVector3String(string lData, char lSeperator = ' ') { string[] lParts = lData.Split(new char[] { lSeperator }, StringSplitOptions.RemoveEmptyEntries); float lX = lParts[0].ParseInvariantFloat(); float lY = lParts[1].ParseInvariantFloat(); float lZ = lParts[2].ParseInvariantFloat(); return new Vector3(lX, lY, lZ); } //------------------------------------------------------------------------------------------------------------ public static Vector4 ParseVector4String(string lData, char lSeperator = ' ') { string[] lParts = lData.Split(new char[] { lSeperator }, StringSplitOptions.RemoveEmptyEntries); float lX = lParts[0].ParseInvariantFloat(); float lY = lParts[1].ParseInvariantFloat(); float lZ = lParts[2].ParseInvariantFloat(); float lW = lParts[3].ParseInvariantFloat(); return new Vector4(lX, lY, lZ, lW); } //------------------------------------------------------------------------------------------------------------ public static Quaternion ParseQuaternion(string lJsonData) { string[] lQuaternionArray = lJsonData.Replace("(", "").Replace(")", "").Replace(" ", "").Split(','); Quaternion lQuaternion = Quaternion.identity; if (float.TryParse(lQuaternionArray[0], out lQuaternion.x) == false) { return Quaternion.identity; } if (float.TryParse(lQuaternionArray[1], out lQuaternion.y) == false) { return Quaternion.identity; } if (float.TryParse(lQuaternionArray[2], out lQuaternion.z) == false) { return Quaternion.identity; } if (float.TryParse(lQuaternionArray[3], out lQuaternion.w) == false) { return Quaternion.identity; } return lQuaternion; } //------------------------------------------------------------------------------------------------------------ public static string Vector3String(Vector3 lVector3) { return "(" + lVector3.x.ToString("f3") + "," + lVector3.y.ToString("f3") + "," + lVector3.z.ToString("f3") + ")"; } //------------------------------------------------------------------------------------------------------------ public static string Vector4String(Vector4 lVector4) { return "(" + lVector4.x.ToString("f3") + "," + lVector4.y.ToString("f3") + "," + lVector4.z.ToString("f3") + "," + lVector4.w.ToString("f3") + ")"; } //------------------------------------------------------------------------------------------------------------ public static string QuaternionString(Quaternion lQuaternion) { return "(" + lQuaternion.x.ToString("f3") + "," + lQuaternion.y.ToString("f3") + "," + lQuaternion.z.ToString("f3") + "," + lQuaternion.w.ToString("f3") + ")"; } //------------------------------------------------------------------------------------------------------------ public static int FirstInt(string lJsonData) { string lDigits = ""; for (int lCount = 0; lCount < lJsonData.Length && Char.IsDigit(lJsonData[lCount]); ++lCount) { lDigits += lJsonData[lCount]; } return int.Parse(lDigits); } } }
/* Project Orleans Cloud Service SDK ver. 1.0 Copyright (c) Microsoft Corporation All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Threading.Tasks; using Orleans.Runtime; using Orleans.Providers; using Orleans.Runtime.Configuration; namespace Orleans.Streams { /// <summary> /// Provider-facing interface for manager of streaming providers /// </summary> internal interface IStreamProviderRuntime : IProviderRuntime { /// <summary> /// Retrieves the opaque identity of currently executing grain or client object. /// Just for logging purposes. /// </summary> /// <param name="handler"></param> string ExecutingEntityIdentity(); SiloAddress ExecutingSiloAddress { get; } StreamDirectory GetStreamDirectory(); void RegisterSystemTarget(ISystemTarget target); void UnRegisterSystemTarget(ISystemTarget target); /// <summary> /// Register a timer to send regular callbacks to this grain. /// This timer will keep the current grain from being deactivated. /// </summary> /// <param name="callback"></param> /// <param name="state"></param> /// <param name="dueTime"></param> /// <param name="period"></param> /// <returns></returns> IDisposable RegisterTimer(Func<object, Task> asyncCallback, object state, TimeSpan dueTime, TimeSpan period); /// <summary> /// Binds an extension to an addressable object, if not already done. /// </summary> /// <typeparam name="TExtension">The type of the extension (e.g. StreamConsumerExtension).</typeparam> /// <param name="newExtensionFunc">A factory function that constructs a new extension object.</param> /// <returns>A tuple, containing first the extension and second an addressable reference to the extension's interface.</returns> Task<Tuple<TExtension, TExtensionInterface>> BindExtension<TExtension, TExtensionInterface>(Func<TExtension> newExtensionFunc) where TExtension : IGrainExtension where TExtensionInterface : IGrainExtension; /// <summary> /// A Pub Sub runtime interface. /// </summary> /// <returns></returns> IStreamPubSub PubSub(StreamPubSubType pubSubType); /// <summary> /// A consistent ring interface. /// </summary> /// <param name="numSubRanges">Total number of sub ranges within this silo range.</param> /// <returns></returns> IConsistentRingProviderForGrains GetConsistentRingProvider(int mySubRangeIndex, int numSubRanges); /// <summary> /// Return true if this runtime executes inside silo, false otherwise (on the client). /// </summary> /// <param name="pubSubType"></param> /// <returns></returns> bool InSilo { get; } /// <summary> /// Invoke the given async function from within a valid Orleans scheduler context. /// </summary> /// <param name="asyncFunc"></param> Task InvokeWithinSchedulingContextAsync(Func<Task> asyncFunc, object context); object GetCurrentSchedulingContext(); } /// <summary> /// Provider-facing interface for manager of streaming providers /// </summary> internal interface ISiloSideStreamProviderRuntime : IStreamProviderRuntime { /// <summary> /// Start the pulling agents for a given persistent stream provider. /// </summary> /// <param name="streamProviderName"></param> /// <param name="balancerType"></param> /// <param name="pubSubType"></param> /// <param name="adapterFactory"></param> /// <param name="queueAdapter"></param> /// <param name="getQueueMsgsTimerPeriod"></param> /// <param name="initQueueTimeout"></param> /// <returns></returns> Task<IPersistentStreamPullingManager> InitializePullingAgents( string streamProviderName, IQueueAdapterFactory adapterFactory, IQueueAdapter queueAdapter, PersistentStreamProviderConfig config); } public enum StreamPubSubType { ExplicitGrainBasedAndImplicit, ExplicitGrainBasedOnly, ImplicitOnly, } [Serializable] public class PersistentStreamProviderConfig { public const string GET_QUEUE_MESSAGES_TIMER_PERIOD = "GetQueueMessagesTimerPeriod"; public static readonly TimeSpan DEFAULT_GET_QUEUE_MESSAGES_TIMER_PERIOD = TimeSpan.FromMilliseconds(100); public const string INIT_QUEUE_TIMEOUT = "InitQueueTimeout"; public static readonly TimeSpan DEFAULT_INIT_QUEUE_TIMEOUT = TimeSpan.FromSeconds(5); public const string MAX_EVENT_DELIVERY_TIME = "MaxEventDeliveryTime"; public static readonly TimeSpan DEFAULT_MAX_EVENT_DELIVERY_TIME = TimeSpan.FromMinutes(1); public const string STREAM_INACTIVITY_PERIOD = "StreamInactivityPeriod"; public static readonly TimeSpan DEFAULT_STREAM_INACTIVITY_PERIOD = TimeSpan.FromMinutes(30); public const string QUEUE_BALANCER_TYPE = "QueueBalancerType"; public const StreamQueueBalancerType DEFAULT_STREAM_QUEUE_BALANCER_TYPE = StreamQueueBalancerType.ConsistentRingBalancer; public const string STREAM_PUBSUB_TYPE = "PubSubType"; public const StreamPubSubType DEFAULT_STREAM_PUBSUB_TYPE = StreamPubSubType.ExplicitGrainBasedAndImplicit; public TimeSpan GetQueueMsgsTimerPeriod { get; private set; } public TimeSpan InitQueueTimeout { get; private set; } public TimeSpan MaxEventDeliveryTime { get; private set; } public TimeSpan StreamInactivityPeriod { get; private set; } public StreamQueueBalancerType BalancerType { get; private set; } public StreamPubSubType PubSubType { get; private set; } public PersistentStreamProviderConfig(IProviderConfiguration config) { string timePeriod; if (!config.Properties.TryGetValue(GET_QUEUE_MESSAGES_TIMER_PERIOD, out timePeriod)) GetQueueMsgsTimerPeriod = DEFAULT_GET_QUEUE_MESSAGES_TIMER_PERIOD; else GetQueueMsgsTimerPeriod = ConfigUtilities.ParseTimeSpan(timePeriod, "Invalid time value for the " + GET_QUEUE_MESSAGES_TIMER_PERIOD + " property in the provider config values."); string timeout; if (!config.Properties.TryGetValue(INIT_QUEUE_TIMEOUT, out timeout)) InitQueueTimeout = DEFAULT_INIT_QUEUE_TIMEOUT; else InitQueueTimeout = ConfigUtilities.ParseTimeSpan(timeout, "Invalid time value for the " + INIT_QUEUE_TIMEOUT + " property in the provider config values."); string balanceTypeString; BalancerType = !config.Properties.TryGetValue(QUEUE_BALANCER_TYPE, out balanceTypeString) ? DEFAULT_STREAM_QUEUE_BALANCER_TYPE : (StreamQueueBalancerType)Enum.Parse(typeof(StreamQueueBalancerType), balanceTypeString); if (!config.Properties.TryGetValue(MAX_EVENT_DELIVERY_TIME, out timeout)) MaxEventDeliveryTime = DEFAULT_MAX_EVENT_DELIVERY_TIME; else MaxEventDeliveryTime = ConfigUtilities.ParseTimeSpan(timeout, "Invalid time value for the " + MAX_EVENT_DELIVERY_TIME + " property in the provider config values."); if (!config.Properties.TryGetValue(STREAM_INACTIVITY_PERIOD, out timeout)) StreamInactivityPeriod = DEFAULT_STREAM_INACTIVITY_PERIOD; else StreamInactivityPeriod = ConfigUtilities.ParseTimeSpan(timeout, "Invalid time value for the " + STREAM_INACTIVITY_PERIOD + " property in the provider config values."); string pubSubTypeString; PubSubType = !config.Properties.TryGetValue(STREAM_PUBSUB_TYPE, out pubSubTypeString) ? DEFAULT_STREAM_PUBSUB_TYPE : (StreamPubSubType)Enum.Parse(typeof(StreamPubSubType), pubSubTypeString); } public override string ToString() { return String.Format("{0}={1}, {2}={3}, {4}={5}, {6}={7}, {8}={9}, {10}={11}", GET_QUEUE_MESSAGES_TIMER_PERIOD, GetQueueMsgsTimerPeriod, INIT_QUEUE_TIMEOUT, InitQueueTimeout, MAX_EVENT_DELIVERY_TIME, MaxEventDeliveryTime, STREAM_INACTIVITY_PERIOD, StreamInactivityPeriod, QUEUE_BALANCER_TYPE, BalancerType, STREAM_PUBSUB_TYPE, PubSubType); } } internal interface IStreamPubSub // Compare with: IPubSubRendezvousGrain { Task<ISet<PubSubSubscriptionState>> RegisterProducer(StreamId streamId, string streamProvider, IStreamProducerExtension streamProducer); Task UnregisterProducer(StreamId streamId, string streamProvider, IStreamProducerExtension streamProducer); Task RegisterConsumer(GuidId subscriptionId, StreamId streamId, string streamProvider, IStreamConsumerExtension streamConsumer, IStreamFilterPredicateWrapper filter); Task UnregisterConsumer(GuidId subscriptionId, StreamId streamId, string streamProvider); Task<int> ProducerCount(Guid streamId, string streamProvider, string streamNamespace); Task<int> ConsumerCount(Guid streamId, string streamProvider, string streamNamespace); Task<List<GuidId>> GetAllSubscriptions(StreamId streamId, IStreamConsumerExtension streamConsumer); GuidId CreateSubscriptionId(StreamId streamId, IStreamConsumerExtension streamConsumer); Task<bool> FaultSubscription(StreamId streamId, GuidId subscriptionId); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // // using System; using System.Runtime.InteropServices; using Windows.Foundation; #pragma warning disable 436 // Redefining types from Windows.Foundation namespace Windows.UI.Xaml.Media.Media3D { // // Matrix3D is the managed projection of Windows.UI.Xaml.Media.Media3D.Matrix3D. Any // changes to the layout of this type must be exactly mirrored on the native WinRT side as well. // // Note that this type is owned by the Jupiter team. Please contact them before making any // changes here. // [StructLayout(LayoutKind.Sequential)] public struct Matrix3D : IFormattable { // Assuming this matrix has fourth column of 0,0,0,1 and isn't identity this function: // Returns false if HasInverse is false, otherwise inverts the matrix. private bool NormalizedAffineInvert() { double z20 = _m12 * _m23 - _m22 * _m13; double z10 = _m32 * _m13 - _m12 * _m33; double z00 = _m22 * _m33 - _m32 * _m23; double det = _m31 * z20 + _m21 * z10 + _m11 * z00; if (IsZero(det)) { return false; } // Compute 3x3 non-zero cofactors for the 2nd column double z21 = _m21 * _m13 - _m11 * _m23; double z11 = _m11 * _m33 - _m31 * _m13; double z01 = _m31 * _m23 - _m21 * _m33; // Compute all six 2x2 determinants of 1st two columns double y01 = _m11 * _m22 - _m21 * _m12; double y02 = _m11 * _m32 - _m31 * _m12; double y03 = _m11 * _offsetY - _offsetX * _m12; double y12 = _m21 * _m32 - _m31 * _m22; double y13 = _m21 * _offsetY - _offsetX * _m22; double y23 = _m31 * _offsetY - _offsetX * _m32; // Compute all non-zero and non-one 3x3 cofactors for 2nd // two columns double z23 = _m23 * y03 - _offsetZ * y01 - _m13 * y13; double z13 = _m13 * y23 - _m33 * y03 + _offsetZ * y02; double z03 = _m33 * y13 - _offsetZ * y12 - _m23 * y23; double z22 = y01; double z12 = -y02; double z02 = y12; double rcp = 1.0 / det; // Multiply all 3x3 cofactors by reciprocal & transpose _m11 = (z00 * rcp); _m12 = (z10 * rcp); _m13 = (z20 * rcp); _m21 = (z01 * rcp); _m22 = (z11 * rcp); _m23 = (z21 * rcp); _m31 = (z02 * rcp); _m32 = (z12 * rcp); _m33 = (z22 * rcp); _offsetX = (z03 * rcp); _offsetY = (z13 * rcp); _offsetZ = (z23 * rcp); return true; } // RETURNS true if has inverse & invert was done. Otherwise returns false & leaves matrix unchanged. private bool InvertCore() { if (IsAffine) { return NormalizedAffineInvert(); } // compute all six 2x2 determinants of 2nd two columns double y01 = _m13 * _m24 - _m23 * _m14; double y02 = _m13 * _m34 - _m33 * _m14; double y03 = _m13 * _m44 - _offsetZ * _m14; double y12 = _m23 * _m34 - _m33 * _m24; double y13 = _m23 * _m44 - _offsetZ * _m24; double y23 = _m33 * _m44 - _offsetZ * _m34; // Compute 3x3 cofactors for 1st the column double z30 = _m22 * y02 - _m32 * y01 - _m12 * y12; double z20 = _m12 * y13 - _m22 * y03 + _offsetY * y01; double z10 = _m32 * y03 - _offsetY * y02 - _m12 * y23; double z00 = _m22 * y23 - _m32 * y13 + _offsetY * y12; // Compute 4x4 determinant double det = _offsetX * z30 + _m31 * z20 + _m21 * z10 + _m11 * z00; if (IsZero(det)) { return false; } // Compute 3x3 cofactors for the 2nd column double z31 = _m11 * y12 - _m21 * y02 + _m31 * y01; double z21 = _m21 * y03 - _offsetX * y01 - _m11 * y13; double z11 = _m11 * y23 - _m31 * y03 + _offsetX * y02; double z01 = _m31 * y13 - _offsetX * y12 - _m21 * y23; // Compute all six 2x2 determinants of 1st two columns y01 = _m11 * _m22 - _m21 * _m12; y02 = _m11 * _m32 - _m31 * _m12; y03 = _m11 * _offsetY - _offsetX * _m12; y12 = _m21 * _m32 - _m31 * _m22; y13 = _m21 * _offsetY - _offsetX * _m22; y23 = _m31 * _offsetY - _offsetX * _m32; // Compute all 3x3 cofactors for 2nd two columns double z33 = _m13 * y12 - _m23 * y02 + _m33 * y01; double z23 = _m23 * y03 - _offsetZ * y01 - _m13 * y13; double z13 = _m13 * y23 - _m33 * y03 + _offsetZ * y02; double z03 = _m33 * y13 - _offsetZ * y12 - _m23 * y23; double z32 = _m24 * y02 - _m34 * y01 - _m14 * y12; double z22 = _m14 * y13 - _m24 * y03 + _m44 * y01; double z12 = _m34 * y03 - _m44 * y02 - _m14 * y23; double z02 = _m24 * y23 - _m34 * y13 + _m44 * y12; double rcp = 1.0 / det; // Multiply all 3x3 cofactors by reciprocal & transpose _m11 = (z00 * rcp); _m12 = (z10 * rcp); _m13 = (z20 * rcp); _m14 = (z30 * rcp); _m21 = (z01 * rcp); _m22 = (z11 * rcp); _m23 = (z21 * rcp); _m24 = (z31 * rcp); _m31 = (z02 * rcp); _m32 = (z12 * rcp); _m33 = (z22 * rcp); _m34 = (z32 * rcp); _offsetX = (z03 * rcp); _offsetY = (z13 * rcp); _offsetZ = (z23 * rcp); _m44 = (z33 * rcp); return true; } public Matrix3D(double m11, double m12, double m13, double m14, double m21, double m22, double m23, double m24, double m31, double m32, double m33, double m34, double offsetX, double offsetY, double offsetZ, double m44) { _m11 = m11; _m12 = m12; _m13 = m13; _m14 = m14; _m21 = m21; _m22 = m22; _m23 = m23; _m24 = m24; _m31 = m31; _m32 = m32; _m33 = m33; _m34 = m34; _offsetX = offsetX; _offsetY = offsetY; _offsetZ = offsetZ; _m44 = m44; } // the transform is identity by default // Actually fill in the fields - some (internal) code uses the fields directly for perf. private static Matrix3D s_identity = CreateIdentity(); public double M11 { get { return _m11; } set { _m11 = value; } } public double M12 { get { return _m12; } set { _m12 = value; } } public double M13 { get { return _m13; } set { _m13 = value; } } public double M14 { get { return _m14; } set { _m14 = value; } } public double M21 { get { return _m21; } set { _m21 = value; } } public double M22 { get { return _m22; } set { _m22 = value; } } public double M23 { get { return _m23; } set { _m23 = value; } } public double M24 { get { return _m24; } set { _m24 = value; } } public double M31 { get { return _m31; } set { _m31 = value; } } public double M32 { get { return _m32; } set { _m32 = value; } } public double M33 { get { return _m33; } set { _m33 = value; } } public double M34 { get { return _m34; } set { _m34 = value; } } public double OffsetX { get { return _offsetX; } set { _offsetX = value; } } public double OffsetY { get { return _offsetY; } set { _offsetY = value; } } public double OffsetZ { get { return _offsetZ; } set { _offsetZ = value; } } public double M44 { get { return _m44; } set { _m44 = value; } } public static Matrix3D Identity { get { return s_identity; } } public bool IsIdentity { get { return (_m11 == 1 && _m12 == 0 && _m13 == 0 && _m14 == 0 && _m21 == 0 && _m22 == 1 && _m23 == 0 && _m24 == 0 && _m31 == 0 && _m32 == 0 && _m33 == 1 && _m34 == 0 && _offsetX == 0 && _offsetY == 0 && _offsetZ == 0 && _m44 == 1); } } public override string ToString() { // Delegate to the internal method which implements all ToString calls. return ConvertToString(null /* format string */, null /* format provider */); } public string ToString(IFormatProvider provider) { // Delegate to the internal method which implements all ToString calls. return ConvertToString(null /* format string */, provider); } string IFormattable.ToString(string format, IFormatProvider provider) { // Delegate to the internal method which implements all ToString calls. return ConvertToString(format, provider); } private string ConvertToString(string format, IFormatProvider provider) { if (IsIdentity) { return "Identity"; } // Helper to get the numeric list separator for a given culture. char separator = TokenizerHelper.GetNumericListSeparator(provider); return String.Format(provider, "{1:" + format + "}{0}{2:" + format + "}{0}{3:" + format + "}{0}{4:" + format + "}{0}{5:" + format + "}{0}{6:" + format + "}{0}{7:" + format + "}{0}{8:" + format + "}{0}{9:" + format + "}{0}{10:" + format + "}{0}{11:" + format + "}{0}{12:" + format + "}{0}{13:" + format + "}{0}{14:" + format + "}{0}{15:" + format + "}{0}{16:" + format + "}", separator, _m11, _m12, _m13, _m14, _m21, _m22, _m23, _m24, _m31, _m32, _m33, _m34, _offsetX, _offsetY, _offsetZ, _m44); } public override int GetHashCode() { // Perform field-by-field XOR of HashCodes return M11.GetHashCode() ^ M12.GetHashCode() ^ M13.GetHashCode() ^ M14.GetHashCode() ^ M21.GetHashCode() ^ M22.GetHashCode() ^ M23.GetHashCode() ^ M24.GetHashCode() ^ M31.GetHashCode() ^ M32.GetHashCode() ^ M33.GetHashCode() ^ M34.GetHashCode() ^ OffsetX.GetHashCode() ^ OffsetY.GetHashCode() ^ OffsetZ.GetHashCode() ^ M44.GetHashCode(); } public override bool Equals(object o) { return o is Matrix3D && Matrix3D.Equals(this, (Matrix3D)o); } public bool Equals(Matrix3D value) { return Matrix3D.Equals(this, value); } public static bool operator ==(Matrix3D matrix1, Matrix3D matrix2) { return matrix1.M11 == matrix2.M11 && matrix1.M12 == matrix2.M12 && matrix1.M13 == matrix2.M13 && matrix1.M14 == matrix2.M14 && matrix1.M21 == matrix2.M21 && matrix1.M22 == matrix2.M22 && matrix1.M23 == matrix2.M23 && matrix1.M24 == matrix2.M24 && matrix1.M31 == matrix2.M31 && matrix1.M32 == matrix2.M32 && matrix1.M33 == matrix2.M33 && matrix1.M34 == matrix2.M34 && matrix1.OffsetX == matrix2.OffsetX && matrix1.OffsetY == matrix2.OffsetY && matrix1.OffsetZ == matrix2.OffsetZ && matrix1.M44 == matrix2.M44; } public static bool operator !=(Matrix3D matrix1, Matrix3D matrix2) { return !(matrix1 == matrix2); } public static Matrix3D operator *(Matrix3D matrix1, Matrix3D matrix2) { Matrix3D matrix3D = new Matrix3D(); matrix3D.M11 = matrix1.M11 * matrix2.M11 + matrix1.M12 * matrix2.M21 + matrix1.M13 * matrix2.M31 + matrix1.M14 * matrix2.OffsetX; matrix3D.M12 = matrix1.M11 * matrix2.M12 + matrix1.M12 * matrix2.M22 + matrix1.M13 * matrix2.M32 + matrix1.M14 * matrix2.OffsetY; matrix3D.M13 = matrix1.M11 * matrix2.M13 + matrix1.M12 * matrix2.M23 + matrix1.M13 * matrix2.M33 + matrix1.M14 * matrix2.OffsetZ; matrix3D.M14 = matrix1.M11 * matrix2.M14 + matrix1.M12 * matrix2.M24 + matrix1.M13 * matrix2.M34 + matrix1.M14 * matrix2.M44; matrix3D.M21 = matrix1.M21 * matrix2.M11 + matrix1.M22 * matrix2.M21 + matrix1.M23 * matrix2.M31 + matrix1.M24 * matrix2.OffsetX; matrix3D.M22 = matrix1.M21 * matrix2.M12 + matrix1.M22 * matrix2.M22 + matrix1.M23 * matrix2.M32 + matrix1.M24 * matrix2.OffsetY; matrix3D.M23 = matrix1.M21 * matrix2.M13 + matrix1.M22 * matrix2.M23 + matrix1.M23 * matrix2.M33 + matrix1.M24 * matrix2.OffsetZ; matrix3D.M24 = matrix1.M21 * matrix2.M14 + matrix1.M22 * matrix2.M24 + matrix1.M23 * matrix2.M34 + matrix1.M24 * matrix2.M44; matrix3D.M31 = matrix1.M31 * matrix2.M11 + matrix1.M32 * matrix2.M21 + matrix1.M33 * matrix2.M31 + matrix1.M34 * matrix2.OffsetX; matrix3D.M32 = matrix1.M31 * matrix2.M12 + matrix1.M32 * matrix2.M22 + matrix1.M33 * matrix2.M32 + matrix1.M34 * matrix2.OffsetY; matrix3D.M33 = matrix1.M31 * matrix2.M13 + matrix1.M32 * matrix2.M23 + matrix1.M33 * matrix2.M33 + matrix1.M34 * matrix2.OffsetZ; matrix3D.M34 = matrix1.M31 * matrix2.M14 + matrix1.M32 * matrix2.M24 + matrix1.M33 * matrix2.M34 + matrix1.M34 * matrix2.M44; matrix3D.OffsetX = matrix1.OffsetX * matrix2.M11 + matrix1.OffsetY * matrix2.M21 + matrix1.OffsetZ * matrix2.M31 + matrix1.M44 * matrix2.OffsetX; matrix3D.OffsetY = matrix1.OffsetX * matrix2.M12 + matrix1.OffsetY * matrix2.M22 + matrix1.OffsetZ * matrix2.M32 + matrix1.M44 * matrix2.OffsetY; matrix3D.OffsetZ = matrix1.OffsetX * matrix2.M13 + matrix1.OffsetY * matrix2.M23 + matrix1.OffsetZ * matrix2.M33 + matrix1.M44 * matrix2.OffsetZ; matrix3D.M44 = matrix1.OffsetX * matrix2.M14 + matrix1.OffsetY * matrix2.M24 + matrix1.OffsetZ * matrix2.M34 + matrix1.M44 * matrix2.M44; // matrix3D._type is not set. return matrix3D; } public bool HasInverse { get { return !IsZero(Determinant); } } public void Invert() { if (!InvertCore()) { throw new InvalidOperationException(); } } private static Matrix3D CreateIdentity() { Matrix3D matrix3D = new Matrix3D(); matrix3D.SetMatrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); return matrix3D; } private void SetMatrix(double m11, double m12, double m13, double m14, double m21, double m22, double m23, double m24, double m31, double m32, double m33, double m34, double offsetX, double offsetY, double offsetZ, double m44) { _m11 = m11; _m12 = m12; _m13 = m13; _m14 = m14; _m21 = m21; _m22 = m22; _m23 = m23; _m24 = m24; _m31 = m31; _m32 = m32; _m33 = m33; _m34 = m34; _offsetX = offsetX; _offsetY = offsetY; _offsetZ = offsetZ; _m44 = m44; } private static bool Equals(Matrix3D matrix1, Matrix3D matrix2) { return matrix1.M11.Equals(matrix2.M11) && matrix1.M12.Equals(matrix2.M12) && matrix1.M13.Equals(matrix2.M13) && matrix1.M14.Equals(matrix2.M14) && matrix1.M21.Equals(matrix2.M21) && matrix1.M22.Equals(matrix2.M22) && matrix1.M23.Equals(matrix2.M23) && matrix1.M24.Equals(matrix2.M24) && matrix1.M31.Equals(matrix2.M31) && matrix1.M32.Equals(matrix2.M32) && matrix1.M33.Equals(matrix2.M33) && matrix1.M34.Equals(matrix2.M34) && matrix1.OffsetX.Equals(matrix2.OffsetX) && matrix1.OffsetY.Equals(matrix2.OffsetY) && matrix1.OffsetZ.Equals(matrix2.OffsetZ) && matrix1.M44.Equals(matrix2.M44); } private double GetNormalizedAffineDeterminant() { double z20 = _m12 * _m23 - _m22 * _m13; double z10 = _m32 * _m13 - _m12 * _m33; double z00 = _m22 * _m33 - _m32 * _m23; return _m31 * z20 + _m21 * z10 + _m11 * z00; } private bool IsAffine { get { return (_m14 == 0.0 && _m24 == 0.0 && _m34 == 0.0 && _m44 == 1.0); } } private double Determinant { get { if (IsAffine) { return GetNormalizedAffineDeterminant(); } // compute all six 2x2 determinants of 2nd two columns double y01 = _m13 * _m24 - _m23 * _m14; double y02 = _m13 * _m34 - _m33 * _m14; double y03 = _m13 * _m44 - _offsetZ * _m14; double y12 = _m23 * _m34 - _m33 * _m24; double y13 = _m23 * _m44 - _offsetZ * _m24; double y23 = _m33 * _m44 - _offsetZ * _m34; // Compute 3x3 cofactors for 1st the column double z30 = _m22 * y02 - _m32 * y01 - _m12 * y12; double z20 = _m12 * y13 - _m22 * y03 + _offsetY * y01; double z10 = _m32 * y03 - _offsetY * y02 - _m12 * y23; double z00 = _m22 * y23 - _m32 * y13 + _offsetY * y12; return _offsetX * z30 + _m31 * z20 + _m21 * z10 + _m11 * z00; } } private static bool IsZero(double value) { return Math.Abs(value) < 10.0 * DBL_EPSILON_RELATIVE_1; } private const double DBL_EPSILON_RELATIVE_1 = 1.1102230246251567e-016; /* smallest such that 1.0+DBL_EPSILON != 1.0 */ private double _m11; private double _m12; private double _m13; private double _m14; private double _m21; private double _m22; private double _m23; private double _m24; private double _m31; private double _m32; private double _m33; private double _m34; private double _offsetX; private double _offsetY; private double _offsetZ; private double _m44; } } #pragma warning restore 436
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Text.Encodings.Web; using Microsoft.AspNetCore.Antiforgery; using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.Extensions.Options; namespace Microsoft.AspNetCore.Mvc.ViewFeatures { /// <summary> /// Default implementation of <see cref="IHtmlGenerator"/>. /// </summary> public class DefaultHtmlGenerator : IHtmlGenerator { private const string HiddenListItem = @"<li style=""display:none""></li>"; private static readonly MethodInfo ConvertEnumFromStringMethod = typeof(DefaultHtmlGenerator).GetTypeInfo().GetDeclaredMethod(nameof(ConvertEnumFromString)); // See: (http://www.w3.org/TR/html5/forms.html#the-input-element) private static readonly string[] _placeholderInputTypes = new[] { "text", "search", "url", "tel", "email", "password", "number" }; // See: (http://www.w3.org/TR/html5/sec-forms.html#apply) private static readonly string[] _maxLengthInputTypes = new[] { "text", "search", "url", "tel", "email", "password" }; private readonly IAntiforgery _antiforgery; private readonly IModelMetadataProvider _metadataProvider; private readonly IUrlHelperFactory _urlHelperFactory; private readonly HtmlEncoder _htmlEncoder; private readonly ValidationHtmlAttributeProvider _validationAttributeProvider; /// <summary> /// Initializes a new instance of the <see cref="DefaultHtmlGenerator"/> class. /// </summary> /// <param name="antiforgery">The <see cref="IAntiforgery"/> instance which is used to generate antiforgery /// tokens.</param> /// <param name="optionsAccessor">The accessor for <see cref="MvcViewOptions"/>.</param> /// <param name="metadataProvider">The <see cref="IModelMetadataProvider"/>.</param> /// <param name="urlHelperFactory">The <see cref="IUrlHelperFactory"/>.</param> /// <param name="htmlEncoder">The <see cref="HtmlEncoder"/>.</param> /// <param name="validationAttributeProvider">The <see cref="ValidationHtmlAttributeProvider"/>.</param> public DefaultHtmlGenerator( IAntiforgery antiforgery, IOptions<MvcViewOptions> optionsAccessor, IModelMetadataProvider metadataProvider, IUrlHelperFactory urlHelperFactory, HtmlEncoder htmlEncoder, ValidationHtmlAttributeProvider validationAttributeProvider) { if (antiforgery == null) { throw new ArgumentNullException(nameof(antiforgery)); } if (optionsAccessor == null) { throw new ArgumentNullException(nameof(optionsAccessor)); } if (metadataProvider == null) { throw new ArgumentNullException(nameof(metadataProvider)); } if (urlHelperFactory == null) { throw new ArgumentNullException(nameof(urlHelperFactory)); } if (htmlEncoder == null) { throw new ArgumentNullException(nameof(htmlEncoder)); } if (validationAttributeProvider == null) { throw new ArgumentNullException(nameof(validationAttributeProvider)); } _antiforgery = antiforgery; _metadataProvider = metadataProvider; _urlHelperFactory = urlHelperFactory; _htmlEncoder = htmlEncoder; _validationAttributeProvider = validationAttributeProvider; // Underscores are fine characters in id's. IdAttributeDotReplacement = optionsAccessor.Value.HtmlHelperOptions.IdAttributeDotReplacement; } /// <summary> /// Gets or sets a value that indicates whether the <c>maxlength</c> attribute should be rendered for /// compatible HTML input elements, when they're bound to models marked with either /// <see cref="StringLengthAttribute"/> or <see cref="MaxLengthAttribute"/> attributes. /// </summary> /// <value>The default value is <see langword="true"/>.</value> /// <remarks> /// <para> /// If both attributes are specified, the one with the smaller value will be used for the rendered /// <c>maxlength</c> attribute. /// </para> /// <para> /// This property is currently ignored. /// </para> /// </remarks> protected bool AllowRenderingMaxLengthAttribute { get; } = true; /// <inheritdoc /> public string IdAttributeDotReplacement { get; } /// <inheritdoc /> public string Encode(string value) { return !string.IsNullOrEmpty(value) ? _htmlEncoder.Encode(value) : string.Empty; } /// <inheritdoc /> public string Encode(object value) { return (value != null) ? _htmlEncoder.Encode(value.ToString()) : string.Empty; } /// <inheritdoc /> public string FormatValue(object value, string format) { return ViewDataDictionary.FormatValue(value, format); } /// <inheritdoc /> public virtual TagBuilder GenerateActionLink( ViewContext viewContext, string linkText, string actionName, string controllerName, string protocol, string hostname, string fragment, object routeValues, object htmlAttributes) { if (viewContext == null) { throw new ArgumentNullException(nameof(viewContext)); } if (linkText == null) { throw new ArgumentNullException(nameof(linkText)); } var urlHelper = _urlHelperFactory.GetUrlHelper(viewContext); var url = urlHelper.Action(actionName, controllerName, routeValues, protocol, hostname, fragment); return GenerateLink(linkText, url, htmlAttributes); } /// <inheritdoc /> public virtual TagBuilder GeneratePageLink( ViewContext viewContext, string linkText, string pageName, string pageHandler, string protocol, string hostname, string fragment, object routeValues, object htmlAttributes) { if (viewContext == null) { throw new ArgumentNullException(nameof(viewContext)); } if (linkText == null) { throw new ArgumentNullException(nameof(linkText)); } var urlHelper = _urlHelperFactory.GetUrlHelper(viewContext); var url = urlHelper.Page(pageName, pageHandler, routeValues, protocol, hostname, fragment); return GenerateLink(linkText, url, htmlAttributes); } /// <inheritdoc /> public virtual IHtmlContent GenerateAntiforgery(ViewContext viewContext) { if (viewContext == null) { throw new ArgumentNullException(nameof(viewContext)); } var formContext = viewContext.FormContext; if (formContext.CanRenderAtEndOfForm) { // Inside a BeginForm/BeginRouteForm or a <form> tag helper. So, the antiforgery token might have // already been created and appended to the 'end form' content (the AntiForgeryToken HTML helper does // this) OR the <form> tag helper might have already generated an antiforgery token. if (formContext.HasAntiforgeryToken) { return HtmlString.Empty; } formContext.HasAntiforgeryToken = true; } return _antiforgery.GetHtml(viewContext.HttpContext); } /// <inheritdoc /> public virtual TagBuilder GenerateCheckBox( ViewContext viewContext, ModelExplorer modelExplorer, string expression, bool? isChecked, object htmlAttributes) { if (viewContext == null) { throw new ArgumentNullException(nameof(viewContext)); } if (modelExplorer != null) { // CheckBoxFor() case. That API does not support passing isChecked directly. Debug.Assert(!isChecked.HasValue); if (modelExplorer.Model != null) { if (bool.TryParse(modelExplorer.Model.ToString(), out var modelChecked)) { isChecked = modelChecked; } } } var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes); if (isChecked.HasValue && htmlAttributeDictionary != null) { // Explicit isChecked value must override "checked" in dictionary. htmlAttributeDictionary.Remove("checked"); } // Use ViewData only in CheckBox case (metadata null) and when the user didn't pass an isChecked value. return GenerateInput( viewContext, InputType.CheckBox, modelExplorer, expression, value: "true", useViewData: (modelExplorer == null && !isChecked.HasValue), isChecked: isChecked ?? false, setId: true, isExplicitValue: false, format: null, htmlAttributes: htmlAttributeDictionary); } /// <inheritdoc /> public virtual TagBuilder GenerateHiddenForCheckbox( ViewContext viewContext, ModelExplorer modelExplorer, string expression) { if (viewContext == null) { throw new ArgumentNullException(nameof(viewContext)); } var tagBuilder = new TagBuilder("input"); tagBuilder.MergeAttribute("type", GetInputTypeString(InputType.Hidden)); tagBuilder.MergeAttribute("value", "false"); tagBuilder.TagRenderMode = TagRenderMode.SelfClosing; var fullName = NameAndIdProvider.GetFullHtmlFieldName(viewContext, expression); if (!string.IsNullOrEmpty(fullName)) { tagBuilder.MergeAttribute("name", fullName); } return tagBuilder; } /// <inheritdoc /> public virtual TagBuilder GenerateForm( ViewContext viewContext, string actionName, string controllerName, object routeValues, string method, object htmlAttributes) { if (viewContext == null) { throw new ArgumentNullException(nameof(viewContext)); } var defaultMethod = false; if (string.IsNullOrEmpty(method)) { defaultMethod = true; } else if (HttpMethods.IsPost(method)) { defaultMethod = true; } string action; if (actionName == null && controllerName == null && routeValues == null && defaultMethod) { // Submit to the original URL in the special case that user called the BeginForm() overload without // parameters (except for the htmlAttributes parameter). Also reachable in the even-more-unusual case // that user called another BeginForm() overload with default argument values. var request = viewContext.HttpContext.Request; action = request.PathBase + request.Path + request.QueryString; } else { var urlHelper = _urlHelperFactory.GetUrlHelper(viewContext); action = urlHelper.Action(action: actionName, controller: controllerName, values: routeValues); } return GenerateFormCore(viewContext, action, method, htmlAttributes); } /// <inheritdoc /> public virtual TagBuilder GeneratePageForm( ViewContext viewContext, string pageName, string pageHandler, object routeValues, string fragment, string method, object htmlAttributes) { if (viewContext == null) { throw new ArgumentNullException(nameof(viewContext)); } var urlHelper = _urlHelperFactory.GetUrlHelper(viewContext); var action = urlHelper.Page(pageName, pageHandler, routeValues, protocol: null, host: null, fragment: fragment); return GenerateFormCore(viewContext, action, method, htmlAttributes); } /// <inheritdoc /> public TagBuilder GenerateRouteForm( ViewContext viewContext, string routeName, object routeValues, string method, object htmlAttributes) { if (viewContext == null) { throw new ArgumentNullException(nameof(viewContext)); } var urlHelper = _urlHelperFactory.GetUrlHelper(viewContext); var action = urlHelper.RouteUrl(routeName, routeValues); return GenerateFormCore(viewContext, action, method, htmlAttributes); } /// <inheritdoc /> public virtual TagBuilder GenerateHidden( ViewContext viewContext, ModelExplorer modelExplorer, string expression, object value, bool useViewData, object htmlAttributes) { if (viewContext == null) { throw new ArgumentNullException(nameof(viewContext)); } // Special-case opaque values and arbitrary binary data. if (value is byte[] byteArrayValue) { value = Convert.ToBase64String(byteArrayValue); } var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes); return GenerateInput( viewContext, InputType.Hidden, modelExplorer, expression, value, useViewData, isChecked: false, setId: true, isExplicitValue: true, format: null, htmlAttributes: htmlAttributeDictionary); } /// <inheritdoc /> public virtual TagBuilder GenerateLabel( ViewContext viewContext, ModelExplorer modelExplorer, string expression, string labelText, object htmlAttributes) { if (viewContext == null) { throw new ArgumentNullException(nameof(viewContext)); } if (modelExplorer == null) { throw new ArgumentNullException(nameof(modelExplorer)); } var resolvedLabelText = labelText ?? modelExplorer.Metadata.DisplayName ?? modelExplorer.Metadata.PropertyName; if (resolvedLabelText == null && expression != null) { var index = expression.LastIndexOf('.'); if (index == -1) { // Expression does not contain a dot separator. resolvedLabelText = expression; } else { resolvedLabelText = expression.Substring(index + 1); } } var tagBuilder = new TagBuilder("label"); var fullName = NameAndIdProvider.GetFullHtmlFieldName(viewContext, expression); var idString = NameAndIdProvider.CreateSanitizedId(viewContext, fullName, IdAttributeDotReplacement); tagBuilder.Attributes.Add("for", idString); tagBuilder.InnerHtml.SetContent(resolvedLabelText); tagBuilder.MergeAttributes(GetHtmlAttributeDictionaryOrNull(htmlAttributes), replaceExisting: true); return tagBuilder; } /// <inheritdoc /> public virtual TagBuilder GeneratePassword( ViewContext viewContext, ModelExplorer modelExplorer, string expression, object value, object htmlAttributes) { if (viewContext == null) { throw new ArgumentNullException(nameof(viewContext)); } var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes); return GenerateInput( viewContext, InputType.Password, modelExplorer, expression, value, useViewData: false, isChecked: false, setId: true, isExplicitValue: true, format: null, htmlAttributes: htmlAttributeDictionary); } /// <inheritdoc /> public virtual TagBuilder GenerateRadioButton( ViewContext viewContext, ModelExplorer modelExplorer, string expression, object value, bool? isChecked, object htmlAttributes) { if (viewContext == null) { throw new ArgumentNullException(nameof(viewContext)); } var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes); if (modelExplorer == null) { // RadioButton() case. Do not override checked attribute if isChecked is implicit. if (!isChecked.HasValue && (htmlAttributeDictionary == null || !htmlAttributeDictionary.ContainsKey("checked"))) { // Note value may be null if isChecked is non-null. if (value == null) { throw new ArgumentNullException(nameof(value)); } // isChecked not provided nor found in the given attributes; fall back to view data. var valueString = Convert.ToString(value, CultureInfo.CurrentCulture); isChecked = string.Equals( EvalString(viewContext, expression), valueString, StringComparison.OrdinalIgnoreCase); } } else { // RadioButtonFor() case. That API does not support passing isChecked directly. Debug.Assert(!isChecked.HasValue); // Need a value to determine isChecked. Debug.Assert(value != null); var model = modelExplorer.Model; var valueString = Convert.ToString(value, CultureInfo.CurrentCulture); isChecked = model != null && string.Equals(model.ToString(), valueString, StringComparison.OrdinalIgnoreCase); } if (isChecked.HasValue && htmlAttributeDictionary != null) { // Explicit isChecked value must override "checked" in dictionary. htmlAttributeDictionary.Remove("checked"); } return GenerateInput( viewContext, InputType.Radio, modelExplorer, expression, value, useViewData: false, isChecked: isChecked ?? false, setId: true, isExplicitValue: true, format: null, htmlAttributes: htmlAttributeDictionary); } /// <inheritdoc /> public virtual TagBuilder GenerateRouteLink( ViewContext viewContext, string linkText, string routeName, string protocol, string hostName, string fragment, object routeValues, object htmlAttributes) { if (viewContext == null) { throw new ArgumentNullException(nameof(viewContext)); } if (linkText == null) { throw new ArgumentNullException(nameof(linkText)); } var urlHelper = _urlHelperFactory.GetUrlHelper(viewContext); var url = urlHelper.RouteUrl(routeName, routeValues, protocol, hostName, fragment); return GenerateLink(linkText, url, htmlAttributes); } /// <inheritdoc /> public TagBuilder GenerateSelect( ViewContext viewContext, ModelExplorer modelExplorer, string optionLabel, string expression, IEnumerable<SelectListItem> selectList, bool allowMultiple, object htmlAttributes) { if (viewContext == null) { throw new ArgumentNullException(nameof(viewContext)); } var currentValues = GetCurrentValues(viewContext, modelExplorer, expression, allowMultiple); return GenerateSelect( viewContext, modelExplorer, optionLabel, expression, selectList, currentValues, allowMultiple, htmlAttributes); } /// <inheritdoc /> public virtual TagBuilder GenerateSelect( ViewContext viewContext, ModelExplorer modelExplorer, string optionLabel, string expression, IEnumerable<SelectListItem> selectList, ICollection<string> currentValues, bool allowMultiple, object htmlAttributes) { if (viewContext == null) { throw new ArgumentNullException(nameof(viewContext)); } var fullName = NameAndIdProvider.GetFullHtmlFieldName(viewContext, expression); var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes); if (!IsFullNameValid(fullName, htmlAttributeDictionary)) { throw new ArgumentException( Resources.FormatHtmlGenerator_FieldNameCannotBeNullOrEmpty( typeof(IHtmlHelper).FullName, nameof(IHtmlHelper.Editor), typeof(IHtmlHelper<>).FullName, nameof(IHtmlHelper<object>.EditorFor), "htmlFieldName"), nameof(expression)); } // If we got a null selectList, try to use ViewData to get the list of items. if (selectList == null) { selectList = GetSelectListItems(viewContext, expression); } modelExplorer = modelExplorer ?? ExpressionMetadataProvider.FromStringExpression(expression, viewContext.ViewData, _metadataProvider); // Convert each ListItem to an <option> tag and wrap them with <optgroup> if requested. var listItemBuilder = GenerateGroupsAndOptions(optionLabel, selectList, currentValues); var tagBuilder = new TagBuilder("select"); tagBuilder.InnerHtml.SetHtmlContent(listItemBuilder); tagBuilder.MergeAttributes(htmlAttributeDictionary); NameAndIdProvider.GenerateId(viewContext, tagBuilder, fullName, IdAttributeDotReplacement); if (!string.IsNullOrEmpty(fullName)) { tagBuilder.MergeAttribute("name", fullName, replaceExisting: true); } if (allowMultiple) { tagBuilder.MergeAttribute("multiple", "multiple"); } // If there are any errors for a named field, we add the css attribute. if (viewContext.ViewData.ModelState.TryGetValue(fullName, out var entry)) { if (entry.Errors.Count > 0) { tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName); } } AddValidationAttributes(viewContext, tagBuilder, modelExplorer, expression); return tagBuilder; } /// <inheritdoc /> public virtual TagBuilder GenerateTextArea( ViewContext viewContext, ModelExplorer modelExplorer, string expression, int rows, int columns, object htmlAttributes) { if (viewContext == null) { throw new ArgumentNullException(nameof(viewContext)); } if (rows < 0) { throw new ArgumentOutOfRangeException(nameof(rows), Resources.HtmlHelper_TextAreaParameterOutOfRange); } if (columns < 0) { throw new ArgumentOutOfRangeException( nameof(columns), Resources.HtmlHelper_TextAreaParameterOutOfRange); } var fullName = NameAndIdProvider.GetFullHtmlFieldName(viewContext, expression); var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes); if (!IsFullNameValid(fullName, htmlAttributeDictionary)) { throw new ArgumentException( Resources.FormatHtmlGenerator_FieldNameCannotBeNullOrEmpty( typeof(IHtmlHelper).FullName, nameof(IHtmlHelper.Editor), typeof(IHtmlHelper<>).FullName, nameof(IHtmlHelper<object>.EditorFor), "htmlFieldName"), nameof(expression)); } viewContext.ViewData.ModelState.TryGetValue(fullName, out var entry); var value = string.Empty; if (entry != null && entry.AttemptedValue != null) { value = entry.AttemptedValue; } else if (modelExplorer.Model != null) { value = modelExplorer.Model.ToString(); } var tagBuilder = new TagBuilder("textarea"); NameAndIdProvider.GenerateId(viewContext, tagBuilder, fullName, IdAttributeDotReplacement); tagBuilder.MergeAttributes(htmlAttributeDictionary, replaceExisting: true); if (rows > 0) { tagBuilder.MergeAttribute("rows", rows.ToString(CultureInfo.InvariantCulture), replaceExisting: true); } if (columns > 0) { tagBuilder.MergeAttribute( "cols", columns.ToString(CultureInfo.InvariantCulture), replaceExisting: true); } if (!string.IsNullOrEmpty(fullName)) { tagBuilder.MergeAttribute("name", fullName, replaceExisting: true); } AddPlaceholderAttribute(viewContext.ViewData, tagBuilder, modelExplorer, expression); AddMaxLengthAttribute(viewContext.ViewData, tagBuilder, modelExplorer, expression); AddValidationAttributes(viewContext, tagBuilder, modelExplorer, expression); // If there are any errors for a named field, we add this CSS attribute. if (entry != null && entry.Errors.Count > 0) { tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName); } // The first newline is always trimmed when a TextArea is rendered, so we add an extra one // in case the value being rendered is something like "\r\nHello" tagBuilder.InnerHtml.AppendLine(); tagBuilder.InnerHtml.Append(value); return tagBuilder; } /// <inheritdoc /> public virtual TagBuilder GenerateTextBox( ViewContext viewContext, ModelExplorer modelExplorer, string expression, object value, string format, object htmlAttributes) { if (viewContext == null) { throw new ArgumentNullException(nameof(viewContext)); } var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes); return GenerateInput( viewContext, InputType.Text, modelExplorer, expression, value, useViewData: (modelExplorer == null && value == null), isChecked: false, setId: true, isExplicitValue: true, format: format, htmlAttributes: htmlAttributeDictionary); } /// <inheritdoc /> public virtual TagBuilder GenerateValidationMessage( ViewContext viewContext, ModelExplorer modelExplorer, string expression, string message, string tag, object htmlAttributes) { if (viewContext == null) { throw new ArgumentNullException(nameof(viewContext)); } var fullName = NameAndIdProvider.GetFullHtmlFieldName(viewContext, expression); var htmlAttributeDictionary = GetHtmlAttributeDictionaryOrNull(htmlAttributes); if (!IsFullNameValid(fullName, htmlAttributeDictionary, fallbackAttributeName: "data-valmsg-for")) { throw new ArgumentException( Resources.FormatHtmlGenerator_FieldNameCannotBeNullOrEmpty( typeof(IHtmlHelper).FullName, nameof(IHtmlHelper.Editor), typeof(IHtmlHelper<>).FullName, nameof(IHtmlHelper<object>.EditorFor), "htmlFieldName"), nameof(expression)); } var formContext = viewContext.ClientValidationEnabled ? viewContext.FormContext : null; if (!viewContext.ViewData.ModelState.ContainsKey(fullName) && formContext == null) { return null; } var tryGetModelStateResult = viewContext.ViewData.ModelState.TryGetValue(fullName, out var entry); var modelErrors = tryGetModelStateResult ? entry.Errors : null; ModelError modelError = null; if (modelErrors != null && modelErrors.Count != 0) { modelError = modelErrors.FirstOrDefault(m => !string.IsNullOrEmpty(m.ErrorMessage)) ?? modelErrors[0]; } if (modelError == null && formContext == null) { return null; } // Even if there are no model errors, we generate the span and add the validation message // if formContext is not null. if (string.IsNullOrEmpty(tag)) { tag = viewContext.ValidationMessageElement; } var tagBuilder = new TagBuilder(tag); tagBuilder.MergeAttributes(htmlAttributeDictionary); // Only the style of the span is changed according to the errors if message is null or empty. // Otherwise the content and style is handled by the client-side validation. var className = (modelError != null) ? HtmlHelper.ValidationMessageCssClassName : HtmlHelper.ValidationMessageValidCssClassName; tagBuilder.AddCssClass(className); if (!string.IsNullOrEmpty(message)) { tagBuilder.InnerHtml.SetContent(message); } else if (modelError != null) { modelExplorer = modelExplorer ?? ExpressionMetadataProvider.FromStringExpression( expression, viewContext.ViewData, _metadataProvider); tagBuilder.InnerHtml.SetContent( ValidationHelpers.GetModelErrorMessageOrDefault(modelError, entry, modelExplorer)); } if (formContext != null) { if (!string.IsNullOrEmpty(fullName)) { tagBuilder.MergeAttribute("data-valmsg-for", fullName); } var replaceValidationMessageContents = string.IsNullOrEmpty(message); tagBuilder.MergeAttribute("data-valmsg-replace", replaceValidationMessageContents.ToString().ToLowerInvariant()); } return tagBuilder; } /// <inheritdoc /> public virtual TagBuilder GenerateValidationSummary( ViewContext viewContext, bool excludePropertyErrors, string message, string headerTag, object htmlAttributes) { if (viewContext == null) { throw new ArgumentNullException(nameof(viewContext)); } var viewData = viewContext.ViewData; if (!viewContext.ClientValidationEnabled && viewData.ModelState.IsValid) { // Client-side validation is not enabled to add to the generated element and element will be empty. return null; } if (excludePropertyErrors && (!viewData.ModelState.TryGetValue(viewData.TemplateInfo.HtmlFieldPrefix, out var entryForModel) || entryForModel.Errors.Count == 0)) { // Client-side validation (if enabled) will not affect the generated element and element will be empty. return null; } TagBuilder messageTag; if (string.IsNullOrEmpty(message)) { messageTag = null; } else { if (string.IsNullOrEmpty(headerTag)) { headerTag = viewContext.ValidationSummaryMessageElement; } messageTag = new TagBuilder(headerTag); messageTag.InnerHtml.SetContent(message); } // If excludePropertyErrors is true, describe any validation issue with the current model in a single item. // Otherwise, list individual property errors. var isHtmlSummaryModified = false; var modelStates = ValidationHelpers.GetModelStateList(viewData, excludePropertyErrors); var htmlSummary = new TagBuilder("ul"); foreach (var modelState in modelStates) { // Perf: Avoid allocations for (var i = 0; i < modelState.Errors.Count; i++) { var modelError = modelState.Errors[i]; var errorText = ValidationHelpers.GetModelErrorMessageOrDefault(modelError); if (!string.IsNullOrEmpty(errorText)) { var listItem = new TagBuilder("li"); listItem.InnerHtml.SetContent(errorText); htmlSummary.InnerHtml.AppendLine(listItem); isHtmlSummaryModified = true; } } } if (!isHtmlSummaryModified) { htmlSummary.InnerHtml.AppendHtml(HiddenListItem); htmlSummary.InnerHtml.AppendLine(); } var tagBuilder = new TagBuilder("div"); tagBuilder.MergeAttributes(GetHtmlAttributeDictionaryOrNull(htmlAttributes)); if (viewData.ModelState.IsValid) { tagBuilder.AddCssClass(HtmlHelper.ValidationSummaryValidCssClassName); } else { tagBuilder.AddCssClass(HtmlHelper.ValidationSummaryCssClassName); } if (messageTag != null) { tagBuilder.InnerHtml.AppendLine(messageTag); } tagBuilder.InnerHtml.AppendHtml(htmlSummary); if (viewContext.ClientValidationEnabled && !excludePropertyErrors) { // Inform the client where to replace the list of property errors after validation. tagBuilder.MergeAttribute("data-valmsg-summary", "true"); } return tagBuilder; } /// <inheritdoc /> public virtual ICollection<string> GetCurrentValues( ViewContext viewContext, ModelExplorer modelExplorer, string expression, bool allowMultiple) { if (viewContext == null) { throw new ArgumentNullException(nameof(viewContext)); } var fullName = NameAndIdProvider.GetFullHtmlFieldName(viewContext, expression); var type = allowMultiple ? typeof(string[]) : typeof(string); var rawValue = GetModelStateValue(viewContext, fullName, type); // If ModelState did not contain a current value, fall back to ViewData- or ModelExplorer-supplied value. if (rawValue == null) { if (modelExplorer == null) { // Html.DropDownList() and Html.ListBox() helper case. rawValue = viewContext.ViewData.Eval(expression); if (rawValue is IEnumerable<SelectListItem>) { // This ViewData item contains the fallback selectList collection for GenerateSelect(). // Do not try to use this collection. rawValue = null; } } else { // <select/>, Html.DropDownListFor() and Html.ListBoxFor() helper case. Do not use ViewData. rawValue = modelExplorer.Model; } if (rawValue == null) { return null; } } // Convert raw value to a collection. IEnumerable rawValues; if (allowMultiple) { rawValues = rawValue as IEnumerable; if (rawValues == null || rawValues is string) { throw new InvalidOperationException( Resources.FormatHtmlHelper_SelectExpressionNotEnumerable(nameof(expression))); } } else { rawValues = new[] { rawValue }; } modelExplorer = modelExplorer ?? ExpressionMetadataProvider.FromStringExpression(expression, viewContext.ViewData, _metadataProvider); var metadata = modelExplorer.Metadata; if (allowMultiple && metadata.IsEnumerableType) { metadata = metadata.ElementMetadata; } var enumNames = metadata.EnumNamesAndValues; var isTargetEnum = metadata.IsEnum; // Logic below assumes isTargetEnum and enumNames are consistent. Confirm that expectation is met. Debug.Assert(isTargetEnum ^ enumNames == null); var innerType = metadata.UnderlyingOrModelType; // Convert raw value collection to strings. var currentValues = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (var value in rawValues) { // Add original or converted string. var stringValue = (value as string) ?? Convert.ToString(value, CultureInfo.CurrentCulture); // Do not add simple names of enum properties here because whitespace isn't relevant for their binding. // Will add matching names just below. if (enumNames == null || !enumNames.ContainsKey(stringValue.Trim())) { currentValues.Add(stringValue); } // Remainder handles isEnum cases. Convert.ToString() returns field names for enum values but select // list may (well, should) contain integer values. var enumValue = value as Enum; if (isTargetEnum && enumValue == null && value != null) { var valueType = value.GetType(); if (typeof(long).IsAssignableFrom(valueType) || typeof(ulong).IsAssignableFrom(valueType)) { // E.g. user added an int to a ViewData entry and called a string-based HTML helper. enumValue = ConvertEnumFromInteger(value, innerType); } else if (!string.IsNullOrEmpty(stringValue)) { // E.g. got a string from ModelState. var methodInfo = ConvertEnumFromStringMethod.MakeGenericMethod(innerType); enumValue = (Enum)methodInfo.Invoke(obj: null, parameters: new[] { stringValue }); } } if (enumValue != null) { // Add integer value. var integerString = enumValue.ToString("d"); currentValues.Add(integerString); // isTargetEnum may be false when raw value has a different type than the target e.g. ViewData // contains enum values and property has type int or string. if (isTargetEnum) { // Add all simple names for this value. var matchingNames = enumNames .Where(kvp => string.Equals(integerString, kvp.Value, StringComparison.Ordinal)) .Select(kvp => kvp.Key); foreach (var name in matchingNames) { currentValues.Add(name); } } } } return currentValues; } internal static string EvalString(ViewContext viewContext, string key, string format) { return Convert.ToString(viewContext.ViewData.Eval(key, format), CultureInfo.CurrentCulture); } /// <remarks> /// Not used directly in HtmlHelper. Exposed for use in DefaultDisplayTemplates. /// </remarks> internal static TagBuilder GenerateOption(SelectListItem item, string text) { return GenerateOption(item, text, item.Selected); } internal static TagBuilder GenerateOption(SelectListItem item, string text, bool selected) { var tagBuilder = new TagBuilder("option"); tagBuilder.InnerHtml.SetContent(text); if (item.Value != null) { tagBuilder.Attributes["value"] = item.Value; } if (selected) { tagBuilder.Attributes["selected"] = "selected"; } if (item.Disabled) { tagBuilder.Attributes["disabled"] = "disabled"; } return tagBuilder; } internal static object GetModelStateValue(ViewContext viewContext, string key, Type destinationType) { if (viewContext.ViewData.ModelState.TryGetValue(key, out var entry) && entry.RawValue != null) { return ModelBindingHelper.ConvertTo(entry.RawValue, destinationType, culture: null); } return null; } /// <summary> /// Generate a &lt;form&gt; element. /// </summary> /// <param name="viewContext">A <see cref="ViewContext"/> instance for the current scope.</param> /// <param name="action">The URL where the form-data should be submitted.</param> /// <param name="method">The HTTP method for processing the form, either GET or POST.</param> /// <param name="htmlAttributes"> /// An <see cref="object"/> that contains the HTML attributes for the element. Alternatively, an /// <see cref="IDictionary{String, Object}"/> instance containing the HTML attributes. /// </param> /// <returns> /// A <see cref="TagBuilder"/> instance for the &lt;/form&gt; element. /// </returns> protected virtual TagBuilder GenerateFormCore( ViewContext viewContext, string action, string method, object htmlAttributes) { if (viewContext == null) { throw new ArgumentNullException(nameof(viewContext)); } var tagBuilder = new TagBuilder("form"); tagBuilder.MergeAttributes(GetHtmlAttributeDictionaryOrNull(htmlAttributes)); // action is implicitly generated from other parameters, so htmlAttributes take precedence. tagBuilder.MergeAttribute("action", action); if (string.IsNullOrEmpty(method)) { // Occurs only when called from a tag helper. method = "post"; } // For tag helpers, htmlAttributes will be null; replaceExisting value does not matter. // method is an explicit parameter to HTML helpers, so it takes precedence over the htmlAttributes. tagBuilder.MergeAttribute("method", method, replaceExisting: true); return tagBuilder; } /// <summary> /// Generate an input tag. /// </summary> /// <param name="viewContext">The <see cref="ViewContext"/>.</param> /// <param name="inputType">The <see cref="InputType"/>.</param> /// <param name="modelExplorer">The <see cref="ModelExplorer"/>.</param> /// <param name="expression">The expression.</param> /// <param name="value">The value.</param> /// <param name="useViewData">Whether to use view data.</param> /// <param name="isChecked">If the input is checked.</param> /// <param name="setId">Whether this should set id.</param> /// <param name="isExplicitValue">Whether this is an explicit value.</param> /// <param name="format">The format.</param> /// <param name="htmlAttributes">The html attributes.</param> /// <returns></returns> protected virtual TagBuilder GenerateInput( ViewContext viewContext, InputType inputType, ModelExplorer modelExplorer, string expression, object value, bool useViewData, bool isChecked, bool setId, bool isExplicitValue, string format, IDictionary<string, object> htmlAttributes) { if (viewContext == null) { throw new ArgumentNullException(nameof(viewContext)); } // Not valid to use TextBoxForModel() and so on in a top-level view; would end up with an unnamed input // elements. But we support the *ForModel() methods in any lower-level template, once HtmlFieldPrefix is // non-empty. var fullName = NameAndIdProvider.GetFullHtmlFieldName(viewContext, expression); if (!IsFullNameValid(fullName, htmlAttributes)) { throw new ArgumentException( Resources.FormatHtmlGenerator_FieldNameCannotBeNullOrEmpty( typeof(IHtmlHelper).FullName, nameof(IHtmlHelper.Editor), typeof(IHtmlHelper<>).FullName, nameof(IHtmlHelper<object>.EditorFor), "htmlFieldName"), nameof(expression)); } var inputTypeString = GetInputTypeString(inputType); var tagBuilder = new TagBuilder("input") { TagRenderMode = TagRenderMode.SelfClosing, }; tagBuilder.MergeAttributes(htmlAttributes); tagBuilder.MergeAttribute("type", inputTypeString); if (!string.IsNullOrEmpty(fullName)) { tagBuilder.MergeAttribute("name", fullName, replaceExisting: true); } var suppliedTypeString = tagBuilder.Attributes["type"]; if (_placeholderInputTypes.Contains(suppliedTypeString)) { AddPlaceholderAttribute(viewContext.ViewData, tagBuilder, modelExplorer, expression); } if (_maxLengthInputTypes.Contains(suppliedTypeString)) { AddMaxLengthAttribute(viewContext.ViewData, tagBuilder, modelExplorer, expression); } var valueParameter = FormatValue(value, format); var usedModelState = false; switch (inputType) { case InputType.CheckBox: var modelStateWasChecked = GetModelStateValue(viewContext, fullName, typeof(bool)) as bool?; if (modelStateWasChecked.HasValue) { isChecked = modelStateWasChecked.Value; usedModelState = true; } goto case InputType.Radio; case InputType.Radio: if (!usedModelState) { if (GetModelStateValue(viewContext, fullName, typeof(string)) is string modelStateValue) { isChecked = string.Equals(modelStateValue, valueParameter, StringComparison.Ordinal); usedModelState = true; } } if (!usedModelState && useViewData) { isChecked = EvalBoolean(viewContext, expression); } if (isChecked) { tagBuilder.MergeAttribute("checked", "checked"); } tagBuilder.MergeAttribute("value", valueParameter, isExplicitValue); break; case InputType.Password: if (value != null) { tagBuilder.MergeAttribute("value", valueParameter, isExplicitValue); } break; case InputType.Text: default: var attributeValue = (string)GetModelStateValue(viewContext, fullName, typeof(string)); if (attributeValue == null) { attributeValue = useViewData ? EvalString(viewContext, expression, format) : valueParameter; } var addValue = true; object typeAttributeValue; if (htmlAttributes != null && htmlAttributes.TryGetValue("type", out typeAttributeValue)) { var typeAttributeString = typeAttributeValue.ToString(); if (string.Equals(typeAttributeString, "file", StringComparison.OrdinalIgnoreCase) || string.Equals(typeAttributeString, "image", StringComparison.OrdinalIgnoreCase)) { // 'value' attribute is not needed for 'file' and 'image' input types. addValue = false; } } if (addValue) { tagBuilder.MergeAttribute("value", attributeValue, replaceExisting: isExplicitValue); } break; } if (setId) { NameAndIdProvider.GenerateId(viewContext, tagBuilder, fullName, IdAttributeDotReplacement); } // If there are any errors for a named field, we add the CSS attribute. if (viewContext.ViewData.ModelState.TryGetValue(fullName, out var entry) && entry.Errors.Count > 0) { tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName); } AddValidationAttributes(viewContext, tagBuilder, modelExplorer, expression); return tagBuilder; } /// <summary> /// Generate a link. /// </summary> /// <param name="linkText">The text for the link.</param> /// <param name="url">The url for the link.</param> /// <param name="htmlAttributes">The html attributes.</param> /// <returns>The <see cref="TagBuilder"/>.</returns> protected virtual TagBuilder GenerateLink( string linkText, string url, object htmlAttributes) { if (linkText == null) { throw new ArgumentNullException(nameof(linkText)); } var tagBuilder = new TagBuilder("a"); tagBuilder.InnerHtml.SetContent(linkText); tagBuilder.MergeAttributes(GetHtmlAttributeDictionaryOrNull(htmlAttributes)); tagBuilder.MergeAttribute("href", url); return tagBuilder; } /// <summary> /// Adds a placeholder attribute to the <paramref name="tagBuilder" />. /// </summary> /// <param name="viewData">A <see cref="ViewDataDictionary"/> instance for the current scope.</param> /// <param name="tagBuilder">A <see cref="TagBuilder"/> instance.</param> /// <param name="modelExplorer">The <see cref="ModelExplorer"/> for the <paramref name="expression"/>.</param> /// <param name="expression">Expression name, relative to the current model.</param> protected virtual void AddPlaceholderAttribute( ViewDataDictionary viewData, TagBuilder tagBuilder, ModelExplorer modelExplorer, string expression) { modelExplorer = modelExplorer ?? ExpressionMetadataProvider.FromStringExpression( expression, viewData, _metadataProvider); var placeholder = modelExplorer.Metadata.Placeholder; if (!string.IsNullOrEmpty(placeholder)) { tagBuilder.MergeAttribute("placeholder", placeholder); } } /// <summary> /// Adds a <c>maxlength</c> attribute to the <paramref name="tagBuilder" />. /// </summary> /// <param name="viewData">A <see cref="ViewDataDictionary"/> instance for the current scope.</param> /// <param name="tagBuilder">A <see cref="TagBuilder"/> instance.</param> /// <param name="modelExplorer">The <see cref="ModelExplorer"/> for the <paramref name="expression"/>.</param> /// <param name="expression">Expression name, relative to the current model.</param> protected virtual void AddMaxLengthAttribute( ViewDataDictionary viewData, TagBuilder tagBuilder, ModelExplorer modelExplorer, string expression) { modelExplorer = modelExplorer ?? ExpressionMetadataProvider.FromStringExpression( expression, viewData, _metadataProvider); int? maxLengthValue = null; foreach (var attribute in modelExplorer.Metadata.ValidatorMetadata) { if (attribute is MaxLengthAttribute maxLengthAttribute && (!maxLengthValue.HasValue || maxLengthValue.Value > maxLengthAttribute.Length)) { maxLengthValue = maxLengthAttribute.Length; } else if (attribute is StringLengthAttribute stringLengthAttribute && (!maxLengthValue.HasValue || maxLengthValue.Value > stringLengthAttribute.MaximumLength)) { maxLengthValue = stringLengthAttribute.MaximumLength; } } if (maxLengthValue.HasValue) { tagBuilder.MergeAttribute("maxlength", maxLengthValue.Value.ToString(CultureInfo.InvariantCulture)); } } /// <summary> /// Adds validation attributes to the <paramref name="tagBuilder" /> if client validation /// is enabled. /// </summary> /// <param name="viewContext">A <see cref="ViewContext"/> instance for the current scope.</param> /// <param name="tagBuilder">A <see cref="TagBuilder"/> instance.</param> /// <param name="modelExplorer">The <see cref="ModelExplorer"/> for the <paramref name="expression"/>.</param> /// <param name="expression">Expression name, relative to the current model.</param> protected virtual void AddValidationAttributes( ViewContext viewContext, TagBuilder tagBuilder, ModelExplorer modelExplorer, string expression) { modelExplorer = modelExplorer ?? ExpressionMetadataProvider.FromStringExpression( expression, viewContext.ViewData, _metadataProvider); _validationAttributeProvider.AddAndTrackValidationAttributes( viewContext, modelExplorer, expression, tagBuilder.Attributes); } private static Enum ConvertEnumFromInteger(object value, Type targetType) { try { return (Enum)Enum.ToObject(targetType, value); } catch (Exception exception) when (exception is FormatException || exception.InnerException is FormatException) { // The integer was too large for this enum type. return null; } } private static object ConvertEnumFromString<TEnum>(string value) where TEnum : struct { if (Enum.TryParse(value, out TEnum enumValue)) { return enumValue; } // Do not return default(TEnum) when parse was unsuccessful. return null; } private static bool EvalBoolean(ViewContext viewContext, string key) { return Convert.ToBoolean(viewContext.ViewData.Eval(key), CultureInfo.InvariantCulture); } private static string EvalString(ViewContext viewContext, string key) { return Convert.ToString(viewContext.ViewData.Eval(key), CultureInfo.CurrentCulture); } // Only need a dictionary if htmlAttributes is non-null. TagBuilder.MergeAttributes() is fine with null. private static IDictionary<string, object> GetHtmlAttributeDictionaryOrNull(object htmlAttributes) { IDictionary<string, object> htmlAttributeDictionary = null; if (htmlAttributes != null) { htmlAttributeDictionary = htmlAttributes as IDictionary<string, object>; if (htmlAttributeDictionary == null) { htmlAttributeDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes); } } return htmlAttributeDictionary; } private static string GetInputTypeString(InputType inputType) { switch (inputType) { case InputType.CheckBox: return "checkbox"; case InputType.Hidden: return "hidden"; case InputType.Password: return "password"; case InputType.Radio: return "radio"; case InputType.Text: return "text"; default: return "text"; } } private static IEnumerable<SelectListItem> GetSelectListItems( ViewContext viewContext, string expression) { if (viewContext == null) { throw new ArgumentNullException(nameof(viewContext)); } // Method is called only if user did not pass a select list in. They must provide select list items in the // ViewData dictionary and definitely not as the Model. (Even if the Model datatype were correct, a // <select> element generated for a collection of SelectListItems would be useless.) var value = viewContext.ViewData.Eval(expression); // First check whether above evaluation was successful and did not match ViewData.Model. if (value == null || value == viewContext.ViewData.Model) { throw new InvalidOperationException(Resources.FormatHtmlHelper_MissingSelectData( $"IEnumerable<{nameof(SelectListItem)}>", expression)); } // Second check the Eval() call returned a collection of SelectListItems. if (!(value is IEnumerable<SelectListItem> selectList)) { throw new InvalidOperationException(Resources.FormatHtmlHelper_WrongSelectDataType( expression, value.GetType().FullName, $"IEnumerable<{nameof(SelectListItem)}>")); } return selectList; } private static bool IsFullNameValid(string fullName, IDictionary<string, object> htmlAttributeDictionary) { return IsFullNameValid(fullName, htmlAttributeDictionary, fallbackAttributeName: "name"); } private static bool IsFullNameValid( string fullName, IDictionary<string, object> htmlAttributeDictionary, string fallbackAttributeName) { if (string.IsNullOrEmpty(fullName)) { // fullName==null is normally an error because name="" is not valid in HTML 5. if (htmlAttributeDictionary == null) { return false; } // Check if user has provided an explicit name attribute. // Generalized a bit because other attributes e.g. data-valmsg-for refer to element names. htmlAttributeDictionary.TryGetValue(fallbackAttributeName, out var attributeObject); var attributeString = Convert.ToString(attributeObject, CultureInfo.InvariantCulture); if (string.IsNullOrEmpty(attributeString)) { return false; } } return true; } /// <inheritdoc /> public IHtmlContent GenerateGroupsAndOptions(string optionLabel, IEnumerable<SelectListItem> selectList) { return GenerateGroupsAndOptions(optionLabel, selectList, currentValues: null); } private IHtmlContent GenerateGroupsAndOptions( string optionLabel, IEnumerable<SelectListItem> selectList, ICollection<string> currentValues) { if (!(selectList is IList<SelectListItem> itemsList)) { itemsList = selectList.ToList(); } var count = itemsList.Count; if (optionLabel != null) { count++; } // Short-circuit work below if there's nothing to add. if (count == 0) { return HtmlString.Empty; } var listItemBuilder = new HtmlContentBuilder(count); // Make optionLabel the first item that gets rendered. if (optionLabel != null) { listItemBuilder.AppendLine(GenerateOption( new SelectListItem() { Text = optionLabel, Value = string.Empty, Selected = false, }, currentValues: null)); } // Group items in the SelectList if requested. // The worst case complexity of this algorithm is O(number of groups*n). // If there aren't any groups, it is O(n) where n is number of items in the list. var optionGenerated = new bool[itemsList.Count]; for (var i = 0; i < itemsList.Count; i++) { if (!optionGenerated[i]) { var item = itemsList[i]; var optGroup = item.Group; if (optGroup != null) { var groupBuilder = new TagBuilder("optgroup"); if (optGroup.Name != null) { groupBuilder.MergeAttribute("label", optGroup.Name); } if (optGroup.Disabled) { groupBuilder.MergeAttribute("disabled", "disabled"); } groupBuilder.InnerHtml.AppendLine(); for (var j = i; j < itemsList.Count; j++) { var groupItem = itemsList[j]; if (!optionGenerated[j] && object.ReferenceEquals(optGroup, groupItem.Group)) { groupBuilder.InnerHtml.AppendLine(GenerateOption(groupItem, currentValues)); optionGenerated[j] = true; } } listItemBuilder.AppendLine(groupBuilder); } else { listItemBuilder.AppendLine(GenerateOption(item, currentValues)); optionGenerated[i] = true; } } } return listItemBuilder; } private IHtmlContent GenerateOption(SelectListItem item, ICollection<string> currentValues) { var selected = item.Selected; if (currentValues != null) { var value = item.Value ?? item.Text; selected = currentValues.Contains(value); } var tagBuilder = GenerateOption(item, item.Text, selected); return tagBuilder; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Utilities { public class PatternMatcherTests { [Fact] public void BreakIntoCharacterParts_EmptyIdentifier() { VerifyBreakIntoCharacterParts(string.Empty, new string[0]); } [Fact] public void BreakIntoCharacterParts_SimpleIdentifier() { VerifyBreakIntoCharacterParts("foo", "foo"); } [Fact] public void BreakIntoCharacterParts_PrefixUnderscoredIdentifier() { VerifyBreakIntoCharacterParts("_foo", "_", "foo"); } [Fact] public void BreakIntoCharacterParts_UnderscoredIdentifier() { VerifyBreakIntoCharacterParts("f_oo", "f", "_", "oo"); } [Fact] public void BreakIntoCharacterParts_PostfixUnderscoredIdentifier() { VerifyBreakIntoCharacterParts("foo_", "foo", "_"); } [Fact] public void BreakIntoCharacterParts_PrefixUnderscoredIdentifierWithCapital() { VerifyBreakIntoCharacterParts("_Foo", "_", "Foo"); } [Fact] public void BreakIntoCharacterParts_MUnderscorePrefixed() { VerifyBreakIntoCharacterParts("m_foo", "m", "_", "foo"); } [Fact] public void BreakIntoCharacterParts_CamelCaseIdentifier() { VerifyBreakIntoCharacterParts("FogBar", "Fog", "Bar"); } [Fact] public void BreakIntoCharacterParts_MixedCaseIdentifier() { VerifyBreakIntoCharacterParts("fogBar", "fog", "Bar"); } [Fact] public void BreakIntoCharacterParts_TwoCharacterCapitalIdentifier() { VerifyBreakIntoCharacterParts("UIElement", "U", "I", "Element"); } [Fact] public void BreakIntoCharacterParts_NumberSuffixedIdentifier() { VerifyBreakIntoCharacterParts("Foo42", "Foo", "42"); } [Fact] public void BreakIntoCharacterParts_NumberContainingIdentifier() { VerifyBreakIntoCharacterParts("Fog42Bar", "Fog", "42", "Bar"); } [Fact] public void BreakIntoCharacterParts_NumberPrefixedIdentifier() { // 42Bar is not a valid identifier in either C# or VB, but it is entirely conceivable the user might be // typing it trying to do a substring match VerifyBreakIntoCharacterParts("42Bar", "42", "Bar"); } [Fact] [WorkItem(544296)] public void BreakIntoWordParts_VarbatimIdentifier() { VerifyBreakIntoWordParts("@int:", "int"); } [Fact] [WorkItem(537875)] public void BreakIntoWordParts_AllCapsConstant() { VerifyBreakIntoWordParts("C_STYLE_CONSTANT", "C", "_", "STYLE", "_", "CONSTANT"); } [Fact] [WorkItem(540087)] public void BreakIntoWordParts_SingleLetterPrefix1() { VerifyBreakIntoWordParts("UInteger", "U", "Integer"); } [Fact] [WorkItem(540087)] public void BreakIntoWordParts_SingleLetterPrefix2() { VerifyBreakIntoWordParts("IDisposable", "I", "Disposable"); } [Fact] [WorkItem(540087)] public void BreakIntoWordParts_TwoCharacterCapitalIdentifier() { VerifyBreakIntoWordParts("UIElement", "UI", "Element"); } [Fact] [WorkItem(540087)] public void BreakIntoWordParts_XDocument() { VerifyBreakIntoWordParts("XDocument", "X", "Document"); } [Fact] [WorkItem(540087)] public void BreakIntoWordParts_XMLDocument1() { VerifyBreakIntoWordParts("XMLDocument", "XML", "Document"); } [Fact] public void BreakIntoWordParts_XMLDocument2() { VerifyBreakIntoWordParts("XmlDocument", "Xml", "Document"); } [Fact] public void BreakIntoWordParts_TwoUppercaseCharacters() { VerifyBreakIntoWordParts("SimpleUIElement", "Simple", "UI", "Element"); } private void VerifyBreakIntoWordParts(string original, params string[] parts) { AssertEx.Equal(parts, BreakIntoWordParts(original)); } private void VerifyBreakIntoCharacterParts(string original, params string[] parts) { AssertEx.Equal(parts, BreakIntoCharacterParts(original)); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveExact() { var match = TryMatchSingleWordPattern("Foo", "Foo"); Assert.Equal(PatternMatchKind.Exact, match.Value.Kind); Assert.Equal(true, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_SingleWordPreferCaseSensitiveExactInsensitive() { var match = TryMatchSingleWordPattern("foo", "Foo"); Assert.Equal(PatternMatchKind.Exact, match.Value.Kind); Assert.Equal(false, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitivePrefix() { var match = TryMatchSingleWordPattern("Foo", "Fo"); Assert.Equal(PatternMatchKind.Prefix, match.Value.Kind); Assert.Equal(true, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitivePrefixCaseInsensitive() { var match = TryMatchSingleWordPattern("Foo", "fo"); Assert.Equal(PatternMatchKind.Prefix, match.Value.Kind); Assert.Equal(false, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveCamelCaseMatchSimple() { var match = TryMatchSingleWordPattern("FogBar", "FB"); Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind); Assert.Equal(true, match.Value.IsCaseSensitive); Assert.InRange((int)match.Value.CamelCaseWeight, 1, int.MaxValue); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveCamelCaseMatchPartialPattern() { var match = TryMatchSingleWordPattern("FogBar", "FoB"); Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind); Assert.Equal(true, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveCamelCaseMatchToLongPattern1() { var match = TryMatchSingleWordPattern("FogBar", "FBB"); Assert.Null(match); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveCamelCaseMatchToLongPattern2() { var match = TryMatchSingleWordPattern("FogBar", "FoooB"); Assert.Null(match); } [Fact] public void TryMatchSingleWordPattern_CamelCaseMatchPartiallyUnmatched() { var match = TryMatchSingleWordPattern("FogBarBaz", "FZ"); Assert.Null(match); } [Fact] public void TryMatchSingleWordPattern_CamelCaseMatchCompletelyUnmatched() { var match = TryMatchSingleWordPattern("FogBarBaz", "ZZ"); Assert.Null(match); } [Fact] [WorkItem(544975)] public void TryMatchSingleWordPattern_TwoUppercaseCharacters() { var match = TryMatchSingleWordPattern("SimpleUIElement", "SiUI"); Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind); Assert.True(match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveLowercasePattern() { var match = TryMatchSingleWordPattern("FogBar", "b"); Assert.Equal(PatternMatchKind.Substring, match.Value.Kind); Assert.False(match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveLowercasePattern2() { var match = TryMatchSingleWordPattern("FogBar", "fB"); Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind); Assert.Equal(false, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveTryUnderscoredName() { var match = TryMatchSingleWordPattern("_fogBar", "_fB"); Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind); Assert.Equal(true, match.Value.IsCaseSensitive); } public void TryMatchSingleWordPattern_PreferCaseSensitiveTryUnderscoredName2() { var match = TryMatchSingleWordPattern("_fogBar", "fB"); Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind); Assert.Equal(true, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveTryUnderscoredNameInsensitive() { var match = TryMatchSingleWordPattern("_FogBar", "_fB"); Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind); Assert.Equal(false, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveMiddleUnderscore() { var match = TryMatchSingleWordPattern("Fog_Bar", "FB"); Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind); Assert.Equal(true, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveMiddleUnderscore2() { var match = TryMatchSingleWordPattern("Fog_Bar", "F_B"); Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind); Assert.Equal(true, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveMiddleUnderscore3() { var match = TryMatchSingleWordPattern("Fog_Bar", "F__B"); Assert.Null(match); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveMiddleUnderscore4() { var match = TryMatchSingleWordPattern("Fog_Bar", "f_B"); Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind); Assert.Equal(false, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveMiddleUnderscore5() { var match = TryMatchSingleWordPattern("Fog_Bar", "F_b"); Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind); Assert.Equal(false, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveRelativeWeights1() { var match1 = TryMatchSingleWordPattern("FogBarBaz", "FB"); var match2 = TryMatchSingleWordPattern("FooFlobBaz", "FB"); // We should prefer something that starts at the beginning if possible Assert.InRange((int)match1.Value.CamelCaseWeight, (int)match2.Value.CamelCaseWeight + 1, int.MaxValue); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveRelativeWeights2() { var match1 = TryMatchSingleWordPattern("BazBarFooFooFoo", "FFF"); var match2 = TryMatchSingleWordPattern("BazFogBarFooFoo", "FFF"); // Contiguous things should also be preferred Assert.InRange((int)match1.Value.CamelCaseWeight, (int)match2.Value.CamelCaseWeight + 1, int.MaxValue); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveRelativeWeights3() { var match1 = TryMatchSingleWordPattern("FogBarFooFoo", "FFF"); var match2 = TryMatchSingleWordPattern("BarFooFooFoo", "FFF"); // The weight of being first should be greater than the weight of being contiguous Assert.InRange((int)match1.Value.CamelCaseWeight, (int)match2.Value.CamelCaseWeight + 1, int.MaxValue); } [Fact] public void TryMatchSingleWordPattern_PreferCaseInsensitiveBasicEquals() { var match = TryMatchSingleWordPattern("Foo", "foo"); Assert.Equal(PatternMatchKind.Exact, match.Value.Kind); Assert.Equal(false, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseInsensitiveBasicEquals2() { var match = TryMatchSingleWordPattern("Foo", "Foo"); // Since it's actually case sensitive, we'll report it as such even though we didn't prefer it Assert.Equal(PatternMatchKind.Exact, match.Value.Kind); Assert.Equal(true, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseInsensitiveBasicPrefix() { var match = TryMatchSingleWordPattern("FogBar", "fog"); Assert.Equal(PatternMatchKind.Prefix, match.Value.Kind); Assert.Equal(false, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseInsensitiveBasicPrefix2() { var match = TryMatchSingleWordPattern("FogBar", "Fog"); Assert.Equal(PatternMatchKind.Prefix, match.Value.Kind); Assert.Equal(true, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseInsensitiveCamelCase1() { var match = TryMatchSingleWordPattern("FogBar", "FB"); Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind); Assert.Equal(true, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseInsensitiveCamelCase2() { var match = TryMatchSingleWordPattern("FogBar", "fB"); Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind); Assert.Equal(false, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseInsensitiveCamelCase3() { var match = TryMatchSingleWordPattern("fogBar", "fB"); Assert.Equal(PatternMatchKind.CamelCase, match.Value.Kind); Assert.Equal(true, match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseSensitiveWhenPrefix() { var match = TryMatchSingleWordPattern("fogBarFoo", "Fog"); Assert.Equal(PatternMatchKind.Prefix, match.Value.Kind); Assert.False(match.Value.IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_PreferCaseInsensitiveWhenPrefix() { var match = TryMatchSingleWordPattern("fogBarFoo", "Fog"); Assert.Equal(PatternMatchKind.Prefix, match.Value.Kind); Assert.Equal(false, match.Value.IsCaseSensitive); } private void AssertContainsType(PatternMatchKind type, IEnumerable<PatternMatch> results) { Assert.True(results.Any(r => r.Kind == type)); } [Fact] public void MatchMultiWordPattern_ExactWithLowercase() { var match = TryMatchMultiWordPattern("AddMetadataReference", "addmetadatareference"); AssertContainsType(PatternMatchKind.Exact, match); } [Fact] public void MatchMultiWordPattern_SingleLowercasedSearchWord1() { var match = TryMatchMultiWordPattern("AddMetadataReference", "add"); AssertContainsType(PatternMatchKind.Prefix, match); } [Fact] public void MatchMultiWordPattern_SingleLowercasedSearchWord2() { var match = TryMatchMultiWordPattern("AddMetadataReference", "metadata"); AssertContainsType(PatternMatchKind.Substring, match); } [Fact] public void MatchMultiWordPattern_SingleUppercaseSearchWord1() { var match = TryMatchMultiWordPattern("AddMetadataReference", "Add"); AssertContainsType(PatternMatchKind.Prefix, match); } [Fact] public void MatchMultiWordPattern_SingleUppercaseSearchWord2() { var match = TryMatchMultiWordPattern("AddMetadataReference", "Metadata"); AssertContainsType(PatternMatchKind.Substring, match); } [Fact] public void MatchMultiWordPattern_SingleUppercaseSearchLetter1() { var match = TryMatchMultiWordPattern("AddMetadataReference", "A"); AssertContainsType(PatternMatchKind.Prefix, match); } [Fact] public void MatchMultiWordPattern_SingleUppercaseSearchLetter2() { var match = TryMatchMultiWordPattern("AddMetadataReference", "M"); AssertContainsType(PatternMatchKind.Substring, match); } [Fact] public void MatchMultiWordPattern_TwoLowercaseWords() { var match = TryMatchMultiWordPattern("AddMetadataReference", "add metadata"); AssertContainsType(PatternMatchKind.Prefix, match); AssertContainsType(PatternMatchKind.Substring, match); } [Fact] public void MatchMultiWordPattern_TwoUppercaseLettersSeparateWords() { var match = TryMatchMultiWordPattern("AddMetadataReference", "A M"); AssertContainsType(PatternMatchKind.Prefix, match); AssertContainsType(PatternMatchKind.Substring, match); } [Fact] public void MatchMultiWordPattern_TwoUppercaseLettersOneWord() { var match = TryMatchMultiWordPattern("AddMetadataReference", "AM"); AssertContainsType(PatternMatchKind.CamelCase, match); } [Fact] public void MatchMultiWordPattern_Mixed1() { var match = TryMatchMultiWordPattern("AddMetadataReference", "ref Metadata"); Assert.True(match.Select(m => m.Kind).SequenceEqual(new[] { PatternMatchKind.Substring, PatternMatchKind.Substring })); } [Fact] public void MatchMultiWordPattern_Mixed2() { var match = TryMatchMultiWordPattern("AddMetadataReference", "ref M"); Assert.True(match.Select(m => m.Kind).SequenceEqual(new[] { PatternMatchKind.Substring, PatternMatchKind.Substring })); } [Fact] public void MatchMultiWordPattern_MixedCamelCase() { var match = TryMatchMultiWordPattern("AddMetadataReference", "AMRe"); AssertContainsType(PatternMatchKind.CamelCase, match); } [Fact] public void MatchMultiWordPattern_BlankPattern() { Assert.Null(TryMatchMultiWordPattern("AddMetadataReference", string.Empty)); } [Fact] public void MatchMultiWordPattern_WhitespaceOnlyPattern() { Assert.Null(TryMatchMultiWordPattern("AddMetadataReference", " ")); } [Fact] public void MatchMultiWordPattern_EachWordSeparately1() { var match = TryMatchMultiWordPattern("AddMetadataReference", "add Meta"); AssertContainsType(PatternMatchKind.Prefix, match); AssertContainsType(PatternMatchKind.Substring, match); } [Fact] public void MatchMultiWordPattern_EachWordSeparately2() { var match = TryMatchMultiWordPattern("AddMetadataReference", "Add meta"); AssertContainsType(PatternMatchKind.Prefix, match); AssertContainsType(PatternMatchKind.Substring, match); } [Fact] public void MatchMultiWordPattern_EachWordSeparately3() { var match = TryMatchMultiWordPattern("AddMetadataReference", "Add Meta"); AssertContainsType(PatternMatchKind.Prefix, match); AssertContainsType(PatternMatchKind.Substring, match); } [Fact] public void MatchMultiWordPattern_MixedCasing1() { Assert.Null(TryMatchMultiWordPattern("AddMetadataReference", "mEta")); } [Fact] public void MatchMultiWordPattern_MixedCasing2() { Assert.Null(TryMatchMultiWordPattern("AddMetadataReference", "Data")); } [Fact] public void MatchMultiWordPattern_AsteriskSplit() { var match = TryMatchMultiWordPattern("GetKeyWord", "K*W"); Assert.True(match.Select(m => m.Kind).SequenceEqual(new[] { PatternMatchKind.Substring, PatternMatchKind.Substring })); } [WorkItem(544628)] [Fact] public void MatchMultiWordPattern_LowercaseSubstring1() { Assert.Null(TryMatchMultiWordPattern("Operator", "a")); } [WorkItem(544628)] [Fact] public void MatchMultiWordPattern_LowercaseSubstring2() { var match = TryMatchMultiWordPattern("FooAttribute", "a"); AssertContainsType(PatternMatchKind.Substring, match); Assert.False(match.First().IsCaseSensitive); } [Fact] public void TryMatchSingleWordPattern_CultureAwareSingleWordPreferCaseSensitiveExactInsensitive() { var previousCulture = Thread.CurrentThread.CurrentCulture; var turkish = CultureInfo.GetCultureInfo("tr-TR"); Thread.CurrentThread.CurrentCulture = turkish; try { var match = TryMatchSingleWordPattern("ioo", "\u0130oo"); // u0130 = Capital I with dot Assert.Equal(PatternMatchKind.Exact, match.Value.Kind); Assert.False(match.Value.IsCaseSensitive); } finally { Thread.CurrentThread.CurrentCulture = previousCulture; } } [Fact] public void MatchAllLowerPattern1() { Assert.NotNull(TryMatchSingleWordPattern("FogBarChangedEventArgs", "changedeventargs")); } [Fact] public void MatchAllLowerPattern2() { Assert.Null(TryMatchSingleWordPattern("FogBarChangedEventArgs", "changedeventarrrgh")); } [Fact] public void MatchAllLowerPattern3() { Assert.NotNull(TryMatchSingleWordPattern("ABCDEFGH", "bcd")); } [Fact] public void MatchAllLowerPattern4() { Assert.Null(TryMatchSingleWordPattern("AbcdefghijEfgHij", "efghij")); } private static IList<string> PartListToSubstrings(string identifier, List<TextSpan> parts) { return parts.Select(span => identifier.Substring(span.Start, span.Length)).ToList(); } private static IList<string> BreakIntoCharacterParts(string identifier) { return PartListToSubstrings(identifier, StringBreaker.BreakIntoCharacterParts(identifier)); } private static IList<string> BreakIntoWordParts(string identifier) { return PartListToSubstrings(identifier, StringBreaker.BreakIntoWordParts(identifier)); } private static PatternMatch? TryMatchSingleWordPattern(string candidate, string pattern) { return new PatternMatcher(pattern).MatchSingleWordPattern_ForTestingOnly(candidate); } private static IEnumerable<PatternMatch> TryMatchMultiWordPattern(string candidate, string pattern) { return new PatternMatcher(pattern).GetMatches(candidate); } } }
#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 System; using System.Collections.Generic; using System.Reflection; using Boo.Lang.Compiler.TypeSystem.Core; using Boo.Lang.Compiler.TypeSystem.Services; using Boo.Lang.Compiler.Util; using Boo.Lang.Environments; namespace Boo.Lang.Compiler.TypeSystem.Reflection { public class ExternalType : IType { protected IReflectionTypeSystemProvider _provider; private readonly Type _type; IType[] _interfaces; IEntity[] _members; int _typeDepth = -1; string _primitiveName; string _fullName; private string _name; public ExternalType(IReflectionTypeSystemProvider tss, Type type) { if (null == type) throw new ArgumentException("type"); _provider = tss; _type = type; } public virtual string FullName { get { if (null != _fullName) return _fullName; return _fullName = BuildFullName(); } } internal string PrimitiveName { get { return _primitiveName; } set { _primitiveName = value; } } public virtual string Name { get { if (null != _name) return _name; return _name = TypeUtilities.TypeName(_type); } } public EntityType EntityType { get { return EntityType.Type; } } public IType Type { get { return this; } } public virtual bool IsFinal { get { return _type.IsSealed; } } public bool IsByRef { get { return _type.IsByRef; } } public virtual IEntity DeclaringEntity { get { return DeclaringType; } } public IType DeclaringType { get { System.Type declaringType = _type.DeclaringType; return null != declaringType ? _provider.Map(declaringType) : null; } } public bool IsDefined(IType attributeType) { ExternalType type = attributeType as ExternalType; if (null == type) return false; return MetadataUtil.IsAttributeDefined(_type, type.ActualType); } public virtual IType ElementType { get { return _provider.Map(_type.GetElementType() ?? _type); } } public virtual bool IsClass { get { return _type.IsClass; } } public bool IsAbstract { get { return _type.IsAbstract; } } public bool IsInterface { get { return _type.IsInterface; } } public bool IsEnum { get { return _type.IsEnum; } } public virtual bool IsValueType { get { return _type.IsValueType; } } public bool IsArray { get { return false; } } public bool IsPointer { get { return _type.IsPointer; } } public virtual IType BaseType { get { Type baseType = _type.BaseType; return null == baseType ? null : _provider.Map(baseType); } } protected virtual MemberInfo[] GetDefaultMembers() { return ActualType.GetDefaultMembers(); } public IEntity GetDefaultMember() { return _provider.Map(GetDefaultMembers()); } public Type ActualType { get { return _type; } } public virtual bool IsSubclassOf(IType other) { var external = other as ExternalType; if (external == null) return false; return _type.IsSubclassOf(external._type) || (external.IsInterface && external._type.IsAssignableFrom(_type)); } public virtual bool IsAssignableFrom(IType other) { var external = other as ExternalType; if (null == external) { if (EntityType.Null == other.EntityType) { return !IsValueType; } return other.IsSubclassOf(this); } if (other == _provider.Map(Types.Void)) { return false; } return _type.IsAssignableFrom(external._type); } public virtual IType[] GetInterfaces() { if (null == _interfaces) { Type[] interfaces = _type.GetInterfaces(); _interfaces = new IType[interfaces.Length]; for (int i=0; i<_interfaces.Length; ++i) { _interfaces[i] = _provider.Map(interfaces[i]); } } return _interfaces; } public virtual IEnumerable<IEntity> GetMembers() { if (null == _members) { IEntity[] members = CreateMembers(); _members = members; } return _members; } protected virtual IEntity[] CreateMembers() { List<IEntity> result = new List<IEntity>(); foreach (MemberInfo member in DeclaredMembers()) result.Add(_provider.Map(member)); return result.ToArray(); } private MemberInfo[] DeclaredMembers() { return _type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); } public int GetTypeDepth() { if (-1 == _typeDepth) { _typeDepth = GetTypeDepth(_type); } return _typeDepth; } public virtual INamespace ParentNamespace { get { return null; } } public virtual bool Resolve(ICollection<IEntity> resultingSet, string name, EntityType typesToConsider) { bool found = My<NameResolutionService>.Instance.Resolve(name, GetMembers(), typesToConsider, resultingSet); if (IsInterface) { if (_provider.Map(typeof(object)).Resolve(resultingSet, name, typesToConsider)) found = true; foreach (IType baseInterface in GetInterfaces()) found |= baseInterface.Resolve(resultingSet, name, typesToConsider); } else { if (!found || TypeSystemServices.ContainsMethodsOnly(resultingSet)) { IType baseType = BaseType; if (null != baseType) found |= baseType.Resolve(resultingSet, name, typesToConsider); } } return found; } override public string ToString() { return this.DisplayName(); } static int GetTypeDepth(Type type) { if (type.IsByRef) { return GetTypeDepth(type.GetElementType()); } if (type.IsInterface) { return GetInterfaceDepth(type); } return GetClassDepth(type); } static int GetClassDepth(Type type) { int depth = 0; Type objectType = Types.Object; while (type != null && type != objectType) { type = type.BaseType; ++depth; } return depth; } static int GetInterfaceDepth(Type type) { Type[] interfaces = type.GetInterfaces(); if (interfaces.Length > 0) { int current = 0; foreach (Type i in interfaces) { int depth = GetInterfaceDepth(i); if (depth > current) { current = depth; } } return 1+current; } return 1; } protected virtual string BuildFullName() { if (_primitiveName != null) return _primitiveName; // keep builtin names pretty ('ref int' instead of 'ref System.Int32') if (_type.IsByRef) return "ref " + ElementType.FullName; return TypeUtilities.GetFullName(_type); } ExternalGenericTypeInfo _genericTypeDefinitionInfo = null; public virtual IGenericTypeInfo GenericInfo { get { if (ActualType.IsGenericTypeDefinition) return _genericTypeDefinitionInfo ?? (_genericTypeDefinitionInfo = new ExternalGenericTypeInfo(_provider, this)); return null; } } ExternalConstructedTypeInfo _genericTypeInfo = null; public virtual IConstructedTypeInfo ConstructedInfo { get { if (ActualType.IsGenericType && !ActualType.IsGenericTypeDefinition) return _genericTypeInfo ?? (_genericTypeInfo = new ExternalConstructedTypeInfo(_provider, this)); return null; } } private ArrayTypeCache _arrayTypes; public IArrayType MakeArrayType(int rank) { if (null == _arrayTypes) _arrayTypes = new ArrayTypeCache(this); return _arrayTypes.MakeArrayType(rank); } public IType MakePointerType() { return _provider.Map(_type.MakePointerType()); } } }
// Lucene version compatibility level 4.8.1 using J2N; using Lucene.Net.Analysis.TokenAttributes; using Lucene.Net.Diagnostics; using Lucene.Net.Util; using System.IO; namespace Lucene.Net.Analysis.Util { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// An abstract base class for simple, character-oriented tokenizers. /// <para> /// You must specify the required <see cref="LuceneVersion"/> compatibility /// when creating <see cref="CharTokenizer"/>: /// <list type="bullet"> /// <item><description>As of 3.1, <see cref="CharTokenizer"/> uses an int based API to normalize and /// detect token codepoints. See <see cref="IsTokenChar(int)"/> and /// <see cref="Normalize(int)"/> for details.</description></item> /// </list> /// </para> /// <para> /// A new <see cref="CharTokenizer"/> API has been introduced with Lucene 3.1. This API /// moved from UTF-16 code units to UTF-32 codepoints to eventually add support /// for <a href= /// "http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Character.html#supplementary" /// >supplementary characters</a>. The old <i>char</i> based API has been /// deprecated and should be replaced with the <i>int</i> based methods /// <see cref="IsTokenChar(int)"/> and <see cref="Normalize(int)"/>. /// </para> /// <para> /// As of Lucene 3.1 each <see cref="CharTokenizer"/> - constructor expects a /// <see cref="LuceneVersion"/> argument. Based on the given <see cref="LuceneVersion"/> either the new /// API or a backwards compatibility layer is used at runtime. For /// <see cref="LuceneVersion"/> &lt; 3.1 the backwards compatibility layer ensures correct /// behavior even for indexes build with previous versions of Lucene. If a /// <see cref="LuceneVersion"/> >= 3.1 is used <see cref="CharTokenizer"/> requires the new API to /// be implemented by the instantiated class. Yet, the old <i>char</i> based API /// is not required anymore even if backwards compatibility must be preserved. /// <see cref="CharTokenizer"/> subclasses implementing the new API are fully backwards /// compatible if instantiated with <see cref="LuceneVersion"/> &lt; 3.1. /// </para> /// <para> /// <strong>Note:</strong> If you use a subclass of <see cref="CharTokenizer"/> with <see cref="LuceneVersion"/> >= /// 3.1 on an index build with a version &lt; 3.1, created tokens might not be /// compatible with the terms in your index. /// </para> /// </summary> public abstract class CharTokenizer : Tokenizer { /// <summary> /// Creates a new <see cref="CharTokenizer"/> instance /// </summary> /// <param name="matchVersion"> /// Lucene version to match </param> /// <param name="input"> /// the input to split up into tokens </param> public CharTokenizer(LuceneVersion matchVersion, TextReader input) : base(input) { Init(matchVersion); } /// <summary> /// Creates a new <see cref="CharTokenizer"/> instance /// </summary> /// <param name="matchVersion"> /// Lucene version to match </param> /// <param name="factory"> /// the attribute factory to use for this <see cref="Tokenizer"/> </param> /// <param name="input"> /// the input to split up into tokens </param> public CharTokenizer(LuceneVersion matchVersion, AttributeFactory factory, TextReader input) : base(factory, input) { Init(matchVersion); } /// <summary> /// LUCENENET specific - Added in the .NET version to assist with setting the attributes /// from multiple constructors. /// </summary> /// <param name="matchVersion"></param> private void Init(LuceneVersion matchVersion) { charUtils = CharacterUtils.GetInstance(matchVersion); termAtt = AddAttribute<ICharTermAttribute>(); offsetAtt = AddAttribute<IOffsetAttribute>(); } private int offset = 0, bufferIndex = 0, dataLen = 0, finalOffset = 0; private const int MAX_WORD_LEN = 255; private const int IO_BUFFER_SIZE = 4096; private ICharTermAttribute termAtt; private IOffsetAttribute offsetAtt; private CharacterUtils charUtils; private readonly CharacterUtils.CharacterBuffer ioBuffer = CharacterUtils.NewCharacterBuffer(IO_BUFFER_SIZE); /// <summary> /// Returns true iff a codepoint should be included in a token. This tokenizer /// generates as tokens adjacent sequences of codepoints which satisfy this /// predicate. Codepoints for which this is false are used to define token /// boundaries and are not included in tokens. /// </summary> protected abstract bool IsTokenChar(int c); /// <summary> /// Called on each token character to normalize it before it is added to the /// token. The default implementation does nothing. Subclasses may use this to, /// e.g., lowercase tokens. /// </summary> protected virtual int Normalize(int c) { return c; } public override sealed bool IncrementToken() { ClearAttributes(); int length = 0; int start = -1; // this variable is always initialized int end = -1; char[] buffer = termAtt.Buffer; while (true) { if (bufferIndex >= dataLen) { offset += dataLen; charUtils.Fill(ioBuffer, m_input); // read supplementary char aware with CharacterUtils if (ioBuffer.Length == 0) { dataLen = 0; // so next offset += dataLen won't decrement offset if (length > 0) { break; } else { finalOffset = CorrectOffset(offset); return false; } } dataLen = ioBuffer.Length; bufferIndex = 0; } // use CharacterUtils here to support < 3.1 UTF-16 code unit behavior if the char based methods are gone int c = charUtils.CodePointAt(ioBuffer.Buffer, bufferIndex, ioBuffer.Length); int charCount = Character.CharCount(c); bufferIndex += charCount; if (IsTokenChar(c)) // if it's a token char { if (length == 0) // start of token { if (Debugging.AssertsEnabled) Debugging.Assert(start == -1); start = offset + bufferIndex - charCount; end = start; } // check if a supplementary could run out of bounds else if (length >= buffer.Length - 1) { buffer = termAtt.ResizeBuffer(2 + length); // make sure a supplementary fits in the buffer } end += charCount; length += Character.ToChars(Normalize(c), buffer, length); // buffer it, normalized if (length >= MAX_WORD_LEN) // buffer overflow! make sure to check for >= surrogate pair could break == test { break; } } // at non-Letter w/ chars else if (length > 0) { break; // return 'em } } termAtt.Length = length; if (Debugging.AssertsEnabled) Debugging.Assert(start != -1); offsetAtt.SetOffset(CorrectOffset(start), finalOffset = CorrectOffset(end)); return true; } public override sealed void End() { base.End(); // set final offset offsetAtt.SetOffset(finalOffset, finalOffset); } public override void Reset() { base.Reset(); bufferIndex = 0; offset = 0; dataLen = 0; finalOffset = 0; ioBuffer.Reset(); // make sure to reset the IO buffer!! } } }
//#define USE_SQL_SERVER using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Orleans; using Orleans.Runtime; using Orleans.TestingHost; using Orleans.TestingHost.Utils; using Orleans.Internal; using TestExtensions; using UnitTests.GrainInterfaces; using Xunit; // ReSharper disable InconsistentNaming // ReSharper disable UnusedVariable namespace UnitTests.TimerTests { public class ReminderTests_Base : OrleansTestingBase, IDisposable { protected TestCluster HostedCluster { get; private set; } internal static readonly TimeSpan LEEWAY = TimeSpan.FromMilliseconds(100); // the experiment shouldnt be that long that the sums of leeways exceeds a period internal static readonly TimeSpan ENDWAIT = TimeSpan.FromMinutes(5); internal const string DR = "DEFAULT_REMINDER"; internal const string R1 = "REMINDER_1"; internal const string R2 = "REMINDER_2"; protected const long retries = 3; protected const long failAfter = 2; // NOTE: match this sleep with 'failCheckAfter' used in PerGrainFailureTest() so you dont try to get counter immediately after failure as new activation may not have the reminder statistics protected const long failCheckAfter = 6; // safe value: 9 protected ILogger log; public ReminderTests_Base(BaseTestClusterFixture fixture) { HostedCluster = fixture.HostedCluster; GrainFactory = fixture.GrainFactory; var filters = new LoggerFilterOptions(); #if DEBUG filters.AddFilter("Storage", LogLevel.Trace); filters.AddFilter("Reminder", LogLevel.Trace); #endif log = TestingUtils.CreateDefaultLoggerFactory(TestingUtils.CreateTraceFileName("client", DateTime.Now.ToString("yyyyMMdd_hhmmss")), filters).CreateLogger<ReminderTests_Base>(); } public IGrainFactory GrainFactory { get; } public void Dispose() { // ReminderTable.Clear() cannot be called from a non-Orleans thread, // so we must proxy the call through a grain. var controlProxy = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); controlProxy.EraseReminderTable().WaitWithThrow(TestConstants.InitTimeout); } public async Task Test_Reminders_Basic_StopByRef() { IReminderTestGrain2 grain = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IGrainReminder r1 = await grain.StartReminder(DR); IGrainReminder r2 = await grain.StartReminder(DR); try { // First handle should now be out of date once the seconf handle to the same reminder was obtained await grain.StopReminder(r1); Assert.True(false, "Removed reminder1, which shouldn't be possible."); } catch (Exception exc) { log.Info("Couldn't remove {0}, as expected. Exception received = {1}", r1, exc); } await grain.StopReminder(r2); log.Info("Removed reminder2 successfully"); // trying to see if readreminder works _ = await grain.StartReminder(DR); _ = await grain.StartReminder(DR); _ = await grain.StartReminder(DR); _ = await grain.StartReminder(DR); IGrainReminder r = await grain.GetReminderObject(DR); await grain.StopReminder(r); log.Info("Removed got reminder successfully"); } public async Task Test_Reminders_Basic_ListOps() { Guid id = Guid.NewGuid(); log.Info("Start Grain Id = {0}", id); IReminderTestGrain2 grain = this.GrainFactory.GetGrain<IReminderTestGrain2>(id); const int count = 5; Task<IGrainReminder>[] startReminderTasks = new Task<IGrainReminder>[count]; for (int i = 0; i < count; i++) { startReminderTasks[i] = grain.StartReminder(DR + "_" + i); log.Info("Started {0}_{1}", DR, i); } await Task.WhenAll(startReminderTasks); // do comparison on strings List<string> registered = (from reminder in startReminderTasks select reminder.Result.ReminderName).ToList(); log.Info("Waited"); List<IGrainReminder> remindersList = await grain.GetRemindersList(); List<string> fetched = (from reminder in remindersList select reminder.ReminderName).ToList(); foreach (var remRegistered in registered) { Assert.True(fetched.Remove(remRegistered), $"Couldn't get reminder {remRegistered}. " + $"Registered list: {Utils.EnumerableToString(registered)}, " + $"fetched list: {Utils.EnumerableToString(remindersList, r => r.ReminderName)}"); } Assert.True(fetched.Count == 0, $"More than registered reminders. Extra: {Utils.EnumerableToString(fetched)}"); // do some time tests as well log.Info("Time tests"); TimeSpan period = await grain.GetReminderPeriod(DR); Thread.Sleep(period.Multiply(2) + LEEWAY); // giving some leeway for (int i = 0; i < count; i++) { long curr = await grain.GetCounter(DR + "_" + i); Assert.Equal(2, curr); // string.Format("Incorrect ticks for {0}_{1}", DR, i)); } } public async Task Test_Reminders_1J_MultiGrainMultiReminders() { IReminderTestGrain2 g1 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g2 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g3 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g4 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); IReminderTestGrain2 g5 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); TimeSpan period = await g1.GetReminderPeriod(DR); Task<bool>[] tasks = { Task.Run(() => this.PerGrainMultiReminderTestChurn(g1)), Task.Run(() => this.PerGrainMultiReminderTestChurn(g2)), Task.Run(() => this.PerGrainMultiReminderTestChurn(g3)), Task.Run(() => this.PerGrainMultiReminderTestChurn(g4)), Task.Run(() => this.PerGrainMultiReminderTestChurn(g5)), }; Thread.Sleep(period.Multiply(5)); // start another silo ... although it will take it a while before it stabilizes log.Info("Starting another silo"); await this.HostedCluster.StartAdditionalSilosAsync(1, true); //Block until all tasks complete. await Task.WhenAll(tasks).WithTimeout(ENDWAIT); } public async Task Test_Reminders_ReminderNotFound() { IReminderTestGrain2 g1 = this.GrainFactory.GetGrain<IReminderTestGrain2>(Guid.NewGuid()); // request a reminder that does not exist IGrainReminder reminder = await g1.GetReminderObject("blarg"); Assert.Null(reminder); } internal async Task<bool> PerGrainMultiReminderTestChurn(IReminderTestGrain2 g) { // for churn cases, we do execute start and stop reminders with retries as we don't have the queue-ing // functionality implemented on the LocalReminderService yet TimeSpan period = await g.GetReminderPeriod(DR); this.log.Info("PerGrainMultiReminderTestChurn Period={0} Grain={1}", period, g); // Start Default Reminder //g.StartReminder(DR, file + "_" + DR).Wait(); await ExecuteWithRetries(g.StartReminder, DR); TimeSpan sleepFor = period.Multiply(2); await Task.Delay(sleepFor); // Start R1 //g.StartReminder(R1, file + "_" + R1).Wait(); await ExecuteWithRetries(g.StartReminder, R1); sleepFor = period.Multiply(2); await Task.Delay(sleepFor); // Start R2 //g.StartReminder(R2, file + "_" + R2).Wait(); await ExecuteWithRetries(g.StartReminder, R2); sleepFor = period.Multiply(2); await Task.Delay(sleepFor); sleepFor = period.Multiply(1); await Task.Delay(sleepFor); // Stop R1 //g.StopReminder(R1).Wait(); await ExecuteWithRetriesStop(g.StopReminder, R1); sleepFor = period.Multiply(2); await Task.Delay(sleepFor); // Stop R2 //g.StopReminder(R2).Wait(); await ExecuteWithRetriesStop(g.StopReminder, R2); sleepFor = period.Multiply(1); await Task.Delay(sleepFor); // Stop Default reminder //g.StopReminder(DR).Wait(); await ExecuteWithRetriesStop(g.StopReminder, DR); sleepFor = period.Multiply(1) + LEEWAY; // giving some leeway await Task.Delay(sleepFor); long last = await g.GetCounter(R1); AssertIsInRange(last, 4, 6, g, R1, sleepFor); last = await g.GetCounter(R2); AssertIsInRange(last, 4, 6, g, R2, sleepFor); last = await g.GetCounter(DR); AssertIsInRange(last, 9, 10, g, DR, sleepFor); return true; } protected async Task<bool> PerGrainFailureTest(IReminderTestGrain2 grain) { TimeSpan period = await grain.GetReminderPeriod(DR); this.log.Info("PerGrainFailureTest Period={0} Grain={1}", period, grain); await grain.StartReminder(DR); TimeSpan sleepFor = period.Multiply(failCheckAfter) + LEEWAY; // giving some leeway Thread.Sleep(sleepFor); long last = await grain.GetCounter(DR); AssertIsInRange(last, failCheckAfter - 1, failCheckAfter + 1, grain, DR, sleepFor); await grain.StopReminder(DR); sleepFor = period.Multiply(2) + LEEWAY; // giving some leeway Thread.Sleep(sleepFor); long curr = await grain.GetCounter(DR); AssertIsInRange(curr, last, last + 1, grain, DR, sleepFor); return true; } protected async Task<bool> PerGrainMultiReminderTest(IReminderTestGrain2 g) { TimeSpan period = await g.GetReminderPeriod(DR); this.log.Info("PerGrainMultiReminderTest Period={0} Grain={1}", period, g); // Each reminder is started 2 periods after the previous reminder // once all reminders have been started, stop them every 2 periods // except the default reminder, which we stop after 3 periods instead // just to test and break the symmetry // Start Default Reminder await g.StartReminder(DR); TimeSpan sleepFor = period.Multiply(2) + LEEWAY; // giving some leeway Thread.Sleep(sleepFor); long last = await g.GetCounter(DR); AssertIsInRange(last, 1, 2, g, DR, sleepFor); // Start R1 await g.StartReminder(R1); Thread.Sleep(sleepFor); last = await g.GetCounter(R1); AssertIsInRange(last, 1, 2, g, R1, sleepFor); // Start R2 await g.StartReminder(R2); Thread.Sleep(sleepFor); last = await g.GetCounter(R1); AssertIsInRange(last, 3, 4, g, R1, sleepFor); last = await g.GetCounter(R2); AssertIsInRange(last, 1, 2, g, R2, sleepFor); last = await g.GetCounter(DR); AssertIsInRange(last, 5, 6, g, DR, sleepFor); // Stop R1 await g.StopReminder(R1); Thread.Sleep(sleepFor); last = await g.GetCounter(R1); AssertIsInRange(last, 3, 4, g, R1, sleepFor); last = await g.GetCounter(R2); AssertIsInRange(last, 3, 4, g, R2, sleepFor); last = await g.GetCounter(DR); AssertIsInRange(last, 7, 8, g, DR, sleepFor); // Stop R2 await g.StopReminder(R2); sleepFor = period.Multiply(3) + LEEWAY; // giving some leeway Thread.Sleep(sleepFor); last = await g.GetCounter(R1); AssertIsInRange(last, 3, 4, g, R1, sleepFor); last = await g.GetCounter(R2); AssertIsInRange(last, 3, 4, g, R2, sleepFor); last = await g.GetCounter(DR); AssertIsInRange(last, 10, 12, g, DR, sleepFor); // Stop Default reminder await g.StopReminder(DR); sleepFor = period.Multiply(1) + LEEWAY; // giving some leeway Thread.Sleep(sleepFor); last = await g.GetCounter(R1); AssertIsInRange(last, 3, 4, g, R1, sleepFor); last = await g.GetCounter(R2); AssertIsInRange(last, 3, 4, g, R2, sleepFor); last = await g.GetCounter(DR); AssertIsInRange(last, 10, 12, g, DR, sleepFor); return true; } protected async Task<bool> PerCopyGrainFailureTest(IReminderTestCopyGrain grain) { TimeSpan period = await grain.GetReminderPeriod(DR); this.log.Info("PerCopyGrainFailureTest Period={0} Grain={1}", period, grain); await grain.StartReminder(DR); Thread.Sleep(period.Multiply(failCheckAfter) + LEEWAY); // giving some leeway long last = await grain.GetCounter(DR); Assert.Equal(failCheckAfter, last); // "{0} CopyGrain {1} Reminder {2}" // Time(), grain.GetPrimaryKey(), DR); await grain.StopReminder(DR); Thread.Sleep(period.Multiply(2) + LEEWAY); // giving some leeway long curr = await grain.GetCounter(DR); Assert.Equal(last, curr); // "{0} CopyGrain {1} Reminder {2}", Time(), grain.GetPrimaryKey(), DR); return true; } protected static string Time() { return DateTime.UtcNow.ToString("hh:mm:ss.fff"); } protected void AssertIsInRange(long val, long lowerLimit, long upperLimit, IGrain grain, string reminderName, TimeSpan sleepFor) { StringBuilder sb = new StringBuilder(); sb.AppendFormat("Grain: {0} Grain PrimaryKey: {1}, Reminder: {2}, SleepFor: {3} Time now: {4}", grain, grain.GetPrimaryKey(), reminderName, sleepFor, Time()); sb.AppendFormat( " -- Expecting value in the range between {0} and {1}, and got value {2}.", lowerLimit, upperLimit, val); this.log.Info(sb.ToString()); bool tickCountIsInsideRange = lowerLimit <= val && val <= upperLimit; Skip.IfNot(tickCountIsInsideRange, $"AssertIsInRange: {sb} -- WHICH IS OUTSIDE RANGE."); } protected async Task ExecuteWithRetries(Func<string, TimeSpan?, bool, Task> function, string reminderName, TimeSpan? period = null, bool validate = false) { for (long i = 1; i <= retries; i++) { try { await function(reminderName, period, validate).WithTimeout(TestConstants.InitTimeout); return; // success ... no need to retry } catch (AggregateException aggEx) { aggEx.Handle(exc => HandleError(exc, i)); } catch (ReminderException exc) { HandleError(exc, i); } } // execute one last time and bubble up errors if any await function(reminderName, period, validate).WithTimeout(TestConstants.InitTimeout); } // Func<> doesnt take optional parameters, thats why we need a separate method protected async Task ExecuteWithRetriesStop(Func<string, Task> function, string reminderName) { for (long i = 1; i <= retries; i++) { try { await function(reminderName).WithTimeout(TestConstants.InitTimeout); return; // success ... no need to retry } catch (AggregateException aggEx) { aggEx.Handle(exc => HandleError(exc, i)); } catch (ReminderException exc) { HandleError(exc, i); } } // execute one last time and bubble up errors if any await function(reminderName).WithTimeout(TestConstants.InitTimeout); } private bool HandleError(Exception ex, long i) { if (ex is AggregateException) { ex = ((AggregateException)ex).Flatten().InnerException; } if (ex is ReminderException) { this.log.Info("Retriable operation failed on attempt {0}: {1}", i, ex.ToString()); Thread.Sleep(TimeSpan.FromMilliseconds(10)); // sleep a bit before retrying return true; } return false; } } } // ReSharper restore InconsistentNaming // ReSharper restore UnusedVariable
// 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.ComponentModel; using System.Globalization; using System.IdentityModel.Claims; using System.IdentityModel.Policy; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.Net; using System.Net.Security; using System.Runtime; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel.Channels; using System.ServiceModel.Diagnostics; using System.ServiceModel.Security.Tokens; using System.Text; using System.Threading; namespace System.ServiceModel.Security { public static class ProtectionLevelHelper { public static bool IsDefined(ProtectionLevel value) { return (value == ProtectionLevel.None || value == ProtectionLevel.Sign || value == ProtectionLevel.EncryptAndSign); } public static void Validate(ProtectionLevel value) { if (!IsDefined(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("value", (int)value, typeof(ProtectionLevel))); } } public static bool IsStronger(ProtectionLevel v1, ProtectionLevel v2) { return ((v1 == ProtectionLevel.EncryptAndSign && v2 != ProtectionLevel.EncryptAndSign) || (v1 == ProtectionLevel.Sign && v2 == ProtectionLevel.None)); } public static bool IsStrongerOrEqual(ProtectionLevel v1, ProtectionLevel v2) { return (v1 == ProtectionLevel.EncryptAndSign || (v1 == ProtectionLevel.Sign && v2 != ProtectionLevel.EncryptAndSign)); } public static ProtectionLevel Max(ProtectionLevel v1, ProtectionLevel v2) { return IsStronger(v1, v2) ? v1 : v2; } public static int GetOrdinal(Nullable<ProtectionLevel> p) { if (p.HasValue) { switch ((ProtectionLevel)p) { default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("p", (int)p, typeof(ProtectionLevel))); case ProtectionLevel.None: return 2; case ProtectionLevel.Sign: return 3; case ProtectionLevel.EncryptAndSign: return 4; } } return 1; } } internal static class SslProtocolsHelper { internal static bool IsDefined(SslProtocols value) { SslProtocols allValues = SslProtocols.None; foreach (var protocol in Enum.GetValues(typeof(SslProtocols))) { allValues |= (SslProtocols)protocol; } return (value & allValues) == value; } internal static void Validate(SslProtocols value) { if (!IsDefined(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("value", (int)value, typeof(SslProtocols))); } } } internal static class TokenImpersonationLevelHelper { internal static bool IsDefined(TokenImpersonationLevel value) { return (value == TokenImpersonationLevel.None || value == TokenImpersonationLevel.Anonymous || value == TokenImpersonationLevel.Identification || value == TokenImpersonationLevel.Impersonation || value == TokenImpersonationLevel.Delegation); } internal static void Validate(TokenImpersonationLevel value) { if (!IsDefined(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("value", (int)value, typeof(TokenImpersonationLevel))); } } private static TokenImpersonationLevel[] s_TokenImpersonationLevelOrder = new TokenImpersonationLevel[] { TokenImpersonationLevel.None, TokenImpersonationLevel.Anonymous, TokenImpersonationLevel.Identification, TokenImpersonationLevel.Impersonation, TokenImpersonationLevel.Delegation }; internal static string ToString(TokenImpersonationLevel impersonationLevel) { if (impersonationLevel == TokenImpersonationLevel.Identification) { return "identification"; } if (impersonationLevel == TokenImpersonationLevel.None) { return "none"; } if (impersonationLevel == TokenImpersonationLevel.Anonymous) { return "anonymous"; } if (impersonationLevel == TokenImpersonationLevel.Impersonation) { return "impersonation"; } if (impersonationLevel == TokenImpersonationLevel.Delegation) { return "delegation"; } Fx.Assert("unknown token impersonation level"); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("impersonationLevel", (int)impersonationLevel, typeof(TokenImpersonationLevel))); } internal static bool IsGreaterOrEqual(TokenImpersonationLevel x, TokenImpersonationLevel y) { Validate(x); Validate(y); if (x == y) return true; int px = 0; int py = 0; for (int i = 0; i < s_TokenImpersonationLevelOrder.Length; i++) { if (x == s_TokenImpersonationLevelOrder[i]) px = i; if (y == s_TokenImpersonationLevelOrder[i]) py = i; } return (px > py); } internal static int Compare(TokenImpersonationLevel x, TokenImpersonationLevel y) { int result = 0; if (x != y) { switch (x) { case TokenImpersonationLevel.Identification: result = -1; break; case TokenImpersonationLevel.Impersonation: switch (y) { case TokenImpersonationLevel.Identification: result = 1; break; case TokenImpersonationLevel.Delegation: result = -1; break; default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("y", (int)y, typeof(TokenImpersonationLevel))); } break; case TokenImpersonationLevel.Delegation: result = 1; break; default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("x", (int)x, typeof(TokenImpersonationLevel))); } } return result; } } internal static class SecurityUtils { public const string Principal = "Principal"; public const string Identities = "Identities"; private static IIdentity s_anonymousIdentity; private static X509SecurityTokenAuthenticator s_nonValidatingX509Authenticator; internal static X509SecurityTokenAuthenticator NonValidatingX509Authenticator { get { if (s_nonValidatingX509Authenticator == null) { s_nonValidatingX509Authenticator = new X509SecurityTokenAuthenticator(X509CertificateValidator.None); } return s_nonValidatingX509Authenticator; } } internal static IIdentity AnonymousIdentity { get { if (s_anonymousIdentity == null) { s_anonymousIdentity = CreateIdentity(string.Empty); } return s_anonymousIdentity; } } public static DateTime MaxUtcDateTime { get { // + and - TimeSpan.TicksPerDay is to compensate the DateTime.ParseExact (to localtime) overflow. return new DateTime(DateTime.MaxValue.Ticks - TimeSpan.TicksPerDay, DateTimeKind.Utc); } } public static DateTime MinUtcDateTime { get { // + and - TimeSpan.TicksPerDay is to compensate the DateTime.ParseExact (to localtime) overflow. return new DateTime(DateTime.MinValue.Ticks + TimeSpan.TicksPerDay, DateTimeKind.Utc); } } internal static IIdentity CreateIdentity(string name) { return new GenericIdentity(name); } internal static EndpointIdentity CreateWindowsIdentity() { return CreateWindowsIdentity(false); } internal static EndpointIdentity CreateWindowsIdentity(NetworkCredential serverCredential) { if (serverCredential != null && !NetworkCredentialHelper.IsDefault(serverCredential)) { string upn; if (serverCredential.Domain != null && serverCredential.Domain.Length > 0) { upn = serverCredential.UserName + "@" + serverCredential.Domain; } else { upn = serverCredential.UserName; } return EndpointIdentity.CreateUpnIdentity(upn); } return CreateWindowsIdentity(); } #if !SUPPORTS_WINDOWSIDENTITY internal static EndpointIdentity CreateWindowsIdentity(bool spnOnly) { EndpointIdentity identity = null; if (spnOnly) { identity = EndpointIdentity.CreateSpnIdentity(String.Format(CultureInfo.InvariantCulture, "host/{0}", DnsCache.MachineName)); } else { throw ExceptionHelper.PlatformNotSupported(); } return identity; } #else private static bool IsSystemAccount(WindowsIdentity self) { SecurityIdentifier sid = self.User; if (sid == null) { return false; } // S-1-5-82 is the prefix for the sid that represents the identity that IIS 7.5 Apppool thread runs under. return (sid.IsWellKnown(WellKnownSidType.LocalSystemSid) || sid.IsWellKnown(WellKnownSidType.NetworkServiceSid) || sid.IsWellKnown(WellKnownSidType.LocalServiceSid) || self.User.Value.StartsWith("S-1-5-82", StringComparison.OrdinalIgnoreCase)); } internal static EndpointIdentity CreateWindowsIdentity(bool spnOnly) { EndpointIdentity identity = null; using (WindowsIdentity self = WindowsIdentity.GetCurrent()) { bool isSystemAccount = IsSystemAccount(self); if (spnOnly || isSystemAccount) { identity = EndpointIdentity.CreateSpnIdentity(String.Format(CultureInfo.InvariantCulture, "host/{0}", DnsCache.MachineName)); } else { // Save windowsIdentity for delay lookup identity = new UpnEndpointIdentity(CloneWindowsIdentityIfNecessary(self)); } } return identity; } internal static WindowsIdentity CloneWindowsIdentityIfNecessary(WindowsIdentity wid) { return CloneWindowsIdentityIfNecessary(wid, null); } internal static WindowsIdentity CloneWindowsIdentityIfNecessary(WindowsIdentity wid, string authType) { if (wid != null) { IntPtr token = UnsafeGetWindowsIdentityToken(wid); if (token != IntPtr.Zero) { return UnsafeCreateWindowsIdentityFromToken(token, authType); } } return wid; } private static IntPtr UnsafeGetWindowsIdentityToken(WindowsIdentity wid) { throw ExceptionHelper.PlatformNotSupported("UnsafeGetWindowsIdentityToken is not supported"); } private static WindowsIdentity UnsafeCreateWindowsIdentityFromToken(IntPtr token, string authType) { if (authType != null) return new WindowsIdentity(token, authType); return new WindowsIdentity(token); } #endif // !SUPPORTS_WINDOWSIDENTITY internal static string GetSpnFromIdentity(EndpointIdentity identity, EndpointAddress target) { bool foundSpn = false; string spn = null; if (identity != null) { if (ClaimTypes.Spn.Equals(identity.IdentityClaim.ClaimType)) { spn = (string)identity.IdentityClaim.Resource; foundSpn = true; } else if (ClaimTypes.Upn.Equals(identity.IdentityClaim.ClaimType)) { spn = (string)identity.IdentityClaim.Resource; foundSpn = true; } else if (ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType)) { spn = string.Format(CultureInfo.InvariantCulture, "host/{0}", (string)identity.IdentityClaim.Resource); foundSpn = true; } } if (!foundSpn) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.Format(SR.CannotDetermineSPNBasedOnAddress, target))); } return spn; } internal static string GetSpnFromTarget(EndpointAddress target) { if (target == null) { throw Fx.AssertAndThrow("target should not be null - expecting an EndpointAddress"); } return string.Format(CultureInfo.InvariantCulture, "host/{0}", target.Uri.DnsSafeHost); } internal static bool IsSupportedAlgorithm(string algorithm, SecurityToken token) { if (token.SecurityKeys == null) { return false; } for (int i = 0; i < token.SecurityKeys.Count; ++i) { if (token.SecurityKeys[i].IsSupportedAlgorithm(algorithm)) { return true; } } return false; } internal static Claim GetPrimaryIdentityClaim(ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies) { return GetPrimaryIdentityClaim(AuthorizationContext.CreateDefaultAuthorizationContext(authorizationPolicies)); } internal static Claim GetPrimaryIdentityClaim(AuthorizationContext authContext) { if (authContext != null) { for (int i = 0; i < authContext.ClaimSets.Count; ++i) { ClaimSet claimSet = authContext.ClaimSets[i]; foreach (Claim claim in claimSet.FindClaims(null, Rights.Identity)) { return claim; } } } return null; } internal static string GenerateId() { return SecurityUniqueId.Create().Value; } internal static ReadOnlyCollection<IAuthorizationPolicy> CreatePrincipalNameAuthorizationPolicies(string principalName) { if (principalName == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("principalName"); Claim identityClaim; Claim primaryPrincipal; if (principalName.Contains("@") || principalName.Contains(@"\")) { identityClaim = new Claim(ClaimTypes.Upn, principalName, Rights.Identity); #if SUPPORTS_WINDOWSIDENTITY primaryPrincipal = Claim.CreateUpnClaim(principalName); #else throw ExceptionHelper.PlatformNotSupported("UPN claim not supported"); #endif // SUPPORTS_WINDOWSIDENTITY } else { identityClaim = new Claim(ClaimTypes.Spn, principalName, Rights.Identity); primaryPrincipal = Claim.CreateSpnClaim(principalName); } List<Claim> claims = new List<Claim>(2); claims.Add(identityClaim); claims.Add(primaryPrincipal); List<IAuthorizationPolicy> policies = new List<IAuthorizationPolicy>(1); policies.Add(new UnconditionalPolicy(SecurityUtils.CreateIdentity(principalName), new DefaultClaimSet(ClaimSet.Anonymous, claims))); return policies.AsReadOnly(); } internal static string GetIdentityNamesFromContext(AuthorizationContext authContext) { if (authContext == null) return String.Empty; StringBuilder str = new StringBuilder(256); for (int i = 0; i < authContext.ClaimSets.Count; ++i) { ClaimSet claimSet = authContext.ClaimSets[i]; // Windows WindowsClaimSet windows = claimSet as WindowsClaimSet; if (windows != null) { #if SUPPORTS_WINDOWSIDENTITY if (str.Length > 0) str.Append(", "); AppendIdentityName(str, windows.WindowsIdentity); #else throw ExceptionHelper.PlatformNotSupported(ExceptionHelper.WinsdowsStreamSecurityNotSupported); #endif // SUPPORTS_WINDOWSIDENTITY } else { // X509 X509CertificateClaimSet x509 = claimSet as X509CertificateClaimSet; if (x509 != null) { if (str.Length > 0) str.Append(", "); AppendCertificateIdentityName(str, x509.X509Certificate); } } } if (str.Length <= 0) { List<IIdentity> identities = null; object obj; if (authContext.Properties.TryGetValue(SecurityUtils.Identities, out obj)) { identities = obj as List<IIdentity>; } if (identities != null) { for (int i = 0; i < identities.Count; ++i) { IIdentity identity = identities[i]; if (identity != null) { if (str.Length > 0) str.Append(", "); AppendIdentityName(str, identity); } } } } return str.Length <= 0 ? String.Empty : str.ToString(); } internal static void AppendCertificateIdentityName(StringBuilder str, X509Certificate2 certificate) { string value = certificate.SubjectName.Name; if (String.IsNullOrEmpty(value)) { value = certificate.GetNameInfo(X509NameType.DnsName, false); if (String.IsNullOrEmpty(value)) { value = certificate.GetNameInfo(X509NameType.SimpleName, false); if (String.IsNullOrEmpty(value)) { value = certificate.GetNameInfo(X509NameType.EmailName, false); if (String.IsNullOrEmpty(value)) { value = certificate.GetNameInfo(X509NameType.UpnName, false); } } } } // Same format as X509Identity str.Append(String.IsNullOrEmpty(value) ? "<x509>" : value); str.Append("; "); str.Append(certificate.Thumbprint); } internal static void AppendIdentityName(StringBuilder str, IIdentity identity) { string name = null; try { name = identity.Name; } #pragma warning suppress 56500 catch (Exception e) { if (Fx.IsFatal(e)) { throw; } // suppress exception, this is just info. } str.Append(String.IsNullOrEmpty(name) ? "<null>" : name); #if SUPPORTS_WINDOWSIDENTITY // NegotiateStream WindowsIdentity windows = identity as WindowsIdentity; if (windows != null) { if (windows.User != null) { str.Append("; "); str.Append(windows.User.ToString()); } } else { WindowsSidIdentity sid = identity as WindowsSidIdentity; if (sid != null) { str.Append("; "); str.Append(sid.SecurityIdentifier.ToString()); } } #else throw ExceptionHelper.PlatformNotSupported(ExceptionHelper.WinsdowsStreamSecurityNotSupported); #endif // SUPPORTS_WINDOWSIDENTITY } internal static void OpenTokenProviderIfRequired(SecurityTokenProvider tokenProvider, TimeSpan timeout) { OpenCommunicationObject(tokenProvider as ICommunicationObject, timeout); } internal static void CloseTokenProviderIfRequired(SecurityTokenProvider tokenProvider, TimeSpan timeout) { CloseCommunicationObject(tokenProvider, false, timeout); } internal static void AbortTokenProviderIfRequired(SecurityTokenProvider tokenProvider) { CloseCommunicationObject(tokenProvider, true, TimeSpan.Zero); } internal static void OpenTokenAuthenticatorIfRequired(SecurityTokenAuthenticator tokenAuthenticator, TimeSpan timeout) { OpenCommunicationObject(tokenAuthenticator as ICommunicationObject, timeout); } internal static void CloseTokenAuthenticatorIfRequired(SecurityTokenAuthenticator tokenAuthenticator, TimeSpan timeout) { CloseTokenAuthenticatorIfRequired(tokenAuthenticator, false, timeout); } internal static void CloseTokenAuthenticatorIfRequired(SecurityTokenAuthenticator tokenAuthenticator, bool aborted, TimeSpan timeout) { CloseCommunicationObject(tokenAuthenticator, aborted, timeout); } internal static void AbortTokenAuthenticatorIfRequired(SecurityTokenAuthenticator tokenAuthenticator) { CloseCommunicationObject(tokenAuthenticator, true, TimeSpan.Zero); } private static void OpenCommunicationObject(ICommunicationObject obj, TimeSpan timeout) { if (obj != null) obj.Open(timeout); } private static void CloseCommunicationObject(Object obj, bool aborted, TimeSpan timeout) { if (obj != null) { ICommunicationObject co = obj as ICommunicationObject; if (co != null) { if (aborted) { try { co.Abort(); } catch (CommunicationException) { } } else { co.Close(timeout); } } else if (obj is IDisposable) { ((IDisposable)obj).Dispose(); } } } internal static SecurityStandardsManager CreateSecurityStandardsManager(MessageSecurityVersion securityVersion, SecurityTokenManager tokenManager) { SecurityTokenSerializer tokenSerializer = tokenManager.CreateSecurityTokenSerializer(securityVersion.SecurityTokenVersion); return new SecurityStandardsManager(securityVersion, tokenSerializer); } internal static SecurityStandardsManager CreateSecurityStandardsManager(SecurityTokenRequirement requirement, SecurityTokenManager tokenManager) { MessageSecurityTokenVersion securityVersion = (MessageSecurityTokenVersion)requirement.GetProperty<MessageSecurityTokenVersion>(ServiceModelSecurityTokenRequirement.MessageSecurityVersionProperty); if (securityVersion == MessageSecurityTokenVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005BasicSecurityProfile10) return CreateSecurityStandardsManager(MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10, tokenManager); if (securityVersion == MessageSecurityTokenVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005) return CreateSecurityStandardsManager(MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11, tokenManager); if (securityVersion == MessageSecurityTokenVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005BasicSecurityProfile10) return CreateSecurityStandardsManager(MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10, tokenManager); if (securityVersion == MessageSecurityTokenVersion.WSSecurity10WSTrust13WSSecureConversation13BasicSecurityProfile10) return CreateSecurityStandardsManager(MessageSecurityVersion.WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10, tokenManager); if (securityVersion == MessageSecurityTokenVersion.WSSecurity11WSTrust13WSSecureConversation13) return CreateSecurityStandardsManager(MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12, tokenManager); if (securityVersion == MessageSecurityTokenVersion.WSSecurity11WSTrust13WSSecureConversation13BasicSecurityProfile10) return CreateSecurityStandardsManager(MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10, tokenManager); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } internal static SecurityStandardsManager CreateSecurityStandardsManager(MessageSecurityVersion securityVersion, SecurityTokenSerializer securityTokenSerializer) { if (securityVersion == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("securityVersion")); } if (securityTokenSerializer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("securityTokenSerializer"); } return new SecurityStandardsManager(securityVersion, securityTokenSerializer); } internal static NetworkCredential GetNetworkCredentialsCopy(NetworkCredential networkCredential) { NetworkCredential result; if (networkCredential != null && !NetworkCredentialHelper.IsDefault(networkCredential)) { result = new NetworkCredential(networkCredential.UserName, networkCredential.Password, networkCredential.Domain); } else { result = networkCredential; } return result; } internal static NetworkCredential GetNetworkCredentialOrDefault(NetworkCredential credential) { // Because CredentialCache.DefaultNetworkCredentials is not immutable, we dont use it in our OM. Instead we // use an empty NetworkCredential to denote the default credentials. if (NetworkCredentialHelper.IsNullOrEmpty(credential)) { return CredentialCache.DefaultNetworkCredentials; } return credential; } internal static string AppendWindowsAuthenticationInfo(string inputString, NetworkCredential credential, AuthenticationLevel authenticationLevel, TokenImpersonationLevel impersonationLevel) { const string delimiter = "\0"; // nonprintable characters are invalid for SSPI Domain/UserName/Password if (NetworkCredentialHelper.IsDefault(credential)) { string sid = NetworkCredentialHelper.GetCurrentUserIdAsString(credential); return string.Concat(inputString, delimiter, sid, delimiter, AuthenticationLevelHelper.ToString(authenticationLevel), delimiter, TokenImpersonationLevelHelper.ToString(impersonationLevel)); } return string.Concat(inputString, delimiter, credential.Domain, delimiter, credential.UserName, delimiter, credential.Password, delimiter, AuthenticationLevelHelper.ToString(authenticationLevel), delimiter, TokenImpersonationLevelHelper.ToString(impersonationLevel)); } internal static class NetworkCredentialHelper { static internal bool IsNullOrEmpty(NetworkCredential credential) { return credential == null || ( string.IsNullOrEmpty(credential.UserName) && string.IsNullOrEmpty(credential.Domain) && string.IsNullOrEmpty(credential.Password) ); } static internal bool IsDefault(NetworkCredential credential) { return CredentialCache.DefaultNetworkCredentials.Equals(credential); } internal static string GetCurrentUserIdAsString(NetworkCredential credential) { #if SUPPORTS_WINDOWSIDENTITY using (WindowsIdentity self = WindowsIdentity.GetCurrent()) { return self.User.Value; } #else // There's no way to retrieve the current logged in user Id in UWP apps or in // *NIX so returning a username which is very unlikely to be a real username; return "____CURRENTUSER_NOT_AVAILABLE____"; #endif } } internal static byte[] CloneBuffer(byte[] buffer) { byte[] copy = Fx.AllocateByteArray(buffer.Length); Buffer.BlockCopy(buffer, 0, copy, 0, buffer.Length); return copy; } internal static string GetKeyDerivationAlgorithm(SecureConversationVersion version) { string derivationAlgorithm = null; if (version == SecureConversationVersion.WSSecureConversationFeb2005) { derivationAlgorithm = SecurityAlgorithms.Psha1KeyDerivation; } else if (version == SecureConversationVersion.WSSecureConversation13) { derivationAlgorithm = SecurityAlgorithms.Psha1KeyDerivationDec2005; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } return derivationAlgorithm; } internal static X509Certificate2 GetCertificateFromStore(StoreName storeName, StoreLocation storeLocation, X509FindType findType, object findValue, EndpointAddress target) { X509Certificate2 certificate = GetCertificateFromStoreCore(storeName, storeLocation, findType, findValue, target, true); if (certificate == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.CannotFindCert, storeName, storeLocation, findType, findValue))); return certificate; } internal static bool TryGetCertificateFromStore(StoreName storeName, StoreLocation storeLocation, X509FindType findType, object findValue, EndpointAddress target, out X509Certificate2 certificate) { certificate = GetCertificateFromStoreCore(storeName, storeLocation, findType, findValue, target, false); return (certificate != null); } private static X509Certificate2 GetCertificateFromStoreCore(StoreName storeName, StoreLocation storeLocation, X509FindType findType, object findValue, EndpointAddress target, bool throwIfMultipleOrNoMatch) { if (findValue == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("findValue"); } X509Store store = new X509Store(storeName, storeLocation); X509Certificate2Collection certs = null; try { store.Open(OpenFlags.ReadOnly); certs = store.Certificates.Find(findType, findValue, false); if (certs.Count == 1) { return new X509Certificate2(certs[0].Handle); } if (throwIfMultipleOrNoMatch) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateCertificateLoadException( storeName, storeLocation, findType, findValue, target, certs.Count)); } else { return null; } } finally { ResetAllCertificates(certs); store.Dispose(); } } internal static Exception CreateCertificateLoadException(StoreName storeName, StoreLocation storeLocation, X509FindType findType, object findValue, EndpointAddress target, int certCount) { if (certCount == 0) { if (target == null) { return new InvalidOperationException(SR.Format(SR.CannotFindCert, storeName, storeLocation, findType, findValue)); } return new InvalidOperationException(SR.Format(SR.CannotFindCertForTarget, storeName, storeLocation, findType, findValue, target)); } if (target == null) { return new InvalidOperationException(SR.Format(SR.FoundMultipleCerts, storeName, storeLocation, findType, findValue)); } return new InvalidOperationException(SR.Format(SR.FoundMultipleCertsForTarget, storeName, storeLocation, findType, findValue, target)); } internal static void FixNetworkCredential(ref NetworkCredential credential) { if (credential == null) { return; } string username = credential.UserName; string domain = credential.Domain; if (!string.IsNullOrEmpty(username) && string.IsNullOrEmpty(domain)) { // do the splitting only if there is exactly 1 \ or exactly 1 @ string[] partsWithSlashDelimiter = username.Split('\\'); string[] partsWithAtDelimiter = username.Split('@'); if (partsWithSlashDelimiter.Length == 2 && partsWithAtDelimiter.Length == 1) { if (!string.IsNullOrEmpty(partsWithSlashDelimiter[0]) && !string.IsNullOrEmpty(partsWithSlashDelimiter[1])) { credential = new NetworkCredential(partsWithSlashDelimiter[1], credential.Password, partsWithSlashDelimiter[0]); } } else if (partsWithSlashDelimiter.Length == 1 && partsWithAtDelimiter.Length == 2) { if (!string.IsNullOrEmpty(partsWithAtDelimiter[0]) && !string.IsNullOrEmpty(partsWithAtDelimiter[1])) { credential = new NetworkCredential(partsWithAtDelimiter[0], credential.Password, partsWithAtDelimiter[1]); } } } } #if SUPPORTS_WINDOWSIDENTITY // NegotiateStream public static void ValidateAnonymityConstraint(WindowsIdentity identity, bool allowUnauthenticatedCallers) { if (!allowUnauthenticatedCallers && identity.User.IsWellKnown(WellKnownSidType.AnonymousSid)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning( new SecurityTokenValidationException(SR.Format(SR.AnonymousLogonsAreNotAllowed))); } } #endif // SUPPORTS_WINDOWSIDENTITY // This is the workaround, Since store.Certificates returns a full collection // of certs in store. These are holding native resources. internal static void ResetAllCertificates(X509Certificate2Collection certificates) { if (certificates != null) { for (int i = 0; i < certificates.Count; ++i) { ResetCertificate(certificates[i]); } } } internal static void ResetCertificate(X509Certificate2 certificate) { // Check that Dispose() and Reset() do the same thing certificate.Dispose(); } } internal struct SecurityUniqueId { private static long s_nextId = 0; private static string s_commonPrefix = "uuid-" + Guid.NewGuid().ToString() + "-"; private long _id; private string _prefix; private string _val; private SecurityUniqueId(string prefix, long id) { _id = id; _prefix = prefix; _val = null; } public static SecurityUniqueId Create() { return Create(s_commonPrefix); } public static SecurityUniqueId Create(string prefix) { return new SecurityUniqueId(prefix, Interlocked.Increment(ref s_nextId)); } public string Value { get { if (_val == null) _val = _prefix + _id.ToString(CultureInfo.InvariantCulture); return _val; } } } internal static class EmptyReadOnlyCollection<T> { public static ReadOnlyCollection<T> Instance = new ReadOnlyCollection<T>(new List<T>()); } internal class OperationWithTimeoutAsyncResult : TraceAsyncResult { private static readonly Action<object> s_scheduledCallback = new Action<object>(OnScheduled); private TimeoutHelper _timeoutHelper; private Action<TimeSpan> _operationWithTimeout; public OperationWithTimeoutAsyncResult(Action<TimeSpan> operationWithTimeout, TimeSpan timeout, AsyncCallback callback, object state) : base(callback, state) { _operationWithTimeout = operationWithTimeout; _timeoutHelper = new TimeoutHelper(timeout); ActionItem.Schedule(s_scheduledCallback, this); } private static void OnScheduled(object state) { OperationWithTimeoutAsyncResult thisResult = (OperationWithTimeoutAsyncResult)state; Exception completionException = null; try { using (thisResult.CallbackActivity == null ? null : ServiceModelActivity.BoundOperation(thisResult.CallbackActivity)) { thisResult._operationWithTimeout(thisResult._timeoutHelper.RemainingTime()); } } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Fx.IsFatal(e)) { throw; } completionException = e; } thisResult.Complete(false, completionException); } public static void End(IAsyncResult result) { End<OperationWithTimeoutAsyncResult>(result); } } }
using System; using System.Configuration; using System.Diagnostics; using System.Drawing; using System.Windows.Forms; using FogBugzNet; namespace FogBugzCaseTracker { public partial class HoverWindow : Form { private void Initialize() { loadSettings(); SetState(new StateLoggedOff(this)); trayIcon.ShowBalloonTip(2000); string Url = ConfigurationManager.AppSettings["AutoUpdateURL"] ?? ""; int Hours; int.TryParse(ConfigurationManager.AppSettings["VersionUpdateCheckIntervalHours"], out Hours); _autoUpdate = new AutoUpdater(Url, new TimeSpan(Hours, 0, 0)); _autoUpdate.Run(); MoveWindowToCenter(); loginWithPrompt(); } private void updateCasesTimer_Click(object sender, EventArgs e) { if (_fb.IsLoggedIn) updateCases(true); } private void HoverWindow_Load(object sender, EventArgs e) { Initialize(); } private void HoverWindow_MouseDown(object sender, MouseEventArgs e) { startDragging(e); } private void HoverWindow_MouseMove(object sender, MouseEventArgs e) { if (_dragging) dragWindow(e); } private void btnExit_Click(object sender, EventArgs e) { Close(); } private void lblWorkingOn_MouseMove(object sender, MouseEventArgs e) { if (_dragging) dragWindow(e); } private void lblWorkingOn_MouseDown(object sender, MouseEventArgs e) { startDragging(e); } private void listCases_SelectedIndexChanged(object sender, EventArgs e) { UpdateTrackedItem(); } private void trayIcon_MouseClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) menuMain.Show(); } private void trayIcon_MouseUp(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { Visible = !Visible; btnShowHide.Text = Visible ? "Hide" : "Show"; // TODO: should be handled by the state classes } } private void btnConfigure_Click(object sender, EventArgs e) { loginWithPrompt(true); } private void HoverWindow_FormClosed(object sender, FormClosedEventArgs e) { CloseApplication(); } private void btnRefresh_Click(object sender, EventArgs e) { updateCases(); backgroundPic.Focus(); } private void btnResolve_Click(object sender, EventArgs e) { _fb.ResolveCase(TrackedCase.ID); updateCases(); } private void btnViewCase_Click(object sender, EventArgs e) { Process.Start(_fb.CaseEditURL(((Case)dropCaseList.SelectedItem).ID)); } private void btnShowHide_Click(object sender, EventArgs e) { Visible = !Visible; btnShowHide.Text = Visible ? "Hide" : "Show"; } private void listCases_DropDown(object sender, EventArgs e) { timerUpdateCases.Enabled = false; } private void listCases_DropDownClosed(object sender, EventArgs e) { timerUpdateCases.Enabled = true; } private void contextMenuStrip1_Opened(object sender, EventArgs e) { timerUpdateCases.Enabled = false; } private void contextMenuStrip1_Closed(object sender, ToolStripDropDownClosedEventArgs e) { timerUpdateCases.Enabled = true; } private void btnMain_Click(object sender, EventArgs e) { ShowMainMenu(); } private void ShowMainMenu() { Point p = new Point(Location.X + btnMain.Location.X, Location.Y + btnMain.Location.Y + btnMain.Height); menuMain.Show(p); backgroundPic.Focus(); } private void btnFilter_Click(object sender, EventArgs e) { ShowFilterDialog(); backgroundPic.Focus(); } private void grip_MouseDown(object sender, MouseEventArgs e) { _resizing = true; _gripStartX = Cursor.Position.X; } private void grip_MouseUp(object sender, MouseEventArgs e) { _resizing = false; } private void grip_MouseMove(object sender, MouseEventArgs e) { if (_resizing) ResizeWidth(); } private void btnResolveClose_Click(object sender, EventArgs e) { _fb.ResolveCase(TrackedCase.ID); updateCases(); } private void HoverWindow_MouseUp(object sender, MouseEventArgs e) { _dragging = false; } private void label1_MouseUp(object sender, MouseEventArgs e) { _dragging = false; } private void backgroundPic_MouseDown(object sender, MouseEventArgs e) { startDragging(e); } private void backgroundPic_MouseMove(object sender, MouseEventArgs e) { if (_dragging) dragWindow(e); } private void backgroundPic_MouseUp(object sender, MouseEventArgs e) { _dragging = false; } private void backgroundPic_Click(object sender, EventArgs e) { } private void btnNewCase_Click(object sender, EventArgs e) { Process.Start(_fb.NewCaseURL); } private void btnExportExcel_Click(object sender, EventArgs e) { ExportToExcel(); } private void timerRetryLogin_Tick(object sender, EventArgs e) { RetryLogin(); } private void btnExportFreeMind_Click(object sender, EventArgs e) { ExportToFreeMind(); } private void btnImportFreeMind_Click(object sender, EventArgs e) { DoImport(); } private void btnPause_Click(object sender, EventArgs e) { PauseWork(); backgroundPic.Focus(); } private void lblImBack_Click(object sender, EventArgs e) { if (!_dragging) ResumeWork(); backgroundPic.Focus(); } private void btnNewSubcase_Click(object sender, EventArgs e) { Process.Start(_fb.NewSubCaseURL(_trackedCase.ID)); } private void btnViewCaseOutline_Click(object sender, EventArgs e) { Process.Start(_fb.ViewOutlineURL(_trackedCase.ID)); } private void btnNewEstimate_Click(object sender, EventArgs e) { ObtainUserEstimate(_trackedCase.ID); } private void aboutToolStripMenuItem_Click(object sender, EventArgs e) { AboutDlg dlg = new AboutDlg(); dlg.ShowDialog(); } private void btnSettings_Click(object sender, EventArgs e) { ShowSettingsDialog(); } private bool UserIsAway() { if (_settings.MinutesBeforeAway == 0) return false; return Interop.GetTimeSinceLastInput().TotalMinutes > _settings.MinutesBeforeAway; } private void timerAway_Tick(object sender, EventArgs e) { if ((null != _currentState && _currentState.GetType() == typeof(StateTrackingCase)) && UserIsAway()) PauseWork(); } private void btnStop_Click(object sender, EventArgs e) { StopWork(); backgroundPic.Focus(); } private void pnlPaused_MouseDown(object sender, MouseEventArgs e) { startDragging(e); } private void pnlPaused_MouseMove(object sender, MouseEventArgs e) { if (_dragging) dragWindow(e); } private void pnlPaused_MouseUp(object sender, MouseEventArgs e) { _dragging = false; } private void pnlPaused_Resize(object sender, EventArgs e) { lblImBack.Left = (pnlPaused.Width - lblImBack.Width) / 2; } private void busyPicture_Click(object sender, EventArgs e) { ShowMainMenu(); } } // Class HoverWindow }
/* * 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 OpenSim.Data; using OpenSim.Framework; using OpenMetaverse; using OpenMetaverse.StructuredData; using log4net; using Npgsql; namespace OpenSim.Data.PGSQL { public class UserProfilesData : IProfilesData { static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected PGSQLManager m_database; #region Properites string ConnectionString { get; set; } protected virtual Assembly Assembly { get { return GetType().Assembly; } } #endregion Properties #region class Member Functions public UserProfilesData(string connectionString) { ConnectionString = connectionString; Init(); } void Init() { using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) { dbcon.Open(); Migration m = new Migration(dbcon, Assembly, "UserProfiles"); m.Update(); m_database = new PGSQLManager(ConnectionString); } } #endregion Member Functions #region Classifieds Queries /// <summary> /// Gets the classified records. /// </summary> /// <returns> /// Array of classified records /// </returns> /// <param name='creatorId'> /// Creator identifier. /// </param> public OSDArray GetClassifiedRecords(UUID creatorId) { OSDArray data = new OSDArray(); using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) { string query = @"SELECT classifieduuid, name FROM classifieds WHERE creatoruuid = :Id"; dbcon.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) { cmd.Parameters.Add(m_database.CreateParameter("Id", creatorId)); using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.Default)) { if (reader.HasRows) { while (reader.Read()) { OSDMap n = new OSDMap(); UUID Id = UUID.Zero; string Name = null; try { Id = DBGuid.FromDB(reader["classifieduuid"]); Name = Convert.ToString(reader["name"]); } catch (Exception e) { m_log.Error("[PROFILES_DATA]: UserAccount exception ", e); } n.Add("classifieduuid", OSD.FromUUID(Id)); n.Add("name", OSD.FromString(Name)); data.Add(n); } } } } } return data; } public bool UpdateClassifiedRecord(UserClassifiedAdd ad, ref string result) { string query = string.Empty; query = @"WITH upsert AS ( UPDATE classifieds SET classifieduuid = :ClassifiedId, creatoruuid = :CreatorId, creationdate = :CreatedDate, expirationdate = :ExpirationDate,category =:Category, name = :Name, description = :Description, parceluuid = :ParcelId, parentestate = :ParentEstate, snapshotuuid = :SnapshotId, simname = :SimName, posglobal = :GlobalPos, parcelname = :ParcelName, classifiedflags = :Flags, priceforlisting = :ListingPrice RETURNING * ) INSERT INTO classifieds (classifieduuid,creatoruuid,creationdate,expirationdate,category,name, description,parceluuid,parentestate,snapshotuuid,simname,posglobal,parcelname,classifiedflags, priceforlisting) SELECT :ClassifiedId,:CreatorId,:CreatedDate,:ExpirationDate,:Category,:Name,:Description, :ParcelId,:ParentEstate,:SnapshotId,:SimName,:GlobalPos,:ParcelName,:Flags,:ListingPrice WHERE NOT EXISTS ( SELECT * FROM upsert )"; if (string.IsNullOrEmpty(ad.ParcelName)) ad.ParcelName = "Unknown"; if (ad.ParcelId == null) ad.ParcelId = UUID.Zero; if (string.IsNullOrEmpty(ad.Description)) ad.Description = "No Description"; DateTime epoch = new DateTime(1970, 1, 1); DateTime now = DateTime.Now; TimeSpan epochnow = now - epoch; TimeSpan duration; DateTime expiration; TimeSpan epochexp; if (ad.Flags == 2) { duration = new TimeSpan(7, 0, 0, 0); expiration = now.Add(duration); epochexp = expiration - epoch; } else { duration = new TimeSpan(365, 0, 0, 0); expiration = now.Add(duration); epochexp = expiration - epoch; } ad.CreationDate = (int)epochnow.TotalSeconds; ad.ExpirationDate = (int)epochexp.TotalSeconds; try { using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) { dbcon.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) { cmd.Parameters.Add(m_database.CreateParameter("ClassifiedId", ad.ClassifiedId)); cmd.Parameters.Add(m_database.CreateParameter("CreatorId", ad.CreatorId)); cmd.Parameters.Add(m_database.CreateParameter("CreatedDate", (int)ad.CreationDate)); cmd.Parameters.Add(m_database.CreateParameter("ExpirationDate", (int)ad.ExpirationDate)); cmd.Parameters.Add(m_database.CreateParameter("Category", ad.Category.ToString())); cmd.Parameters.Add(m_database.CreateParameter("Name", ad.Name.ToString())); cmd.Parameters.Add(m_database.CreateParameter("Description", ad.Description.ToString())); cmd.Parameters.Add(m_database.CreateParameter("ParcelId", ad.ParcelId)); cmd.Parameters.Add(m_database.CreateParameter("ParentEstate", (int)ad.ParentEstate)); cmd.Parameters.Add(m_database.CreateParameter("SnapshotId", ad.SnapshotId)); cmd.Parameters.Add(m_database.CreateParameter("SimName", ad.SimName.ToString())); cmd.Parameters.Add(m_database.CreateParameter("GlobalPos", ad.GlobalPos.ToString())); cmd.Parameters.Add(m_database.CreateParameter("ParcelName", ad.ParcelName.ToString())); cmd.Parameters.Add(m_database.CreateParameter("Flags", (int)Convert.ToInt32(ad.Flags))); cmd.Parameters.Add(m_database.CreateParameter("ListingPrice", (int)Convert.ToInt32(ad.Price))); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.Error("[PROFILES_DATA]: ClassifiedsUpdate exception ", e); result = e.Message; return false; } return true; } public bool DeleteClassifiedRecord(UUID recordId) { string query = string.Empty; query = @"DELETE FROM classifieds WHERE classifieduuid = :ClassifiedId ;"; try { using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) { dbcon.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) { cmd.Parameters.Add(m_database.CreateParameter("ClassifiedId", recordId)); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.Error("[PROFILES_DATA]: DeleteClassifiedRecord exception ", e); return false; } return true; } public bool GetClassifiedInfo(ref UserClassifiedAdd ad, ref string result) { string query = string.Empty; query += "SELECT * FROM classifieds WHERE "; query += "classifieduuid = :AdId"; try { using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) { dbcon.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) { cmd.Parameters.Add(m_database.CreateParameter("AdId", ad.ClassifiedId)); using (NpgsqlDataReader reader = cmd.ExecuteReader()) { if (reader.Read()) { ad.CreatorId = DBGuid.FromDB(reader["creatoruuid"]); ad.ParcelId = DBGuid.FromDB(reader["parceluuid"]); ad.SnapshotId = DBGuid.FromDB(reader["snapshotuuid"]); ad.CreationDate = Convert.ToInt32(reader["creationdate"]); ad.ExpirationDate = Convert.ToInt32(reader["expirationdate"]); ad.ParentEstate = Convert.ToInt32(reader["parentestate"]); ad.Flags = (byte)Convert.ToInt16(reader["classifiedflags"]); ad.Category = Convert.ToInt32(reader["category"]); ad.Price = Convert.ToInt16(reader["priceforlisting"]); ad.Name = reader["name"].ToString(); ad.Description = reader["description"].ToString(); ad.SimName = reader["simname"].ToString(); ad.GlobalPos = reader["posglobal"].ToString(); ad.ParcelName = reader["parcelname"].ToString(); } } } dbcon.Close(); } } catch (Exception e) { m_log.Error("[PROFILES_DATA]: GetClassifiedInfo exception ", e); } return true; } public static UUID GetUUID(object uuidValue) { UUID ret = UUID.Zero; UUID.TryParse(uuidValue.ToString(), out ret); return ret; } #endregion Classifieds Queries #region Picks Queries public OSDArray GetAvatarPicks(UUID avatarId) { string query = string.Empty; query += "SELECT pickuuid, name FROM userpicks WHERE "; query += "creatoruuid = :Id"; OSDArray data = new OSDArray(); try { using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) { dbcon.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) { cmd.Parameters.Add(m_database.CreateParameter("Id", avatarId)); using (NpgsqlDataReader reader = cmd.ExecuteReader()) { if (reader.HasRows) { while (reader.Read()) { OSDMap record = new OSDMap(); record.Add("pickuuid", OSD.FromUUID(DBGuid.FromDB(reader["pickuuid"]))); record.Add("name", OSD.FromString((string)reader["name"])); data.Add(record); } } } } } } catch (Exception e) { m_log.Error("[PROFILES_DATA]: GetAvatarPicks exception ", e); } return data; } public UserProfilePick GetPickInfo(UUID avatarId, UUID pickId) { string query = string.Empty; UserProfilePick pick = new UserProfilePick(); query += "SELECT * FROM userpicks WHERE "; query += "creatoruuid = :CreatorId AND "; query += "pickuuid = :PickId"; try { using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) { dbcon.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) { cmd.Parameters.Add(m_database.CreateParameter("CreatorId", avatarId)); cmd.Parameters.Add(m_database.CreateParameter("PickId", pickId)); using (NpgsqlDataReader reader = cmd.ExecuteReader()) { if (reader.HasRows) { reader.Read(); string description = (string)reader["description"]; if (string.IsNullOrEmpty(description)) description = "No description given."; pick.PickId = DBGuid.FromDB(reader["pickuuid"]); pick.CreatorId = DBGuid.FromDB(reader["creatoruuid"]); pick.ParcelId = DBGuid.FromDB(reader["parceluuid"]); pick.SnapshotId = DBGuid.FromDB(reader["snapshotuuid"]); pick.GlobalPos = (string)reader["posglobal"].ToString(); pick.TopPick = Convert.ToBoolean(reader["toppick"]); pick.Enabled = Convert.ToBoolean(reader["enabled"]); pick.Name = reader["name"].ToString(); pick.Desc = reader["description"].ToString(); pick.ParcelName = reader["user"].ToString(); pick.OriginalName = reader["originalname"].ToString(); pick.SimName = reader["simname"].ToString(); pick.SortOrder = (int)reader["sortorder"]; } } } dbcon.Close(); } } catch (Exception e) { m_log.Error("[PROFILES_DATA]: GetPickInfo exception ", e); } return pick; } public bool UpdatePicksRecord(UserProfilePick pick) { string query = string.Empty; query = @"WITH upsert AS ( UPDATE userpicks SET pickuuid = :PickId, creatoruuid = :CreatorId, toppick = :TopPick, parceluuid = :ParcelId, name = :Name, description = :Desc, snapshotuuid = :SnapshotId, ""user"" = :User, originalname = :Original, simname = :SimName, posglobal = :GlobalPos, sortorder = :SortOrder, enabled = :Enabled RETURNING * ) INSERT INTO userpicks (pickuuid,creatoruuid,toppick,parceluuid,name,description, snapshotuuid,""user"",originalname,simname,posglobal,sortorder,enabled) SELECT :PickId,:CreatorId,:TopPick,:ParcelId,:Name,:Desc,:SnapshotId,:User, :Original,:SimName,:GlobalPos,:SortOrder,:Enabled WHERE NOT EXISTS ( SELECT * FROM upsert )"; try { using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) { dbcon.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) { cmd.Parameters.Add(m_database.CreateParameter("PickId", pick.PickId)); cmd.Parameters.Add(m_database.CreateParameter("CreatorId", pick.CreatorId)); cmd.Parameters.Add(m_database.CreateParameter("TopPick", pick.TopPick)); cmd.Parameters.Add(m_database.CreateParameter("ParcelId", pick.ParcelId)); cmd.Parameters.Add(m_database.CreateParameter("Name", pick.Name)); cmd.Parameters.Add(m_database.CreateParameter("Desc", pick.Desc)); cmd.Parameters.Add(m_database.CreateParameter("SnapshotId", pick.SnapshotId)); cmd.Parameters.Add(m_database.CreateParameter("User", pick.ParcelName)); cmd.Parameters.Add(m_database.CreateParameter("Original", pick.OriginalName)); cmd.Parameters.Add(m_database.CreateParameter("SimName", pick.SimName)); cmd.Parameters.Add(m_database.CreateParameter("GlobalPos", pick.GlobalPos)); cmd.Parameters.Add(m_database.CreateParameter("SortOrder", pick.SortOrder)); cmd.Parameters.Add(m_database.CreateParameter("Enabled", pick.Enabled)); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.Error("[PROFILES_DATA]: UpdateAvatarNotes exception ", e); return false; } return true; } public bool DeletePicksRecord(UUID pickId) { string query = string.Empty; query += "DELETE FROM userpicks WHERE "; query += "pickuuid = :PickId"; try { using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) { dbcon.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) { cmd.Parameters.Add(m_database.CreateParameter("PickId", pickId)); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.Error("[PROFILES_DATA]: DeleteUserPickRecord exception ", e); return false; } return true; } #endregion Picks Queries #region Avatar Notes Queries public bool GetAvatarNotes(ref UserProfileNotes notes) { // WIP string query = string.Empty; query += "SELECT notes FROM usernotes WHERE "; query += "useruuid = :Id AND "; query += "targetuuid = :TargetId"; OSDArray data = new OSDArray(); try { using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) { dbcon.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) { cmd.Parameters.Add(m_database.CreateParameter("Id", notes.UserId)); cmd.Parameters.Add(m_database.CreateParameter("TargetId", notes.TargetId)); using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if (reader.HasRows) { reader.Read(); notes.Notes = OSD.FromString((string)reader["notes"]); } } } } } catch (Exception e) { m_log.Error("[PROFILES_DATA]: GetAvatarNotes exception ", e); } return true; } public bool UpdateAvatarNotes(ref UserProfileNotes note, ref string result) { string query = string.Empty; bool remove; if (string.IsNullOrEmpty(note.Notes)) { remove = true; query += "DELETE FROM usernotes WHERE "; query += "useruuid=:UserId AND "; query += "targetuuid=:TargetId"; } else { remove = false; query = @"WITH upsert AS ( UPDATE usernotes SET notes = :Notes, useruuid = :UserId, targetuuid = :TargetId RETURNING * ) INSERT INTO usernotes (notes,useruuid,targetuuid) SELECT :Notes,:UserId,:TargetId WHERE NOT EXISTS ( SELECT * FROM upsert )"; } try { using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) { dbcon.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) { if (!remove) cmd.Parameters.Add(m_database.CreateParameter("Notes", note.Notes)); cmd.Parameters.Add(m_database.CreateParameter("TargetId", note.TargetId)); cmd.Parameters.Add(m_database.CreateParameter("UserId", note.UserId)); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.Error("[PROFILES_DATA]: UpdateAvatarNotes exception ", e); return false; } return true; } #endregion Avatar Notes Queries #region Avatar Properties public bool GetAvatarProperties(ref UserProfileProperties props, ref string result) { string query = string.Empty; query += "SELECT * FROM userprofile WHERE "; query += "useruuid = :Id"; try { using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) { dbcon.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) { cmd.Parameters.Add(m_database.CreateParameter("Id", props.UserId)); using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if (reader.HasRows) { // m_log.DebugFormat("[PROFILES_DATA]" + // ": Getting data for {0}.", props.UserId); reader.Read(); props.WebUrl = (string)reader["profileURL"].ToString(); props.ImageId = DBGuid.FromDB(reader["profileImage"]); props.AboutText = (string)reader["profileAboutText"]; props.FirstLifeImageId = DBGuid.FromDB(reader["profileFirstImage"]); props.FirstLifeText = (string)reader["profileFirstText"]; props.PartnerId = DBGuid.FromDB(reader["profilePartner"]); props.WantToMask = (int)reader["profileWantToMask"]; props.WantToText = (string)reader["profileWantToText"]; props.SkillsMask = (int)reader["profileSkillsMask"]; props.SkillsText = (string)reader["profileSkillsText"]; props.Language = (string)reader["profileLanguages"]; } else { //m_log.DebugFormat("[PROFILES_DATA]" + // ": No data for {0}", props.UserId); props.WebUrl = string.Empty; props.ImageId = UUID.Zero; props.AboutText = string.Empty; props.FirstLifeImageId = UUID.Zero; props.FirstLifeText = string.Empty; props.PartnerId = UUID.Zero; props.WantToMask = 0; props.WantToText = string.Empty; props.SkillsMask = 0; props.SkillsText = string.Empty; props.Language = string.Empty; props.PublishProfile = false; props.PublishMature = false; query = "INSERT INTO userprofile ("; query += "useruuid, "; query += "\"profilePartner\", "; query += "\"profileAllowPublish\", "; query += "\"profileMaturePublish\", "; query += "\"profileURL\", "; query += "\"profileWantToMask\", "; query += "\"profileWantToText\", "; query += "\"profileSkillsMask\", "; query += "\"profileSkillsText\", "; query += "\"profileLanguages\", "; query += "\"profileImage\", "; query += "\"profileAboutText\", "; query += "\"profileFirstImage\", "; query += "\"profileFirstText\") VALUES ("; query += ":userId, "; query += ":profilePartner, "; query += ":profileAllowPublish, "; query += ":profileMaturePublish, "; query += ":profileURL, "; query += ":profileWantToMask, "; query += ":profileWantToText, "; query += ":profileSkillsMask, "; query += ":profileSkillsText, "; query += ":profileLanguages, "; query += ":profileImage, "; query += ":profileAboutText, "; query += ":profileFirstImage, "; query += ":profileFirstText)"; dbcon.Close(); dbcon.Open(); using (NpgsqlCommand put = new NpgsqlCommand(query, dbcon)) { //m_log.DebugFormat("[PROFILES_DATA]" + // ": Adding new data for {0}", props.UserId); put.Parameters.Add(m_database.CreateParameter("userId", props.UserId)); put.Parameters.Add(m_database.CreateParameter("profilePartner", props.PartnerId)); put.Parameters.Add(m_database.CreateParameter("profileAllowPublish", props.PublishProfile)); put.Parameters.Add(m_database.CreateParameter("profileMaturePublish", props.PublishMature)); put.Parameters.Add(m_database.CreateParameter("profileURL", props.WebUrl)); put.Parameters.Add(m_database.CreateParameter("profileWantToMask", props.WantToMask)); put.Parameters.Add(m_database.CreateParameter("profileWantToText", props.WantToText)); put.Parameters.Add(m_database.CreateParameter("profileSkillsMask", props.SkillsMask)); put.Parameters.Add(m_database.CreateParameter("profileSkillsText", props.SkillsText)); put.Parameters.Add(m_database.CreateParameter("profileLanguages", props.Language)); put.Parameters.Add(m_database.CreateParameter("profileImage", props.ImageId)); put.Parameters.Add(m_database.CreateParameter("profileAboutText", props.AboutText)); put.Parameters.Add(m_database.CreateParameter("profileFirstImage", props.FirstLifeImageId)); put.Parameters.Add(m_database.CreateParameter("profileFirstText", props.FirstLifeText)); put.ExecuteNonQuery(); } } } } } } catch (Exception e) { m_log.Error("[PROFILES_DATA]: GetAvatarProperties exception ", e); result = e.Message; return false; } return true; } public bool UpdateAvatarProperties(ref UserProfileProperties props, ref string result) { string query = string.Empty; query += "UPDATE userprofile SET "; query += "\"profileURL\"=:profileURL, "; query += "\"profileImage\"=:image, "; query += "\"profileAboutText\"=:abouttext,"; query += "\"profileFirstImage\"=:firstlifeimage,"; query += "\"profileFirstText\"=:firstlifetext "; query += "WHERE \"useruuid\"=:uuid"; try { using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) { dbcon.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) { cmd.Parameters.Add(m_database.CreateParameter("profileURL", props.WebUrl)); cmd.Parameters.Add(m_database.CreateParameter("image", props.ImageId)); cmd.Parameters.Add(m_database.CreateParameter("abouttext", props.AboutText)); cmd.Parameters.Add(m_database.CreateParameter("firstlifeimage", props.FirstLifeImageId)); cmd.Parameters.Add(m_database.CreateParameter("firstlifetext", props.FirstLifeText)); cmd.Parameters.Add(m_database.CreateParameter("uuid", props.UserId)); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.Error("[PROFILES_DATA]: AgentPropertiesUpdate exception ", e); return false; } return true; } #endregion Avatar Properties #region Avatar Interests public bool UpdateAvatarInterests(UserProfileProperties up, ref string result) { string query = string.Empty; query += "UPDATE userprofile SET "; query += "\"profileWantToMask\"=:WantMask, "; query += "\"profileWantToText\"=:WantText,"; query += "\"profileSkillsMask\"=:SkillsMask,"; query += "\"profileSkillsText\"=:SkillsText, "; query += "\"profileLanguages\"=:Languages "; query += "WHERE \"useruuid\"=:uuid"; try { using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) { dbcon.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) { cmd.Parameters.Add(m_database.CreateParameter("WantMask", up.WantToMask)); cmd.Parameters.Add(m_database.CreateParameter("WantText", up.WantToText)); cmd.Parameters.Add(m_database.CreateParameter("SkillsMask", up.SkillsMask)); cmd.Parameters.Add(m_database.CreateParameter("SkillsText", up.SkillsText)); cmd.Parameters.Add(m_database.CreateParameter("Languages", up.Language)); cmd.Parameters.Add(m_database.CreateParameter("uuid", up.UserId)); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.Error("[PROFILES_DATA]: UpdateAvatarInterests exception ", e); result = e.Message; return false; } return true; } #endregion Avatar Interests public OSDArray GetUserImageAssets(UUID avatarId) { OSDArray data = new OSDArray(); string query = "SELECT \"snapshotuuid\" FROM {0} WHERE \"creatoruuid\" = :Id"; try { using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) { dbcon.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format(query, "\"classifieds\""), dbcon)) { cmd.Parameters.Add(m_database.CreateParameter("Id", avatarId)); using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if (reader.HasRows) { while (reader.Read()) { data.Add(new OSDString(reader["snapshotuuid"].ToString())); } } } } dbcon.Close(); dbcon.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format(query, "\"userpicks\""), dbcon)) { cmd.Parameters.Add(m_database.CreateParameter("Id", avatarId)); using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if (reader.HasRows) { while (reader.Read()) { data.Add(new OSDString(reader["snapshotuuid"].ToString())); } } } } dbcon.Close(); dbcon.Open(); query = "SELECT \"profileImage\", \"profileFirstImage\" FROM \"userprofile\" WHERE \"useruuid\" = :Id"; using (NpgsqlCommand cmd = new NpgsqlCommand(string.Format(query, "\"userpicks\""), dbcon)) { cmd.Parameters.Add(m_database.CreateParameter("Id", avatarId)); using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if (reader.HasRows) { while (reader.Read()) { data.Add(new OSDString(reader["profileImage"].ToString())); data.Add(new OSDString(reader["profileFirstImage"].ToString())); } } } } } } catch (Exception e) { m_log.Error("[PROFILES_DATA]: GetUserImageAssets exception ", e); } return data; } #region User Preferences public bool GetUserPreferences(ref UserPreferences pref, ref string result) { string query = string.Empty; query += "SELECT imviaemail::VARCHAR,visible::VARCHAR,email FROM "; query += "usersettings WHERE "; query += "useruuid = :Id"; OSDArray data = new OSDArray(); try { using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) { dbcon.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) { cmd.Parameters.Add(m_database.CreateParameter("Id", pref.UserId)); using (NpgsqlDataReader reader = cmd.ExecuteReader()) { if (reader.HasRows) { reader.Read(); bool.TryParse((string)reader["imviaemail"], out pref.IMViaEmail); bool.TryParse((string)reader["visible"], out pref.Visible); pref.EMail = (string)reader["email"]; } else { using (NpgsqlCommand put = new NpgsqlCommand(query, dbcon)) { put.Parameters.Add(m_database.CreateParameter("Id", pref.UserId)); query = "INSERT INTO usersettings VALUES "; query += "(:Id,'false','false', '')"; put.ExecuteNonQuery(); } } } } } } catch (Exception e) { m_log.Error("[PROFILES_DATA]: GetUserPreferences exception ", e); result = e.Message; } return true; } public bool UpdateUserPreferences(ref UserPreferences pref, ref string result) { string query = string.Empty; query += "UPDATE usersettings SET "; query += "imviaemail=:ImViaEmail, "; query += "visible=:Visible, "; query += "email=:Email "; query += "WHERE useruuid=:uuid"; try { using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) { dbcon.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) { cmd.Parameters.Add(m_database.CreateParameter("ImViaEmail", pref.IMViaEmail)); cmd.Parameters.Add(m_database.CreateParameter("Visible", pref.Visible)); cmd.Parameters.Add(m_database.CreateParameter("EMail", pref.EMail.ToString().ToLower())); cmd.Parameters.Add(m_database.CreateParameter("uuid", pref.UserId)); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.Error("[PROFILES_DATA]: UpdateUserPreferences exception ", e); result = e.Message; return false; } return true; } #endregion User Preferences #region Integration public bool GetUserAppData(ref UserAppData props, ref string result) { string query = string.Empty; query += "SELECT * FROM userdata WHERE "; query += "\"UserId\" = :Id AND "; query += "\"TagId\" = :TagId"; try { using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) { dbcon.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) { cmd.Parameters.Add(m_database.CreateParameter("Id", props.UserId)); cmd.Parameters.Add(m_database.CreateParameter("TagId", props.TagId)); using (NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if (reader.HasRows) { reader.Read(); props.DataKey = (string)reader["DataKey"]; props.DataVal = (string)reader["DataVal"]; } else { query += "INSERT INTO userdata VALUES ( "; query += ":UserId,"; query += ":TagId,"; query += ":DataKey,"; query += ":DataVal) "; using (NpgsqlCommand put = new NpgsqlCommand(query, dbcon)) { put.Parameters.Add(m_database.CreateParameter("UserId", props.UserId)); put.Parameters.Add(m_database.CreateParameter("TagId", props.TagId)); put.Parameters.Add(m_database.CreateParameter("DataKey", props.DataKey.ToString())); put.Parameters.Add(m_database.CreateParameter("DataVal", props.DataVal.ToString())); put.ExecuteNonQuery(); } } } } } } catch (Exception e) { m_log.Error("[PROFILES_DATA]: GetUserAppData exception ", e); result = e.Message; return false; } return true; } public bool SetUserAppData(UserAppData props, ref string result) { string query = string.Empty; query += "UPDATE userdata SET "; query += "\"TagId\" = :TagId, "; query += "\"DataKey\" = :DataKey, "; query += "\"DataVal\" = :DataVal WHERE "; query += "\"UserId\" = :UserId AND "; query += "\"TagId\" = :TagId"; try { using (NpgsqlConnection dbcon = new NpgsqlConnection(ConnectionString)) { dbcon.Open(); using (NpgsqlCommand cmd = new NpgsqlCommand(query, dbcon)) { cmd.Parameters.Add(m_database.CreateParameter("UserId", props.UserId.ToString())); cmd.Parameters.Add(m_database.CreateParameter("TagId", props.TagId.ToString())); cmd.Parameters.Add(m_database.CreateParameter("DataKey", props.DataKey.ToString())); cmd.Parameters.Add(m_database.CreateParameter("DataVal", props.DataKey.ToString())); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.Error("[PROFILES_DATA]: SetUserData exception ", e); return false; } return true; } #endregion Integration } }
/* Copyright 2014 David Bordoley Copyright 2014 Zumero, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using Xunit; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; namespace SQLitePCL.pretty.tests { public class DatabaseBackupTests { [Fact] public void TestDispose() { using (var db = SQLite3.OpenInMemory()) { db.Execute("CREATE TABLE foo (x int);"); foreach (int i in Enumerable.Range(0, 1000)) { db.Execute("INSERT INTO foo (x) VALUES (?);", i); } IDatabaseBackup notDisposedBackup; using (var db2 = SQLite3.OpenInMemory()) { var backup = db.BackupInit("main", db2, "main"); backup.Dispose(); Assert.Throws<ObjectDisposedException>(() => { var x = backup.PageCount; }); Assert.Throws<ObjectDisposedException>(() => { var x = backup.RemainingPages; }); Assert.Throws<ObjectDisposedException>(() => { backup.Step(1); }); notDisposedBackup = db.BackupInit("main", db2, "main"); } // Ensure diposing the database connection automatically disposes the backup as well. Assert.Throws<ObjectDisposedException>(() => { var x = notDisposedBackup.PageCount; }); // Test double disposing doesn't result in exceptions. notDisposedBackup.Dispose(); } } [Fact] public void TestBackupWithPageStepping() { using (var db = SQLite3.OpenInMemory()) { db.Execute("CREATE TABLE foo (x int);"); foreach (int i in Enumerable.Range(0, 1000)) { db.Execute("INSERT INTO foo (x) VALUES (?);", i); } using (var db2 = SQLite3.OpenInMemory()) { using (var backup = db.BackupInit("main", db2, "main")) { Assert.Equal(0, backup.RemainingPages); Assert.Equal(0, backup.PageCount); backup.Step(1); var remainingPages = backup.RemainingPages; while (backup.Step(1)) { Assert.True(backup.RemainingPages < remainingPages); remainingPages = backup.RemainingPages; } Assert.False(backup.Step(2)); Assert.False(backup.Step(-1)); Assert.Equal(backup.RemainingPages, 0); Assert.True(backup.PageCount > 0); } } } } [Fact] public void TestBackup() { using (var db = SQLite3.OpenInMemory()) { db.Execute("CREATE TABLE foo (x int);"); foreach (int i in Enumerable.Range(0, 1000)) { db.Execute("INSERT INTO foo (x) VALUES (?);", i); } using (var db2 = SQLite3.OpenInMemory()) { using (var backup = db.BackupInit("main", db2, "main")) { Assert.Equal(0, backup.RemainingPages); Assert.Equal(0, backup.PageCount); Assert.False(backup.Step(-1)); Assert.Equal(backup.RemainingPages, 0); Assert.True(backup.PageCount > 0); } } using (var db3 = SQLite3.OpenInMemory()) { db.Backup("main", db3, "main"); var backupResults = Enumerable.Zip( db.Query("SELECT x FROM foo"), db3.Query("SELECT x FROM foo"), Tuple.Create); foreach (var pair in backupResults) { Assert.Equal(pair.Item1[0].ToInt(), pair.Item2[0].ToInt()); } } } } } public class StatementTests { [Fact] public void TestCurrent() { using (var db = SQLite3.OpenInMemory()) using (var stmt = db.PrepareStatement("SELECT 1")) { stmt.MoveNext(); Assert.Equal(stmt.Current[0].ToInt(), 1); var ienumCurrent = ((IEnumerator)stmt).Current; var ienumResultSet = (IReadOnlyList<IResultSetValue>) ienumCurrent; Assert.Equal(ienumResultSet[0].ToInt(), 1); } } [Fact] public void TestDispose() { using (var db = SQLite3.OpenInMemory()) { var stmt = db.PrepareStatement("SELECT 1"); stmt.Dispose(); // Test double dispose stmt.Dispose(); Assert.Throws<ObjectDisposedException>(() => { var x = stmt.BindParameters; }); Assert.Throws<ObjectDisposedException>(() => { var x = stmt.Columns; }); Assert.Throws<ObjectDisposedException>(() => { var x = stmt.Current; }); Assert.Throws<ObjectDisposedException>(() => { var x = stmt.SQL; }); Assert.Throws<ObjectDisposedException>(() => { var x = stmt.IsBusy; }); Assert.Throws<ObjectDisposedException>(() => { var x = stmt.IsReadOnly; }); Assert.Throws<ObjectDisposedException>(() => { stmt.ClearBindings(); }); Assert.Throws<ObjectDisposedException>(() => { stmt.MoveNext(); }); Assert.Throws<ObjectDisposedException>(() => { stmt.Reset(); }); Assert.Throws<ObjectDisposedException>(() => { stmt.Status(StatementStatusCode.Sort, false); }); } } [Fact] public void TestBusy() { using (var db = SQLite3.OpenInMemory()) { db.ExecuteAll( @"CREATE TABLE foo (x int); INSERT INTO foo (x) VALUES (1); INSERT INTO foo (x) VALUES (2); INSERT INTO foo (x) VALUES (3);"); using (var stmt = db.PrepareStatement("SELECT x FROM foo;")) { Assert.False(stmt.IsBusy); stmt.MoveNext(); Assert.True(stmt.IsBusy); stmt.MoveNext(); Assert.True(stmt.IsBusy); stmt.MoveNext(); Assert.True(stmt.IsBusy); stmt.MoveNext(); Assert.False(stmt.IsBusy); } } } [Fact] public void TestBindParameterCount() { Tuple<string, int>[] tests = { Tuple.Create("CREATE TABLE foo (x int)", 0), Tuple.Create("CREATE TABLE foo2 (x int, y int)", 0), Tuple.Create("select * from foo", 0), Tuple.Create("INSERT INTO foo (x) VALUES (?)", 1), Tuple.Create("INSERT INTO foo2 (x, y) VALUES (?, ?)", 2) }; using (var db = SQLite3.OpenInMemory()) { foreach (var test in tests) { using (var stmt = db.PrepareStatement(test.Item1)) { Assert.Equal(test.Item2, stmt.BindParameters.Count); stmt.MoveNext(); } } } } [Fact] public void TestReadOnly() { Tuple<string, bool>[] tests = { Tuple.Create("CREATE TABLE foo (x int)", false), Tuple.Create("CREATE TABLE foo2 (x int, y int)", false), Tuple.Create("select * from foo", true), Tuple.Create("INSERT INTO foo (x) VALUES (?)", false), Tuple.Create("INSERT INTO foo2 (x, y) VALUES (?, ?)", false) }; using (var db = SQLite3.OpenInMemory()) { foreach (var test in tests) { using (var stmt = db.PrepareStatement(test.Item1)) { Assert.Equal(test.Item2, stmt.IsReadOnly); stmt.MoveNext(); } } } } [Fact] public void TestGetSQL() { string[] sql = { "CREATE TABLE foo (x int)", "INSERT INTO foo (x) VALUES (1)", "INSERT INTO foo (x) VALUES (2)", "INSERT INTO foo (x) VALUES (3)", "SELECT x FROM foo", }; using (var db = SQLite3.OpenInMemory()) { foreach (var sqlStmt in sql) { using (var stmt = db.PrepareStatement(sqlStmt)) { stmt.MoveNext(); Assert.Equal(sqlStmt, stmt.SQL); } } } } [Fact] public void TestGetBindParameters() { using (var db = SQLite3.OpenInMemory()) { db.Execute("CREATE TABLE foo (x int, v int, t text, d real, b blob, q blob);"); using (var stmt = db.PrepareStatement("INSERT INTO foo (x,v,t,d,b,q) VALUES (:x,:v,:t,:d,:b,:q)")) { Assert.Equal(stmt.BindParameters[0].Name, ":x"); Assert.Equal(stmt.BindParameters[1].Name, ":v"); Assert.Equal(stmt.BindParameters[2].Name, ":t"); Assert.Equal(stmt.BindParameters[3].Name, ":d"); Assert.Equal(stmt.BindParameters[4].Name, ":b"); Assert.Equal(stmt.BindParameters[5].Name, ":q"); Assert.Equal(stmt.BindParameters[":x"].Name, ":x"); Assert.Equal(stmt.BindParameters[":v"].Name, ":v"); Assert.Equal(stmt.BindParameters[":t"].Name, ":t"); Assert.Equal(stmt.BindParameters[":d"].Name, ":d"); Assert.Equal(stmt.BindParameters[":b"].Name, ":b"); Assert.Equal(stmt.BindParameters[":q"].Name, ":q"); Assert.True(stmt.BindParameters.ContainsKey(":x")); Assert.False(stmt.BindParameters.ContainsKey(":nope")); Assert.Equal(stmt.BindParameters.Keys.Count(), 6); Assert.Equal(stmt.BindParameters.Values.Count(), 6); Assert.Throws<KeyNotFoundException>(() => { var x = stmt.BindParameters[":nope"]; }); Assert.Throws<ArgumentOutOfRangeException>(() => { var x = stmt.BindParameters[-1]; }); Assert.Throws<ArgumentOutOfRangeException>(() => { var x = stmt.BindParameters[100]; }); Assert.NotNull(((IEnumerable) stmt.BindParameters).GetEnumerator()); } } } [Fact] public void TestExecute() { using (var db = SQLite3.OpenInMemory()) { db.Execute("CREATE TABLE foo (v int);"); using (var stmt = db.PrepareStatement("INSERT INTO foo (v) VALUES (?)")) { foreach (var i in Enumerable.Range(0, 100)) { stmt.Execute(i); } } foreach (var result in db.Query("SELECT v FROM foo ORDER BY 1").Select((v, index) => Tuple.Create(index, v[0].ToInt()))) { Assert.Equal(result.Item1, result.Item2); } } } [Fact] public void TestQuery() { using (var db = SQLite3.OpenInMemory()) { db.Execute("CREATE TABLE foo (v int);"); using (var stmt = db.PrepareStatement("INSERT INTO foo (v) VALUES (?)")) { foreach (var i in Enumerable.Range(0, 100)) { stmt.Execute(i); } } using (var stmt = db.PrepareStatement("SELECT * from FOO WHERE v < ?")) { var result = stmt.Query(50).Count(); // Ensure that enumerating the Query Enumerable doesn't dispose the stmt { var x = stmt.IsBusy; } Assert.Equal(result, 50); } using (var stmt = db.PrepareStatement("SELECT * from FOO WHERE v < 50")) { var result = stmt.Query().Count(); // Ensure that enumerating the Query Enumerable doesn't dispose the stmt { var x = stmt.IsBusy; } Assert.Equal(result, 50); } } } [Fact] public void TestClearBindings() { using (var db = SQLite3.OpenInMemory()) { db.Execute("CREATE TABLE foo (x int, v int);"); using (var stmt = db.PrepareStatement("INSERT INTO foo (x,v) VALUES (:x,:v)")) { stmt.BindParameters[0].Bind(1); stmt.BindParameters[1].Bind(2); stmt.MoveNext(); stmt.Reset(); stmt.ClearBindings(); stmt.MoveNext(); } var last = db.Query("SELECT * from FOO") .Select(row => Tuple.Create(row[0].ToInt(), row[1].ToInt())) .Last(); Assert.Equal(last.Item1, 0); Assert.Equal(last.Item2, 0); } } [Fact] public void TestGetColumns() { using (var db = SQLite3.OpenInMemory()) { var count = 0; var stmt = db.PrepareStatement("SELECT 1 as a, 2 as a, 3 as a"); foreach (var column in stmt.Columns) { count++; Assert.Equal(column.Name, "a"); } Assert.Throws<ArgumentOutOfRangeException>(() => { var x = stmt.Columns[-1]; }); Assert.Throws<ArgumentOutOfRangeException>(() => { var x = stmt.Columns[3]; }); Assert.Equal(count, stmt.Columns.Count); } } [Fact] public void TestStatus() { using (var db = SQLite3.OpenInMemory()) { db.Execute("CREATE TABLE foo (x int);"); using (var stmt = db.PrepareStatement("SELECT x FROM foo")) { stmt.MoveNext(); int vmStep = stmt.Status(StatementStatusCode.VirtualMachineStep, false); Assert.True(vmStep > 0); int vmStep2 = stmt.Status(StatementStatusCode.VirtualMachineStep, true); Assert.Equal(vmStep, vmStep2); int vmStep3 = stmt.Status(StatementStatusCode.VirtualMachineStep, false); Assert.Equal(0, vmStep3); } } } } public class BindParameters { [Fact] public void TestBindOnDisposedStatement() { using (var db = SQLite3.OpenInMemory()) { db.Execute("CREATE TABLE foo (v int);"); IReadOnlyOrderedDictionary<string, IBindParameter> bindParams; using (var stmt = db.PrepareStatement("INSERT INTO foo (v) VALUES (?)")) { bindParams = stmt.BindParameters; } Assert.Throws<ObjectDisposedException>(() => { var x = bindParams[0]; }); } } [Fact] public void TestBindObject() { using (var db = SQLite3.OpenInMemory()) { db.Execute("CREATE TABLE foo (v int);"); using (var stmt = db.PrepareStatement("INSERT INTO foo (v) VALUES (?)")) { var stream = new MemoryStream(); stream.Dispose(); Assert.Throws<ArgumentException>(() => stmt.BindParameters[0].Bind(stream)); Assert.Throws<ArgumentException>(() => stmt.BindParameters[0].Bind(new object())); } using (var stmt = db.PrepareStatement("SELECT ?")) { stmt.Reset(); stmt.ClearBindings(); stmt.BindParameters[0].Bind((object) DateTime.MaxValue); stmt.MoveNext(); Assert.Equal(stmt.Current[0].ToDateTime(), DateTime.MaxValue); stmt.Reset(); stmt.ClearBindings(); stmt.BindParameters[0].Bind((object) DateTimeOffset.MaxValue); stmt.MoveNext(); Assert.Equal(stmt.Current[0].ToDateTimeOffset(), DateTimeOffset.MaxValue); stmt.Reset(); stmt.ClearBindings(); stmt.BindParameters[0].Bind((object) TimeSpan.Zero); stmt.MoveNext(); Assert.Equal(stmt.Current[0].ToTimeSpan(), TimeSpan.Zero); } } } [Fact] public void TestBindExtensions() { using (var db = SQLite3.OpenInMemory()) { using (var stmt = db.PrepareStatement("SELECT ?")) { stmt.Reset(); stmt.ClearBindings(); stmt.BindParameters[0].Bind(true); stmt.MoveNext(); Assert.Equal(stmt.Current[0].ToBool(), true); stmt.Reset(); stmt.ClearBindings(); stmt.BindParameters[0].Bind(TimeSpan.Zero); stmt.MoveNext(); Assert.Equal(stmt.Current[0].ToTimeSpan(), TimeSpan.Zero); stmt.Reset(); stmt.ClearBindings(); stmt.BindParameters[0].Bind(1.1m); stmt.MoveNext(); Assert.Equal(stmt.Current[0].ToDecimal(), new Decimal(1.1)); stmt.Reset(); stmt.ClearBindings(); stmt.BindParameters[0].Bind(DateTime.MaxValue); stmt.MoveNext(); Assert.Equal(stmt.Current[0].ToDateTime(), DateTime.MaxValue); stmt.Reset(); stmt.ClearBindings(); stmt.BindParameters[0].Bind(DateTimeOffset.MaxValue); stmt.MoveNext(); Assert.Equal(stmt.Current[0].ToDateTimeOffset(), DateTimeOffset.MaxValue); } } } [Fact] public void TestBindSQLiteValue() { using (var db = SQLite3.OpenInMemory()) { db.Execute("CREATE TABLE foo (v int);"); using (var stmt = db.PrepareStatement("SELECT ?")) { var param = stmt.BindParameters[0]; param.Bind(SQLiteValue.Null); stmt.MoveNext(); var result = stmt.Current.First(); Assert.Equal(result.SQLiteType, SQLiteType.Null); stmt.Reset(); param.Bind(new byte[0].ToSQLiteValue()); stmt.MoveNext(); result = stmt.Current.First(); Assert.Equal(result.SQLiteType, SQLiteType.Blob); Assert.Equal(result.ToBlob(), new Byte[0]); stmt.Reset(); param.Bind("test".ToSQLiteValue()); stmt.MoveNext(); result = stmt.Current.First(); Assert.Equal(result.SQLiteType, SQLiteType.Text); Assert.Equal(result.ToString(), "test"); stmt.Reset(); param.Bind((1).ToSQLiteValue()); stmt.MoveNext(); result = stmt.Current.First(); Assert.Equal(result.SQLiteType, SQLiteType.Integer); Assert.Equal(result.ToInt64(), 1); stmt.Reset(); param.Bind((0.0).ToSQLiteValue()); stmt.MoveNext(); result = stmt.Current.First(); Assert.Equal(result.SQLiteType, SQLiteType.Float); Assert.Equal(result.ToInt(), 0); } } } } public class ResultSetTests { [Fact] public void TestCount() { using (var db = SQLite3.OpenInMemory()) { db.ExecuteAll( @"CREATE TABLE foo (x int, v int); INSERT INTO foo (x, v) VALUES (1, 2); INSERT INTO foo (x, v) VALUES (2, 3);"); foreach (var row in db.Query("select * from foo")) { Assert.Equal(row.Count, 2); } foreach (var row in db.Query("select x from foo")) { Assert.Equal(row.Count, 1); } } } [Fact] public void TestBracketOp() { using (var db = SQLite3.OpenInMemory()) { db.ExecuteAll( @"CREATE TABLE foo (x int, v int); INSERT INTO foo (x, v) VALUES (1, 2); INSERT INTO foo (x, v) VALUES (2, 3);"); foreach (var row in db.Query("select * from foo")) { Assert.Throws<ArgumentOutOfRangeException>(() => { var x = row[-1]; }); Assert.Throws<ArgumentOutOfRangeException>(() => { var x = row[row.Count]; }); Assert.Equal(row[0].SQLiteType, SQLiteType.Integer); Assert.Equal(row[1].SQLiteType, SQLiteType.Integer); } } } [Fact] public void TestColumns() { using (var db = SQLite3.OpenInMemory()) { foreach (var row in db.Query("SELECT 1 as a, 2 as b")) { var columns = row.Columns(); Assert.Equal(columns[0].Name, "a"); Assert.Equal(columns[1].Name, "b"); Assert.Equal(columns.Count, 2); var count = row.Columns().Count(); Assert.Equal(count, 2); } } } } public class BlobStreamTests { [Fact] public void TestRead() { using (var db = SQLite3.OpenInMemory()) { byte[] bytes = new byte[1000]; Random random = new Random(); random.NextBytes(bytes); db.Execute("CREATE TABLE foo (x blob);"); db.Execute("INSERT INTO foo (x) VALUES(?);", bytes); var stream = db.Query("SELECT rowid, x FROM foo;") .Select(row => db.OpenBlob(row[1].ColumnInfo, row[0].ToInt64(), false)) .First(); using (stream) { Assert.True(stream.CanRead); Assert.False(stream.CanWrite); Assert.True(stream.CanSeek); for (int i = 0; i < stream.Length; i++) { int b = stream.ReadByte(); Assert.Equal(bytes[i], b); } // Since this is a read only stream, this is a good chance to test that writing fails Assert.Throws<NotSupportedException>(() => stream.WriteByte(0)); } } } [Fact] public void TestDispose() { Stream notDisposedStream; using (var db = SQLite3.OpenInMemory()) { db.Execute("CREATE TABLE foo (x blob);"); db.Execute("INSERT INTO foo (x) VALUES(?);", "data"); var blob = db.Query("SELECT rowid, x FROM foo") .Select(row => db.OpenBlob(row[1].ColumnInfo, row[0].ToInt64(), true)) .First(); blob.Dispose(); // Test double dispose doesn't crash blob.Dispose(); Assert.Throws<ObjectDisposedException>(() => { var x = blob.Length; }); Assert.Throws<ObjectDisposedException>(() => { var x = blob.Position; }); Assert.Throws<ObjectDisposedException>(() => { blob.Position = 10; }); Assert.Throws<ObjectDisposedException>(() => { blob.Read(new byte[10], 0, 2); }); Assert.Throws<ObjectDisposedException>(() => { blob.Write(new byte[10], 0, 1); }); Assert.Throws<ObjectDisposedException>(() => { blob.Seek(0, SeekOrigin.Begin); }); notDisposedStream = db.Query("SELECT rowid, x FROM foo;") .Select(row => db.OpenBlob(row[1].ColumnInfo, row[0].ToInt64(), false)) .First(); } // Test that disposing the connection disposes the stream Assert.Throws<ObjectDisposedException>(() => { var x = notDisposedStream.Length; }); } [Fact] public void TestSeek() { using (var db = SQLite3.OpenInMemory()) { db.Execute("CREATE TABLE foo (x blob);"); db.Execute("INSERT INTO foo (x) VALUES(?);", "data"); var blob = db.Query("SELECT rowid, x FROM foo") .Select(row => db.OpenBlob(row[1].ColumnInfo, row[0].ToInt64(), true)) .First(); using (blob) { Assert.True(blob.CanSeek); Assert.Throws<NotSupportedException>(() => blob.SetLength(10)); { blob.Position = 100; } // Test input validation blob.Position = 5; Assert.Throws<IOException>(() => blob.Seek(-10, SeekOrigin.Begin)); Assert.Equal(blob.Position, 5); Assert.Throws<IOException>(() => blob.Seek(-10, SeekOrigin.Current)); Assert.Equal(blob.Position, 5); Assert.Throws<IOException>(() => blob.Seek(-100, SeekOrigin.End)); Assert.Equal(blob.Position, 5); Assert.Throws<ArgumentException>(() => blob.Seek(-100, (SeekOrigin)10)); Assert.Equal(blob.Position, 5); blob.Seek(0, SeekOrigin.Begin); Assert.Equal(blob.Position, 0); blob.Seek(0, SeekOrigin.End); Assert.Equal(blob.Position, blob.Length); blob.Position = 5; blob.Seek(2, SeekOrigin.Current); Assert.Equal(blob.Position, 7); } } } [Fact] public void TestWrite() { using (var db = SQLite3.OpenInMemory()) { byte[] bytes = new byte[1000]; Random random = new Random(); random.NextBytes(bytes); var source = new MemoryStream(bytes); db.Execute("CREATE TABLE foo (x blob);"); db.Execute("INSERT INTO foo (x) VALUES(?);", source); var stream = db.Query("SELECT rowid, x FROM foo") .Select(row => db.OpenBlob(row[1].ColumnInfo, row[0].ToInt64(), true)) .First(); using (stream) { Assert.True(stream.CanRead); Assert.True(stream.CanWrite); source.CopyTo(stream); stream.Position = 0; for (int i = 0; i < stream.Length; i++) { int b = stream.ReadByte(); Assert.Equal(bytes[i], b); } // Test writing after the end of the stream // Assert that nothing changes. stream.Position = stream.Length; stream.Write(new byte[10], 0, 10); stream.Position = 0; for (int i = 0; i < stream.Length; i++) { int b = stream.ReadByte(); Assert.Equal(bytes[i], b); } } } } } }
// // ForestDBViewStore.cs // // Author: // Jim Borden <jim.borden@couchbase.com> // // Copyright (c) 2015 Couchbase, Inc All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #define PARSED_KEYS #define CONNECTION_PER_THREAD using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using CBForest; using Couchbase.Lite.Internal; using Couchbase.Lite.Util; using Couchbase.Lite.Views; using Couchbase.Lite.Storage.ForestDB.Internal; using Couchbase.Lite.Store; namespace Couchbase.Lite.Storage.ForestDB { internal unsafe delegate void C4KeyActionDelegate(C4Key*[] key); internal sealed unsafe class ForestDBViewStore : IViewStore, IQueryRowStore { private static readonly string Tag = typeof(ForestDBViewStore).Name; internal const string VIEW_INDEX_PATH_EXTENSION = "viewindex"; private ForestDBCouchStore _dbStorage; private string _path; #if CONNECTION_PER_THREAD private ConcurrentDictionary<int, IntPtr> _fdbConnections = new ConcurrentDictionary<int, IntPtr>(); #endif public IViewStoreDelegate Delegate { get; set; } public string Name { get; private set; } private C4View* IndexDB { get { #if CONNECTION_PER_THREAD return (C4View*)_fdbConnections.GetOrAdd(Thread.CurrentThread.ManagedThreadId, x => new IntPtr(OpenIndex())).ToPointer(); #else if(_indexDB == null) { _indexDB = OpenIndex(); } return _indexDB; #endif } } #if !CONNECTION_PER_THREAD private C4View* _indexDB; #endif public int TotalRows { get { try { return (int)Native.c4view_getTotalRows(IndexDB); } catch(Exception e) { Log.To.Database.W(Tag, "Exception opening index while getting total rows, returning 0", e); return 0; } } } public long LastSequenceChangedAt { get { try { return (long)Native.c4view_getLastSequenceChangedAt(IndexDB); } catch(Exception e) { Log.To.Database.W(Tag, "Exception opening index while getting last sequence changed at, returning 0", e); return 0; } } } public long LastSequenceIndexed { get { try { Log.To.Query.D (Tag, "Last sequence indexed for {0} is {1}", Name, Native.c4view_getLastSequenceIndexed (IndexDB)); return (long)Native.c4view_getLastSequenceIndexed(IndexDB); } catch(Exception e) { Log.To.Database.W(Tag, "Exception opening index while getting last sequence indexed, returning 0", e); return 0; } } } public ForestDBViewStore(ForestDBCouchStore dbStorage, string name, bool create) { Debug.Assert(dbStorage != null); Debug.Assert(name != null); _dbStorage = dbStorage; Name = name; var filename = ViewNameToFilename(name); _path = Path.Combine(_dbStorage.Directory, filename); var files = System.IO.Directory.GetFiles(_dbStorage.Directory, filename + "*"); if(files.Length == 0) { if(!create) { // This is normal operation, so make an exception for logging at error level Log.To.View.V(Tag, "create is false but no db file exists at {0}", _path); throw new InvalidOperationException(String.Format( "Create is false but no db file exists at {0}", _path)); } OpenIndexWithOptions(C4DatabaseFlags.Create, true); } } public static void WithC4Keys(object[] keySources, bool writeNull, C4KeyActionDelegate action) { if(keySources == null) { action(null); return; } var c4Keys = new C4Key*[keySources.Length]; for(int i = 0; i < keySources.Length; i++) { if(keySources[i] == null && !writeNull) { c4Keys[i] = null; } else { c4Keys[i] = CouchbaseBridge.SerializeToKey(keySources[i]); } } try { action(c4Keys); } finally { foreach(C4Key* key in c4Keys) { Native.c4key_free(key); } } } public AtomicAction ActionToChangeEncryptionKey(SymmetricKey newKey) { return new AtomicAction(() => { ForestDBBridge.Check(err => { var newc4key = default(C4EncryptionKey); if(newKey != null) { newc4key = new C4EncryptionKey(newKey.KeyData); } return Native.c4view_rekey(IndexDB, &newc4key, err); }); CloseIndex(); }, null, null); } internal static string FileNameToViewName(string filename) { if(!filename.Contains(VIEW_INDEX_PATH_EXTENSION)) { return null; } var parts = filename.Split('.'); return UnescapeString(parts[0]); } private void CloseIndex() { #if CONNECTION_PER_THREAD var connections = _fdbConnections.Values.ToArray(); _fdbConnections.Clear(); foreach (var connection in connections) { ForestDBBridge.Check(err => Native.c4view_close((C4View*)connection.ToPointer(), err)); Native.c4view_free((C4View*)connection.ToPointer()); } #else var indexDb = _indexDB; _indexDB = null; ForestDBBridge.Check(err => Native.c4view_close(indexDb, err)); Native.c4view_free(indexDb); #endif } private C4View* OpenIndexWithOptions(C4DatabaseFlags options, bool dryRun = false) { var retVal = (C4View*)ForestDBBridge.Check(err => { var encryptionKey = default(C4EncryptionKey); if(_dbStorage.EncryptionKey != null) { encryptionKey = new C4EncryptionKey(_dbStorage.EncryptionKey.KeyData); } return Native.c4view_open(_dbStorage.Forest, _path, Name, dryRun ? "0" : Delegate.MapVersion, options, &encryptionKey, err); }); if(dryRun) { ForestDBBridge.Check(err => Native.c4view_close(retVal, err)); Native.c4view_free(retVal); } return retVal; } private C4View* OpenIndex() { return OpenIndexWithOptions((C4DatabaseFlags)0); } internal static string ViewNameToFilename(string viewName) { return Path.ChangeExtension(EscapeString(viewName), VIEW_INDEX_PATH_EXTENSION); } private static bool IsLegalChar(byte c) { // POSIX legal characters return (c > 47 && c < 58) || (c > 64 && c < 91) || (c > 96 && c < 123) || c == 45 || c == 46 || c == 95 || c > 127; } private unsafe static string EscapeString(string unescaped) { var sb = new StringBuilder(); var length = 0; var buffer = new byte[6]; fixed (byte* bufPtr = buffer) fixed (char* ptr = unescaped) { var currentCharPtr = ptr; while(length < unescaped.Length) { var numBytes = Encoding.UTF8.GetBytes(currentCharPtr, 1, bufPtr, 6); if(IsLegalChar(buffer[0])) { sb.Append(*currentCharPtr); } else { sb.AppendFormat("@{0}", Misc.ConvertToHex(buffer, numBytes)); } currentCharPtr++; length++; } } return sb.ToString(); } private static string UnescapeString(string escaped) { var sb = new StringBuilder(); var buffer = new char[2]; var charCounter = 0; foreach(var c in escaped) { if(c == '@') { charCounter = 1; continue; } else if(charCounter > 0) { buffer[charCounter - 1] = c; if(charCounter == 2) { sb.Append((char)Convert.ToByte(new string(buffer), 16)); charCounter = 0; } else { charCounter++; } } else { sb.Append(c); } } return sb.ToString(); } private static string ViewNames(IEnumerable<IViewStore> inputViews) { var names = inputViews.Select(x => x.Name); return String.Join(", ", names.ToStringArray()); } private CBForestQueryEnumerator QueryEnumeratorWithOptions(QueryOptions options) { var enumerator = default(C4QueryEnumerator*); var startKey = options.StartKey; var endKey = options.EndKey; if(options.Descending) { startKey = Misc.KeyForPrefixMatch(startKey, options.PrefixMatchLevel); } else { endKey = Misc.KeyForPrefixMatch(options.EndKey, options.PrefixMatchLevel); } using(var startkeydocid_ = new C4String(options.StartKeyDocId)) using(var endkeydocid_ = new C4String(options.EndKeyDocId)) { WithC4Keys(new object[] { startKey, endKey }, false, startEndKey => WithC4Keys(options.Keys == null ? null : options.Keys.ToArray(), true, c4keys => { var opts = C4QueryOptions.DEFAULT; opts.descending = options.Descending; opts.endKey = startEndKey[1]; opts.endKeyDocID = endkeydocid_.AsC4Slice(); opts.inclusiveEnd = options.InclusiveEnd; opts.inclusiveStart = options.InclusiveStart; if(c4keys != null) { opts.keysCount = (uint)c4keys.Length; } if(!options.Reduce) { opts.limit = (ulong)options.Limit; opts.skip = (ulong)options.Skip; } opts.startKey = startEndKey[0]; opts.startKeyDocID = startkeydocid_.AsC4Slice(); fixed (C4Key** keysPtr = c4keys) { opts.keys = keysPtr; enumerator = (C4QueryEnumerator*)ForestDBBridge.Check(err => { var localOpts = opts; return Native.c4view_query(IndexDB, &localOpts, err); }); } }) ); } return new CBForestQueryEnumerator(enumerator); } #if PARSED_KEYS private static bool GroupTogether(object lastKey, object key, int groupLevel) { if(groupLevel == 0) { return !((lastKey == null) || (key == null)) && lastKey.Equals(key); } var lastArr = lastKey as IList; var arr = key as IList; if(lastArr == null || arr == null) { return groupLevel == 1 && (!((lastKey == null) || (key == null)) && lastKey.Equals(key)); } var level = Math.Min(groupLevel, Math.Min(lastArr.Count, arr.Count)); for(int i = 0; i < level; i++) { if(!lastArr[i].Equals(arr[i])) { return false; } } return true; } private static object GroupKey(object key, int groupLevel) { var arr = key.AsList<object>(); if(groupLevel > 0 && arr != null && arr.Count > groupLevel) { return new Couchbase.Lite.Util.ArraySegment<object>(arr.ToArray(), 0, groupLevel); } return key; } #endif private static object CallReduce(ReduceDelegate reduce, IList<object> keys, IList<object> vals) { if(reduce == null) { return null; } #if PARSED_KEYS var lazyKeys = keys; #else var lazyKeys = new LazyJsonArray(keys); #endif var lazyValues = new LazyJsonArray(vals); try { var result = reduce(lazyKeys, lazyValues, false); if(result != null) { return result; } } catch(Exception e) { Log.To.Query.W(Tag, "Exception in reduce block, returning null", e); } return null; } private QueryRow CreateReducedRow(object key, bool group, int groupLevel, ReduceDelegate reduce, Func<QueryRow, bool> filter, IList<object> keysToReduce, IList<object> valsToReduce) { try { var row = new QueryRow(null, 0, group ? GroupKey(key, groupLevel) : null, CallReduce(reduce, keysToReduce, valsToReduce), null, this); if(filter != null && filter(row)) { row = null; } return row; } catch(CouchbaseLiteException) { Log.To.Query.E(Tag, "Failed to run reduce query for {0}, rethrowing...", Name); throw; } catch(Exception e) { throw Misc.CreateExceptionAndLog(Log.To.Query, e, Tag, "Exception while running reduce query for {0}", Name); } } public void Close() { CloseIndex(); _dbStorage.ForgetViewStorage(Name); } public void DeleteIndex() { ForestDBBridge.Check(err => Native.c4view_eraseIndex(IndexDB, err)); } public void DeleteView() { _dbStorage.ForgetViewStorage(Name); #if CONNECTION_PER_THREAD var connections = _fdbConnections.Values.ToArray (); var current = IndexDB; _fdbConnections.Clear (); foreach (var connection in connections) { if (connection.ToPointer() != current) { ForestDBBridge.Check (err => Native.c4view_close ((C4View*)connection.ToPointer (), err)); Native.c4view_free ((C4View*)connection.ToPointer ()); } } ForestDBBridge.Check (err => Native.c4view_delete (current, err)); Native.c4view_free(current); #else ForestDBBridge.Check(err => Native.c4view_delete(IndexDB, err)); #endif } public bool SetVersion(string version) { return true; } public bool UpdateIndexes(IEnumerable<IViewStore> views) { Log.To.Query.V(Tag, "Checking indexes of ({0}) for {1}", ViewNames(views), Name); // Creates an array of tuples -> [[view1, view1 last sequence, view1 native handle], // [view2, view2 last sequence, view2 native handle], ...] var viewsArray = views.Where (x => { var viewDelegate = x.Delegate; if (viewDelegate == null || viewDelegate.Map == null) { Log.To.Query.V (Tag, " {0} has no map block; skipping it", x.Name); return false; } return true; }).Cast<ForestDBViewStore> ().ToArray (); var nativeViews = new C4View*[viewsArray.Length]; for(int i = 0; i < viewsArray.Length; i++) { nativeViews[i] = viewsArray[i].IndexDB; } var indexer = (C4Indexer*)ForestDBBridge.Check(err => Native.c4indexer_begin(_dbStorage.Forest, nativeViews, err)); var enumerator = new CBForestDocEnumerator(indexer); var commit = false; try { var lastSequenceIndexed = viewsArray.Select (x => x.LastSequenceIndexed).ToArray (); foreach(var next in enumerator) { var seq = next.Sequence; for(int i = 0; i < viewsArray.Length; i++) { var info = viewsArray [i]; if (seq <= lastSequenceIndexed[i]) { continue; // This view has already indexed this sequence } var rev = new ForestRevisionInternal(next, true); var keys = new List<object>(); var values = new List<string>(); var conflicts = default(List<string>); foreach(var leaf in new CBForestHistoryEnumerator(_dbStorage.Forest, next.Sequence, true)) { if(leaf.SelectedRev.revID.Equals(leaf.CurrentRevID)) { continue; } if(leaf.IsDeleted) { break; } if(conflicts == null) { conflicts = new List<string>(); } conflicts.Add((string)leaf.SelectedRev.revID); } if(conflicts != null) { rev.SetPropertyForKey("_conflicts", conflicts); } try { var props = rev.GetProperties(); info.Delegate.Map(props, (key, value) => { if(key == null) { Log.To.Query.W(Tag, "Emit function called with a null key; ignoring"); return; } keys.Add(key); if(props == value) { values.Add("*"); } else { values.Add(Manager.GetObjectMapper().WriteValueAsString(value)); } }); } catch(Exception e) { Log.To.Query.W(Tag, String.Format("Exception thrown in map function of {0}, continuing", info.Name), e); continue; } WithC4Keys(keys.ToArray(), true, c4keys => ForestDBBridge.Check(err => Native.c4indexer_emit(indexer, next.GetDocument(), (uint)i, c4keys, values.ToArray(), err)) ); } } commit = true; } catch(Exception e) { Log.To.Query.W(Tag, "Error updates indexes, returning false", e); return false; } finally { ForestDBBridge.Check(err => Native.c4indexer_end(indexer, commit, err)); } return true; } public UpdateJob CreateUpdateJob(IEnumerable<IViewStore> viewsToUpdate) { var cast = viewsToUpdate.Cast<ForestDBViewStore>(); return new UpdateJob(UpdateIndexes, viewsToUpdate, from store in cast select store._dbStorage.LastSequence); } public IEnumerable<QueryRow> RegularQuery(QueryOptions options) { var optionsCopy = options.Copy(); // Needed because Count() and ElementAt() will share this var filter = optionsCopy.Filter; var limit = Int32.MaxValue; var skip = 0; if(filter != null) { // If a filter is present, these need to be applied to the filter // and not the query limit = optionsCopy.Limit; skip = optionsCopy.Skip; optionsCopy.Limit = Int32.MaxValue; optionsCopy.Skip = 0; } var enumerator = QueryEnumeratorWithOptions(optionsCopy); foreach(var next in enumerator) { var key = CouchbaseBridge.DeserializeKey<object>(next.Key); var value = (next.Value as IEnumerable<byte>).ToArray(); var docRevision = default(RevisionInternal); if(value.Length == 1 && value[0] == 42) { docRevision = _dbStorage.GetDocument(next.DocID, null, true); } else { docRevision = _dbStorage.GetDocument(next.DocID, null, optionsCopy.IncludeDocs); } var row = new QueryRow(next.DocID, next.DocSequence, key, value, docRevision, this); if(filter != null) { if(!filter(row)) { continue; } if(skip > 0) { skip--; continue; } if(limit-- == 0) { yield break; } } Log.To.Query.V(Tag, "Query {0} found row with key={1}, value={2}, id={3}", Name, new SecureLogJsonString(key, LogMessageSensitivity.PotentiallyInsecure), new SecureLogString(value, LogMessageSensitivity.PotentiallyInsecure), new SecureLogString(next.DocID, LogMessageSensitivity.PotentiallyInsecure)); yield return row; } } public IEnumerable<QueryRow> ReducedQuery(QueryOptions options) { var groupLevel = options.GroupLevel; var group = options.Group || groupLevel > 0; var reduce = Delegate == null ? null : Delegate.Reduce; if(options.ReduceSpecified) { if(!options.Reduce) { reduce = null; } else if(reduce == null) { throw Misc.CreateExceptionAndLog(Log.To.Query, StatusCode.BadParam, Tag, "Cannot use reduce option in view {0} which has no reduce block defined", Name); } } var lastKey = default(object); var filter = options.Filter; var keysToReduce = default(IList<object>); var valsToReduce = default(IList<object>); if(reduce != null) { keysToReduce = new List<object>(100); valsToReduce = new List<object>(100); } var enumerator = QueryEnumeratorWithOptions(options); var row = default(QueryRow); var returnedCount = 0; var skippedCount = 0; foreach(var next in enumerator) { if(returnedCount >= options.Limit) { yield break; } var key = CouchbaseBridge.DeserializeKey<object>(next.Key); var value = default(object); if(lastKey != null && (key == null || (group && !GroupTogether(lastKey, key, groupLevel)))) { // key doesn't match lastKey; emit a grouped/reduced row for what came before: row = CreateReducedRow(lastKey, group, groupLevel, reduce, filter, keysToReduce, valsToReduce); if(row != null && skippedCount++ >= options.Skip) { var rowCopy = row; Log.To.Query.V(Tag, "Query {0} reduced row with key={1} value={2}", Name, new SecureLogJsonString(key, LogMessageSensitivity.PotentiallyInsecure), new SecureLogJsonString(value, LogMessageSensitivity.PotentiallyInsecure)); row = null; returnedCount++; yield return rowCopy; } keysToReduce.Clear(); valsToReduce.Clear(); } if(key != null && reduce != null) { // Add this key/value to the list to be reduced: keysToReduce.Add(key); var nextVal = next.Value; if(nextVal.size == 1 && nextVal.ElementAt(0) == (byte)'*') { try { var rev = _dbStorage.GetDocument(next.DocID, next.DocSequence); value = rev.GetProperties(); } catch(CouchbaseLiteException e) { Log.To.Query.W(Tag, "Couldn't load doc for row value: status {0}", e.CBLStatus.Code); } catch(Exception e) { Log.To.Query.W(Tag, "Couldn't load doc for row value", e); } } else { value = Manager.GetObjectMapper().ReadValue<object>(next.Value); } valsToReduce.Add(value); } lastKey = key; } if(returnedCount >= options.Limit) { yield break; } row = CreateReducedRow(lastKey, group, groupLevel, reduce, filter, keysToReduce, valsToReduce); if(row != null) { yield return row; } } public IQueryRowStore StorageForQueryRow(QueryRow row) { return this; } public IEnumerable<IDictionary<string, object>> Dump() { var enumerator = QueryEnumeratorWithOptions(new QueryOptions()); foreach(var next in enumerator) { yield return new Dictionary<string, object> { { "seq", next.DocSequence }, { "key", next.KeyJSON }, { "val", next.ValueJSON } }; } } public bool RowValueIsEntireDoc(object valueData) { var valueString = valueData as IEnumerable<byte>; if(valueString == null) { return false; } bool first = true; foreach(var character in valueString) { if(!first) { return false; } if(character != (byte)'*') { return false; } first = false; } return true; } public T ParseRowValue<T>(IEnumerable<byte> valueData) { return Manager.GetObjectMapper().ReadValue<T>(valueData); } public IDictionary<string, object> DocumentProperties(string docId, long sequenceNumber) { return _dbStorage.GetDocument(docId, sequenceNumber).GetProperties(); } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using Microsoft.Build.Framework; namespace GodotSharpTools.Build { public class BuildInstance : IDisposable { [MethodImpl(MethodImplOptions.InternalCall)] private extern static void godot_icall_BuildInstance_ExitCallback(string solution, string config, int exitCode); [MethodImpl(MethodImplOptions.InternalCall)] private extern static string godot_icall_BuildInstance_get_MSBuildPath(); [MethodImpl(MethodImplOptions.InternalCall)] private extern static string godot_icall_BuildInstance_get_FrameworkPath(); [MethodImpl(MethodImplOptions.InternalCall)] private extern static string godot_icall_BuildInstance_get_MonoWindowsBinDir(); [MethodImpl(MethodImplOptions.InternalCall)] private extern static bool godot_icall_BuildInstance_get_UsingMonoMSBuildOnWindows(); private static string GetMSBuildPath() { string msbuildPath = godot_icall_BuildInstance_get_MSBuildPath(); if (msbuildPath == null) throw new FileNotFoundException("Cannot find the MSBuild executable."); return msbuildPath; } private static string GetFrameworkPath() { return godot_icall_BuildInstance_get_FrameworkPath(); } private static string MonoWindowsBinDir { get { string monoWinBinDir = godot_icall_BuildInstance_get_MonoWindowsBinDir(); if (monoWinBinDir == null) throw new FileNotFoundException("Cannot find the Windows Mono binaries directory."); return monoWinBinDir; } } private static bool UsingMonoMSBuildOnWindows { get { return godot_icall_BuildInstance_get_UsingMonoMSBuildOnWindows(); } } private string solution; private string config; private Process process; private int exitCode; public int ExitCode { get { return exitCode; } } public bool IsRunning { get { return process != null && !process.HasExited; } } public BuildInstance(string solution, string config) { this.solution = solution; this.config = config; } public bool Build(string loggerAssemblyPath, string loggerOutputDir, string[] customProperties = null) { bool debugMSBuild = IsDebugMSBuildRequested(); List<string> customPropertiesList = new List<string>(); if (customProperties != null) customPropertiesList.AddRange(customProperties); string frameworkPath = GetFrameworkPath(); if (!string.IsNullOrEmpty(frameworkPath)) customPropertiesList.Add("FrameworkPathOverride=" + frameworkPath); string compilerArgs = BuildArguments(loggerAssemblyPath, loggerOutputDir, customPropertiesList); ProcessStartInfo startInfo = new ProcessStartInfo(GetMSBuildPath(), compilerArgs); bool redirectOutput = !debugMSBuild; startInfo.RedirectStandardOutput = redirectOutput; startInfo.RedirectStandardError = redirectOutput; startInfo.UseShellExecute = false; if (UsingMonoMSBuildOnWindows) { // These environment variables are required for Mono's MSBuild to find the compilers. // We use the batch files in Mono's bin directory to make sure the compilers are executed with mono. string monoWinBinDir = MonoWindowsBinDir; startInfo.EnvironmentVariables.Add("CscToolExe", Path.Combine(monoWinBinDir, "csc.bat")); startInfo.EnvironmentVariables.Add("VbcToolExe", Path.Combine(monoWinBinDir, "vbc.bat")); startInfo.EnvironmentVariables.Add("FscToolExe", Path.Combine(monoWinBinDir, "fsharpc.bat")); } // Needed when running from Developer Command Prompt for VS RemovePlatformVariable(startInfo.EnvironmentVariables); using (Process process = new Process()) { process.StartInfo = startInfo; process.Start(); if (redirectOutput) { process.BeginOutputReadLine(); process.BeginErrorReadLine(); } process.WaitForExit(); exitCode = process.ExitCode; } return true; } public bool BuildAsync(string loggerAssemblyPath, string loggerOutputDir, string[] customProperties = null) { bool debugMSBuild = IsDebugMSBuildRequested(); if (process != null) throw new InvalidOperationException("Already in use"); List<string> customPropertiesList = new List<string>(); if (customProperties != null) customPropertiesList.AddRange(customProperties); string frameworkPath = GetFrameworkPath(); if (!string.IsNullOrEmpty(frameworkPath)) customPropertiesList.Add("FrameworkPathOverride=" + frameworkPath); string compilerArgs = BuildArguments(loggerAssemblyPath, loggerOutputDir, customPropertiesList); ProcessStartInfo startInfo = new ProcessStartInfo(GetMSBuildPath(), compilerArgs); bool redirectOutput = !debugMSBuild; startInfo.RedirectStandardOutput = redirectOutput; startInfo.RedirectStandardError = redirectOutput; startInfo.UseShellExecute = false; if (UsingMonoMSBuildOnWindows) { // These environment variables are required for Mono's MSBuild to find the compilers. // We use the batch files in Mono's bin directory to make sure the compilers are executed with mono. string monoWinBinDir = MonoWindowsBinDir; startInfo.EnvironmentVariables.Add("CscToolExe", Path.Combine(monoWinBinDir, "csc.bat")); startInfo.EnvironmentVariables.Add("VbcToolExe", Path.Combine(monoWinBinDir, "vbc.bat")); startInfo.EnvironmentVariables.Add("FscToolExe", Path.Combine(monoWinBinDir, "fsharpc.bat")); } // Needed when running from Developer Command Prompt for VS RemovePlatformVariable(startInfo.EnvironmentVariables); process = new Process(); process.StartInfo = startInfo; process.EnableRaisingEvents = true; process.Exited += new EventHandler(BuildProcess_Exited); process.Start(); if (redirectOutput) { process.BeginOutputReadLine(); process.BeginErrorReadLine(); } return true; } private string BuildArguments(string loggerAssemblyPath, string loggerOutputDir, List<string> customProperties) { string arguments = string.Format(@"""{0}"" /v:normal /t:Build ""/p:{1}"" ""/l:{2},{3};{4}""", solution, "Configuration=" + config, typeof(GodotBuildLogger).FullName, loggerAssemblyPath, loggerOutputDir ); foreach (string customProperty in customProperties) { arguments += " \"/p:" + customProperty + "\""; } return arguments; } private void RemovePlatformVariable(StringDictionary environmentVariables) { // EnvironmentVariables is case sensitive? Seriously? List<string> platformEnvironmentVariables = new List<string>(); foreach (string env in environmentVariables.Keys) { if (env.ToUpper() == "PLATFORM") platformEnvironmentVariables.Add(env); } foreach (string env in platformEnvironmentVariables) environmentVariables.Remove(env); } private void BuildProcess_Exited(object sender, System.EventArgs e) { exitCode = process.ExitCode; godot_icall_BuildInstance_ExitCallback(solution, config, exitCode); Dispose(); } private static bool IsDebugMSBuildRequested() { return Environment.GetEnvironmentVariable("GODOT_DEBUG_MSBUILD")?.Trim() == "1"; } public void Dispose() { if (process != null) { process.Dispose(); process = null; } } } public class GodotBuildLogger : ILogger { public string Parameters { get; set; } public LoggerVerbosity Verbosity { get; set; } public void Initialize(IEventSource eventSource) { if (null == Parameters) throw new LoggerException("Log directory was not set."); string[] parameters = Parameters.Split(';'); string logDir = parameters[0]; if (String.IsNullOrEmpty(logDir)) throw new LoggerException("Log directory was not set."); if (parameters.Length > 1) throw new LoggerException("Too many parameters passed."); string logFile = Path.Combine(logDir, "msbuild_log.txt"); string issuesFile = Path.Combine(logDir, "msbuild_issues.csv"); try { if (!Directory.Exists(logDir)) Directory.CreateDirectory(logDir); this.logStreamWriter = new StreamWriter(logFile); this.issuesStreamWriter = new StreamWriter(issuesFile); } catch (Exception ex) { if ( ex is UnauthorizedAccessException || ex is ArgumentNullException || ex is PathTooLongException || ex is DirectoryNotFoundException || ex is NotSupportedException || ex is ArgumentException || ex is SecurityException || ex is IOException ) { throw new LoggerException("Failed to create log file: " + ex.Message); } else { // Unexpected failure throw; } } eventSource.ProjectStarted += new ProjectStartedEventHandler(eventSource_ProjectStarted); eventSource.TaskStarted += new TaskStartedEventHandler(eventSource_TaskStarted); eventSource.MessageRaised += new BuildMessageEventHandler(eventSource_MessageRaised); eventSource.WarningRaised += new BuildWarningEventHandler(eventSource_WarningRaised); eventSource.ErrorRaised += new BuildErrorEventHandler(eventSource_ErrorRaised); eventSource.ProjectFinished += new ProjectFinishedEventHandler(eventSource_ProjectFinished); } void eventSource_ErrorRaised(object sender, BuildErrorEventArgs e) { string line = String.Format("{0}({1},{2}): error {3}: {4}", e.File, e.LineNumber, e.ColumnNumber, e.Code, e.Message); if (e.ProjectFile.Length > 0) line += string.Format(" [{0}]", e.ProjectFile); WriteLine(line); string errorLine = String.Format(@"error,{0},{1},{2},{3},{4},{5}", e.File.CsvEscape(), e.LineNumber, e.ColumnNumber, e.Code.CsvEscape(), e.Message.CsvEscape(), e.ProjectFile.CsvEscape()); issuesStreamWriter.WriteLine(errorLine); } void eventSource_WarningRaised(object sender, BuildWarningEventArgs e) { string line = String.Format("{0}({1},{2}): warning {3}: {4}", e.File, e.LineNumber, e.ColumnNumber, e.Code, e.Message, e.ProjectFile); if (e.ProjectFile != null && e.ProjectFile.Length > 0) line += string.Format(" [{0}]", e.ProjectFile); WriteLine(line); string warningLine = String.Format(@"warning,{0},{1},{2},{3},{4},{5}", e.File.CsvEscape(), e.LineNumber, e.ColumnNumber, e.Code.CsvEscape(), e.Message.CsvEscape(), e.ProjectFile != null ? e.ProjectFile.CsvEscape() : string.Empty); issuesStreamWriter.WriteLine(warningLine); } void eventSource_MessageRaised(object sender, BuildMessageEventArgs e) { // BuildMessageEventArgs adds Importance to BuildEventArgs // Let's take account of the verbosity setting we've been passed in deciding whether to log the message if ((e.Importance == MessageImportance.High && IsVerbosityAtLeast(LoggerVerbosity.Minimal)) || (e.Importance == MessageImportance.Normal && IsVerbosityAtLeast(LoggerVerbosity.Normal)) || (e.Importance == MessageImportance.Low && IsVerbosityAtLeast(LoggerVerbosity.Detailed)) ) { WriteLineWithSenderAndMessage(String.Empty, e); } } void eventSource_TaskStarted(object sender, TaskStartedEventArgs e) { // TaskStartedEventArgs adds ProjectFile, TaskFile, TaskName // To keep this log clean, this logger will ignore these events. } void eventSource_ProjectStarted(object sender, ProjectStartedEventArgs e) { WriteLine(e.Message); indent++; } void eventSource_ProjectFinished(object sender, ProjectFinishedEventArgs e) { indent--; WriteLine(e.Message); } /// <summary> /// Write a line to the log, adding the SenderName /// </summary> private void WriteLineWithSender(string line, BuildEventArgs e) { if (0 == String.Compare(e.SenderName, "MSBuild", true /*ignore case*/)) { // Well, if the sender name is MSBuild, let's leave it out for prettiness WriteLine(line); } else { WriteLine(e.SenderName + ": " + line); } } /// <summary> /// Write a line to the log, adding the SenderName and Message /// (these parameters are on all MSBuild event argument objects) /// </summary> private void WriteLineWithSenderAndMessage(string line, BuildEventArgs e) { if (0 == String.Compare(e.SenderName, "MSBuild", true /*ignore case*/)) { // Well, if the sender name is MSBuild, let's leave it out for prettiness WriteLine(line + e.Message); } else { WriteLine(e.SenderName + ": " + line + e.Message); } } private void WriteLine(string line) { for (int i = indent; i > 0; i--) { logStreamWriter.Write("\t"); } logStreamWriter.WriteLine(line); } public void Shutdown() { logStreamWriter.Close(); issuesStreamWriter.Close(); } public bool IsVerbosityAtLeast(LoggerVerbosity checkVerbosity) { return this.Verbosity >= checkVerbosity; } private StreamWriter logStreamWriter; private StreamWriter issuesStreamWriter; private int indent; } }
// 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.Win32.SafeHandles; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Security.Claims; using System.Text; using System.Threading; using KERB_LOGON_SUBMIT_TYPE = Interop.SspiCli.KERB_LOGON_SUBMIT_TYPE; using KERB_S4U_LOGON = Interop.SspiCli.KERB_S4U_LOGON; using KerbS4uLogonFlags = Interop.SspiCli.KerbS4uLogonFlags; using LUID = Interop.LUID; using LSA_STRING = Interop.SspiCli.LSA_STRING; using QUOTA_LIMITS = Interop.SspiCli.QUOTA_LIMITS; using SECURITY_LOGON_TYPE = Interop.SspiCli.SECURITY_LOGON_TYPE; using TOKEN_SOURCE = Interop.SspiCli.TOKEN_SOURCE; using System.Runtime.Serialization; namespace System.Security.Principal { public class WindowsIdentity : ClaimsIdentity, IDisposable, ISerializable, IDeserializationCallback { private string _name = null; private SecurityIdentifier _owner = null; private SecurityIdentifier _user = null; private IdentityReferenceCollection _groups = null; private SafeAccessTokenHandle _safeTokenHandle = SafeAccessTokenHandle.InvalidHandle; private string _authType = null; private int _isAuthenticated = -1; private volatile TokenImpersonationLevel _impersonationLevel; private volatile bool _impersonationLevelInitialized; public new const string DefaultIssuer = @"AD AUTHORITY"; private string _issuerName = DefaultIssuer; private object _claimsIntiailizedLock = new object(); private volatile bool _claimsInitialized; private List<Claim> _deviceClaims; private List<Claim> _userClaims; // // Constructors. // private WindowsIdentity() : base(null, null, null, ClaimTypes.Name, ClaimTypes.GroupSid) { } /// <summary> /// Initializes a new instance of the WindowsIdentity class for the user represented by the specified User Principal Name (UPN). /// </summary> /// <remarks> /// Unlike the desktop version, we connect to Lsa only as an untrusted caller. We do not attempt to explot Tcb privilege or adjust the current /// thread privilege to include Tcb. /// </remarks> public WindowsIdentity(string sUserPrincipalName) : base(null, null, null, ClaimTypes.Name, ClaimTypes.GroupSid) { // Desktop compat: See comments below for why we don't validate sUserPrincipalName. using (SafeLsaHandle lsaHandle = ConnectToLsa()) { int packageId = LookupAuthenticationPackage(lsaHandle, Interop.SspiCli.AuthenticationPackageNames.MICROSOFT_KERBEROS_NAME_A); // 8 byte or less name that indicates the source of the access token. This choice of name is visible to callers through the native GetTokenInformation() api // so we'll use the same name the CLR used even though we're not actually the "CLR." byte[] sourceName = { (byte)'C', (byte)'L', (byte)'R', (byte)0 }; TOKEN_SOURCE sourceContext; if (!Interop.Advapi32.AllocateLocallyUniqueId(out sourceContext.SourceIdentifier)) throw new SecurityException(new Win32Exception().Message); sourceContext.SourceName = new byte[TOKEN_SOURCE.TOKEN_SOURCE_LENGTH]; Buffer.BlockCopy(sourceName, 0, sourceContext.SourceName, 0, sourceName.Length); // Desktop compat: Desktop never null-checks sUserPrincipalName. Actual behavior is that the null makes it down to Encoding.Unicode.GetBytes() which then throws // the ArgumentNullException (provided that the prior LSA calls didn't fail first.) To make this compat decision explicit, we'll null check ourselves // and simulate the exception from Encoding.Unicode.GetBytes(). if (sUserPrincipalName == null) throw new ArgumentNullException("s"); byte[] upnBytes = Encoding.Unicode.GetBytes(sUserPrincipalName); if (upnBytes.Length > ushort.MaxValue) { // Desktop compat: LSA only allocates 16 bits to hold the UPN size. We should throw an exception here but unfortunately, the desktop did an unchecked cast to ushort, // effectively truncating upnBytes to the first (N % 64K) bytes. We'll simulate the same behavior here (albeit in a way that makes it look less accidental.) Array.Resize(ref upnBytes, upnBytes.Length & ushort.MaxValue); } unsafe { // // Build the KERB_S4U_LOGON structure. Note that the LSA expects this entire // structure to be contained within the same block of memory, so we need to allocate // enough room for both the structure itself and the UPN string in a single buffer // and do the marshalling into this buffer by hand. // int authenticationInfoLength = checked(sizeof(KERB_S4U_LOGON) + upnBytes.Length); using (SafeLocalAllocHandle authenticationInfo = Interop.Kernel32.LocalAlloc(0, new UIntPtr(checked((uint)authenticationInfoLength)))) { if (authenticationInfo.IsInvalid) throw new OutOfMemoryException(); KERB_S4U_LOGON* pKerbS4uLogin = (KERB_S4U_LOGON*)(authenticationInfo.DangerousGetHandle()); pKerbS4uLogin->MessageType = KERB_LOGON_SUBMIT_TYPE.KerbS4ULogon; pKerbS4uLogin->Flags = KerbS4uLogonFlags.None; pKerbS4uLogin->ClientUpn.Length = pKerbS4uLogin->ClientUpn.MaximumLength = checked((ushort)upnBytes.Length); IntPtr pUpnOffset = (IntPtr)(pKerbS4uLogin + 1); pKerbS4uLogin->ClientUpn.Buffer = pUpnOffset; Marshal.Copy(upnBytes, 0, pKerbS4uLogin->ClientUpn.Buffer, upnBytes.Length); pKerbS4uLogin->ClientRealm.Length = pKerbS4uLogin->ClientRealm.MaximumLength = 0; pKerbS4uLogin->ClientRealm.Buffer = IntPtr.Zero; ushort sourceNameLength = checked((ushort)(sourceName.Length)); using (SafeLocalAllocHandle sourceNameBuffer = Interop.Kernel32.LocalAlloc(0, new UIntPtr(sourceNameLength))) { if (sourceNameBuffer.IsInvalid) throw new OutOfMemoryException(); Marshal.Copy(sourceName, 0, sourceNameBuffer.DangerousGetHandle(), sourceName.Length); LSA_STRING lsaOriginName = new LSA_STRING(sourceNameBuffer.DangerousGetHandle(), sourceNameLength); SafeLsaReturnBufferHandle profileBuffer; int profileBufferLength; LUID logonId; SafeAccessTokenHandle accessTokenHandle; QUOTA_LIMITS quota; int subStatus; int ntStatus = Interop.SspiCli.LsaLogonUser( lsaHandle, ref lsaOriginName, SECURITY_LOGON_TYPE.Network, packageId, authenticationInfo.DangerousGetHandle(), authenticationInfoLength, IntPtr.Zero, ref sourceContext, out profileBuffer, out profileBufferLength, out logonId, out accessTokenHandle, out quota, out subStatus); if (ntStatus == unchecked((int)Interop.StatusOptions.STATUS_ACCOUNT_RESTRICTION) && subStatus < 0) ntStatus = subStatus; if (ntStatus < 0) // non-negative numbers indicate success throw GetExceptionFromNtStatus(ntStatus); if (subStatus < 0) // non-negative numbers indicate success throw GetExceptionFromNtStatus(subStatus); if (profileBuffer != null) profileBuffer.Dispose(); _safeTokenHandle = accessTokenHandle; } } } } } private static SafeLsaHandle ConnectToLsa() { SafeLsaHandle lsaHandle; int ntStatus = Interop.SspiCli.LsaConnectUntrusted(out lsaHandle); if (ntStatus < 0) // non-negative numbers indicate success throw GetExceptionFromNtStatus(ntStatus); return lsaHandle; } private static int LookupAuthenticationPackage(SafeLsaHandle lsaHandle, string packageName) { Debug.Assert(!string.IsNullOrEmpty(packageName)); unsafe { int packageId; byte[] asciiPackageName = Encoding.ASCII.GetBytes(packageName); fixed (byte* pAsciiPackageName = &asciiPackageName[0]) { LSA_STRING lsaPackageName = new LSA_STRING((IntPtr)pAsciiPackageName, checked((ushort)(asciiPackageName.Length))); int ntStatus = Interop.SspiCli.LsaLookupAuthenticationPackage(lsaHandle, ref lsaPackageName, out packageId); if (ntStatus < 0) // non-negative numbers indicate success throw GetExceptionFromNtStatus(ntStatus); } return packageId; } } public WindowsIdentity(IntPtr userToken) : this(userToken, null, -1) { } public WindowsIdentity(IntPtr userToken, string type) : this(userToken, type, -1) { } private WindowsIdentity(IntPtr userToken, string authType, int isAuthenticated) : base(null, null, null, ClaimTypes.Name, ClaimTypes.GroupSid) { CreateFromToken(userToken); _authType = authType; _isAuthenticated = isAuthenticated; } private void CreateFromToken(IntPtr userToken) { if (userToken == IntPtr.Zero) throw new ArgumentException(SR.Argument_TokenZero); Contract.EndContractBlock(); // Find out if the specified token is a valid. uint dwLength = (uint)sizeof(uint); bool result = Interop.Advapi32.GetTokenInformation(userToken, (uint)TokenInformationClass.TokenType, SafeLocalAllocHandle.InvalidHandle, 0, out dwLength); if (Marshal.GetLastWin32Error() == Interop.Errors.ERROR_INVALID_HANDLE) throw new ArgumentException(SR.Argument_InvalidImpersonationToken); if (!Interop.Kernel32.DuplicateHandle(Interop.Kernel32.GetCurrentProcess(), userToken, Interop.Kernel32.GetCurrentProcess(), ref _safeTokenHandle, 0, true, Interop.DuplicateHandleOptions.DUPLICATE_SAME_ACCESS)) throw new SecurityException(new Win32Exception().Message); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2229", Justification = "Public API has already shipped.")] public WindowsIdentity(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } void IDeserializationCallback.OnDeserialization(object sender) { throw new PlatformNotSupportedException(); } // // Factory methods. // public static WindowsIdentity GetCurrent() { return GetCurrentInternal(TokenAccessLevels.MaximumAllowed, false); } public static WindowsIdentity GetCurrent(bool ifImpersonating) { return GetCurrentInternal(TokenAccessLevels.MaximumAllowed, ifImpersonating); } public static WindowsIdentity GetCurrent(TokenAccessLevels desiredAccess) { return GetCurrentInternal(desiredAccess, false); } // GetAnonymous() is used heavily in ASP.NET requests as a dummy identity to indicate // the request is anonymous. It does not represent a real process or thread token so // it cannot impersonate or do anything useful. Note this identity does not represent the // usual concept of an anonymous token, and the name is simply misleading but we cannot change it now. public static WindowsIdentity GetAnonymous() { return new WindowsIdentity(); } // // Properties. // // this is defined 'override sealed' for back compat. Il generated is 'virtual final' and this needs to be the same. public override sealed string AuthenticationType { get { // If this is an anonymous identity, return an empty string if (_safeTokenHandle.IsInvalid) return String.Empty; if (_authType == null) { Interop.LUID authId = GetLogonAuthId(_safeTokenHandle); if (authId.LowPart == Interop.LuidOptions.ANONYMOUS_LOGON_LUID) return String.Empty; // no authentication, just return an empty string SafeLsaReturnBufferHandle pLogonSessionData = SafeLsaReturnBufferHandle.InvalidHandle; try { int status = Interop.SspiCli.LsaGetLogonSessionData(ref authId, ref pLogonSessionData); if (status < 0) // non-negative numbers indicate success throw GetExceptionFromNtStatus(status); pLogonSessionData.Initialize((uint)Marshal.SizeOf<Interop.SECURITY_LOGON_SESSION_DATA>()); Interop.SECURITY_LOGON_SESSION_DATA logonSessionData = pLogonSessionData.Read<Interop.SECURITY_LOGON_SESSION_DATA>(0); return Marshal.PtrToStringUni(logonSessionData.AuthenticationPackage.Buffer); } finally { if (!pLogonSessionData.IsInvalid) pLogonSessionData.Dispose(); } } return _authType; } } public TokenImpersonationLevel ImpersonationLevel { get { // In case of a race condition here here, both threads will set m_impersonationLevel to the same value, // which is ok. if (!_impersonationLevelInitialized) { TokenImpersonationLevel impersonationLevel = TokenImpersonationLevel.None; // If this is an anonymous identity if (_safeTokenHandle.IsInvalid) { impersonationLevel = TokenImpersonationLevel.Anonymous; } else { TokenType tokenType = (TokenType)GetTokenInformation<int>(TokenInformationClass.TokenType); if (tokenType == TokenType.TokenPrimary) { impersonationLevel = TokenImpersonationLevel.None; // primary token; } else { /// This is an impersonation token, get the impersonation level int level = GetTokenInformation<int>(TokenInformationClass.TokenImpersonationLevel); impersonationLevel = (TokenImpersonationLevel)level + 1; } } _impersonationLevel = impersonationLevel; _impersonationLevelInitialized = true; } return _impersonationLevel; } } public override bool IsAuthenticated { get { if (_isAuthenticated == -1) { // This approach will not work correctly for domain guests (will return false // instead of true). This is a corner-case that is not very interesting. _isAuthenticated = CheckNtTokenForSid(new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[] { Interop.SecurityIdentifier.SECURITY_AUTHENTICATED_USER_RID })) ? 1 : 0; } return _isAuthenticated == 1; } } private bool CheckNtTokenForSid(SecurityIdentifier sid) { Contract.EndContractBlock(); // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return false; // CheckTokenMembership expects an impersonation token SafeAccessTokenHandle token = SafeAccessTokenHandle.InvalidHandle; TokenImpersonationLevel til = ImpersonationLevel; bool isMember = false; try { if (til == TokenImpersonationLevel.None) { if (!Interop.Advapi32.DuplicateTokenEx(_safeTokenHandle, (uint)TokenAccessLevels.Query, IntPtr.Zero, (uint)TokenImpersonationLevel.Identification, (uint)TokenType.TokenImpersonation, ref token)) throw new SecurityException(new Win32Exception().Message); } // CheckTokenMembership will check if the SID is both present and enabled in the access token. #if uap if (!Interop.Kernel32.CheckTokenMembershipEx((til != TokenImpersonationLevel.None ? _safeTokenHandle : token), sid.BinaryForm, Interop.Kernel32.CTMF_INCLUDE_APPCONTAINER, ref isMember)) throw new SecurityException(new Win32Exception().Message); #else if (!Interop.Advapi32.CheckTokenMembership((til != TokenImpersonationLevel.None ? _safeTokenHandle : token), sid.BinaryForm, ref isMember)) throw new SecurityException(new Win32Exception().Message); #endif } finally { if (token != SafeAccessTokenHandle.InvalidHandle) { token.Dispose(); } } return isMember; } // // IsGuest, IsSystem and IsAnonymous are maintained for compatibility reasons. It is always // possible to extract this same information from the User SID property and the new // (and more general) methods defined in the SID class (IsWellKnown, etc...). // public virtual bool IsGuest { get { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return false; return CheckNtTokenForSid(new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[] { Interop.SecurityIdentifier.SECURITY_BUILTIN_DOMAIN_RID, (int)WindowsBuiltInRole.Guest })); } } public virtual bool IsSystem { get { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return false; SecurityIdentifier sid = new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[] { Interop.SecurityIdentifier.SECURITY_LOCAL_SYSTEM_RID }); return (this.User == sid); } } public virtual bool IsAnonymous { get { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return true; SecurityIdentifier sid = new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[] { Interop.SecurityIdentifier.SECURITY_ANONYMOUS_LOGON_RID }); return (this.User == sid); } } public override string Name { get { return GetName(); } } internal String GetName() { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return String.Empty; if (_name == null) { // revert thread impersonation for the duration of the call to get the name. RunImpersonated(SafeAccessTokenHandle.InvalidHandle, delegate { NTAccount ntAccount = this.User.Translate(typeof(NTAccount)) as NTAccount; _name = ntAccount.ToString(); }); } return _name; } public SecurityIdentifier Owner { get { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return null; if (_owner == null) { using (SafeLocalAllocHandle tokenOwner = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenOwner)) { _owner = new SecurityIdentifier(tokenOwner.Read<IntPtr>(0), true); } } return _owner; } } public SecurityIdentifier User { get { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return null; if (_user == null) { using (SafeLocalAllocHandle tokenUser = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenUser)) { _user = new SecurityIdentifier(tokenUser.Read<IntPtr>(0), true); } } return _user; } } public IdentityReferenceCollection Groups { get { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return null; if (_groups == null) { IdentityReferenceCollection groups = new IdentityReferenceCollection(); using (SafeLocalAllocHandle pGroups = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenGroups)) { uint groupCount = pGroups.Read<uint>(0); Interop.TOKEN_GROUPS tokenGroups = pGroups.Read<Interop.TOKEN_GROUPS>(0); Interop.SID_AND_ATTRIBUTES[] groupDetails = new Interop.SID_AND_ATTRIBUTES[tokenGroups.GroupCount]; pGroups.ReadArray((uint)Marshal.OffsetOf<Interop.TOKEN_GROUPS>("Groups").ToInt32(), groupDetails, 0, groupDetails.Length); foreach (Interop.SID_AND_ATTRIBUTES group in groupDetails) { // Ignore disabled, logon ID, and deny-only groups. uint mask = Interop.SecurityGroups.SE_GROUP_ENABLED | Interop.SecurityGroups.SE_GROUP_LOGON_ID | Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY; if ((group.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_ENABLED) { groups.Add(new SecurityIdentifier(group.Sid, true)); } } } Interlocked.CompareExchange(ref _groups, groups, null); } return _groups; } } public SafeAccessTokenHandle AccessToken { get { return _safeTokenHandle; } } public virtual IntPtr Token { get { return _safeTokenHandle.DangerousGetHandle(); } } // // Public methods. // public static void RunImpersonated(SafeAccessTokenHandle safeAccessTokenHandle, Action action) { if (action == null) throw new ArgumentNullException(nameof(action)); RunImpersonatedInternal(safeAccessTokenHandle, action); } public static T RunImpersonated<T>(SafeAccessTokenHandle safeAccessTokenHandle, Func<T> func) { if (func == null) throw new ArgumentNullException(nameof(func)); T result = default(T); RunImpersonatedInternal(safeAccessTokenHandle, () => result = func()); return result; } protected virtual void Dispose(bool disposing) { if (disposing) { if (_safeTokenHandle != null && !_safeTokenHandle.IsClosed) _safeTokenHandle.Dispose(); } _name = null; _owner = null; _user = null; } public void Dispose() { Dispose(true); } // // internal. // private static AsyncLocal<SafeAccessTokenHandle> s_currentImpersonatedToken = new AsyncLocal<SafeAccessTokenHandle>(CurrentImpersonatedTokenChanged); private static void RunImpersonatedInternal(SafeAccessTokenHandle token, Action action) { bool isImpersonating; int hr; SafeAccessTokenHandle previousToken = GetCurrentToken(TokenAccessLevels.MaximumAllowed, false, out isImpersonating, out hr); if (previousToken == null || previousToken.IsInvalid) throw new SecurityException(new Win32Exception(hr).Message); s_currentImpersonatedToken.Value = isImpersonating ? previousToken : null; ExecutionContext currentContext = ExecutionContext.Capture(); // Run everything else inside of ExecutionContext.Run, so that any EC changes will be undone // on the way out. ExecutionContext.Run( currentContext, delegate { if (!Interop.Advapi32.RevertToSelf()) Environment.FailFast(new Win32Exception().Message); s_currentImpersonatedToken.Value = null; if (!token.IsInvalid && !Interop.Advapi32.ImpersonateLoggedOnUser(token)) throw new SecurityException(SR.Argument_ImpersonateUser); s_currentImpersonatedToken.Value = token; action(); }, null); } private static void CurrentImpersonatedTokenChanged(AsyncLocalValueChangedArgs<SafeAccessTokenHandle> args) { if (!args.ThreadContextChanged) return; // we handle explicit Value property changes elsewhere. if (!Interop.Advapi32.RevertToSelf()) Environment.FailFast(new Win32Exception().Message); if (args.CurrentValue != null && !args.CurrentValue.IsInvalid) { if (!Interop.Advapi32.ImpersonateLoggedOnUser(args.CurrentValue)) Environment.FailFast(new Win32Exception().Message); } } internal static WindowsIdentity GetCurrentInternal(TokenAccessLevels desiredAccess, bool threadOnly) { int hr = 0; bool isImpersonating; SafeAccessTokenHandle safeTokenHandle = GetCurrentToken(desiredAccess, threadOnly, out isImpersonating, out hr); if (safeTokenHandle == null || safeTokenHandle.IsInvalid) { // either we wanted only ThreadToken - return null if (threadOnly && !isImpersonating) return null; // or there was an error throw new SecurityException(new Win32Exception(hr).Message); } WindowsIdentity wi = new WindowsIdentity(); wi._safeTokenHandle.Dispose(); wi._safeTokenHandle = safeTokenHandle; return wi; } // // private. // private static int GetHRForWin32Error(int dwLastError) { if ((dwLastError & 0x80000000) == 0x80000000) return dwLastError; else return (dwLastError & 0x0000FFFF) | unchecked((int)0x80070000); } private static Exception GetExceptionFromNtStatus(int status) { if ((uint)status == Interop.StatusOptions.STATUS_ACCESS_DENIED) return new UnauthorizedAccessException(); if ((uint)status == Interop.StatusOptions.STATUS_INSUFFICIENT_RESOURCES || (uint)status == Interop.StatusOptions.STATUS_NO_MEMORY) return new OutOfMemoryException(); uint win32ErrorCode = Interop.Advapi32.LsaNtStatusToWinError((uint)status); return new SecurityException(new Win32Exception(unchecked((int)win32ErrorCode)).Message); } private static SafeAccessTokenHandle GetCurrentToken(TokenAccessLevels desiredAccess, bool threadOnly, out bool isImpersonating, out int hr) { isImpersonating = true; SafeAccessTokenHandle safeTokenHandle; hr = 0; bool success = Interop.Advapi32.OpenThreadToken(desiredAccess, WinSecurityContext.Both, out safeTokenHandle); if (!success) hr = Marshal.GetHRForLastWin32Error(); if (!success && hr == GetHRForWin32Error(Interop.Errors.ERROR_NO_TOKEN)) { // No impersonation isImpersonating = false; if (!threadOnly) safeTokenHandle = GetCurrentProcessToken(desiredAccess, out hr); } return safeTokenHandle; } private static SafeAccessTokenHandle GetCurrentProcessToken(TokenAccessLevels desiredAccess, out int hr) { hr = 0; SafeAccessTokenHandle safeTokenHandle; if (!Interop.Advapi32.OpenProcessToken(Interop.Kernel32.GetCurrentProcess(), desiredAccess, out safeTokenHandle)) hr = GetHRForWin32Error(Marshal.GetLastWin32Error()); return safeTokenHandle; } /// <summary> /// Get a property from the current token /// </summary> private T GetTokenInformation<T>(TokenInformationClass tokenInformationClass) where T : struct { Debug.Assert(!_safeTokenHandle.IsInvalid && !_safeTokenHandle.IsClosed, "!m_safeTokenHandle.IsInvalid && !m_safeTokenHandle.IsClosed"); using (SafeLocalAllocHandle information = GetTokenInformation(_safeTokenHandle, tokenInformationClass)) { Debug.Assert(information.ByteLength >= (ulong)Marshal.SizeOf<T>(), "information.ByteLength >= (ulong)Marshal.SizeOf(typeof(T))"); return information.Read<T>(0); } } private static Interop.LUID GetLogonAuthId(SafeAccessTokenHandle safeTokenHandle) { using (SafeLocalAllocHandle pStatistics = GetTokenInformation(safeTokenHandle, TokenInformationClass.TokenStatistics)) { Interop.TOKEN_STATISTICS statistics = pStatistics.Read<Interop.TOKEN_STATISTICS>(0); return statistics.AuthenticationId; } } private static SafeLocalAllocHandle GetTokenInformation(SafeAccessTokenHandle tokenHandle, TokenInformationClass tokenInformationClass) { SafeLocalAllocHandle safeLocalAllocHandle = SafeLocalAllocHandle.InvalidHandle; uint dwLength = (uint)sizeof(uint); bool result = Interop.Advapi32.GetTokenInformation(tokenHandle, (uint)tokenInformationClass, safeLocalAllocHandle, 0, out dwLength); int dwErrorCode = Marshal.GetLastWin32Error(); switch (dwErrorCode) { case Interop.Errors.ERROR_BAD_LENGTH: // special case for TokenSessionId. Falling through case Interop.Errors.ERROR_INSUFFICIENT_BUFFER: // ptrLength is an [In] param to LocalAlloc UIntPtr ptrLength = new UIntPtr(dwLength); safeLocalAllocHandle.Dispose(); safeLocalAllocHandle = Interop.Kernel32.LocalAlloc(0, ptrLength); if (safeLocalAllocHandle == null || safeLocalAllocHandle.IsInvalid) throw new OutOfMemoryException(); safeLocalAllocHandle.Initialize(dwLength); result = Interop.Advapi32.GetTokenInformation(tokenHandle, (uint)tokenInformationClass, safeLocalAllocHandle, dwLength, out dwLength); if (!result) throw new SecurityException(new Win32Exception().Message); break; case Interop.Errors.ERROR_INVALID_HANDLE: throw new ArgumentException(SR.Argument_InvalidImpersonationToken); default: throw new SecurityException(new Win32Exception(dwErrorCode).Message); } return safeLocalAllocHandle; } protected WindowsIdentity(WindowsIdentity identity) : base(identity, null, GetAuthType(identity), null, null) { bool mustDecrement = false; try { if (!identity._safeTokenHandle.IsInvalid && identity._safeTokenHandle != SafeAccessTokenHandle.InvalidHandle && identity._safeTokenHandle.DangerousGetHandle() != IntPtr.Zero) { identity._safeTokenHandle.DangerousAddRef(ref mustDecrement); if (!identity._safeTokenHandle.IsInvalid && identity._safeTokenHandle.DangerousGetHandle() != IntPtr.Zero) CreateFromToken(identity._safeTokenHandle.DangerousGetHandle()); _authType = identity._authType; _isAuthenticated = identity._isAuthenticated; } } finally { if (mustDecrement) identity._safeTokenHandle.DangerousRelease(); } } private static string GetAuthType(WindowsIdentity identity) { if (identity == null) { throw new ArgumentNullException(nameof(identity)); } return identity._authType; } /// <summary> /// Returns a new instance of <see cref="WindowsIdentity"/> with values copied from this object. /// </summary> public override ClaimsIdentity Clone() { return new WindowsIdentity(this); } /// <summary> /// Gets the 'User Claims' from the NTToken that represents this identity /// </summary> public virtual IEnumerable<Claim> UserClaims { get { InitializeClaims(); return _userClaims.ToArray(); } } /// <summary> /// Gets the 'Device Claims' from the NTToken that represents the device the identity is using /// </summary> public virtual IEnumerable<Claim> DeviceClaims { get { InitializeClaims(); return _deviceClaims.ToArray(); } } /// <summary> /// Gets the claims as <see cref="IEnumerable{Claim}"/>, associated with this <see cref="WindowsIdentity"/>. /// Includes UserClaims and DeviceClaims. /// </summary> public override IEnumerable<Claim> Claims { get { if (!_claimsInitialized) { InitializeClaims(); } foreach (Claim claim in base.Claims) yield return claim; foreach (Claim claim in _userClaims) yield return claim; foreach (Claim claim in _deviceClaims) yield return claim; } } /// <summary> /// Intenal method to initialize the claim collection. /// Lazy init is used so claims are not initialzed until needed /// </summary> private void InitializeClaims() { if (!_claimsInitialized) { lock (_claimsIntiailizedLock) { if (!_claimsInitialized) { _userClaims = new List<Claim>(); _deviceClaims = new List<Claim>(); if (!String.IsNullOrEmpty(Name)) { // // Add the name claim only if the WindowsIdentity.Name is populated // WindowsIdentity.Name will be null when it is the fake anonymous user // with a token value of IntPtr.Zero // _userClaims.Add(new Claim(NameClaimType, Name, ClaimValueTypes.String, _issuerName, _issuerName, this)); } // primary sid AddPrimarySidClaim(_userClaims); // group sids AddGroupSidClaims(_userClaims); _claimsInitialized = true; } } } } /// <summary> /// Creates a collection of SID claims that represent the users groups. /// </summary> private void AddGroupSidClaims(List<Claim> instanceClaims) { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return; SafeLocalAllocHandle safeAllocHandle = SafeLocalAllocHandle.InvalidHandle; SafeLocalAllocHandle safeAllocHandlePrimaryGroup = SafeLocalAllocHandle.InvalidHandle; try { // Retrieve the primary group sid safeAllocHandlePrimaryGroup = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenPrimaryGroup); Interop.TOKEN_PRIMARY_GROUP primaryGroup = (Interop.TOKEN_PRIMARY_GROUP)Marshal.PtrToStructure<Interop.TOKEN_PRIMARY_GROUP>(safeAllocHandlePrimaryGroup.DangerousGetHandle()); SecurityIdentifier primaryGroupSid = new SecurityIdentifier(primaryGroup.PrimaryGroup, true); // only add one primary group sid bool foundPrimaryGroupSid = false; // Retrieve all group sids, primary group sid is one of them safeAllocHandle = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenGroups); int count = Marshal.ReadInt32(safeAllocHandle.DangerousGetHandle()); IntPtr pSidAndAttributes = new IntPtr((long)safeAllocHandle.DangerousGetHandle() + (long)Marshal.OffsetOf<Interop.TOKEN_GROUPS>("Groups")); Claim claim; for (int i = 0; i < count; ++i) { Interop.SID_AND_ATTRIBUTES group = (Interop.SID_AND_ATTRIBUTES)Marshal.PtrToStructure<Interop.SID_AND_ATTRIBUTES>(pSidAndAttributes); uint mask = Interop.SecurityGroups.SE_GROUP_ENABLED | Interop.SecurityGroups.SE_GROUP_LOGON_ID | Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY; SecurityIdentifier groupSid = new SecurityIdentifier(group.Sid, true); if ((group.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_ENABLED) { if (!foundPrimaryGroupSid && StringComparer.Ordinal.Equals(groupSid.Value, primaryGroupSid.Value)) { claim = new Claim(ClaimTypes.PrimaryGroupSid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this); claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString()); instanceClaims.Add(claim); foundPrimaryGroupSid = true; } //Primary group sid generates both regular groupsid claim and primary groupsid claim claim = new Claim(ClaimTypes.GroupSid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this); claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString()); instanceClaims.Add(claim); } else if ((group.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY) { if (!foundPrimaryGroupSid && StringComparer.Ordinal.Equals(groupSid.Value, primaryGroupSid.Value)) { claim = new Claim(ClaimTypes.DenyOnlyPrimaryGroupSid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this); claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString()); instanceClaims.Add(claim); foundPrimaryGroupSid = true; } //Primary group sid generates both regular groupsid claim and primary groupsid claim claim = new Claim(ClaimTypes.DenyOnlySid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this); claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString()); instanceClaims.Add(claim); } pSidAndAttributes = new IntPtr((long)pSidAndAttributes + Marshal.SizeOf<Interop.SID_AND_ATTRIBUTES>()); } } finally { safeAllocHandle.Dispose(); safeAllocHandlePrimaryGroup.Dispose(); } } /// <summary> /// Creates a Windows SID Claim and adds to collection of claims. /// </summary> private void AddPrimarySidClaim(List<Claim> instanceClaims) { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return; SafeLocalAllocHandle safeAllocHandle = SafeLocalAllocHandle.InvalidHandle; try { safeAllocHandle = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenUser); Interop.SID_AND_ATTRIBUTES user = (Interop.SID_AND_ATTRIBUTES)Marshal.PtrToStructure<Interop.SID_AND_ATTRIBUTES>(safeAllocHandle.DangerousGetHandle()); uint mask = Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY; SecurityIdentifier sid = new SecurityIdentifier(user.Sid, true); Claim claim; if (user.Attributes == 0) { claim = new Claim(ClaimTypes.PrimarySid, sid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this); claim.Properties.Add(ClaimTypes.WindowsSubAuthority, sid.IdentifierAuthority.ToString()); instanceClaims.Add(claim); } else if ((user.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY) { claim = new Claim(ClaimTypes.DenyOnlyPrimarySid, sid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this); claim.Properties.Add(ClaimTypes.WindowsSubAuthority, sid.IdentifierAuthority.ToString()); instanceClaims.Add(claim); } } finally { safeAllocHandle.Dispose(); } } } internal enum WinSecurityContext { Thread = 1, // OpenAsSelf = false Process = 2, // OpenAsSelf = true Both = 3 // OpenAsSelf = true, then OpenAsSelf = false } internal enum TokenType : int { TokenPrimary = 1, TokenImpersonation } internal enum TokenInformationClass : int { TokenUser = 1, TokenGroups, TokenPrivileges, TokenOwner, TokenPrimaryGroup, TokenDefaultDacl, TokenSource, TokenType, TokenImpersonationLevel, TokenStatistics, TokenRestrictedSids, TokenSessionId, TokenGroupsAndPrivileges, TokenSessionReference, TokenSandBoxInert, TokenAuditPolicy, TokenOrigin, TokenElevationType, TokenLinkedToken, TokenElevation, TokenHasRestrictions, TokenAccessInformation, TokenVirtualizationAllowed, TokenVirtualizationEnabled, TokenIntegrityLevel, TokenUIAccess, TokenMandatoryPolicy, TokenLogonSid, TokenIsAppContainer, TokenCapabilities, TokenAppContainerSid, TokenAppContainerNumber, TokenUserClaimAttributes, TokenDeviceClaimAttributes, TokenRestrictedUserClaimAttributes, TokenRestrictedDeviceClaimAttributes, TokenDeviceGroups, TokenRestrictedDeviceGroups, MaxTokenInfoClass // MaxTokenInfoClass should always be the last enum } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Sockets; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Web.Script.Serialization; using System.Diagnostics; namespace Mycroft.App { /// <summary> /// The client abstract class. Any application made will inherit from /// this class. /// </summary> public abstract class Client { private string manifest; private TcpClient cli; private Stream stream; private JavaScriptSerializer ser = new JavaScriptSerializer(); private StreamReader reader; protected MessageEventHandler handler; public string InstanceId; /// <summary> /// Constructor for a client /// </summary> public Client(string manifestPath) { var textStreamReader = new StreamReader(manifestPath); manifest = textStreamReader.ReadToEnd(); var jsobj = ser.Deserialize<dynamic>(manifest); InstanceId = jsobj["instanceId"]; handler = new MessageEventHandler(); } #region Mycroft Connection /// <summary> /// Connects to Mycroft /// </summary> /// <param name="hostname">The hostname to connect to</param> /// <param name="port">The port to connect to</param> public async void Connect(string hostname, string port) { cli = new TcpClient(hostname, Convert.ToInt32(port)); stream = cli.GetStream(); reader = new StreamReader(stream); try { await StartListening(); } finally { CloseConnection(); } } /// <summary> /// Start recieving messages from Mycroft /// </summary> /// <returns>An Awaitable Task</returns> public async Task StartListening() { await SendManifest(); handler.Handle("CONNECT"); while (true) { dynamic obj = await ReadJson(); string type = obj.type; dynamic message = obj.message; handler.Handle(type, message); } } /// <summary> /// Close the connection from the Mycroft server /// </summary> public async void CloseConnection() { handler.Handle("END"); await SendData("APP_DOWN"); cli.Close(); } #endregion #region Message Sending and Recieving /// <summary> /// Send a message to Mycroft where data is a string. Used for sending /// Messages with no body (and app manifest because it's already a string) /// </summary> /// <param name="type">The type of message being sent</param> /// <param name="data">The message string that you are sending</param> /// <returns>A task</returns> private async Task SendData(string type, string data = "") { string msg = type + " " + data; msg = msg.Trim(); msg = Encoding.UTF8.GetByteCount(msg) + "\n" + msg; stream.Write(Encoding.UTF8.GetBytes(msg), 0, (int)msg.Length); } /// <summary> /// Sends a message to Mycroft where data is an object. Used for sending messages /// that actually have a body /// </summary> /// <param name="type">The type of message being sent</param> /// <param name="data">The json object being sent</param> /// <returns>A task</returns> private async Task SendJson(string type, Object data) { string obj = ser.Serialize(data); string msg = type + " " + obj; msg = msg.Trim(); msg = Encoding.UTF8.GetByteCount(msg) + "\n" + msg; stream.Write(Encoding.UTF8.GetBytes(msg), 0, (int)msg.Length); } /// <summary> /// Reads in json from the Mycroft server. /// </summary> /// <returns>An object with the type and message received</returns> private async Task<Object> ReadJson() { //Size of message in bytes string len = reader.ReadLine(); var size = Convert.ToInt32(len); //buffer to put message in var buf = new Char[size]; //Get the message reader.Read(buf, 0, size); var str = new string(buf).Trim(); var re = new Regex(@"^([A-Z_]*)"); //Match the message type var match = re.Match(str); if (match.Length <= 0) { throw new ArgumentException("Couldn't match a message type string in message: " + str); } //Convert the json string to an object var jsonstr = str.TrimStart(match.Value.ToCharArray()); if (jsonstr.Trim().Length == 0) { return new { type = match.Value, message = new { } }; } var obj = ser.Deserialize<dynamic>(jsonstr); //Return the type string and the object return new { type = match.Value, message = obj }; } #endregion #region Message Helpers /// <summary> /// Sends APP_MANIFEST to Mycroft /// </summary> /// <returns>A task</returns> public async Task SendManifest() { SendData("APP_MANIFEST", manifest); } /// <summary> /// Sends APP_UP to Mycroft /// </summary> /// <returns>A task</returns> public async Task Up() { SendData("APP_UP"); } /// <summary> /// Sends APP_DOWN to Mycroft /// </summary> /// <returns>A task</returns> public async Task Down() { SendData("APP_DOWN"); } /// <summary> /// Sends APP_IN_USE to Mycroft /// </summary> /// <param name="priority">the priority of the app</param> /// <returns>A task</returns> public async Task InUse(int priority) { SendJson("APP_IN_USE", new { priority = priority }); } /// <summary> /// Sends MSG_BROADCAST to Mycroft /// </summary> /// <param name="content">The content object of the message</param> /// <returns>A task</returns> public async Task Broadcast(dynamic content) { var broadcast = new { id = Guid.NewGuid(), content = content }; SendJson("MSG_BROADCAST", broadcast); } /// <summary> /// Sends MSG_QUERY to Mycroft /// </summary> /// <param name="capability">The capability</param> /// <param name="action">The action</param> /// <param name="data">The data of the message</param> /// <param name="instanceId">An array of instance ids. Defaults to null</param> /// <param name="priority">the priority. Defaults to 30</param> /// <returns>A task</returns> public async Task Query(string capability, string action, dynamic data, string[] instanceId = null, int priority = 30) { if (instanceId == null) instanceId = new string[0]; var query = new { id = Guid.NewGuid(), capability = capability, action = action, data = data, instanceId = instanceId, priority = priority }; SendJson("MSG_QUERY", query); } /// <summary> /// Sends MSG_QUERY_SUCCESS to Mycroft /// </summary> /// <param name="id">The id of the message being responded to</param> /// <param name="ret">The content of the message</param> /// <returns>A task</returns> public async Task QuerySuccess(string id, dynamic ret) { var querySuccess = new { id = id, ret = ret }; SendJson("MSG_QUERY_SUCCESS", querySuccess); } /// <summary> /// Sends MSG_QUERY_FAIL to Mycroft /// </summary> /// <param name="id">The id of the message being responded to</param> /// <param name="message">The error message</param> /// <returns>A task</returns> public async Task QueryFail(string id, string message) { var queryFail = new { id = id, message = message }; SendJson("MSG_QUERY_FAIL", queryFail); } #endregion } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Data; using System.Xml.Serialization; using CALI.Database.Contracts; using CALI.Database.Contracts.Auth; ////////////////////////////////////////////////////////////// //Do not modify this file. Use a partial class to extend. // //Override methods in the logic front class. // ////////////////////////////////////////////////////////////// namespace CALI.Database.Logic.Auth { [Serializable] public abstract partial class RolePermissionLogicBase : LogicBase<RolePermissionLogicBase> { //Put your code in a separate file. This is auto generated. [XmlArray] public List<RolePermissionContract> Results; public RolePermissionLogicBase() { Results = new List<RolePermissionContract>(); } /// <summary> /// Run RolePermission_Insert. /// </summary> /// <param name="fldRoleId">Value for RoleId</param> /// <param name="fldPermissionId">Value for PermissionId</param> /// <returns>The new ID</returns> public virtual int? Insert(int fldRoleId , int fldPermissionId ) { int? result = null; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[RolePermission_Insert]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@RoleId", fldRoleId) , new SqlParameter("@PermissionId", fldPermissionId) }); result = (int?)cmd.ExecuteScalar(); } }); return result; } /// <summary> /// Run RolePermission_Insert. /// </summary> /// <param name="fldRoleId">Value for RoleId</param> /// <param name="fldPermissionId">Value for PermissionId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The new ID</returns> public virtual int? Insert(int fldRoleId , int fldPermissionId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Auth].[RolePermission_Insert]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@RoleId", fldRoleId) , new SqlParameter("@PermissionId", fldPermissionId) }); return (int?)cmd.ExecuteScalar(); } } /// <summary> /// Insert by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>1, if insert was successful</returns> public int Insert(RolePermissionContract row) { int? result = null; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[RolePermission_Insert]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@RoleId", row.RoleId) , new SqlParameter("@PermissionId", row.PermissionId) }); result = (int?)cmd.ExecuteScalar(); row.RolePermissionId = result; } }); return result != null ? 1 : 0; } /// <summary> /// Insert by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>1, if insert was successful</returns> public int Insert(RolePermissionContract row, SqlConnection connection, SqlTransaction transaction) { int? result = null; using ( var cmd = new SqlCommand("[Auth].[RolePermission_Insert]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@RoleId", row.RoleId) , new SqlParameter("@PermissionId", row.PermissionId) }); result = (int?)cmd.ExecuteScalar(); row.RolePermissionId = result; } return result != null ? 1 : 0; } /// <summary> /// Insert the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Insert</param> /// <returns>The number of rows affected.</returns> public virtual int InsertAll(List<RolePermissionContract> rows) { var rowCount = 0; CALIDb.ConnectThen(x => { rowCount = InsertAll(rows, x, null); }); return rowCount; } /// <summary> /// Insert the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Insert</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int InsertAll(List<RolePermissionContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Insert(row, connection, transaction); return rowCount; } /// <summary> /// Run RolePermission_Update. /// </summary> /// <returns>The number of rows affected.</returns> /// <param name="fldRolePermissionId">Value for RolePermissionId</param> /// <param name="fldRoleId">Value for RoleId</param> /// <param name="fldPermissionId">Value for PermissionId</param> public virtual int Update(int fldRolePermissionId , int fldRoleId , int fldPermissionId ) { var rowCount = 0; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[RolePermission_Update]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@RolePermissionId", fldRolePermissionId) , new SqlParameter("@RoleId", fldRoleId) , new SqlParameter("@PermissionId", fldPermissionId) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Run RolePermission_Update. /// </summary> /// <param name="fldRolePermissionId">Value for RolePermissionId</param> /// <param name="fldRoleId">Value for RoleId</param> /// <param name="fldPermissionId">Value for PermissionId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Update(int fldRolePermissionId , int fldRoleId , int fldPermissionId , SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Auth].[RolePermission_Update]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@RolePermissionId", fldRolePermissionId) , new SqlParameter("@RoleId", fldRoleId) , new SqlParameter("@PermissionId", fldPermissionId) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Update by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public virtual int Update(RolePermissionContract row) { var rowCount = 0; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[RolePermission_Update]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@RolePermissionId", row.RolePermissionId) , new SqlParameter("@RoleId", row.RoleId) , new SqlParameter("@PermissionId", row.PermissionId) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Update by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Update(RolePermissionContract row, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Auth].[RolePermission_Update]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@RolePermissionId", row.RolePermissionId) , new SqlParameter("@RoleId", row.RoleId) , new SqlParameter("@PermissionId", row.PermissionId) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Update the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Update</param> /// <returns>The number of rows affected.</returns> public virtual int UpdateAll(List<RolePermissionContract> rows) { var rowCount = 0; CALIDb.ConnectThen(x => { rowCount = UpdateAll(rows, x, null); }); return rowCount; } /// <summary> /// Update the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Update</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int UpdateAll(List<RolePermissionContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Update(row, connection, transaction); return rowCount; } /// <summary> /// Run RolePermission_Delete. /// </summary> /// <returns>The number of rows affected.</returns> /// <param name="fldRolePermissionId">Value for RolePermissionId</param> public virtual int Delete(int fldRolePermissionId ) { var rowCount = 0; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[RolePermission_Delete]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@RolePermissionId", fldRolePermissionId) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Run RolePermission_Delete. /// </summary> /// <param name="fldRolePermissionId">Value for RolePermissionId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Delete(int fldRolePermissionId , SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Auth].[RolePermission_Delete]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@RolePermissionId", fldRolePermissionId) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Delete by providing a populated data row container /// </summary> /// <param name="row">The table row data to use</param> /// <returns>The number of rows affected.</returns> public virtual int Delete(RolePermissionContract row) { var rowCount = 0; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[RolePermission_Delete]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@RolePermissionId", row.RolePermissionId) }); rowCount = cmd.ExecuteNonQuery(); } }); return rowCount; } /// <summary> /// Delete by providing a populated data contract /// </summary> /// <param name="row">The table row data to use</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Delete(RolePermissionContract row, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; using ( var cmd = new SqlCommand("[Auth].[RolePermission_Delete]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@RolePermissionId", row.RolePermissionId) }); rowCount = cmd.ExecuteNonQuery(); } return rowCount; } /// <summary> /// Delete the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Delete</param> /// <returns>The number of rows affected.</returns> public virtual int DeleteAll(List<RolePermissionContract> rows) { var rowCount = 0; CALIDb.ConnectThen(x => { rowCount = DeleteAll(rows, x, null); }); return rowCount; } /// <summary> /// Delete the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Delete</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int DeleteAll(List<RolePermissionContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Delete(row, connection, transaction); return rowCount; } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldRolePermissionId">Value for RolePermissionId</param> /// <returns>True, if the values exist, or false.</returns> public virtual bool Exists(int fldRolePermissionId ) { bool result = false; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[RolePermission_Exists]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@RolePermissionId", fldRolePermissionId) }); result = (bool)cmd.ExecuteScalar(); } }); return result; } /// <summary> /// Determine if the table contains a row with the existing values /// </summary> /// <param name="fldRolePermissionId">Value for RolePermissionId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>True, if the values exist, or false.</returns> public virtual bool Exists(int fldRolePermissionId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Auth].[RolePermission_Exists]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@RolePermissionId", fldRolePermissionId) }); return (bool)cmd.ExecuteScalar(); } } /// <summary> /// Run RolePermission_SelectAll, and return results as a list of RolePermissionRow. /// </summary> /// <returns>A collection of RolePermissionRow.</returns> public virtual bool SelectAll() { var result = false; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[RolePermission_SelectAll]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run RolePermission_SelectAll, and return results as a list of RolePermissionRow. /// </summary> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of RolePermissionRow.</returns> public virtual bool SelectAll(SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Auth].[RolePermission_SelectAll]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run RolePermission_SelectBy_RolePermissionId, and return results as a list of RolePermissionRow. /// </summary> /// <param name="fldRolePermissionId">Value for RolePermissionId</param> /// <returns>A collection of RolePermissionRow.</returns> public virtual bool SelectBy_RolePermissionId(int fldRolePermissionId ) { var result = false; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[RolePermission_SelectBy_RolePermissionId]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@RolePermissionId", fldRolePermissionId) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run RolePermission_SelectBy_RolePermissionId, and return results as a list of RolePermissionRow. /// </summary> /// <param name="fldRolePermissionId">Value for RolePermissionId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of RolePermissionRow.</returns> public virtual bool SelectBy_RolePermissionId(int fldRolePermissionId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Auth].[RolePermission_SelectBy_RolePermissionId]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@RolePermissionId", fldRolePermissionId) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run RolePermission_SelectBy_RoleId, and return results as a list of RolePermissionRow. /// </summary> /// <param name="fldRoleId">Value for RoleId</param> /// <returns>A collection of RolePermissionRow.</returns> public virtual bool SelectBy_RoleId(int fldRoleId ) { var result = false; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[RolePermission_SelectBy_RoleId]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@RoleId", fldRoleId) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run RolePermission_SelectBy_RoleId, and return results as a list of RolePermissionRow. /// </summary> /// <param name="fldRoleId">Value for RoleId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of RolePermissionRow.</returns> public virtual bool SelectBy_RoleId(int fldRoleId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Auth].[RolePermission_SelectBy_RoleId]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@RoleId", fldRoleId) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Run RolePermission_SelectBy_PermissionId, and return results as a list of RolePermissionRow. /// </summary> /// <param name="fldPermissionId">Value for PermissionId</param> /// <returns>A collection of RolePermissionRow.</returns> public virtual bool SelectBy_PermissionId(int fldPermissionId ) { var result = false; CALIDb.ConnectThen(x => { using ( var cmd = new SqlCommand("[Auth].[RolePermission_SelectBy_PermissionId]", x) { CommandType = CommandType.StoredProcedure, CommandTimeout = DefaultCommandTimeout }) { cmd.Parameters.AddRange(new[] { new SqlParameter("@PermissionId", fldPermissionId) }); using(var r = cmd.ExecuteReader()) result = ReadAll(r); } }); return result; } /// <summary> /// Run RolePermission_SelectBy_PermissionId, and return results as a list of RolePermissionRow. /// </summary> /// <param name="fldPermissionId">Value for PermissionId</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>A collection of RolePermissionRow.</returns> public virtual bool SelectBy_PermissionId(int fldPermissionId , SqlConnection connection, SqlTransaction transaction) { using ( var cmd = new SqlCommand("[Auth].[RolePermission_SelectBy_PermissionId]", connection) {CommandType = CommandType.StoredProcedure,Transaction = transaction}) { cmd.Parameters.AddRange(new[] { new SqlParameter("@PermissionId", fldPermissionId) }); using(var r = cmd.ExecuteReader()) return ReadAll(r); } } /// <summary> /// Read all items into this collection /// </summary> /// <param name="reader">The result of running a sql command.</param> public virtual bool ReadAll(SqlDataReader reader) { var canRead = ReadOne(reader); var result = canRead; while (canRead) canRead = ReadOne(reader); return result; } /// <summary> /// Read one item into Results /// </summary> /// <param name="reader">The result of running a sql command.</param> public virtual bool ReadOne(SqlDataReader reader) { if (reader.Read()) { Results.Add( new RolePermissionContract { RolePermissionId = reader.GetInt32(0), RoleId = reader.GetInt32(1), PermissionId = reader.GetInt32(2), }); return true; } return false; } /// <summary> /// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value). /// </summary> /// <param name="row">The data to save</param> /// <returns>The number of rows affected.</returns> public virtual int Save(RolePermissionContract row) { if(row == null) return 0; if(row.RolePermissionId != null) return Update(row); return Insert(row); } /// <summary> /// Saves the row, either by inserting (when the identity key is null) or by updating (identity key has value). /// </summary> /// <param name="row">The data to save</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int Save(RolePermissionContract row, SqlConnection connection, SqlTransaction transaction) { if(row == null) return 0; if(row.RolePermissionId != null) return Update(row, connection, transaction); return Insert(row, connection, transaction); } /// <summary> /// Save the rows in bulk, uses the same connection (faster). /// </summary> /// <param name="rows">The table rows to Save</param> /// <returns>The number of rows affected.</returns> public virtual int SaveAll(List<RolePermissionContract> rows) { var rowCount = 0; CALIDb.ConnectThen(x => { foreach(var row in rows) rowCount += Save(row, x, null); }); return rowCount; } /// <summary> /// Save the rows in bulk, uses the same connection (faster), in a provided transaction scrope. /// </summary> /// <param name="rows">The table rows to Save</param> /// <param name="connection">The SqlConnection to use</param> /// <param name="transaction">The SqlTransaction to use</param> /// <returns>The number of rows affected.</returns> public virtual int SaveAll(List<RolePermissionContract> rows, SqlConnection connection, SqlTransaction transaction) { var rowCount = 0; foreach(var row in rows) rowCount += Save(row, connection, transaction); return rowCount; } } }
// Copyright 2014 The Rector & Visitors of the University of Virginia // // 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.Linq; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Sensus.UI.UiProperties; using Newtonsoft.Json; using Sensus.Context; using Sensus.Callbacks; #if __IOS__ using CoreLocation; #endif namespace Sensus.Probes { public abstract class PollingProbe : Probe { /// <summary> /// It's important to mitigate lag in polling operations since participation assessments are done on the basis of poll rates. /// </summary> private const bool POLL_CALLBACK_LAG = false; private int _pollingSleepDurationMS; private int _pollingTimeoutMinutes; private bool _isPolling; private List<DateTime> _pollTimes; private ScheduledCallback _pollCallback; #if __IOS__ private bool _significantChangePoll; private bool _significantChangeOverrideScheduledPolls; private CLLocationManager _locationManager; #endif private readonly object _locker = new object(); [EntryIntegerUiProperty("Sleep Duration (MS):", true, 5)] public virtual int PollingSleepDurationMS { get { return _pollingSleepDurationMS; } set { if (value <= 1000) value = 1000; _pollingSleepDurationMS = value; } } [EntryIntegerUiProperty("Timeout (Mins.):", true, 6)] public int PollingTimeoutMinutes { get { return _pollingTimeoutMinutes; } set { if (value < 1) value = 1; _pollingTimeoutMinutes = value; } } [JsonIgnore] public abstract int DefaultPollingSleepDurationMS { get; } protected override float RawParticipation { get { int oneDayMS = (int)new TimeSpan(1, 0, 0, 0).TotalMilliseconds; float pollsPerDay = oneDayMS / (float)_pollingSleepDurationMS; float fullParticipationPolls = pollsPerDay * Protocol.ParticipationHorizonDays; lock (_pollTimes) { return _pollTimes.Count(pollTime => pollTime >= Protocol.ParticipationHorizon) / fullParticipationPolls; } } } public List<DateTime> PollTimes { get { return _pollTimes; } } #if __IOS__ [OnOffUiProperty("Significant Change Poll:", true, 7)] public bool SignificantChangePoll { get { return _significantChangePoll; } set { _significantChangePoll = value; } } [OnOffUiProperty("Significant Change Override Scheduled Polls:", true, 8)] public bool SignificantChangeOverrideScheduledPolls { get { return _significantChangeOverrideScheduledPolls; } set { _significantChangeOverrideScheduledPolls = value; } } #endif public override string CollectionDescription { get { TimeSpan interval = new TimeSpan(0, 0, 0, 0, _pollingSleepDurationMS); double value = -1; string unit; int decimalPlaces = 0; if (interval.TotalSeconds <= 60) { value = interval.TotalSeconds; unit = "second"; decimalPlaces = 1; } else if (interval.TotalMinutes <= 60) { value = interval.TotalMinutes; unit = "minute"; } else if (interval.TotalHours <= 24) { value = interval.TotalHours; unit = "hour"; } else { value = interval.TotalDays; unit = "day"; } value = Math.Round(value, decimalPlaces); if (value == 1) return DisplayName + ": Once per " + unit + "."; else return DisplayName + ": Every " + value + " " + unit + "s."; } } protected PollingProbe() { _pollingSleepDurationMS = DefaultPollingSleepDurationMS; _pollingTimeoutMinutes = 5; _isPolling = false; _pollTimes = new List<DateTime>(); #if __IOS__ _significantChangePoll = false; _significantChangeOverrideScheduledPolls = false; _locationManager = new CLLocationManager(); _locationManager.LocationsUpdated += (sender, e) => { SensusContext.Current.CallbackScheduler.ScheduleOneTimeCallback(_pollCallback, 0); }; #endif } protected override void InternalStart() { lock (_locker) { base.InternalStart(); #if __IOS__ string userNotificationMessage = DisplayName + " data requested."; #elif __ANDROID__ string userNotificationMessage = null; #elif WINDOWS_PHONE string userNotificationMessage = null; // TODO: Should we use a message? #elif LOCAL_TESTS string userNotificationMessage = null; #else #warning "Unrecognized platform" string userNotificationMessage = null; #endif _pollCallback = new ScheduledCallback((callbackId, cancellationToken, letDeviceSleepCallback) => { return Task.Run(async () => { if (Running) { _isPolling = true; IEnumerable<Datum> data = null; try { SensusServiceHelper.Get().Logger.Log("Polling.", LoggingLevel.Normal, GetType()); data = Poll(cancellationToken); lock (_pollTimes) { _pollTimes.Add(DateTime.Now); _pollTimes.RemoveAll(pollTime => pollTime < Protocol.ParticipationHorizon); } } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Failed to poll: " + ex.Message, LoggingLevel.Normal, GetType()); } if (data != null) foreach (Datum datum in data) { if (cancellationToken.IsCancellationRequested) break; try { await StoreDatumAsync(datum, cancellationToken); } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Failed to store datum: " + ex.Message, LoggingLevel.Normal, GetType()); } } _isPolling = false; } }); }, GetType().FullName, Protocol.Id, Protocol.Id, TimeSpan.FromMinutes(_pollingTimeoutMinutes), userNotificationMessage); #if __IOS__ if (_significantChangePoll) { _locationManager.RequestAlwaysAuthorization(); _locationManager.DistanceFilter = 5.0; _locationManager.PausesLocationUpdatesAutomatically = false; _locationManager.AllowsBackgroundLocationUpdates = true; if (CLLocationManager.LocationServicesEnabled) { _locationManager.StartMonitoringSignificantLocationChanges(); } else { SensusServiceHelper.Get().Logger.Log("Location services not enabled.", LoggingLevel.Normal, GetType()); } } // schedule the callback if we're not doing significant-change polling, or if we are but the latter doesn't override the former. if (!_significantChangePoll || !_significantChangeOverrideScheduledPolls) { SensusContext.Current.CallbackScheduler.ScheduleRepeatingCallback(_pollCallback, 0, _pollingSleepDurationMS, POLL_CALLBACK_LAG); } #elif __ANDROID__ SensusContext.Current.CallbackScheduler.ScheduleRepeatingCallback(_pollCallback, 0, _pollingSleepDurationMS, POLL_CALLBACK_LAG); #endif } } protected abstract IEnumerable<Datum> Poll(CancellationToken cancellationToken); public override void Stop() { lock (_locker) { base.Stop(); #if __IOS__ if (_significantChangePoll) _locationManager.StopMonitoringSignificantLocationChanges(); #endif SensusContext.Current.CallbackScheduler.UnscheduleCallback(_pollCallback?.Id); _pollCallback = null; } } public override bool TestHealth(ref string error, ref string warning, ref string misc) { bool restart = base.TestHealth(ref error, ref warning, ref misc); if (Running) { double msElapsedSincePreviousStore = (DateTimeOffset.UtcNow - MostRecentStoreTimestamp.GetValueOrDefault(DateTimeOffset.MinValue)).TotalMilliseconds; int allowedLagMS = 5000; if (!_isPolling && _pollingSleepDurationMS <= int.MaxValue - allowedLagMS && // some probes (iOS HealthKit) have polling delays set to int.MaxValue. if we add to this (as we're about to do in the next check), we'll wrap around to 0 resulting in incorrect statuses. only do the check if we won't wrap around. msElapsedSincePreviousStore > (_pollingSleepDurationMS + allowedLagMS)) // system timer callbacks aren't always fired exactly as scheduled, resulting in health tests that identify warning conditions for delayed polling. allow a small fudge factor to ignore these warnings. warning += "Probe \"" + GetType().FullName + "\" has not stored data in " + msElapsedSincePreviousStore + "ms (polling delay = " + _pollingSleepDurationMS + "ms)." + Environment.NewLine; } return restart; } public override void Reset() { base.Reset(); _isPolling = false; _pollCallback = null; lock (_pollTimes) { _pollTimes.Clear(); } } } }
//----------------------------------------------------------------------- // <copyright file="FramingSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; using Akka.IO; using Akka.Streams.Dsl; using Akka.Streams.Stage; using Akka.Streams.TestKit.Tests; using Akka.TestKit; using Akka.Util; using FluentAssertions; using Xunit; using Xunit.Abstractions; namespace Akka.Streams.Tests.Dsl { public class FramingSpec : AkkaSpec { private readonly ITestOutputHelper _helper; private ActorMaterializer Materializer { get; } public FramingSpec(ITestOutputHelper helper) : base(helper) { _helper = helper; var settings = ActorMaterializerSettings.Create(Sys); Materializer = ActorMaterializer.Create(Sys, settings); } private sealed class Rechunker : PushPullStage<ByteString, ByteString> { private ByteString _rechunkBuffer = ByteString.Empty; public override ISyncDirective OnPush(ByteString element, IContext<ByteString> context) { _rechunkBuffer += element; return Rechunk(context); } public override ISyncDirective OnPull(IContext<ByteString> context) => Rechunk(context); public override ITerminationDirective OnUpstreamFinish(IContext<ByteString> context) => _rechunkBuffer.IsEmpty ? context.Finish() : context.AbsorbTermination(); private ISyncDirective Rechunk(IContext<ByteString> context) { if (!context.IsFinishing && ThreadLocalRandom.Current.Next(1, 3) == 2) return context.Pull(); var nextChunkSize = _rechunkBuffer.IsEmpty ? 0 : ThreadLocalRandom.Current.Next(0, _rechunkBuffer.Count + 1); var newChunk = _rechunkBuffer.Take(nextChunkSize).Compact(); _rechunkBuffer = _rechunkBuffer.Drop(nextChunkSize).Compact(); return context.IsFinishing && _rechunkBuffer.IsEmpty ? context.PushAndFinish(newChunk) : context.Push(newChunk); } } private Flow<ByteString, ByteString, NotUsed> Rechunk => Flow.Create<ByteString>().Transform(() => new Rechunker()).Named("rechunker"); private static readonly List<ByteString> DelimiterBytes = new List<string> {"\n", "\r\n", "FOO"}.Select(ByteString.FromString).ToList(); private static readonly List<ByteString> BaseTestSequences = new List<string> { "", "foo", "hello world" }.Select(ByteString.FromString).ToList(); private static Flow<ByteString, string, NotUsed> SimpleLines(string delimiter, int maximumBytes, bool allowTruncation = true) { return Framing.Delimiter(ByteString.FromString(delimiter), maximumBytes, allowTruncation) .Select(x => x.DecodeString(Encoding.UTF8)).Named("LineFraming"); } private static IEnumerable<ByteString> CompleteTestSequence(ByteString delimiter) { for (var i = 0; i < delimiter.Count; i++) foreach (var sequence in BaseTestSequences) yield return delimiter.Take(i) + sequence; } [Fact] public void Delimiter_bytes_based_framing_must_work_with_various_delimiters_and_test_sequences() { for (var i = 1; i <= 100; i++) { foreach (var delimiter in DelimiterBytes) { var testSequence = CompleteTestSequence(delimiter).ToList(); var task = Source.From(testSequence) .Select(x => x + delimiter) .Via(Rechunk) .Via(Framing.Delimiter(delimiter, 256)) .RunWith(Sink.Seq<ByteString>(), Materializer); task.Wait(TimeSpan.FromDays(3)).Should().BeTrue(); task.Result.ShouldAllBeEquivalentTo(testSequence); } } } [Fact] public void Delimiter_bytes_based_framing_must_respect_maximum_line_settings() { var task1 = Source.Single(ByteString.FromString("a\nb\nc\nd\n")) .Via(SimpleLines("\n", 1)) .Limit(100) .RunWith(Sink.Seq<string>(), Materializer); task1.Wait(TimeSpan.FromDays(3)).Should().BeTrue(); task1.Result.ShouldAllBeEquivalentTo(new[] {"a", "b", "c", "d"}); var task2 = Source.Single(ByteString.FromString("ab\n")) .Via(SimpleLines("\n", 1)) .Limit(100) .RunWith(Sink.Seq<string>(), Materializer); task2.Invoking(t => t.Wait(TimeSpan.FromSeconds(3))).ShouldThrow<Framing.FramingException>(); var task3 = Source.Single(ByteString.FromString("aaa")) .Via(SimpleLines("\n", 2)) .Limit(100) .RunWith(Sink.Seq<string>(), Materializer); task3.Invoking(t => t.Wait(TimeSpan.FromSeconds(3))).ShouldThrow<Framing.FramingException>(); } [Fact] public void Delimiter_bytes_based_framing_must_work_with_empty_streams() { var task = Source.Empty<ByteString>().Via(SimpleLines("\n", 256)).RunAggregate(new List<string>(), (list, s) => { list.Add(s); return list; }, Materializer); task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); task.Result.Should().BeEmpty(); } [Fact] public void Delimiter_bytes_based_framing_must_report_truncated_frames() { var task = Source.Single(ByteString.FromString("I habe no end")) .Via(SimpleLines("\n", 256, false)) .Grouped(1000) .RunWith(Sink.First<IEnumerable<string>>(), Materializer); task.Invoking(t => t.Wait(TimeSpan.FromSeconds(3))).ShouldThrow<Framing.FramingException>(); } [Fact] public void Delimiter_bytes_based_framing_must_allow_truncated_frames_if_configured_so() { var task = Source.Single(ByteString.FromString("I have no end")) .Via(SimpleLines("\n", 256)) .Grouped(1000) .RunWith(Sink.First<IEnumerable<string>>(), Materializer); task.AwaitResult().Should().ContainSingle(s => s.Equals("I have no end")); } private static string RandomString(int length) { const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; var random = new Random(); return new string(Enumerable.Repeat(chars, length) .Select(s => s[random.Next(s.Length)]).ToArray()); } private static readonly ByteString ReferenceChunk = ByteString.FromString(RandomString(0x100001)); private static readonly List<ByteOrder> ByteOrders = new List<ByteOrder> { ByteOrder.BigEndian, ByteOrder.LittleEndian }; private static readonly List<int> FrameLengths = new List<int> { 0, 1, 2, 3, 0xFF, 0x100, 0x101, 0xFFF, 0x1000, 0x1001, 0xFFFF, 0x10000, 0x10001 }; private static readonly List<int> FieldLengths = new List<int> {1, 2, 3, 4}; private static readonly List<int> FieldOffsets = new List<int> {0, 1, 2, 3, 15, 16, 31, 32, 44, 107}; private static ByteString Encode(ByteString payload, int fieldOffset, int fieldLength, ByteOrder byteOrder) { var h = new ByteStringBuilder().PutInt(payload.Count, byteOrder).Result(); var header = byteOrder == ByteOrder.LittleEndian ? h.Take(fieldLength) : h.Drop(4 - fieldLength); return ByteString.Create(new byte[fieldOffset]) + header + payload; } [Fact] public void Length_field_based_framing_must_work_with_various_byte_orders_frame_lengths_and_offsets() { var counter = 1; foreach (var byteOrder in ByteOrders) { foreach (var fieldOffset in FieldOffsets) { foreach (var fieldLength in FieldLengths) { var encodedFrames = FrameLengths.Where(x => x < 1L << (fieldLength * 8)).Select(length => { var payload = ReferenceChunk.Take(length); return Encode(payload, fieldOffset, fieldLength, byteOrder); }).ToList(); var task = Source.From(encodedFrames) .Via(Rechunk) .Via(Framing.LengthField(fieldLength, int.MaxValue, fieldOffset, byteOrder)) .Grouped(10000) .RunWith(Sink.First<IEnumerable<ByteString>>(), Materializer); task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); task.Result.ShouldAllBeEquivalentTo(encodedFrames); _helper.WriteLine($"{counter++} from 80 passed"); } } } } [Fact] public void Length_field_based_framing_must_work_with_empty_streams() { var task = Source.Empty<ByteString>() .Via(Framing.LengthField(4, int.MaxValue, 0, ByteOrder.BigEndian)) .RunAggregate(new List<ByteString>(), (list, s) => { list.Add(s); return list; }, Materializer); task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); task.Result.Should().BeEmpty(); } [Fact] public void Length_field_based_framing_must_report_oversized_frames() { var task1 = Source.Single(Encode(ReferenceChunk.Take(100), 0, 1, ByteOrder.BigEndian)) .Via(Framing.LengthField(1, 99, 0, ByteOrder.BigEndian)) .RunAggregate(new List<ByteString>(), (list, s) => { list.Add(s); return list; }, Materializer); task1.Invoking(t => t.Wait(TimeSpan.FromSeconds(3))).ShouldThrow<Framing.FramingException>(); var task2 = Source.Single(Encode(ReferenceChunk.Take(100), 49, 1, ByteOrder.BigEndian)) .Via(Framing.LengthField(1, 100, 0, ByteOrder.BigEndian)) .RunAggregate(new List<ByteString>(), (list, s) => { list.Add(s); return list; }, Materializer); task2.Invoking(t => t.Wait(TimeSpan.FromSeconds(3))).ShouldThrow<Framing.FramingException>(); } [Fact] public void Length_field_based_framing_must_report_truncated_frames() { foreach (var byteOrder in ByteOrders) { foreach (var fieldOffset in FieldOffsets) { foreach (var fieldLength in FieldLengths) { foreach (var frameLength in FrameLengths.Where(f => f < 1 << (fieldLength * 8) && f != 0)) { var fullFrame = Encode(ReferenceChunk.Take(frameLength), fieldOffset, fieldLength, byteOrder); var partialFrame = fullFrame.DropRight(1); Action action = () => { Source.From(new[] {fullFrame, partialFrame}) .Via(Rechunk) .Via(Framing.LengthField(fieldLength, int.MaxValue, fieldOffset, byteOrder)) .Grouped(10000) .RunWith(Sink.First<IEnumerable<ByteString>>(), Materializer) .Wait(TimeSpan.FromSeconds(5)); }; action.ShouldThrow<Framing.FramingException>(); } } } } } [Fact] public void Length_field_based_framing_must_support_simple_framing_adapter() { var rechunkBidi = BidiFlow.FromFlowsMat(Rechunk, Rechunk, Keep.Left); var codecFlow = Framing.SimpleFramingProtocol(1024) .Atop(rechunkBidi) .Atop(Framing.SimpleFramingProtocol(1024).Reversed()) .Join(Flow.Create<ByteString>()); // Loopback var random= new Random(); var testMessages = Enumerable.Range(1, 100).Select(_ => ReferenceChunk.Take(random.Next(1024))).ToList(); var task = Source.From(testMessages) .Via(codecFlow) .Limit(1000) .RunWith(Sink.Seq<ByteString>(), Materializer); task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); task.Result.ShouldAllBeEquivalentTo(testMessages); } } }
// // DBusServiceManager.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2007-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Text; using System.Text.RegularExpressions; using System.Collections.Generic; using System.Reflection; using NDesk.DBus; using org.freedesktop.DBus; using Hyena; using Banshee.Base; namespace Banshee.ServiceStack { public class DBusExportableAttribute : Attribute { private string service_name; public string ServiceName { get { return service_name; } set { service_name = value; } } } public class DBusServiceManager : IService, IRemoteServiceManager { public const string ObjectRoot = "/org/bansheeproject/Banshee"; private Dictionary<object, ObjectPath> registered_objects = new Dictionary<object, ObjectPath> (); public static string MakeDBusSafeString (string str) { return str == null ? String.Empty : Regex.Replace (str, @"[^A-Za-z0-9]*", String.Empty); } public static string MakeObjectPath (IRemoteExportable o) { StringBuilder object_path = new StringBuilder (); object_path.Append (ObjectRoot); object_path.Append ('/'); Stack<string> paths = new Stack<string> (); IRemoteExportable p = o.Parent; while (p != null) { paths.Push (String.Format ("{0}/", GetObjectName (p))); p = p.Parent; } while (paths.Count > 0) { object_path.Append (paths.Pop ()); } object_path.Append (GetObjectName (o)); return object_path.ToString (); } private static string GetObjectName (IRemoteExportable o) { return o is IRemoteObjectName ? ((IRemoteObjectName)o).ExportObjectName : o.ServiceName; } public static string [] MakeObjectPathArray<T> (IEnumerable<T> collection) where T : IRemoteExportable { List<string> paths = new List<string> (); foreach (IRemoteExportable item in collection) { paths.Add (MakeObjectPath (item)); } return paths.ToArray (); } public bool Enabled { get { return DBusConnection.Enabled; } } public bool ServiceNameHasOwner (string serviceName) { return DBusConnection.NameHasOwner (serviceName); } public void Disconnect (string serviceName) { DBusConnection.Disconnect (serviceName); } public string RegisterObject (IRemoteExportable o) { return RegisterObject (DBusConnection.DefaultServiceName, o); } public string RegisterObject (string serviceName, IRemoteExportable o) { return RegisterObject (serviceName, o, MakeObjectPath (o)); } public string RegisterObject (object o, string objectName) { return RegisterObject (DBusConnection.DefaultServiceName, o, objectName); } public string RegisterObject (string serviceName, object o, string objectName) { ObjectPath path = null; if (!DBusConnection.ConnectTried) { DBusConnection.Connect (); } if (DBusConnection.Enabled && Bus.Session != null) { IRemoteExportableProvider exportable_provider = o as IRemoteExportableProvider; if (exportable_provider != null) { foreach (IRemoteExportable e in exportable_provider.Exportables) { RegisterObject (e); } } object [] attrs = o.GetType ().GetCustomAttributes (typeof (DBusExportableAttribute), true); if (attrs != null && attrs.Length > 0) { DBusExportableAttribute dbus_attr = (DBusExportableAttribute)attrs[0]; if (!String.IsNullOrEmpty (dbus_attr.ServiceName)) { serviceName = dbus_attr.ServiceName; } } lock (registered_objects) { registered_objects.Add (o, path = new ObjectPath (objectName)); } string bus_name = DBusConnection.MakeBusName (serviceName); Log.DebugFormat ("Registering remote object {0} ({1}) on {2}", path, o.GetType (), bus_name); #pragma warning disable 0618 Bus.Session.Register (bus_name, path, o); #pragma warning restore 0618 Log.DebugFormat ("Registered remote object {0} ({1}) on {2}", path, o.GetType (), bus_name); } return path != null ? path.ToString () : null; } public void UnregisterObject (object o) { ObjectPath path = null; lock (registered_objects) { if (!registered_objects.TryGetValue (o, out path)) { Log.WarningFormat ("Unable to unregister DBus object {0}, does not appear to be registered", o.GetType ()); return; } registered_objects.Remove (o); } Bus.Session.Unregister (path); } public T FindInstance<T> (string objectPath) where T : class { return FindInstance<T> (DBusConnection.DefaultBusName, true, objectPath); } public T FindInstance<T> (string serviceName, string objectPath) where T : class { return FindInstance<T> (serviceName, false, objectPath); } public static T FindInstance<T> (string serviceName, bool isFullBusName, string objectPath) where T : class { string busName = isFullBusName ? serviceName : DBusConnection.MakeBusName (serviceName); if (!DBusConnection.Enabled || !Bus.Session.NameHasOwner (busName)) { return null; } string full_object_path = objectPath; if (!objectPath.StartsWith (ObjectRoot)) { full_object_path = ObjectRoot + objectPath; } return Bus.Session.GetObject<T> (busName, new ObjectPath (full_object_path)); } string IService.ServiceName { get { return "DBusServiceManager"; } } } }
// // 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.Linq; using System.Net; using System.Net.Http; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Compute { /// <summary> /// Operations for listing usage. /// </summary> internal partial class UsageOperations : IServiceOperations<ComputeManagementClient>, IUsageOperations { /// <summary> /// Initializes a new instance of the UsageOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal UsageOperations(ComputeManagementClient client) { this._client = client; } private ComputeManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Compute.ComputeManagementClient. /// </summary> public ComputeManagementClient Client { get { return this._client; } } /// <summary> /// Lists compute usages for a subscription. /// </summary> /// <param name='location'> /// Required. The location upon which resource usage is queried. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Usages operation response. /// </returns> public async Task<ListUsagesResponse> ListAsync(string location, CancellationToken cancellationToken) { // Validate if (location == null) { throw new ArgumentNullException("location"); } if (location != null && location.Length > 1000) { throw new ArgumentOutOfRangeException("location"); } if (Regex.IsMatch(location, "^[-\\w\\._]+$") == false) { throw new ArgumentOutOfRangeException("location"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("location", location); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/"; url = url + "Microsoft.Compute"; url = url + "/locations/"; url = url + Uri.EscapeDataString(location); url = url + "/usages"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-06-15"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } 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 // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.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) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ListUsagesResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ListUsagesResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Usage usageInstance = new Usage(); result.Usages.Add(usageInstance); JToken unitValue = valueValue["unit"]; if (unitValue != null && unitValue.Type != JTokenType.Null) { UsageUnit unitInstance = ((UsageUnit)Enum.Parse(typeof(UsageUnit), ((string)unitValue), true)); usageInstance.Unit = unitInstance; } JToken currentValueValue = valueValue["currentValue"]; if (currentValueValue != null && currentValueValue.Type != JTokenType.Null) { int currentValueInstance = ((int)currentValueValue); usageInstance.CurrentValue = currentValueInstance; } JToken limitValue = valueValue["limit"]; if (limitValue != null && limitValue.Type != JTokenType.Null) { uint limitInstance = ((uint)limitValue); usageInstance.Limit = limitInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { UsageName nameInstance = new UsageName(); usageInstance.Name = nameInstance; JToken valueValue2 = nameValue["value"]; if (valueValue2 != null && valueValue2.Type != JTokenType.Null) { string valueInstance = ((string)valueValue2); nameInstance.Value = valueInstance; } JToken localizedValueValue = nameValue["localizedValue"]; if (localizedValueValue != null && localizedValueValue.Type != JTokenType.Null) { string localizedValueInstance = ((string)localizedValueValue); nameInstance.LocalizedValue = localizedValueInstance; } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: FormatterServices ** ** ** Purpose: Provides some static methods to aid with the implementation ** of a Formatter for Serialization. ** ** ============================================================*/ namespace System.Runtime.Serialization { using System; using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Security; using System.Security.Permissions; using System.Runtime.Serialization.Formatters; using System.Runtime.Remoting; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Threading; using System.IO; using System.Text; using System.Globalization; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] public static class FormatterServices { internal static Dictionary<MemberHolder, MemberInfo[]> m_MemberInfoTable = new Dictionary<MemberHolder, MemberInfo[]>(32); #if FEATURE_SERIALIZATION [System.Security.SecurityCritical] private static bool unsafeTypeForwardersIsEnabled = false; [System.Security.SecurityCritical] private static volatile bool unsafeTypeForwardersIsEnabledInitialized = false; #endif private static Object s_FormatterServicesSyncObject = null; private static Object formatterServicesSyncObject { get { if (s_FormatterServicesSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange<Object>(ref s_FormatterServicesSyncObject, o, null); } return s_FormatterServicesSyncObject; } } [SecuritySafeCritical] static FormatterServices() { // Static initialization touches security critical types, so we need an // explicit static constructor to allow us to mark it safe critical. } private static MemberInfo[] GetSerializableMembers(RuntimeType type) { // get the list of all fields FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); int countProper = 0; for (int i = 0; i < fields.Length; i++) { if ((fields[i].Attributes & FieldAttributes.NotSerialized) == FieldAttributes.NotSerialized) continue; countProper++; } if (countProper != fields.Length) { FieldInfo[] properFields = new FieldInfo[countProper]; countProper = 0; for (int i = 0; i < fields.Length; i++) { if ((fields[i].Attributes & FieldAttributes.NotSerialized) == FieldAttributes.NotSerialized) continue; properFields[countProper] = fields[i]; countProper++; } return properFields; } else return fields; } private static bool CheckSerializable(RuntimeType type) { if (type.IsSerializable) { return true; } return false; } private static MemberInfo[] InternalGetSerializableMembers(RuntimeType type) { List<SerializationFieldInfo> allMembers = null; MemberInfo[] typeMembers; FieldInfo [] typeFields; RuntimeType parentType; Contract.Assert((object)type != null, "[GetAllSerializableMembers]type!=null"); //< if (type.IsInterface) { return new MemberInfo[0]; } if (!(CheckSerializable(type))) { throw new SerializationException(Environment.GetResourceString("Serialization_NonSerType", type.FullName, type.Module.Assembly.FullName)); } //Get all of the serializable members in the class to be serialized. typeMembers = GetSerializableMembers(type); //If this class doesn't extend directly from object, walk its hierarchy and //get all of the private and assembly-access fields (e.g. all fields that aren't //virtual) and include them in the list of things to be serialized. parentType = (RuntimeType)(type.BaseType); if (parentType != null && parentType != (RuntimeType)typeof(Object)) { RuntimeType[] parentTypes = null; int parentTypeCount = 0; bool classNamesUnique = GetParentTypes(parentType, out parentTypes, out parentTypeCount); if (parentTypeCount > 0){ allMembers = new List<SerializationFieldInfo>(); for (int i = 0; i < parentTypeCount;i++){ parentType = parentTypes[i]; if (!CheckSerializable(parentType)) { throw new SerializationException(Environment.GetResourceString("Serialization_NonSerType", parentType.FullName, parentType.Module.Assembly.FullName)); } typeFields = parentType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance); String typeName = classNamesUnique ? parentType.Name : parentType.FullName; foreach (FieldInfo field in typeFields) { // Family and Assembly fields will be gathered by the type itself. if (!field.IsNotSerialized) { allMembers.Add(new SerializationFieldInfo((RuntimeFieldInfo)field, typeName)); } } } //If we actually found any new MemberInfo's, we need to create a new MemberInfo array and //copy all of the members which we've found so far into that. if (allMembers!=null && allMembers.Count>0) { MemberInfo[] membersTemp = new MemberInfo[allMembers.Count + typeMembers.Length]; Array.Copy(typeMembers, membersTemp, typeMembers.Length); ((ICollection)allMembers).CopyTo(membersTemp, typeMembers.Length); typeMembers = membersTemp; } } } return typeMembers; } private static bool GetParentTypes(RuntimeType parentType, out RuntimeType[] parentTypes, out int parentTypeCount){ //Check if there are any dup class names. Then we need to include as part of //typeName to prefix the Field names in SerializationFieldInfo /*out*/ parentTypes = null; /*out*/ parentTypeCount = 0; bool unique = true; RuntimeType objectType = (RuntimeType)typeof(object); for (RuntimeType t1 = parentType; t1 != objectType; t1 = (RuntimeType)t1.BaseType) { if (t1.IsInterface) continue; string t1Name = t1.Name; for(int i=0;unique && i<parentTypeCount;i++){ string t2Name = parentTypes[i].Name; if (t2Name.Length == t1Name.Length && t2Name[0] == t1Name[0] && t1Name == t2Name){ unique = false; break; } } //expand array if needed if (parentTypes == null || parentTypeCount == parentTypes.Length){ RuntimeType[] tempParentTypes = new RuntimeType[Math.Max(parentTypeCount*2, 12)]; if (parentTypes != null) Array.Copy(parentTypes, 0, tempParentTypes, 0, parentTypeCount); parentTypes = tempParentTypes; } parentTypes[parentTypeCount++] = t1; } return unique; } // Get all of the Serializable members for a particular class. For all practical intents and // purposes, this is the non-transient, non-static members (fields and properties). In order to // be included, properties must have both a getter and a setter. N.B.: A class // which implements ISerializable or has a serialization surrogate may not use all of these members // (or may have additional members). [System.Security.SecurityCritical] // auto-generated_required public static MemberInfo[] GetSerializableMembers(Type type) { return GetSerializableMembers(type, new StreamingContext(StreamingContextStates.All)); } // Get all of the Serializable Members for a particular class. If we're not cloning, this is all // non-transient, non-static fields. If we are cloning, include the transient fields as well since // we know that we're going to live inside of the same context. [System.Security.SecurityCritical] // auto-generated_required public static MemberInfo[] GetSerializableMembers(Type type, StreamingContext context) { MemberInfo[] members; if ((object)type==null) { throw new ArgumentNullException("type"); } Contract.EndContractBlock(); if (!(type is RuntimeType)) { throw new SerializationException(Environment.GetResourceString("Serialization_InvalidType", type.ToString())); } MemberHolder mh = new MemberHolder(type, context); //If we've already gathered the members for this type, just return them. if (m_MemberInfoTable.ContainsKey(mh)) { return m_MemberInfoTable[mh]; } lock (formatterServicesSyncObject) { //If we've already gathered the members for this type, just return them. if (m_MemberInfoTable.ContainsKey(mh)) { return m_MemberInfoTable[mh]; } members = InternalGetSerializableMembers((RuntimeType)type); m_MemberInfoTable[mh] = members; } return members; } static readonly Type[] advancedTypes = new Type[]{ typeof(System.DelegateSerializationHolder), #if FEATURE_REMOTING typeof(System.Runtime.Remoting.ObjRef), typeof(System.Runtime.Remoting.IEnvoyInfo), typeof(System.Runtime.Remoting.Lifetime.ISponsor), #endif }; public static void CheckTypeSecurity(Type t, TypeFilterLevel securityLevel) { if (securityLevel == TypeFilterLevel.Low){ for(int i=0;i<advancedTypes.Length;i++){ if (advancedTypes[i].IsAssignableFrom(t)) throw new SecurityException(Environment.GetResourceString("Serialization_TypeSecurity", advancedTypes[i].FullName, t.FullName)); } } } // Gets a new instance of the object. The entire object is initalized to 0 and no // constructors have been run. **THIS MEANS THAT THE OBJECT MAY NOT BE IN A STATE // CONSISTENT WITH ITS INTERNAL REQUIREMENTS** This method should only be used for // deserialization when the user intends to immediately populate all fields. This method // will not create an unitialized string because it is non-sensical to create an empty // instance of an immutable type. // [System.Security.SecurityCritical] // auto-generated_required public static Object GetUninitializedObject(Type type) { if ((object)type == null) { throw new ArgumentNullException("type"); } Contract.EndContractBlock(); if (!(type is RuntimeType)) { throw new SerializationException(Environment.GetResourceString("Serialization_InvalidType", type.ToString())); } return nativeGetUninitializedObject((RuntimeType)type); } [System.Security.SecurityCritical] // auto-generated_required public static Object GetSafeUninitializedObject(Type type) { if ((object)type == null) { throw new ArgumentNullException("type"); } Contract.EndContractBlock(); if (!(type is RuntimeType)) { throw new SerializationException(Environment.GetResourceString("Serialization_InvalidType", type.ToString())); } #if FEATURE_REMOTING if (Object.ReferenceEquals(type, typeof(System.Runtime.Remoting.Messaging.ConstructionCall)) || Object.ReferenceEquals(type, typeof(System.Runtime.Remoting.Messaging.LogicalCallContext)) || Object.ReferenceEquals(type, typeof(System.Runtime.Remoting.Contexts.SynchronizationAttribute))) return nativeGetUninitializedObject((RuntimeType)type); #endif try { return nativeGetSafeUninitializedObject((RuntimeType)type); } catch(SecurityException e) { throw new SerializationException(Environment.GetResourceString("Serialization_Security", type.FullName), e); } } #if MONO private static Object nativeGetUninitializedObject(RuntimeType type) { return System.Runtime.Remoting.Activation.ActivationServices.AllocateUninitializedClassInstance (type); } private static Object nativeGetSafeUninitializedObject(RuntimeType type) { return System.Runtime.Remoting.Activation.ActivationServices.AllocateUninitializedClassInstance (type); } #else [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern Object nativeGetSafeUninitializedObject(RuntimeType type); [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern Object nativeGetUninitializedObject(RuntimeType type); #endif #if FEATURE_SERIALIZATION #if MONO static bool GetEnableUnsafeTypeForwarders () { return false; } #else [System.Security.SecurityCritical] [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool GetEnableUnsafeTypeForwarders(); #endif [SecuritySafeCritical] internal static bool UnsafeTypeForwardersIsEnabled() { if (!unsafeTypeForwardersIsEnabledInitialized) { unsafeTypeForwardersIsEnabled = GetEnableUnsafeTypeForwarders(); unsafeTypeForwardersIsEnabledInitialized = true; } return unsafeTypeForwardersIsEnabled; } #endif private static Binder s_binder = Type.DefaultBinder; [System.Security.SecurityCritical] internal static void SerializationSetValue(MemberInfo fi, Object target, Object value) { Contract.Requires(fi != null); RtFieldInfo rtField = fi as RtFieldInfo; if (rtField != null) { rtField.CheckConsistency(target); rtField.UnsafeSetValue(target, value, BindingFlags.Default, s_binder, null); return; } SerializationFieldInfo serField = fi as SerializationFieldInfo; if (serField != null) { serField.InternalSetValue(target, value, BindingFlags.Default, s_binder, null); return; } throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFieldInfo")); } // Fill in the members of obj with the data contained in data. // Returns the number of members populated. // [System.Security.SecurityCritical] // auto-generated_required public static Object PopulateObjectMembers(Object obj, MemberInfo[] members, Object[] data) { if (obj==null) { throw new ArgumentNullException("obj"); } if (members==null) { throw new ArgumentNullException("members"); } if (data==null) { throw new ArgumentNullException("data"); } if (members.Length!=data.Length) { throw new ArgumentException(Environment.GetResourceString("Argument_DataLengthDifferent")); } Contract.EndContractBlock(); MemberInfo mi; BCLDebug.Trace("SER", "[PopulateObjectMembers]Enter."); for (int i=0; i<members.Length; i++) { mi = members[i]; if (mi==null) { throw new ArgumentNullException("members", Environment.GetResourceString("ArgumentNull_NullMember", i)); } //If we find an empty, it means that the value was never set during deserialization. //This is either a forward reference or a null. In either case, this may break some of the //invariants mantained by the setter, so we'll do nothing with it for right now. if (data[i]!=null) { if (mi.MemberType==MemberTypes.Field) { SerializationSetValue(mi, obj, data[i]); } else { throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMemberInfo")); } BCLDebug.Trace("SER", "[PopulateObjectMembers]\tType:", obj.GetType(), "\tMember:", members[i].Name, " with member type: ", ((FieldInfo)members[i]).FieldType); } //Console.WriteLine("X"); } BCLDebug.Trace("SER", "[PopulateObjectMembers]Leave."); return obj; } // Extracts the data from obj. members is the array of members which we wish to // extract (must be FieldInfos or PropertyInfos). For each supplied member, extract the matching value and // return it in a Object[] of the same size. // [System.Security.SecurityCritical] // auto-generated_required public static Object[] GetObjectData(Object obj, MemberInfo[] members) { if (obj==null) { throw new ArgumentNullException("obj"); } if (members==null) { throw new ArgumentNullException("members"); } Contract.EndContractBlock(); int numberOfMembers = members.Length; Object[] data = new Object[numberOfMembers]; MemberInfo mi; for (int i=0; i<numberOfMembers; i++) { mi=members[i]; if (mi==null) { throw new ArgumentNullException("members", Environment.GetResourceString("ArgumentNull_NullMember", i)); } if (mi.MemberType==MemberTypes.Field) { Contract.Assert(mi is RuntimeFieldInfo || mi is SerializationFieldInfo, "[FormatterServices.GetObjectData]mi is RuntimeFieldInfo || mi is SerializationFieldInfo."); RtFieldInfo rfi = mi as RtFieldInfo; if (rfi != null) { rfi.CheckConsistency(obj); data[i] = rfi.UnsafeGetValue(obj); } else { data[i] = ((SerializationFieldInfo)mi).InternalGetValue(obj); } } else { throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMemberInfo")); } } return data; } [System.Security.SecurityCritical] // auto-generated_required [System.Runtime.InteropServices.ComVisible(false)] public static ISerializationSurrogate GetSurrogateForCyclicalReference(ISerializationSurrogate innerSurrogate) { if (innerSurrogate == null) throw new ArgumentNullException("innerSurrogate"); Contract.EndContractBlock(); return new SurrogateForCyclicalReference(innerSurrogate); } /*=============================GetTypeFromAssembly============================== **Action: **Returns: **Arguments: **Exceptions: ==============================================================================*/ [System.Security.SecurityCritical] // auto-generated_required public static Type GetTypeFromAssembly(Assembly assem, String name) { if (assem==null) throw new ArgumentNullException("assem"); Contract.EndContractBlock(); return assem.GetType(name, false, false); } /*============================LoadAssemblyFromString============================ **Action: Loads an assembly from a given string. The current assembly loading story ** is quite confusing. If the assembly is in the fusion cache, we can load it ** using the stringized-name which we transmitted over the wire. If that fails, ** we try for a lookup of the assembly using the simple name which is the first ** part of the assembly name. If we can't find it that way, we'll return null ** as our failure result. **Returns: The loaded assembly or null if it can't be found. **Arguments: assemblyName -- The stringized assembly name. **Exceptions: None ==============================================================================*/ internal static Assembly LoadAssemblyFromString(String assemblyName) { // // Try using the stringized assembly name to load from the fusion cache. // BCLDebug.Trace("SER", "[LoadAssemblyFromString]Looking for assembly: ", assemblyName); Assembly found = Assembly.Load(assemblyName); return found; } internal static Assembly LoadAssemblyFromStringNoThrow(String assemblyName) { try { return LoadAssemblyFromString(assemblyName); } catch (Exception e){ BCLDebug.Trace("SER", "[LoadAssemblyFromString]", e.ToString()); } return null; } internal static string GetClrAssemblyName(Type type, out bool hasTypeForwardedFrom) { if ((object)type == null) { throw new ArgumentNullException("type"); } object[] typeAttributes = type.GetCustomAttributes(typeof(TypeForwardedFromAttribute), false); if (typeAttributes != null && typeAttributes.Length > 0) { hasTypeForwardedFrom = true; TypeForwardedFromAttribute typeForwardedFromAttribute = (TypeForwardedFromAttribute)typeAttributes[0]; return typeForwardedFromAttribute.AssemblyFullName; } else { hasTypeForwardedFrom = false; return type.Assembly.FullName; } } internal static string GetClrTypeFullName(Type type) { if (type.IsArray) { return GetClrTypeFullNameForArray(type); } else { return GetClrTypeFullNameForNonArrayTypes(type); } } static string GetClrTypeFullNameForArray(Type type) { int rank = type.GetArrayRank(); if (rank == 1) { return String.Format(CultureInfo.InvariantCulture, "{0}{1}", GetClrTypeFullName(type.GetElementType()), "[]"); } else { StringBuilder builder = new StringBuilder(GetClrTypeFullName(type.GetElementType())).Append("["); for (int commaIndex = 1; commaIndex < rank; commaIndex++) { builder.Append(","); } builder.Append("]"); return builder.ToString(); } } static string GetClrTypeFullNameForNonArrayTypes(Type type) { if (!type.IsGenericType) { return type.FullName; } Type[] genericArguments = type.GetGenericArguments(); StringBuilder builder = new StringBuilder(type.GetGenericTypeDefinition().FullName).Append("["); bool hasTypeForwardedFrom; foreach (Type genericArgument in genericArguments) { builder.Append("[").Append(GetClrTypeFullName(genericArgument)).Append(", "); builder.Append(GetClrAssemblyName(genericArgument, out hasTypeForwardedFrom)).Append("],"); } //remove the last comma and close typename for generic with a close bracket return builder.Remove(builder.Length - 1, 1).Append("]").ToString(); } } internal sealed class SurrogateForCyclicalReference : ISerializationSurrogate { ISerializationSurrogate innerSurrogate; internal SurrogateForCyclicalReference(ISerializationSurrogate innerSurrogate) { if (innerSurrogate == null) throw new ArgumentNullException("innerSurrogate"); this.innerSurrogate = innerSurrogate; } [System.Security.SecurityCritical] // auto-generated public void GetObjectData(Object obj, SerializationInfo info, StreamingContext context) { innerSurrogate.GetObjectData(obj, info, context); } [System.Security.SecurityCritical] // auto-generated public Object SetObjectData(Object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector) { return innerSurrogate.SetObjectData(obj, info, context, selector); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using Ecosim.SceneEditor; using Ecosim.SceneData; namespace Ecosim.SceneEditor.Helpers { public class HandleBuildings : PanelHelper { protected Scene scene; protected EditorCtrl ctrl; protected readonly MapsPanel parent; protected GUIStyle tabNormal; protected GUIStyle tabSelected; private PanelHelper helper; private bool isDragging; protected string[] buildingCategories; protected EcoTerrainElements.BuildingPrototype[] buildingsInCategory; private int activeCategory = 0; private int activeBuildingInC = 0; protected float angleX = 0f; protected float angleY = 0f; protected float angleZ = 0f; protected HandleParameters handleParams = null; protected Buildings.Building selectedBuilding = null; protected Texture2D renderTex; public HandleBuildings (EditorCtrl ctrl, MapsPanel parent, Scene scene) { this.ctrl = ctrl; this.parent = parent; this.scene = parent.scene; tabNormal = ctrl.listItem; tabSelected = ctrl.listItemSelected; renderTex = new Texture2D (375, 300, TextureFormat.RGB24, false); Setup (); } void SetupBuildingsInCategory () { EcoTerrainElements.EBuildingCategories cat = StringToEBuildingCat (buildingCategories [activeCategory]); List<EcoTerrainElements.BuildingPrototype> list = new List<EcoTerrainElements.BuildingPrototype> (); foreach (EcoTerrainElements.BuildingPrototype bp in EcoTerrainElements.self.buildings) { if (bp.category == cat) { list.Add (bp); } } buildingsInCategory = list.ToArray (); } EcoTerrainElements.EBuildingCategories StringToEBuildingCat (string str) { foreach (EcoTerrainElements.EBuildingCategories cat in System.Enum.GetValues(typeof(EcoTerrainElements.EBuildingCategories))) { if (cat.ToString () == str) { return cat; } } return EcoTerrainElements.EBuildingCategories.EXTRA; } protected virtual void Setup () { EditBuildings.self.StartEditBuildings (scene); TerrainMgr.self.ForceRedraw (); List<string> buildingCatList = new List<string> (); foreach (EcoTerrainElements.EBuildingCategories cat in System.Enum.GetValues(typeof(EcoTerrainElements.EBuildingCategories))) { buildingCatList.Add (cat.ToString ()); } buildingCategories = buildingCatList.ToArray (); SetupBuildingsInCategory (); RenderPreviewTexture (); } /*void RenderPreviewTexture () { (GameObject.FindObjectOfType <MonoBehaviour> () as MonoBehaviour).StartCoroutine (CORenderPreviewTexture()); }*/ //IEnumerator CORenderPreviewTexture () { protected virtual void RenderPreviewTexture () { RenderTileIcons.RenderSettings rs = new RenderTileIcons.RenderSettings (60f, 30f, 120f, 24f); EcoTerrainElements.BuildingPrototype bp = buildingsInCategory[activeBuildingInC]; //yield return new WaitForEndOfFrame (); RenderTileIcons.self.Render (rs, ref renderTex, scene.successionTypes[0].vegetations[0].tiles[0], bp.prefabContainer.mesh, bp.prefabContainer.material); } void ResetEdit () { if (handleParams != null) { handleParams.Disable (); handleParams = null; } EditBuildings.self.StopEditBuildings (scene); TerrainMgr.self.ForceRedraw (); } public virtual bool Render (int mx, int my) { RenderCategory (); RenderBuilding (); RenderRenderedTexture (); RenderTransformControls (); RenderActiveState (); RenderBuildingParameterMap (mx, my); return false; } protected virtual void RenderCategory () { GUILayout.BeginHorizontal (); { GUILayout.Label ("Category", GUILayout.Width (100)); if (GUILayout.Button (buildingCategories [activeCategory], GUILayout.Width (200))) { ctrl.StartSelection (buildingCategories, activeCategory, newIndex => { if (newIndex != activeCategory) { activeCategory = newIndex; SetupBuildingsInCategory (); activeBuildingInC = (buildingsInCategory.Length > 0) ? 0 : -1; RenderPreviewTexture (); } }); } } GUILayout.FlexibleSpace (); GUILayout.EndHorizontal (); } protected virtual void RenderBuilding () { GUILayout.BeginHorizontal (); { GUILayout.Label ("Building", GUILayout.Width (100)); if (activeBuildingInC >= 0) { if (GUILayout.Button (buildingsInCategory [activeBuildingInC].ToString (), GUILayout.Width (200))) { ctrl.StartSelection (buildingsInCategory, activeBuildingInC, newIndex => { if (newIndex != activeBuildingInC) { activeBuildingInC = newIndex; RenderPreviewTexture (); } }); } if (selectedBuilding != null) { if (GUILayout.Button ("Update")) { selectedBuilding.name = buildingsInCategory [activeBuildingInC].name; selectedBuilding.prefab = buildingsInCategory [activeBuildingInC].prefabContainer; EditBuildings.self.BuildingChanged (selectedBuilding); } } } else { GUILayout.Label ("Category is empty."); } GUILayout.FlexibleSpace (); } GUILayout.EndHorizontal (); GUILayout.Label ("Press N to place a new building. Click on a building to edit it."); } protected virtual void RenderRenderedTexture () { GUILayout.BeginHorizontal (ctrl.skin.box); { GUILayout.Label (renderTex, GUIStyle.none); } GUILayout.EndVertical (); } protected virtual void RenderTransformControls () { if (selectedBuilding != null) { bool hasChanged = false; GUILayout.BeginHorizontal (); { GUILayout.Label ("Rotation:", GUILayout.Width (60)); GUILayout.Label ("X", GUILayout.Width (10)); float newX = GUILayout.HorizontalSlider (angleX, -45f, 45f, GUILayout.Width (45)); EcoGUI.FloatField ("", ref newX, 0, null, GUILayout.Width (30)); newX = Mathf.Clamp (newX, -45f, 45f); GUILayout.Label ("Y", GUILayout.Width (10)); float newY = GUILayout.HorizontalSlider (angleY, 0f, 360f, GUILayout.Width (45)); EcoGUI.FloatField ("", ref newY, 0, null, GUILayout.Width (30)); newY = Mathf.Clamp (newY, 0f, 360f); GUILayout.Label ("Z", GUILayout.Width (10)); float newZ = GUILayout.HorizontalSlider (angleZ, -45, 45f, GUILayout.Width (45)); EcoGUI.FloatField ("", ref newZ, 0, null, GUILayout.Width (30)); newZ = Mathf.Clamp (newZ, -45f, 45f); if (newX != angleX) { angleX = Mathf.Round (newX); hasChanged = true; } if (newY != angleY) { angleY = Mathf.Round (newY / 5) * 5; hasChanged = true; } if (newZ != angleZ) { angleZ = Mathf.Round (newZ); hasChanged = true; } GUILayout.FlexibleSpace (); } GUILayout.EndHorizontal (); float level; if (TerrainMgr.TryGetTerrainHeight (selectedBuilding.position, out level)) { GUILayout.BeginHorizontal (); { GUILayout.Label ("Vertical pos:", GUILayout.Width (60)); float pos = selectedBuilding.position.y; float newPos = GUILayout.HorizontalSlider (pos, level - 10f, level + 20f, GUILayout.Width (270)); if (pos != newPos) { selectedBuilding.position.y = newPos; hasChanged = true; } GUILayout.FlexibleSpace (); } GUILayout.EndHorizontal (); } if (hasChanged) { selectedBuilding.rotation = Quaternion.Euler (angleX, angleY, angleZ); EditBuildings.self.BuildingChanged (selectedBuilding); } } } protected virtual void RenderActiveState () { if (selectedBuilding != null) { GUILayout.BeginHorizontal (); { GUILayout.Label ("Building ID:" + selectedBuilding.id); if (GUILayout.Button ("Disabled", (selectedBuilding.isActive) ? tabNormal : tabSelected, GUILayout.Width (100))) { selectedBuilding.isActive = false; selectedBuilding.startsActive = false; } if (GUILayout.Button ("Enabled", (selectedBuilding.isActive) ? tabSelected : tabNormal, GUILayout.Width (100))) { selectedBuilding.isActive = true; selectedBuilding.startsActive = true; } GUILayout.FlexibleSpace (); } GUILayout.EndHorizontal (); } } protected virtual void RenderBuildingParameterMap (int mx, int my) { if (selectedBuilding != null) { Data buildingMap = null; string mapName = Buildings.GetMapNameForBuildingId(selectedBuilding.id); if (scene.progression.HasData (mapName)) { buildingMap = scene.progression.GetData (mapName); } if (buildingMap != null) { GUILayout.BeginHorizontal (); { GUILayout.Label ("Parameter map " + mapName, GUILayout.Width (100)); if (handleParams != null) { if (GUILayout.Button ("Stop Edit")) { handleParams.Disable (); handleParams = null; } } else { if (GUILayout.Button ("Start Edit")) { handleParams = new HandleParameters (ctrl, parent, scene, buildingMap); } } if (GUILayout.Button ("Delete")) { if (handleParams != null) { handleParams.Disable (); handleParams = null; } scene.progression.DeleteData (mapName); } GUILayout.FlexibleSpace (); } GUILayout.EndHorizontal (); } else { GUILayout.BeginHorizontal (); { GUILayout.Label ("Parameter map " + mapName, GUILayout.Width (100)); if (GUILayout.Button ("Create as 1 bit (0..1)")) { scene.progression.AddData (mapName, new SparseBitMap1 (scene)); } if (GUILayout.Button ("Create as 8 bit (0..255)")) { scene.progression.AddData (mapName, new SparseBitMap8 (scene)); } GUILayout.FlexibleSpace (); } GUILayout.EndHorizontal (); } if (handleParams != null) { GUILayout.BeginVertical (ctrl.skin.box); { handleParams.Render (mx, my); GUILayout.Space (3); } GUILayout.EndVertical (); } } } protected virtual void SelectBuilding () { Buildings.Building newlySelected = EditBuildings.self.GetSelection (); if (newlySelected == selectedBuilding) return; if (handleParams != null) { handleParams.Disable (); handleParams = null; } selectedBuilding = newlySelected; } public void Disable () { ResetEdit (); UnityEngine.Object.Destroy (renderTex); } public virtual void Update () { if (handleParams != null) { return; // we're editing building map (parameter map for a building) } bool ctrlKey = Input.GetKey (KeyCode.LeftControl) | Input.GetKey (KeyCode.RightControl); Vector3 mousePos = Input.mousePosition; if ((CameraControl.MouseOverGUI) || Input.GetKey (KeyCode.LeftAlt) || Input.GetKey (KeyCode.RightAlt)) { return; } // New building if (Input.GetKeyDown (KeyCode.N) && (activeBuildingInC >= 0)) { Vector3 hitPoint; if (TerrainMgr.TryScreenToTerrainCoord (mousePos, out hitPoint)) { Buildings.Building newBuilding = new Buildings.Building (scene.buildings.GetNewBuildingID ()); newBuilding.name = buildingsInCategory [activeBuildingInC].name; newBuilding.prefab = buildingsInCategory [activeBuildingInC].prefabContainer; newBuilding.position = hitPoint; newBuilding.scale = Vector3.one; newBuilding.rotation = Quaternion.identity; BuildingCreated (newBuilding); } } // Select building if (Input.GetMouseButtonDown (0) && !ctrlKey) { Ray screenRay = Camera.main.ScreenPointToRay (mousePos); RaycastHit hit; if (Physics.Raycast (screenRay, out hit, 10000f, Layers.M_EDIT1)) { GameObject go = hit.collider.gameObject; Buildings.Building building = EditBuildings.self.GetBuildingForGO (go); // TODO: Don't be able to click buildings that are Action Object buildings BuildingClicked (building); } } // Dragging building else if (Input.GetMouseButton (0) && isDragging) { Vector3 hitPoint; if (TerrainMgr.TryScreenToTerrainCoord (mousePos, out hitPoint)) { selectedBuilding.position = hitPoint; EditBuildings.self.BuildingChanged (selectedBuilding); } } else if (isDragging) { isDragging = false; } // Delete building else if (Input.GetKeyDown (KeyCode.Delete) || Input.GetKeyDown (KeyCode.Backspace)) { Buildings.Building selectedBuilding = EditBuildings.self.GetSelection (); if (selectedBuilding != null) { EditBuildings.self.DestroyBuilding (selectedBuilding); SelectBuilding (); } } } protected virtual void BuildingCreated (Buildings.Building newBuilding) { EditBuildings.self.AddBuilding (newBuilding); EditBuildings.self.MarkBuildingSelected (newBuilding); SelectBuilding (); angleX = 0; angleY = 0; angleZ = 0; } protected virtual void BuildingClicked (Buildings.Building building) { if (building != null) { if (building == selectedBuilding) { // Building was already selected, we start to drag.... isDragging = true; } else { EditBuildings.self.MarkBuildingSelected (building); SelectBuilding (); EcoTerrainElements.BuildingPrototype proto = EcoTerrainElements.GetBuilding (building.name); activeCategory = (int)proto.category; SetupBuildingsInCategory (); for (int i = 0; i < buildingsInCategory.Length; i++) { if (buildingsInCategory [i].prefabContainer == proto.prefabContainer) { activeBuildingInC = i; RenderPreviewTexture (); break; } } Vector3 angles = building.rotation.eulerAngles; angleX = angles.x; angleY = angles.y; angleZ = angles.z; } } else { EditBuildings.self.ClearSelection (); } } } }
using System; using System.Runtime.InteropServices; using System.Security; using BulletSharp.Math; namespace BulletSharp { public class MultiBodyLink { internal IntPtr _native; internal MultiBodyLink(IntPtr native) { _native = native; } public Vector3 GetAxisBottom(int dof) { Vector3 value; btMultibodyLink_getAxisBottom(_native, dof, out value); return value; } public Vector3 GetAxisTop(int dof) { Vector3 value; btMultibodyLink_getAxisTop(_native, dof, out value); return value; } public void SetAxisBottom(int dof, float x, float y, float z) { btMultibodyLink_setAxisBottom(_native, dof, x, y, z); } public void SetAxisBottom(int dof, Vector3 axis) { btMultibodyLink_setAxisBottom2(_native, dof, ref axis); } public void SetAxisTop(int dof, float x, float y, float z) { btMultibodyLink_setAxisTop(_native, dof, x, y, z); } public void SetAxisTop(int dof, Vector3 axis) { btMultibodyLink_setAxisTop2(_native, dof, ref axis); } public void UpdateCacheMultiDof() { btMultibodyLink_updateCacheMultiDof(_native); } /* public void UpdateCacheMultiDof(float pq) { btMultibodyLink_updateCacheMultiDof2(_native, pq._native); } public SpatialMotionVector AbsFrameLocVelocity { get { return btMultibodyLink_getAbsFrameLocVelocity(_native); } set { btMultibodyLink_setAbsFrameLocVelocity(_native, value._native); } } public SpatialMotionVector AbsFrameTotVelocity { get { return btMultibodyLink_getAbsFrameTotVelocity(_native); } set { btMultibodyLink_setAbsFrameTotVelocity(_native, value._native); } } */ public Vector3 AppliedConstraintForce { get { Vector3 value; btMultibodyLink_getAppliedConstraintForce(_native, out value); return value; } set { btMultibodyLink_setAppliedConstraintForce(_native, ref value); } } public Vector3 AppliedConstraintTorque { get { Vector3 value; btMultibodyLink_getAppliedConstraintTorque(_native, out value); return value; } set { btMultibodyLink_setAppliedConstraintTorque(_native, ref value); } } public Vector3 AppliedForce { get { Vector3 value; btMultibodyLink_getAppliedForce(_native, out value); return value; } set { btMultibodyLink_setAppliedForce(_native, ref value); } } public Vector3 AppliedTorque { get { Vector3 value; btMultibodyLink_getAppliedTorque(_native, out value); return value; } set { btMultibodyLink_setAppliedTorque(_native, ref value); } } /* public SpatialMotionVector Axes { get { return btMultibodyLink_getAxes(_native); } } */ public Quaternion CachedRotParentToThis { get { Quaternion value; btMultibodyLink_getCachedRotParentToThis(_native, out value); return value; } set { btMultibodyLink_setCachedRotParentToThis(_native, ref value); } } public Vector3 CachedRVector { get { Vector3 value; btMultibodyLink_getCachedRVector(_native, out value); return value; } set { btMultibodyLink_setCachedRVector(_native, ref value); } } public Matrix CachedWorldTransform { get { Matrix value; btMultibodyLink_getCachedWorldTransform(_native, out value); return value; } set { btMultibodyLink_setCachedWorldTransform(_native, ref value); } } public int CfgOffset { get { return btMultibodyLink_getCfgOffset(_native); } set { btMultibodyLink_setCfgOffset(_native, value); } } public MultiBodyLinkCollider Collider { get { return CollisionObject.GetManaged(btMultibodyLink_getCollider(_native)) as MultiBodyLinkCollider; } set { btMultibodyLink_setCollider(_native, value._native); } } public int DofCount { get { return btMultibodyLink_getDofCount(_native); } set { btMultibodyLink_setDofCount(_native, value); } } public int DofOffset { get { return btMultibodyLink_getDofOffset(_native); } set { btMultibodyLink_setDofOffset(_native, value); } } public Vector3 DVector { get { Vector3 value; btMultibodyLink_getDVector(_native, out value); return value; } set { btMultibodyLink_setDVector(_native, ref value); } } public Vector3 EVector { get { Vector3 value; btMultibodyLink_getEVector(_native, out value); return value; } set { btMultibodyLink_setEVector(_native, ref value); } } public int Flags { get { return btMultibodyLink_getFlags(_native); } set { btMultibodyLink_setFlags(_native, value); } } public Vector3 InertiaLocal { get { Vector3 value; btMultibodyLink_getInertiaLocal(_native, out value); return value; } set { btMultibodyLink_setInertiaLocal(_native, ref value); } } /* public MultiBodyJointFeedback JointFeedback { get { return btMultibodyLink_getJointFeedback(_native); } set { btMultibodyLink_setJointFeedback(_native, value._native); } } public char JointName { get { return btMultibodyLink_getJointName(_native); } set { btMultibodyLink_setJointName(_native, value._native); } } public ScalarArray JointPos { get { return btMultibodyLink_getJointPos(_native); } } public ScalarArray JointTorque { get { return btMultibodyLink_getJointTorque(_native); } } public eFeatherstoneJointType JointType { get { return btMultibodyLink_getJointType(_native); } set { btMultibodyLink_setJointType(_native, value); } } public char LinkName { get { return btMultibodyLink_getLinkName(_native); } set { btMultibodyLink_setLinkName(_native, value._native); } } */ public float Mass { get { return btMultibodyLink_getMass(_native); } set { btMultibodyLink_setMass(_native, value); } } public int Parent { get { return btMultibodyLink_getParent(_native); } set { btMultibodyLink_setParent(_native, value); } } public int PosVarCount { get { return btMultibodyLink_getPosVarCount(_native); } set { btMultibodyLink_setPosVarCount(_native, value); } } public Quaternion ZeroRotParentToThis { get { Quaternion value; btMultibodyLink_getZeroRotParentToThis(_native, out value); return value; } set { btMultibodyLink_setZeroRotParentToThis(_native, ref value); } } [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_getAbsFrameLocVelocity(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_getAbsFrameTotVelocity(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_getAppliedConstraintForce(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_getAppliedConstraintTorque(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_getAppliedForce(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_getAppliedTorque(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btMultibodyLink_getAxes(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_getAxisBottom(IntPtr obj, int dof, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_getAxisTop(IntPtr obj, int dof, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_getCachedRotParentToThis(IntPtr obj, [Out] out Quaternion value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_getCachedRVector(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_getCachedWorldTransform(IntPtr obj, [Out] out Matrix value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btMultibodyLink_getCfgOffset(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btMultibodyLink_getCollider(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btMultibodyLink_getDofCount(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btMultibodyLink_getDofOffset(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_getDVector(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_getEVector(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btMultibodyLink_getFlags(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_getInertiaLocal(IntPtr obj, [Out] out Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btMultibodyLink_getJointFeedback(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btMultibodyLink_getJointName(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btMultibodyLink_getJointPos(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btMultibodyLink_getJointTorque(IntPtr obj); //[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] //static extern eFeatherstoneJointType btMultibodyLink_getJointType(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern IntPtr btMultibodyLink_getLinkName(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern float btMultibodyLink_getMass(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btMultibodyLink_getParent(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern int btMultibodyLink_getPosVarCount(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_getZeroRotParentToThis(IntPtr obj, [Out] out Quaternion value); //[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] //static extern void btMultibodyLink_setAbsFrameLocVelocity(IntPtr obj, SpatialMotionVector value); //[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] //static extern void btMultibodyLink_setAbsFrameTotVelocity(IntPtr obj, SpatialMotionVector value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_setAppliedConstraintForce(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_setAppliedConstraintTorque(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_setAppliedForce(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_setAppliedTorque(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_setAxisBottom(IntPtr obj, int dof, float x, float y, float z); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_setAxisBottom2(IntPtr obj, int dof, [In] ref Vector3 axis); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_setAxisTop(IntPtr obj, int dof, float x, float y, float z); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_setAxisTop2(IntPtr obj, int dof, [In] ref Vector3 axis); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_setCachedRotParentToThis(IntPtr obj, [In] ref Quaternion value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_setCachedRVector(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_setCachedWorldTransform(IntPtr obj, [In] ref Matrix value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_setCfgOffset(IntPtr obj, int value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_setCollider(IntPtr obj, IntPtr value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_setDofCount(IntPtr obj, int value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_setDofOffset(IntPtr obj, int value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_setDVector(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_setEVector(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_setFlags(IntPtr obj, int value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_setInertiaLocal(IntPtr obj, [In] ref Vector3 value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_setJointFeedback(IntPtr obj, IntPtr value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_setJointName(IntPtr obj, IntPtr value); //[DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] //static extern void btMultibodyLink_setJointType(IntPtr obj, eFeatherstoneJointType value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_setLinkName(IntPtr obj, IntPtr value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_setMass(IntPtr obj, float value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_setParent(IntPtr obj, int value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_setPosVarCount(IntPtr obj, int value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_setZeroRotParentToThis(IntPtr obj, [In] ref Quaternion value); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_updateCacheMultiDof(IntPtr obj); [DllImport(Native.Dll, CallingConvention = Native.Conv), SuppressUnmanagedCodeSecurity] static extern void btMultibodyLink_updateCacheMultiDof2(IntPtr obj, IntPtr pq); } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Mail; using System.Net.Security; using System.Text; using System.Threading; using System.Security.Cryptography.X509Certificates; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using Mono.Addins; using Amib.Threading; /***************************************************** * * ScriptsHttpRequests * * Implements the llHttpRequest and http_response * callback. * * Some stuff was already in LSLLongCmdHandler, and then * there was this file with a stub class in it. So, * I am moving some of the objects and functions out of * LSLLongCmdHandler, such as the HttpRequestClass, the * start and stop methods, and setting up pending and * completed queues. These are processed in the * LSLLongCmdHandler polling loop. Similiar to the * XMLRPCModule, since that seems to work. * * //TODO * * This probably needs some throttling mechanism but * it's wide open right now. This applies to both * number of requests and data volume. * * Linden puts all kinds of header fields in the requests. * Not doing any of that: * User-Agent * X-SecondLife-Shard * X-SecondLife-Object-Name * X-SecondLife-Object-Key * X-SecondLife-Region * X-SecondLife-Local-Position * X-SecondLife-Local-Velocity * X-SecondLife-Local-Rotation * X-SecondLife-Owner-Name * X-SecondLife-Owner-Key * * HTTPS support * * Configurable timeout? * Configurable max response size? * Configurable * * **************************************************/ namespace OpenSim.Region.CoreModules.Scripting.HttpRequest { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HttpRequestModule")] public class HttpRequestModule : ISharedRegionModule, IHttpRequestModule { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private object HttpListLock = new object(); private int httpTimeout = 30000; private string m_name = "HttpScriptRequests"; private OutboundUrlFilter m_outboundUrlFilter; private string m_proxyurl = ""; private string m_proxyexcepts = ""; // <request id, HttpRequestClass> private Dictionary<UUID, HttpRequestClass> m_pendingRequests; private Scene m_scene; // private Queue<HttpRequestClass> rpcQueue = new Queue<HttpRequestClass>(); public static SmartThreadPool ThreadPool = null; public HttpRequestModule() { ServicePointManager.ServerCertificateValidationCallback +=ValidateServerCertificate; } public static bool ValidateServerCertificate( object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { // If this is a web request we need to check the headers first // We may want to ignore SSL if (sender is HttpWebRequest) { HttpWebRequest Request = (HttpWebRequest)sender; ServicePoint sp = Request.ServicePoint; // We don't case about encryption, get out of here if (Request.Headers.Get("NoVerifyCert") != null) { return true; } // If there was an upstream cert verification error, bail if ((((int)sslPolicyErrors) & ~4) != 0) return false; // Check for policy and execute it if defined #pragma warning disable 0618 if (ServicePointManager.CertificatePolicy != null) { return ServicePointManager.CertificatePolicy.CheckValidationResult (sp, certificate, Request, 0); } #pragma warning restore 0618 return true; } // If it's not HTTP, trust .NET to check it if ((((int)sslPolicyErrors) & ~4) != 0) return false; return true; } #region IHttpRequestModule Members public UUID MakeHttpRequest(string url, string parameters, string body) { return UUID.Zero; } public UUID StartHttpRequest( uint localID, UUID itemID, string url, List<string> parameters, Dictionary<string, string> headers, string body, out HttpInitialRequestStatus status) { UUID reqID = UUID.Random(); HttpRequestClass htc = new HttpRequestClass(); // Partial implementation: support for parameter flags needed // see http://wiki.secondlife.com/wiki/LlHTTPRequest // // Parameters are expected in {key, value, ... , key, value} if (parameters != null) { string[] parms = parameters.ToArray(); for (int i = 0; i < parms.Length; i += 2) { switch (Int32.Parse(parms[i])) { case (int)HttpRequestConstants.HTTP_METHOD: htc.HttpMethod = parms[i + 1]; break; case (int)HttpRequestConstants.HTTP_MIMETYPE: htc.HttpMIMEType = parms[i + 1]; break; case (int)HttpRequestConstants.HTTP_BODY_MAXLENGTH: // TODO implement me break; case (int)HttpRequestConstants.HTTP_VERIFY_CERT: htc.HttpVerifyCert = (int.Parse(parms[i + 1]) != 0); break; case (int)HttpRequestConstants.HTTP_VERBOSE_THROTTLE: // TODO implement me break; case (int)HttpRequestConstants.HTTP_CUSTOM_HEADER: //Parameters are in pairs and custom header takes //arguments in pairs so adjust for header marker. ++i; //Maximum of 8 headers are allowed based on the //Second Life documentation for llHTTPRequest. for (int count = 1; count <= 8; ++count) { //Not enough parameters remaining for a header? if (parms.Length - i < 2) break; //Have we reached the end of the list of headers? //End is marked by a string with a single digit. //We already know we have at least one parameter //so it is safe to do this check at top of loop. if (Char.IsDigit(parms[i][0])) break; if (htc.HttpCustomHeaders == null) htc.HttpCustomHeaders = new List<string>(); htc.HttpCustomHeaders.Add(parms[i]); htc.HttpCustomHeaders.Add(parms[i+1]); i += 2; } break; case (int)HttpRequestConstants.HTTP_PRAGMA_NO_CACHE: htc.HttpPragmaNoCache = (int.Parse(parms[i + 1]) != 0); break; } } } htc.RequestModule = this; htc.LocalID = localID; htc.ItemID = itemID; htc.Url = url; htc.ReqID = reqID; htc.HttpTimeout = httpTimeout; htc.OutboundBody = body; htc.ResponseHeaders = headers; htc.proxyurl = m_proxyurl; htc.proxyexcepts = m_proxyexcepts; // Same number as default HttpWebRequest.MaximumAutomaticRedirections htc.MaxRedirects = 50; if (StartHttpRequest(htc)) { status = HttpInitialRequestStatus.OK; return htc.ReqID; } else { status = HttpInitialRequestStatus.DISALLOWED_BY_FILTER; return UUID.Zero; } } /// <summary> /// Would a caller to this module be allowed to make a request to the given URL? /// </summary> /// <returns></returns> public bool CheckAllowed(Uri url) { return m_outboundUrlFilter.CheckAllowed(url); } public bool StartHttpRequest(HttpRequestClass req) { if (!CheckAllowed(new Uri(req.Url))) return false; lock (HttpListLock) { m_pendingRequests.Add(req.ReqID, req); } req.Process(); return true; } public void StopHttpRequest(uint m_localID, UUID m_itemID) { if (m_pendingRequests != null) { lock (HttpListLock) { HttpRequestClass tmpReq; if (m_pendingRequests.TryGetValue(m_itemID, out tmpReq)) { tmpReq.Stop(); m_pendingRequests.Remove(m_itemID); } } } } /* * TODO * Not sure how important ordering is is here - the next first * one completed in the list is returned, based soley on its list * position, not the order in which the request was started or * finished. I thought about setting up a queue for this, but * it will need some refactoring and this works 'enough' right now */ public IServiceRequest GetNextCompletedRequest() { lock (HttpListLock) { foreach (UUID luid in m_pendingRequests.Keys) { HttpRequestClass tmpReq; if (m_pendingRequests.TryGetValue(luid, out tmpReq)) { if (tmpReq.Finished) { return tmpReq; } } } } return null; } public void RemoveCompletedRequest(UUID id) { lock (HttpListLock) { HttpRequestClass tmpReq; if (m_pendingRequests.TryGetValue(id, out tmpReq)) { tmpReq.Stop(); tmpReq = null; m_pendingRequests.Remove(id); } } } #endregion #region ISharedRegionModule Members public void Initialise(IConfigSource config) { m_proxyurl = config.Configs["Startup"].GetString("HttpProxy"); m_proxyexcepts = config.Configs["Startup"].GetString("HttpProxyExceptions"); m_outboundUrlFilter = new OutboundUrlFilter("Script HTTP request module", config); int maxThreads = 15; IConfig httpConfig = config.Configs["HttpRequestModule"]; if (httpConfig != null) { maxThreads = httpConfig.GetInt("MaxPoolThreads", maxThreads); } m_pendingRequests = new Dictionary<UUID, HttpRequestClass>(); // First instance sets this up for all sims if (ThreadPool == null) { STPStartInfo startInfo = new STPStartInfo(); startInfo.IdleTimeout = 20000; startInfo.MaxWorkerThreads = maxThreads; startInfo.MinWorkerThreads = 1; startInfo.ThreadPriority = ThreadPriority.BelowNormal; startInfo.StartSuspended = true; startInfo.ThreadPoolName = "ScriptsHttpReq"; ThreadPool = new SmartThreadPool(startInfo); ThreadPool.Start(); } } public void AddRegion(Scene scene) { m_scene = scene; m_scene.RegisterModuleInterface<IHttpRequestModule>(this); } public void RemoveRegion(Scene scene) { scene.UnregisterModuleInterface<IHttpRequestModule>(this); if (scene == m_scene) m_scene = null; } public void PostInitialise() { } public void RegionLoaded(Scene scene) { } public void Close() { } public string Name { get { return m_name; } } public Type ReplaceableInterface { get { return null; } } #endregion } public class HttpRequestClass : IServiceRequest { // Constants for parameters // public const int HTTP_BODY_MAXLENGTH = 2; // public const int HTTP_METHOD = 0; // public const int HTTP_MIMETYPE = 1; // public const int HTTP_VERIFY_CERT = 3; // public const int HTTP_VERBOSE_THROTTLE = 4; // public const int HTTP_CUSTOM_HEADER = 5; // public const int HTTP_PRAGMA_NO_CACHE = 6; /// <summary> /// Module that made this request. /// </summary> public HttpRequestModule RequestModule { get; set; } private bool _finished; public bool Finished { get { return _finished; } } // public int HttpBodyMaxLen = 2048; // not implemented // Parameter members and default values public string HttpMethod = "GET"; public string HttpMIMEType = "text/plain;charset=utf-8"; public int HttpTimeout; public bool HttpVerifyCert = true; public IWorkItemResult WorkItem = null; //public bool HttpVerboseThrottle = true; // not implemented public List<string> HttpCustomHeaders = null; public bool HttpPragmaNoCache = true; // Request info private UUID _itemID; public UUID ItemID { get { return _itemID; } set { _itemID = value; } } private uint _localID; public uint LocalID { get { return _localID; } set { _localID = value; } } public DateTime Next; public string proxyurl; public string proxyexcepts; /// <summary> /// Number of HTTP redirects that this request has been through. /// </summary> public int Redirects { get; private set; } /// <summary> /// Maximum number of HTTP redirects allowed for this request. /// </summary> public int MaxRedirects { get; set; } public string OutboundBody; private UUID _reqID; public UUID ReqID { get { return _reqID; } set { _reqID = value; } } public HttpWebRequest Request; public string ResponseBody; public List<string> ResponseMetadata; public Dictionary<string, string> ResponseHeaders; public int Status; public string Url; public void Process() { _finished = false; lock (HttpRequestModule.ThreadPool) WorkItem = HttpRequestModule.ThreadPool.QueueWorkItem(new WorkItemCallback(StpSendWrapper), null); } private object StpSendWrapper(object o) { SendRequest(); return null; } /* * TODO: More work on the response codes. Right now * returning 200 for success or 499 for exception */ public void SendRequest() { HttpWebResponse response = null; Stream resStream = null; StringBuilder sb = new StringBuilder(); byte[] buf = new byte[8192]; string tempString = null; int count = 0; try { Request = (HttpWebRequest)WebRequest.Create(Url); Request.AllowAutoRedirect = false; //This works around some buggy HTTP Servers like Lighttpd Request.ServicePoint.Expect100Continue = false; Request.Method = HttpMethod; Request.ContentType = HttpMIMEType; if (!HttpVerifyCert) { // We could hijack Connection Group Name to identify // a desired security exception. But at the moment we'll use a dummy header instead. Request.Headers.Add("NoVerifyCert", "true"); } // else // { // Request.ConnectionGroupName="Verify"; // } if (!HttpPragmaNoCache) { Request.Headers.Add("Pragma", "no-cache"); } if (HttpCustomHeaders != null) { for (int i = 0; i < HttpCustomHeaders.Count; i += 2) Request.Headers.Add(HttpCustomHeaders[i], HttpCustomHeaders[i+1]); } if (!string.IsNullOrEmpty(proxyurl)) { if (!string.IsNullOrEmpty(proxyexcepts)) { string[] elist = proxyexcepts.Split(';'); Request.Proxy = new WebProxy(proxyurl, true, elist); } else { Request.Proxy = new WebProxy(proxyurl, true); } } foreach (KeyValuePair<string, string> entry in ResponseHeaders) if (entry.Key.ToLower().Equals("user-agent")) Request.UserAgent = entry.Value; else Request.Headers[entry.Key] = entry.Value; // Encode outbound data if (!string.IsNullOrEmpty(OutboundBody)) { byte[] data = Util.UTF8.GetBytes(OutboundBody); Request.ContentLength = data.Length; using (Stream bstream = Request.GetRequestStream()) bstream.Write(data, 0, data.Length); } Request.Timeout = HttpTimeout; try { // execute the request response = (HttpWebResponse) Request.GetResponse(); } catch (WebException e) { if (e.Status != WebExceptionStatus.ProtocolError) { throw; } response = (HttpWebResponse)e.Response; } Status = (int)response.StatusCode; resStream = response.GetResponseStream(); do { // fill the buffer with data count = resStream.Read(buf, 0, buf.Length); // make sure we read some data if (count != 0) { // translate from bytes to ASCII text tempString = Util.UTF8.GetString(buf, 0, count); // continue building the string sb.Append(tempString); if (sb.Length > 2048) break; } } while (count > 0); // any more data to read? ResponseBody = sb.ToString().Replace("\r", ""); } catch (WebException e) { if (e.Status == WebExceptionStatus.ProtocolError) { HttpWebResponse webRsp = (HttpWebResponse)((WebException)e).Response; Status = (int)webRsp.StatusCode; try { using (Stream responseStream = webRsp.GetResponseStream()) { using (StreamReader reader = new StreamReader(responseStream)) ResponseBody = reader.ReadToEnd(); } } catch { ResponseBody = webRsp.StatusDescription; } } else { Status = (int)OSHttpStatusCode.ClientErrorJoker; ResponseBody = e.Message; } if (ResponseBody == null) ResponseBody = String.Empty; _finished = true; return; } catch (Exception e) { // Don't crash on anything else } finally { if (resStream != null) resStream.Close(); if (response != null) response.Close(); // We need to resubmit if ( (Status == (int)HttpStatusCode.MovedPermanently || Status == (int)HttpStatusCode.Found || Status == (int)HttpStatusCode.SeeOther || Status == (int)HttpStatusCode.TemporaryRedirect)) { if (Redirects >= MaxRedirects) { Status = (int)OSHttpStatusCode.ClientErrorJoker; ResponseBody = "Number of redirects exceeded max redirects"; _finished = true; } else { string location = response.Headers["Location"]; if (location == null) { Status = (int)OSHttpStatusCode.ClientErrorJoker; ResponseBody = "HTTP redirect code but no location header"; _finished = true; } else if (!RequestModule.CheckAllowed(new Uri(location))) { Status = (int)OSHttpStatusCode.ClientErrorJoker; ResponseBody = "URL from HTTP redirect blocked: " + location; _finished = true; } else { Status = 0; Url = response.Headers["Location"]; Redirects++; ResponseBody = null; // m_log.DebugFormat("Redirecting to [{0}]", Url); Process(); } } } else { _finished = true; } } if (ResponseBody == null) ResponseBody = String.Empty; _finished = true; } public void Stop() { try { if (!WorkItem.Cancel()) { WorkItem.Cancel(true); } } catch (Exception) { } } } }
using Microsoft.TeamFoundation.Build.WebApi; using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent; using Microsoft.VisualStudio.Services.Agent.Util; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Microsoft.VisualStudio.Services.Agent.Worker.Build { public sealed class TfsVCSourceProvider : SourceProvider, ISourceProvider { public override string RepositoryType => WellKnownRepositoryTypes.TfsVersionControl; public async Task GetSourceAsync( IExecutionContext executionContext, ServiceEndpoint endpoint, CancellationToken cancellationToken) { // Validate args. ArgUtil.NotNull(executionContext, nameof(executionContext)); ArgUtil.NotNull(endpoint, nameof(endpoint)); // Create the tf command manager. var tf = HostContext.CreateService<ITfsVCCommandManager>(); tf.CancellationToken = cancellationToken; tf.Endpoint = endpoint; tf.ExecutionContext = executionContext; // Check if the administrator accepted the license terms of the TEE EULA when configuring the agent. AgentSettings settings = HostContext.GetService<IConfigurationStore>().GetSettings(); if (tf.Features.HasFlag(TfsVCFeatures.Eula) && settings.AcceptTeeEula) { // Check if the "tf eula -accept" command needs to be run for the current user. bool skipEula = false; try { skipEula = tf.TestEulaAccepted(); } catch (Exception ex) { Trace.Error("Unexpected exception while testing whether the TEE EULA has been accepted for the current security user."); Trace.Error(ex); } if (!skipEula) { // Run the command "tf eula -accept". try { await tf.EulaAsync(); } catch (Exception ex) { Trace.Error(ex); executionContext.Warning(ex.Message); } } } // Get the workspaces. ITfsVCWorkspace[] tfWorkspaces = await tf.WorkspacesAsync(); // Determine the workspace name. string buildDirectory = executionContext.Variables.Agent_BuildDirectory; ArgUtil.NotNullOrEmpty(buildDirectory, nameof(buildDirectory)); string workspaceName = $"ws_{Path.GetFileName(buildDirectory)}_{settings.AgentId}"; executionContext.Variables.Set(Constants.Variables.Build.RepoTfvcWorkspace, workspaceName); // Get the definition mappings. DefinitionWorkspaceMapping[] definitionMappings = JsonConvert.DeserializeObject<DefinitionWorkspaceMappings>(endpoint.Data[WellKnownEndpointData.TfvcWorkspaceMapping])?.Mappings; // Determine the sources directory. string sourcesDirectory = executionContext.Variables.Build_SourcesDirectory; ArgUtil.NotNullOrEmpty(sourcesDirectory, nameof(sourcesDirectory)); // Attempt to re-use an existing workspace if the command manager supports scorch // or if clean is not specified. ITfsVCWorkspace existingTFWorkspace = null; bool clean = endpoint.Data.ContainsKey(WellKnownEndpointData.Clean) && StringUtil.ConvertToBoolean(endpoint.Data[WellKnownEndpointData.Clean], defaultValue: false); if (tf.Features.HasFlag(TfsVCFeatures.Scorch) || !clean) { existingTFWorkspace = MatchExactWorkspace( tfWorkspaces: tfWorkspaces, name: workspaceName, definitionMappings: definitionMappings, sourcesDirectory: sourcesDirectory); if (existingTFWorkspace != null) { if (tf.Features.HasFlag(TfsVCFeatures.GetFromUnmappedRoot)) { // Undo pending changes. ITfsVCStatus tfStatus = await tf.StatusAsync(localPath: sourcesDirectory); if (tfStatus?.HasPendingChanges ?? false) { await tf.UndoAsync(localPath: sourcesDirectory); // Cleanup remaining files/directories from pend adds. tfStatus.AllAdds .OrderByDescending(x => x.LocalItem) // Sort descending so nested items are deleted before their parent is deleted. .ToList() .ForEach(x => { executionContext.Output(StringUtil.Loc("Deleting", x.LocalItem)); IOUtil.Delete(x.LocalItem, cancellationToken); }); } } else { // Perform "undo" for each map. foreach (DefinitionWorkspaceMapping definitionMapping in definitionMappings ?? new DefinitionWorkspaceMapping[0]) { if (definitionMapping.MappingType == DefinitionMappingType.Map) { // Check the status. string localPath = ResolveMappingLocalPath(definitionMapping, sourcesDirectory); ITfsVCStatus tfStatus = await tf.StatusAsync(localPath: localPath); if (tfStatus?.HasPendingChanges ?? false) { // Undo. await tf.UndoAsync(localPath: localPath); // Cleanup remaining files/directories from pend adds. tfStatus.AllAdds .OrderByDescending(x => x.LocalItem) // Sort descending so nested items are deleted before their parent is deleted. .ToList() .ForEach(x => { executionContext.Output(StringUtil.Loc("Deleting", x.LocalItem)); IOUtil.Delete(x.LocalItem, cancellationToken); }); } } } } // Scorch. if (clean) { await tf.ScorchAsync(); } } } // Create a new workspace. if (existingTFWorkspace == null) { // Remove any conflicting workspaces. await RemoveConflictingWorkspacesAsync( tf: tf, tfWorkspaces: tfWorkspaces, name: workspaceName, directory: sourcesDirectory); // Recreate the sources directory. executionContext.Debug($"Deleting: '{sourcesDirectory}'."); IOUtil.DeleteDirectory(sourcesDirectory, cancellationToken); Directory.CreateDirectory(sourcesDirectory); // Create the workspace. await tf.WorkspaceNewAsync(); // Remove the default mapping. if (tf.Features.HasFlag(TfsVCFeatures.DefaultWorkfoldMap)) { await tf.WorkfoldUnmapAsync("$/"); } // Sort the definition mappings. definitionMappings = (definitionMappings ?? new DefinitionWorkspaceMapping[0]) .OrderBy(x => x.NormalizedServerPath?.Length ?? 0) // By server path length. .ToArray() ?? new DefinitionWorkspaceMapping[0]; // Add the definition mappings to the workspace. foreach (DefinitionWorkspaceMapping definitionMapping in definitionMappings) { switch (definitionMapping.MappingType) { case DefinitionMappingType.Cloak: // Add the cloak. await tf.WorkfoldCloakAsync(serverPath: definitionMapping.ServerPath); break; case DefinitionMappingType.Map: // Add the mapping. await tf.WorkfoldMapAsync( serverPath: definitionMapping.ServerPath, localPath: ResolveMappingLocalPath(definitionMapping, sourcesDirectory)); break; default: throw new NotSupportedException(); } } } if (tf.Features.HasFlag(TfsVCFeatures.GetFromUnmappedRoot)) { // Get. await tf.GetAsync(localPath: sourcesDirectory); } else { // Perform "get" for each map. foreach (DefinitionWorkspaceMapping definitionMapping in definitionMappings ?? new DefinitionWorkspaceMapping[0]) { if (definitionMapping.MappingType == DefinitionMappingType.Map) { await tf.GetAsync(localPath: ResolveMappingLocalPath(definitionMapping, sourcesDirectory)); } } } string shelvesetName = executionContext.Variables.Build_SourceTfvcShelveset; if (!string.IsNullOrEmpty(shelvesetName)) { // Get the shelveset details. ITfsVCShelveset tfShelveset = null; string gatedShelvesetName = executionContext.Variables.Build_GatedShelvesetName; if (!string.IsNullOrEmpty(gatedShelvesetName)) { tfShelveset = await tf.ShelvesetsAsync(shelveset: shelvesetName); // The command throws if the shelveset is not found. // This assertion should never fail. ArgUtil.NotNull(tfShelveset, nameof(tfShelveset)); } // Unshelve. await tf.UnshelveAsync(shelveset: shelvesetName); if (!string.IsNullOrEmpty(gatedShelvesetName)) { // Create the comment file for reshelve. StringBuilder comment = new StringBuilder(tfShelveset.Comment ?? string.Empty); if (!(executionContext.Variables.Build_GatedRunCI ?? true)) { if (comment.Length > 0) { comment.AppendLine(); } comment.Append(Constants.Build.NoCICheckInComment); } string commentFile = null; try { commentFile = Path.GetTempFileName(); // TODO: FIGURE OUT WHAT ENCODING TF EXPECTS File.WriteAllText(path: commentFile, contents: comment.ToString()); // Reshelve. await tf.ShelveAsync(shelveset: gatedShelvesetName, commentFile: commentFile); } finally { // Cleanup the comment file. if (File.Exists(commentFile)) { File.Delete(commentFile); } } } } } public Task PostJobCleanupAsync(IExecutionContext executionContext, ServiceEndpoint endpoint) { return Task.CompletedTask; } public override string GetLocalPath(IExecutionContext executionContext, ServiceEndpoint endpoint, string path) { ArgUtil.NotNull(executionContext, nameof(executionContext)); ArgUtil.NotNull(executionContext.Variables, nameof(executionContext.Variables)); ArgUtil.NotNull(endpoint, nameof(endpoint)); path = path ?? string.Empty; if (path.StartsWith("$/") || path.StartsWith(@"$\")) { // Create the tf command manager. var tf = HostContext.CreateService<ITfsVCCommandManager>(); tf.CancellationToken = CancellationToken.None; tf.Endpoint = endpoint; tf.ExecutionContext = executionContext; // Attempt to resolve the path. string localPath = tf.ResolvePath(serverPath: path); if (!string.IsNullOrEmpty(localPath)) { return localPath; } } // Return the original path. return path; } private static string ResolveMappingLocalPath(DefinitionWorkspaceMapping definitionMapping, string sourcesDirectory) { string relativePath = (definitionMapping.LocalPath ?? string.Empty) .Trim('/', '\\'); if (Path.DirectorySeparatorChar == '\\') { relativePath = relativePath.Replace('/', Path.DirectorySeparatorChar); } else { relativePath = relativePath.Replace('\\', Path.DirectorySeparatorChar); } return Path.Combine(sourcesDirectory, relativePath); } private ITfsVCWorkspace MatchExactWorkspace(ITfsVCWorkspace[] tfWorkspaces, string name, DefinitionWorkspaceMapping[] definitionMappings, string sourcesDirectory) { ArgUtil.NotNullOrEmpty(name, nameof(name)); ArgUtil.NotNullOrEmpty(sourcesDirectory, nameof(sourcesDirectory)); // Short-circuit early if the sources directory is empty. // // Consider the sources directory to be empty if it only contains a .tf directory exists. This can // indicate the workspace is in a corrupted state and the tf commands (e.g. status) will not return // reliable information. An easy way to reproduce this is to delete the workspace directory, then // run "tf status" on that workspace. The .tf directory will be recreated but the contents will be // in a corrupted state. if (!Directory.Exists(sourcesDirectory) || !Directory.EnumerateFileSystemEntries(sourcesDirectory).Any(x => !x.EndsWith($"{Path.DirectorySeparatorChar}.tf"))) { Trace.Info($"Sources directory does not exist or is empty."); return null; } string machineName = Environment.MachineName; Trace.Info("Attempting to find a matching workspace."); Trace.Info($"Expected workspace name '{name}', machine name '{machineName}', number of mappings '{definitionMappings?.Length ?? 0}'."); foreach (ITfsVCWorkspace tfWorkspace in tfWorkspaces ?? new ITfsVCWorkspace[0]) { // Compare the works name, machine name, and number of mappings. Trace.Info($"Candidate workspace name '{tfWorkspace.Name}', machine name '{tfWorkspace.Computer}', number of mappings '{tfWorkspace.Mappings?.Length ?? 0}'."); if (!string.Equals(tfWorkspace.Name, name, StringComparison.Ordinal) || !string.Equals(tfWorkspace.Computer, machineName, StringComparison.Ordinal) || (tfWorkspace.Mappings?.Length ?? 0) != (definitionMappings?.Length ?? 0)) { continue; } // TODO: Is there such a thing as a single level cloak? // Sort the TF mappings. List<ITfsVCMapping> sortedTFMappings = (tfWorkspace.Mappings ?? new ITfsVCMapping[0]) .OrderBy(x => !x.Cloak) // Cloaks first .ThenBy(x => !x.Recursive) // Then recursive maps .ThenBy(x => x.ServerPath) // Then sort by server path .ToList(); sortedTFMappings.ForEach(x => Trace.Info($"TF mapping: cloak '{x.Cloak}', recursive '{x.Recursive}', server path '{x.ServerPath}', local path '{x.LocalPath}'.")); // Sort the definition mappings. List<DefinitionWorkspaceMapping> sortedDefinitionMappings = (definitionMappings ?? new DefinitionWorkspaceMapping[0]) .OrderBy(x => x.MappingType != DefinitionMappingType.Cloak) // Cloaks first .ThenBy(x => !x.Recursive) // Then recursive maps .ThenBy(x => x.NormalizedServerPath) // Then sort by the normalized server path .ToList(); sortedDefinitionMappings.ForEach(x => Trace.Info($"Definition mapping: cloak '{x.MappingType == DefinitionMappingType.Cloak}', recursive '{x.Recursive}', server path '{x.NormalizedServerPath}', local path '{ResolveMappingLocalPath(x, sourcesDirectory)}'.")); // Compare the mappings, bool allMatch = true; for (int i = 0 ; i < sortedTFMappings.Count ; i++) { ITfsVCMapping tfMapping = sortedTFMappings[i]; DefinitionWorkspaceMapping definitionMapping = sortedDefinitionMappings[i]; if (tfMapping.Cloak) { // The TF mapping is a cloak. // Verify the definition mapping is a cloak and the server paths match. if (definitionMapping.MappingType != DefinitionMappingType.Cloak || !string.Equals(tfMapping.ServerPath, definitionMapping.ServerPath, StringComparison.Ordinal)) { allMatch = false; // Mapping comparison failed. break; } } else { // The TF mapping is a map. // Verify the definition mapping is a map and the local paths match. if (definitionMapping.MappingType != DefinitionMappingType.Map || !string.Equals(tfMapping.LocalPath, ResolveMappingLocalPath(definitionMapping, sourcesDirectory), StringComparison.Ordinal)) { allMatch = false; // Mapping comparison failed. break; } if (tfMapping.Recursive) { // The TF mapping is a recursive map. // Verify the server paths match. if (!string.Equals(tfMapping.ServerPath, definitionMapping.ServerPath, StringComparison.Ordinal)) { allMatch = false; // Mapping comparison failed. break; } } else { // The TF mapping is a single-level map. // Verify the definition mapping is a single-level map and the normalized server paths match. if (definitionMapping.Recursive || !string.Equals(tfMapping.ServerPath, definitionMapping.NormalizedServerPath, StringComparison.Ordinal)) { allMatch = false; // Mapping comparison failed. break; } } } } if (allMatch) { Trace.Info("Matching workspace found."); return tfWorkspace; } } Trace.Info("Matching workspace not found."); return null; } private async Task RemoveConflictingWorkspacesAsync(ITfsVCCommandManager tf, ITfsVCWorkspace[] tfWorkspaces, string name, string directory) { // Validate the args. ArgUtil.NotNullOrEmpty(name, nameof(name)); ArgUtil.NotNullOrEmpty(directory, nameof(directory)); // Fixup the directory. directory = directory.TrimEnd('/', '\\'); ArgUtil.NotNullOrEmpty(directory, nameof(directory)); string directorySlash = $"{directory}{Path.DirectorySeparatorChar}"; foreach (ITfsVCWorkspace tfWorkspace in tfWorkspaces ?? new ITfsVCWorkspace[0]) { // Attempt to match the workspace by name. if (string.Equals(tfWorkspace.Name, name, StringComparison.OrdinalIgnoreCase)) { // Try deleting the workspace from the server. if (!(await tf.TryWorkspaceDeleteAsync(tfWorkspace))) { // Otherwise fallback to deleting the workspace from the local computer. await tf.WorkspacesRemoveAsync(tfWorkspace); } // Continue iterating over the rest of the workspaces. continue; } // Attempt to match the workspace by local path. foreach (ITfsVCMapping tfMapping in tfWorkspace.Mappings ?? new ITfsVCMapping[0]) { // Skip cloaks. if (tfMapping.Cloak) { continue; } if (string.Equals(tfMapping.LocalPath, directory, StringComparison.Ordinal) || (tfMapping.LocalPath ?? string.Empty).StartsWith(directorySlash, StringComparison.Ordinal)) { // Try deleting the workspace from the server. if (!(await tf.TryWorkspaceDeleteAsync(tfWorkspace))) { // Otherwise fallback to deleting the workspace from the local computer. await tf.WorkspacesRemoveAsync(tfWorkspace); } // Break out of this nested for loop only. // Continue iterating over the rest of the workspaces. break; } } } } public sealed class DefinitionWorkspaceMappings { public DefinitionWorkspaceMapping[] Mappings { get; set; } } public sealed class DefinitionWorkspaceMapping { public string LocalPath { get; set; } public DefinitionMappingType MappingType { get; set; } // Remove the trailing "/*" from the single-level mapping server path. public string NormalizedServerPath => Recursive ? ServerPath : ServerPath.Substring(0, ServerPath.Length - 2); // Returns true if the path does not end with "/*". public bool Recursive => !(ServerPath ?? string.Empty).EndsWith("/*"); public string ServerPath { get; set; } } public enum DefinitionMappingType { Cloak, Map, } } }
using Codex.ObjectModel; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Codex { /// <summary> /// Represents a source file with associated semantic bindings /// </summary> public partial interface IBoundSourceFile : IBoundSourceInfo { /// <summary> /// The source file /// </summary> ISourceFile SourceFile { get; } /// <summary> /// Gets the commit referencing the file. /// </summary> ICommit Commit { get; } /// <summary> /// Gets the repository containing the file. /// </summary> IRepository Repo { get; } /// <summary> /// The lines in the source file /// </summary> //[Include(ObjectStage.Analysis)] //IReadOnlyList<string> SourceFileContentLines { get; } } public interface IBoundSourceInfo { /// <summary> /// The number of references in the file /// </summary> [CoerceGet(typeof(int?))] int ReferenceCount { get; } /// <summary> /// The number of definitions in the file /// </summary> [CoerceGet(typeof(int?))] int DefinitionCount { get; } /// <summary> /// The language of the file /// TODO: Remove /// </summary> string Language { get; } /// <summary> /// References for the document. Sorted. May overlap. /// </summary> [ReadOnlyList] [SearchBehavior(SearchBehavior.None)] [Include(ObjectStage.Analysis)] IReadOnlyList<IReferenceSpan> References { get; } // TODO: Should this be just the symbol /// <summary> /// Definitions for the document. Sorted. No overlap? /// </summary> [SearchBehavior(SearchBehavior.None)] IReadOnlyList<IDefinitionSpan> Definitions { get; } /// <summary> /// Classifications for the document. Sorted by start index. No overlap. /// </summary> [ReadOnlyList] [SearchBehavior(SearchBehavior.None)] [Include(ObjectStage.Analysis)] IReadOnlyList<IClassificationSpan> Classifications { get; } /// <summary> /// Outlining regions for the document. May overlap. /// </summary> [SearchBehavior(SearchBehavior.None)] IReadOnlyList<IOutliningRegion> OutliningRegions { get; } /// <summary> /// Indicates that the file should be excluded from text search /// </summary> [SearchBehavior(SearchBehavior.Term)] bool ExcludeFromSearch { get; } } /// <summary> /// Information about a source file as defined by the source control provider /// </summary> public interface ISourceControlFileInfo { /// <summary> /// Unique id for the source file content as defined by the source control provider (i.e. git SHA) /// </summary> [SearchBehavior(SearchBehavior.NormalizedKeyword)] string SourceControlContentId { get; } } public interface ISourceFileInfo : IRepoFileScopeEntity, ISourceControlFileInfo, // TODO: Remove and join source files by repository relative path with mapping from repository relative path to (project, project relative path) IProjectFileScopeEntity { /// <summary> /// The number of lines in the file /// </summary> int Lines { get; } /// <summary> /// The size of the file in bytes /// </summary> int Size { get; } /// <summary> /// The language of the file /// TODO: Remove /// </summary> string Language { get; } /// <summary> /// The web address of the file. TODO: Remove? Is repo relative path enough? /// </summary> string WebAddress { get; } /// <summary> /// The encoding used for the file /// </summary> IEncodingDescription Encoding { get; } /// <summary> /// Extensible key value properties for the document. /// </summary> [Include(ObjectStage.Analysis)] IPropertyMap Properties { get; } } /// <summary> /// Describes encoding so that file may be reconstituted in a byte-identical form /// </summary> public interface IEncodingDescription { /// <summary> /// The name of the encoding /// </summary> string Name { get; } /// <summary> /// The encoding preamble /// </summary> byte[] Preamble { get; } } public interface ISourceFileBase { /// <summary> /// The information about the source file /// </summary> ISourceFileInfo Info { get; } /// <summary> /// Indicates that the file should be excluded from text search /// </summary> [SearchBehavior(SearchBehavior.Term)] bool ExcludeFromSearch { get; } } /// <summary> /// Defines text contents of a file and associated data /// </summary> public interface ISourceFile : ISourceFileBase { /// <summary> /// The content of the file /// </summary> [SearchBehavior(SearchBehavior.FullText)] string Content { get; } } /// <summary> /// Defines text contents of a file and associated data /// </summary> public interface IChunkedSourceFile : ISourceFileBase { /// <summary> /// The content of the file /// </summary> IReadOnlyList<IChunkReference> Chunks { get; } } public interface IChunkReference { [SearchBehavior(SearchBehavior.Term)] string Id { get; } int StartLineNumber { get; } } /// <summary> /// Defines a chunk of text lines from a source file /// </summary>s public interface ISourceFileContentChunk { /// <summary> /// Lines defined as part of the chunk /// </summary> [SearchBehavior(SearchBehavior.FullText)] IReadOnlyList<string> ContentLines { get; } } public interface IOutliningRegion { string Kind { get; } /// <summary> /// Defines the region containing the header text of the outlining region /// </summary> ILineSpan Header { get; } /// <summary> /// Defines the region containing the collapsible content region of the outlining region /// </summary> ILineSpan Content { get; } } public interface IDefinitionSpan : ISpan { /// <summary> /// The definition symbol referred to by the span /// </summary> IDefinitionSymbol Definition { get; } /// <summary> /// Gets the definitions for parameters /// </summary> [ReadOnlyList] IReadOnlyList<IParameterDefinitionSpan> Parameters { get; } } /// <summary> /// A specialized definition span referring to a parameter of a method/property /// </summary> public interface IParameterDefinitionSpan : ILineSpan { // TODO: This is in theory implied from the ordering in IDefinitionSpan.Parameters. So no need // to serialize if its the same as the implied value /// <summary> /// The index of the parameter in the list of parameters for the method /// </summary> int ParameterIndex { get; } /// <summary> /// The name of the parameter /// </summary> string Name { get; } } public interface IReferenceSpan : ISymbolSpan { /// <summary> /// Gets the symbol id of the definition which provides this reference /// (i.e. method definition for interface implementation) /// </summary> SymbolId RelatedDefinition { get; } /// <summary> /// The reference symbol referred to by the span /// </summary> IReferenceSymbol Reference { get; } /// <summary> /// Gets the references to parameters /// </summary> [ReadOnlyList] IReadOnlyList<IParameterReferenceSpan> Parameters { get; } } /// <summary> /// A specialized reference span referring to a parameter to a method/property /// </summary> public interface IParameterReferenceSpan : ISymbolSpan { /// <summary> /// The index of the parameter in the list of parameters for the method /// </summary> [SearchBehavior(SearchBehavior.Term)] int ParameterIndex { get; } } /// <summary> /// Defines a classified span of text /// </summary> public interface IClassificationSpan : ISpan { /// <summary> /// The default classification color for the span. This is used for /// contexts where a mapping from classification id to color is not /// available. /// </summary> int DefaultClassificationColor { get; } /// <summary> /// The classification identifier for the span /// </summary> string Classification { get; } // TODO: Should locals be moved from here? /// <summary> /// The identifier to the local group of spans which refer to the same common symbol /// </summary> int LocalGroupId { get; } } public interface ISymbolSpan : ITextLineSpan { } public interface ITextLineSpan : ILineSpan { /// <summary> /// The line text /// TODO: It would be nice to not store this here and instead apply it as a join /// </summary> string LineSpanText { get; } } public interface ILineSpan : ISpan { /// <summary> /// The 0-based index of the line containing the span /// </summary> [Include(ObjectStage.None)] [CoerceGet(typeof(int?))] int LineIndex { get; } /// <summary> /// The 1-based line number of the line containing the span /// </summary> [CoerceGet(typeof(int?))] int LineNumber { get; } /// <summary> /// The character position where the span starts in the line text /// </summary> int LineSpanStart { get; } /// <summary> /// If positive, the offset of the line span from the beginning of the line /// If negative, the offset of the linespan from the end of the next line /// </summary> int LineOffset { get; } } public static class SpanExtensions { public static int LineSpanEnd(this ILineSpan lineSpan) { return lineSpan.LineSpanStart + lineSpan.Length; } public static string GetSegment(this ITextLineSpan lineSpan) { return lineSpan.LineSpanText.Substring(lineSpan.LineSpanStart, lineSpan.Length); } public static int End(this ISpan lineSpan) { return lineSpan.Start + lineSpan.Length; } public static bool SpanEquals(this ISpan span, ISpan otherSpan) { if (span == null) { return false; } return span.Start == otherSpan.Start && span.Length == otherSpan.Length; } public static bool Contains(this ISpan span, ISpan otherSpan) { if (span == null || otherSpan == null) { return false; } return otherSpan.Start >= span.Start && otherSpan.End() <= span.End(); } } public interface ISpan { /// <summary> /// The absolute character offset of the span within the document /// </summary> int Start { get; } /// <summary> /// The length of the span /// </summary> int Length { get; } } }
/* * 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.Concurrent; using System.Linq; using QuantConnect.Data; using QuantConnect.Data.Market; namespace QuantConnect.Securities { /// <summary> /// Base class caching caching spot for security data and any other temporary properties. /// </summary> /// <remarks> /// This class is virtually unused and will soon be made obsolete. /// This comment made in a remark to prevent obsolete errors in all users algorithms /// </remarks> public class SecurityCache { // this is used to prefer quote bar data over the tradebar data private DateTime _lastQuoteBarUpdate; private BaseData _lastData; private readonly ConcurrentDictionary<Type, BaseData> _dataByType = new ConcurrentDictionary<Type, BaseData>(); /// <summary> /// Gets the most recent price submitted to this cache /// </summary> public decimal Price { get; private set; } /// <summary> /// Gets the most recent open submitted to this cache /// </summary> public decimal Open { get; private set; } /// <summary> /// Gets the most recent high submitted to this cache /// </summary> public decimal High { get; private set; } /// <summary> /// Gets the most recent low submitted to this cache /// </summary> public decimal Low { get; private set; } /// <summary> /// Gets the most recent close submitted to this cache /// </summary> public decimal Close { get; private set; } /// <summary> /// Gets the most recent bid submitted to this cache /// </summary> public decimal BidPrice { get; private set; } /// <summary> /// Gets the most recent ask submitted to this cache /// </summary> public decimal AskPrice { get; private set; } /// <summary> /// Gets the most recent bid size submitted to this cache /// </summary> public decimal BidSize { get; private set; } /// <summary> /// Gets the most recent ask size submitted to this cache /// </summary> public decimal AskSize { get; private set; } /// <summary> /// Gets the most recent volume submitted to this cache /// </summary> public decimal Volume { get; private set; } /// <summary> /// Gets the most recent open interest submitted to this cache /// </summary> public long OpenInterest { get; private set; } /// <summary> /// Add a new market data point to the local security cache for the current market price. /// Rules: /// Don't cache fill forward data. /// Always return the last observation. /// If two consecutive data has the same time stamp and one is Quotebars and the other Tradebar, prioritize the Quotebar. /// </summary> public void AddData(BaseData data) { var openInterest = data as OpenInterest; if (openInterest != null) { OpenInterest = (long)openInterest.Value; return; } // Only cache non fill-forward data. if (data.IsFillForward) return; // Always keep track of the last obesrvation _dataByType[data.GetType()] = data; // don't set _lastData if receive quotebar then tradebar w/ same end time. this // was implemented to grant preference towards using quote data in the fill // models and provide a level of determinism on the values exposed via the cache. if (_lastData == null || _lastQuoteBarUpdate != data.EndTime || data.DataType != MarketDataType.TradeBar ) { _lastData = data; } var tick = data as Tick; if (tick != null) { if (tick.Value != 0) Price = tick.Value; if (tick.BidPrice != 0) BidPrice = tick.BidPrice; if (tick.BidSize != 0) BidSize = tick.BidSize; if (tick.AskPrice != 0) AskPrice = tick.AskPrice; if (tick.AskSize != 0) AskSize = tick.AskSize; if (tick.Quantity != 0) Volume = tick.Quantity; return; } var bar = data as IBar; if (bar != null) { if (_lastQuoteBarUpdate != data.EndTime) { if (bar.Open != 0) Open = bar.Open; if (bar.High != 0) High = bar.High; if (bar.Low != 0) Low = bar.Low; if (bar.Close != 0) { Price = bar.Close; Close = bar.Close; } } var tradeBar = bar as TradeBar; if (tradeBar != null) { if (tradeBar.Volume != 0) Volume = tradeBar.Volume; } var quoteBar = bar as QuoteBar; if (quoteBar != null) { _lastQuoteBarUpdate = quoteBar.EndTime; if (quoteBar.Ask != null && quoteBar.Ask.Close != 0) AskPrice = quoteBar.Ask.Close; if (quoteBar.Bid != null && quoteBar.Bid.Close != 0) BidPrice = quoteBar.Bid.Close; if (quoteBar.LastBidSize != 0) BidSize = quoteBar.LastBidSize; if (quoteBar.LastAskSize != 0) AskSize = quoteBar.LastAskSize; } } else { Price = data.Price; } } /// <summary> /// Get last data packet recieved for this security /// </summary> /// <returns>BaseData type of the security</returns> public BaseData GetData() { return _lastData; } /// <summary> /// Get last data packet recieved for this security of the specified ty[e /// </summary> /// <typeparam name="T">The data type</typeparam> /// <returns>The last data packet, null if none received of type</returns> public T GetData<T>() where T : BaseData { BaseData data; _dataByType.TryGetValue(typeof(T), out data); return data as T; } /// <summary> /// Reset cache storage and free memory /// </summary> public void Reset() { _dataByType.Clear(); } } }
// 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.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a source code document that is part of a project. /// It provides access to the source text, parsed syntax tree and the corresponding semantic model. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] public partial class Document : TextDocument { private readonly DocumentState _state; private WeakReference<SemanticModel> _model; private Task<SyntaxTree> _syntaxTreeResultTask; internal Document(Project project, DocumentState state) { Contract.ThrowIfNull(project); Contract.ThrowIfNull(state); this.Project = project; _state = state; } internal DocumentState State { get { return _state; } } internal override TextDocumentState GetDocumentState() { return _state; } /// <summary> /// The kind of source code this document contains. /// </summary> public SourceCodeKind SourceCodeKind { get { return _state.SourceCodeKind; } } /// <summary> /// Get the current syntax tree for the document if the text is already loaded and the tree is already parsed. /// In almost all cases, you should call <see cref="GetSyntaxTreeAsync"/> to fetch the tree, which will parse the tree /// if it's not already parsed. /// </summary> public bool TryGetSyntaxTree(out SyntaxTree syntaxTree) { // if we already have cache, use it if (_syntaxTreeResultTask != null) { syntaxTree = _syntaxTreeResultTask.Result; } if (!_state.TryGetSyntaxTree(out syntaxTree)) { return false; } // cache the result if it is not already cached if (_syntaxTreeResultTask == null) { var result = Task.FromResult(syntaxTree); Interlocked.CompareExchange(ref _syntaxTreeResultTask, result, null); } return true; } /// <summary> /// Get the current syntax tree version for the document if the text is already loaded and the tree is already parsed. /// In almost all cases, you should call <see cref="GetSyntaxVersionAsync"/> to fetch the version, which will load the tree /// if it's not already available. /// </summary> public bool TryGetSyntaxVersion(out VersionStamp version) { version = default(VersionStamp); VersionStamp textVersion; if (!this.TryGetTextVersion(out textVersion)) { return false; } var projectVersion = this.Project.Version; version = textVersion.GetNewerVersion(projectVersion); return true; } /// <summary> /// Gets the version of the document's top level signature if it is already loaded and available. /// </summary> internal bool TryGetTopLevelChangeTextVersion(out VersionStamp version) { return _state.TryGetTopLevelChangeTextVersion(out version); } /// <summary> /// Gets the version of the syntax tree. This is generally the newer of the text version and the project's version. /// </summary> public async Task<VersionStamp> GetSyntaxVersionAsync(CancellationToken cancellationToken = default(CancellationToken)) { var textVersion = await this.GetTextVersionAsync(cancellationToken).ConfigureAwait(false); var projectVersion = this.Project.Version; return textVersion.GetNewerVersion(projectVersion); } /// <summary> /// <code>true</code> if this Document supports providing data through the /// <see cref="GetSyntaxTreeAsync"/> and <see cref="GetSyntaxRootAsync"/> methods. /// /// If <code>false</code> then these methods will return <code>null</code> instead. /// </summary> public bool SupportsSyntaxTree { get { return this.State.SupportsSyntaxTree; } } /// <summary> /// <code>true</code> if this Document supports providing data through the /// <see cref="GetSemanticModelAsync"/> method. /// /// If <code>false</code> then this method will return <code>null</code> instead. /// </summary> public bool SupportsSemanticModel { get { return this.SupportsSyntaxTree && this.Project.SupportsCompilation; } } private Task<SyntaxTree> GetExistingSyntaxTreeTask() { if (_syntaxTreeResultTask != null) { return _syntaxTreeResultTask; } // First see if we already have a semantic model computed. If so, we can just return // that syntax tree. SemanticModel semanticModel; if (TryGetSemanticModel(out semanticModel)) { // PERF: This is a hot code path, so cache the result to reduce allocations var result = Task.FromResult(semanticModel.SyntaxTree); Interlocked.CompareExchange(ref _syntaxTreeResultTask, result, null); return _syntaxTreeResultTask; } // second, see whether we already computed the tree, if we already did, return the cache SyntaxTree tree; if (TryGetSyntaxTree(out tree)) { if (_syntaxTreeResultTask == null) { var result = Task.FromResult(tree); Interlocked.CompareExchange(ref _syntaxTreeResultTask, result, null); } return _syntaxTreeResultTask; } return null; } /// <summary> /// Gets the <see cref="SyntaxTree" /> for this document asynchronously. /// </summary> public Task<SyntaxTree> GetSyntaxTreeAsync(CancellationToken cancellationToken = default(CancellationToken)) { // If the language doesn't support getting syntax trees for a document, then bail out // immediately. if (!this.SupportsSyntaxTree) { return SpecializedTasks.Default<SyntaxTree>(); } var syntaxTreeTask = GetExistingSyntaxTreeTask(); if (syntaxTreeTask != null) { return syntaxTreeTask; } // we can't cache this result, since internally it uses AsyncLazy which // care about cancellation token return _state.GetSyntaxTreeAsync(cancellationToken); } internal SyntaxTree GetSyntaxTreeSynchronously(CancellationToken cancellationToken) { if (!this.SupportsSyntaxTree) { return null; } // if we already have a stask for getting this syntax tree, and the task // has completed, then we can just return that value. var syntaxTreeTask = GetExistingSyntaxTreeTask(); if (syntaxTreeTask?.Status == TaskStatus.RanToCompletion) { return syntaxTreeTask.Result; } // Otherwise defer to our state to get this value. return _state.GetSyntaxTree(cancellationToken); } /// <summary> /// Gets the root node of the current syntax tree if the syntax tree has already been parsed and the tree is still cached. /// In almost all cases, you should call <see cref="GetSyntaxRootAsync"/> to fetch the root node, which will parse /// the document if necessary. /// </summary> public bool TryGetSyntaxRoot(out SyntaxNode root) { root = null; SyntaxTree tree; return this.TryGetSyntaxTree(out tree) && tree.TryGetRoot(out root) && root != null; } /// <summary> /// Gets the root node of the syntax tree asynchronously. /// </summary> public async Task<SyntaxNode> GetSyntaxRootAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (!this.SupportsSyntaxTree) { return null; } var tree = await this.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); return await tree.GetRootAsync(cancellationToken).ConfigureAwait(false); } /// <summary> /// Only for features that absolutely must run synchronously (probably because they're /// on the UI thread). Right now, the only feature this is for is Outlining as VS will /// block on that feature from the UI thread when a document is opened. /// </summary> internal SyntaxNode GetSyntaxRootSynchronously(CancellationToken cancellationToken) { if (!this.SupportsSyntaxTree) { return null; } var tree = this.GetSyntaxTreeSynchronously(cancellationToken); return tree.GetRoot(cancellationToken); } /// <summary> /// Gets the current semantic model for this document if the model is already computed and still cached. /// In almost all cases, you should call <see cref="GetSemanticModelAsync"/>, which will compute the semantic model /// if necessary. /// </summary> public bool TryGetSemanticModel(out SemanticModel semanticModel) { semanticModel = null; return _model != null && _model.TryGetTarget(out semanticModel); } /// <summary> /// Gets the semantic model for this document asynchronously. /// </summary> public async Task<SemanticModel> GetSemanticModelAsync(CancellationToken cancellationToken = default(CancellationToken)) { try { if (!this.SupportsSemanticModel) { return null; } SemanticModel semanticModel; if (this.TryGetSemanticModel(out semanticModel)) { return semanticModel; } var syntaxTree = await this.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var compilation = await this.Project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); var result = compilation.GetSemanticModel(syntaxTree); Contract.ThrowIfNull(result); // first try set the cache if it has not been set var original = Interlocked.CompareExchange(ref _model, new WeakReference<SemanticModel>(result), null); // okay, it is first time. if (original == null) { return result; } // it looks like someone has set it. try to reuse same semantic model if (original.TryGetTarget(out semanticModel)) { return semanticModel; } // it looks like cache is gone. reset the cache. original.SetTarget(result); return result; } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Creates a new instance of this document updated to have the source code kind specified. /// </summary> public Document WithSourceCodeKind(SourceCodeKind kind) { return this.Project.Solution.WithDocumentSourceCodeKind(this.Id, kind).GetDocument(this.Id); } /// <summary> /// Creates a new instance of this document updated to have the text specified. /// </summary> public Document WithText(SourceText text) { return this.Project.Solution.WithDocumentText(this.Id, text, PreservationMode.PreserveIdentity).GetDocument(this.Id); } /// <summary> /// Creates a new instance of this document updated to have a syntax tree rooted by the specified syntax node. /// </summary> public Document WithSyntaxRoot(SyntaxNode root) { return this.Project.Solution.WithDocumentSyntaxRoot(this.Id, root, PreservationMode.PreserveIdentity).GetDocument(this.Id); } /// <summary> /// Get the text changes between this document and a prior version of the same document. /// The changes, when applied to the text of the old document, will produce the text of the current document. /// </summary> public async Task<IEnumerable<TextChange>> GetTextChangesAsync(Document oldDocument, CancellationToken cancellationToken = default(CancellationToken)) { try { using (Logger.LogBlock(FunctionId.Workspace_Document_GetTextChanges, this.Name, cancellationToken)) { if (oldDocument == this) { // no changes return SpecializedCollections.EmptyEnumerable<TextChange>(); } if (this.Id != oldDocument.Id) { throw new ArgumentException(WorkspacesResources.The_specified_document_is_not_a_version_of_this_document); } // first try to see if text already knows its changes IList<TextChange> textChanges = null; SourceText text; SourceText oldText; if (this.TryGetText(out text) && oldDocument.TryGetText(out oldText)) { if (text == oldText) { return SpecializedCollections.EmptyEnumerable<TextChange>(); } var container = text.Container; if (container != null) { textChanges = text.GetTextChanges(oldText).ToList(); // if changes are significant (not the whole document being replaced) then use these changes if (textChanges.Count > 1 || (textChanges.Count == 1 && textChanges[0].Span != new TextSpan(0, oldText.Length))) { return textChanges; } } } // get changes by diffing the trees if (this.SupportsSyntaxTree) { var tree = await this.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var oldTree = await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); return tree.GetChanges(oldTree); } text = await this.GetTextAsync(cancellationToken).ConfigureAwait(false); oldText = await oldDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); return text.GetTextChanges(oldText).ToList(); } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Gets the list of <see cref="DocumentId"/>s that are linked to this /// <see cref="Document" />. <see cref="Document"/>s are considered to be linked if they /// share the same <see cref="TextDocument.FilePath" />. This <see cref="DocumentId"/> is excluded from the /// result. /// </summary> public ImmutableArray<DocumentId> GetLinkedDocumentIds() { var documentIdsWithPath = this.Project.Solution.GetDocumentIdsWithFilePath(this.FilePath); var filteredDocumentIds = this.Project.Solution.FilterDocumentIdsByLanguage(documentIdsWithPath, this.Project.Language).ToImmutableArray(); return filteredDocumentIds.Remove(this.Id); } /// <summary> /// Creates a branched version of this document that has its semantic model frozen in whatever state it is available at the time, /// assuming a background process is constructing the semantics asynchronously. Repeated calls to this method may return /// documents with increasingly more complete semantics. /// /// Use this method to gain access to potentially incomplete semantics quickly. /// </summary> internal async Task<Document> WithFrozenPartialSemanticsAsync(CancellationToken cancellationToken) { var solution = this.Project.Solution; var workspace = solution.Workspace; // only produce doc with frozen semantics if this document is part of the workspace's // primary branch and there is actual background compilation going on, since w/o // background compilation the semantics won't be moving toward completeness. Also, // ensure that the project that this document is part of actually supports compilations, // as partial semantics don't make sense otherwise. if (solution.BranchId == workspace.PrimaryBranchId && workspace.PartialSemanticsEnabled && this.Project.SupportsCompilation) { var newSolution = await this.Project.Solution.WithFrozenPartialCompilationIncludingSpecificDocumentAsync(this.Id, cancellationToken).ConfigureAwait(false); return newSolution.GetDocument(this.Id); } else { return this; } } private string GetDebuggerDisplay() { return this.Name; } /// <summary> /// Returns the options that should be applied to this document. This consists of global options from <see cref="Solution.Options"/>, /// merged with any settings the user has specified at the solution, project, and document levels. /// </summary> public DocumentOptionSet Options { get { // TODO: merge with document-specific options return new DocumentOptionSet(Project.Solution.Options, Project.Language); } } } }
using System; using Esprima.Ast; using Jint.Extensions; using Jint.Native; using Jint.Runtime.Environments; using Jint.Runtime.Interop; using Jint.Runtime.References; using System.Collections.Concurrent; using System.Numerics; using System.Reflection; namespace Jint.Runtime.Interpreter.Expressions { internal sealed class JintUnaryExpression : JintExpression { private readonly record struct OperatorKey(string OperatorName, Type Operand); private static readonly ConcurrentDictionary<OperatorKey, MethodDescriptor> _knownOperators = new(); private readonly JintExpression _argument; private readonly UnaryOperator _operator; private JintUnaryExpression(Engine engine, UnaryExpression expression) : base(expression) { _argument = Build(engine, expression.Argument); _operator = expression.Operator; } internal static JintExpression Build(Engine engine, UnaryExpression expression) { if (expression.Operator == UnaryOperator.Minus && expression.Argument is Literal literal) { var value = JintLiteralExpression.ConvertToJsValue(literal); if (!(value is null)) { // valid for caching return new JintConstantExpression(expression, EvaluateMinus(value)); } } return new JintUnaryExpression(engine, expression); } public override Completion GetValue(EvaluationContext context) { // need to notify correct node when taking shortcut context.LastSyntaxNode = _expression; return Completion.Normal(EvaluateJsValue(context), _expression.Location); } protected override ExpressionResult EvaluateInternal(EvaluationContext context) { return NormalCompletion(EvaluateJsValue(context)); } private JsValue EvaluateJsValue(EvaluationContext context) { var engine = context.Engine; switch (_operator) { case UnaryOperator.Plus: { var v = _argument.GetValue(context).Value; if (context.OperatorOverloadingAllowed && TryOperatorOverloading(context, v, "op_UnaryPlus", out var result)) { return result; } return TypeConverter.ToNumber(v); } case UnaryOperator.Minus: { var v = _argument.GetValue(context).Value; if (context.OperatorOverloadingAllowed && TryOperatorOverloading(context, v, "op_UnaryNegation", out var result)) { return result; } return EvaluateMinus(v); } case UnaryOperator.BitwiseNot: { var v = _argument.GetValue(context).Value; if (context.OperatorOverloadingAllowed && TryOperatorOverloading(context, v, "op_OnesComplement", out var result)) { return result; } var value = TypeConverter.ToNumeric(v); if (value.IsNumber()) { return JsNumber.Create(~TypeConverter.ToInt32(value)); } return JsBigInt.Create(~value.AsBigInt()); } case UnaryOperator.LogicalNot: { var v = _argument.GetValue(context).Value; if (context.OperatorOverloadingAllowed && TryOperatorOverloading(context, v, "op_LogicalNot", out var result)) { return result; } return !TypeConverter.ToBoolean(v) ? JsBoolean.True : JsBoolean.False; } case UnaryOperator.Delete: // https://262.ecma-international.org/5.1/#sec-11.4.1 if (_argument.Evaluate(context).Value is not Reference r) { return JsBoolean.True; } if (r.IsUnresolvableReference()) { if (r.IsStrictReference()) { ExceptionHelper.ThrowSyntaxError(engine.Realm, "Delete of an unqualified identifier in strict mode."); } engine._referencePool.Return(r); return JsBoolean.True; } var referencedName = r.GetReferencedName(); if (r.IsPropertyReference()) { if (r.IsSuperReference()) { ExceptionHelper.ThrowReferenceError(engine.Realm, r); } var o = TypeConverter.ToObject(engine.Realm, r.GetBase()); var deleteStatus = o.Delete(referencedName); if (!deleteStatus) { if (r.IsStrictReference()) { ExceptionHelper.ThrowTypeError(engine.Realm, $"Cannot delete property '{referencedName}' of {o}"); } if (StrictModeScope.IsStrictModeCode && !r.GetBase().AsObject().GetProperty(referencedName).Configurable) { ExceptionHelper.ThrowTypeError(engine.Realm, $"Cannot delete property '{referencedName}' of {o}"); } } engine._referencePool.Return(r); return deleteStatus ? JsBoolean.True : JsBoolean.False; } if (r.IsStrictReference()) { ExceptionHelper.ThrowSyntaxError(engine.Realm); } var bindings = r.GetBase().TryCast<EnvironmentRecord>(); var property = referencedName; engine._referencePool.Return(r); return bindings.DeleteBinding(property.ToString()) ? JsBoolean.True : JsBoolean.False; case UnaryOperator.Void: _argument.GetValue(context); return Undefined.Instance; case UnaryOperator.TypeOf: { var result = _argument.Evaluate(context); JsValue v; if (result.Value is Reference rf) { if (rf.IsUnresolvableReference()) { engine._referencePool.Return(rf); return JsString.UndefinedString; } v = engine.GetValue(rf, true); } else { v = (JsValue) result.Value; } if (v.IsUndefined()) { return JsString.UndefinedString; } if (v.IsNull()) { return JsString.ObjectString; } switch (v.Type) { case Types.Boolean: return JsString.BooleanString; case Types.Number: return JsString.NumberString; case Types.BigInt: return JsString.BigIntString; case Types.String: return JsString.StringString; case Types.Symbol: return JsString.SymbolString; } if (v.IsCallable) { return JsString.FunctionString; } return JsString.ObjectString; } default: ExceptionHelper.ThrowArgumentException(); return null; } } private static JsValue EvaluateMinus(JsValue value) { if (value.IsInteger()) { var asInteger = value.AsInteger(); if (asInteger != 0) { return JsNumber.Create(asInteger * -1); } } value = TypeConverter.ToNumeric(value); if (value.IsNumber()) { var n = ((JsNumber) value)._value; return double.IsNaN(n) ? JsNumber.DoubleNaN : JsNumber.Create(n * -1); } var bigInt = value.AsBigInt(); return JsBigInt.Create(BigInteger.Negate(bigInt)); } internal static bool TryOperatorOverloading(EvaluationContext context, JsValue value, string clrName, out JsValue result) { var operand = value.ToObject(); if (operand != null) { var operandType = operand.GetType(); var arguments = new[] { value }; var key = new OperatorKey(clrName, operandType); var method = _knownOperators.GetOrAdd(key, _ => { MethodInfo foundMethod = null; foreach (var x in operandType.GetOperatorOverloadMethods()) { if (x.Name == clrName && x.GetParameters().Length == 1) { foundMethod = x; break; } } if (foundMethod != null) { return new MethodDescriptor(foundMethod); } return null; }); if (method != null) { result = method.Call(context.Engine, null, arguments); return true; } } result = null; return false; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Net; using System.Net.Http.Formatting; using System.Web; using System.Web.Hosting; using System.Web.Http; using System.Web.Routing; using Kudu.Contracts.Infrastructure; using Kudu.Contracts.Jobs; using Kudu.Contracts.Settings; using Kudu.Contracts.SiteExtensions; using Kudu.Contracts.SourceControl; using Kudu.Contracts.Tracing; using Kudu.Core; using Kudu.Core.Commands; using Kudu.Core.Deployment; using Kudu.Core.Deployment.Generator; using Kudu.Core.Hooks; using Kudu.Core.Infrastructure; using Kudu.Core.Jobs; using Kudu.Core.Settings; using Kudu.Core.SiteExtensions; using Kudu.Core.SourceControl; using Kudu.Core.SourceControl.Git; using Kudu.Core.SSHKey; using Kudu.Core.Tracing; using Kudu.Services.Diagnostics; using Kudu.Services.GitServer; using Kudu.Services.Infrastructure; using Kudu.Services.Performance; using Kudu.Services.ServiceHookHandlers; using Kudu.Services.SSHKey; using Kudu.Services.Web.Infrastructure; using Kudu.Services.Web.Services; using Kudu.Services.Web.Tracing; using Microsoft.AspNet.SignalR; using Ninject; using Ninject.Activation; using Ninject.Web.Common; using XmlSettings; [assembly: WebActivator.PreApplicationStartMethod(typeof(Kudu.Services.Web.App_Start.NinjectServices), "Start")] [assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(Kudu.Services.Web.App_Start.NinjectServices), "Stop")] namespace Kudu.Services.Web.App_Start { public static class NinjectServices { /// <summary> /// Root directory that contains the VS target files /// </summary> private const string SdkRootDirectory = "msbuild"; private static readonly Bootstrapper _bootstrapper = new Bootstrapper(); // Due to a bug in Ninject we can't use Dispose to clean up LockFile so we shut it down manually private static DeploymentLockFile _deploymentLock; private static event Action Shutdown; /// <summary> /// Starts the application /// </summary> public static void Start() { HttpApplication.RegisterModule(typeof(OnePerRequestHttpModule)); HttpApplication.RegisterModule(typeof(NinjectHttpModule)); _bootstrapper.Initialize(CreateKernel); } /// <summary> /// Stops the application. /// </summary> public static void Stop() { if (Shutdown != null) { Shutdown(); } if (_deploymentLock != null) { _deploymentLock.TerminateAsyncLocks(); _deploymentLock = null; } _bootstrapper.ShutDown(); } /// <summary> /// Creates the kernel that will manage your application. /// </summary> /// <returns>The created kernel.</returns> private static IKernel CreateKernel() { var kernel = new StandardKernel(); kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel); kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>(); kernel.Components.Add<INinjectHttpApplicationPlugin, NinjectHttpApplicationPlugin>(); RegisterServices(kernel); return kernel; } /// <summary> /// Load your modules or register your services here! /// </summary> /// <param name="kernel">The kernel.</param> [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "")] private static void RegisterServices(IKernel kernel) { var serverConfiguration = new ServerConfiguration(); // Make sure %HOME% is correctly set EnsureHomeEnvironmentVariable(); IEnvironment environment = GetEnvironment(); // Per request environment kernel.Bind<IEnvironment>().ToMethod(context => GetEnvironment(context.Kernel.Get<IDeploymentSettingsManager>())) .InRequestScope(); // General kernel.Bind<HttpContextBase>().ToMethod(context => new HttpContextWrapper(HttpContext.Current)) .InRequestScope(); kernel.Bind<IServerConfiguration>().ToConstant(serverConfiguration); kernel.Bind<IBuildPropertyProvider>().ToConstant(new BuildPropertyProvider()); System.Func<ITracer> createTracerThunk = () => GetTracer(environment, kernel); System.Func<ILogger> createLoggerThunk = () => GetLogger(environment, kernel); // First try to use the current request profiler if any, otherwise create a new one var traceFactory = new TracerFactory(() => TraceServices.CurrentRequestTracer ?? createTracerThunk()); kernel.Bind<ITracer>().ToMethod(context => TraceServices.CurrentRequestTracer ?? NullTracer.Instance); kernel.Bind<ITraceFactory>().ToConstant(traceFactory); TraceServices.SetTraceFactory(createTracerThunk, createLoggerThunk); // Setup the deployment lock string lockPath = Path.Combine(environment.SiteRootPath, Constants.LockPath); string deploymentLockPath = Path.Combine(lockPath, Constants.DeploymentLockFile); string statusLockPath = Path.Combine(lockPath, Constants.StatusLockFile); string sshKeyLockPath = Path.Combine(lockPath, Constants.SSHKeyLockFile); string hooksLockPath = Path.Combine(lockPath, Constants.HooksLockFile); _deploymentLock = new DeploymentLockFile(deploymentLockPath, kernel.Get<ITraceFactory>()); _deploymentLock.InitializeAsyncLocks(); var statusLock = new LockFile(statusLockPath, kernel.Get<ITraceFactory>()); var sshKeyLock = new LockFile(sshKeyLockPath, kernel.Get<ITraceFactory>()); var hooksLock = new LockFile(hooksLockPath, kernel.Get<ITraceFactory>()); kernel.Bind<IOperationLock>().ToConstant(sshKeyLock).WhenInjectedInto<SSHKeyController>(); kernel.Bind<IOperationLock>().ToConstant(statusLock).WhenInjectedInto<DeploymentStatusManager>(); kernel.Bind<IOperationLock>().ToConstant(hooksLock).WhenInjectedInto<WebHooksManager>(); kernel.Bind<IOperationLock>().ToConstant(_deploymentLock); kernel.Bind<IAnalytics>().ToMethod(context => new Analytics(context.Kernel.Get<IDeploymentSettingsManager>(), context.Kernel.Get<ITracer>(), environment.AnalyticsPath)); var shutdownDetector = new ShutdownDetector(); shutdownDetector.Initialize(); IDeploymentSettingsManager noContextDeploymentsSettingsManager = new DeploymentSettingsManager(new XmlSettings.Settings(GetSettingsPath(environment))); // Trace shutdown event // Cannot use shutdownDetector.Token.Register because of race condition // with NinjectServices.Stop via WebActivator.ApplicationShutdownMethodAttribute Shutdown += () => TraceShutdown(environment, noContextDeploymentsSettingsManager); // LogStream service // The hooks and log stream start endpoint are low traffic end-points. Re-using it to avoid creating another lock var logStreamManagerLock = hooksLock; kernel.Bind<LogStreamManager>().ToMethod(context => new LogStreamManager(Path.Combine(environment.RootPath, Constants.LogFilesPath), context.Kernel.Get<IEnvironment>(), context.Kernel.Get<IDeploymentSettingsManager>(), context.Kernel.Get<ITracer>(), shutdownDetector, logStreamManagerLock)); kernel.Bind<InfoRefsController>().ToMethod(context => new InfoRefsController(t => context.Kernel.Get(t))) .InRequestScope(); kernel.Bind<CustomGitRepositoryHandler>().ToMethod(context => new CustomGitRepositoryHandler(t => context.Kernel.Get(t))) .InRequestScope(); // Deployment Service kernel.Bind<ISettings>().ToMethod(context => new XmlSettings.Settings(GetSettingsPath(environment))) .InRequestScope(); kernel.Bind<IDeploymentSettingsManager>().To<DeploymentSettingsManager>() .InRequestScope(); kernel.Bind<IDeploymentStatusManager>().To<DeploymentStatusManager>() .InRequestScope(); kernel.Bind<ISiteBuilderFactory>().To<SiteBuilderFactory>() .InRequestScope(); kernel.Bind<IWebHooksManager>().To<WebHooksManager>() .InRequestScope(); var noContextTraceFactory = new TracerFactory(() => GetTracerWithoutContext(environment, noContextDeploymentsSettingsManager)); ITriggeredJobsManager triggeredJobsManager = new TriggeredJobsManager( noContextTraceFactory, kernel.Get<IEnvironment>(), kernel.Get<IDeploymentSettingsManager>(), kernel.Get<IAnalytics>(), kernel.Get<IWebHooksManager>()); kernel.Bind<ITriggeredJobsManager>().ToConstant(triggeredJobsManager) .InTransientScope(); IContinuousJobsManager continuousJobManager = new ContinuousJobsManager( noContextTraceFactory, kernel.Get<IEnvironment>(), kernel.Get<IDeploymentSettingsManager>(), kernel.Get<IAnalytics>()); kernel.Bind<IContinuousJobsManager>().ToConstant(continuousJobManager) .InTransientScope(); kernel.Bind<ILogger>().ToMethod(context => GetLogger(environment, context.Kernel)) .InRequestScope(); kernel.Bind<IRepository>().ToMethod(context => new GitExeRepository(context.Kernel.Get<IEnvironment>(), context.Kernel.Get<IDeploymentSettingsManager>(), context.Kernel.Get<ITraceFactory>())) .InRequestScope(); kernel.Bind<IDeploymentManager>().To<DeploymentManager>() .InRequestScope(); kernel.Bind<ISSHKeyManager>().To<SSHKeyManager>() .InRequestScope(); kernel.Bind<IRepositoryFactory>().ToMethod(context => _deploymentLock.RepositoryFactory = new RepositoryFactory(context.Kernel.Get<IEnvironment>(), context.Kernel.Get<IDeploymentSettingsManager>(), context.Kernel.Get<ITraceFactory>(), context.Kernel.Get<HttpContextBase>())) .InRequestScope(); kernel.Bind<IApplicationLogsReader>().To<ApplicationLogsReader>() .InSingletonScope(); // Git server kernel.Bind<IDeploymentEnvironment>().To<DeploymentEnvrionment>(); kernel.Bind<IGitServer>().ToMethod(context => new GitExeServer(context.Kernel.Get<IEnvironment>(), _deploymentLock, GetRequestTraceFile(context.Kernel), context.Kernel.Get<IRepositoryFactory>(), context.Kernel.Get<IDeploymentEnvironment>(), context.Kernel.Get<IDeploymentSettingsManager>(), context.Kernel.Get<ITraceFactory>())) .InRequestScope(); // Git Servicehook parsers kernel.Bind<IServiceHookHandler>().To<GenericHandler>().InRequestScope(); kernel.Bind<IServiceHookHandler>().To<GitHubHandler>().InRequestScope(); kernel.Bind<IServiceHookHandler>().To<BitbucketHandler>().InRequestScope(); kernel.Bind<IServiceHookHandler>().To<DropboxHandler>().InRequestScope(); kernel.Bind<IServiceHookHandler>().To<CodePlexHandler>().InRequestScope(); kernel.Bind<IServiceHookHandler>().To<CodebaseHqHandler>().InRequestScope(); kernel.Bind<IServiceHookHandler>().To<GitlabHqHandler>().InRequestScope(); kernel.Bind<IServiceHookHandler>().To<GitHubCompatHandler>().InRequestScope(); kernel.Bind<IServiceHookHandler>().To<KilnHgHandler>().InRequestScope(); // SiteExtensions kernel.Bind<ISiteExtensionManager>().To<SiteExtensionManager>().InRequestScope(); // Command executor kernel.Bind<ICommandExecutor>().ToMethod(context => GetCommandExecutor(environment, context)) .InRequestScope(); MigrateSite(environment, noContextDeploymentsSettingsManager); RegisterRoutes(kernel, RouteTable.Routes); // Register the default hubs route: ~/signalr GlobalHost.DependencyResolver = new SignalRNinjectDependencyResolver(kernel); RouteTable.Routes.MapConnection<PersistentCommandController>("commandstream", "/api/commandstream"); RouteTable.Routes.MapHubs("/api/filesystemhub", new HubConfiguration()); } public class SignalRNinjectDependencyResolver : DefaultDependencyResolver { private readonly IKernel _kernel; public SignalRNinjectDependencyResolver(IKernel kernel) { _kernel = kernel; } public override object GetService(Type serviceType) { return _kernel.TryGet(serviceType) ?? base.GetService(serviceType); } public override IEnumerable<object> GetServices(Type serviceType) { return System.Linq.Enumerable.Concat(_kernel.GetAll(serviceType), base.GetServices(serviceType)); } } public static void RegisterRoutes(IKernel kernel, RouteCollection routes) { var configuration = kernel.Get<IServerConfiguration>(); GlobalConfiguration.Configuration.Formatters.Clear(); GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.LocalOnly; var jsonFormatter = new JsonMediaTypeFormatter(); GlobalConfiguration.Configuration.Formatters.Add(jsonFormatter); GlobalConfiguration.Configuration.DependencyResolver = new NinjectWebApiDependencyResolver(kernel); GlobalConfiguration.Configuration.Filters.Add(new TraceExceptionFilterAttribute()); // Git Service routes.MapHttpRoute("git-info-refs-root", "info/refs", new { controller = "InfoRefs", action = "Execute" }); routes.MapHttpRoute("git-info-refs", configuration.GitServerRoot + "/info/refs", new { controller = "InfoRefs", action = "Execute" }); // Push url routes.MapHandler<ReceivePackHandler>(kernel, "git-receive-pack-root", "git-receive-pack"); routes.MapHandler<ReceivePackHandler>(kernel, "git-receive-pack", configuration.GitServerRoot + "/git-receive-pack"); // Fetch Hook routes.MapHandler<FetchHandler>(kernel, "fetch", "deploy"); // Clone url routes.MapHandler<UploadPackHandler>(kernel, "git-upload-pack-root", "git-upload-pack"); routes.MapHandler<UploadPackHandler>(kernel, "git-upload-pack", configuration.GitServerRoot + "/git-upload-pack"); // Custom GIT repositories, which can be served from any directory that has a git repo routes.MapHandler<CustomGitRepositoryHandler>(kernel, "git-custom-repository", "git/{*path}"); // Scm (deployment repository) routes.MapHttpRouteDual("scm-info", "scm/info", new { controller = "LiveScm", action = "GetRepositoryInfo" }); routes.MapHttpRouteDual("scm-clean", "scm/clean", new { controller = "LiveScm", action = "Clean" }); routes.MapHttpRouteDual("scm-delete", "scm", new { controller = "LiveScm", action = "Delete" }, new { verb = new HttpMethodConstraint("DELETE") }); // Scm files editor routes.MapHttpRouteDual("scm-get-files", "scmvfs/{*path}", new { controller = "LiveScmEditor", action = "GetItem" }, new { verb = new HttpMethodConstraint("GET", "HEAD") }); routes.MapHttpRouteDual("scm-put-files", "scmvfs/{*path}", new { controller = "LiveScmEditor", action = "PutItem" }, new { verb = new HttpMethodConstraint("PUT") }); routes.MapHttpRouteDual("scm-delete-files", "scmvfs/{*path}", new { controller = "LiveScmEditor", action = "DeleteItem" }, new { verb = new HttpMethodConstraint("DELETE") }); // Live files editor routes.MapHttpRouteDual("vfs-get-files", "vfs/{*path}", new { controller = "Vfs", action = "GetItem" }, new { verb = new HttpMethodConstraint("GET", "HEAD") }); routes.MapHttpRouteDual("vfs-put-files", "vfs/{*path}", new { controller = "Vfs", action = "PutItem" }, new { verb = new HttpMethodConstraint("PUT") }); routes.MapHttpRouteDual("vfs-delete-files", "vfs/{*path}", new { controller = "Vfs", action = "DeleteItem" }, new { verb = new HttpMethodConstraint("DELETE") }); // Zip file handler routes.MapHttpRouteDual("zip-get-files", "zip/{*path}", new { controller = "Zip", action = "GetItem" }, new { verb = new HttpMethodConstraint("GET", "HEAD") }); routes.MapHttpRouteDual("zip-put-files", "zip/{*path}", new { controller = "Zip", action = "PutItem" }, new { verb = new HttpMethodConstraint("PUT") }); // Live Command Line routes.MapHttpRouteDual("execute-command", "command", new { controller = "Command", action = "ExecuteCommand" }, new { verb = new HttpMethodConstraint("POST") }); // Deployments routes.MapHttpRouteDual("all-deployments", "deployments", new { controller = "Deployment", action = "GetDeployResults" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpRouteDual("one-deployment-get", "deployments/{id}", new { controller = "Deployment", action = "GetResult" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpRouteDual("one-deployment-put", "deployments/{id}", new { controller = "Deployment", action = "Deploy", id = RouteParameter.Optional }, new { verb = new HttpMethodConstraint("PUT") }); routes.MapHttpRouteDual("one-deployment-delete", "deployments/{id}", new { controller = "Deployment", action = "Delete" }, new { verb = new HttpMethodConstraint("DELETE") }); routes.MapHttpRouteDual("one-deployment-log", "deployments/{id}/log", new { controller = "Deployment", action = "GetLogEntry" }); routes.MapHttpRouteDual("one-deployment-log-details", "deployments/{id}/log/{logId}", new { controller = "Deployment", action = "GetLogEntryDetails" }); // SSHKey routes.MapHttpRouteDual("get-sshkey", "sshkey", new { controller = "SSHKey", action = "GetPublicKey" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpRouteDual("put-sshkey", "sshkey", new { controller = "SSHKey", action = "SetPrivateKey" }, new { verb = new HttpMethodConstraint("PUT") }); routes.MapHttpRouteDual("delete-sshkey", "sshkey", new { controller = "SSHKey", action = "DeleteKeyPair" }, new { verb = new HttpMethodConstraint("DELETE") }); // Environment routes.MapHttpRouteDual("get-env", "environment", new { controller = "Environment", action = "Get" }, new { verb = new HttpMethodConstraint("GET") }); // Settings routes.MapHttpRouteDual("set-setting", "settings", new { controller = "Settings", action = "Set" }, new { verb = new HttpMethodConstraint("POST") }); routes.MapHttpRoute("get-all-settings-old", "settings", new { controller = "Settings", action = "GetAll" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpRoute("get-all-settings", "api/settings", new { controller = "Settings", action = "GetAll", version = 2 }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpRouteDual("get-setting", "settings/{key}", new { controller = "Settings", action = "Get" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpRouteDual("delete-setting", "settings/{key}", new { controller = "Settings", action = "Delete" }, new { verb = new HttpMethodConstraint("DELETE") }); // Diagnostics routes.MapHttpRouteDual("diagnostics", "dump", new { controller = "Diagnostics", action = "GetLog" }); routes.MapHttpRouteDual("diagnostics-set-setting", "diagnostics/settings", new { controller = "Diagnostics", action = "Set" }, new { verb = new HttpMethodConstraint("POST") }); routes.MapHttpRouteDual("diagnostics-get-all-settings", "diagnostics/settings", new { controller = "Diagnostics", action = "GetAll" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpRouteDual("diagnostics-get-setting", "diagnostics/settings/{key}", new { controller = "Diagnostics", action = "Get" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpRouteDual("diagnostics-delete-setting", "diagnostics/settings/{key}", new { controller = "Diagnostics", action = "Delete" }, new { verb = new HttpMethodConstraint("DELETE") }); // Logs routes.MapHandlerDual<LogStreamHandler>(kernel, "logstream", "logstream/{*path}"); routes.MapHttpRoute("recent-logs", "api/logs/recent", new { controller = "Diagnostics", action = "GetRecentLogs" }, new { verb = new HttpMethodConstraint("GET") }); // Processes routes.MapHttpProcessesRoute("all-processes", "", new { controller = "Process", action = "GetAllProcesses" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpProcessesRoute("one-process-get", "/{id}", new { controller = "Process", action = "GetProcess" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpProcessesRoute("one-process-delete", "/{id}", new { controller = "Process", action = "KillProcess" }, new { verb = new HttpMethodConstraint("DELETE") }); routes.MapHttpProcessesRoute("one-process-dump", "/{id}/dump", new { controller = "Process", action = "MiniDump" }, new { verb = new HttpMethodConstraint("GET") }); if (ProcessExtensions.SupportGCDump) { routes.MapHttpProcessesRoute("one-process-gcdump", "/{id}/gcdump", new { controller = "Process", action = "GCDump" }, new { verb = new HttpMethodConstraint("GET") }); } routes.MapHttpProcessesRoute("all-threads", "/{id}/threads", new { controller = "Process", action = "GetAllThreads" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpProcessesRoute("one-process-thread", "/{processId}/threads/{threadId}", new { controller = "Process", action = "GetThread" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpProcessesRoute("all-modules", "/{id}/modules", new { controller = "Process", action = "GetAllModules" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpProcessesRoute("one-process-module", "/{id}/modules/{baseAddress}", new { controller = "Process", action = "GetModule" }, new { verb = new HttpMethodConstraint("GET") }); // Runtime routes.MapHttpRouteDual("runtime", "diagnostics/runtime", new { controller = "Runtime", action = "GetRuntimeVersions" }, new { verb = new HttpMethodConstraint("GET") }); // Hooks routes.MapHttpRouteDual("unsubscribe-hook", "hooks/{id}", new { controller = "WebHooks", action = "Unsubscribe" }, new { verb = new HttpMethodConstraint("DELETE") }); routes.MapHttpRouteDual("get-hook", "hooks/{id}", new { controller = "WebHooks", action = "GetWebHook" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpRouteDual("publish-hooks", "hooks/publish/{hookEventType}", new { controller = "WebHooks", action = "PublishEvent" }, new { verb = new HttpMethodConstraint("POST") }); routes.MapHttpRouteDual("get-hooks", "hooks", new { controller = "WebHooks", action = "GetWebHooks" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpRouteDual("subscribe-hook", "hooks", new { controller = "WebHooks", action = "Subscribe" }, new { verb = new HttpMethodConstraint("POST") }); // Jobs routes.MapHttpRoute("api-list-all-jobs", "api/webjobs", new { controller = "Jobs", action = "ListAllJobs" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpRouteDual("list-all-jobs", "jobs", new { controller = "Jobs", action = "ListAllJobs" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpWebJobsRoute("list-triggered-jobs", "triggered", "", new { controller = "Jobs", action = "ListTriggeredJobs" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpWebJobsRoute("get-triggered-job", "triggered", "/{jobName}", new { controller = "Jobs", action = "GetTriggeredJob" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpWebJobsRoute("invoke-triggered-job", "triggered", "/{jobName}/run", new { controller = "Jobs", action = "InvokeTriggeredJob" }, new { verb = new HttpMethodConstraint("POST") }); routes.MapHttpWebJobsRoute("get-triggered-job-history", "triggered", "/{jobName}/history", new { controller = "Jobs", action = "GetTriggeredJobHistory" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpWebJobsRoute("get-triggered-job-run", "triggered", "/{jobName}/history/{runId}", new { controller = "Jobs", action = "GetTriggeredJobRun" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpWebJobsRoute("create-triggered-job", "triggered", "/{jobName}", new { controller = "Jobs", action = "CreateTriggeredJob" }, new { verb = new HttpMethodConstraint("PUT") }); routes.MapHttpWebJobsRoute("remove-triggered-job", "triggered", "/{jobName}", new { controller = "Jobs", action = "RemoveTriggeredJob" }, new { verb = new HttpMethodConstraint("DELETE") }); routes.MapHttpWebJobsRoute("get-triggered-job-settings", "triggered", "/{jobName}/settings", new { controller = "Jobs", action = "GetTriggeredJobSettings" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpWebJobsRoute("set-triggered-job-settings", "triggered", "/{jobName}/settings", new { controller = "Jobs", action = "SetTriggeredJobSettings" }, new { verb = new HttpMethodConstraint("PUT") }); routes.MapHttpWebJobsRoute("list-continuous-jobs", "continuous", "", new { controller = "Jobs", action = "ListContinuousJobs" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpWebJobsRoute("get-continuous-job", "continuous", "/{jobName}", new { controller = "Jobs", action = "GetContinuousJob" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpWebJobsRoute("disable-continuous-job", "continuous", "/{jobName}/stop", new { controller = "Jobs", action = "DisableContinuousJob" }, new { verb = new HttpMethodConstraint("POST") }); routes.MapHttpWebJobsRoute("enable-continuous-job", "continuous", "/{jobName}/start", new { controller = "Jobs", action = "EnableContinuousJob" }, new { verb = new HttpMethodConstraint("POST") }); routes.MapHttpWebJobsRoute("create-continuous-job", "continuous", "/{jobName}", new { controller = "Jobs", action = "CreateContinuousJob" }, new { verb = new HttpMethodConstraint("PUT") }); routes.MapHttpWebJobsRoute("remove-continuous-job", "continuous", "/{jobName}", new { controller = "Jobs", action = "RemoveContinuousJob" }, new { verb = new HttpMethodConstraint("DELETE") }); routes.MapHttpWebJobsRoute("get-continuous-job-settings", "continuous", "/{jobName}/settings", new { controller = "Jobs", action = "GetContinuousJobSettings" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpWebJobsRoute("set-continuous-job-settings", "continuous", "/{jobName}/settings", new { controller = "Jobs", action = "SetContinuousJobSettings" }, new { verb = new HttpMethodConstraint("PUT") }); // SiteExtensions routes.MapHttpRoute("api-get-remote-extensions", "api/extensionfeed", new { controller = "SiteExtension", action = "GetRemoteExtensions" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpRoute("api-get-remote-extension", "api/extensionfeed/{id}", new { controller = "SiteExtension", action = "GetRemoteExtension" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpRoute("api-get-local-extensions", "api/siteextensions", new { controller = "SiteExtension", action = "GetLocalExtensions" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpRoute("api-get-local-extension", "api/siteextensions/{id}", new { controller = "SiteExtension", action = "GetLocalExtension" }, new { verb = new HttpMethodConstraint("GET") }); routes.MapHttpRoute("api-uninstall-extension", "api/siteextensions/{id}", new { controller = "SiteExtension", action = "UninstallExtension" }, new { verb = new HttpMethodConstraint("DELETE") }); routes.MapHttpRoute("api-install-update-extension", "api/siteextensions/{id}", new { controller = "SiteExtension", action = "InstallExtension" }, new { verb = new HttpMethodConstraint("PUT") }); } // Perform migration tasks to deal with legacy sites that had different file layout private static void MigrateSite(IEnvironment environment, IDeploymentSettingsManager settings) { try { MoveOldSSHFolder(environment); } catch (Exception e) { ITracer tracer = GetTracerWithoutContext(environment, settings); tracer.Trace("Failed to move legacy .ssh folder: {0}", e.Message); } } // .ssh folder used to be under /site, and is now at the root private static void MoveOldSSHFolder(IEnvironment environment) { var oldSSHDirInfo = new DirectoryInfo(Path.Combine(environment.SiteRootPath, Constants.SSHKeyPath)); if (oldSSHDirInfo.Exists) { string newSSHFolder = Path.Combine(environment.RootPath, Constants.SSHKeyPath); if (!Directory.Exists(newSSHFolder)) { Directory.CreateDirectory(newSSHFolder); } foreach (FileInfo file in oldSSHDirInfo.EnumerateFiles()) { // Copy the file to the new folder, unless it already exists string newFile = Path.Combine(newSSHFolder, file.Name); if (!File.Exists(newFile)) { file.CopyTo(newFile, overwrite: true); } } // Delete the old folder oldSSHDirInfo.Delete(recursive: true); } } private static ITracer GetTracer(IEnvironment environment, IKernel kernel) { TraceLevel level = kernel.Get<IDeploymentSettingsManager>().GetTraceLevel(); if (level > TraceLevel.Off && TraceServices.CurrentRequestTraceFile != null) { string tracePath = Path.Combine(environment.TracePath, Constants.TraceFile); string textPath = Path.Combine(environment.TracePath, TraceServices.CurrentRequestTraceFile); string traceLockPath = Path.Combine(environment.TracePath, Constants.TraceLockFile); var traceLock = new LockFile(traceLockPath); return new CascadeTracer(new Tracer(tracePath, level, traceLock), new TextTracer(textPath, level)); } return NullTracer.Instance; } private static ITracer GetTracerWithoutContext(IEnvironment environment, IDeploymentSettingsManager settings) { TraceLevel level = settings.GetTraceLevel(); if (level > TraceLevel.Off) { string tracePath = Path.Combine(environment.TracePath, Constants.TraceFile); string traceLockPath = Path.Combine(environment.TracePath, Constants.TraceLockFile); var traceLock = new LockFile(traceLockPath); return new Tracer(tracePath, level, traceLock); } return NullTracer.Instance; } private static void TraceShutdown(IEnvironment environment, IDeploymentSettingsManager settings) { ITracer tracer = GetTracerWithoutContext(environment, settings); var attribs = new Dictionary<string, string>(); // Add an attribute containing the process, AppDomain and Thread ids to help debugging attribs.Add("pid", String.Format("{0},{1},{2}", Process.GetCurrentProcess().Id, AppDomain.CurrentDomain.Id.ToString(), System.Threading.Thread.CurrentThread.ManagedThreadId)); attribs.Add("uptime", TraceModule.UpTime.ToString()); attribs.Add("lastrequesttime", TraceModule.LastRequestTime.ToString()); tracer.Trace("Process Shutdown", attribs); } private static ILogger GetLogger(IEnvironment environment, IKernel kernel) { TraceLevel level = kernel.Get<IDeploymentSettingsManager>().GetTraceLevel(); if (level > TraceLevel.Off && TraceServices.CurrentRequestTraceFile != null) { string textPath = Path.Combine(environment.DeploymentTracePath, TraceServices.CurrentRequestTraceFile); return new TextLogger(textPath); } return NullLogger.Instance; } private static string GetRequestTraceFile(IKernel kernel) { TraceLevel level = kernel.Get<IDeploymentSettingsManager>().GetTraceLevel(); if (level > TraceLevel.Off) { return TraceServices.CurrentRequestTraceFile; } return null; } private static ICommandExecutor GetCommandExecutor(IEnvironment environment, IContext context) { if (System.String.IsNullOrEmpty(environment.RepositoryPath)) { throw new HttpResponseException(HttpStatusCode.NotFound); } return new CommandExecutor(environment.RootPath, environment, context.Kernel.Get<IDeploymentSettingsManager>(), TraceServices.CurrentRequestTracer); } private static string GetSettingsPath(IEnvironment environment) { return Path.Combine(environment.DeploymentsPath, Constants.DeploySettingsPath); } private static void EnsureHomeEnvironmentVariable() { // If MapPath("/_app") returns a valid folder, set %HOME% to that, regardless of // it current value. This is the non-Azure code path. string path = HostingEnvironment.MapPath(Constants.MappedSite); if (Directory.Exists(path)) { path = Path.GetFullPath(path); System.Environment.SetEnvironmentVariable("HOME", path); } } private static IEnvironment GetEnvironment(IDeploymentSettingsManager settings = null) { string root = PathResolver.ResolveRootPath(); string siteRoot = Path.Combine(root, Constants.SiteFolder); string repositoryPath = Path.Combine(siteRoot, settings == null ? Constants.RepositoryPath : settings.GetRepositoryPath()); return new Kudu.Core.Environment( root, HttpRuntime.BinDirectory, repositoryPath); } } }
#region Copyright (c) 2002-2003, James W. Newkirk, Michael C. Two, Alexei A. Vorontsov, Charlie Poole, Philip A. Craig /************************************************************************************ ' ' Copyright 2002-2003 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov, Charlie Poole ' Copyright 2000-2002 Philip A. Craig ' ' This software is provided 'as-is', without any express or implied warranty. In no ' event will the authors be held liable for any damages arising from the use of this ' software. ' ' Permission is granted to anyone to use this software for any purpose, including ' commercial applications, and to alter it and redistribute it freely, subject to the ' following restrictions: ' ' 1. The origin of this software must not be misrepresented; you must not claim that ' you wrote the original software. If you use this software in a product, an ' acknowledgment (see the following) in the product documentation is required. ' ' Portions Copyright 2002-2003 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov, Charlie Poole ' or Copyright 2000-2002 Philip A. Craig ' ' 2. Altered source versions must be plainly marked as such, and must not be ' misrepresented as being the original software. ' ' 3. This notice may not be removed or altered from any source distribution. ' '***********************************************************************************/ #endregion namespace NUnit.Util { using System; using Codeblast; public class ConsoleOptions : CommandLineOptions { [Option(Description = "Fixture to test")] public string fixture; [Option(Description = "Project configuration to load")] public string config; [Option(Description = "Name of XML output file")] public string xml; [Option(Description = "Name of transform file")] public string transform; [Option(Description = "Display XML to the console")] public bool xmlConsole; [Option(Short="out", Description = "File to receive test output")] public string output; [Option(Description = "File to receive test error output")] public string err; [Option(Description = "Label each test in stdOut")] public bool labels = false; [Option(Description = "List of categories to include")] public string include; [Option(Description = "List of categories to exclude")] public string exclude; // [Option(Description = "Run in a separate process")] // public bool process; // [Option(Description = "Run in a separate AppDomain")] // public bool domain; // [Option(Description = "Disable shadow copy when running in separate domain")] [Option(Description = "Disable shadow copy")] public bool noshadow; [Option (Description = "Run tests on a separate thread")] public bool thread; [Option(Description = "Wait for input before closing console window")] public bool wait = false; [Option(Description = "Do not display the logo")] public bool nologo = false; [Option(Short="?", Description = "Display help")] public bool help = false; private bool isInvalid = false; public ConsoleOptions(String[] args) : base(args) {} protected override void InvalidOption(string name) { isInvalid = true; } public bool Validate() { if(isInvalid) return false; if(HasInclude && HasExclude) return false; if(NoArgs) return true; if(IsFixture) return true; if(ParameterCount >= 1) return true; return false; } public bool IsAssembly { get { return ParameterCount >= 1 && !IsFixture; } } public bool IsTestProject { get { return ParameterCount == 1 && NUnitProject.CanLoadAsProject( (string)Parameters[0] ); } } public bool IsFixture { get { return ParameterCount >= 1 && ((fixture != null) && (fixture.Length > 0)); } } public bool IsXml { get { return (xml != null) && (xml.Length != 0); } } public bool isOut { get { return (output != null) && (output.Length != 0); } } public bool isErr { get { return (err != null) && (err.Length != 0); } } public bool IsTransform { get { return (transform != null) && (transform.Length != 0); } } public bool HasInclude { get { return include != null && include.Length != 0; } } public bool HasExclude { get { return exclude != null && exclude.Length != 0; } } public string[] IncludedCategories { get { if (HasInclude) return include.Split( new char[] {';', ','}); return null; } } public string[] ExcludedCategories { get { if (HasExclude) return exclude.Split( new char[] {';', ','}); return null; } } public override void Help() { Console.WriteLine(); Console.WriteLine( "NUNIT-CONSOLE [inputfiles] [options]" ); Console.WriteLine(); Console.WriteLine( "Runs a set of NUnit tests from the console." ); Console.WriteLine(); Console.WriteLine( "You may specify one or more assemblies or a single" ); Console.WriteLine( "project file of type .nunit." ); Console.WriteLine(); Console.WriteLine( "Options:" ); base.Help(); Console.WriteLine(); Console.WriteLine( "Options that take values may use an equal sign, a colon" ); Console.WriteLine( "or a space to separate the option from its value." ); Console.WriteLine(); } } }
/* * 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 NUnit.Framework; using SimpleAnalyzer = Lucene.Net.Analysis.SimpleAnalyzer; using Document = Lucene.Net.Documents.Document; using Field = Lucene.Net.Documents.Field; using IndexReader = Lucene.Net.Index.IndexReader; using IndexWriter = Lucene.Net.Index.IndexWriter; using Term = Lucene.Net.Index.Term; using RAMDirectory = Lucene.Net.Store.RAMDirectory; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; namespace Lucene.Net.Search { /// <summary>Similarity unit test.</summary> [TestFixture] public class TestSimilarity:LuceneTestCase { private class AnonymousClassCollector:Collector { public AnonymousClassCollector(TestSimilarity enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(TestSimilarity enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestSimilarity enclosingInstance; public TestSimilarity Enclosing_Instance { get { return enclosingInstance; } } private Scorer scorer; public override void SetScorer(Scorer scorer) { this.scorer = scorer; } public override void Collect(int doc) { Assert.AreEqual(1.0f, scorer.Score()); } public override void SetNextReader(IndexReader reader, int docBase) { } public override bool AcceptsDocsOutOfOrder { get { return true; } } } private class AnonymousClassCollector1:Collector { public AnonymousClassCollector1(TestSimilarity enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(TestSimilarity enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestSimilarity enclosingInstance; public TestSimilarity Enclosing_Instance { get { return enclosingInstance; } } private int base_Renamed = 0; private Scorer scorer; public override void SetScorer(Scorer scorer) { this.scorer = scorer; } public override void Collect(int doc) { //System.out.println("Doc=" + doc + " score=" + score); Assert.AreEqual((float) doc + base_Renamed + 1, scorer.Score()); } public override void SetNextReader(IndexReader reader, int docBase) { base_Renamed = docBase; } public override bool AcceptsDocsOutOfOrder { get { return true; } } } private class AnonymousClassCollector2:Collector { public AnonymousClassCollector2(TestSimilarity enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(TestSimilarity enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestSimilarity enclosingInstance; public TestSimilarity Enclosing_Instance { get { return enclosingInstance; } } private Scorer scorer; public override void SetScorer(Scorer scorer) { this.scorer = scorer; } public override void Collect(int doc) { //System.out.println("Doc=" + doc + " score=" + score); Assert.AreEqual(1.0f, scorer.Score()); } public override void SetNextReader(IndexReader reader, int docBase) { } public override bool AcceptsDocsOutOfOrder { get { return true; } } } private class AnonymousClassCollector3:Collector { public AnonymousClassCollector3(TestSimilarity enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(TestSimilarity enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TestSimilarity enclosingInstance; public TestSimilarity Enclosing_Instance { get { return enclosingInstance; } } private Scorer scorer; public override void SetScorer(Scorer scorer) { this.scorer = scorer; } public override void Collect(int doc) { //System.out.println("Doc=" + doc + " score=" + score); Assert.AreEqual(2.0f, scorer.Score()); } public override void SetNextReader(IndexReader reader, int docBase) { } public override bool AcceptsDocsOutOfOrder { get { return true; } } } private class AnonymousIDFExplanation : Explanation.IDFExplanation { public override float Idf { get { return 1.0f; } } public override string Explain() { return "Inexplicable"; } } [Serializable] public class SimpleSimilarity : Similarity { public override float LengthNorm(System.String field, int numTerms) { return 1.0f; } public override float QueryNorm(float sumOfSquaredWeights) { return 1.0f; } public override float Tf(float freq) { return freq; } public override float SloppyFreq(int distance) { return 2.0f; } public override float Idf(int docFreq, int numDocs) { return 1.0f; } public override float Coord(int overlap, int maxOverlap) { return 1.0f; } public override Explanation.IDFExplanation IdfExplain(System.Collections.Generic.ICollection<Term> terms, Searcher searcher) { return new AnonymousIDFExplanation(); } } [Test] public virtual void TestSimilarity_Renamed() { RAMDirectory store = new RAMDirectory(); IndexWriter writer = new IndexWriter(store, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); writer.SetSimilarity(new SimpleSimilarity()); Document d1 = new Document(); d1.Add(new Field("field", "a c", Field.Store.YES, Field.Index.ANALYZED)); Document d2 = new Document(); d2.Add(new Field("field", "a b c", Field.Store.YES, Field.Index.ANALYZED)); writer.AddDocument(d1); writer.AddDocument(d2); writer.Optimize(); writer.Close(); Searcher searcher = new IndexSearcher(store, true); searcher.Similarity = new SimpleSimilarity(); Term a = new Term("field", "a"); Term b = new Term("field", "b"); Term c = new Term("field", "c"); searcher.Search(new TermQuery(b), new AnonymousClassCollector(this)); BooleanQuery bq = new BooleanQuery(); bq.Add(new TermQuery(a), Occur.SHOULD); bq.Add(new TermQuery(b), Occur.SHOULD); //System.out.println(bq.toString("field")); searcher.Search(bq, new AnonymousClassCollector1(this)); PhraseQuery pq = new PhraseQuery(); pq.Add(a); pq.Add(c); //System.out.println(pq.toString("field")); searcher.Search(pq, new AnonymousClassCollector2(this)); pq.Slop = 2; //System.out.println(pq.toString("field")); searcher.Search(pq, new AnonymousClassCollector3(this)); } } }
// MIT License // // Copyright (c) 2017 Maarten van Sambeek. // // 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. namespace ConnectQl.Tools.Mef.Intellisense { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using ConnectQl.Intellisense; using ConnectQl.Interfaces; using ConnectQl.Results; using Errors; using Interfaces; using JetBrains.Annotations; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Task = Microsoft.VisualStudio.Shell.Task; /// <summary> /// The intellisense session. /// </summary> internal class IntellisenseSession { /// <summary> /// The documents. /// </summary> private readonly Dictionary<string, ConnectQlDocument> documents = new Dictionary<string, ConnectQlDocument>(StringComparer.OrdinalIgnoreCase); /// <summary> /// The project unique name. /// </summary> private readonly string projectUniqueName; /// <summary> /// The project hierarchy item. /// </summary> private readonly IVsHierarchy projectHierarchyItem; /// <summary> /// The error list. /// </summary> private readonly UpdatedErrorListProvider errorList; /// <summary> /// The provider. /// </summary> private readonly ConnectQlDocumentProvider provider; /// <summary> /// The proxy. /// </summary> private IntellisenseProxy proxy; /// <summary> /// Initializes a new instance of the <see cref="IntellisenseSession"/> class. /// </summary> /// <param name="provider"> /// The provider. /// </param> /// <param name="projectUniqueName"> /// The project unique name. /// </param> /// <param name="projectHierarchyItem"> /// The hierarchy item for the project for this intellisense session. /// </param> /// <param name="errorList"> /// The error list to report errors to. /// </param> public IntellisenseSession(ConnectQlDocumentProvider provider, string projectUniqueName, IVsHierarchy projectHierarchyItem, UpdatedErrorListProvider errorList) { this.provider = provider; this.projectUniqueName = projectUniqueName; this.projectHierarchyItem = projectHierarchyItem; this.errorList = errorList; var newProxy = new IntellisenseProxy(projectUniqueName); newProxy.Initialized += this.ProxyOnInitialized; } /// <summary> /// Executes the queries in the file name or stream. /// </summary> /// <param name="filename"> /// The name of the file to execute. /// </param> /// <param name="stream"> /// The stream containing the queries. /// </param> /// <returns> /// The result. /// </returns> [NotNull] public Task<IExecuteResult> ExecuteAsync(string filename, Stream stream) { return this.proxy?.ExecuteAsync(filename, stream) ?? System.Threading.Tasks.Task.FromResult(Result.Empty()); } /// <summary> /// The get document. /// </summary> /// <param name="textBuffer"> /// The text buffer. /// </param> /// <returns> /// The <see cref="IDocument"/>. /// </returns> public IDocument GetDocument(ITextBuffer textBuffer) { this.provider.DocumentFactoryService.TryGetTextDocument(textBuffer, out var document); if (this.documents.TryGetValue(document.FilePath, out var result)) { return result; } result = this.documents[document.FilePath] = new ConnectQlDocument(this, document.FilePath) { Version = textBuffer.CurrentSnapshot.Version.VersionNumber, Content = textBuffer.CurrentSnapshot.GetText() }; this.proxy?.UpdateDocument(document.FilePath, result.Content, result.Version); textBuffer.Changed += (o, e) => this.proxy?.UpdateDocument(document.FilePath, result.Content = textBuffer.CurrentSnapshot.GetText(), result.Version = textBuffer.CurrentSnapshot.Version.VersionNumber); return result; } /// <summary> /// Converts a message to a task. /// </summary> /// <param name="document">The document.</param> /// <param name="message">The message.</param> /// <returns> /// The task. /// </returns> [NotNull] private Task ToTask([NotNull] IDocument document, [NotNull] IMessage message) { var result = new ErrorTask { Text = message.Text, Line = message.Start.Line - 1, Column = message.Start.Column - 1, Document = document.Filename, HierarchyItem = this.projectHierarchyItem }; switch (message.Type) { case ResultMessageType.Error: result.ErrorCategory = TaskErrorCategory.Error; break; case ResultMessageType.Warning: result.ErrorCategory = TaskErrorCategory.Warning; break; case ResultMessageType.Information: result.ErrorCategory = TaskErrorCategory.Message; break; default: throw new ArgumentException($"Invalid message type: {message.Type}.", nameof(message)); } return result; } /// <summary> /// The proxy on document updated. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="documentUpdatedEventArgs"> /// The document updated event args. /// </param> private void ProxyOnDocumentUpdated(object sender, [NotNull] DocumentUpdatedEventArgs documentUpdatedEventArgs) { if (this.documents.TryGetValue(documentUpdatedEventArgs.Document.Filename, out var doc)) { doc.UpdateClassification(documentUpdatedEventArgs.Document); if (documentUpdatedEventArgs.Document.Messages != null) { this.UpdateErrorList(doc); } } } /// <summary> /// Updates the error list. /// </summary> /// <param name="document">The document that was changed.</param> private async void UpdateErrorList(IDocument document) { await System.Threading.Tasks.Task.Run(() => { this.errorList.SuspendRefresh(); foreach (var task in this.errorList.Tasks.OfType<ErrorTask>().Where(et => et.Document == document.Filename).ToList()) { this.errorList.Tasks.Remove(task); } foreach (var task in document.GetMessages().Select(message => this.ToTask(document, message))) { task.Navigate += (o, e) => this.errorList.NavigateToTask(task, new Guid(EnvDTE.Constants.vsViewKindCode)); this.errorList.Tasks.Add(task); } this.errorList.ResumeRefresh(); }); } /// <summary> /// The proxy on initialized. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="eventArgs"> /// The event args. /// </param> private void ProxyOnInitialized(object sender, EventArgs eventArgs) { ((IntellisenseProxy)sender).Initialized -= this.ProxyOnInitialized; var oldProxy = this.proxy; this.proxy = (IntellisenseProxy)sender; this.proxy.ReloadRequested += this.ProxyOnReloadRequested; this.proxy.DocumentUpdated += this.ProxyOnDocumentUpdated; if (oldProxy != null) { oldProxy.ReloadRequested -= this.ProxyOnReloadRequested; oldProxy.DocumentUpdated -= this.ProxyOnDocumentUpdated; oldProxy.Dispose(); } foreach (var keyValuePair in this.documents) { this.proxy.UpdateDocument(keyValuePair.Key, keyValuePair.Value.Content, keyValuePair.Value.Version); } } /// <summary> /// The proxy on reload requested. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="eventArgs"> /// The event args. /// </param> private void ProxyOnReloadRequested(object sender, EventArgs eventArgs) { this.proxy.ReloadRequested -= this.ProxyOnReloadRequested; var newProxy = new IntellisenseProxy(this.projectUniqueName); newProxy.Initialized += this.ProxyOnInitialized; } } }
using UnityEngine; using System.Collections.Generic; namespace Pathfinding { using Pathfinding.Util; /** Contains utility methods for getting useful information out of graph. * This class works a lot with the #Pathfinding.GraphNode class, a useful function to get nodes is #AstarPath.GetNearest. * * \see #AstarPath.GetNearest * \see #Pathfinding.GraphUpdateUtilities * \see #Pathfinding.PathUtilities * * \ingroup utils */ public static class GraphUtilities { /** Convenience method to get a list of all segments of the contours of a graph. * \returns A list of segments. Every 2 elements form a line segment. The first segment is (result[0], result[1]), the second one is (result[2], result[3]) etc. * The line segments are oriented so that the navmesh is on the right side of the segments when seen from above. * * This method works for navmesh, recast, grid graphs and layered grid graphs. For other graph types it will return an empty list. * * If you need more information about how the contours are connected you can take a look at the other variants of this method. * * \snippet MiscSnippets.cs GraphUtilities.GetContours2 * * \shadowimage{navmesh_contour.png} * \shadowimage{grid_contour.png} */ public static List<Vector3> GetContours (NavGraph graph) { List<Vector3> result = ListPool<Vector3>.Claim(); if (graph is INavmesh) { GetContours(graph as INavmesh, (vertices, cycle) => { for (int j = cycle ? vertices.Count - 1 : 0, i = 0; i < vertices.Count; j = i, i++) { result.Add((Vector3)vertices[j]); result.Add((Vector3)vertices[i]); } }); #if !ASTAR_NO_GRID_GRAPH } else if (graph is GridGraph) { GetContours(graph as GridGraph, vertices => { for (int j = vertices.Length - 1, i = 0; i < vertices.Length; j = i, i++) { result.Add((Vector3)vertices[j]); result.Add((Vector3)vertices[i]); } }, 0); #endif } return result; } /** Traces the contour of a navmesh. * \param navmesh The navmesh-like object to trace. This can be a recast or navmesh graph or it could be a single tile in one such graph. * \param results Will be called once for each contour with the contour as a parameter as well as a boolean indicating if the contour is a cycle or a chain (see second image). * * \shadowimage{navmesh_contour.png} * * This image is just used to illustrate the difference between chains and cycles. That it shows a grid graph is not relevant. * \shadowimage{grid_contour_compressed.png} * * \see #GetContours(NavGraph) */ public static void GetContours (INavmesh navmesh, System.Action<List<Int3>, bool> results) { // Assume 3 vertices per node var uses = new bool[3]; var outline = new Dictionary<int, int>(); var vertexPositions = new Dictionary<int, Int3>(); var hasInEdge = new HashSet<int>(); navmesh.GetNodes(_node => { var node = _node as TriangleMeshNode; uses[0] = uses[1] = uses[2] = false; if (node != null) { // Find out which edges are shared with other nodes for (int j = 0; j < node.connections.Length; j++) { var other = node.connections[j].node as TriangleMeshNode; // Not necessarily a TriangleMeshNode if (other != null) { int a = node.SharedEdge(other); if (a != -1) uses[a] = true; } } // Loop through all edges on the node for (int j = 0; j < 3; j++) { // The edge is not shared with any other node // I.e it is an exterior edge on the mesh if (!uses[j]) { var i1 = j; var i2 = (j+1) % node.GetVertexCount(); outline[node.GetVertexIndex(i1)] = node.GetVertexIndex(i2); hasInEdge.Add(node.GetVertexIndex(i2)); vertexPositions[node.GetVertexIndex(i1)] = node.GetVertex(i1); vertexPositions[node.GetVertexIndex(i2)] = node.GetVertex(i2); } } } }); Polygon.TraceContours(outline, hasInEdge, (chain, cycle) => { List<Int3> vertices = ListPool<Int3>.Claim(); for (int i = 0; i < chain.Count; i++) vertices.Add(vertexPositions[chain[i]]); results(vertices, cycle); }); } /** Finds all contours of a collection of nodes in a grid graph. * \param grid The grid to find the contours of * \param callback The callback will be called once for every contour that is found with the vertices of the contour. The contour always forms a cycle. * \param yMergeThreshold Contours will be simplified if the y coordinates for adjacent vertices differ by no more than this value. * \param nodes Only these nodes will be searched. If this parameter is null then all nodes in the grid graph will be searched. * * \snippet MiscSnippets.cs GraphUtilities.GetContours1 * * In the image below you can see the contour of a graph. * \shadowimage{grid_contour.png} * * In the image below you can see the contour of just a part of a grid graph (when the \a nodes parameter is supplied) * \shadowimage{grid_contour_partial.png} * * Contour of a hexagon graph * \shadowimage{grid_contour_hexagon.png} * * \see #GetContours(NavGraph) */ public static void GetContours (GridGraph grid, System.Action<Vector3[]> callback, float yMergeThreshold, GridNodeBase[] nodes = null) { // Set of all allowed nodes or null if all nodes are allowed HashSet<GridNodeBase> nodeSet = nodes != null ? new HashSet<GridNodeBase>(nodes) : null; // Use all nodes if the nodes parameter is null if (grid is LayerGridGraph) nodes = nodes ?? (grid as LayerGridGraph).nodes; nodes = nodes ?? grid.nodes; int[] neighbourXOffsets = grid.neighbourXOffsets; int[] neighbourZOffsets = grid.neighbourZOffsets; var neighbourIndices = grid.neighbours == NumNeighbours.Six ? GridGraph.hexagonNeighbourIndices : new [] { 0, 1, 2, 3 }; var offsetMultiplier = grid.neighbours == NumNeighbours.Six ? 1/3f : 0.5f; if (nodes != null) { var trace = ListPool<Vector3>.Claim(); var seenStates = new HashSet<int>(); for (int i = 0; i < nodes.Length; i++) { var startNode = nodes[i]; // The third check is a fast check for if the node has connections in all grid directions, if it has then we can skip processing it (unless the nodes parameter was used in which case we have to handle the edge cases) if (startNode != null && startNode.Walkable && (!startNode.HasConnectionsToAllEightNeighbours || nodeSet != null)) { for (int startDir = 0; startDir < neighbourIndices.Length; startDir++) { int startState = (startNode.NodeIndex << 4) | startDir; // Check if there is an obstacle in that direction var startNeighbour = startNode.GetNeighbourAlongDirection(neighbourIndices[startDir]); if ((startNeighbour == null || (nodeSet != null && !nodeSet.Contains(startNeighbour))) && !seenStates.Contains(startState)) { // Start tracing a contour here trace.ClearFast(); int dir = startDir; GridNodeBase node = startNode; while (true) { int state = (node.NodeIndex << 4) | dir; if (state == startState && trace.Count > 0) { break; } seenStates.Add(state); var neighbour = node.GetNeighbourAlongDirection(neighbourIndices[dir]); if (neighbour == null || (nodeSet != null && !nodeSet.Contains(neighbour))) { // Draw edge var d0 = neighbourIndices[dir]; dir = (dir + 1) % neighbourIndices.Length; var d1 = neighbourIndices[dir]; // Position in graph space of the vertex Vector3 graphSpacePos = new Vector3(node.XCoordinateInGrid + 0.5f, 0, node.ZCoordinateInGrid + 0.5f); // Offset along diagonal to get the correct XZ coordinates graphSpacePos.x += (neighbourXOffsets[d0] + neighbourXOffsets[d1]) * offsetMultiplier; graphSpacePos.z += (neighbourZOffsets[d0] + neighbourZOffsets[d1]) * offsetMultiplier; graphSpacePos.y = grid.transform.InverseTransform((Vector3)node.position).y; if (trace.Count >= 2) { var v0 = trace[trace.Count-2]; var v1 = trace[trace.Count-1]; var v1d = v1 - v0; var v2d = graphSpacePos - v0; // Replace the previous point if it is colinear with the point just before it and just after it (the current point), because that point wouldn't add much information, but it would add CPU overhead if (((Mathf.Abs(v1d.x) > 0.01f || Mathf.Abs(v2d.x) > 0.01f) && (Mathf.Abs(v1d.z) > 0.01f || Mathf.Abs(v2d.z) > 0.01f)) || (Mathf.Abs(v1d.y) > yMergeThreshold || Mathf.Abs(v2d.y) > yMergeThreshold)) { trace.Add(graphSpacePos); } else { trace[trace.Count-1] = graphSpacePos; } } else { trace.Add(graphSpacePos); } } else { // Move node = neighbour; dir = (dir + neighbourIndices.Length/2 + 1) % neighbourIndices.Length; } } var result = trace.ToArray(); grid.transform.Transform(result); callback(result); } } } } ListPool<Vector3>.Release(ref trace); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace Gearset.Components { /// <summary> /// Displays a hierarchy of values that need to be traced. /// </summary> public class TreeView : Gear { private TreeViewNode root; private int iterationCount; Texture2D closedTexture; Texture2D openedTexture; Vector2 Position; MouseState prevMouse; public TreeViewConfig Config { get { return GearsetSettings.Instance.TreeViewConfig; } } #region Constructor public TreeView() : base(GearsetSettings.Instance.TreeViewConfig) { Config.Cleared += new EventHandler(Config_Cleared); Config.Filter = String.Empty; root = new TreeViewNode("root"); #if XBOX this.openedTexture = GearsetResources.Content.Load<Texture2D>("close_Xbox360"); this.closedTexture = GearsetResources.Content.Load<Texture2D>("open_Xbox360"); #elif WINDOWS_PHONE this.openedTexture = GearsetResources.Content.Load<Texture2D>("close_wp"); this.closedTexture = GearsetResources.Content.Load<Texture2D>("open_wp"); #else this.openedTexture = GearsetResources.Content.Load<Texture2D>("close"); this.closedTexture = GearsetResources.Content.Load<Texture2D>("open"); #endif this.Position = new Vector2(5, 20); } void Config_Cleared(object sender, EventArgs e) { Clear(); } #endregion public void Clear() { root.Nodes.Clear(); } #region Set /// <summary> /// Sets the value of a specified key, if the key is not present /// in the tree, then is added. /// </summary> /// <param name="key"></param> public void Set(String key, Object value) { bool foundKey = false; TreeViewNode currentNode = root; String remainingName = key; while (!foundKey) { iterationCount++; String subName; bool foundSubKey = false; int dotIndex = remainingName.IndexOf('.'); if (dotIndex < 0 || dotIndex >= remainingName.Length) { subName = remainingName; remainingName = ""; foundKey = true; } else { subName = remainingName.Remove(dotIndex,remainingName.Length - dotIndex); remainingName = remainingName.Substring(subName.Length + 1); } foreach (TreeViewNode node in currentNode.Nodes) { if (node.Name == subName) { currentNode = node; foundSubKey = true; // A part of the key was found. break; } } if (!foundSubKey) { // If there's no subKey, we create it. TreeViewNode newNode = new TreeViewNode(subName); currentNode.Nodes.Add(newNode); currentNode = newNode; foundSubKey = true; // A part of the key was found (created). } } currentNode.Value = value; } #endregion #region Update public override void Update(GameTime gameTime) { #if XBOX360 return; #endif MouseState mouse = Mouse.GetState(); if (mouse.LeftButton == ButtonState.Released && prevMouse.LeftButton == ButtonState.Pressed) { LeftClick(new Vector2(mouse.X, mouse.Y)); } prevMouse = mouse; } #endregion #region LeftClick public void LeftClick(Vector2 clickPos) { int position = 20; foreach (TreeViewNode node in root.Nodes) { if (Config.Filter == String.Empty || node.FilterName.Contains(Config.Filter)) position = CheckLeftRecursively(node, position, 1, clickPos); } } private int CheckLeftRecursively(TreeViewNode node, int position, int level, Vector2 clickPos) { int newPosition = position + 12; Rectangle rect = new Rectangle((int)this.Position.X + level * 11 - 12,(int)this.Position.Y + position, closedTexture.Width, closedTexture.Height); if (rect.Contains((int)clickPos.X, (int)clickPos.Y)) { node.Toggle(); return newPosition; } if (node.Open) { foreach (TreeViewNode n in node.Nodes) { newPosition = CheckLeftRecursively(n, newPosition, level + 1, clickPos); } } return newPosition; } #endregion #region Draw public override void Draw(GameTime gameTime) { // Only draw if we're doing a spriteBatch pass if (GearsetResources.CurrentRenderPass != RenderPass.SpriteBatchPass) return; int position = 20; foreach (TreeViewNode node in root.Nodes) { if (Config.Filter == String.Empty || node.FilterName.Contains(Config.Filter)) position = DrawRecursively(node, position, 1); } } private int DrawRecursively(TreeViewNode node, int position, int level) { int newPosition = position + 12; DrawNode(node, position, level); if (node.Open) { foreach (TreeViewNode n in node.Nodes) { newPosition = DrawRecursively(n, newPosition, level + 1); } } return newPosition; } private void DrawText(String text, Vector2 drawPosition) { Color color = new Color(1, 1, 1, GearsetResources.GlobalAlpha) * GearsetResources.GlobalAlpha; Color shadowColor = new Color(0, 0, 0, GearsetResources.GlobalAlpha) * GearsetResources.GlobalAlpha; GearsetResources.SpriteBatch.DrawString(GearsetResources.Font, text, drawPosition + new Vector2(-1, 0), shadowColor); GearsetResources.SpriteBatch.DrawString(GearsetResources.Font, text, drawPosition + new Vector2(0, 1), shadowColor); GearsetResources.SpriteBatch.DrawString(GearsetResources.Font, text, drawPosition + new Vector2(0, -1), shadowColor); GearsetResources.SpriteBatch.DrawString(GearsetResources.Font, text, drawPosition + new Vector2(1, 0), shadowColor); GearsetResources.SpriteBatch.DrawString(GearsetResources.Font, text, drawPosition, color); Vector2 textSize = GearsetResources.Font.MeasureString(text); textSize.Y = 12; textSize.X += 6; drawPosition.X -= 3; GearsetResources.Console.SolidBoxDrawer.ShowBoxOnce(drawPosition, drawPosition + textSize); } private void DrawNode(TreeViewNode node, int position, int level) { Vector2 drawPosition = new Vector2(this.Position.X + level * 11, this.Position.Y + position); if (node.Nodes.Count == 0) { DrawText(node.Name + ": " + TextHelper.FormatForDebug(node.Value), drawPosition); } else { Color color = new Color(1, 1, 1, GearsetResources.GlobalAlpha) * GearsetResources.GlobalAlpha; if (!node.Open) GearsetResources.SpriteBatch.Draw(closedTexture, drawPosition - new Vector2(12, 0), color); else GearsetResources.SpriteBatch.Draw(openedTexture, drawPosition - new Vector2(12, 0), color); DrawText(node.Name, drawPosition); } } #endregion } }
// <copyright file="CsvRecordParserTest.cs" company="Fubar Development Junker"> // Copyright (c) 2016 Fubar Development Junker. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> using BeanIO.Stream.Csv; using Xunit; namespace BeanIO.Stream { public class CsvRecordParserTest { private readonly CsvRecordParser _parser = new CsvRecordParser(); [Fact] public void TestEmptyString() { var expected = new[] { string.Empty }; Assert.Equal(expected, Assert.IsType<string[]>(_parser.Unmarshal(string.Empty))); } [Fact] public void TestNewLine() { var record = "\n"; var expected = new[] { "\n" }; Assert.Equal(expected, Assert.IsType<string[]>(_parser.Unmarshal(record))); } [Fact] public void TestDelimiter() { var record = " 1,2,3"; var expected = new[] { " 1", "2", "3" }; Assert.Equal(expected, Assert.IsType<string[]>(_parser.Unmarshal(record))); } [Fact] public void TestDelimiterOnly() { var record = ","; var expected = new[] { string.Empty, string.Empty }; Assert.Equal(expected, Assert.IsType<string[]>(_parser.Unmarshal(record))); } [Fact] public void TestEscapedDelimiter() { var record = "\"1,\",2"; var expected = new[] { "1,", "2" }; Assert.Equal(expected, Assert.IsType<string[]>(_parser.Unmarshal(record))); } [Fact] public void TestEscapedQuote() { var record = "\"1,\"\"\",2"; var expected = new[] { "1,\"", "2" }; Assert.Equal(expected, Assert.IsType<string[]>(_parser.Unmarshal(record))); } [Fact] public void TestQuotedFields() { var record = "\"1\",\"\",\"3\""; var expected = new[] { "1", string.Empty, "3" }; Assert.Equal(expected, Assert.IsType<string[]>(_parser.Unmarshal(record))); } [Fact] public void TestCharacaterOutofQuotedField() { Assert.Throws<RecordIOException>(() => _parser.Unmarshal("\"1\",\"\",\"3\"2\n\r1,2")); } [Fact] public void TestSpaceOutofQuotedField() { Assert.Throws<RecordIOException>(() => _parser.Unmarshal("\"1\",\"\",\"3\" \n\r1,2")); } [Fact] public void TestUnquotedQuote() { Assert.Throws<RecordIOException>(() => _parser.Unmarshal("1\"1,2,3")); } [Fact] public void TestCustomDelimiter() { CsvParserConfiguration config = new CsvParserConfiguration() { Delimiter = '|', }; var parser = new CsvRecordParser(config); var record = "\"1\"|2|3"; var expected = new[] { "1", "2", "3" }; Assert.Equal(expected, Assert.IsType<string[]>(parser.Unmarshal(record))); } [Fact] public void TestCustomQuote() { CsvParserConfiguration config = new CsvParserConfiguration() { Quote = '\'', }; var parser = new CsvRecordParser(config); var record = "'1',' 234 ',5\n"; var expected = new[] { "1", " 234 ", "5\n" }; Assert.Equal(expected, Assert.IsType<string[]>(parser.Unmarshal(record))); } [Fact] public void TestCustomEscape() { CsvParserConfiguration config = new CsvParserConfiguration() { Quote = '\'', Escape = '\\', }; var parser = new CsvRecordParser(config); var record = "'1',' \\'23\\\\4\\' ',5\\\\"; var expected = new[] { "1", " '23\\4' ", "5\\\\" }; Assert.Equal(expected, Assert.IsType<string[]>(parser.Unmarshal(record))); } [Fact] public void TestWhitespaceeAllowed() { CsvParserConfiguration config = new CsvParserConfiguration() { Quote = '\'', IsWhitespaceAllowed = true, }; var parser = new CsvRecordParser(config); var record = " '1' , '2' "; var expected = new[] { "1", "2" }; Assert.Equal(expected, Assert.IsType<string[]>(parser.Unmarshal(record))); } [Fact] public void TestEscapeDisabled() { CsvParserConfiguration config = new CsvParserConfiguration() { Quote = '\'', Escape = null, }; var parser = new CsvRecordParser(config); var record = "'1\"','2'"; var expected = new[] { "1\"", "2" }; Assert.Equal(expected, Assert.IsType<string[]>(parser.Unmarshal(record))); } [Fact] public void TestUnquotedQuoteAllowed() { CsvParserConfiguration config = new CsvParserConfiguration() { Quote = '\'', UnquotedQuotesAllowed = true, }; var parser = new CsvRecordParser(config); var record = "1\"1,2"; var expected = new[] { "1\"1", "2" }; Assert.Equal(expected, Assert.IsType<string[]>(parser.Unmarshal(record))); } [Fact] public void TestMissingQuoteEOF() { Assert.Throws<RecordIOException>(() => _parser.Unmarshal("field1,\"field2")); } [Fact] public void TestQuoteIsDelimiter() { CsvParserConfiguration config = new CsvParserConfiguration() { Delimiter = ',', Quote = ',', }; Assert.Throws<BeanIOConfigurationException>(() => new CsvRecordParser(config)); } [Fact] public void TestQuoteIsEscape() { CsvParserConfiguration config = new CsvParserConfiguration() { Delimiter = ',', Escape = ',', }; Assert.Throws<BeanIOConfigurationException>(() => new CsvRecordParser(config)); } [Fact] public void TestCreateWhitespace() { var record = " 1,2, 3 "; var expected = new[] { " 1", "2", " 3 " }; Assert.Equal(expected, Assert.IsType<string[]>(_parser.Unmarshal(record))); } [Fact] public void TestMarshalDefaultConfiguration() { CsvRecordParserFactory factory = new CsvRecordParserFactory(); CsvRecordParser parser = (CsvRecordParser)factory.CreateMarshaller(); Assert.Equal( "value1,\"\"\"value2\"\"\",\"value,3\"", parser.Marshal(new[] { "value1", "\"value2\"", "value,3" })); } [Fact] public void TestMarshalCustomConfiguration() { CsvRecordParserFactory factory = new CsvRecordParserFactory() { Delimiter = ':', Quote = '\'', Escape = '\\', RecordTerminator = string.Empty, }; CsvRecordParser parser = (CsvRecordParser)factory.CreateMarshaller(); Assert.Equal( "value1:'\\'value2\\'':'value:3'", parser.Marshal(new[] { "value1", "'value2'", "value:3" })); } [Fact] public void TestMarshalAlwaysQuote() { CsvRecordParserFactory factory = new CsvRecordParserFactory() { Quote = '\'', Escape = '\\', RecordTerminator = string.Empty, AlwaysQuote = true, }; CsvRecordParser parser = (CsvRecordParser)factory.CreateMarshaller(); Assert.Equal( "'value1','\\'value2\\'','value,3'", parser.Marshal(new[] { "value1", "'value2'", "value,3" })); } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Orleans.Runtime.Configuration; using Orleans.MultiCluster; namespace Orleans.Runtime { /// <summary> /// Interface for system management functions of silos, /// exposed as a grain for receiving remote requests / commands. /// </summary> public interface IManagementGrain : IGrainWithIntegerKey { /// <summary> /// Get the list of silo hosts and statuses currently known about in this cluster. /// </summary> /// <param name="onlyActive">Whether data on just current active silos should be returned, /// or by default data for all current and previous silo instances [including those in Joining or Dead status].</param> /// <returns></returns> Task<Dictionary<SiloAddress, SiloStatus>> GetHosts(bool onlyActive = false); /// <summary> /// Get the list of silo hosts and membership information currently known about in this cluster. /// </summary> /// <param name="onlyActive">Whether data on just current active silos should be returned, /// or by default data for all current and previous silo instances [including those in Joining or Dead status].</param> /// <returns></returns> Task<MembershipEntry[]> GetDetailedHosts(bool onlyActive = false); /// <summary> /// Set the current log level for system runtime components. /// </summary> /// <param name="hostsIds">List of silos this command is to be sent to.</param> /// <param name="traceLevel">New log level to use.</param> /// <returns>Completion promise for this operation.</returns> Task SetSystemLogLevel(SiloAddress[] hostsIds, int traceLevel); /// <summary> /// Set the current log level for application grains. /// </summary> /// <param name="hostsIds">List of silos this command is to be sent to.</param> /// <param name="traceLevel">New log level to use.</param> /// <returns>Completion promise for this operation.</returns> Task SetAppLogLevel(SiloAddress[] hostsIds, int traceLevel); /// <summary> /// Set the current log level for a particular Logger, by name (with prefix matching). /// </summary> /// <param name="hostsIds">List of silos this command is to be sent to.</param> /// <param name="logName">Name of the Logger (with prefix matching) to change.</param> /// <param name="traceLevel">New log level to use.</param> /// <returns>Completion promise for this operation.</returns> Task SetLogLevel(SiloAddress[] hostsIds, string logName, int traceLevel); /// <summary> /// Perform a run of the .NET garbage collector in the specified silos. /// </summary> /// <param name="hostsIds">List of silos this command is to be sent to.</param> /// <returns>Completion promise for this operation.</returns> Task ForceGarbageCollection(SiloAddress[] hostsIds); /// <summary> /// Perform a run of the Orleans activation collecter in the specified silos. /// </summary> /// <param name="hostsIds">List of silos this command is to be sent to.</param> /// <returns>Completion promise for this operation.</returns> Task ForceActivationCollection(SiloAddress[] hostsIds, TimeSpan ageLimit); Task ForceActivationCollection(TimeSpan ageLimit); /// <summary> /// Perform a run of the silo statistics collector in the specified silos. /// </summary> /// <param name="hostsIds">List of silos this command is to be sent to.</param> /// <returns>Completion promise for this operation.</returns> Task ForceRuntimeStatisticsCollection(SiloAddress[] siloAddresses); /// <summary> /// Return the most recent silo runtime statistics information for the specified silos. /// </summary> /// <param name="hostsIds">List of silos this command is to be sent to.</param> /// <returns>Completion promise for this operation.</returns> Task<SiloRuntimeStatistics[]> GetRuntimeStatistics(SiloAddress[] hostsIds); /// <summary> /// Return the most recent grain statistics information, amalgomated across silos. /// </summary> /// <param name="hostsIds">List of silos this command is to be sent to.</param> /// <returns>Completion promise for this operation.</returns> Task<SimpleGrainStatistic[]> GetSimpleGrainStatistics(SiloAddress[] hostsIds); /// <summary> /// Return the most recent grain statistics information, amalgomated across all silos. /// </summary> /// <returns>Completion promise for this operation.</returns> Task<SimpleGrainStatistic[]> GetSimpleGrainStatistics(); /// <summary> /// Returns the most recent detailed grain statistics information, amalgomated across silos for the specified types. /// </summary> /// <param name="hostsIds">List of silos this command is to be sent to.</param> /// <param name="types">Array of grain types to filter the results with</param> /// <returns></returns> Task<DetailedGrainStatistic[]> GetDetailedGrainStatistics(string[] types = null,SiloAddress[] hostsIds=null); Task<int> GetGrainActivationCount(GrainReference grainReference); /// <summary> /// Return the total count of all current grain activations across all silos. /// </summary> /// <returns>Completion promise for this operation.</returns> /// Task<int> GetTotalActivationCount(); /// <summary> /// Execute a control command on the specified providers on all silos in the cluster. /// Commands are sent to all known providers on each silo which match both the <c>providerTypeFullName</c> AND <c>providerName</c> parameters. /// </summary> /// <remarks> /// Providers must implement the <c>Orleans.Providers.IControllable</c> /// interface in order to receive these control channel commands. /// </remarks> /// <param name="providerTypeFullName">Class full name for the provider type to send this command to.</param> /// <param name="providerName">Provider name to send this command to.</param> /// <param name="command">An id / serial number of this command. /// This is an opaque value to the Orleans runtime - the control protocol semantics are decided between the sender and provider.</param> /// <param name="arg">An opaque command argument. /// This is an opaque value to the Orleans runtime - the control protocol semantics are decided between the sender and provider.</param> /// <returns>Completion promise for this operation.</returns> Task<object[]> SendControlCommandToProvider(string providerTypeFullName, string providerName, int command, object arg = null); /// <summary> /// Update the configuration information dynamically. Only a subset of configuration information /// can be updated - will throw an error (and make no config changes) if you specify attributes /// or elements that cannot be changed. The configuration format is XML, in the same format /// as the OrleansConfiguration.xml file. The allowed elements and attributes are: /// <pre> /// &lt;OrleansConfiguration&gt; /// &lt;Globals&gt; /// &lt;Messaging ResponseTimeout=&quot;?&quot;/&gt; /// &lt;Caching CacheSize=&quot;?&quot;/&gt; /// &lt;Activation CollectionInterval=&quot;?&quot; CollectionAmount=&quot;?&quot; CollectionTotalMemoryLimit=&quot;?&quot; CollectionActivationLimit=&quot;?&quot;/&gt; /// &lt;Liveness ProbeTimeout=&quot;?&quot; TableRefreshTimeout=&quot;?&quot; NumMissedProbesLimit=&quot;?&quot;/&gt; /// &lt;/Globals&gt; /// &lt;Defaults&gt; /// &lt;LoadShedding Enabled=&quot;?&quot; LoadLimit=&quot;?&quot;/&gt; /// &lt;Tracing DefaultTraceLevel=&quot;?&quot; PropagateActivityId=&quot;?&quot;&gt; /// &lt;TraceLevelOverride LogPrefix=&quot;?&quot; TraceLevel=&quot;?&quot;/&gt; /// &lt;/Tracing&gt; /// &lt;/Defaults&gt; /// &lt;/OrleansConfiguration&gt; /// </pre> /// </summary> /// <param name="hostIds">Silos to update, or null for all silos</param> /// <param name="configuration">XML elements and attributes to update</param> /// <returns></returns> Task UpdateConfiguration(SiloAddress[] hostIds, Dictionary<string, string> configuration, Dictionary<string, string> tracing); /// <summary> /// Update the stream providers dynamically. The stream providers in the listed silos will be /// updated based on the differences between its loaded stream providers and the list of providers /// in the streamProviderConfigurations: If a provider in the configuration object already exists /// in the silo, it will be kept as is; if a provider in the configuration object does not exist /// in the silo, it will be loaded and started; if a provider that exists in silo but is not in /// the configuration object, it will be stopped and removed from the silo. /// </summary> /// <param name="hostIds">Silos to update, or null for all silos</param> /// <param name="streamProviderConfigurations">stream provider configurations that carries target stream providers</param> /// <returns></returns> Task UpdateStreamProviders(SiloAddress[] hostIds, IDictionary<string, ProviderCategoryConfiguration> streamProviderConfigurations); /// <summary> /// Returns an array of all the active grain types in the system /// </summary> /// <param name="hostsIds">List of silos this command is to be sent to.</param> /// <returns></returns> Task<string[]> GetActiveGrainTypes(SiloAddress[] hostsIds=null); #region MultiCluster Management /// <summary> /// Get the current list of multicluster gateways. /// </summary> /// <returns>A list of the currently known gateways</returns> Task<List<IMultiClusterGatewayInfo>> GetMultiClusterGateways(); /// <summary> /// Get the current multicluster configuration. /// </summary> /// <returns>The current multicluster configuration, or null if there is none</returns> Task<MultiClusterConfiguration> GetMultiClusterConfiguration(); /// <summary> /// Contact all silos in all clusters and return silos that do not have the latest multi-cluster configuration. /// If some clusters and/or silos cannot be reached, an exception is thrown. /// </summary> /// <returns>A list of silo addresses of silos that do not have the latest configuration</returns> Task<List<SiloAddress>> FindLaggingSilos(); /// <summary> /// Configure the active multi-cluster, by injecting a multicluster configuration. /// </summary> /// <param name="clusters">the clusters that should be part of the active configuration</param> /// <param name="comment">a comment to store alongside the configuration</param> /// <param name="checkForLaggingSilosFirst">if true, checks that all clusters are reachable and up-to-date before injecting the new configuration</param> /// <returns> The task completes once information has propagated to the gossip channels</returns> Task<MultiClusterConfiguration> InjectMultiClusterConfiguration(IEnumerable<string> clusters, string comment = "", bool checkForLaggingSilosFirst = true); #endregion } }
using System; using Csla; using Csla.Data; using DalEf; using Csla.Serialization; using System.ComponentModel.DataAnnotations; using BusinessObjects.Properties; using System.Linq; using BusinessObjects.CoreBusinessClasses; using BusinessObjects.Common; namespace BusinessObjects.MDSubjects { [Serializable] public partial class cMDSubjects_Enums_SoleProprietorType: CoreBusinessClass<cMDSubjects_Enums_SoleProprietorType> { #region Business Methods public static readonly PropertyInfo< System.Int32 > IdProperty = RegisterProperty< System.Int32 >(p => p.Id, string.Empty); #if !SILVERLIGHT [System.ComponentModel.DataObjectField(true, true)] #endif public System.Int32 Id { get { return GetProperty(IdProperty); } internal set { SetProperty(IdProperty, value); } } private static readonly PropertyInfo< System.String > nameProperty = RegisterProperty<System.String>(p => p.Name, string.Empty); [System.ComponentModel.DataAnnotations.StringLength(100, ErrorMessageResourceName = "ErrorMessageMaxLength", ErrorMessageResourceType = typeof(Resources))] [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.String Name { get { return GetProperty(nameProperty); } set { SetProperty(nameProperty, value.Trim()); } } private static readonly PropertyInfo<bool?> immutableProperty = RegisterProperty<bool?>(p => p.Immutable, string.Empty, (bool?)null); public bool? Immutable { get { return GetProperty(immutableProperty); } set { SetProperty(immutableProperty, value); } } private static readonly PropertyInfo< System.Int32? > enumNumberProperty = RegisterProperty<System.Int32?>(p => p.EnumNumber, string.Empty,(System.Int32?)null); public System.Int32? EnumNumber { get { return GetProperty(enumNumberProperty); } set { SetProperty(enumNumberProperty, value); } } private static readonly PropertyInfo< bool? > inactiveProperty = RegisterProperty<bool?>(p => p.Inactive, string.Empty,(bool?)null); public bool? Inactive { get { return GetProperty(inactiveProperty); } set { SetProperty(inactiveProperty, value); } } protected static readonly PropertyInfo<System.Int32?> companyUsingServiceIdProperty = RegisterProperty<System.Int32?>(p => p.CompanyUsingServiceId, string.Empty); public System.Int32? CompanyUsingServiceId { get { return GetProperty(companyUsingServiceIdProperty); } set { SetProperty(companyUsingServiceIdProperty, value); } } /// <summary> /// Used for optimistic concurrency. /// </summary> [NotUndoable] internal System.Byte[] LastChanged = new System.Byte[8]; #endregion #region Factory Methods public static cMDSubjects_Enums_SoleProprietorType NewMDSubjects_Enums_SoleProprietorType() { return DataPortal.Create<cMDSubjects_Enums_SoleProprietorType>(); } public static cMDSubjects_Enums_SoleProprietorType GetMDSubjects_Enums_SoleProprietorType(int uniqueId) { return DataPortal.Fetch<cMDSubjects_Enums_SoleProprietorType>(new SingleCriteria<cMDSubjects_Enums_SoleProprietorType, int>(uniqueId)); } internal static cMDSubjects_Enums_SoleProprietorType GetMDSubjects_Enums_SoleProprietorType(MDSubjects_Enums_SoleProprietorType data) { return DataPortal.Fetch<cMDSubjects_Enums_SoleProprietorType>(data); } #endregion #region Data Access [RunLocal] protected override void DataPortal_Create() { BusinessRules.CheckRules(); } private void DataPortal_Fetch(SingleCriteria<cMDSubjects_Enums_SoleProprietorType, int> criteria) { using (var ctx = ObjectContextManager<MDSubjectsEntities>.GetManager("MDSubjectsEntities")) { var data = ctx.ObjectContext.MDSubjects_Enums_SoleProprietorType.First(p => p.Id == criteria.Value); LoadProperty<int>(IdProperty, data.Id); LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey)); LoadProperty<string>(nameProperty, data.Name); LoadProperty<bool?>(immutableProperty, data.Immutable); LoadProperty<int?>(enumNumberProperty, data.EnumNumber); LoadProperty<bool?>(inactiveProperty, data.Inactive); LoadProperty<int?>(companyUsingServiceIdProperty, data.CompanyUsingServiceId); LastChanged = data.LastChanged; BusinessRules.CheckRules(); } } private void DataPortal_Fetch(MDSubjects_Enums_SoleProprietorType data) { LoadProperty<int>(IdProperty, data.Id); LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey)); LoadProperty<string>(nameProperty, data.Name); LoadProperty<bool?>(immutableProperty, data.Immutable); LoadProperty<int?>(enumNumberProperty, data.EnumNumber); LoadProperty<bool?>(inactiveProperty, data.Inactive); LoadProperty<int?>(companyUsingServiceIdProperty, data.CompanyUsingServiceId); LastChanged = data.LastChanged; BusinessRules.CheckRules(); MarkAsChild(); } [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Insert() { using (var ctx = ObjectContextManager<MDSubjectsEntities>.GetManager("MDSubjectsEntities")) { var data = new MDSubjects_Enums_SoleProprietorType(); data.Name = ReadProperty<string>(nameProperty); data.Immutable = ReadProperty<bool?>(immutableProperty); data.EnumNumber = ReadProperty<int?>(enumNumberProperty); data.Inactive = ReadProperty<bool?>(inactiveProperty); data.CompanyUsingServiceId = ReadProperty<int?>(companyUsingServiceIdProperty); ctx.ObjectContext.AddToMDSubjects_Enums_SoleProprietorType(data); ctx.ObjectContext.SaveChanges(); //Get New id int newId = data.Id; //Load New Id into object LoadProperty(IdProperty, newId); //Load New EntityKey into Object LoadProperty(EntityKeyDataProperty, Serialize(data.EntityKey)); ctx.ObjectContext.SaveChanges(); } } [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Update() { using (var ctx = ObjectContextManager<MDSubjectsEntities>.GetManager("MDSubjectsEntities")) { var data = new MDSubjects_Enums_SoleProprietorType(); data.Id = ReadProperty<int>(IdProperty); data.EntityKey = Deserialize(ReadProperty(EntityKeyDataProperty)) as System.Data.EntityKey; ctx.ObjectContext.Attach(data); data.Name = ReadProperty<string>(nameProperty); data.Immutable = ReadProperty<bool?>(immutableProperty); data.EnumNumber = ReadProperty<int?>(enumNumberProperty); data.Inactive = ReadProperty<bool?>(inactiveProperty); data.CompanyUsingServiceId = ReadProperty<int?>(companyUsingServiceIdProperty); ctx.ObjectContext.SaveChanges(); } } #endregion } public partial class cMDSubjects_Enums_SoleProprietorType_List : BusinessListBase<cMDSubjects_Enums_SoleProprietorType_List, cMDSubjects_Enums_SoleProprietorType> { public static cMDSubjects_Enums_SoleProprietorType_List GetcMDSubjects_Enums_SoleProprietorType_List() { return DataPortal.Fetch<cMDSubjects_Enums_SoleProprietorType_List>(); } public static cMDSubjects_Enums_SoleProprietorType_List GetcMDSubjects_Enums_SoleProprietorType_List(int companyId, int includeInactiveId) { return DataPortal.Fetch<cMDSubjects_Enums_SoleProprietorType_List>(new ActiveEnums_Criteria(companyId, includeInactiveId)); } private void DataPortal_Fetch() { using (var ctx = ObjectContextManager<MDSubjectsEntities>.GetManager("MDSubjectsEntities")) { var result = ctx.ObjectContext.MDSubjects_Enums_SoleProprietorType; foreach (var data in result) { var obj = cMDSubjects_Enums_SoleProprietorType.GetMDSubjects_Enums_SoleProprietorType(data); this.Add(obj); } } } private void DataPortal_Fetch(ActiveEnums_Criteria criteria) { using (var ctx = ObjectContextManager<MDSubjectsEntities>.GetManager("MDSubjectsEntities")) { var result = ctx.ObjectContext.MDSubjects_Enums_SoleProprietorType.Where(p => (p.CompanyUsingServiceId == criteria.CompanyId || (p.CompanyUsingServiceId ?? 0) == 0) && ((p.Inactive ?? false) == false || p.Id == criteria.IncludeInactiveId)); foreach (var data in result) { var obj = cMDSubjects_Enums_SoleProprietorType.GetMDSubjects_Enums_SoleProprietorType(data); this.Add(obj); } } } } }